diff --git a/.gitattributes b/.gitattributes index d2b789541..488a40d4b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,3 +4,5 @@ text=auto *.h text README text LICENSE text +# the license texts the Windows build ships, checked by their SHA-256: byte for byte as upstream, LF on every checkout +ref/licenses/*.txt -text diff --git a/.github/actions/apt-install/action.yml b/.github/actions/apt-install/action.yml new file mode 100644 index 000000000..0495b07ac --- /dev/null +++ b/.github/actions/apt-install/action.yml @@ -0,0 +1,137 @@ +# Installs Ubuntu packages, with the downloaded .deb files kept in the Actions cache. +# +# The Ubuntu mirror of the hosted runners has been slow: about 150 kB/s, with stalls of 30 s on single files, +# so 130 small packages took over 13 minutes to download. The .deb files of the last install are kept in the +# cache, under a key of the runner image and the package list: +# - the same image and list (the usual case): the cached files are installed as they are, without the mirror +# and without `apt-get update`; should that fail, the next way is taken +# - otherwise: `apt-get update`, then `apt-get install`, which takes the cached files of the same version +# (checked against the index) and downloads the rest; the files of this install are cached for the next run +# +# A cache entry can't be overwritten, so each one is saved under the key with the run appended, and the newest +# entry of a key is restored by its prefix. Cached files that failed to install are then replaced by the next +# save rather than restored again on every run of that image. +# +# Caches of a pull request are seen only by that pull request; the pushes to staging and master (Build binaries) +# fill the ones every pull request starts from. + +name: Install apt packages +description: apt-get install, with the downloaded packages kept in the Actions cache + +inputs: + packages: + description: The packages to install, separated by spaces or new lines + required: true + +runs: + using: composite + steps: + # the key: the runner image (its packages are what the cached files were resolved against) and the list, + # sorted, so neither its order nor its line breaks change it. Without ImageVersion (not a GitHub-hosted + # runner) the image isn't known, so the cached files are never installed as they are + - name: Cache key of the packages + id: key + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + run: | + set -euo pipefail + printf '%s\n' "$PACKAGES" | tr -s '[:space:]' '\n' | sed '/^$/d' | sort -u > "$RUNNER_TEMP/apt-packages.txt" + os="${ImageOS:-$(. /etc/os-release && echo "${ID}${VERSION_ID}")}" + image="${ImageVersion:-unknown}" + prefix="apt-v2-${os}-$(dpkg --print-architecture)-" + list_hash="$(sha256sum < "$RUNNER_TEMP/apt-packages.txt" | cut -c1-16)" + { + echo "key=${prefix}${image}-${list_hash}" + echo "save-key=${prefix}${image}-${list_hash}-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}" + echo "image-prefix=${prefix}${image}-" + echo "prefix=${prefix}" + echo "known-image=$([ -n "${ImageVersion:-}" ] && echo true || echo false)" + } >> "$GITHUB_OUTPUT" + cat "$RUNNER_TEMP/apt-packages.txt" + + # no entry is saved under the key itself, so this restores the newest entry of the key (by its prefix), else + # a cache of another list (another workflow) or of an older image: the files apt finds there in the version + # it wants aren't downloaded again + - name: Restore the downloaded packages + id: restore + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: /tmp/apt-archives + key: ${{ steps.key.outputs.key }} + restore-keys: | + ${{ steps.key.outputs.image-prefix }} + ${{ steps.key.outputs.prefix }} + + # /tmp rather than the runner's temp folder: apt downloads as the user _apt, who has to reach the folder. + # Recommended packages are left out: the build needs the headers and libraries the packages depend on + - name: Install the packages + id: install + shell: bash + env: + EXACT_HIT: ${{ startsWith(steps.restore.outputs.cache-matched-key, format('{0}-', steps.key.outputs.key)) && steps.key.outputs.known-image == 'true' }} + run: | + set -euo pipefail + archives=/tmp/apt-archives + mkdir -p "$archives/partial" + + # a mirror that stops answering used to hold this step for over an hour: time out each download and + # retry it. The translations of the package descriptions aren't needed + printf '%s\n' \ + 'Acquire::Retries "3";' \ + 'Acquire::http::Timeout "60";' \ + 'Acquire::https::Timeout "60";' \ + 'Acquire::Languages "none";' \ + | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null + + mapfile -t packages < "$RUNNER_TEMP/apt-packages.txt" + apt=(sudo apt-get -y --no-install-recommends -o "Dir::Cache::Archives=$archives/") + + all_installed() { + local package + for package in "${packages[@]}"; do + [[ "$(dpkg-query -W -f '${db:Status-Abbrev}' "$package" 2> /dev/null)" == ii* ]] || return 1 + done + } + + done=false + fix=() + if [ "$EXACT_HIT" = true ] && compgen -G "$archives/*.deb" > /dev/null; then + echo "::group::Install the $(ls "$archives"/*.deb | wc -l) cached packages" + if "${apt[@]}" install "$archives"/*.deb && all_installed; then + done=true + echo "from-cache=true" >> "$GITHUB_OUTPUT" + else + echo "::warning::The cached packages didn't install; installing from the mirror" + fix=(--fix-broken) + fi + echo "::endgroup::" + fi + + if [ "$done" != true ]; then + sudo apt-get update + "${apt[@]}" "${fix[@]}" install "${packages[@]}" + all_installed + fi + + # only the files of the packages now installed are kept, in the version installed: the cached files then + # are exactly this install, and the next run on this image can install them as they are + sudo rm -rf "$archives/partial" "$archives/lock" + sudo chown -R "$(id -u):$(id -g)" "$archives" + installed="$(dpkg-query -W -f '${db:Status-Abbrev}|${Package}|${Version}|${Architecture}\n' \ + | awk -F'|' '$1 ~ /^ii/ { print $2 "|" $3 "|" $4 }')" + for deb in "$archives"/*.deb; do + [ -e "$deb" ] || continue + id="$(dpkg-deb --show --showformat='${Package}|${Version}|${Architecture}' "$deb")" + grep -qxF -- "$id" <<< "$installed" || rm -f "$deb" + done + echo "Cached packages: $(find "$archives" -maxdepth 1 -name '*.deb' | wc -l), $(du -sh "$archives" | cut -f1)" + + # saved unless the cached files of this image and list installed as they are: after a miss, and after cached + # files that failed to install and were replaced from the mirror + - name: Save the downloaded packages + if: steps.install.outputs.from-cache != 'true' + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: /tmp/apt-archives + key: ${{ steps.key.outputs.save-key }} diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..23c5f7c9d --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,15 @@ +# Keeps the GitHub Actions used by the workflows and by the local actions (.github/actions) up to date. The actions +# are pinned by commit hash, with the version in a comment; Dependabot updates both. One pull request a week for all +# of them, so the workflows stay on the same versions. +version: 2 +updates: + - package-ecosystem: github-actions + directories: + - / + - /.github/actions/* + schedule: + interval: weekly + groups: + github-actions: + patterns: + - "*" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ff39d872f..9a2d3aee5 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -24,14 +24,14 @@ concurrency: jobs: build: - name: Build under Build Wrapper + name: Compilation database for SonarQube Cloud runs-on: ubuntu-24.04 permissions: contents: read env: BUILD_WRAPPER_OUT_DIR: bw-output steps: - - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 submodules: recursive @@ -41,23 +41,20 @@ jobs: with: python-version: '3.14' - # A mirror that stops answering used to hold this step for over an hour. - # Time out each download, retry it, and give up on the whole step early. + # The packages are kept in the Actions cache (.github/actions/apt-install): the mirror of the + # runners has been too slow to download them every time. The timeout is a safety net. + # The X11 packages are the ones GLFW (ref/glfw, 3.4) looks for; xorg-dev brought ~45 more. - name: Install build dependencies timeout-minutes: 15 - run: | - printf '%s\n' \ - 'Acquire::Retries "3";' \ - 'Acquire::http::Timeout "60";' \ - 'Acquire::https::Timeout "60";' \ - | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null - sudo apt-get update -y - sudo apt-get install -y \ - build-essential \ - libgl1-mesa-dev libglew-dev libglfw3-dev \ - libpng-dev libopenal-dev libluajit-5.1-dev \ - libserialport-dev libsndfile1-dev \ - xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential pkg-config + libgl1-mesa-dev libglew-dev libglfw3-dev + libpng-dev libopenal-dev libluajit-5.1-dev + libserialport-dev libsndfile1-dev + libx11-dev libxcursor-dev libxext-dev libxi-dev libxinerama-dev libxrandr-dev + libxkbcommon-dev libwayland-dev wayland-protocols - name: Build current OpenAL Soft run: | @@ -76,22 +73,26 @@ jobs: ref/glm/glm/gtx/string_cast.inl grep -n "std::string format(const char\* message" ref/glm/glm/gtx/string_cast.inl - - name: Install SonarQube Cloud Build Wrapper - uses: SonarSource/sonarqube-scan-action/install-build-wrapper@fd88b7d7ccbaefd23d8f36f73b59db7a3d246602 # v6.0.0 - + # The analyzer needs the compile command of every file and the headers they include, not the objects: the + # compilation database CMake writes at configure time is enough, so nothing is compiled here. The headers the + # project generates (version_info.h, the editor icons) are written by the configure step too. - name: Configure (CMake) run: | cmake -S . -B build \ -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \ -DWITH_ZMQ=OFF -DWITH_OPENVR=OFF -DUSE_LTO=OFF \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" \ -DPython3_EXECUTABLE="$(which python3)" - - name: Build under Build Wrapper + # glslang writes its build_info.h at build time; its sources are excluded from the analysis, but the target + # is cheap and makes the include available should a header of ours reach it + - name: Compilation database run: | - build-wrapper-linux-x86-64 \ - --out-dir "${BUILD_WRAPPER_OUT_DIR}" \ - cmake --build build --config Release -j"$(nproc)" + cmake --build build --target glslang-build-info || echo "no glslang-build-info target, nothing generated" + mkdir -p "${BUILD_WRAPPER_OUT_DIR}" + cp build/compile_commands.json "${BUILD_WRAPPER_OUT_DIR}/compile_commands.json" + echo "$(grep -c '"file"' "${BUILD_WRAPPER_OUT_DIR}/compile_commands.json") compile commands" # Metadata the trusted workflow needs to identify the PR. # Treated as UNVERIFIED input there and re-checked against the API. @@ -108,13 +109,14 @@ jobs: printf '%s\n' "$PR_HEAD_SHA" > .sonar-meta/head_sha printf '%s\n' "$COMMIT_SHA" > .sonar-meta/sha - # The C/C++ analyzer needs the sources AND the build-wrapper output. - # compile_commands.json holds absolute paths, so the trusted workflow must - # unpack this at the same $GITHUB_WORKSPACE path — same repo, so it matches. + # The C/C++ analyzer needs the sources AND the compilation database (kept in bw-output/, where the + # trusted workflow reads it). compile_commands.json holds absolute paths, so the trusted workflow must + # unpack this at the same $GITHUB_WORKSPACE path — same repo, so it matches. build/CMakeFiles stays in: + # with nothing compiled it is small, and it holds cmake_pch.hxx, which every command of the targets with + # the precompiled header includes (-include). - name: Pack analysis input run: | tar -czf /tmp/workspace.tar.gz \ - --exclude='./build/CMakeFiles' \ --exclude='*.o' \ --exclude='*.a' \ --exclude='*.so' \ diff --git a/.github/workflows/build_bin.yml b/.github/workflows/build_bin.yml index 65d74e36f..b6fb697b6 100644 --- a/.github/workflows/build_bin.yml +++ b/.github/workflows/build_bin.yml @@ -23,6 +23,101 @@ env: jobs: + # ============================================================ + # Whether the binaries are built at all + # ============================================================ + + # Every push to a branch of this repository runs this workflow, and a pull request from such a branch would run it + # once more for the same commit. The push run builds and publishes the download of the branch, so the pull request + # run of a branch of this repository builds nothing (the merge with the base is compiled by the Build and Coverage + # workflows), except a pull request into master (staging into master): that is the check before a release, of the + # merge, with both variants. A pull request from a fork has no push run here and builds as before. A push that changes only + # documentation or the data of the scenario tests (which the binaries don't contain) builds nothing either: the + # download of the branch stays at its last build, of the same binaries. Pushes to staging and master and manual runs + # always build. The checks are job-level conditions, not `paths-ignore` or `branches-ignore` on the trigger: a skipped + # job counts as passed, a workflow that doesn't start would leave a required check pending for ever (none is + # required today; a skipped matrix job shows under its unexpanded name, `${{ matrix.variant.name }}`). Anything + # this job can't decide builds. + # + # The variant without AVX2 (CPUs older than Haswell, 2013) is the same sources with one compiler switch: it is built + # for master only (pushes to master, pull requests into master, so every staging into master) and by a manual run. + # It builds no unit tests: they run in the AVX2 build of the same commit. + changes: + name: Whether to build + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + outputs: + build: ${{ steps.decide.outputs.build }} + variants: ${{ steps.decide.outputs.variants }} + noavx2: ${{ steps.decide.outputs.noavx2 }} + steps: + - name: Decide from the event and the changed files + id: decide + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + REPO: ${{ github.repository }} + REF: ${{ github.ref }} + SHA: ${{ github.sha }} + BEFORE: ${{ github.event.before }} + PR_NUMBER: ${{ github.event.pull_request.number }} + PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} + BASE_REF: ${{ github.base_ref }} + run: | + avx2='{"name":"AVX2","suffix":"avx2","cmake_flags":"-DENABLE_AVX2=ON","tests":true}' + noavx2='{"name":"No AVX2","suffix":"noavx2","cmake_flags":"-DENABLE_AVX2=OFF -DWITH_TESTS=OFF","tests":false}' + if [ "$EVENT_NAME" = workflow_dispatch ] \ + || { [ "$EVENT_NAME" = push ] && [ "$REF" = refs/heads/master ]; } \ + || { [ "$EVENT_NAME" = pull_request ] && [ "$BASE_REF" = master ]; }; then + echo "variants=[$avx2,$noavx2]" >> "$GITHUB_OUTPUT" + echo "noavx2=true" >> "$GITHUB_OUTPUT" + else + echo "variants=[$avx2]" >> "$GITHUB_OUTPUT" + echo "noavx2=false" >> "$GITHUB_OUTPUT" + fi + build() { echo "$1"; echo "build=true" >> "$GITHUB_OUTPUT"; exit 0; } + case "$EVENT_NAME" in + pull_request) + [ "$BASE_REF" != master ] || build "A pull request into master, building the merge." + if [ "$PR_HEAD_REPO" = "$REPO" ]; then + echo "A branch of this repository: its push run builds this commit." + echo "build=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[] | .filename, (.previous_filename // empty)')" \ + || build "The files of the pull request are not available, building." ;; + push) + case "$REF" in + refs/heads/staging|refs/heads/master) build "A push to staging or master, building." ;; + esac + # a new branch (before = zeros) against staging, then master; a later push against the commit before it + if [ -n "$BEFORE" ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + bases="$BEFORE" + else + bases="staging master" + fi + files="" + for base in $bases; do + # the compare lists at most 300 files: more than that, or no list, builds + if out="$(gh api "repos/$REPO/compare/$base...$SHA" --jq 'if (.files | length) < 300 then (.files[] | .filename, (.previous_filename // empty)) else error("too many files") end')"; then + files="$out" + break + fi + done ;; + *) build "A manual run, building." ;; + esac + [ -n "$files" ] || build "The list of changed files is not available or empty, building." + # what the binaries don't contain: *.md, docs/, LICENSE and the scenario tests (cases and their runner) + # (not *.txt: CMakeLists.txt is code; tests/unit is built into the binaries' test run) + if printf '%s\n' "$files" | grep -Evq '(\.md$|^docs/|^LICENSE|^tests/scenarios/)'; then + build "Code changed, building." + fi + echo "Only documentation or scenario test data changed, the binaries are not built." + echo "build=false" >> "$GITHUB_OUTPUT" + # ============================================================ # Windows / MSVC # ============================================================ @@ -37,6 +132,8 @@ jobs: windows: name: Windows x64 / MSVC / ${{ matrix.variant.name }} + needs: changes + if: needs.changes.outputs.build == 'true' runs-on: windows-2022 concurrency: group: ${{ github.workflow }}-windows-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} @@ -45,13 +142,8 @@ jobs: strategy: fail-fast: false matrix: - variant: - - name: "AVX2" - suffix: "avx2" - cmake_flags: "-DENABLE_AVX2=ON" - - name: "No AVX2" - suffix: "noavx2" - cmake_flags: "-DENABLE_AVX2=OFF" + # AVX2 always, without AVX2 for master only: see the job `changes` + variant: ${{ fromJSON(needs.changes.outputs.variants) }} steps: - name: Checkout repository @@ -101,6 +193,7 @@ jobs: # the unit tests run at the end of the build and load lua51.dll (the Lua screens), but ref/luajit has only its import # library. LuaJIT of the same 2.0 line is built here and put on PATH for them; it doesn't go into the uploaded build - name: Build lua51.dll for the unit tests + if: matrix.variant.tests shell: cmd run: | for /f "usebackq delims=" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSDIR=%%i" @@ -180,6 +273,170 @@ jobs: -Recurse ` -Force + # The downloads of the next step, kept between the runs: a release out of reach then doesn't fail the build. The + # key is this file, which pins them; a cache of an older one is taken too, as the next step checks every file by + # its SHA-256 and downloads only those it doesn't have. + - name: Restore the audio library downloads + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/audio-dlls-downloads + key: audio-dlls-${{ hashFiles('.github/workflows/build_bin.yml') }} + restore-keys: audio-dlls- + + # The game loads OpenAL32.dll and libsndfile-1.dll from its own folder, and the depot had OpenAL Soft 1.18.1 and + # libsndfile 1.0.28 (2017) there. OpenAL Soft 1.18 lacks ALC_SOFT_reopen_device and ALC_SOFT_system_events, so on + # Windows the sound didn't follow a change of the output device; libsndfile 1.0.28 reads no Opus and no MP3, which + # the Linux build (libsndfile 1.2) does. The official release binaries of both are taken, pinned by SHA-256. They + # need nothing beyond the system DLLs and msvcrt.dll (soft_oal.dll) or KERNEL32.dll (sndfile.dll). soft_oal.dll + # has no AVX code; sndfile.dll (its static opus and mpg123) picks its AVX/AVX2 paths at run time, so the same files + # go with both variants. The exe links them by name: soft_oal.dll is shipped as OpenAL32.dll (as its readme says, + # without the router), sndfile.dll as libsndfile-1.dll. Both are LGPL, so their license texts go with them, in + # licenses/, with those of what the DLLs have built in (below); the libsndfile zip has none, its COPYING is taken + # from the source tree of the same tag. Those texts are kept in ref/licenses (with where each comes from), so the + # build doesn't depend on the servers they come from. + - name: Add the OpenAL Soft and libsndfile DLLs + shell: pwsh + timeout-minutes: 10 + run: | + $ErrorActionPreference = 'Stop' + $ProgressPreference = 'SilentlyContinue' + $output = "build/bin/$env:CONFIG_WIN" + $licenses = Join-Path $output 'licenses' + $work = Join-Path $env:RUNNER_TEMP 'audio-dlls' + $downloads = Join-Path $env:RUNNER_TEMP 'audio-dlls-downloads' + New-Item -ItemType Directory -Force -Path $work, $licenses, $downloads | Out-Null + $pinned = [System.Collections.Generic.List[string]]::new() + + # the file of the URL with the given SHA-256: the one kept by a run before, else downloaded. named by its + # SHA-256 and the last part of its path, without the query + function Get-Pinned([string] $Url, [string] $Sha256) { + $name = "$Sha256-$([uri]::new($Url).Segments[-1])" + $pinned.Add($name) + $file = Join-Path $downloads $name + if ((Test-Path -Path $file) -and (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() -eq $Sha256) { + Write-Host "$Url kept by a run before" + return $file + } + Invoke-WebRequest -Uri $Url -OutFile $file -UserAgent 'ci-download' -MaximumRetryCount 3 -RetryIntervalSec 10 -TimeoutSec 120 + $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() + if ($hash -ne $Sha256) { + Remove-Item -Path $file -Force + throw "${Url}: SHA-256 $hash, expected $Sha256" + } + return $file + } + + # each package: the zip and, for each file wanted from it, where it goes in the build + $packages = @( + @{ Url = 'https://github.com/kcat/openal-soft/releases/download/1.25.2/openal-soft-1.25.2-bin.zip' + Sha256 = '67a0c4b800bd860c93c04f38caf8cbe4875f9c84700ac430efc451f70e265434' + Files = [ordered]@{ + 'openal-soft-1.25.2-bin/bin/Win64/soft_oal.dll' = 'OpenAL32.dll' + 'openal-soft-1.25.2-bin/COPYING' = 'licenses/openal-soft-COPYING.txt' } }, + @{ Url = 'https://github.com/libsndfile/libsndfile/releases/download/1.2.2/libsndfile-1.2.2-win64.zip' + Sha256 = '2173935c0c1ed13cf627951d34483f9d405ead2eb473190461c42ba220643a3f' + Files = [ordered]@{ + 'libsndfile-1.2.2-win64/bin/sndfile.dll' = 'libsndfile-1.dll' } } + ) + foreach ($package in $packages) { + $zip = Get-Pinned $package.Url $package.Sha256 + $unpacked = Join-Path $work ([IO.Path]::GetFileNameWithoutExtension($zip)) + Expand-Archive -Path $zip -DestinationPath $unpacked -Force + foreach ($entry in $package.Files.GetEnumerator()) { + Copy-Item -Path (Join-Path $unpacked $entry.Key) -Destination (Join-Path $output $entry.Value) -Force + Write-Host "$($entry.Value) <- $($package.Url) $($entry.Key)" + } + } + + # the license texts, each from the source tree of the version built in: of libsndfile, its ALAC and GSM 06.10 + # code, and the libraries its vcpkg build linked into sndfile.dll; of OpenAL Soft's PFFFT, Microsoft GSL and + # its BSD 3-Clause parts, and of the MinGW-w64 runtime and winpthreads, linked into soft_oal.dll (a MinGW GCC + # 15 build: the texts are the same in mingw-w64 12 and 13). + # The versions in sndfile.dll: those it names (libopus 1.4, libFLAC 1.4.2, libVorbis 1.3.7), mpg123 1.31.3 by + # the SHA-512 of its source archive in the build paths it keeps, and libogg 1.3.5 and LAME 3.100 of the vcpkg + # ports of the time (mid 2023). LAME's from Debian's copy of the 3.100 source, the same file as in LAME's own + # repository on SourceForge. The texts are in ref/licenses, whose README names the URL of each; each is + # checked by its SHA-256, so an edit or a line ending changed on the way doesn't go out unnoticed + $texts = [ordered]@{ + 'libsndfile-COPYING.txt' = 'ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140' + 'libsndfile-ALAC-LICENSE.txt' = '232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9' + 'libsndfile-GSM610-COPYRIGHT.txt' = '1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7' + 'libogg-COPYING.txt' = 'd2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814' + 'libvorbis-COPYING.txt' = 'ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a' + 'flac-COPYING.Xiph.txt' = '6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d' + 'opus-COPYING.txt' = '8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682' + 'mpg123-COPYING.txt' = 'c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366' + 'lame-COPYING.txt' = 'bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd' + 'openal-soft-pffft-LICENSE.txt' = '64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de' + 'openal-soft-gsl-LICENSE.txt' = '4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555' + 'openal-soft-BSD-3Clause.txt' = 'b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff' + 'openal-soft-winpthreads-COPYING.txt' = '63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177' + 'openal-soft-mingw-w64-runtime.txt' = 'e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd' + } + foreach ($text in $texts.GetEnumerator()) { + $file = Join-Path 'ref/licenses' $text.Key + $hash = (Get-FileHash -Algorithm SHA256 -Path $file).Hash.ToLowerInvariant() + if ($hash -ne $text.Value) { + throw "${file}: SHA-256 $hash, expected $($text.Value)" + } + Copy-Item -Path $file -Destination (Join-Path $licenses $text.Key) -Force + } + + # OpenAL Soft's bs2b has its license only in its source files: the notice as core/bs2b.cpp of 1.25.2 has it + @' + Copyright (c) 2005 Boris Mikhaylov + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + '@ | Set-Content -Path (Join-Path $licenses 'openal-soft-bs2b-LICENSE.txt') -Encoding utf8 + + # what the DLLs are and have built in, where their source is (the LGPL ones); the DLLs can be replaced by the user + @( + 'OpenAL32.dll: OpenAL Soft 1.25.2, unmodified soft_oal.dll of the official binaries, GNU LGPL 2 or later' + ' (openal-soft-COPYING.txt). Source: https://github.com/kcat/openal-soft/releases/tag/1.25.2' + ' Built in: a modified PFFFT, BSD-style (openal-soft-pffft-LICENSE.txt); Microsoft GSL, MIT' + ' (openal-soft-gsl-LICENSE.txt); the ambisonic rotator, the vocal morpher and the compressor, BSD 3-Clause' + ' (openal-soft-BSD-3Clause.txt); bs2b, MIT (openal-soft-bs2b-LICENSE.txt); {fmt} 11.2.0, MIT, whose' + ' exception for the object form asks for no text. Linked into it by its MinGW-w64 build: the MinGW-w64' + ' runtime (openal-soft-mingw-w64-runtime.txt) and winpthreads, MIT and BSD-style' + ' (openal-soft-winpthreads-COPYING.txt);' + ' libstdc++ and libgcc under the GCC Runtime Library Exception, which asks for no text.' + ' Its default HRTF data set is based on the KEMAR HRTF measurements by Bill Gardner and Keith Martin,' + ' MIT Media Laboratory, 1994: http://sound.media.mit.edu/resources/KEMAR.html' + 'libsndfile-1.dll: libsndfile 1.2.2, unmodified sndfile.dll of the official binaries, GNU LGPL 2.1 or later' + ' (libsndfile-COPYING.txt). Source: https://github.com/libsndfile/libsndfile/releases/tag/1.2.2' + ' Its ALAC code: Apache License 2.0 (libsndfile-ALAC-LICENSE.txt). Its GSM 06.10 code: Jutta Degener and' + ' Carsten Bormann, TU Berlin (libsndfile-GSM610-COPYRIGHT.txt). Its G.721/G.723 code: Sun Microsystems, public' + ' domain.' + ' Linked into it by its build, made with the vcpkg ports of the time and their patches' + ' (https://github.com/microsoft/vcpkg/tree/2023.08.09/ports, the ports named below):' + ' libogg 1.3.5, BSD (libogg-COPYING.txt), port libogg. Source: https://github.com/xiph/ogg/releases/tag/v1.3.5' + ' libvorbis 1.3.7, BSD (libvorbis-COPYING.txt), port libvorbis. Source: https://github.com/xiph/vorbis/releases/tag/v1.3.7' + ' libFLAC 1.4.2, BSD (flac-COPYING.Xiph.txt), port libflac. Source: https://github.com/xiph/flac/releases/tag/1.4.2' + ' libopus 1.4, BSD (opus-COPYING.txt), port opus. Source: https://github.com/xiph/opus/releases/tag/v1.4' + ' mpg123 1.31.3, GNU LGPL 2.1 (mpg123-COPYING.txt), port mpg123. Source: https://www.mpg123.de/download/mpg123-1.31.3.tar.bz2' + ' LAME 3.100, GNU LGPL 2 or later (lame-COPYING.txt), port mp3lame. Source: https://sourceforge.net/projects/lame/files/lame/3.100/' + ) | Set-Content -Path (Join-Path $licenses 'audio-libraries.txt') -Encoding utf8 + + # the files no pin names any more aren't kept for the next run + Get-ChildItem -Path $downloads -File | Where-Object { $pinned -notcontains $_.Name } | Remove-Item -Force + - name: Upload Windows build uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: @@ -206,7 +463,14 @@ jobs: linux: name: Linux x64 / GCC / ${{ matrix.variant.name }} + needs: changes + if: needs.changes.outputs.build == 'true' runs-on: ubuntu-24.04 + # the key of a compiler cache saved here, one output per variant (a matrix job's outputs are shared by its legs): + # the job linux-ccache-cleanup deletes the older ones, so this job needs no write access + outputs: + ccache-key-avx2: ${{ steps.ccache-saved.outputs.avx2 }} + ccache-key-noavx2: ${{ steps.ccache-saved.outputs.noavx2 }} # see the notes above the windows job: two variants, each with a concurrency group of its own concurrency: group: ${{ github.workflow }}-linux-${{ matrix.variant.suffix }}-${{ github.event_name }}-${{ github.ref == 'refs/heads/master' && github.sha || github.ref }} @@ -215,13 +479,8 @@ jobs: strategy: fail-fast: false matrix: - variant: - - name: "AVX2" - suffix: "avx2" - cmake_flags: "-DENABLE_AVX2=ON" - - name: "No AVX2" - suffix: "noavx2" - cmake_flags: "-DENABLE_AVX2=OFF" + # AVX2 always, without AVX2 for master only: see the job `changes` + variant: ${{ fromJSON(needs.changes.outputs.variants) }} steps: - name: Checkout repository @@ -236,37 +495,40 @@ jobs: with: python-version: "3.14" - # A mirror that stops answering used to hold this step for over an hour. - # Time out each download, retry it, and give up on the whole step early. + # The packages are kept in the Actions cache (.github/actions/apt-install): the mirror of the runners has been + # too slow to download them every time. The timeout is a safety net. + # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). + # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. + # The X11 packages are the ones GLFW (ref/glfw, 3.4) looks for; xorg-dev brought ~45 more. The game loads the + # X11 and Wayland libraries of the system, none of them is bundled (CMake_modules/bundle_runtime_libs.cmake). - name: Install Linux dependencies timeout-minutes: 15 - run: | - printf '%s\n' \ - 'Acquire::Retries "3";' \ - 'Acquire::http::Timeout "60";' \ - 'Acquire::https::Timeout "60";' \ - | sudo tee /etc/apt/apt.conf.d/80-ci-retries > /dev/null - sudo apt-get update - - # libasound2-dev, libpulse-dev and libpipewire-0.3-dev: the headers of OpenAL Soft's audio backends (built below). - # Without them it builds with OSS only, which modern distributions and the Steam Linux Runtime don't have: no sound. - sudo apt-get install -y \ - build-essential \ - libasound2-dev \ - libpulse-dev \ - libpipewire-0.3-dev \ - libgl1-mesa-dev \ - libglew-dev \ - libglfw3-dev \ - libpng-dev \ - libopenal-dev \ - libluajit-5.1-dev \ - libserialport-dev \ - libsndfile1-dev \ - libcurl4-openssl-dev \ - xorg-dev \ - libxkbcommon-dev \ - libwayland-dev \ + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential + ccache + pkg-config + libasound2-dev + libpulse-dev + libpipewire-0.3-dev + libgl1-mesa-dev + libglew-dev + libglfw3-dev + libpng-dev + libopenal-dev + libluajit-5.1-dev + libserialport-dev + libsndfile1-dev + libcurl4-openssl-dev + libx11-dev + libxcursor-dev + libxext-dev + libxi-dev + libxinerama-dev + libxrandr-dev + libxkbcommon-dev + libwayland-dev wayland-protocols # @@ -309,11 +571,39 @@ jobs: cmake --version python --version + # The compiler cache (ccache), one per variant. Only the runs on staging and master save it (the step after the + # build) and delete their older ones; a pull request takes the newest one of its variant, and so recompiles just + # what it changed. A pull request can read the caches of its base branch and of the default branch, not those of + # other pull requests. A push of another branch can read only master's, so it hits only as far as the branch + # still matches master. + # The compiler version is in the key, so a new GCC of the runner image starts a cache of its own, with no + # fallback to the cache of the old one, which ccache couldn't use (the compiler is part of its hash). + - name: Compiler cache key + id: ccache-key + run: echo "gcc=$(g++ -dumpfullversion)" >> "$GITHUB_OUTPUT" + + - name: Restore the compiler cache + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ccache + key: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} + restore-keys: | + ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}- + - name: Configure + env: + CCACHE_DIR: ${{ runner.temp }}/ccache + CCACHE_MAXSIZE: 500M + # the game and eu07_core use a precompiled header (stdafx.h): ccache caches such compilations only with + # this sloppiness, else it compiles every file in full + CCACHE_SLOPPINESS: pch_defines,time_macros,include_file_mtime,include_file_ctime run: | + ccache --zero-stats cmake \ -S . \ -B build \ + -DCMAKE_C_COMPILER_LAUNCHER=ccache \ + -DCMAKE_CXX_COMPILER_LAUNCHER=ccache \ -DCMAKE_BUILD_TYPE="${CONFIG_LINUX}" \ -DWITH_ZMQ=OFF \ -DWITH_OPENVR=OFF \ @@ -322,11 +612,36 @@ jobs: -DPython3_EXECUTABLE="${{ steps.python.outputs.python-path }}" \ -DCMAKE_CXX_FLAGS="-Wno-attributes -fno-inline-functions-called-once" + # CCACHE_BASEDIR makes the paths relative, so a cache made on another checkout path still hits - name: Build + env: + CCACHE_DIR: ${{ runner.temp }}/ccache + CCACHE_MAXSIZE: 500M + CCACHE_BASEDIR: ${{ github.workspace }} + # the game and eu07_core use a precompiled header (stdafx.h): ccache caches such compilations only with + # this sloppiness, else it compiles every file in full + CCACHE_SLOPPINESS: pch_defines,time_macros,include_file_mtime,include_file_ctime run: | cmake \ --build build \ --parallel "$(nproc)" + ccache --show-stats + + - name: Save the compiler cache + id: ccache-save + if: ${{ !cancelled() && github.event_name == 'push' && (github.ref == 'refs/heads/staging' || github.ref == 'refs/heads/master') }} + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/ccache + key: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} + + # for the job linux-ccache-cleanup, which deletes the older caches of this branch and variant + - name: Pass on the saved compiler cache key + id: ccache-saved + if: ${{ !cancelled() && steps.ccache-save.outcome == 'success' }} + env: + KEY: ccache-linux-${{ matrix.variant.suffix }}-gcc${{ steps.ccache-key.outputs.gcc }}-${{ github.sha }} + run: echo "${{ matrix.variant.suffix }}=$KEY" >> "$GITHUB_OUTPUT" # the build copies the shared libraries next to the game (CMake_modules/bundle_runtime_libs.cmake) and the # game looks for them there first ($ORIGIN): each one it loads from outside build/bin has to be one of the system @@ -391,13 +706,49 @@ jobs: retention-days: 14 + # a cache can't be written over, so every save of the linux job is a new key of up to 0.5 GB. the older ones of the + # branch and variant (of any GCC) go right after it, or they'd fill the 10 GB of the repository and push out the + # small caches (audio-dlls-*, apt-*). only the caches created before the one saved go: when two runs of a branch end + # together, the one which saved later keeps its cache. a failed delete only leaves the old cache to the eviction + linux-ccache-cleanup: + name: Linux / delete the older compiler caches + needs: linux + if: ${{ !cancelled() && (needs.linux.outputs.ccache-key-avx2 != '' || needs.linux.outputs.ccache-key-noavx2 != '') }} + runs-on: ubuntu-24.04 + permissions: + actions: write + + steps: + - name: Delete the older compiler caches + env: + GH_TOKEN: ${{ github.token }} + SAVED: ${{ needs.linux.outputs.ccache-key-avx2 }} ${{ needs.linux.outputs.ccache-key-noavx2 }} + run: | + # the ids of the caches created before the one saved (env.KEEP); none when it isn't listed. the times are + # compared as numbers, as their fractions of a second can have any number of digits + older=' + def t: capture("^(?[^.Z]+)(?[.][0-9]+)?Z$") | ((.s + "Z") | fromdateiso8601) + (("0" + (.f // "")) | tonumber); + (map(select(.key == env.KEEP)) | first | .createdAt) as $saved + | if $saved == null then empty else ($saved | t) as $at | .[] | select((.createdAt | t) < $at) | .id end' + for KEEP in $SAVED; do + export KEEP + # the key without its GCC version and commit: ccache-linux-- + prefix="${KEEP%%-gcc*}-" + gh cache list --repo "$GITHUB_REPOSITORY" --ref "$GITHUB_REF" --key "$prefix" --limit 100 \ + --json id,key,createdAt --jq "$older" | + while read -r id; do + gh cache delete "$id" --repo "$GITHUB_REPOSITORY" || echo "::warning::cache $id not deleted" + done + done + + # ============================================================ # Public download: release assets need no GitHub account # ============================================================ publish: name: Publish public download - needs: [windows, linux] + needs: [changes, windows, linux] if: github.event_name != 'pull_request' runs-on: ubuntu-24.04 permissions: @@ -409,25 +760,27 @@ jobs: steps: # the AVX2 build keeps the old name of the download, so the links already handed out still work - name: Download Windows build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-avx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64 - name: Download Windows build (no AVX2) - uses: actions/download-artifact@v4 + if: needs.changes.outputs.noavx2 == 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-windows-x64-noavx2-${{ env.CONFIG_WIN }} path: dist/maszyna-windows-x64-noavx2 - name: Download Linux build (AVX2) - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-avx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64 - name: Download Linux build (no AVX2) - uses: actions/download-artifact@v4 + if: needs.changes.outputs.noavx2 == 'true' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: maszyna-linux-x64-noavx2-${{ env.CONFIG_LINUX }} path: dist/maszyna-linux-x64-noavx2 @@ -438,6 +791,7 @@ jobs: # the artifacts lose the executable bit for dir in maszyna-linux-x64 maszyna-linux-x64-noavx2; do + [ -d "$dir" ] || continue find "$dir" -type f -exec sh -c 'file -b "$1" | grep -q "^ELF" && chmod +x "$1"' _ {} \; if [ -d "$dir/linuxpython64/bin" ]; then chmod +x "$dir"/linuxpython64/bin/* @@ -445,9 +799,12 @@ jobs: done (cd maszyna-windows-x64 && zip -qr9 ../maszyna-windows-x64.zip .) - (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) tar -czf maszyna-linux-x64.tar.gz -C maszyna-linux-x64 . - tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . + # without AVX2: master only + if [ -d maszyna-windows-x64-noavx2 ]; then + (cd maszyna-windows-x64-noavx2 && zip -qr9 ../maszyna-windows-x64-noavx2.zip .) + tar -czf maszyna-linux-x64-noavx2.tar.gz -C maszyna-linux-x64-noavx2 . + fi ls -la - name: Publish rolling release of the branch @@ -462,23 +819,26 @@ jobs: tag="build-$slug" base="${{ github.server_url }}/${{ github.repository }}/releases/download/$tag" + assets=(dist/maszyna-windows-x64.zip dist/maszyna-linux-x64.tar.gz) + links=("- Windows: $base/maszyna-windows-x64.zip" "- Linux: $base/maszyna-linux-x64.tar.gz") + if [ -f dist/maszyna-windows-x64-noavx2.zip ]; then + assets+=(dist/maszyna-windows-x64-noavx2.zip dist/maszyna-linux-x64-noavx2.tar.gz) + links+=("- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" + "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz") + else + links+=("- CPUs without AVX2 (older than Haswell, 2013): built for master only, see the release build-master") + fi notes="$(printf '%s\n' \ "Automatic build of branch \`$BRANCH\`, commit $SHA, replaced by every push to the branch." \ "" \ "Download without a GitHub account:" \ - "- Windows: $base/maszyna-windows-x64.zip" \ - "- Windows, CPUs without AVX2 (older than Haswell, 2013): $base/maszyna-windows-x64-noavx2.zip" \ - "- Linux: $base/maszyna-linux-x64.tar.gz" \ - "- Linux, CPUs without AVX2: $base/maszyna-linux-x64-noavx2.tar.gz" \ + "${links[@]}" \ "" \ "Unpack over a MaSzyna installation (the game data isn't included). Build log: $RUN_URL")" gh release delete "$tag" --yes --cleanup-tag || true gh release create "$tag" \ - dist/maszyna-windows-x64.zip \ - dist/maszyna-windows-x64-noavx2.zip \ - dist/maszyna-linux-x64.tar.gz \ - dist/maszyna-linux-x64-noavx2.tar.gz \ + "${assets[@]}" \ --target "$SHA" \ --prerelease \ --latest=false \ diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index d2f00bccd..3f48480a9 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -28,8 +28,49 @@ concurrency: cancel-in-progress: true jobs: + # A pull request that changes only documentation or the scenario tests (cases and their runner, which aren't built) + # doesn't need the coverage build. The check is a job-level + # condition, not `paths-ignore` on the trigger: a workflow that doesn't start leaves a required check "pending" + # for ever, while a skipped job (its name is fixed) counts as passed. A push, and anything this step can't + # decide, runs the build. + changes: + name: Which files changed + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + pull-requests: read + outputs: + code: ${{ steps.files.outputs.code }} + steps: + - name: List the changed files + id: files + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + REPO: ${{ github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + if [ "$EVENT_NAME" != pull_request ]; then + echo "code=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + if ! files="$(gh api --paginate "repos/$REPO/pulls/$PR_NUMBER/files" --jq '.[] | .filename, (.previous_filename // empty)')" || [ -z "$files" ]; then + echo "The list of changed files is not available, building." + echo "code=true" >> "$GITHUB_OUTPUT" + exit 0 + fi + # what is not built: *.md, docs/, LICENSE and tests/scenarios/ (not *.txt: CMakeLists.txt is code) + if printf '%s\n' "$files" | grep -Evq '(\.md$|^docs/|^LICENSE|^tests/scenarios/)'; then + echo "code=true" >> "$GITHUB_OUTPUT" + else + echo "Only documentation or scenario tests changed, the coverage build is skipped." + echo "code=false" >> "$GITHUB_OUTPUT" + fi + coverage: name: Unit test coverage (GCC) + needs: changes + if: needs.changes.outputs.code == 'true' runs-on: ubuntu-24.04 timeout-minutes: 60 permissions: @@ -47,14 +88,19 @@ jobs: # the same packages as the Build workflow: the game is configured as a whole, # though only the unit tests and the core library they link are built - name: Install build dependencies + timeout-minutes: 15 + uses: ./.github/actions/apt-install + with: + packages: >- + build-essential pkg-config + libgl1-mesa-dev libglew-dev libglfw3-dev + libpng-dev libopenal-dev libluajit-5.1-dev + libserialport-dev libsndfile1-dev + libx11-dev libxcursor-dev libxext-dev libxi-dev libxinerama-dev libxrandr-dev + libxkbcommon-dev libwayland-dev wayland-protocols + + - name: Install gcovr run: | - sudo apt-get update -y - sudo apt-get install -y \ - build-essential \ - libgl1-mesa-dev libglew-dev libglfw3-dev \ - libpng-dev libopenal-dev libluajit-5.1-dev \ - libserialport-dev libsndfile1-dev \ - xorg-dev libxkbcommon-dev libwayland-dev wayland-protocols python3 -m pip install --no-cache-dir --only-binary :all: gcovr==8.3 - name: Build current OpenAL Soft @@ -78,7 +124,6 @@ jobs: run: | cmake -S . -B build \ -DCMAKE_BUILD_TYPE=Debug \ - -DWITH_BETTER_RENDERER=OFF \ -DWITH_ZMQ=OFF -DWITH_OPENVR=OFF -DUSE_LTO=OFF \ -DCMAKE_CXX_FLAGS="--coverage -O0 -Wno-attributes -fno-inline-functions-called-once" \ -DPython3_EXECUTABLE="$(which python3)" @@ -90,15 +135,14 @@ jobs: - name: Run the unit tests run: ./build/tests/unit/eu07_unit_tests - # the game's own sources only: no submodules, no vendored code, not the tests themselves. - # betterRenderer/ is left out for its thirdparty/yaml-cpp, which every target of the game links and so builds here + # the game's own sources only: no submodules, no vendored code, not the tests themselves - name: Coverage report run: | # a failure of gcovr fails the step, though its output goes through tee set -o pipefail mkdir -p coverage-report/html gcovr --root . build \ - --exclude 'ref/' --exclude 'imgui/' --exclude 'stb/' --exclude 'betterRenderer/' \ + --exclude 'ref/' --exclude 'imgui/' --exclude 'stb/' \ --exclude 'tests/' --exclude 'build/' \ --gcov-ignore-parse-errors=negative_hits.warn_once_per_file \ --gcov-ignore-errors=no_working_dir_found \ diff --git a/.github/workflows/shaders.yml b/.github/workflows/shaders.yml index 2d6135de4..b90be3d06 100644 --- a/.github/workflows/shaders.yml +++ b/.github/workflows/shaders.yml @@ -15,6 +15,7 @@ on: - 'shaders/**' - 'gl/**' - 'rendering/common/**' + - 'rendering/vulkan14/vulkan14bindings.h' - 'ci_shadervalidator/**' - '.github/workflows/shaders.yml' pull_request: @@ -23,6 +24,7 @@ on: - 'shaders/**' - 'gl/**' - 'rendering/common/**' + - 'rendering/vulkan14/vulkan14bindings.h' - 'ci_shadervalidator/**' - '.github/workflows/shaders.yml' diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 93475df19..58e852370 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -130,6 +130,9 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} REPO: ${{ github.repository }} + RUN_EVENT: ${{ github.event.workflow_run.event }} + RUN_REPO: ${{ github.event.workflow_run.head_repository.full_name }} + RUN_BRANCH: ${{ github.event.workflow_run.head_branch }} run: | set -euo pipefail cd "$GITHUB_WORKSPACE" @@ -137,7 +140,18 @@ jobs: echo "event=$event" >> "$GITHUB_OUTPUT" if [ "$event" != "pull_request" ]; then - echo "Branch build, no PR parameters." + # A push: the branch comes from the trusted event, not from the artifact. Only + # master and staging are pushed to with a build (build.yml); anything else is refused + # rather than analysed as a branch of its own. + if [ "$RUN_EVENT" != "push" ] || [ "$RUN_REPO" != "$REPO" ]; then + echo "::error::branch build that isn't a push to this repository ($RUN_EVENT, $RUN_REPO)" + exit 1 + fi + case "$RUN_BRANCH" in + master|staging) echo "branch=$RUN_BRANCH" >> "$GITHUB_OUTPUT" ;; + *) echo "::error::no analysis for a push to $RUN_BRANCH"; exit 1 ;; + esac + echo "Branch build of $RUN_BRANCH, no PR parameters." exit 0 fi @@ -189,11 +203,9 @@ jobs: --define sonar.pullrequest.branch=${{ steps.meta.outputs.head }} --define sonar.pullrequest.base=${{ steps.meta.outputs.base }} - # No sonar.branch.name here on purpose: branch analysis is a paid feature, - # and passing it would push the scanner onto that code path. Omitting it - # means this is a plain main-branch analysis, which the Free plan allows. + # master is the main branch of the SonarQube Cloud project: no sonar.branch.name. - name: SonarQube Cloud scan (main branch) - if: steps.meta.outputs.event != 'pull_request' + if: steps.meta.outputs.event != 'pull_request' && steps.meta.outputs.branch == 'master' uses: SonarSource/sonarqube-scan-action@fd88b7d7ccbaefd23d8f36f73b59db7a3d246602 # v6.0.0 env: SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} @@ -206,6 +218,25 @@ jobs: --define sonar.qualitygate.wait=true --define sonar.scm.revision=${{ github.event.workflow_run.head_sha }} + # staging as a branch of its own next to master, so its issues and its quality gate show + # before staging is merged into master. SonarQube Cloud keeps it as a long-lived branch + # only if its name matches the project's long-lived branch pattern (Administration > + # Branches and Pull Requests); otherwise it is a short-lived one, deleted when inactive. + - name: SonarQube Cloud scan (staging) + if: steps.meta.outputs.event != 'pull_request' && steps.meta.outputs.branch == 'staging' + uses: SonarSource/sonarqube-scan-action@fd88b7d7ccbaefd23d8f36f73b59db7a3d246602 # v6.0.0 + env: + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + SONAR_HOST_URL: https://sonarcloud.io + with: + args: > + --define sonar.cfamily.compile-commands=${{ env.BUILD_WRAPPER_OUT_DIR }}/compile_commands.json + --define sonar.cfamily.taintAnalysis=false + --define sonar.exclusions=${{ env.SONAR_EXCLUSIONS }} + --define sonar.qualitygate.wait=true + --define sonar.scm.revision=${{ github.event.workflow_run.head_sha }} + --define sonar.branch.name=staging + - name: Report success if: success() env: diff --git a/.gitignore b/.gitignore index 9c9706dba..e428a464b 100644 --- a/.gitignore +++ b/.gitignore @@ -28,3 +28,6 @@ vcpkg.json tools/python314/ __pycache__/ *.pyc + +# reviews of other pull requests, kept locally +/pr-reviews/ diff --git a/AGENTS.md b/AGENTS.md index 3b52f36ee..29ce734ed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -93,6 +93,50 @@ To keep the gate passing, write new code so that it doesn't raise the rules that The project is C++20 (`CMAKE_CXX_STANDARD 20`), so no C++23 library addition is available on any compiler. That rules out `std::ranges::to`, `views::zip`, `views::enumerate`, `ranges::contains`, `std::print` and `std::expected`. +## Naming and the vehicle code + +New code, and code that gets restructured, is named in English with these cases: + +- **PascalCase** for types (classes, structs, enums, aliases), for public member functions and for free functions declared in + headers. +- **camelCase** for everything else: private and internal functions (those of an anonymous namespace too), all variables, members + (public ones too) and parameters, and the values of enums (`VehicleCommand::mainController`). +- No prefixes of the type or the kind (`f`, `i`, `b`, `mv`, `p` and the like) and no Polish names (`zaluzje`, `temperatura1`). + +Code that isn't otherwise touched keeps its names; renaming a member goes together with the restructuring of its part. What files, +scripts and the log read stays byte for byte the same whatever the C++ names are: the keywords of the `.fiz` and the scenery, the +keys of the dictionaries of the Python screens, the texts of the log and of `STR(...)`. + +The vehicle code is in `physics/` (the physics of the vehicles: `vehicle.h` with the class `physics::Vehicle`, and `physics/components/*.cpp` by subsystem, `brakes.*`, +couplers, collisions, derailment) and `vehicle/` (the vehicle in the scenery, the cab, the AI). Keep it that way: + +- `physics/vehicletypes.h` holds the vocabulary the rest of the simulator passes around (vehicle ends, sides, couplings, lights, + sounds, the types of drive and brake). A header that only names these includes it, not `physics/vehicle.h`; a header that only + points at a `physics::Vehicle` or a `TDynamicObject` declares it (`utilities/Classes.h`) and includes neither. +- A state of several mutually exclusive values is an `enum class`, a set of independent conditions is named fields, not the bits of + an `int`. Numbers of the formats (`.scn`, events, the network) are read into these where they come in and written where they go out. +- The commands between the vehicles are `VehicleCommand` (`physics/vehiclecommand.h`); their text names only matter where a command + comes as text. +- What depends on the kind of drive (`EngineType`) goes into its class in `physics/components/drive.*`, not into a new `switch`. +- The parts of `physics::Vehicle` are components, as `physics/components/maincircuit.h`, `lowvoltage.h`, `pantographs.h` and + `airsupply.h` show: what the `.fiz` defines is in their public `config`, written only by the parser and the setup of the vehicle; + their state is private, read through queries and changed through operations named after what happens (`Close()`, + `ResetGround()`, `Switch()`). The logic that concerns only a part is its own (`Update()` of the converter, of the compressor, of + the air of the pantographs), and the vehicle hands it what it needs as plain values (`ConverterSupply`, `CompressorInputs`) rather + than a `physics::Vehicle &`. The vehicle decides when a part acts and follows up what a step of it reports. A test that sets a + state directly uses the `...ForTest()` operation of the part, never a back door in the game's code. A new part follows the same + pattern, and a part being worked on moves to it. +- Outside `physics/` the state of a `physics::Vehicle` is changed only through its operations (`SetMainCtrlPos()`, + `SetLitLights()`, `UnloadStep()`, `ShakeVertically()`, ...), never by writing its fields; the only exception is its definition, + which the scenery and the `.mmd` adjust as the vehicle loads. A field the rest of the simulator only reads is private with a + query named as the field was (`Vmax()`, `Ft()`), a field nothing outside uses is private outright, and a new field starts + private. The same holds for `TController`: the cab and the events read it through its queries; only the debug and timetable + panels are its friends. +- What concerns a consist rather than a vehicle works on the vehicles of the consist given to it in their order + (`physics::ConsistBrakeBlending`), not on `TDynamicObject`, so that it can be tested without the scenery. +- The renderer and the rest of the simulator outside `physics/` and `vehicle/` read a vehicle through `TDynamicObject` (its + dimensions, speed, active cab, lights), not through `physics/vehicle.h`. + ## Renderers: the move to OpenGL 4.6 and Vulkan The renderers on `master` are to be replaced. `feat/gl46-migration` (PR #216, a draft with milestone 27.04, to be merged after the diff --git a/CMakeLists.txt b/CMakeLists.txt index d9ef586f4..561bbc127 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -17,6 +17,25 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake_modules/") set(DEPS_DIR ${DEPS_DIR} "${CMAKE_CURRENT_SOURCE_DIR}/ref") project("eu07") +# the submodules a clone hasn't filled (an older clone, whose .gitmodules didn't list them yet): told at once, before the error of the +# first one used, which names only its missing file +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.gitmodules") + file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/.gitmodules" EU07_SUBMODULE_PATHS REGEX "^[ \t]*path[ \t]*=") + set(EU07_EMPTY_SUBMODULES "") + foreach (line IN LISTS EU07_SUBMODULE_PATHS) + string(REGEX REPLACE "^[ \t]*path[ \t]*=[ \t]*" "" submodule "${line}") + string(STRIP "${submodule}" submodule) + file(GLOB submodule_files "${CMAKE_CURRENT_SOURCE_DIR}/${submodule}/*") + if (NOT submodule_files) + list(APPEND EU07_EMPTY_SUBMODULES "${submodule}") + endif() + endforeach() + if (EU07_EMPTY_SUBMODULES) + string(REPLACE ";" ", " EU07_EMPTY_SUBMODULES "${EU07_EMPTY_SUBMODULES}") + message(WARNING "empty submodules: ${EU07_EMPTY_SUBMODULES}. fill them with: git submodule sync && git submodule update --init --recursive") + endif() +endif() + #set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fsanitize=address -fsanitize=undefined") #set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fsanitize=undefined -Wformat") #set(CMAKE_LD_FLAGS "${CMAKE_LD_FLAGS} -fsanitize=address -fsanitize=undefined") @@ -37,7 +56,8 @@ set(CMAKE_CXX_STANDARD 20) file(GLOB HEADERS "*.h" "Console/*.h" -"McZapkie/*.h" +"physics/*.h" +"physics/components/*.h" "gl/*.h" "network/*.h" "vr/*.h" @@ -60,7 +80,10 @@ file(GLOB HEADERS "*.h" "model/*.h" "utilities/*.h" "world/*.h" -"vehicle/*.h") +"vehicle/*.h" +"vehicle/ai/*.h" +"vehicle/dynamic/*.h" +"vehicle/cab/*.h") set(GLOBAL_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}") set(GLOBAL_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/global_include") @@ -73,6 +96,12 @@ endif() option(WITH_OPENGL_MODERN "Compile with OpenGL modern renderer" ON) option(WITH_VULKAN "Compile with the Vulkan 1.4 renderer (gfxrenderer vulkan); needs the submodules ref/volk and ref/Vulkan-Headers" ON) option(WITH_DLSS "Compile the Vulkan renderer with NVIDIA DLSS (gfx.antialiasing dlss); needs the DLSS SDK in DLSS_SDK_ROOT, cmake -P tools/fetch_dlss_sdk.cmake" OFF) +# the development libraries of dlss (the indicator and the debug keys, gfx.dlss.developer) next to the program, in ngx_dev/. the license +# of the sdk lets only the production libraries go out with the program, so a build to be given out leaves them off +option(DLSS_DEVELOPMENT_LIBRARIES "With WITH_DLSS, copy the development libraries of DLSS to ngx_dev/ next to the program (not to be distributed)" OFF) +if (WITH_DLSS AND NOT WITH_VULKAN) + message(WARNING "WITH_DLSS=ON is for the Vulkan renderer, which WITH_VULKAN=OFF leaves out: the build has no DLSS") +endif() option(WITH_PYTHON "Python 3.14 embedded scripting" ON) option(WITH_UART "Compile with libserialport" ON) option(WITH_LUA "Compile with lua scripting support" ON) @@ -90,6 +119,7 @@ option(WITHDUMPGEN "Enable generating DMP files on crash" ON) option(ENABLE_AVX2 "Enable AVX2 instruction set (requires AVX2-capable CPU, Haswell/2013 or newer)" ON) option(BUNDLE_VC_RUNTIME "Copy the Visual C++ runtime libraries next to the executable (MSVC), so it does not depend on the installed redistributable" ON) option(ADD_VERSION_SUFFIX "Add date and commit hash to the executable name" ON) +option(USE_SYSTEM_JSON "Use an installed nlohmann_json (3.9 or newer) instead of the ref/json submodule" OFF) set(BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) # vcpkg init @@ -101,6 +131,7 @@ list(APPEND CMAKE_MODULE_PATH "${VCPKG_INSTALLED_PATH}/share") set(SOURCES "model/Texture.cpp" "utilities/Timer.cpp" +"utilities/asciiname.cpp" "utilities/workerpool.cpp" "utilities/memorystats.cpp" "world/Track.cpp" @@ -121,6 +152,7 @@ set(SOURCES "world/RailCarve.cpp" "world/RailLayer.cpp" "world/TrackUneven.cpp" +"world/TrackBuckle.cpp" "world/Road.cpp" "world/Sweep.cpp" "world/RoadPoint.cpp" @@ -136,15 +168,61 @@ set(SOURCES "world/catenary_catalog.cpp" "world/catenary_scene_objects.cpp" "world/TractionPower.cpp" -"vehicle/Train.cpp" +"vehicle/cab/auxiliarycommands.cpp" +"vehicle/cab/brakecommands.cpp" +"vehicle/cab/cab.cpp" +"vehicle/cab/cabcommands.cpp" +"vehicle/cab/commandtable.cpp" +"vehicle/cab/controllercommands.cpp" +"vehicle/cab/couplingcommands.cpp" +"vehicle/cab/doorcommands.cpp" +"vehicle/cab/equipmentcommands.cpp" +"vehicle/cab/lightcommands.cpp" +"vehicle/cab/pantographcommands.cpp" +"vehicle/cab/powercommands.cpp" +"vehicle/cab/screens.cpp" +"vehicle/cab/setup.cpp" +"vehicle/cab/signalcommands.cpp" +"vehicle/cab/sounds.cpp" +"vehicle/cab/train.cpp" +"vehicle/cab/update.cpp" "world/TrkFoll.cpp" +"world/deer.cpp" "vehicle/AirCoupler.cpp" "model/AnimModel.cpp" "vehicle/Button.cpp" "vehicle/Camera.cpp" -"vehicle/Driver.cpp" +"vehicle/ai/consist.cpp" +"vehicle/ai/controls.cpp" +"vehicle/ai/doors.cpp" +"vehicle/ai/driver.cpp" +"vehicle/ai/engine.cpp" +"vehicle/ai/force.cpp" +"vehicle/ai/obstacles.cpp" +"vehicle/ai/orders.cpp" +"vehicle/ai/physicslog.cpp" +"vehicle/ai/routescan.cpp" +"vehicle/ai/situation.cpp" +"vehicle/ai/speed.cpp" +"vehicle/ai/speedpos.cpp" +"vehicle/ai/speedtable.cpp" +"vehicle/crewchange.cpp" "application/driverhints.cpp" -"vehicle/DynObj.cpp" +"vehicle/dynamic/animations.cpp" +"vehicle/dynamic/consist.cpp" +"vehicle/dynamic/couplers.cpp" +"vehicle/dynamic/destinations.cpp" +"vehicle/dynamic/lifecycle.cpp" +"vehicle/dynamic/lights.cpp" +"vehicle/dynamic/load.cpp" +"vehicle/dynamic/mmd.cpp" +"vehicle/dynamic/movement.cpp" +"vehicle/dynamic/neighbours.cpp" +"vehicle/dynamic/offtrack.cpp" +"vehicle/dynamic/sounds.cpp" +"vehicle/dynamic/update.cpp" +"vehicle/dynamic/vehicletable.cpp" +"vehicle/dynamic/visual.cpp" "EU07.cpp" "export_e3d_standalone.cpp" "export_btf_standalone.cpp" @@ -164,7 +242,6 @@ set(SOURCES "rendering/nullrenderer.cpp" "rendering/renderer.cpp" "model/ResourceManager.cpp" -"scene/sn_utils.cpp" "world/Segment.cpp" "environment/sky.cpp" "environment/sun.cpp" @@ -185,6 +262,7 @@ set(SOURCES "input/drivermouseinput.cpp" "utilities/translation.cpp" "model/material.cpp" +"model/materialdata.cpp" "stdafx.cpp" "input/messaging.cpp" "scene/scene.cpp" @@ -206,6 +284,7 @@ set(SOURCES "rendering/screenshot.cpp" "input/driverkeyboardinput.cpp" "application/drivermode.cpp" +"application/consistviews.cpp" "application/driveruilayer.cpp" "application/driveruipanels.cpp" "input/editorkeyboardinput.cpp" @@ -213,6 +292,7 @@ set(SOURCES "editor/editorModelSets.cpp" "editor/editorTrackPresets.cpp" "editor/editorIncludeInfo.cpp" +"editor/editorSwitchDrives.cpp" "editor/editorTerrain.cpp" "editor/editorTrack.cpp" "editor/editorTrackTrace.cpp" @@ -277,6 +357,7 @@ set(SOURCES "application/editormodelineside.cpp" "application/editormodevehicle.cpp" "application/editormodeselection.cpp" +"application/editormodetracknames.cpp" "application/editormodeviewport.cpp" "application/editormodefields.cpp" "application/editormodeterrainchunks.cpp" @@ -314,6 +395,7 @@ set(SOURCES "utilities/dictionary.cpp" "rendering/particles.cpp" "utilities/headtrack.cpp" +"utilities/hardwareprobe.cpp" "rendering/geometrybank.cpp" "simulation/simulationsounds.cpp" "rendering/openglcamera.cpp" @@ -360,6 +442,7 @@ set(SOURCES "rendering/common/gpuparticles.cpp" "rendering/common/windscreenwater.cpp" "rendering/common/locallights.cpp" +"rendering/common/moths.cpp" "rendering/common/skylight.cpp" "rendering/common/weatherstate.cpp" "rendering/common/exposure.cpp" @@ -435,7 +518,8 @@ endif() if (WITH_LUA) set(DEFINITIONS ${DEFINITIONS} "WITH_LUA") - set(SOURCES ${SOURCES} "scripting/lua.cpp") + # the scenery scripts (lua.cpp) and the Lua screens (luaprogram.cpp) share the sandbox of luasandbox.cpp + set(SOURCES ${SOURCES} "scripting/lua.cpp" "scripting/luasandbox.cpp") endif() # the script screens (scripting/scriptscreens.cpp), with the Lua and the WebAssembly runtime when they're built @@ -708,30 +792,75 @@ add_library(eu07_settings INTERFACE) # the parts of the simulation the game shares with the unit tests: the vehicle physics, the vehicle # definition parser, the helpers they use and the rules of the test mode. built once, and tested as the game uses them set(CORE_SOURCES -"McZapkie/friction.cpp" -"McZapkie/hamulce.cpp" -"McZapkie/Mover.cpp" -"McZapkie/couplerphysics.cpp" -"McZapkie/Oerlikon_ESt.cpp" +"audio/startsample.cpp" +"physics/friction.cpp" +"physics/brakes.cpp" +"physics/vehiclecommand.cpp" +"physics/components/body.cpp" +"physics/components/drive.cpp" +"physics/components/cab.cpp" +"physics/components/collisions.cpp" +"physics/components/commands.cpp" +"physics/components/controllers.cpp" +"physics/components/couplers.cpp" +"physics/components/diesel.cpp" +"physics/components/doors.cpp" +"physics/components/electrics.cpp" +"physics/components/fizparser.cpp" +"physics/components/fizsections.cpp" +"physics/components/pneumatics.cpp" +"physics/components/securitysystem.cpp" +"physics/components/setup.cpp" +"physics/components/traction.cpp" +"physics/couplerphysics.cpp" +"physics/consistbraking.cpp" +"physics/derailment.cpp" +"physics/collision.cpp" +"vehicle/derailmotion.cpp" +"world/TrackCheck.cpp" +"world/SleeperPack.cpp" +"physics/oerlikonest.cpp" +"utilities/logfiles.cpp" "utilities/parser.cpp" "utilities/utilities.cpp" +"utilities/hardwareinfo.cpp" +"scene/sn_utils.cpp" +"scene/regionfile.cpp" +"utilities/inionlysettings.cpp" "utilities/crashsignals.cpp" "scripting/ladderlogic.cpp" "scripting/scriptscreenrules.cpp" "scripting/scriptscreenkernels.cpp" "scripting/scriptscreendrawing.cpp" "simulation/simulationtestrules.cpp" +"vehicle/aipower.cpp" +"vehicle/aiwire.cpp" "vehicle/blackbox.cpp" "utilities/physicslog.cpp" "vehicle/enginestart.cpp" "vehicle/brakesetting.cpp" +"vehicle/fieldshunting.cpp" +"vehicle/gaugewrap.cpp" +"vehicle/drivingaid.cpp" "vehicle/brakingcurve.cpp" +"vehicle/signalpassing.cpp" +"vehicle/brakereleaser.cpp" "vehicle/handover.cpp" "vehicle/uphillstart.cpp" +"vehicle/crew.cpp" +"vehicle/brakecharge.cpp" "vehicle/horn.cpp" +"vehicle/cameraviews.cpp" "vehicle/linebreaker.cpp" "vehicle/smoke.cpp" "vehicle/odometer.cpp" +"world/timetablestart.cpp" +"vehicle/timetableservice.cpp" +"world/timetableflags.cpp" +"world/timetablereader.cpp" +"world/stationnames.cpp" +"world/eventconditions.cpp" +"utilities/wholefile.cpp" ) add_library(eu07_core STATIC ${CORE_SOURCES}) target_link_libraries(eu07_core PUBLIC eu07_settings) @@ -753,7 +882,7 @@ if (WITH_VULKAN) add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different ${DLSS_RUNTIME_RELEASE} "$") endif() - if (DLSS_RUNTIME_DEVELOPMENT) + if (DLSS_DEVELOPMENT_LIBRARIES AND DLSS_RUNTIME_DEVELOPMENT) add_custom_command(TARGET ${PROJECT_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E make_directory "$/ngx_dev" COMMAND ${CMAKE_COMMAND} -E copy_if_different ${DLSS_RUNTIME_DEVELOPMENT} "$/ngx_dev") @@ -766,7 +895,6 @@ target_compile_definitions(eu07_settings INTERFACE ${DEFINITIONS}) target_include_directories(eu07_settings INTERFACE "." "Console" - "McZapkie" "gl" "${DEPS_DIR}/glad/include" "${DEPS_DIR}/dds-ktx/include" @@ -871,10 +999,14 @@ target_link_libraries(eu07_settings INTERFACE Threads::Threads) find_package(GLM REQUIRED) target_include_directories(eu07_settings INTERFACE ${GLM_INCLUDE_DIR}) -# JSON lib -add_subdirectory(ref/json) +# JSON lib: the ref/json submodule by default, or an installed package (e.g. nlohmann-json3-dev, vcpkg nlohmann-json). +# Both give the nlohmann_json::nlohmann_json target; 3.9 is the first release with ordered_json, used by the unit tests. +if (USE_SYSTEM_JSON) + find_package(nlohmann_json 3.9 REQUIRED) +else() + add_subdirectory(ref/json) +endif() target_link_libraries(eu07_settings INTERFACE nlohmann_json::nlohmann_json) -target_include_directories(eu07_settings INTERFACE ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR}) @@ -930,13 +1062,16 @@ if (WIN32) endif() # http client of the editor, for the orthophoto, the terrain model and the topo map of geoportal.gov.pl: WinHTTP on Windows, -# libcurl elsewhere when available +# libcurl elsewhere when available. libcurl isn't linked: only its headers are used, and editor/editorHttp.cpp loads the +# system's libcurl at run time (dlopen), so the game starts on a system without it and only the editor's downloads are off +# there. the package doesn't bundle it either (CMake_modules/bundle_runtime_libs.cmake) if (WIN32) target_link_libraries(eu07_settings INTERFACE winhttp) else() find_package(CURL QUIET) if (CURL_FOUND) - target_link_libraries(eu07_settings INTERFACE CURL::libcurl) + target_include_directories(eu07_settings INTERFACE $) + target_link_libraries(eu07_settings INTERFACE ${CMAKE_DL_LIBS}) target_compile_definitions(eu07_settings INTERFACE EU07_WITH_CURL) else() message(STATUS "libcurl not found: the editor's orthophoto and terrain model will only show what's cached, its topo map nothing") @@ -992,14 +1127,29 @@ if (UNIX AND NOT APPLE AND BUNDLE_RUNTIME_LIBS) endif() if(WIN32 AND WITH_PYTHON) + # the Python runtime next to the game, copied when it isn't there yet or the Python install changed, rather + # than after every link of the game: the library alone is thousands of files. the folder is the game's + # RUNTIME_OUTPUT_DIRECTORY, spelled out: $ here would make this target depend on the game + get_property(EU07_MULTI_CONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if (EU07_MULTI_CONFIG) + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin/$") + else() + set(EU07_PY_TARGET_DIR "${CMAKE_BINARY_DIR}/bin") + endif() + set(EU07_PY_STAMP "${EU07_PY_TARGET_DIR}/python64/python_runtime.stamp") add_custom_command( - TARGET ${PROJECT_NAME} POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "$" - COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "$" - # Lib with its site-packages is huge, the script copies it only when the Python install has changed - COMMAND ${CMAKE_COMMAND} "-DPY_LIBDIR=${EU07_PY_LIBDIR}" "-DPY_DLLSDIR=${EU07_PY_DLLSDIR}" "-DDEST_DIR=$" - -P "${CMAKE_CURRENT_SOURCE_DIR}/CMake_modules/CopyPythonRuntime.cmake" - ) + OUTPUT "${EU07_PY_STAMP}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_DLL}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${EU07_PY_ZLIB}" "${EU07_PY_TARGET_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_LIBDIR}" "${EU07_PY_TARGET_DIR}/python64/Lib" + COMMAND ${CMAKE_COMMAND} -E copy_directory_if_different "${EU07_PY_DLLSDIR}" "${EU07_PY_TARGET_DIR}/python64/DLLs" + COMMAND ${CMAKE_COMMAND} -E touch "${EU07_PY_STAMP}" + DEPENDS "${EU07_PY_DLL}" "${EU07_PY_ZLIB}" + COMMENT "Copying the Python runtime next to the game" + VERBATIM) + add_custom_target(eu07_python_runtime DEPENDS "${EU07_PY_STAMP}") + set_target_properties(eu07_python_runtime PROPERTIES FOLDER "libraries") + add_dependencies(${PROJECT_NAME} eu07_python_runtime) endif() # the Visual C++ runtime the simulator is built with, next to it: older runtimes installed in the system crash the programs of newer @@ -1021,7 +1171,11 @@ if (WITH_WASM) target_link_libraries(${PROJECT_NAME} eu07_wamr) endif () -# yaml-cpp, for the descriptions of scenery templates edited in the scenery editor and for the heightmap terrain +# yaml-cpp, for the descriptions of scenery templates edited in the scenery editor and for the heightmap terrain. a clone made before +# the submodule was added has it empty, or under an older url +if (NOT EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/ref/yaml-cpp/CMakeLists.txt") + message(FATAL_ERROR "the submodule ref/yaml-cpp is empty: git submodule sync && git submodule update --init --recursive") +endif() add_subdirectory("ref/yaml-cpp" "${CMAKE_CURRENT_BINARY_DIR}/yaml-cpp" EXCLUDE_FROM_ALL) target_link_libraries(eu07_settings INTERFACE yaml-cpp) diff --git a/CMake_modules/CopyPythonRuntime.cmake b/CMake_modules/CopyPythonRuntime.cmake deleted file mode 100644 index 04c412185..000000000 --- a/CMake_modules/CopyPythonRuntime.cmake +++ /dev/null @@ -1,39 +0,0 @@ -# Copies the Python runtime (Lib and DLLs) used by the embedded interpreter next to the executable. -# Run as a post-build step: cmake -DPY_LIBDIR=... -DPY_DLLSDIR=... -DDEST_DIR=... -P CopyPythonRuntime.cmake -# -# Lib also carries the site-packages of whichever Python install the build found, which can be tens of thousands -# of files. Copying them after every link took minutes, so the copy is skipped while the source install looks -# unchanged since the last copy. Delete /python64/.eu07_python_runtime to force a refresh. - -foreach(_var PY_LIBDIR PY_DLLSDIR DEST_DIR) - if(NOT DEFINED ${_var}) - message(FATAL_ERROR "CopyPythonRuntime.cmake: ${_var} is not set") - endif() -endforeach() - -# directory timestamps change when pip adds or removes a package, or the Python install itself is replaced -set(_stamp "") -foreach(_path "${PY_LIBDIR}" "${PY_LIBDIR}/site-packages" "${PY_DLLSDIR}") - file(TIMESTAMP "${_path}" _time "%Y-%m-%dT%H:%M:%S" UTC) - string(APPEND _stamp "${_path} ${_time}\n") -endforeach() - -set(_stamp_file "${DEST_DIR}/python64/.eu07_python_runtime") -set(_old_stamp "") -if(EXISTS "${_stamp_file}") - file(READ "${_stamp_file}" _old_stamp) -endif() - -if(NOT _old_stamp STREQUAL _stamp) - message(STATUS "Copying the Python runtime to ${DEST_DIR}/python64") - foreach(_pair "${PY_LIBDIR}|Lib" "${PY_DLLSDIR}|DLLs") - string(REPLACE "|" ";" _pair "${_pair}") - list(GET _pair 0 _source) - list(GET _pair 1 _target) - execute_process(COMMAND "${CMAKE_COMMAND}" -E copy_directory_if_different "${_source}" "${DEST_DIR}/python64/${_target}" RESULT_VARIABLE _result) - if(NOT _result EQUAL 0) - message(FATAL_ERROR "CopyPythonRuntime.cmake: copying ${_source} failed") - endif() - endforeach() - file(WRITE "${_stamp_file}" "${_stamp}") -endif() diff --git a/CMake_modules/bundle_runtime_libs.cmake b/CMake_modules/bundle_runtime_libs.cmake index a0f71543e..5b95c50e8 100644 --- a/CMake_modules/bundle_runtime_libs.cmake +++ b/CMake_modules/bundle_runtime_libs.cmake @@ -4,6 +4,12 @@ # the libraries of the system itself stay out: the C library and the loader, the GPU driver stack (libGL and its # kin come with the driver), X11 / Wayland, the sound servers, libstdc++ (the GPU drivers bring their own need of a # newer one) and a few more every distribution has. what a library left out depends on isn't bundled either +# +# libcurl and everything it pulls in (TLS, Kerberos, LDAP, HTTP/2, compression, name handling) stay out too: the +# build machine's copy knows the CA bundle path of the build machine's distribution (Debian), so shipped next to +# the game it breaks the certificate checks on Fedora or openSUSE, and the security updates of the TLS stack come +# from the user's system, not from our package. the game isn't linked with libcurl: the editor loads the system's one +# at run time (editor/editorHttp.cpp), and without it only the editor's downloads are off get_filename_component(game_folder "${GAME}" DIRECTORY) set(manifest "${game_folder}/bundled_libs.txt") @@ -43,7 +49,15 @@ set(system_libraries "^lib(asound|pulse|pulse-simple|jack|pipewire-[0-9.]+)\\.so" "^lib(udev|systemd|dbus-1)\\.so" "^libz\\.so" - "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so") + "^lib(fontconfig|freetype|harfbuzz|expat|uuid)\\.so" + "^libcurl" + "^lib(ssl|crypto)\\.so" + "^lib(gssapi_krb5|krb5|k5crypto|krb5support|com_err|keyutils)\\.so" + "^lib(ldap|lber|sasl2)" + "^lib(nghttp2|nghttp3|ngtcp2|rtmp|ssh2?|psl|idn2|unistring)\\.so" + "^libbrotli(dec|enc|common)\\.so" + "^libzstd\\.so" + "^lib(gnutls|hogweed|nettle|gmp|p11-kit|tasn1|ffi)\\.so") file(GET_RUNTIME_DEPENDENCIES EXECUTABLES "${GAME}" diff --git a/McZapkie/MOVER.h b/McZapkie/MOVER.h deleted file mode 100644 index d4730f617..000000000 --- a/McZapkie/MOVER.h +++ /dev/null @@ -1,2878 +0,0 @@ -/* -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 -//--------------------------------------------------------------------------- -// Q: 20160805 - odlaczenie pliku fizyki .pas od kompilacji -#include -#include -#include -#include "hamulce.h" -#include "couplerphysics.h" -#include "scripting/ladderlogic.h" -#include "vehicle/odometerreading.h" - -class cParser; -/* -MaSzyna EU07 locomotive simulator -Copyright (C) 2001-2004 Maciej Czapkiewicz and others - -*/ - -/* -(C) McZapkie v.2004.02 -Co brakuje: -6. brak pantografow itp 'Nie do konca, juz czesc zrobiona - Winger -7. brak efektu grzania oporow rozruchowych, silnika, osi -9. ulepszyc sprzeg sztywny oraz automatyczny -10. klopoty z EN57 -... -n. Inne lokomotywy oprocz elektrowozu pradu stalego -*/ -/* -Zrobione: -1. model szeregowego silnika elektrycznego sterowanego reostatem -2. fizyka ruchu - sily oporu, nachylenia, przyspieszenia styczne i normalne, -przyczepnosc/poslizg przy hamowaniu i rozruchu -3. docisk klockow hamulcowych -hamulec reczny oraz pomocniczy hamulec pneumatyczny -4. ubytki cisnienia wskutek hamowania, kompresor - ladowanie zbiornika -5. niektore uszkodzenia i awarie - logika rozmyta -a) silnik elektryczny - za duzy prad, napiecie, obroty -b) sprzegi - zerwanie gdy zbyt duze sily -6. flagi niektorych dzwiekow -7. hamulec zasadniczy - elektropneumatyczny (impulsowanie), pneumatyczny - zmiany cisnienia -zwiekszenie nacisku przy duzych predkosciach w hamulcach Oerlikona -8. sprzegi - sila, tlumiennosc -9. lok. el. - wylacznik glowny, odlacznik uszkodzonych silnikow -10. parametry trakcji -11. opoznienia w zalaczaniu stycznikow -12. trakcja wielokrotna -13. informacja na temat zrodla mocy dla silnikow trakcyjnych, ogrzewania, oswietlenia -14. dumb - uproszczony model lokomotywy (tylko dla AI) -15. ladunki - ilosc, typ, szybkosc na- i rozladunku, funkcje przetestowac! -16. ulepszony model fizyczny silnika elektrycznego (hamowanie silnikiem, ujemne napiecia) -17. poprawione hamulce - parametry cylindrow itp -18. ulepszone hamulce - napelnianie uderzeniowe, stopnie hamowania -19. poprawione hamulce - wyszczegolnenie cisnienia dla stopni hamowania -20. poprawione hamulce elektropneumatyczne -21. poprawione hamowanie przeciwposlizgowe i odluzniacz -22. dodany model mechanicznego napedu recznego (drezyna) -23. poprawiona szybkosc hamowania pomocniczego i przeciwposlizgowego, odlaczanie silnikow, odlaczanie bocznikow -24. wprowadzone systemy zabezpieczenia: SHP, Czuwak, sygnalizacja kabinowa (nie dzialaja w DebugMode). -25. poprawiona predkosc propagacji fali cisnienia (normalizacja przez kwadrat dlugosci) //to jest zdeka liniowe -26. uwzgledniona masa ladunku, przesuniecie w/m toru ruchu -27. lampy/sygnaly przednie/tylne -28. wprowadzona pozycja odciecia hamulca (yB: tja, ale oerlikona....) -29. rozne poprawki: slizganie, wykolejanie itp -30. model silnika spalinowego z przekladnia mechaniczna -31. otwieranie drzwi, sprezarka, przetwornica -32. wylaczanie obliczen dla nieruchomych wagonow -33. Zbudowany model rozdzielacza powietrza roznych systemow -34. Poprawiona pozycja napelniania uderzeniowego i hamulec EP -35. Dodane baterie akumulatorow (KURS90) -36. Hamowanie elektrodynamiczne w ET42 i poprawione w EP09 -37. jednokierunkowosc walu kulakowego w EZT (nie do konca) -38. wal kulakowy w ET40 -39. poprawiona blokada nastawnika w ET40 -... -*/ - - -/// Global counter incremented when a string-to-numeric conversion fails during config parsing. -extern int ConversionError; - -/// Static friction coefficient for steel-on-steel contact (used for adhesion at standstill). -const double Steel2Steel_friction = 0.15; // tarcie statyczne -/// Earth gravitational acceleration [m/s^2]. -const double g = 9.81; // przyspieszenie ziemskie -/// Sand consumption rate when sanding is active [kg/s]. -const double SandSpeed = 0.1; // ile kg/s} -/// 2*pi shortcut. -const double Pirazy2 = 6.2831853071794f; - -//-- var, const, procedure --------------------------------------------------- -/// Truthy alias used by CheckLocomotiveParameters() to ignore a check failure. -static bool const Go = true; -/// Falsy alias used by CheckLocomotiveParameters() to abort on a check failure. -static bool const Hold = false; /*dla CheckLocomotiveParameters*/ -/// Maximum number of resistor / scheme entries for electric motor traction. -static int const ResArraySize = 64; /*dla silnikow elektrycznych*/ -/// Maximum number of motor-parameter table entries (gear stages). -static int const MotorParametersArraySize = 10; -/// Maximum number of pantograph current collectors per vehicle. -static int const maxcc = 4; /*max. ilosc odbierakow pradu*/ -// static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca pomocniczego*/ -// static int const MainBrakeMaxPos = 10; /*max. ilosc nastaw hamulca zasadniczego*/ -/// Number of positions on the manual (parking) brake handle. -static int const ManualBrakePosNo = 20; /*ilosc nastaw hamulca recznego*/ -/// Number of positions on the lights selector switch. -static int const LightsSwitchPosNo = 16; -/// Maximum number of positions of the universal (auxiliary) controller. -static int const UniversalCtrlArraySize = 32; /*max liczba pozycji uniwersalnego nastawnika*/ - -/*uszkodzenia toru*/ -/// Track damage flag: rail wear. -static int const dtrack_railwear = 2; -/// Track damage flag: free / loose rail. -static int const dtrack_freerail = 4; -/// Track damage flag: thin (worn-out) rail. -static int const dtrack_thinrail = 8; -/// Track damage flag: bent rail. -static int const dtrack_railbend = 16; -/// Track damage flag: vegetation overgrowth. -static int const dtrack_plants = 32; -/// Track damage flag: track impassable for movement. -static int const dtrack_nomove = 64; -/// Track damage flag: rails missing entirely. -static int const dtrack_norail = 128; - -/*uszkodzenia taboru*/ -/// Vehicle damage flag: thin wheel (locomotives). -static int const dtrain_thinwheel = 1; /*dla lokomotyw*/ -/// Vehicle damage flag: shifted load (wagons). -static int const dtrain_loadshift = 1; /*dla wagonow*/ -/// Vehicle damage flag: wheel wear. -static int const dtrain_wheelwear = 2; -/// Vehicle damage flag: bearing failure. -static int const dtrain_bearing = 4; -/// Vehicle damage flag: coupling damage. -static int const dtrain_coupling = 8; -/// Vehicle damage flag: ventilator failure (electric locomotive). -static int const dtrain_ventilator = 16; /*dla lokomotywy el.*/ -/// Vehicle damage flag: load damage (wagons). -static int const dtrain_loaddamage = 16; /*dla wagonow*/ -/// Vehicle damage flag: engine failure (locomotives). -static int const dtrain_engine = 32; /*dla lokomotyw*/ -/// Vehicle damage flag: load destroyed (wagons). -static int const dtrain_loaddestroyed = 32; /*dla wagonow*/ -/// Vehicle damage flag: axle damage. -static int const dtrain_axle = 64; -/// Vehicle damage flag: derailment. -static int const dtrain_out = 128; /*wykolejenie*/ -/// Vehicle damage flag: broken pantograph. -static int const dtrain_pantograph = 256; /*polamanie pantografu*/ - -/// Reason for a derailment event. -enum DerailReason -{ - /// No derailment. - NONE = 0, - /// End of track reached. - END_OF_TRACK = 1, // Ra: powód wykolejenia: brak szyn - /// Speed too high for curve (overturn). - TOO_HIGH_SPEED = 2, // Ra: powód wykolejenia: przewrócony na łuku - /// Track gauge does not match wheelset gauge. - GAUGE_MISMATCH = 3, // Ra: powód wykolejenia: za szeroki tor - /// Track type incompatible with this vehicle. - WRONG_TRACK_TYPE = 4, // Ra: powód wykolejenia: nieodpowiednia trajektoria - /// Collision with another vehicle. - COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem - /// Trailing through a switch with a movable nose set the other way. - TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem -}; - -/*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ -/// Fuzzy-logic probability weight: electric engine general problem. -#define p_elengproblem (1e-02) -/// Fuzzy-logic probability weight: electric engine damage. -#define p_elengdamage (1e-01) -/// Fuzzy-logic probability weight: coupler damage. -#define p_coupldmg (2e-03) -/// Fuzzy-logic probability weight: derailment. -#define p_derail (1e-03) -/// Fuzzy-logic probability weight: acceleration-related event. -#define p_accn (1e-01) -/// Fuzzy-logic probability weight: damage caused by wheel slip. -#define p_slippdmg (1e-03) - -/*typ sprzegu*/ -/// Coupling type: virtual — vehicles share a track and are aware of each other. -static int const ctrain_virtual = 0; // gdy pojazdy na tym samym torze się widzą wzajemnie -/// Coupling type: physical coupler. -static int const ctrain_coupler = 1; // sprzeg fizyczny -/// Coupling type: pneumatic brake hose. -static int const ctrain_pneumatic = 2; // przewody hamulcowe -/// Coupling type: control cable (multiple-unit). -static int const ctrain_controll = 4; // przewody sterujące (ukrotnienie) -/// Coupling type: high-voltage power cable. -static int const ctrain_power = 8; // przewody zasilające (WN) -/// Coupling type: passenger gangway. -static int const ctrain_passenger = 16; // mostek przejściowy -/// Coupling type: secondary 8 atm pneumatic line (yellow, main air). -static int const ctrain_scndpneumatic = 32; // przewody 8 atm (żółte; zasilanie powietrzem) -/// Coupling type: high-voltage train heating cable. -static int const ctrain_heating = 64; // przewody ogrzewania WN -/// Coupling type: permanent (inter-section) — not separable during ordinary shunting; encoded as negative in config files. -static int const ctrain_depot = 128; // nie rozłączalny podczas zwykłych manewrów (międzyczłonowy), we wpisie wartość ujemna -/// Vehicle ends — front or rear (mutually exclusive). -enum end -{ - /// Front end. - front = 0, - /// Rear end. - rear = 1 -}; - -/// Vehicle sides — right or left (mutually exclusive). -enum side -{ - /// Right side. - right = 0, - /// Left side. - left = 1 -}; - -/// Bit flags representing the kind of physical/logical connections in a coupling. Combinable. -enum coupling -{ - /// No coupling (virtual / not connected). - faux = 0x0, - /// Mechanical coupler. - coupler = 0x1, - /// Pneumatic brake hose (PG). - brakehose = 0x2, - /// Control cable (multiple-unit). - control = 0x4, - /// High-voltage cable (traction supply). - highvoltage = 0x8, - /// Passenger gangway. - gangway = 0x10, - /// Main air (8 atm) line — secondary pneumatic supply. - mainhose = 0x20, - /// Train heating cable. - heating = 0x40, - /// Permanent (non-separable) coupling. - permanent = 0x80, - /// 24 V auxiliary power cable. - power24v = 0x100, - /// 110 V auxiliary power cable. - power110v = 0x200, - /// 3-phase 400 V auxiliary power cable. - power3x400v = 0x400, - // uic = 0x1000, -}; -/// Range of effect for a control command (mutually exclusive). -enum class range_t -{ - /// Affects only this vehicle. - local, - /// Affects this multiple-unit (vehicles permanently coupled into a unit). - unit, - /// Affects the entire consist. - consist -}; -/// State of the door closure signalling (SOD) of a vehicle or a consist, ordered from the least to the most -/// severe: the state of a consist is the most severe state of its vehicles. -enum class door_closure_t -{ - /// No doors worked by the crew: the vehicle doesn't take part in the signalling. - none, - /// All doors closed and locked: they can't be opened. - locked, - /// All doors closed, but released: a permit is given, or no lock holds them shut. - released, - /// A door is open, or not fully closed yet. - open -}; -/// Whether the door closure signalling lamp is lit: steadily for locked doors, in the lit phase of the -/// blinking for released ones, never with a door open or with no doors signalled. -bool door_closure_lamp(door_closure_t const State, bool const BlinkLit); -/// Possible settings for an enable/disable input pair (mutually exclusive). -enum class operation_t -{ - /// No input. - none = 0, - /// Enable input held active. - enable, - /// Disable input held active. - disable, - /// Enable button press transition (rising edge). - enable_on, - /// Enable button release transition. - enable_off, - /// Disable button press transition. - disable_on, - /// Disable button release transition. - disable_off, -}; -/// What else the line contactors of a vehicle need before they can close (LineContactorsInterlock in the Cntrl. section). -enum class line_contactors_interlock -{ - /// Nothing more, the legacy behaviour. - none, - /// The converter of the vehicle itself running, where it drives the traction motor fans (ET42). - converter, - /// The traction motor blowers of the vehicle running. - motor_blowers -}; -/// Auto-start method for ancillary devices (mutually exclusive). -enum class start_t -{ - /// Device cannot be started. - disabled, - /// Manual start only. - manual, - /// Starts automatically. - automatic, - /// Manual start with automatic fallback. - manualwithautofallback, - /// Driven by the converter state. - converter, - /// Driven by the battery state. - battery, - /// Driven by direction selector state. - direction -}; -/// Bit flags representing vehicle external lights (positions and types). Combinable. -enum light -{ - - /// Headlight, left. - headlight_left = 1 << 0, - /// Red marker, left. - redmarker_left = 1 << 1, - /// Headlight, upper centre. - headlight_upper = 1 << 2, - // TBD, TODO: redmarker_upper support? - /// Headlight, right. - headlight_right = 1 << 4, - /// Red marker, right. - redmarker_right = 1 << 5, - /// Rear-end markers (combined). - rearendsignals = 1 << 6, - /// Auxiliary light, left (e.g. ditch light). - auxiliary_left = 1 << 7, - /// Auxiliary light, right. - auxiliary_right = 1 << 8, - /// High-beam headlight, left. - highbeamlight_left = 1 << 9, - /// High-beam headlight, right. - highbeamlight_right = 1 << 10 -}; - -/// The cab interior light a position of the light preset selector sets (eu07/maszyna#529). -struct lights_preset_cablight -{ - /// Bits of the optional third column of a LightsList row. - enum flag - { - /// The cab light is on. - light_on = 1 << 0, - /// The cab light is dimmed. - light_dimmed = 1 << 1 - }; - bool light{false}; - bool dim{false}; -}; - -/// Door operation method (who controls them and how) — mutually exclusive. -enum control_t -{ - /// Local; passengers operate manually, doors open/close for the duration of loading. - passenger, // local, opened/closed for duration of loading - /// Remote; driver-operated. - driver, // remote, operated by the driver - /// Local autonomous; close when the vehicle moves and/or after a timeout. - autonomous, // local, closed when vehicle moves and/or after timeout - /// Remote; conductor-operated. - conductor, // remote, operated by the conductor - /// Primarily manual but also responds to remote control. - mixed // primary manual but answers also to remote control -}; -/*typ hamulca elektrodynamicznego*/ -/// Electrodynamic-brake type: no ED brake. -static int const dbrake_none = 0; -/// Electrodynamic-brake type: passive (always on while moving). -static int const dbrake_passive = 1; -/// Electrodynamic-brake type: switchable (driver toggles). -static int const dbrake_switch = 2; -/// Electrodynamic-brake type: reversal (engaged via reverser). -static int const dbrake_reversal = 4; -/// Electrodynamic-brake type: automatic (engages from main brake). -static int const dbrake_automatic = 8; - -/*dzwieki*/ -/// Bit flags identifying sound events emitted by a vehicle. Combinable. -enum sound -{ - /// No sound event. - none, - /// Generic "loud" event flag (e.g. impact / forced action). - loud = 1 << 0, - /// Coupler stretching to its limit. - couplerstretch = 1 << 1, - /// Buffer clash (vehicles colliding). - bufferclash = 1 << 2, - /// Contactor / relay clicking. - relay = 1 << 3, - /// Series-parallel switch operating. - parallel = 1 << 4, - /// Field-shunt contactor operating. - shuntfield = 1 << 5, - /// Generic pneumatic event. - pneumatic = 1 << 6, - /// Coupling detached. - detach = 1 << 7, - /// Mechanical coupler attached. - attachcoupler = 1 << 8, - /// Brake hose attached. - attachbrakehose = 1 << 9, - /// Main air hose attached. - attachmainhose = 1 << 10, - /// Control cable attached. - attachcontrol = 1 << 11, - /// Gangway attached. - attachgangway = 1 << 12, - /// Heating cable attached. - attachheating = 1 << 13, - /// Adapter piece attached to coupler. - attachadapter = 1 << 14, - /// Adapter piece removed from coupler. - removeadapter = 1 << 15, - /// Door-open permission signalling. - doorpermit = 1 << 16, -}; - -/// Bit flags for the customizable reset button — which protective relay it resets. Combinable. -enum relay_t -{ - /// Main circuit ground-fault relay. - maincircuitground = 1 << 0, - /// Auxiliary circuit ground-fault relay. - auxiliarycircuitground = 1 << 1, - /// Traction motor overload relay. - tractionnmotoroverload = 1 << 2, - /// Primary converter overload relay. - primaryconverteroverload = 1 << 3, - /// Secondary converter overload relay. - secondaryconverteroverload = 1 << 4, - /// Ventilator overload relay. - ventillatoroverload = 1 << 5, - /// Heating overload relay. - heatingoverload = 1 << 6, - /// Electrodynamic-brake overload relay. - electrodynamicbrakesoverload = 1 << 7, -}; - -/// Bit flags for actions triggered on cab activation / deactivation. Combinable. -enum activation -{ - /// Engage the emergency brake. - emergencybrake = 1 << 0, - /// Operate cab mirrors. - mirrors = 1 << 1, - /// Raise the pantographs. - pantographsup = 1 << 2, - /// Switch on red end-of-train markers. - redmarkers = 1 << 3, - /// Set door-open permit. - doorpermition = 1 << 4, - /// Engage the spring brake. - springbrakeon = 1 << 5, - /// Release the spring brake. - springbrakeoff = 1 << 6, - /// Place the reverser in neutral. - neutraldirection = 1 << 7, -}; - -// szczególne typy pojazdów (inna obsługa) dla zmiennej TrainType -// zamienione na flagi bitowe, aby szybko wybierać grupę (np. EZT+SZT) -// TODO: convert to enums, they're used as specific checks anyway -/// Vehicle type flag: default (no special handling). -static int const dt_Default = 0; -/// Vehicle type flag: EZT (electric multiple unit). -static int const dt_EZT = 1; -/// Vehicle type flag: ET41 locomotive. -static int const dt_ET41 = 2; -/// Vehicle type flag: ET42 locomotive. -static int const dt_ET42 = 4; -/// Vehicle type flag: pseudo-diesel (electric drivetrain with diesel input model). -static int const dt_PseudoDiesel = 8; -/// Vehicle type flag: ET22 locomotive (added in Megapack). -static int const dt_ET22 = 0x10; // używane od Megapacka -/// Vehicle type flag: SN61 (set from CHK only, not used in conditions). -static int const dt_SN61 = 0x20; // nie używane w warunkach, ale ustawiane z CHK -/// Vehicle type flag: EP05 locomotive. -static int const dt_EP05 = 0x40; -/// Vehicle type flag: ET40 locomotive. -static int const dt_ET40 = 0x80; -/// Vehicle type flag: ŠKODA 181 locomotive. -static int const dt_181 = 0x100; -/// Vehicle type flag: DMU (diesel multiple unit). -static int const dt_DMU = 0x200; - -// stałe dla asynchronów -/// EIM config index: dfic — frequency rise rate at start. -static int const eimc_s_dfic = 0; -/// EIM config index: dfmax — maximum frequency rate of change. -static int const eimc_s_dfmax = 1; -/// EIM config index: p — number of pole pairs. -static int const eimc_s_p = 2; -/// EIM config index: cfu — voltage / frequency conversion coefficient. -static int const eimc_s_cfu = 3; -/// EIM config index: cim — current / current conversion coefficient. -static int const eimc_s_cim = 4; -/// EIM config index: icif — magnetisation current ratio. -static int const eimc_s_icif = 5; -/// EIM config index: Uzmax — maximum DC link voltage. -static int const eimc_f_Uzmax = 7; -/// EIM config index: Uzh — DC link voltage at field-weakening transition. -static int const eimc_f_Uzh = 8; -/// EIM config index: DU — voltage drop at the converter. -static int const eimc_f_DU = 9; -/// EIM config index: I0 — no-load magnetising current. -static int const eimc_f_I0 = 10; -/// EIM config index: cfu — V/f gain in normal mode. -static int const eimc_f_cfu = 11; -/// EIM config index: cfuH — V/f gain in field-weakening region. -static int const eimc_f_cfuH = 12; -/// EIM config index: F0 — starting force at zero speed. -static int const eimc_p_F0 = 13; -/// EIM config index: a1 — force-frequency slope coefficient. -static int const eimc_p_a1 = 14; -/// EIM config index: Pmax — maximum power. -static int const eimc_p_Pmax = 15; -/// EIM config index: Fh — force at field-weakening point. -static int const eimc_p_Fh = 16; -/// EIM config index: Ph — power at field-weakening point. -static int const eimc_p_Ph = 17; -/// EIM config index: Vh0 — speed where field weakening begins. -static int const eimc_p_Vh0 = 18; -/// EIM config index: Vh1 — speed of full field weakening. -static int const eimc_p_Vh1 = 19; -/// EIM config index: Imax — maximum motor current. -static int const eimc_p_Imax = 20; -/// EIM config index: abed — anti-skid set point. -static int const eimc_p_abed = 21; -/// EIM config index: eped — EP brake intensity bias. -static int const eimc_p_eped = 22; - -// zmienne dla asynchronów -/// EIM variable index: FMAXMAX — absolute maximum allowable force. -static int const eimv_FMAXMAX = 0; -/// EIM variable index: Fmax — current force limit. -static int const eimv_Fmax = 1; -/// EIM variable index: ks — slip coefficient. -static int const eimv_ks = 2; -/// EIM variable index: df — frequency offset. -static int const eimv_df = 3; -/// EIM variable index: fp — base frequency. -static int const eimv_fp = 4; -/// EIM variable index: U — applied voltage. -static int const eimv_U = 5; -/// EIM variable index: pole — pole-pair indicator. -static int const eimv_pole = 6; -/// EIM variable index: Ic — control current. -static int const eimv_Ic = 7; -/// EIM variable index: If — field current. -static int const eimv_If = 8; -/// EIM variable index: M — torque. -static int const eimv_M = 9; -/// EIM variable index: Fr — actual force. -static int const eimv_Fr = 10; -/// EIM variable index: Ipoj — line current. -static int const eimv_Ipoj = 11; -/// EIM variable index: Pm — mechanical power. -static int const eimv_Pm = 12; -/// EIM variable index: Pe — electrical power. -static int const eimv_Pe = 13; -/// EIM variable index: eta — efficiency. -static int const eimv_eta = 14; -/// EIM variable index: fkr — critical frequency. -static int const eimv_fkr = 15; -/// EIM variable index: Uzsmax — maximum measured DC link voltage. -static int const eimv_Uzsmax = 16; -/// EIM variable index: Pmax — instantaneous power limit. -static int const eimv_Pmax = 17; -/// EIM variable index: Fzad — set-point force. -static int const eimv_Fzad = 18; -/// EIM variable index: Imax — maximum allowed current. -static int const eimv_Imax = 19; -/// EIM variable index: Fful — full force. -static int const eimv_Fful = 20; - -/// Brake-of-mode flag: PS (pneumatic, primary). -static int const bom_PS = 1; -/// Brake-of-mode flag: PN (pneumatic, no electrodynamic). -static int const bom_PN = 2; -/// Brake-of-mode flag: EP (electro-pneumatic). -static int const bom_EP = 4; -/// Brake-of-mode flag: MED (mixed pneumatic+ED). -static int const bom_MED = 8; - -/// Bit flags reporting vehicle problems that prevent driving. -enum TProblem // lista problemów taboru, które uniemożliwiają jazdę -{ // flagi bitowe - /// The vehicle has the brake applied or seized axles. - pr_Hamuje = 1, // pojazd ma załączony hamulec lub zatarte osie - /// The vehicle requires pantographs to be inflated/raised. - pr_Pantografy = 2, // pojazd wymaga napompowania pantografów - /// Reserved sentinel — last bit flag. - pr_Ostatni = 0x80000000 // ostatnia flaga bitowa -}; - -/// Compressor parameter list — indices into the compressor programmer table. -enum TCompressorList // lista parametrów w programatorze sprężarek -{ // pozycje kolejne - /// Compressor enable permission (0/1). - cl_Allow = 0, // zezwolenie na pracę sprężarek - /// Compressor output multiplier. - cl_SpeedFactor = 1, // mnożnik wydajności - /// Pressure-switch lower threshold multiplier. - cl_MinFactor = 2, // mnożnik progu załącznika ciśnieniowego - /// Pressure-switch upper threshold multiplier. - cl_MaxFactor = 3 // mnożnik progu wyłącznika ciśnieniowego -}; - -/// 3-D position in world coordinates [m]. -struct TLocation -{ - /// X coordinate. - double X; - /// Y coordinate (vertical). - double Y; - /// Z coordinate. - double Z; -}; - -/// Euler-angle rotation (radians) around X / Y / Z axes. -struct TRotation -{ - /// Rotation around X axis. - double Rx; - /// Rotation around Y axis. - double Ry; - /// Rotation around Z axis. - double Rz; -}; - -/// Vehicle bounding box (width × length × height [m]). -struct TDimension -{ - /// Width. - double W = 0.0; - /// Length. - double L = 0.0; - /// Height. - double H = 0.0; -}; - -/// A pending command queued for the vehicle, with its arguments and propagation rules. -struct TCommand -{ - /// Command name. - std::string Command; /*komenda*/ - /// First numeric argument. - double Value1 = 0.0; /*argumenty komendy*/ - /// Second numeric argument. - double Value2 = 0.0; - /// Coupling flag controlling how the command propagates between vehicles. - int Coupling{coupling::control}; // coupler flag used to determine command propagation - /// World-space location associated with the command. - TLocation Location; -}; - -/*tory*/ -/// Geometric shape of a track segment under the vehicle. -struct TTrackShape -{ /*ksztalt odcinka*/ - /// Curvature radius [m]; 0 means straight track. - double R = 0.0; // promien - /// Segment length [m]. - double Len = 0.0; // dlugosc - /// Track gradient (rise/run). - double dHtrack = 0.0; // nachylenie - /// Track cant / superelevation. - double dHrail = 0.0; // przechylka -}; - -/// Per-segment track parameters: gauge, friction, category, load capacity, damage. -struct TTrackParam -{ /*parametry odcinka - szerokosc, tarcie statyczne, kategoria, obciazalnosc w t/os, uszkodzenia*/ - /// Track gauge / width [m]. - double Width = 0.0; - /// Static friction coefficient on this segment. - double friction = 0.0; - /// Track category bit flags. - int CategoryFlag = 0; - /// Track-quality bit flags. - int QualityFlag = 0; - /// Track-damage bit flags (dtrack_*). - int DamageFlag = 0; - /// Maximum allowed velocity on this segment (used by AI driver). - double Velmax; /*dla uzytku maszynisty w ai_driver*/ -}; - -/// Traction-supply parameters at the vehicle's current location. -struct TTractionParam -{ - /// Catenary voltage [V]. - double TractionVoltage = 0.0; /*napiecie*/ - /// Catenary frequency [Hz] (0 for DC). - double TractionFreq = 0.0; /*czestotliwosc*/ - /// Maximum current capacity [A]. - double TractionMaxCurrent = 0.0; /*obciazalnosc*/ - /// Pantograph-catenary contact resistance [Ω]. - double TractionResistivity = 0.0; /*rezystancja styku*/ -}; -/*powyzsze parametry zwiazane sa z torem po ktorym aktualnie pojazd jedzie*/ - -// what a horn needs to sound: air from the main reservoir, or the low voltage -enum class horn_supply -{ - air, - electric -}; - -/// High-level brake-system family. -enum class TBrakeSystem -{ - /// Individual (vehicle-only) brake. - Individual, - /// Pneumatic brake (Westinghouse-style). - Pneumatic, - /// Electro-pneumatic brake. - ElectroPneumatic -}; -/// Brake-system subtype identifying the manufacturer's distributor family. -enum class TBrakeSubSystem -{ - ss_None, - ss_W, - ss_K, - ss_KK, - ss_Hik, - ss_ESt, - ss_KE, - ss_LSt, - ss_MT, - ss_Dako -}; -/// Specific brake-distributor (valve) model. -enum class TBrakeValve -{ - NoValve, - W, - W_Lu_VI, - W_Lu_L, - W_Lu_XR, - K, - Kg, - Kp, - Kss, - Kkg, - Kkp, - Kks, - Hikg1, - Hikss, - Hikp1, - KE, - SW, - EStED, - NESt3, - ESt3, - LSt, - ESt4, - ESt3AL2, - EP1, - EP2, - M483, - CV1_L_TR, - CV1, - CV1_R, - Other -}; -/// Specific driver's brake-handle model (cab valve). -enum class TBrakeHandle -{ - NoHandle, - West, - FV4a, - M394, - M254, - FVE408, - FVel6, - D2, - Knorr, - FD1, - BS2, - testH, - St113, - MHZ_P, - MHZ_T, - MHZ_EN57, - MHZ_K5P, - MHZ_K8P, - MHZ_6P -}; -/// Type of the auxiliary (independent) brake. -enum class TLocalBrake -{ - NoBrake, - ManualBrake, - PneumaticBrake, - HydraulicBrake -}; -/// Brake delay parameter table (apply/release for passenger and freight). -using TBrakeDelayTable = double[4]; - -/// One row of the brake pressure / pipe pressure / flow-speed table for a brake handle position. -struct TBrakePressure -{ - /// Brake pipe pressure target [bar]. - double PipePressureVal = 0.0; - /// Brake cylinder pressure target [bar]. - double BrakePressureVal = 0.0; - /// Flow speed (orifice scaling). - double FlowSpeedVal = 0.0; - /// Brake system this entry applies to. - TBrakeSystem BrakeType = TBrakeSystem::Pneumatic; -}; - -/// Brake pressure table indexed by handle position. -using TBrakePressureTable = std::map; - -/// Engine / drive type. -enum class TEngineType -{ - None, - Dumb, - WheelsDriven, - ElectricSeriesMotor, - ElectricInductionMotor, - DieselEngine, - SteamEngine, - DieselElectric, - Main -}; -/// Form of energy supplied by the power source. -enum class TPowerType -{ - NoPower, - BioPower, - MechPower, - ElectricPower, - SteamPower -}; -/// Fuel type for combustion engines. -enum class TFuelType -{ - Undefined, - Coal, - Oil -}; -/// Steam-locomotive grate parameters. -struct TGrateType -{ - /// Fuel type burned on this grate. - TFuelType FuelType; - /// Grate surface area [m²]. - double GrateSurface; - /// Fuel transport speed (stoker rate). - double FuelTransportSpeed; - /// Fuel ignition temperature [°C]. - double IgnitionTemperature; - /// Maximum allowable grate temperature [°C]. - double MaxTemperature; - // inline TGrateType() { - // FuelType = Undefined; - // GrateSurface = 0.0; - // FuelTransportSpeed = 0.0; - // IgnitionTemperature = 0.0; - // MaxTemperature = 0.0; - // } -}; -/// Steam-locomotive boiler parameters. -struct TBoilerType -{ - /// Boiler internal volume [m³]. - double BoilerVolume; - /// Heat exchange surface of the boiler [m²]. - double BoilerHeatSurface; - /// Superheater surface [m²]. - double SuperHeaterSurface; - /// Maximum water volume [m³]. - double MaxWaterVolume; - /// Minimum (safety) water volume [m³]. - double MinWaterVolume; - /// Maximum boiler pressure [bar]. - double MaxPressure; - // inline TBoilerType() { - // BoilerVolume = 0.0; - // BoilerHeatSurface = 0.0; - // SuperHeaterSurface = 0.0; - // MaxWaterVolume = 0.0; - // MinWaterVolume = 0.0; - // MaxPressure = 0.0; - // } -}; -/// Pantograph (current collector) model identifier. -enum TPantType -{ - /// AKP-4E pantograph (PKP single-arm). - AKP_4E, - /// DSA-series pantograph (Stemmann). - DSAx, - /// EC160/EC200 pantograph. - EC160_200, - /// WBL85 pantograph. - WBL85 -}; -/// Current-collector (pantograph) configuration block. -struct TCurrentCollector -{ - /// Number of pantographs of this type. - long CollectorsNo; // musi być tu, bo inaczej się kopie - /// Minimum pantograph height [m] (currently unused). - double MinH; - /// Maximum pantograph height [m] (currently unused). - double MaxH; - /// Working width of the contact strip [m]. - double CSW; // szerokość części roboczej (styku) ślizgacza - /// Minimum acceptable contact-line voltage [V]. - double MinV; - /// Maximum acceptable contact-line voltage [V]. - double MaxV; - /// True if an over-voltage protection relay is fitted. - bool OVP; // czy jest przekaznik nadnapieciowy - /// Minimum voltage required to engage the main switch [V]. - double InsetV; // minimalne napięcie wymagane do załączenia - /// Minimum air pressure required to operate [bar]. - double MinPress; // minimalne ciśnienie do załączenia WS - /// Maximum air pressure after the reductor [bar]. - double MaxPress; // maksymalne ciśnienie za reduktorem - /// True if power output is faked (e.g. for AI vehicles without a model). - bool FakePower; - /// Physical layout id (orientation / side). - int PhysicalLayout; - /// Pantograph type (model). - TPantType PantographType; - // inline TCurrentCollector() { - // CollectorsNo = 0; - // MinH, MaxH, CSW, MinV, MaxV = 0.0; - // OVP, InsetV, MinPress, MaxPress = 0.0; - // } -}; -/// Power-source kind (where the vehicle gets electrical or mechanical energy from). -enum class TPowerSource -{ - NotDefined, - InternalSource, - Transducer, - Generator, - Accumulator, - CurrentCollector, - PowerCable, - Heater, - Main -}; - -/// Diesel engine driven generator parameters and outputs. -struct engine_generator -{ - // ld inputs - /// Pointer to the prime-mover revolutions [rev/s]. - double *engine_revolutions; // revs per second of the prime mover - // config - /// Minimum working rev rate [rev/s]. - double revolutions_min; // min working revolutions rate, in revs per second - /// Maximum working rev rate [rev/s]. - double revolutions_max; // max working revolutions rate, in revs per second - /// Voltage generated at revolutions_min [V]. - double voltage_min; // voltage generated at min working revolutions - /// Voltage generated at revolutions_max [V]. - double voltage_max; // voltage generated at max working revolutions - // ld outputs - /// Current rev rate [rev/s]. - double revolutions; - /// Current generated voltage [V]. - double voltage; -}; - -/// Battery / accumulator power source. -struct TAccumulator -{ - /// Maximum capacity [Ah]. - double MaxCapacity; - /// Source used to recharge the battery. - TPowerSource RechargeSource; - // inline _mover__1() { - // MaxCapacity = 0.0; - // RechargeSource = NotDefined; - // } -}; - -/// Permanent power cable (e.g. to a heater) carrying a specific power form. -struct TPowerCable -{ - /// Type of power transmitted. - TPowerType PowerTrans; - /// Steam pressure (when SteamPower is transmitted) [bar]. - double SteamPressure; - // inline _mover__2() { - // SteamPressure = 0.0; - // PowerTrans = NoPower; - // } -}; - -/// Steam locomotive boiler-and-grate combo. -struct THeater -{ - /// Grate parameters. - TGrateType Grate; - /// Boiler parameters. - TBoilerType Boiler; -}; - -/// Transducer (DC-DC / converter) parameters. -struct TTransducer -{ - // ld inputs - /// Input voltage [V]. - double InputVoltage; -}; - -/// -/// Generic power-source parameters. The trailing union holds source-specific -/// configuration depending on SourceType. -/// -struct TPowerParameters -{ - /// Maximum source voltage [V]. - double MaxVoltage{0.0}; - /// Maximum source current [A]. - double MaxCurrent{0.0}; - /// Internal resistance [Ω]. - double IntR{0.001}; - /// Type of source (selects which union member is meaningful). - TPowerSource SourceType; - union - { - struct - { - THeater RHeater; - }; - struct - { - TPowerCable RPowerCable; - }; - struct - { - TCurrentCollector CollectorParameters; - }; - struct - { - TAccumulator RAccumulator; - }; - struct - { - engine_generator EngineGenerator; - }; - struct - { - TTransducer Transducer; - }; - struct - { - TPowerType PowerType; - }; - }; - inline TPowerParameters() - { - SourceType = TPowerSource::NotDefined; - PowerType = TPowerType::NoPower; - RPowerCable.PowerTrans = TPowerType::NoPower; - } -}; - -/*dla lokomotyw elektrycznych:*/ -struct TScheme -{ - int Relay = 0; /*numer pozycji rozruchu samoczynnego*/ - double R = 0.0; /*opornik rozruchowy*/ /*dla dizla napelnienie*/ - int Bn = 0; - int Mn = 0; /*ilosc galezi i silnikow w galezi*/ /*dla dizla Mn: czy luz czy nie*/ - bool AutoSwitch = false; /*czy dana pozycja nastawniana jest recznie czy autom.*/ - int ScndAct = 0; /*jesli ma bocznik w nastawniku, to ktory bocznik na ktorej pozycji*/ -}; -using TSchemeTable = TScheme[ResArraySize + 1]; /*tablica rezystorow rozr.*/ -struct TDEScheme -{ - double RPM = 0.0; /*obroty diesla*/ - double GenPower = 0.0; /*moc maksymalna*/ - double Umax = 0.0; /*napiecie maksymalne*/ - double Imax = 0.0; /*prad maksymalny*/ -}; -using TDESchemeTable = TDEScheme[33]; /*tablica WWList dla silnikow spalinowych*/ -struct TFFScheme -{ - double v = 0.0; // parametr wejsciowy - double freq = 0.0; // wyjscie: czestotliwosc falownika -}; -using TFFSchemeTable = TFFScheme[33]; - -struct TWiperScheme -{ - uint8_t byteSum = 0; // suma bitowa pracujacych wycieraczek - double WiperSpeed = 0.0; // predkosc wycieraczki - double interval = 0.0; // interwal pracy wycieraczki - double outBackDelay = 0.0; // czas po jakim wycieraczka zacznie wracac z konca do poczatku -}; -using TWiperSchemeTable = TWiperScheme[16]; - -struct TShuntScheme -{ - double Umin = 0.0; - double Umax = 0.0; - double Pmin = 0.0; - double Pmax = 0.0; -}; -using TShuntSchemeTable = TShuntScheme[33]; -struct TMPTRelay -{ /*lista przekaznikow bocznikowania*/ - double Iup = 0.0; - double Idown = 0.0; -}; -using TMPTRelayTable = TMPTRelay[MotorParametersArraySize + 1]; // indexed like MotorParam - -struct TMotorParameters -{ - double mfi{0.0}; - double mIsat{0.0}; - double mfi0{0.0}; // aproksymacja M(I) silnika} {dla dizla mIsat=przekladnia biegu - double fi{0.0}; - double Isat{0.0}; - double fi0{0.0}; // aproksymacja E(n)=fi*n} {dla dizla fi, mfi: predkosci przelozenia biegu <-> - bool AutoSwitch{false}; -}; - -struct TUniversalCtrl -{ - int mode = 0; /*tryb pracy zadajnika - pomocnicze*/ - double MinCtrlVal = 0.0; /*minimalna wartosc nastawy*/ - double MaxCtrlVal = 0.0; /*maksymalna wartosc nastawy*/ - double SetCtrlVal = 0.0; /*docelowa wartosc nastawy*/ - double SpeedUp = 0.0; /*szybkosc zwiekszania nastawy*/ - double SpeedDown = 0.0; /*szybkosc zmniejszania nastawy*/ - int ReturnPosition = 0; /*pozycja na ktora odskakuje zadajnik*/ - int NextPosFastInc = 0; /*nastepna duza pozycja przy przechodzeniu szybkim*/ - int PrevPosFastDec = 0; /*poprzednia duza pozycja przy przechodzeniu szybkim*/ -}; -using TUniversalCtrlTable = std::array; - -class TSecuritySystem -{ - bool vigilance_enabled = false; - bool cabsignal_enabled = false; - bool radiostop_enabled = false; - - bool cabsignal_active = false; - bool pressed = false; - bool enabled = false; - bool is_sifa = false; // Sifa-like pedal device, with inverted input for convenient keyboard usage - bool separate_acknowledge = false; // cabsignal reset button is separate from vigilance - bool cabsignal_lock = false; - bool vigilance_suspended = false; // the vigilance device switched off by the shunt mode of the vehicle, see AwareOffInShuntMode - - double vigilance_timer = 0.0; - double alert_timer = 0.0; - double press_timer = 0.0; - - double velocity = 0.0; - bool power = false; - int cabactive = 0; - - double AwareDelay = 30.0; - double AwareMinSpeed = 0.0; - double SoundSignalDelay = 5.0; - double EmergencyBrakeDelay = 5.0; - double MaxHoldTime = 1.5; - bool CabDependent = false; - bool AwareOffInShuntMode = false; // the shunt mode of the vehicle switches the vigilance device off, as on the SM42 - - public: - void set_enabled(bool e); - void acknowledge_press(); - void acknowledge_release(); - void cabsignal_reset(); - void update(double dt, double Vel, bool pwr, int cab); - void set_cabsignal(); - void set_cabsignal_lock(bool); - void set_shunt_mode(bool State); - bool is_blinking() const; - bool is_vigilance_blinking() const; - bool is_cabsignal_blinking() const; - bool is_beeping() const; - bool is_cabsignal_beeping() const; - bool is_braking() const; - bool is_engine_blocked() const; - bool radiostop_available() const; - bool has_separate_acknowledge() const; - void load(std::string const &line, double Vmax); - - double MagnetLocation = 0.0; -}; - -struct TTransmision -{ // liczba zebow przekladni - int NToothM = 0; - int NToothW = 0; - double Ratio = 1.0; - double Efficiency = 1.0; -}; - -enum class TCouplerType -{ - NoCoupler, - Articulated, - Bare, - Chain, - Screw, - Automatic -}; - -struct power_coupling -{ - double current{0.0}; - double voltage{0.0}; - bool is_local{false}; // whether the power comes from external or onboard source - bool is_live{false}; // whether the coupling with next vehicle is live -}; - -struct TCoupling -{ - /*parametry*/ - double SpringKB = 1.0; /*stala sprezystosci zderzaka/sprzegu, %tlumiennosci */ - double DmaxB = 0.1; /*tolerancja scisku/rozciagania, sila rozerwania*/ - double FmaxB = 1000.0; - double SpringKC = 1.0; - double DmaxC = 0.1; - double FmaxC = 1000.0; - double beta = 0.0; - TCouplerType CouplerType = TCouplerType::NoCoupler; /*typ sprzegu*/ - int AutomaticCouplingFlag = coupling::coupler; - int AllowedFlag = coupling::coupler | coupling::brakehose; // Ra: maska dostępnych - int PowerFlag = coupling::power110v | coupling::power24v; - int PowerCoupling = coupling::permanent; // type of coupling required for power transfer - /*zmienne*/ - bool AutomaticCouplingAllowed{true}; // whether automatic coupling can be currently performed - int CouplingFlag = 0; /*0 - wirtualnie, 1 - sprzegi, 2 - pneumatycznie, 4 - sterowanie, 8 - kabel mocy*/ - class TMoverParameters *Connected = nullptr; /*co jest podlaczone*/ - int ConnectedNr = 0; // Ra: od której strony podłączony do (Connected): 0=przód, 1=tył - double CForce = 0.0; /*sila z jaka dzialal*/ - double Dist = 0.0; /*strzalka ugiecia zderzaków*/ - bool CheckCollision = false; /*czy sprawdzac sile czy pedy*/ - float stretch_duration{0.f}; // seconds, elapsed time with excessive force applied to the coupler - bool broken{false}; // the coupler broke (damage_coupler()), until it's repaired (repair_coupler()) - // optional adapter piece - double adapter_length{0.0}; // meters, value added on the given end to standard vehicle (half)length - double adapter_height{0.0}; // meters, distance from rail level - TCouplerType adapter_type = TCouplerType::NoCoupler; // CouplerType override if other than NoCoupler - - power_coupling power_high; - power_coupling power_110v; - power_coupling power_24v; - - // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end, - // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end - coupler_physics::end_parameters physics; - coupler_physics::pair_state physics_state; - - int sounds{0}; // sounds emitted by the coupling devices - bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ - std::string control_type; // abstraction of control coupling interface and communication standard - - inline bool has_adapter() const - { - return adapter_type != TCouplerType::NoCoupler; - } - inline TCouplerType type() const - { - return adapter_type == TCouplerType::NoCoupler ? CouplerType : adapter_type; - } -}; - -class TDynamicObject; -struct neighbour_data -{ - TDynamicObject *vehicle{nullptr}; // detected obstacle - int vehicle_end{-1}; // facing end of the obstacle - float distance{10000.f}; // distance to the obstacle // NOTE: legacy value. TBD, TODO: use standard -1 instead? -}; - -struct speed_control -{ - bool IsActive = false; - bool Start = false; - bool ManualStateOverride = true; - bool BrakeIntervention = false; - bool BrakeInterventionBraking = false; - bool BrakeInterventionUnbraking = false; - bool Standby = false; - bool Parking = false; - double InitialPower = 1.0; - double FullPowerVelocity = -1; - double StartVelocity = -1; - double VelocityStep = 5; - double PowerStep = 0.1; - double MinPower = 0.0; - double MaxPower = 1.0; - double MinVelocity = 0; - double MaxVelocity = 120; - double DesiredVelocity = 0; - double DesiredPower = 1.0; - double Offset = -0.5; - double FactorPpos = 0.5; - double FactorPneg = 0.5; - double FactorIpos = 0.0; - double FactorIneg = 0.0; - double BrakeInterventionVel = 30.0; - double PowerUpSpeed = 1000; - double PowerDownSpeed = 1000; -}; - -struct inverter -{ - double Freal = 0.0; - double Request = 0.0; - bool IsActive = true; - bool Activate = true; - bool Error = false; - bool Failure_Drive = false; - bool Failure_Const = false; -}; - -class TMoverParameters -{ // Ra: wrapper na kod pascalowy, przejmujący jego funkcje Q: 20160824 - juz nie wrapper a klasa bazowa :) - private: - // types - /* TODO: implement - // communication cable, exchanging control signals with adjacent vehicle - struct jumper_cable { - // types - using flag_pair = std::pair; - // members - // booleans - // std::array flags {}; - // boolean pairs, exchanged data is swapped when connected to a matching end (front to front or back to back) - // TBD, TODO: convert to regular bool array for efficiency once it's working? - std::array flag_pairs {}; - // integers - // std::array values {}; - }; - */ - // basic approximation of a generic device - // TBD: inheritance or composition? - struct basic_device - { - // config - start_t start_type{start_t::manual}; - // ld inputs - bool is_enabled{false}; // device is allowed/requested to operate - bool is_disabled{false}; // device is requested to stop - // TODO: add remaining inputs; start conditions and potential breakers - // ld outputs - bool is_active{false}; // device is working - }; - - struct basic_light : public basic_device - { - // config - float dimming{1.0f}; // light strength multiplier - // ld outputs - float intensity{0.0f}; // current light strength - }; - - struct cooling_fan : public basic_device - { - // config - float speed{0.f}; // cooling fan rpm; either fraction of parent rpm, or absolute value if negative - float sustain_time{0.f}; // time of sustaining work of cooling fans after stop - float min_start_velocity{-1.f}; // minimal velocity of vehicle, when cooling fans activate - // ld outputs - float revolutions{0.f}; // current fan rpm - float stop_timer{0.f}; // current time, when shut off condition is active - }; - - // basic approximation of a fuel pump - struct fuel_pump : public basic_device - { - // TODO: fuel consumption, optional automatic engine start after activation - }; - - // basic approximation of an oil pump - struct oil_pump : public basic_device - { - // config - float pressure_minimum{0.f}; // lowest acceptable working pressure - float pressure_maximum{0.65f}; // oil pressure at maximum engine revolutions - // ld inputs - float resource_amount{1.f}; // amount of affected resource, compared to nominal value - // internal data - float pressure_target{0.f}; - // ld outputs - float pressure{0.f}; // current pressure - }; - - // basic approximation of a water pump - struct water_pump : public basic_device - { - // ld inputs - // TODO: move to breaker list in the basic device once implemented - bool breaker{false}; // device is allowed to operate - }; - - // basic approximation of a solenoid valve - struct basic_valve : basic_device - { - // config - bool solenoid{true}; // requires electric power to operate - bool spring{true}; // spring return or double acting actuator - }; - - // basic approximation of a pantograph - struct basic_pantograph - { - // ld inputs - basic_valve valve; // associated pneumatic valve - // ld outputs - bool is_active{false}; // device is working - bool sound_event{false}; // indicates last state which generated sound event - double voltage{0.0}; - }; - - // basic approximation of doors - struct basic_door - { - // config - // ld inputs - bool open_permit{false}; // door can be opened - bool local_open{false}; // local attempt to open the door - bool local_close{false}; // local attempt to close the door - bool remote_open{false}; // received remote signal to open the door - bool remote_close{false}; // received remote signal to close the door - // internal data - float auto_timer{-1.f}; // delay between activation of open state and closing state for automatic doors - float close_delay{0.f}; // delay between activation of closing state and actual closing - float open_delay{0.f}; // delay between activation of opening state and actual opening - float position{0.f}; // current shift of the door from the closed position - float step_position{0.f}; // current shift of the movable step from the retracted position - // ld outputs - bool is_closed{true}; // the door is fully closed - bool is_door_closed{true}; // the door is fully closed, step doesn't matter - bool is_closing{false}; // the door is currently closing - bool is_opening{false}; // the door is currently opening - bool is_open{false}; // the door is fully open - bool step_folding{false}; // the doorstep is currently closing - bool step_unfolding{false}; // the doorstep is currently opening - }; - - struct door_data - { - // config - control_t open_control{control_t::passenger}; - float open_rate{1.f}; - float open_delay{0.f}; - control_t close_control{control_t::passenger}; - float close_rate{1.f}; - float close_delay{0.f}; - int type{2}; - float range{0.f}; // extent of primary move/rotation - float range_out{0.f}; // extent of shift outward, applicable for plug doors - int step_type{2}; - float step_rate{0.5f}; - float step_range{0.f}; - bool has_lock{false}; - bool has_warning{false}; - bool has_autowarning{false}; - float auto_duration{-1.f}; // automatic door closure delay period - float auto_velocity{-1.f}; // automatic door closure velocity threshold - bool auto_include_remote{false}; // automatic door closure applies also to remote control - bool permit_needed{false}; - bool closure_signal{false}; // the door closure lamp (SOD) of the cab signals the doors of the whole consist in three states - std::vector permit_presets; // permit presets selectable with preset switch - float voltage{0.f}; // power type required for door movement - // ld inputs - bool lock_enabled{true}; - bool step_enabled{true}; - bool remote_only{false}; // door ignores local control signals - // internal data - int permit_preset{-1}; // curent position of preset selection switch - // vehicle parts - std::array instances; // door on the right and left side of the vehicle - // ld outputs - bool is_locked{false}; - double doorLockSpeed = 10.0; // predkosc przy ktorej wyzwalana jest blokada drzwi - }; - - struct water_heater - { - // config - struct heater_config_t - { - float temp_min{-1}; // lowest accepted temperature - float temp_max{-1}; // highest accepted temperature - }; - heater_config_t config; - // ld inputs - bool breaker{false}; // device is allowed to operate - bool is_enabled{false}; // device is requested to operate - // ld outputs - bool is_active{false}; // device is working - bool is_damaged{false}; // device is damaged - }; - - struct heat_data - { - // input, state of relevant devices - bool cooling{false}; // TODO: user controlled device, implement - // bool okienko { true }; // window in the engine compartment - // system configuration - bool auxiliary_water_circuit{false}; // cooling system has an extra water circuit - double fan_speed{0.075}; // cooling fan rpm; either fraction of engine rpm, or absolute value if negative - // heat exchange factors - double kw{0.35}; - double kv{0.6}; - double kfe{1.0}; - double kfs{80.0}; - double kfo{25.0}; - double kfo2{25.0}; - // system parts - struct fluid_circuit_t - { - - struct circuit_config_t - { - float temp_min{-1}; // lowest accepted temperature - float temp_max{-1}; // highest accepted temperature - float temp_cooling{-1}; // active cooling activation point - float temp_flow{-1}; // fluid flow activation point - bool shutters{false}; // the radiator has shutters to assist the cooling - }; - circuit_config_t config; - bool is_cold{false}; // fluid is too cold - bool is_warm{false}; // fluid is too hot - bool is_hot{false}; // fluid temperature crossed cooling threshold - bool is_flowing{false}; // fluid is being pushed through the circuit - }; - fluid_circuit_t water; - fluid_circuit_t water_aux; - fluid_circuit_t oil; - fluid_circuit_t engine; - // output, state of affected devices - bool PA{false}; // malfunction flag - float rpmw{0.0}; // current main circuit fan revolutions - float rpmwz{0.0}; // desired main circuit fan revolutions - bool zaluzje1{false}; - float rpmw2{0.0}; // current auxiliary circuit fan revolutions - float rpmwz2{0.0}; // desired auxiliary circuit fan revolutions - bool zaluzje2{false}; - // output, temperatures - float Te{15.0}; // ambient temperature TODO: get it from environment data - // NOTE: by default the engine is initialized in warm, startup-ready state - float Ts{50.0}; // engine temperature - float To{45.0}; // oil temperature - float Tsr{50.0}; // main circuit radiator temperature (?) - float Twy{50.0}; // main circuit water temperature - float Tsr2{40.0}; // secondary circuit radiator temperature (?) - float Twy2{40.0}; // secondary circuit water temperature - float temperatura1{50.0}; - float temperatura2{40.0}; - float powerfactor{1.0}; // coefficient of heat generation for engines other than su45 - // engine overheat threshold - float engine_max_temp{-1}; // maximum acceptable engine temperature, triggers overheat lamp when exceeded - bool engine_is_hot{false}; // engine temperature crossed cooling threshold - }; - - struct spring_brake - { - std::shared_ptr Cylinder; - bool Activate{false}; // Input: switching brake on/off in exploitation - main valve/switch - bool ShuttOff{true}; // Input: shutting brake off during failure - valve in pneumatic container - bool Release{false}; // Input: emergency releasing rod - - bool IsReady{false}; // Output: readyness to braking - cylinder is armed, spring is tentioned - bool IsActive{false}; // Output: brake is working - double SBP{0.0}; // Output: pressure in spring brake cylinder - - bool PNBrakeConnection{false}; // Conf: connection to pneumatic brake cylinders - double MaxSetPressure{0.0}; // Conf: Maximal pressure for switched off brake - double ResetPressure{0.0}; // Conf: Pressure for arming brake cylinder - double MinForcePressure{0.1}; // Conf: Minimal pressure for zero force - double MaxBrakeForce{0.0}; // Conf: Maximal tension for brake pads/shoes - double PressureOn{-2.0}; // Conf: Pressure changing ActiveFlag to "On" - double PressureOff{-1.0}; // Conf: Pressure changing ActiveFlag to "Off" - double ValveOffArea{0.0}; // Conf: Area of filling valve - double ValveOnArea{0.0}; // Conf: Area of dumping valve - double ValvePNBrakeArea{0.0}; // Conf: Area of bypass to brake cylinders - - int MultiTractionCoupler{127}; // Conf: Coupling flag necessary for transmitting the command - }; - - public: - std::string chkPath; - bool reload_FIZ(); - double dMoveLen = 0.0; - /*---opis lokomotywy, wagonu itp*/ - /*--opis serii--*/ - int CategoryFlag = 1; /*1 - pociag, 2 - samochod, 4 - statek, 8 - samolot*/ - /*--sekcja stalych typowych parametrow*/ - std::string TypeName; /*nazwa serii/typu*/ - int TrainType = 0; /*typ: EZT/elektrowoz - Winger 040304 Ra: powinno być szybciej niż string*/ - TEngineType EngineType = TEngineType::None; /*typ napedu*/ - TPowerParameters EnginePowerSource; /*zrodlo mocy dla silnikow*/ - TPowerParameters SystemPowerSource; /*zrodlo mocy dla systemow sterowania/przetwornic/sprezarek*/ - TPowerParameters HeatingPowerSource; /*zrodlo mocy dla ogrzewania*/ - TPowerParameters AlterHeatPowerSource; /*alternatywne zrodlo mocy dla ogrzewania*/ - TPowerParameters LightPowerSource; /*zrodlo mocy dla oswietlenia*/ - TPowerParameters AlterLightPowerSource; /*alternatywne mocy dla oswietlenia*/ - double Vmax = -1.0; - double Mass = 0.0; - double Power = 0.0; /*max. predkosc kontrukcyjna, masa wlasna, moc*/ - double Mred = 0.0; /*Ra: zredukowane masy wirujące; potrzebne do obliczeń hamowania*/ - double TotalMass = 0.0; /*wyliczane przez ComputeMass*/ - double HeatingPower = 0.0; - double EngineHeatingRPM{0.0}; // guaranteed engine revolutions with heating enabled - double LightPower = 0.0; /*moc pobierana na ogrzewanie/oswietlenie*/ - double BatteryVoltage = 0.0; /*Winger - baterie w elektrykach*/ - bool Battery = false; /*Czy sa zalaczone baterie*/ - start_t BatteryStart = start_t::manual; - bool EpFuse = true; /*Czy jest wlaczony hamulec EP*/ - double EpForce = 0.0; /*Poziom zadanej sily EP*/ - bool Signalling = false; /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/ - bool Radio = false; /*Czy jest zalaczony radiotelefon*/ - // the cut-off in the radio's power supply: a fuse in the cabinet, a lever on the desk or the switch on the radio's power - // supply (eu07/maszyna#438). Closed unless the driver opens it, so vehicles without such a switch work as before - bool RadioFuse = true; - float NominalBatteryVoltage = 0.f; /*Winger - baterie w elektrykach*/ - TDimension Dim; /*wymiary*/ - double Cx = 0.0; /*wsp. op. aerodyn.*/ - float Floor = 0.96f; // poziom podłogi dla ładunków - float WheelDiameter = 1.f; /*srednica kol napednych*/ - float WheelDiameterL = 0.9f; // Ra: srednica kol tocznych przednich - float WheelDiameterT = 0.9f; // Ra: srednica kol tocznych tylnych - float TrackW = 1.435f; /*nominalna szerokosc toru [m]*/ - double AxleInertialMoment = 0.0; /*moment bezwladnosci zestawu kolowego*/ - std::string AxleArangement; /*uklad osi np. Bo'Bo' albo 1'C*/ - int NPoweredAxles = 0; /*ilosc osi napednych liczona z powyzszego*/ - int NAxles = 0; /*ilosc wszystkich osi j.w.*/ - int BearingType = 1; /*lozyska: 0 - slizgowe, 1 - toczne*/ - double ADist = 0.0; - double BDist = 0.0; /*odlegosc osi oraz czopow skretu*/ - /*hamulce:*/ - int NBpA = 0; /*ilosc el. ciernych na os: 0 1 2 lub 4*/ - int SandCapacity = 0; /*zasobnik piasku [kg]*/ - TBrakeSystem BrakeSystem = TBrakeSystem::Individual; /*rodzaj hamulca zespolonego*/ - TBrakeSubSystem BrakeSubsystem = TBrakeSubSystem::ss_None; - TBrakeValve BrakeValve = TBrakeValve::NoValve; - TBrakeHandle BrakeHandle = TBrakeHandle::NoHandle; - TBrakeHandle BrakeLocHandle = TBrakeHandle::NoHandle; - bool LocHandleTimeTraxx = false; /*hamulec dodatkowy typu traxx*/ - double MBPM = 1.0; /*masa najwiekszego cisnienia*/ - - int wiperSwitchPos = 0; // pozycja przelacznika wycieraczek - double WiperAngle = {45.0}; // kat pracy wycieraczek - - std::shared_ptr Hamulec; - std::shared_ptr Handle; - std::shared_ptr LocHandle; - std::shared_ptr Pipe; - std::shared_ptr Pipe2; - spring_brake SpringBrake; - - TLocalBrake LocalBrake = TLocalBrake::NoBrake; /*rodzaj hamulca indywidualnego*/ - TBrakePressureTable BrakePressureTable; /*wyszczegolnienie cisnien w rurze*/ - TBrakePressure BrakePressureActual; // wartości ważone dla aktualnej pozycji kranu - int ASBType = 0; /*0: brak hamulca przeciwposlizgowego, 1: reczny, 2: automat*/ - int UniversalBrakeButtonFlag[3] = {0, 0, 0}; /* mozliwe działania przycisków hamulcowych */ - int UniversalResetButtonFlag[3] = {0, 0, 0}; // customizable reset buttons assignments - int TurboTest = 0; - bool batterySwAlreadyFired = false; // czy przycisk baterii juz zostal wcisniety - bool isBatteryButtonImpulse = false; // czy przelacznik baterii traktowac jako pojedynczy przycisk - bool shouldHoldBatteryButton = false; // czy nalezy przytrzymac przycisk baterii aby wlaczyc/wylaczyc baterie - float BatteryButtonHoldTime = 1.f; // minimalny czas przytrzymania przycisku baterii - double MaxBrakeForce = 0.0; /*maksymalna sila nacisku hamulca*/ - double MaxBrakePress[5]; // pomocniczy, proz, sred, lad, pp - double P2FTrans = 0.0; - double TrackBrakeForce = 0.0; /*sila nacisku hamulca szynowego*/ - int BrakeMethod = 0; /*flaga rodzaju hamulca*/ - bool Handle_AutomaticOverload = false; // automatyczna asymilacja na pozycji napelniania - bool Handle_ManualOverload = false; // reczna asymilacja na guzik - double Handle_GenericDoubleParameter1 = 0.0; - double Handle_GenericDoubleParameter2 = 0.0; - double Handle_OverloadMaxPressure = 1.0; // maksymalne zwiekszenie cisnienia przy asymilacji - double Handle_OverloadPressureDecrease = 0.002; // predkosc spadku cisnienia przy asymilacji - /*max. cisnienie w cyl. ham., stala proporcjonalnosci p-K*/ - double HighPipePress = 0.0; - double LowPipePress = 0.0; - double DeltaPipePress = 0.0; - /*max. i min. robocze cisnienie w przewodzie glownym oraz roznica miedzy nimi*/ - double CntrlPipePress = 0.0; // ciśnienie z zbiorniku sterującym - double BrakeVolume = 0.0; - double BrakeVVolume = 0.0; - double VeselVolume = 0.0; - /*pojemnosc powietrza w ukladzie hamulcowym, w ukladzie glownej sprezarki [m^3] */ - int BrakeCylNo = 0; /*ilosc cylindrow ham.*/ - double BrakeCylRadius = 0.0; - double BrakeCylDist = 0.0; - double BrakeCylMult[3]; - int LoadFlag = 0; - /*promien cylindra, skok cylindra, przekladnia hamulcowa*/ - double BrakeCylSpring = 0.0; /*suma nacisku sprezyn powrotnych, kN*/ - double BrakeSlckAdj = 0.0; /*opor nastawiacza skoku tloka, kN*/ - double BrakeRigEff = 0.0; /*sprawnosc przekladni dzwigniowej*/ - double RapidMult = 1.0; /*przelozenie rapidu*/ - double RapidVel = 55.0; /*szybkosc przelaczania rapidu*/ - int BrakeValveSize = 0; - std::string BrakeValveParams; - double Spg = 0.0; - double MinCompressor = 0.0; - double MaxCompressor = 0.0; - double MinCompressor_cabA = 0.0; - double MaxCompressor_cabA = 0.0; - double MinCompressor_cabB = 0.0; - double MaxCompressor_cabB = 0.0; - bool CabDependentCompressor = false; - double CompressorSpeed = 0.0; - int CompressorList[4][9]; // pozycje świateł, przód - tył, 1 .. 16 - double EmergencyValveOn = 0.0; - double EmergencyValveOff = 0.0; - bool EmergencyValveOpen = false; - double EmergencyValveArea = 0.0; - double LockPipeOn = -1.0; - double LockPipeOff = -1.0; - double HandleUnlock = -3.0; - bool EmergencyCutsOffHandle = false; - int CompressorListPosNo = 0; - int CompressorListDefPos = 1; - bool CompressorListWrap = false; - /*cisnienie wlaczania, zalaczania sprezarki, wydajnosc sprezarki*/ - TBrakeDelayTable BrakeDelay; /*opoznienie hamowania/odhamowania t/o*/ - double AirLeakRate{0.01}; // base rate of air leak from brake system components ( 0.001 = 1 l/sec ) - int BrakeCtrlPosNo = 0; /*ilosc pozycji hamulca*/ - /*nastawniki:*/ - int MainCtrlPosNo = 0; /*ilosc pozycji nastawnika*/ - int ScndCtrlPosNo = 0; - int LightsPosNo = 0; - int LightsDefPos = 1; - bool LightsWrap = false; - int Lights[2][18]; // pozycje świateł, przód - tył, 1 .. 16 (17 do lightsset) - // the cab interior light each light preset sets, from the optional third column of LightsList (bits of - // lights_preset_cablight::flag); -1: the preset leaves the cab light as it is (eu07/maszyna#529) - std::array LightsCabLight{[] { - std::array positions; - positions.fill(-1); - return positions; - }()}; - int ScndInMain{0}; /*zaleznosc bocznika od nastawnika*/ - bool MBrake = false; /*Czy jest hamulec reczny*/ - double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego - double StopBrakeDecc = 0.0; - bool ReleaseParkingBySpringBrake{false}; - bool ReleaseParkingBySpringBrakeWhenDoorIsOpen{false}; - bool SpringBrakeCutsOffDrive{true}; - double SpringBrakeDriveEmergencyVel{-1}; - bool HideDirStatusWhenMoving{false}; // Czy gasic lampki kierunku powyzej predkosci zdefiniowanej przez HideDirStatusSpeed - int HideDirStatusSpeed{1}; // Predkosc od ktorej lampki kierunku sa wylaczane - bool isDoubleClickForMeasureNeeded = {false}; // czy rozpoczecie pomiaru odleglosci odbywa sie po podwojnym wcisnienciu przycisku? - float DistanceCounterDoublePressPeriod = {1.f}; // czas w jakim nalezy podwojnie wcisnac przycisk, aby rozpoczac pomiar odleglosci - TSecuritySystem SecuritySystem; - int EmergencyBrakeWarningSignal{0}; // combined with basic WarningSignal when manual emergency brake is active - horn_supply HornSupply{horn_supply::air}; // of the low and high tone horns (WarningSignal 1 and 2) - horn_supply Horn3Supply{horn_supply::air}; // of the third horn (WarningSignal 4) - // main reservoir pressure [bar, as MinCP and MaxCP] below which a pneumatic horn stays silent - static constexpr double HornMinPressure{2.0}; - TUniversalCtrlTable UniCtrlList; /*lista pozycji uniwersalnego nastawnika*/ - int UniCtrlListSize = 0; /*wielkosc listy pozycji uniwersalnego nastawnika*/ - bool UniCtrlIntegratedBrakePNCtrl = false; /*zintegrowany nastawnik JH obsluguje hamulec PN*/ - bool UniCtrlIntegratedBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie*/ - bool UniCtrlIntegratedLocalBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie hamulcem pomocniczym*/ - int UniCtrlNoPowerPos{0}; // cached highesr position not generating traction force - // UCList CtrlValStep: the universal controller (EIMCtrlType 3) changes its setting in steps of this size (e.g. 0.05 for the - // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown - // covers a step; 0 (the default) changes it continuously - double UniCtrlValStep{0.0}; - std::pair> PantsPreset{"0132", {0, 0}}; // pantograph preset switches; .first holds possible setups as chars, .second holds currently selected preset in each cab - - /*-sekcja parametrow dla lokomotywy elektrycznej*/ - TSchemeTable RList; /*lista rezystorow rozruchowych i polaczen silnikow, dla dizla: napelnienia*/ - int RlistSize = 0; - TMotorParameters MotorParam[MotorParametersArraySize + 1]; - /*rozne parametry silnika przy bocznikowaniach*/ - /*dla lokomotywy spalinowej z przekladnia mechaniczna: przelozenia biegow*/ - // bounds-safe read access to MotorParam - TMotorParameters const &motor_param(int const Position) const - { - if (Position < 0) - return MotorParam[0]; - if (Position > MotorParametersArraySize) - return MotorParam[MotorParametersArraySize]; - return MotorParam[Position]; - } - TTransmision Transmision; - // record {liczba zebow przekladni} - // NToothM, NToothW : byte; - // Ratio: real; {NToothW/NToothM} - // end; - double NominalVoltage = 0.0; /*nominalne napiecie silnika*/ - double WindingRes = 0.0; - double u = 0.0; // wspolczynnik tarcia yB wywalic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - double CircuitRes = 0.0; /*rezystancje silnika i obwodu*/ - int IminLo = 0; - int IminHi = 0; /*prady przelacznika automatycznego rozruchu, uzywane tez przez ai_driver*/ - int ImaxLo = 0; // maksymalny prad niskiego rozruchu - int ImaxHi = 0; // maksymalny prad wysokiego rozruchu - bool MotorOverloadRelayHighThreshold{false}; - double nmax = 0.0; /*maksymalna dop. ilosc obrotow /s*/ - double InitialCtrlDelay = 0.0; - double CtrlDelay = 0.0; /* -//- -//- miedzy kolejnymi poz.*/ - double CtrlDownDelay = 0.0; /* -//- -//- przy schodzeniu z poz.*/ /*hunter-101012*/ - int FastSerialCircuit = 0; /*0 - po kolei zamyka styczniki az do osiagniecia szeregowej, 1 - natychmiastowe wejscie na szeregowa*/ /*hunter-111012*/ - int BackwardsBranchesAllowed = 1; - int AutoRelayType = 0; /*0 -brak, 1 - jest, 2 - opcja*/ - bool CoupledCtrl = false; /*czy mainctrl i scndctrl sa sprzezone*/ - bool HasCamshaft{false}; - int DynamicBrakeType = 0; /*patrz dbrake_**/ - int DynamicBrakeAmpmeters = 2; /*liczba amperomierzy przy hamowaniu ED*/ - bool SplitEDPneumaticBrake = false; /*czy hamulec ED i pneumatyczny pomocniczy są rozdzielone na osobne nastawniki*/ - int DynamicBrakeCtrlPosNo = 10; /*ilosc pozycji nastawnika hamulca ED (DBPN, domyslnie 10)*/ - double DynamicBrakeRes = 5.8; /*rezystancja oporników przy hamowaniu ED*/ - double DynamicBrakeRes1 = 5.8; /*rezystancja oporników przy hamowaniu ED - 1 tryb*/ - double DynamicBrakeRes2 = 5.8; /*rezystancja oporników przy hamowaniu ED - 2 tryb*/ - double TUHEX_Sum = 750; /*nastawa sterownika hamowania ED - aktualna*/ - double TUHEX_Diff = 10; /*histereza działania sterownika hamowania ED*/ - double TUHEX_MinIw = 60; /*minimalny prąd wzbudzenia przy hamowaniu ED - wynika z chk silnika*/ - double TUHEX_MaxIw = 400; /*maksymalny prąd wzbudzenia przy hamowaniu ED - ograniczenie max siły*/ - double TUHEX_Sum1 = 750; /*nastawa1 sterownika hamowania ED*/ - double TUHEX_Sum2 = 750; /*nastawa2 sterownika hamowania ED*/ - double TUHEX_Sum3 = 750; /*nastawa3 sterownika hamowania ED*/ - int TUHEX_Stages = 0; /*liczba stopni hamowania ED*/ - // TODO: wrap resistor fans variables and state into a device - int RVentType = 0; /*0 - brak, 1 - jest, 2 - automatycznie wlaczany*/ - double RVentnmax = 1.0; /*maks. obroty wentylatorow oporow rozruchowych*/ - double RVentCutOff = 0.0; /*rezystancja wylaczania wentylatorow dla RVentType=2*/ - double RVentSpeed{0.5}; // rozpedzanie sie wentylatora obr/s^2} - double RVentMinI{50.0}; // przy jakim pradzie sie wylaczaja} - bool RVentForceOn{false}; // forced activation switch - int CompressorPower = 1; // 0: main circuit, 1: z przetwornicy, reczne, 2: w przetwornicy, stale, 3: diesel engine, 4: converter of unit in front, 5: converter of unit behind - int SmallCompressorPower = 0; /*Winger ZROBIC*/ - bool Trafo = false; /*pojazd wyposażony w transformator*/ - - /*-sekcja parametrow dla lokomotywy spalinowej z przekladnia mechaniczna*/ - double dizel_Mmax = 1.0; - double dizel_nMmax = 1.0; - double dizel_Mnmax = 2.0; - double dizel_nmax = 2.0; - double dizel_nominalfill = 0.0; - std::map dizel_Momentum_Table; - std::map dizel_vel2nmax_Table; - /*parametry aproksymacji silnika spalinowego*/ - double dizel_Mstand = 0.0; /*moment oporow ruchu silnika dla enrot=0*/ - /* dizel_auto_min, dizel_auto_max: real; {predkosc obrotowa przelaczania automatycznej skrzyni biegow*/ - double dizel_nmax_cutoff = 0.0; /*predkosc obrotowa zadzialania ogranicznika predkosci*/ - double dizel_nmin = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa*/ - double dizel_nmin_hdrive = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa w czasie jazdy na hydro */ - double dizel_nmin_hdrive_factor = 0.0; /*wspolczynnik wzrostu obrotow minimalnych hydro zaleznosci od zadanego procentu*/ - double dizel_nmin_retarder = 0.0; /*obroty pracy podczas hamowania retarderem*/ - double dizel_nreg_acc = 999.0; /*tempo zwiększania prędkości przez regulator dizla */ - double dizel_minVelfullengage = 0.0; /*najmniejsza predkosc przy jezdzie ze sprzeglem bez poslizgu*/ - double dizel_maxVelANS = 3.0; /*predkosc progowa rozlaczenia przetwornika momentu*/ - double dizel_AIM = 1.0; /*moment bezwladnosci walu itp*/ - double dizel_RevolutionsDecreaseRate{2.0}; - double dizel_NominalFuelConsumptionRate = 250.0; /*jednostkowe zużycie paliwa przy mocy nominalnej, wczytywane z fiz, g/kWh*/ - double dizel_FuelConsumption = 0.0; /*współczynnik zużycia paliwa przeliczony do jednostek maszynowych, l/obrót*/ - double dizel_FuelConsumptionActual = 0.0; /*chwilowe spalanie paliwa w l/h*/ - double dizel_FuelConsumptedTotal = 0.0; /*ilość paliwa zużyta od początku symulacji, l*/ - double dizel_engageDia = 0.5; - double dizel_engageMaxForce = 6000.0; - double dizel_engagefriction = 0.5; /*parametry sprzegla*/ - double engagedownspeed = 0.9; - double engageupspeed = 0.5; - /*parametry przetwornika momentu*/ - bool hydro_TC = false; /*obecnosc hydraulicznego przetwornika momentu*/ - double hydro_TC_TMMax = 2.0; /*maksymalne wzmocnienie momentu*/ - double hydro_TC_CouplingPoint = 0.85; /*wzgledna predkosc zasprzeglenia*/ - double hydro_TC_LockupTorque = 3000.0; /*moment graniczny sprzegla blokujacego*/ - double hydro_TC_LockupRate = 1.0; /*szybkosc zalaczania sprzegla blokujacego*/ - double hydro_TC_UnlockRate = 1.0; /*szybkosc rozlaczania sprzegla blokujacego*/ - double hydro_TC_FillRateInc = 1.0; /*szybkosc napelniania sprzegla*/ - double hydro_TC_FillRateDec = 1.0; /*szybkosc oprozniania sprzegla*/ - double hydro_TC_TorqueInIn = 4.5; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ - double hydro_TC_TorqueInOut = 0.0; /*stala momentu proporcjonalnego do roznica obrotow wejsciowych i wyjsciowych*/ - double hydro_TC_TorqueOutOut = 0.0; /*stala momentu proporcjonalnego do kwadratu obrotow wyjsciowych*/ - double hydro_TC_LockupSpeed = 1.0; /*prog predkosci zalaczania sprzegla blokujacego*/ - double hydro_TC_UnlockSpeed = 1.0; /*prog predkosci rozlaczania sprzegla blokujacego*/ - std::map hydro_TC_Table; /*tablica przetwornika momentu*/ - /*parametry retardera*/ - bool hydro_R = false; /*obecnosc retardera*/ - int hydro_R_Placement = 0; /*umiejscowienie retardera: 0 - za skrzynia biegow, 1 - miedzy przetwornikiem a biegami, 2 - przed skrzynia biegow */ - double hydro_R_TorqueInIn = 1.0; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ - double hydro_R_MaxTorque = 1.0; /*maksymalny moment retardera*/ - double hydro_R_MaxPower = 1.0; /*maksymalna moc retardera - ogranicza moment*/ - double hydro_R_FillRateInc = 1.0; /*szybkosc napelniania sprzegla*/ - double hydro_R_FillRateDec = 1.0; /*szybkosc oprozniania sprzegla*/ - double hydro_R_MinVel = 1.0; /*minimalna predkosc, przy ktorej retarder dziala*/ - double hydro_R_EngageVel = 1.0; /*minimalna predkosc hamowania, przy ktorej sprzeglo jest wciaz wlaczone*/ - bool hydro_R_Clutch = false; /*czy retarder ma rozłączalne sprzęgło*/ - double hydro_R_ClutchSpeed = 10.0; /*szybkość narastania obrotów po włączeniu sprzęgła retardera*/ - bool hydro_R_WithIndividual = false; /*czy dla autobusów jest to łączone*/ - /*- dla lokomotyw spalinowo-elektrycznych -*/ - double AnPos = 0.0; // pozycja sterowania dokladnego (analogowego) - bool AnalogCtrl = false; // - bool AnMainCtrl = false; // - bool ShuntModeAllow = false; - bool ShuntMode = false; - - bool Flat = false; - double Vhyp = 1.0; - TDESchemeTable DElist; - TFFSchemeTable FFlist; - int FFListSize = 0; - TFFSchemeTable FFEDlist; - int FFEDListSize = 0; - TWiperSchemeTable WiperList; - int WiperListSize; - int WiperDefaultPos{0}; - int modernWpierListSize; - - double Vadd = 1.0; - TMPTRelayTable MPTRelay; - int RelayType = 0; - TShuntSchemeTable SST; - double PowerCorRatio = 1.0; // Wspolczynnik korekcyjny - /*- dla uproszczonego modelu silnika (dumb) oraz dla drezyny*/ - double Ftmax = 0.0; - /*- dla lokomotyw z silnikami indukcyjnymi -*/ - double eimc[26]; - bool EIMCLogForce = false; // - static std::vector const eimc_labels; - double InverterFrequency{0.0}; // current frequency of power inverters - int InvertersNo = 0; // number of inverters - double InvertersRatio = 0.0; - std::vector Inverters; // all inverters - int InverterControlCouplerFlag = 4; // which coupling flag is necessary to controll inverters - int Imaxrpc = 0; // Maksymalny prad rezystora hamowania chlodzonego pasywnie - int BRVto = 0; // Czas jaki wentylatory jeszcze dodatkowo schladzaja rezystor - double BRVtimer = 0; // Timer dla podtrzymania wentylatora - std::map EIM_Pmax_Table; /*tablica mocy maksymalnej od predkosci*/ - /* -dla pojazdów z blendingiem EP/ED (MED) */ - double MED_Vmax = 0; // predkosc maksymalna dla obliczen chwilowej sily hamowania EP w MED - double MED_Vmin = 0; // predkosc minimalna dla obliczen chwilowej sily hamowania EP w MED - double MED_Vref = 0; // predkosc referencyjna dla obliczen dostepnej sily hamowania EP w MED - double MED_amax{9.81}; // maksymalne opoznienie hamowania sluzbowego MED - bool MED_EPVC = false; // czy korekcja sily hamowania EP, gdy nie ma dostepnego ED - double MED_EPVC_Time = 7; // czas korekcji sily hamowania EP, gdy nie ma dostepnego ED - bool MED_Ncor = false; // czy korekcja sily hamowania z uwzglednieniem nacisku - double MED_MinBrakeReqED = 0; // minimalne zadanie sily hamowania uruchamiajace ED - ponizej tylko EP - double MED_FrED_factor = 1; // mnoznik sily hamowania ED do korekty blendingu - double MED_ED_Delay1 = 0; // opoznienie wdrazania hamowania ED (pierwszy raz) - double MED_ED_Delay2 = 0; // opoznienie zwiekszania sily hamowania ED (kolejne razy) - - int DCEMUED_CC{0}; // na którym sprzęgu sprawdzać działanie ED - double DCEMUED_EP_max_Vel{0.0}; // maksymalna prędkość, przy której działa EP przy włączonym ED w jednostce (dla tocznych) - double DCEMUED_EP_min_Im{0.0}; // minimalny prąd, przy którym EP nie działa przy włączonym ED w członie (dla silnikowych) - double DCEMUED_EP_delay{0.0}; // opóźnienie włączenia hamulca EP przy hamowaniu ED - zwłoka wstępna - - /*-dla wagonow*/ - struct load_attributes - { - std::string name; // name of the cargo - float offset_min{0.f}; // offset applied to cargo model when load amount is 0 - - load_attributes() = default; - load_attributes(std::string const &Name, float const Offsetmin) : name(Name), offset_min(Offsetmin) {} - }; - std::vector LoadAttributes; - float MaxLoad = 0.f; /*masa w T lub ilosc w sztukach - ladownosc*/ - double OverLoadFactor = 0.0; /*ile razy moze byc przekroczona ladownosc*/ - float LoadSpeed = 0.f; - float UnLoadSpeed = 0.f; /*szybkosc na- i rozladunku jednostki/s*/ -#ifdef EU07_USEOLDDOORCODE - int DoorOpenCtrl = 0; - int DoorCloseCtrl = 0; /*0: przez pasazera, 1: przez maszyniste, 2: samoczynne (zamykanie)*/ - double DoorStayOpen = 0.0; /*jak dlugo otwarte w przypadku DoorCloseCtrl=2*/ - bool DoorClosureWarning = false; /*czy jest ostrzeganie przed zamknieciem*/ - bool DoorClosureWarningAuto = false; // departure signal plays automatically while door closing button is held down - double DoorOpenSpeed = 1.0; - double DoorCloseSpeed = 1.0; /*predkosc otwierania i zamykania w j.u. */ - double DoorMaxShiftL = 0.5; - double DoorMaxShiftR = 0.5; - double DoorMaxPlugShift = 0.1; /*szerokosc otwarcia lub kat*/ - int DoorOpenMethod = 2; /*sposob otwarcia - 1: przesuwne, 2: obrotowe, 3: trójelementowe*/ - float DoorCloseDelay{0.f}; // delay (in seconds) before the door begin closing, once conditions to close are met - double PlatformSpeed = 0.5; /*szybkosc stopnia*/ - double PlatformMaxShift{0.0}; /*wysuniecie stopnia*/ - int PlatformOpenMethod{2}; /*sposob animacji stopnia*/ -#endif - double MirrorMaxShift{90.0}; - double MirrorVelClose{5.0}; - bool MirrorForbidden{false}; /*czy jest pozwolenie na otworzenie lusterek (przycisk)*/ - bool ScndS = false; /*Czy jest bocznikowanie na szeregowej*/ - bool ScndCtrlResistiveLock{false}; // the shunt controller can't be moved, up or down, while the master controller is at zero or on a resistive position, and drops to 0 when the master controller gets there (ScndCtrlResistiveLock=Yes in Cntrl.) - bool SpeedCtrl = false; /*czy jest tempomat*/ - speed_control SpeedCtrlUnit; /*parametry tempomatu*/ - double SpeedCtrlButtons[10]{30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; /*przyciski prędkości*/ - double SpeedCtrlDelay = 2; /*opoznienie dzialania tempomatu z wybieralna predkoscia*/ - double SpeedCtrlValue = 0; /*wybrana predkosc jazdy na tempomacie*/ - /*--sekcja zmiennych*/ - /*--opis konkretnego egzemplarza taboru*/ - TLocation Loc{0.0, 0.0, 0.0}; // pozycja pojazdów do wyznaczenia odległości pomiędzy sprzęgami - TRotation Rot{0.0, 0.0, 0.0}; - glm::vec3 Front{}; - std::string Name; /*nazwa wlasna*/ - TCoupling Couplers[2]; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami - // the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on - // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered - bool CouplerPhysics{false}; - std::array Neighbours; // potential collision sources - bool Power110vIsAvailable = false; // cached availability of 110v power - bool Power24vIsAvailable = false; // cached availability of 110v power - double Power24vVoltage{0.0}; // cached battery voltage - bool EventFlag = false; /*!o true jesli cos nietypowego sie wydarzy*/ - int SoundFlag = 0; /*!o patrz stale sound_ */ - int AIFlag{0}; // HACK: events of interest for consist owner - double DistCounter = 0.0; /*! licznik kilometrow */ - odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) - std::pair EnergyMeter; // energy from grid [kWh] - double V = 0.0; // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) - double Vel = 0.0; // moduł prędkości w [km/h], używany przez AI - double AccS = 0.0; // efektywne przyspieszenie styczne w [m/s^2] (wszystkie siły) - double AccSVBased{}; // tangential acceleration calculated from velocity change - double AccN = 0.0; // przyspieszenie normalne w [m/s^2] - double AccVert = 0.0; // vertical acceleration - double nrot = 0.0; // predkosc obrotowa kol (obrotow na sekunde) - double nrot_eps = 0.0; // przyspieszenie kątowe kół (bez kierunku) - double WheelFlat = 0.0; - bool TruckHunting{true}; // enable/disable truck hunting calculation - /*! rotacja kol [obr/s]*/ - double EnginePower = 0.0; /*! chwilowa moc silnikow*/ - double dL = 0.0; - double Fb = 0.0; - double Ff = 0.0; /*przesuniecie, sila hamowania i tarcia*/ - double FTrain = 0.0; - double FStand = 0.0; /*! sila pociagowa i oporow ruchu*/ - double FTotal = 0.0; /*! calkowita sila dzialajaca na pojazd*/ - double UnitBrakeForce = 0.0; /*!s siła hamowania przypadająca na jeden element*/ - double Ntotal = 0.0; /*!s siła nacisku klockow*/ - bool SlippingWheels = false; - bool SandDose = false; /*! poslizg kol, sypanie piasku*/ - bool SandDoseManual = false; /*piaskowanie reczne*/ - bool SandDoseAuto = false; /*piaskowanie automatyczne*/ - bool SandDoseAutoAllow = true; /*zezwolenie na automatyczne piaskowanie*/ - double Sand = 0.0; /*ilosc piasku*/ - double BrakeSlippingTimer = 0.0; /*pomocnicza zmienna do wylaczania przeciwposlizgu*/ - double dpBrake = 0.0; - double dpPipe = 0.0; - double dpMainValve = 0.0; - double dpLocalValve = 0.0; - double EmergencyValveFlow = 0.0; // air flow through alerter valve during last simulation step - /*! przyrosty cisnienia w kroku czasowym*/ - double ScndPipePress = 0.0; /*cisnienie w przewodzie zasilajacym*/ - double BrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych*/ - double LocBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z pomocniczego*/ - double PipeBrakePress = 0.0; /*!o cisnienie w cylindrach hamulcowych z przewodu*/ - double PipePress = 0.0; /*!o cisnienie w przewodzie glownym*/ - double EqvtPipePress = 0.0; /*!o cisnienie w przewodzie glownym skladu*/ - double Volume = 0.0; /*objetosc spr. powietrza w zbiorniku hamulca*/ - double CompressedVolume = 0.0; /*objetosc spr. powietrza w ukl. zasilania*/ - double PantVolume = 0.48; /*objetosc spr. powietrza w ukl. pantografu*/ // aby podniesione pantografy opadły w krótkim czasie przy wyłączonej sprężarce - double Compressor = 0.0; /*! cisnienie w ukladzie zasilajacym*/ - bool CompressorFlag = false; /*!o czy wlaczona sprezarka*/ - bool PantCompFlag = false; /*!o czy wlaczona sprezarka pantografow*/ - bool CompressorAllow = false; /*! zezwolenie na uruchomienie sprezarki NBMX*/ - bool CompressorAllowLocal{true}; // local device state override (most units don't have this fitted so it's set to true not to intefere) - bool CompressorGovernorLock{false}; // indicates whether compressor pressure switch was activated due to reaching cut-out pressure - double CompressorStartDelay{0.0}; // time [s] the compressor waits after getting its power before it can start, after the engine starts say - double CompressorPowerTime{0.0}; // time [s] since the compressor got its power - bool CompressorTankValve{false}; // indicates excessive pressure is vented from compressor tank directly and instantly - start_t CompressorStart{start_t::manual}; // whether the compressor is started manually, or another way - start_t PantographCompressorStart{start_t::manual}; - basic_valve PantsValve; - std::array Pantographs; - bool PantAllDown{false}; - double PantFrontVolt = 0.0; // pantograf pod napieciem? 'Winger 160404 - double PantRearVolt = 0.0; - // TODO converter parameters, for when we start cleaning up mover parameters - start_t ConverterStart{start_t::manual}; // whether converter is started manually, or by other means - float ConverterStartDelay{0.0f}; // delay (in seconds) before the converter is started, once its activation conditions are met - double ConverterStartDelayTimer{0.0}; // helper, for tracking whether converter start delay passed - bool ConverterAllow = false; /*zezwolenie na prace przetwornicy NBMX*/ - bool ConverterAllowLocal{true}; // local device state override (most units don't have this fitted so it's set to true not to intefere) - bool ConverterFlag = false; /*! czy wlaczona przetwornica NBMX*/ - bool BRVentilators = false; /* Czy rezystor hamowania pracuje */ - start_t ConverterOverloadRelayStart{start_t::manual}; // whether overload relay reset responds to dedicated button - bool ConverterOverloadRelayOffWhenMainIsOff{false}; - fuel_pump FuelPump; - oil_pump OilPump; - water_pump WaterPump; - water_heater WaterHeater; - bool WaterCircuitsLink{false}; // optional connection between water circuits - heat_data dizel_heat; - std::array MotorBlowers; - door_data Doors; - float DoorsOpenWithPermitAfter{-1.f}; // remote open if permit button is held for specified time. NOTE: separate from door data as its cab control thing - int DoorsPermitLightBlinking{0}; // when the doors permit signal light is blinking - - int BrakeCtrlPos = -2; /*nastawa hamulca zespolonego*/ - double BrakeCtrlPosR = 0.0; /*nastawa hamulca zespolonego - plynna dla FV4a*/ - double BrakeCtrlPos2 = 0.0; /*nastawa hamulca zespolonego - kapturek dla FV4a*/ - int ManualBrakePos = 0; /*nastawa hamulca recznego*/ - double LocalBrakePosA = 0.0; /*nastawa hamulca pomocniczego*/ - double LocalBrakePosAEIM = 0.0; /*pozycja hamulca pomocniczego ep dla asynchronicznych ezt*/ - double DynamicBrakeCtrlPos = 0.0; /*nastawa nastawnika hamulca elektrodynamicznego (0..1) - aktywne tylko gdy SplitEDPneumaticBrake*/ - bool UniversalBrakeButtonActive[3] = {false, false, false}; /* brake button pressed */ - /* - int BrakeStatus = b_off; //0 - odham, 1 - ham., 2 - uszk., 4 - odluzniacz, 8 - antyposlizg, 16 - uzyte EP, 32 - pozycja R, 64 - powrot z R - */ - bool AlarmChainFlag = false; // manual emergency brake - bool RadioStopFlag = false; /*hamowanie nagle*/ - bool LockPipe = false; /*locking brake pipe in emergency state*/ - bool UnlockPipe = false; /*unlockig brake pipe button pressed*/ - int BrakeDelayFlag = 0; /*nastawa opoznienia ham. osob/towar/posp/exp 0/1/2/4*/ - int BrakeDelays = 0; /*nastawy mozliwe do uzyskania*/ - // the AI wagon inspector cut the brake out (b_dmg) and puts it back when the train no longer needs it - // cut out (brake_setting::apply). Anyone else cutting it out or putting it back takes it over - bool BrakeCutOutByInspector = false; - int BrakeOpModeFlag = 0; /*nastawa trybu pracy PS/PN/EP/MED 1/2/4/8*/ - int BrakeOpModes = 0; /*nastawy mozliwe do uzyskania*/ - bool DynamicBrakeFlag = false; /*czy wlaczony hamulec elektrodymiczny*/ - bool DynamicBrakeEMUStatus = true; /*czy hamulec ED dziala w ezt*/ - int TUHEX_StageActual = 0; /*aktualny stopien tuhexa*/ - bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ - bool TUHEX_Active = false; /*czy hamowanie ED wywołane z zewnątrz*/ - // NapUdWsp: integer; - double LimPipePress = 0.0; /*stabilizator cisnienia*/ - double ActFlowSpeed = 0.0; /*szybkosc stabilizatora*/ - - int DamageFlag = 0; // kombinacja bitowa stalych dtrain_* } - int EngDmgFlag = 0; // kombinacja bitowa stalych usterek} - - // EndSignalsFlag: byte; {ABu 060205: zmiany - koncowki: 1/16 - swiatla prz/tyl, 2/31 - blachy prz/tyl} - // HeadSignalsFlag: byte; {ABu 060205: zmiany - swiatla: 1/2/4 - przod, 16/32/63 - tyl} - TCommand CommandIn; - /*komenda przekazywana przez PutCommand*/ - /*i wykonywana przez RunInternalCommand*/ - std::string CommandOut; /*komenda przekazywana przez ExternalCommand*/ - std::string CommandLast; // Ra: ostatnio wykonana komenda do podglądu - double ValueOut = 0.0; /*argument komendy która ma byc przekazana na zewnatrz*/ - - TTrackShape RunningShape; /*geometria toru po ktorym jedzie pojazd*/ - TTrackParam RunningTrack; /*parametry toru po ktorym jedzie pojazd*/ - double OffsetTrackH = 0.0; - double OffsetTrackV = 0.0; /*przesuniecie poz. i pion. w/m osi toru*/ - - /*-zmienne dla lokomotyw*/ - bool Mains = false; /*polozenie glownego wylacznika*/ - double MainsInitTime{0.0}; // config, initialization time (in seconds) of the main circuit after it receives power, before it can be closed - double MainsInitTimeCountdown{0.0}; // current state of main circuit initialization, remaining time (in seconds) until it's ready - start_t MainsStart{start_t::manual}; - // config, Engine:JointEngineStart. whether the cab's line breaker / engine start switch works the vehicles in multiple - // too; when it doesn't, the cab has separate switches for them (mainb_*, mainc_*) - bool JointEngineStart{true}; - // config, .fiz Cntrl.PantRequiresMain: the line breaker closes without traction voltage and holds without it, and the - // pantographs rise and stay up only while it's closed (EU05, EP05, ČD 181 family); off, the pantographs come first and the line - // breaker needs their voltage. what the main circuit feeds still needs the voltage (MainCircuitPowered()), and without - // it the undervoltage relay opens the line contactors (NoVoltRelay) - bool PantographsRequireMains{false}; - bool LineBreakerClosesOnlyAtNoPowerPos{false}; - bool ControlPressureSwitch{false}; // activates if the main pipe and/or brake cylinder pressure aren't within operational levels - bool HasControlPressureSwitch{true}; - bool ReleaserEnabledOnlyAtNoPowerPos{false}; - int MainCtrlPos = 0; /*polozenie glownego nastawnika*/ - int ScndCtrlPos = 0; /*polozenie dodatkowego nastawnika*/ - int LightsPos = 0; /*polozenie przelacznika wielopozycyjnego swiatel*/ - int CompressorListPos = 0; /*polozenie przelacznika wielopozycyjnego sprezarek*/ - int DirActive = 0; // czy lok. jest wlaczona i w ktorym kierunku: względem wybranej kabiny: -1 - do tylu, +1 - do przodu, 0 - wylaczona - int DirAbsolute = 0; // zadany kierunek jazdy względem sprzęgów (1=w strone 0,-1=w stronę 1) - int MainCtrlMaxDirChangePos{0}; // can't change reverser state with master controller set above this position - int CabActive = 0; // numer kabiny, z której jest sterowanie: 1 lub -1; w przeciwnym razie brak sterowania - rozrzad - int CabOccupied = 0; // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController - bool CabMaster = false; // czy pojazd jest nadrzędny w składzie - inline bool IsCabMaster() const - { - return CabActive == CabOccupied && CabMaster; - } // czy aktualna kabina jest na pewno tą, z której można sterować - bool AutomaticCabActivation = true; // czy zmostkowany rozrzad przelacza sie sam przy zmianie kabiny - int InactiveCabFlag = 0; // co sie dzieje przy dezaktywacji kabiny - bool InactiveCabPantsCheck = false; // niech DynamicObject sprawdzi pantografy - double LastSwitchingTime = 0.0; /*czas ostatniego przelaczania czegos*/ - int WarningSignal = 0; // 0: nie trabi, 1,2,4: trabi - bool DepartureSignal = false; /*sygnal odjazdu*/ - bool InsideConsist = false; - /*-zmienne dla lokomotywy elektrycznej*/ - TTractionParam RunningTraction; /*parametry sieci trakcyjnej najblizej lokomotywy*/ - double enrot = 0.0; // ilosc obrotow silnika - double Im = 0.0; // prad silnika - /* - // currently not used - double IHeating = 0.0; - double ITraction = 0.0; - */ - double Itot = 0.0; // prad calkowity - double TotalCurrent = 0.0; - // momenty - double Mm = 0.0; - double Mw = 0.0; - // sily napedne - double Fw = 0.0; - double Ft = 0.0; - // Ra: Im jest ujemny, jeśli lok jedzie w stronę sprzęgu 1 - // a ujemne powinien być przy odwróconej polaryzacji sieci... - // w wielu miejscach jest używane abs(Im) - int Imin = 0; - int Imax = 0; /*prad przelaczania automatycznego rozruchu, prad bezpiecznika*/ - double EngineVoltage = 0.0; // voltage supplied to engine - int MainCtrlActualPos = 0; /*wskaznik RList*/ - int ScndCtrlActualPos = 0; /*wskaznik MotorParam*/ - bool DelayCtrlFlag = false; // czy czekanie na 1. pozycji na załączenie? - double LastRelayTime = 0.0; /*czas ostatniego przelaczania stycznikow*/ - bool AutoRelayFlag = false; /*mozna zmieniac jesli AutoRelayType=2*/ - bool FuseFlag = false; /*!o bezpiecznik nadmiarowy*/ - bool ConvOvldFlag = false; /*! nadmiarowy przetwornicy i ogrzewania*/ - bool GroundRelay{true}; // switches off to protect against damage from earths - start_t GroundRelayStart{start_t::manual}; // relay activation method - bool StLinFlag = false; /*!o styczniki liniowe*/ - bool StLinSwitchOff{false}; // state of the button forcing motor connectors open - line_contactors_interlock LineContactorsInterlock{line_contactors_interlock::none}; // what else the line contactors need to close - double LouvresOpenPressure{5.0}; // main reservoir pressure [bar] at which the pneumatic louvres of the motor fans open (ET22) - bool ResistorsFlag = false; /*!o jazda rezystorowa*/ - double RventRot = 0.0; /*!s obroty wentylatorow rozruchowych*/ - double PantographVoltage{0.0}; // voltage supplied to pantographs - double PantPress = 0.0; /*Cisnienie w zbiornikach pantografow*/ - bool PantPressSwitchActive{false}; // state of the pantograph pressure switch. gets primed at defined pressure level in pantograph air system - bool PantPressLockActive{false}; // pwr system state flag. fires when pressure switch activates by pantograph pressure dropping below defined level - // switches off if the power level drops below threshold, which opens the line breaker; with PantographsRequireMains - // it opens the line contactors instead, and switches back on only with the master controller at zero or the first position - bool NoVoltRelay{true}; - bool OvervoltageRelay{true}; // switches off if the power level goes above threshold - bool s_CAtestebrake = false; // hunter-091012: zmienna dla testu ca - std::array, 4> PowerCircuits; // 24v, 110v, 3x400v and 3000v power circuits, voltage from local sources and current draw pairs - - /*-zmienne dla lokomotywy spalinowej z przekladnia mechaniczna*/ - double dizel_fill = 0.0; /*napelnienie*/ - double dizel_engagestate = 0.0; /*sprzeglo skrzyni biegow: 0 - luz, 1 - wlaczone, 0.5 - wlaczone 50% (z poslizgiem)*/ - double dizel_engage = 0.0; /*sprzeglo skrzyni biegow: aktualny docisk*/ - double dizel_automaticgearstatus = 0.0; /*0 - bez zmiany, -1 zmiana na nizszy +1 zmiana na wyzszy*/ - bool dizel_startup{false}; // engine startup procedure request indicator - bool dizel_ignition{false}; // engine ignition request indicator - bool dizel_spinup{false}; // engine spin up to idle speed flag - // the starter turns the engine a while before it fires: smoke comes out only after SmokeDelay (the Engine section of the vehicle's - // .fiz, seconds from the start of the spin up) has passed. 0, the default, lets it out as soon as the starter turns, as before eu07/maszyna#523 - double dizel_SmokeDelay{0.0}; - double dizel_FiringCountdown{0.0}; // seconds left until the engine being started fires, 0 once it runs on its own - double dizel_engagedeltaomega = 0.0; /*roznica predkosci katowych tarcz sprzegla*/ - double dizel_n_old = 0.0; /*poredkosc na potrzeby obliczen sprzegiel*/ - double dizel_Torque = 0.0; /*aktualny moment obrotowy silnika spalinowego*/ - double dizel_Power = 0.0; /*aktualna moc silnika spalinowego*/ - double dizel_nreg_min = 0.0; /*predkosc regulatora minimalna, zmienna w hydro*/ - double dizel_nreg_max = 0.0; /*predkosc regulatora maksymalna, zmienna w hydro*/ - - /* - zmienne dla przetowrnika momentu */ - double hydro_TC_Fill = 0.0; /*napelnienie*/ - bool hydro_TC_Lockup = false; /*zapiecie sprzegla*/ - double hydro_TC_TorqueIn = 0.0; /*moment*/ - double hydro_TC_TorqueOut = 0.0; /*moment*/ - double hydro_TC_TMRatio = 1.0; /*aktualne przelozenie momentu*/ - double hydro_TC_Request = 0.0; /*zadanie sily*/ - double hydro_TC_nIn = 0.0; /*predkosc obrotowa walu wejsciowego*/ - double hydro_TC_nOut = 0.0; /*predkosc obrotowa walu wyjsciowego*/ - - /* - zmienne dla przetowrnika momentu */ - double hydro_R_Fill = 0.0; /*napelnienie*/ - double hydro_R_Torque = 0.0; /*moment*/ - double hydro_R_Request = 0.0; /*zadanie sily hamowania*/ - double hydro_R_n = 0.0; /*predkosc obrotowa retardera*/ - bool hydro_R_ClutchActive = false; /*czy retarder jest napędzany*/ - - /*- zmienne dla lokomotyw z silnikami indukcyjnymi -*/ - double eimic = 0; /*aktualna pozycja zintegrowanego sterowania jazda i hamowaniem*/ - double eimic_analog = 0; /*pozycja zadajnika analogowa*/ - double eimic_real = 0; /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/ - double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far - double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/ - int EIMCtrlType = 0; /*rodzaj wariantu zadajnika jazdy*/ - bool SpeedCtrlTypeTime = false; /*czy tempomat sterowany czasowo*/ - int SpeedCtrlAutoTurnOffFlag = 0; /*czy tempomat sam się wyłącza*/ - bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ - bool EIMCtrlEmergency = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ - bool EIMCtrlMainEmergency = false; /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ - double eimv_pr = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/ - double eimv[21]; - static std::vector const eimv_labels; - double SpeedCtrlTimer = 0; /*zegar dzialania tempomatu z wybieralna predkoscia*/ - double eimicSpeedCtrl = 1; /*pozycja sugerowana przez tempomat*/ - double eimicSpeedCtrlIntegral = 0; /*calkowany blad ustawienia predkosci*/ - double NewSpeed = 0; /*nowa predkosc do zadania*/ - double MED_EPVC_CurrentTime = 0; /*aktualny czas licznika czasu korekcji siły EP*/ - double MED_ED_DelayTimer = 0; /*aktualny czas licznika opoznienia hamowania ED*/ - - /*-zmienne dla drezyny*/ - double PulseForce = 0.0; /*przylozona sila*/ - double PulseForceTimer = 0.0; - int PulseForceCount = 0; - - /*dla drezyny, silnika spalinowego i parowego*/ - double eAngle = M_PI * 0.5; - - /*-dla wagonow*/ - float LoadAmount = 0.f; /*masa w T lub ilosc w sztukach - zaladowane*/ - load_attributes LoadType; - std::string LoadQuantity; // jednostki miary - int LoadStatus = 0; //+1=trwa rozladunek,+2=trwa zaladunek,+4=zakończono,0=zaktualizowany model - bool LoadTypeChange{false}; // indicates load type was changed - double LastLoadChangeTime = 0.0; // raz (roz)ładowania -#ifdef EU07_USEOLDDOORCODE - bool DoorBlocked = false; // Czy jest blokada drzwi - bool DoorLockEnabled{true}; - bool DoorLeftOpened = false; // stan drzwi - double DoorLeftOpenTimer{-1.0}; // left door closing timer for automatic door type - bool DoorRightOpened = false; - double DoorRightOpenTimer{-1.0}; // right door closing timer for automatic door type -#endif - // TODO: move these switch types where they belong, cabin definition - std::string PantSwitchType; - std::string ConvSwitchType; - bool HeatingSwitchImpulse{false}; // the train heating switch springs back to its middle position - std::string StLinSwitchType; - - bool Heating = false; // ogrzewanie 'Winger 020304 - bool HeatingAllow{false}; // heating switch // TODO: wrap heating in a basic device - int DoubleTr = 1; // trakcja ukrotniona - przedni pojazd 'Winger 160304 - basic_light CompartmentLights; - - bool PhysicActivation = true; - - /*ABu: stale dla wyznaczania sil (i nie tylko) po optymalizacji*/ - double FrictConst1 = 0.0; - double FrictConst2s = 0.0; - double FrictConst2d = 0.0; - double TotalMassxg = 0.0; /*TotalMass*g*/ - - double fBrakeCtrlPos = -2.0; // płynna nastawa hamulca zespolonego - bool bPantKurek3 = true; // kurek trójdrogowy (pantografu): true=połączenie z ZG, false=połączenie z małą sprężarką // domyślnie zbiornik pantografu połączony jest ze zbiornikiem głównym - bool PantAutoValve{false}; // type of installed pantograph compressor valve - int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać - int iLights[2]; // bity zapalonych świateł tutaj, żeby dało się liczyć pobór prądu - - // Status nowszego hebelka od przyciemniania swiatel/swiatel dlugich - // 0 - swiatla wylaczone (opcja dziala tylko gdy w fiz zdefiniowano OffState w sekcji Switches; w przeciwnym wypadku pstryk startuje z wartoscia == 1 - // 1 - swiatla normalne przyciemnione - // 2 - swiatla normalne - // 3 - swiatla dlugie przyciemnione - // 4 - swiatla dlugie normalne - - struct dimPosition - { - bool isOff = false; - bool isDimmed = false; - bool isHighBeam = false; - }; - - // default positions - std::vector dimPositions = {{false, false, false}, // 0 - Not dimmed - {false, true, false}}; // 1 - Dimmed - - int modernDimmerPosition{0}; - int modernDimmerDefaultPosition{0}; - // bool modernContainOffPos{true}; - bool enableModernDimmer{false}; - bool modernDimmerCanCycle{false}; - // the given dimmer position brought into the DimmerList, to its first or last entry; 0 for an empty list - int clampDimmerPosition(int Position) const; - // the entry of the current dimmer position, or a plain one (not off, not dimmed, no high beam) when the - // position is outside the DimmerList: the .fiz can give a short or an empty list, or a DefaultPos past its end - dimPosition currentDimPosition() const; - // moves the dimmer by Step positions within the DimmerList, around to its other end when it can cycle; - // a position outside the list is brought into it first. false when the dimmer doesn't move - bool stepDimmerPosition(int Step); - - // Barwa reflektora - int refR{255}; // Czerwony - int refG{255}; // Zielony - int refB{255}; // Niebieski - - double dimMultiplier{0.6f}; // mnoznik swiatel przyciemnionych - double normMultiplier{1.0f}; // mnoznik swiatel zwyklych - double highDimMultiplier{2.5f}; // mnoznik dlugich przyciemnionych - double highMultiplier{2.8f}; // mnoznik dlugich - - plc::basic_controller m_plc; - - int AIHintPantstate{0}; // suggested pantograph setup - // suggested pantograph setup in shunting (AI: ShuntPantstate=, eu07/maszyna#461), the bits as in Pantstate: 1 front, - // 2 rear, 3 both; 0 (the default) shunts with the pantographs handled as in train mode - int AIHintShuntPantstate{0}; - bool AIHintPantUpIfIdle{true}; // whether raise both pantographs if idling for a while - double AIHintLocalBrakeAccFactor{1.05}; // suggested acceleration weight for local brake operation - - TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab); - // obsługa sprzęgów - static double CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right); - static double Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2); - bool Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, int CouplingType, bool Enforce = false, bool Audible = true); - int DettachStatus(int ConnectNo); - bool Dettach(int ConnectNo); - void damage_coupler(int const End); - // repairs the broken coupler of the end, and the one of the vehicle it was coupled with, so they can be coupled - // again; the vehicles clear their coupler damage once neither of their couplers is broken. returns: whether there - // was a broken coupler to repair - bool repair_coupler(int const End); - void Derail(DerailReason Reason); - bool DirectionForward(); - bool DirectionBackward(void); /*! kierunek ruchu*/ - bool EIMDirectionChangeAllow(void) const; - inline double IsVehicleEIMBrakingFactor() const - { - return DynamicBrakeFlag && ResistorsFlag ? 0.0 : eimv[eimv_Ipoj] < 0 ? -1.0 : 1.0; - } - void BrakeLevelSet(double b); - bool BrakeLevelAdd(double b); - bool IncBrakeLevel(); // wersja na użytek AI - bool DecBrakeLevel(); - bool ChangeCab(int direction); - bool CurrentSwitch(bool const State); - bool IsMotorOverloadRelayHighThresholdOn() const; - void UpdateBatteryVoltage(double dt); - double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, - TRotation const &NewRot); // oblicza przesuniecie pojazdu - double FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu - wersja zoptymalizowana - void compute_movement_(double const Deltatime); - double ShowEngineRotation(int VehN) const; - - // Q ******************************************************************************************* - double GetTrainsetVoltage(int const Coupling = coupling::heating | coupling::highvoltage) const; - double GetTrainsetHighVoltage() const; - // what turns the physics on, counted for the debug panel (Timer::switching_counter) - enum class wake_cause - { - other, - mainpipe, // air flowing in from a neighbour along the brake pipe - scndpipe, // along the main reservoir pipe - command, - speed, // the test of ComputeTotalForce(): the vehicle moves - acceleration, // accelerates - neighbour, // a neighbour moves or accelerates - rest // active cab, switching, ezt/dmu - }; - bool switch_physics(bool const State, wake_cause const Cause = wake_cause::other); - // whether the vehicle accelerates, for the test which turns the physics off in vehicles standing still (ComputeTotalForce()). - // standing still, its acceleration is the pull of the slope and of the couplers, as the brakes and the resistance count only - // against a speed (FTotal); with Global.physics_sleepheld one held by them, the way ComputeMovement() keeps it standing, doesn't - bool accelerating() const; - double LocalBrakeRatio(void) const; - double ManualBrakeRatio(void) const; - double PipeRatio(void) const; /*ile napelniac*/ - double RealPipeRatio(void) const; /*jak szybko*/ - double BrakeVP(void) const; - double EngineRPMRatio() const; // returns current engine revolutions as percentage of max engine revolutions, in range 0-1 - double EngineIdleRPM() const; - double EngineMaxRPM() const; - - /*! przesylanie komend sterujacych*/ - bool SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype = coupling::control); - bool SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype = coupling::control); - double GetExternalCommand(std::string &Command) const; - bool RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype = coupling::control); - bool RunInternalCommand(); - void PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); - bool CabActivisation(bool const Enforce = false); - bool CabDeactivisation(bool const Enforce = false); - bool CabActivisationAuto(bool const Enforce = false); - bool CabDeactivisationAuto(bool const Enforce = false); - - /*! funkcje zwiekszajace/zmniejszajace nastawniki*/ - /*! glowny nastawnik:*/ - bool IncMainCtrl(int CtrlSpeed); - bool DecMainCtrl(int CtrlSpeed); - bool IsMainCtrlActualNoPowerPos() const; // whether the master controller is actually set to position which won't generate any extra power - bool IsMainCtrlNoPowerPos() const; // whether the master controller is set to position which won't generate any extra power - bool IsMainCtrlMaxPowerPos() const; - int MainCtrlNoPowerPos() const; // highest setting of master controller which won't cause engine to generate extra power - int MainCtrlActualPowerPos() const; // current actual setting of master controller, relative to the highest setting not generating extra power - int MainCtrlPowerPos() const; // current setting of master controller, relative to the highest setting not generating extra power - // positions the master controller of the EIMCtrlType 2 (Elf) has below its own position 0, the emergency brake (0 or 1) - int EIMCtrlEmergencyPositions() const; - // whether the master controller is in its emergency brake position (EIMCtrlType 2 with EIMCtrlMainEmergency) - bool IsMainCtrlEmergencyPos() const; - // the master controller position sent to the coupled vehicles ("MainCtrl"), the same with and without - // EIMCtrlMainEmergency: the Elf's positions without the emergency brake one, which goes as the full braking - int MainCtrlPosForCoupled() const; - // the master controller position of this vehicle for one received from a coupled vehicle ("MainCtrl") - int MainCtrlPosFromCoupled(int Position) const; - /*! pomocniczy nastawnik:*/ - bool IncScndCtrl(int CtrlSpeed); - bool DecScndCtrl(int CtrlSpeed); - int GetVirtualScndPos() const; - // whether ScndCtrlResistiveLock keeps the shunt controller from being moved at the current master controller position - bool IsScndCtrlLockedByMainCtrl() const; - // ScndCtrlResistiveLock: the shunt controller drops to 0 once the master controller is at zero or on a resistive position, so it - // can't stay engaged there, locked in place (eu07/maszyna#402) - void ScndCtrlResistiveLockCheck(); - bool IsScndCtrlNoPowerPos() const; - bool IsScndCtrlMaxPowerPos() const; - - bool AddPulseForce(int Multipler); /*dla drezyny*/ - - bool SandboxManual(bool const State, range_t const Notify = range_t::consist); /*wlacza/wylacza reczne sypanie piasku*/ - bool SandboxAuto(bool const State, range_t const Notify = range_t::consist); /*wlacza/wylacza automatyczne sypanie piasku*/ - bool Sandbox(bool const State, range_t const Notify = range_t::consist); /*wlacza/wylacza sypanie piasku*/ - bool SandboxAutoAllow(bool const State); /*wlacza/wylacza zezwolenie na automatyczne sypanie piasku*/ - - /*! zbijanie czuwaka/SHP*/ - void SecuritySystemReset(void); - void SecuritySystemCheck(double dt); - - bool BatterySwitch(bool State, range_t const Notify = range_t::consist); - bool EpFuseSwitch(bool State); - bool SpringBrakeActivate(bool State); - bool SpringBrakeShutOff(bool State); - bool SpringBrakeRelease(); - - /*! stopnie hamowania - hamulec zasadniczy*/ - bool IncBrakeLevelOld(void); - bool DecBrakeLevelOld(void); - bool IncLocalBrakeLevel(float const CtrlSpeed); - bool DecLocalBrakeLevel(float const CtrlSpeed); - /*! ABu 010205: - skrajne polozenia ham. pomocniczego*/ - bool IncManualBrakeLevel(int CtrlSpeed); - bool DecManualBrakeLevel(int CtrlSpeed); - /*! oddzielny nastawnik hamulca elektrodynamicznego (gdy SplitEDPneumaticBrake)*/ - bool IncDynamicBrakeLevel(float const CtrlSpeed); - bool DecDynamicBrakeLevel(float const CtrlSpeed); - bool DynamicBrakeLevelSet(double Position); - double DynamicBrakeRatio(void) const; - bool DynamicBrakeAvailable(void) const; /*czy ED dostepny w aktualnym oknie predkosci Vh0..Vh1*/ - bool DynamicBrakeSwitch(bool Switch); - bool RadiostopSwitch(bool Switch); - bool AlarmChainSwitch(bool const State); - bool AntiSlippingBrake(void); - bool BrakeReleaser(int state); - bool UniversalBrakeButton(int button, int state); /*uniwersalny przycisk hamulca*/ - bool SwitchEPBrake(int state); - // whether the EP brake control of the cab has power: battery, the reverser out of neutral and the EP fuse on - bool EPBrakeControlPowered() const; - bool AntiSlippingButton(void); /*! reczny wlacznik urzadzen antyposlizgowych*/ - - /*funkcje dla ukladow pneumatycznych*/ - bool IncBrakePress(double &brake, double PressLimit, double dp); - bool DecBrakePress(double &brake, double PressLimit, double dp); - bool BrakeDelaySwitch(int BDS); /*! przelaczanie nastawy opoznienia*/ - bool IncBrakeMult(void); /*przelaczanie prozny/ladowny*/ - bool DecBrakeMult(void); - /*pomocnicze funkcje dla ukladow pneumatycznych*/ - void UpdateBrakePressure(double dt); - void UpdatePipePressure(double dt); - void CompressorCheck(double dt); /*wlacza, wylacza kompresor, laduje zbiornik*/ - void UpdatePantVolume(double dt); // Ra - void UpdateScndPipePressure(double dt); - void UpdateSpringBrake(double dt); - double GetDVc(double dt); - - /*funkcje obliczajace sily*/ - void ComputeConstans(void); // ABu: wczesniejsze wyznaczenie stalych dla liczenia sil - void ComputeMass(void); - void ComputeTotalForce(double dt); - double Adhesive(double staticfriction) const; - double TractionForce(double dt); - double FrictionForce() const; - double BrakeForceR(double ratio, double velocity) const; - double BrakeForceP(double press, double velocity) const; - double BrakeForce(const TTrackParam &Track); - double CouplerForce(int const End, double dt); - // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this - // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all - bool coupler_physics_at(int const End) const; - // the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h - double coupler_force_physical(int const End, double const dt); - // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and - // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers - bool coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd); - // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit - // is too fast for them to catch - void automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd); - void CollisionDetect(int const End, double const dt); - // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio - static constexpr double SafeCollisionVelocity{15.0}; - // closing speed [km/h] of the End of this vehicle and the OtherEnd of the other vehicle it touches, along the coupler - // axis: the sum of the speeds in a head-on collision, the difference in a rear-end one, negative when they part - double CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const; - // velocity [m/s] of this vehicle relative to the other vehicle it touches with its End and the OtherEnd of the - // other one, along this vehicle's axis - double CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const; - // whether the automatic couplers at the End of this vehicle and the OtherEnd of the other one can catch each other on - // contact, rather than the vehicles colliding (with crash damage enabled, only at a closing speed which doesn't derail them) - bool AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const; - // whether the control coupling (multiple-unit control) can join the End of this vehicle and the OtherEnd of the other - // one: not between an electric and a diesel traction vehicle, unless both couplers name the same control system - // (ControlType). Vehicles without own traction (cars, control trailers) take any. Global.control_coupling_engine_check - // off allows it always (eu07/maszyna#520) - bool ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const; - // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling - // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole - int CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const; - // the horns of the Signal (WarningSignal bits) which have the air or the voltage they need to sound - int SoundingHorns(int const Signal) const; - // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: - // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied - bool MainCircuitLampsEnabled() const - { - return false == ControlPressureSwitch && (HasControlPressureSwitch || BrakePress < 1.0); - } - // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so - // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the - // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263) - bool LineContactorsLampLit() const - { - if (EngineType == TEngineType::DieselElectric) - { - return false == StLinFlag; - } - return false == StLinFlag && MainCircuitLampsEnabled(); - } - // the vehicles the line breaker / engine start switch of this vehicle works, and its engine stopping on its own - // stops: the whole consist, or with JointEngineStart=No this vehicle alone (eu07/maszyna#80) - range_t MainSwitchRange() const - { - return JointEngineStart ? range_t::consist : range_t::local; - } - // whether the pneumatic louvres of the motor fans are still closed, the main reservoir short of the pressure that opens them - bool LouvresClosed() const - { - return Compressor < LouvresOpenPressure; - } - // whether the devices the line contactors are interlocked with (LineContactorsInterlock) let them close - bool LineContactorsInterlockReleased() const; - // whether the line contactors wait for the converter of the vehicle, switched off with its local switch (converterlocal_sw). - // the AI driver doesn't leave it so: the converters of the other vehicles running, it would wait for the contactors forever - bool LineContactorsHeldByLocalConverterSwitch() const - { - return LineContactorsInterlock == line_contactors_interlock::converter && false == ConverterAllowLocal; - } - // whether the vehicle has a driver's cab: it has the driver's brake valve (BrakeHandle in the Cntrl. section of the - // .fiz), which the wagons and most cars of the units without a cab don't (a few copy the Cntrl. section of the cab - // car, as the EN57 s car does). it's the vehicle type's, unlike the cab the scenario puts a driver in - bool HasDriverCab() const - { - return BrakeHandle != TBrakeHandle::NoHandle; - } - // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button - // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump - // starts on its own (eu07/maszyna#427). the other vehicles with such a button keep ignoring the command - bool MainCircuitOpensWithStarterOnly() const - { - return EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric; - } - // whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on - bool OilFuelPumpsEnabled() const - { - auto const fuelmanual{FuelPump.start_type != start_t::automatic}; - auto const oilmanual{OilPump.start_type != start_t::automatic}; - return (fuelmanual || oilmanual) && (false == fuelmanual || FuelPump.is_enabled) && (false == oilmanual || OilPump.is_enabled); - } - // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work - bool RadioPowered() const - { - return Radio && RadioFuse && (Power24vIsAvailable || Power110vIsAvailable); - } - /*obrot kol uwzgledniajacy poslizg*/ - double ComputeRotatingWheel(double WForce, double dt, double n) const; - - /*--funkcje dla lokomotyw*/ - bool WaterPumpBreakerSwitch(bool State, range_t const Notify = range_t::consist); // water pump breaker state toggle - bool WaterPumpSwitch(bool State, range_t const Notify = range_t::consist); // water pump state toggle - bool WaterPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // water pump state toggle - bool WaterHeaterBreakerSwitch(bool State, range_t const Notify = range_t::consist); // water heater breaker state toggle - bool WaterHeaterSwitch(bool State, range_t const Notify = range_t::consist); // water heater state toggle - bool WaterCircuitsLinkSwitch(bool State, range_t const Notify = range_t::consist); // water circuits link state toggle - bool FuelPumpSwitch(bool State, range_t const Notify = range_t::consist); // fuel pump state toggle - bool FuelPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // fuel pump state toggle - bool OilPumpSwitch(bool State, range_t const Notify = range_t::consist); // oil pump state toggle - bool OilPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // oil pump state toggle - bool MotorBlowersSwitch(bool State, end const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle - bool MotorBlowersSwitchOff(bool State, end const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle - bool CompartmentLightsSwitch(bool State, range_t const Notify = range_t::consist); // compartment lights state toggle - bool CompartmentLightsSwitchOff(bool State, range_t const Notify = range_t::consist); // compartment lights state toggle - bool MainSwitch(bool const State, range_t const Notify = range_t::consist); /*! wylacznik glowny*/ - void MainSwitch_(bool const State); - bool MainSwitchCheck() const; // checks conditions for closing the line breaker - bool ConverterSwitch(bool State, range_t const Notify = range_t::consist); /*! wl/wyl przetwornicy*/ - bool CompressorSwitch(bool State, range_t const Notify = range_t::consist); /*! wl/wyl sprezarki*/ - bool ChangeCompressorPreset(int const Change, range_t const Notify = range_t::consist); - bool HeatingSwitch(bool const State, range_t const Notify = range_t::consist); - void HeatingSwitch_(bool const State); - double EnginePowerSourceVoltage() const; // returns voltage of defined main engine power source - // whether the main circuit feeds what runs on it (the converter, a compressor, the heating, the motor and resistor - // blowers, the traction motors): the line breaker closed, and where it closes ahead of the pantographs and holds - // without traction voltage (PantographsRequireMains) also the voltage there, at least the one the undervoltage - // trip takes. everywhere else it's the same as Mains - bool MainCircuitPowered() const; - - /*-funkcje typowe dla lokomotywy elektrycznej*/ - void LowVoltagePowerCheck(double const Deltatime); - void MainsCheck(double const Deltatime); - void PowerCouplersCheck(double const Deltatime, coupling const Coupling); - void ConverterCheck(double const Timestep); // przetwornica - void HeatingCheck(double const Timestep); - void WaterPumpCheck(double const Timestep); - void WaterHeaterCheck(double const Timestep); - void FuelPumpCheck(double const Timestep); - void OilPumpCheck(double const Timestep); - void MotorBlowersCheck(double const Timestep); - // whether the circuit a traction motor blower runs off has power: the battery, the converter or the main circuit, by its start type - bool MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const; - void PantographsCheck(double const Timestep); - void LightsCheck(double const Timestep); - bool FuseOn(range_t const Notify = range_t::consist); // bezpiecznik nadamiary - bool FuseFlagCheck(void) const; // sprawdzanie flagi nadmiarowego - void FuseOff(void); // wylaczenie nadmiarowego - bool UniversalResetButton(int const Button, range_t const Notify = range_t::consist); - bool RelayReset(int const Relays, range_t const Notify = range_t::consist); // resets specified relays - double ShowCurrent(int AmpN) const; // pokazuje bezwgl. wartosc pradu na wybranym amperomierzu - double ShowCurrentP(int AmpN) const; // pokazuje bezwgl. wartosc pradu w wybranym pojezdzie //Q 20160722 - - /*!o pokazuje bezwgl. wartosc obrotow na obrotomierzu jednego z 3 pojazdow*/ - /*function ShowEngineRotation(VehN:int): integer; //Ra 2014-06: przeniesione do C++*/ - /*funkcje uzalezniajace sile pociagowa od predkosci: v2n, n2r, current, momentum*/ - double v2n(void); - double Current(double n, double U); - double Momentum(double I) const; - double MomentumF(double I, double Iw, int SCP) const; - - bool CutOffEngine(void); // odlaczenie udszkodzonych silnikow - /*funkcje automatycznego rozruchu np EN57*/ - bool MaxCurrentSwitch(bool State, range_t const Notify = range_t::consist); // przelacznik pradu wysokiego rozruchu - bool MinCurrentSwitch(bool State); // przelacznik pradu automatycznego rozruchu - bool AutoRelaySwitch(bool State); // przelacznik automatycznego rozruchu - bool AutoRelayCheck(); // symulacja automatycznego rozruchu - bool MotorConnectorsCheck(); - bool ResistorsFlagCheck(void) const; // sprawdzenie kontrolki oporow rozruchowych NBMX - - bool OperatePantographsValve(operation_t const State, range_t const Notify = range_t::consist); - bool OperatePantographValve(end const End, operation_t const State, range_t const Notify = range_t::consist); - bool DropAllPantographs(bool const State, range_t const Notify = range_t::consist); - - void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania - void CheckSpeedCtrl(double dt); - void SpeedCtrlButton(int button); - void SpeedCtrlInc(); - void SpeedCtrlDec(); - bool SpeedCtrlPowerInc(); - bool SpeedCtrlPowerDec(); - - /*-funkcje typowe dla lokomotywy spalinowej z przekladnia mechaniczna*/ - bool dizel_EngageSwitch(double state); - bool dizel_EngageChange(double dt); - bool dizel_AutoGearCheck(void); - double dizel_fillcheck(int mcp, double dt); - double dizel_Momentum(double dizel_fill, double n, double dt); - double dizel_MomentumRetarder(double n, double dt); // moment hamowania retardera - void dizel_HeatSet(float const Value); - void dizel_Heat(double const dt); - bool dizel_StartupCheck(); - bool dizel_Update(double dt); - - /* funckje dla wagonow*/ - bool AssignLoad(std::string const &Name, float const Amount = 0.f); - bool LoadingDone(double LSpeed, std::string_view Loadname); - bool PermitDoors(side const Door, bool const State = true, range_t const Notify = range_t::consist); - void PermitDoors_(side const Door, bool const State = true); - bool ChangeDoorPermitPreset(int const Change, range_t const Notify = range_t::consist); - bool PermitDoorStep(bool const State, range_t const Notify = range_t::consist); - bool ChangeDoorControlMode(bool const State, range_t const Notify = range_t::consist); - bool OperateDoors(side const Door, bool const State, range_t const Notify = range_t::consist); - bool LockDoors(bool const State, range_t const Notify = range_t::consist); - bool signal_departure(bool const State, range_t const Notify = range_t::consist); // toggles departure warning - void update_doors(double const Deltatime); // door controller update - door_closure_t door_closure() const; // state of the door closure signalling of this vehicle - // whether the door closure lamp in the cab of this vehicle is lit: with DoorClosureSignal, for the given state of the - // consist; without it, for the lock of the vehicle's own doors, as the lamp always worked - bool door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const; - - /* funkcje dla samochodow*/ - bool ChangeOffsetH(double DeltaOffset); - - /*funkcje ladujace pliki opisujace pojazd*/ - bool LoadFIZ(std::string const &chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); - bool LoadFIZ_Text(std::string const &Text); // the same, from text in the .fiz format - bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); - std::string EngineDescription(int what) const; - // the cab interior light the light preset at given position (1-based, as LightsPos) sets, if it sets one - std::optional LightsPresetCabLight(int Position) const; - - private: - bool LoadFIZ_Parse(cParser &Parser); // reads the definition from either of the above - void LoadFIZ_Param(std::string const &line); - void LoadFIZ_Load(std::string const &line); - void LoadFIZ_Dimensions(std::string const &line); - void LoadFIZ_Wheels(std::string const &line); - void LoadFIZ_Brake(std::string const &line); - void LoadFIZ_Doors(std::string const &line); - void LoadFIZ_BuffCoupl(std::string const &line, int const Index); - void LoadFIZ_TurboPos(std::string const &line); - void LoadFIZ_Cntrl(std::string const &line); - void LoadFIZ_Blending(std::string const &line); - void LoadFIZ_DCEMUED(std::string const &line); - void LoadFIZ_SpringBrake(std::string const &line); - void LoadFIZ_Light(std::string const &line); - void LoadFIZ_Headlights(std::string const &Line); - void LoadFIZ_Clima(std::string const &line); - void LoadFIZ_Power(std::string const &Line); - void LoadFIZ_SpeedControl(std::string const &Line); - void LoadFIZ_Engine(std::string const &Input); - void LoadFIZ_Switches(std::string const &Input); - void LoadFIZ_MotorParamTable(std::string const &Input); - void LoadFIZ_Circuit(std::string const &Input); - void LoadFIZ_AI(std::string const &Input); - void LoadFIZ_RList(std::string const &Input); - void LoadFIZ_UCList(std::string const &Input); - void LoadFIZ_DList(std::string const &Input); - void LoadFIZ_FFList(std::string const &Input); - void LoadFIZ_FFEDList(std::string const &Input); - void LoadFIZ_WiperList(std::string const &Input); - void LoadFIZ_LightsList(std::string const &Input); - void LoadFIZ_DimmerList(std::string const &Input); - void LoadFIZ_CompressorList(std::string const &Input); - void LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Input); - TPowerType LoadFIZ_PowerDecode(std::string const &Power) const; - TPowerSource LoadFIZ_SourceDecode(std::string const &Source) const; - TEngineType LoadFIZ_EngineDecode(std::string const &Engine) const; - bool readMPT0(std::string const &line); - bool readMPT(std::string const &line); // Q 20160717 - bool readMPTElectricSeries(std::string const &line); - bool readMPTDieselElectric(std::string const &line); - bool readMPTDieselEngine(std::string const &line); - bool readBPT(/*int const ln,*/ std::string const &line); // Q 20160721 - bool readRList(std::string const &Input); - bool readUCList(std::string const &Input); - bool readDList(std::string const &line); - bool readDMList(std::string const &line); - bool readV2NMAXList(std::string const &line); - bool readHTCList(std::string const &line); - bool readPmaxList(std::string const &line); - bool readFFList(std::string const &line); - bool readFFEDList(std::string const &line); - bool readWWList(std::string const &line); - bool readWiperList(std::string const &line); - bool readDimmerList(std::string const &line); - bool readLightsList(std::string const &Input); - bool readCompressorList(std::string const &Input); - void BrakeValveDecode(std::string const &s); // Q 20160719 - void BrakeSubsystemDecode(); // Q 20160719 -}; - -// double Distance(TLocation Loc1, TLocation Loc2, TDimension Dim1, TDimension Dim2); - -namespace simulation -{ - -using weights_table = std::unordered_map; - -extern weights_table Weights; - -} // namespace simulation diff --git a/McZapkie/Mover.cpp b/McZapkie/Mover.cpp deleted file mode 100644 index d74aee11f..000000000 --- a/McZapkie/Mover.cpp +++ /dev/null @@ -1,13606 +0,0 @@ -/* -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 "MOVER.h" - -#include "vehicle/DynObj.h" -#include "Oerlikon_ESt.h" -#include "utilities/Globals.h" -#include "utilities/Logs.h" -#include "utilities/Timer.h" -#include "utilities/parser.h" -#include "simulation/simulation.h" - -#include -#include -#include -//--------------------------------------------------------------------------- - -// Ra: tu należy przenosić funcje z mover.pas, które nie są z niego wywoływane. -// Jeśli jakieś zmienne nie są używane w mover.pas, też można je przenosić. -// Przeniesienie wszystkiego na raz zrobiło by zbyt wielki chaos do ogarnięcia. - -const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...) -const double CouplerTune = 0.1; // skalowanie tlumiennosci - -int ConversionError = 0; - -std::vector const TMoverParameters::eimc_labels = {"dfic: ", "dfmax:", "p: ", "scfu: ", "cim: ", "icif: ", "Uzmax:", "Uzh: ", "DU: ", "I0: ", "fcfu: ", - "F0: ", "a1: ", "Pmax: ", "Fh: ", "Ph: ", "Vh0: ", "Vh1: ", "Imax: ", "abed: ", "eped: "}; - -std::vector const TMoverParameters::eimv_labels = { - "Fkrt:", "Fmax:", "ks: ", "df: ", "fp: ", "Us: ", "pole:", "Ic: ", "If: ", "M: ", "Fr: ", "Ipoj:", "Pm: ", "Pe: ", "eta: ", "fkr: ", "Uzsm:", "Pmax:", "Fzad:", "Imax:", "Fful:"}; - -inline double square(double val) // SQR() zle liczylo w current() ... -{ - return val * val; -} - -double ComputeCollision(double &v1, double &v2, double m1, double m2, double beta, bool vc) -{ // oblicza zmiane predkosci i przyrost pedu wskutek kolizji - assert(beta < 1.0); - - if (v1 < v2 && vc == true) - return 0; - else - { - double sum = m1 + m2; - double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum; - double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum; - // the collision changes the velocities directly: the bounce loses energy in the velocities relative to the - // centre of mass only, the pair keeps its momentum. scaling the velocities themselves braked the vehicles - // down with every step their couplers spent stretched or pressed in all the way (eu07/maszyna#553) - auto const centre{(m1 * v1 + m2 * v2) / sum}; - auto const restitution{std::sqrt(1.0 - beta)}; - v1 = std::lerp(centre, w1, restitution); - v2 = std::lerp(centre, w2, restitution); - return m1 * (w2 - w1) * (1 - beta); - } -} - -int DirPatch(int Coupler1, int Coupler2) -{ // poprawka dla liczenia sil przy ustawieniu przeciwnym obiektow - return Coupler1 != Coupler2 ? 1 : -1; -} - -int DirF(int CouplerN) -{ - switch (CouplerN) - { - case 0: - return -1; - case 1: - return 1; - default: - return 0; - } -} - -void TSecuritySystem::set_enabled(bool e) -{ - if (vigilance_enabled || cabsignal_enabled || radiostop_enabled) - enabled = e; - if (CabDependent) - cabactive = 0; -} - -void TSecuritySystem::acknowledge_press() -{ - pressed = true; - - if (vigilance_timer > AwareDelay) - { - alert_timer = 0.0; - vigilance_timer = 0.0; - return; - } - vigilance_timer = 0.0; - - if (!separate_acknowledge && cabsignal_active && !cabsignal_lock) - { - cabsignal_active = false; - alert_timer = 0.0; - } -} - -void TSecuritySystem::acknowledge_release() -{ - pressed = false; - - if (press_timer > MaxHoldTime) - alert_timer = 0.0; - press_timer = 0.0; -} - -void TSecuritySystem::cabsignal_reset() -{ - if (cabsignal_active && !cabsignal_lock) - { - cabsignal_active = false; - alert_timer = 0.0; - } -} - -void TSecuritySystem::update(double dt, double vel, bool pwr, int cab) -{ - if (!enabled || !pwr || DebugModeFlag) - { - power = pwr; - cabsignal_active = false; - vigilance_timer = 0.0; - alert_timer = 0.0; - press_timer = 0.0; - return; - } - - bool just_powered_on = !power && pwr; - bool just_activated = CabDependent && cabactive != cab; - - /* enabling battery */ - if (cabsignal_enabled && (just_powered_on || just_activated)) - { - cabsignal_active = true; - alert_timer = SoundSignalDelay; - } - - power = pwr; - velocity = vel; - cabactive = cab; - - if (vigilance_suspended) - { - // the vigilance device is switched off: no time counts towards a new alarm, of the alerter or of the button held - // too long. an alarm already on, with the emergency braking it leads to, stays until it's acknowledged as usual - if (vigilance_timer <= AwareDelay) - vigilance_timer = 0.0; - if (press_timer <= MaxHoldTime) - press_timer = 0.0; - } - else - { - if (vigilance_enabled && velocity > AwareMinSpeed) - vigilance_timer += dt; - - if (pressed && (!is_sifa || velocity > AwareMinSpeed)) - press_timer += dt; - } - - if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active) - alert_timer += dt; -} - -void TSecuritySystem::set_cabsignal() -{ - if (cabsignal_enabled && power) - cabsignal_active = true; -} - -bool TSecuritySystem::has_separate_acknowledge() const -{ - return separate_acknowledge; -} - -bool TSecuritySystem::is_blinking() const -{ - if (!power) - return false; - - return alert_timer > 0.0; -} - -bool TSecuritySystem::is_vigilance_blinking() const -{ - if (!power) - return false; - - return press_timer > MaxHoldTime || vigilance_timer > AwareDelay; -} - -bool TSecuritySystem::is_cabsignal_blinking() const -{ - if (!power) - return false; - - return cabsignal_active; -} - -bool TSecuritySystem::is_beeping() const -{ - if (!power) - return false; - - return alert_timer > SoundSignalDelay && (!separate_acknowledge || is_vigilance_blinking()); -} - -bool TSecuritySystem::is_cabsignal_beeping() const -{ - if (!power) - return false; - - return alert_timer > SoundSignalDelay && is_cabsignal_blinking(); -} - -bool TSecuritySystem::is_braking() const -{ - if (!power && enabled) - return true; - - return alert_timer > SoundSignalDelay + EmergencyBrakeDelay; -} - -bool TSecuritySystem::radiostop_available() const -{ - return radiostop_enabled; -} - -void TSecuritySystem::set_cabsignal_lock(bool v) -{ - cabsignal_lock = v; -} - -void TSecuritySystem::set_shunt_mode(bool const State) -{ - vigilance_suspended = State && AwareOffInShuntMode; -} - -bool TSecuritySystem::is_engine_blocked() const -{ - if (!is_sifa) - return false; - - return velocity < AwareMinSpeed && pressed; -} - -void TSecuritySystem::load(std::string const &line, double Vmax) -{ - std::string awaresystem = extract_value("AwareSystem", line); - if (awaresystem.find("Active") != std::string::npos) - vigilance_enabled = true; - if (awaresystem.find("CabSignal") != std::string::npos) - cabsignal_enabled = true; - if (awaresystem.find("Sifa") != std::string::npos) - is_sifa = true; - if (awaresystem.find("SeparateAcknowledge") != std::string::npos) - separate_acknowledge = true; - - extract_value(AwareDelay, "AwareDelay", line, ""); - AwareMinSpeed = 0.1 * Vmax; // domyślnie 10% Vmax - extract_value(AwareMinSpeed, "AwareMinSpeed", line, ""); - extract_value(SoundSignalDelay, "SoundSignalDelay", line, ""); - extract_value(EmergencyBrakeDelay, "EmergencyBrakeDelay", line, ""); - extract_value(MaxHoldTime, "MaxHoldTime", line, ""); - extract_value(radiostop_enabled, "RadioStop", line, ""); - extract_value(MagnetLocation, "MagnetLocation", line, ""); - extract_value(CabDependent, "CabDependent", line, ""); - extract_value(AwareOffInShuntMode, "AwareOffInShuntMode", line, ""); -} - -double TableInterpolation(std::map &Map, double Parameter) -{ - if (Map.empty()) - return 0.0; - if (Map.size() == 1) - return Map.begin()->second; - - auto lower = Map.lower_bound(Parameter); - auto upper = lower; - - if (lower != Map.begin()) - lower--; - else - upper++; - - if (upper == Map.end()) - { - lower--; - upper--; - } - double ratio = (upper->second - lower->second) / (upper->first - lower->first); - return lower->second + (Parameter - lower->first) * ratio; -} - -// ************************************************************************************************* -// Q: 20160716 -// Obliczanie natężenie prądu w silnikach -// ************************************************************************************************* -double TMoverParameters::Current(double n, double U) -{ - // wazna funkcja - liczy prad plynacy przez silniki polaczone szeregowo lub rownolegle - // w zaleznosci od polozenia nastawnikow MainCtrl i ScndCtrl oraz predkosci obrotowej n - // a takze wywala bezpiecznik nadmiarowy gdy za duzy prad lub za male napiecie - // jest takze mozliwosc uszkodzenia silnika wskutek nietypowych parametrow - - double R; - double MotorCurrent; - double Rz; - double Delta; - double Isf; - double Mn; // przujmuje int, ale dla poprawnosci obliczeń - double Bn; - int SP = 0; - double U1; // napiecie z korekta - - MotorCurrent = 0; - // i dzialanie hamulca ED w EP09 - if (DynamicBrakeType == dbrake_automatic && TrainType != dt_EZT) - { - if ((Hamulec->GetEDBCP() < 0.25 && Vadd < 1) || BrakePress > 2.1) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && Hamulec->GetEDBCP() > 0.25) - DynamicBrakeFlag = true; - DynamicBrakeFlag = DynamicBrakeFlag && Power110vIsAvailable; - } - if (DynamicBrakeType == dbrake_automatic && TrainType == dt_EZT) - { - DynamicBrakeFlag = Power110vIsAvailable && (TUHEX_Active || Vadd > TUHEX_MinIw) && DynamicBrakeEMUStatus; - } - - // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... - - // BrakeSubsystem = ss_LSt; - // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); - // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna - if (DynamicBrakeFlag) - { - Hamulec->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy - //- WriteLog("A"); - } - else - { - Hamulec->SetED(0); - //- WriteLog("B"); - } - - ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) - ResistorsFlag = ResistorsFlag || (DynamicBrakeFlag == true && DynamicBrakeType == dbrake_automatic); - - if (TrainType == dt_ET22 && DelayCtrlFlag && MainCtrlActualPos > 1) - Bn = 1.0 - 1.0 / RList[MainCtrlActualPos].Bn; - else - Bn = 1; // to jest wykonywane dla EU07 - - R = RList[MainCtrlActualPos].R * Bn + CircuitRes; - - if (TrainType != dt_EZT || Imin != IminLo || false == ScndS) - { - // yBARC - boczniki na szeregu poprawnie - Mn = RList[MainCtrlActualPos].Mn; // to jest wykonywane dla EU07 - } - else - { - Mn = RList[MainCtrlActualPos].Mn * RList[MainCtrlActualPos].Bn; - if (RList[MainCtrlActualPos].Bn > 1) - { - R = CircuitRes; - } - } - - if (DynamicBrakeFlag && !FuseFlag && DynamicBrakeType == dbrake_automatic && Power110vIsAvailable && Mains) // hamowanie EP09 //TUHEX - { - // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 - MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / DynamicBrakeRes; - } - else if (RList[MainCtrlActualPos].Bn == 0 || false == StLinFlag) - { - // wylaczone - MotorCurrent = 0; - } - else - { // wlaczone... - SP = ScndCtrlActualPos; - - if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal - { - if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) - { - SP = RList[MainCtrlActualPos].ScndAct; - } - - Rz = Mn * WindingRes + R; - - if (DynamicBrakeFlag) // hamowanie - { - if (DynamicBrakeType > 1) - { - // if DynamicBrakeType<>dbrake_automatic then - // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} - /* begin - U:=0; - Isf:=Isat; - Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; - MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) - end*/ - if (DynamicBrakeType == dbrake_switch && TrainType == dt_ET42) - { // z Megapacka - Rz = WindingRes + R; - MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} - } - } - else - MotorCurrent = 0; // odciecie pradu od silnika - } - else - { - U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; - // writepaslog("U1 ", FloatToStr(U1)); - // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); - // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); - Isf = Sign(U1) * motor_param(SP).Isat; - // writepaslog("Isf ", FloatToStr(Isf)); - Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 - // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; - // writepaslog("Delta ", FloatToStr(Delta)); - // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); - // writepaslog("U ", FloatToStr(U)); - if (MainCircuitPowered()) - { - if (U > 0) - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); - else - MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); - } - else - MotorCurrent = 0; - } // else DBF - - } // 255 - else - MotorCurrent = 0; - } - // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); - - if (DynamicBrakeType == dbrake_switch && (BrakePress > 2.0 || PipePress < 3.6)) - { - Im = 0; - // Im:=0; - Itot = 0; - } - else - Im = MotorCurrent; - - EnginePower = abs(Itot) * (1 + RList[MainCtrlActualPos].Mn) * abs(U) / 1000.0; - - // awarie - MotorCurrent = abs(Im); // zmienna pomocnicza - - if (MotorCurrent > 0) - { - if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) - EventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ - if (TestFlag(DamageFlag, dtrain_engine) && FuzzyLogic(MotorCurrent, (double)ImaxLo / 10.0, p_elengproblem) && MainSwitch(false)) - EventFlag = true; /*uszkodzony silnik (uplywy)*/ - /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ - if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && SetFlag(DamageFlag, dtrain_engine)) - EventFlag = true; - /*! dorobic grzanie oporow rozruchowych i silnika*/ - } - - return Im; -} - -// ************************************************************************************************* -// główny konstruktor -// ************************************************************************************************* -TMoverParameters::TMoverParameters(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), CabOccupied(Cab) -{ - WriteLog("------------------------------------------------------"); - WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); - - // BrakeLevelSet(-2); //Pascal ustawia na 0, przestawimy na odcięcie (CHK jest jeszcze nie wczytane!) - iLights[0] = 0; - iLights[1] = 0; // światła zgaszone - - // inicjalizacja stalych - for (auto &scheme : RList) - { - scheme = TScheme(); - } - RlistSize = 0; - for (auto &motorparam : MotorParam) - { - motorparam = TMotorParameters(); - } - - for (auto &cablights : Lights) - for (int k = 0; k < 17; ++k) - cablights[k] = 0; - - for (auto &compressorrow : CompressorList) - for (int k = 1; k < 9; ++k) - compressorrow[k] = 0; - CompressorList[0][0] = 0.0; - CompressorList[1][0] = 1.0; - CompressorList[2][0] = 1.0; - CompressorList[3][0] = 1.0; - - for (int b = -1; b <= MainBrakeMaxPos; ++b) - { - BrakePressureTable[b].PipePressureVal = 0.0; - BrakePressureTable[b].BrakePressureVal = 0.0; - BrakePressureTable[b].FlowSpeedVal = 0.0; - } - // with BrakePressureTable[-2] do {pozycja odciecia} - { - BrakePressureTable[-2].PipePressureVal = -1.0; - BrakePressureTable[-2].BrakePressureVal = -1.0; - BrakePressureTable[-2].FlowSpeedVal = 0.0; - } - for (auto &delay : BrakeDelay) - { - delay = 0.0; - } - - for (int b = 0; b < 2; ++b) // Ra: kto tu zrobił "for b:=1 to 2 do" ??? - { - Couplers[b].CouplerType = TCouplerType::NoCoupler; - Couplers[b].SpringKB = 1.0; - Couplers[b].SpringKC = 1.0; - Couplers[b].DmaxB = 0.1; - Couplers[b].FmaxB = 1000.0; - Couplers[b].DmaxC = 0.1; - Couplers[b].FmaxC = 1000.0; - } - for (auto &cylindermult : BrakeCylMult) - { - cylindermult = 0.0; - } - - for (auto &eimcvalue : eimc) - { - eimcvalue = 0.0; - } - eimc[eimc_p_eped] = 1.5; - - for (auto &couplerentry : Couplers) - { - couplerentry.AllowedFlag = 3; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ - couplerentry.CouplingFlag = 0; - couplerentry.Connected = nullptr; - couplerentry.ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony - couplerentry.Render = false; - couplerentry.CForce = 0.0; - couplerentry.Dist = 0.0; - couplerentry.CheckCollision = false; - } - - for (auto &brakepress : MaxBrakePress) - { - brakepress = 0.0; - } - - Vel = abs(VelInitial); - V = VelInitial / 3.6; - - for (auto &eimvvalue : eimv) - { - eimvvalue = 0.0; - } - - RunningShape.Len = 1.0; - - RunningTrack.CategoryFlag = CategoryFlag; - RunningTrack.Width = TrackW; - RunningTrack.friction = Steel2Steel_friction; - RunningTrack.QualityFlag = 20; - RunningTrack.DamageFlag = 0; - RunningTrack.Velmax = 100.0; // dla uzytku maszynisty w ai_driver} - - RunningTraction.TractionVoltage = 0.0; - RunningTraction.TractionFreq = 0.0; - RunningTraction.TractionMaxCurrent = 0.0; - RunningTraction.TractionResistivity = 1.0; -}; - -double TMoverParameters::Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2) -{ // zwraca odległość pomiędzy pojazdami (Loc1) i (Loc2) z uwzględnieneim ich długości (kule!) - return hypot(Loc2.X - Loc1.X, Loc1.Y - Loc2.Y) - 0.5 * (Dim2.L + Dim1.L); -}; - -double TMoverParameters::CouplerDist(TMoverParameters const *Left, TMoverParameters const *Right) -{ // obliczenie odległości pomiędzy sprzęgami (kula!) - return Distance(Left->Loc, Right->Loc, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) -}; - -bool TMoverParameters::Attach(int ConnectNo, int ConnectToNr, TMoverParameters *ConnectTo, int CouplingType, bool Enforce, bool Audible) -{ // łączenie do swojego sprzęgu (ConnectNo) pojazdu (ConnectTo) stroną (ConnectToNr) - // Ra: zwykle wykonywane dwukrotnie, dla każdego pojazdu oddzielnie - // Ra: trzeba by odróżnić wymóg dociśnięcia od uszkodzenia sprzęgu przy podczepianiu AI do składu - - if (ConnectTo == nullptr || CouplingType == coupling::faux) - { - return false; - } - - auto &thiscoupler{Couplers[ConnectNo]}; - auto const otherend{ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr}; - auto &othercoupler = ConnectTo->Couplers[otherend]; - auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)}; - - - if (auto const couplercheck{Enforce || (distance <= dEpsilon && thiscoupler.type() != TCouplerType::NoCoupler && thiscoupler.type() == othercoupler.type())}; false == couplercheck) - { - return false; - } - - // no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI - // or the player (eu07/maszyna#520) - if (auto const compatible{CompatibleCoupling(ConnectNo, *ConnectTo, otherend, CouplingType)}; compatible != CouplingType) - { - WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name)); - CouplingType = compatible; - if (CouplingType == coupling::faux) - { - return false; - } - } - - // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie - if (thiscoupler.CouplingFlag == coupling::faux) - { - // a new coupling: the play of the coupling as set up anew, without the stretch of the one before - thiscoupler.physics_state.couple(); - othercoupler.physics_state.couple(); - // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg - thiscoupler.Render = true; // tego rysować - othercoupler.Render = false; // a tego nie - } - auto const couplingchange{CouplingType ^ thiscoupler.CouplingFlag}; - thiscoupler.Connected = ConnectTo; - thiscoupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu - if (ConnectToNr != 2) - { - thiscoupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone - } - othercoupler.Connected = this; - othercoupler.CouplingFlag = CouplingType; - othercoupler.ConnectedNr = ConnectNo; - - if (true == Audible && couplingchange != 0) - { - // set sound event flag - int soundflag{sound::none}; - std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, - {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, - {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; - for (auto const &[mappingcoupling, mappingsound] : soundmappings) - { - if ((couplingchange & mappingcoupling) != 0) - { - soundflag |= mappingsound; - } - } - SetFlag(thiscoupler.sounds, soundflag); - } - - return true; -} - -int TMoverParameters::DettachStatus(int ConnectNo) -{ // Ra: sprawdzenie, czy odległość jest dobra do rozłączania - // powinny być 3 informacje: =0 sprzęg już rozłączony, <0 da się rozłączyć. >0 nie da się rozłączyć - if (!Couplers[ConnectNo].Connected) - return 0; // nie ma nic, to rozłączanie jest OK - if ((Couplers[ConnectNo].CouplingFlag & ctrain_coupler) == 0) - return -Couplers[ConnectNo].CouplingFlag; // hak nie połączony - rozłączanie jest OK - if (TestFlag(DamageFlag, dtrain_coupling)) - return -Couplers[ConnectNo].CouplingFlag; // hak urwany - rozłączanie jest OK - // CouplerDist(ConnectNo); - if (Couplers[ConnectNo].type() != TCouplerType::Screw || Neighbours[ConnectNo].distance < 0.01) - return -Couplers[ConnectNo].CouplingFlag; // można rozłączać, jeśli dociśnięty - return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag : Couplers[ConnectNo].CouplingFlag; -}; - -bool TMoverParameters::Dettach(int ConnectNo) -{ // rozlaczanie - - auto &thiscoupler{Couplers[ConnectNo]}; - auto &othervehicle{thiscoupler.Connected}; - auto &othercoupler{othervehicle->Couplers[thiscoupler.ConnectedNr]}; - - if (othervehicle == nullptr) - { - return true; - } // nie ma nic, to odczepiono - - auto couplingchange{thiscoupler.CouplingFlag}; // presume we'll uncouple all active flags - auto const couplingstate{DettachStatus(ConnectNo)}; // stan sprzęgu - if (couplingstate < 0) - { - // gdy scisniete zderzaki, chyba ze zerwany sprzeg (wirtualnego nie odpinamy z drugiej strony) - std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); - std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, coupling::faux); - } - else if (couplingstate > 0) - { // odłączamy węże i resztę, pozostaje sprzęg fizyczny, który wymaga dociśnięcia (z wirtualnym nic) - thiscoupler.CouplingFlag &= coupling::coupler; - othercoupler.CouplingFlag &= coupling::coupler; - } - // set sound event flag - couplingchange ^= thiscoupler.CouplingFlag; // remaining bits were removed from coupling - if (couplingchange != 0) - { - int soundflag{sound::detach}; // HACK: use detach flag to indicate removal of listed coupling - std::vector> const soundmappings = {{coupling::coupler, sound::attachcoupler}, {coupling::brakehose, sound::attachbrakehose}, - {coupling::mainhose, sound::attachmainhose}, {coupling::control, sound::attachcontrol}, - {coupling::gangway, sound::attachgangway}, {coupling::heating, sound::attachheating}}; - for (auto const &[mappingcoupling, mappingsound] : soundmappings) - { - if ((couplingchange & mappingcoupling) != 0) - { - soundflag |= mappingsound; - } - } - SetFlag(thiscoupler.sounds, soundflag); - } - - return couplingstate < 0; -}; - -bool TMoverParameters::DirectionForward() -{ - if (false == EIMDirectionChangeAllow()) - { - return false; - } - - if (MainCtrlPosNo > 0 && DirActive < 1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) - { - ++DirActive; - DirAbsolute = DirActive * CabActive; - SendCtrlToNext("Direction", DirActive, CabActive); - return true; - } - else if (DirActive == 1 && IsMainCtrlNoPowerPos() && TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor) - return MinCurrentSwitch(true); //"wysoki rozruch" EN57 - return false; -}; - -// Nastawianie hamulców - -void TMoverParameters::BrakeLevelSet(double b) -{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo - // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego - if (fBrakeCtrlPos == b) - return; // nie przeliczać, jak nie ma zmiany - fBrakeCtrlPos = b; - if (fBrakeCtrlPos < Handle->GetPos(bh_MIN)) - fBrakeCtrlPos = Handle->GetPos(bh_MIN); // odcięcie - else if (fBrakeCtrlPos > Handle->GetPos(bh_MAX)) - fBrakeCtrlPos = Handle->GetPos(bh_MAX); - // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable - BrakeCtrlPosR = fBrakeCtrlPos; - auto x = static_cast(std::floor(fBrakeCtrlPos)); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być - // obcięte a nie zaokrągone - while (x > BrakeCtrlPos && BrakeCtrlPos < BrakeCtrlPosNo) // jeśli zwiększyło się o 1 - if (!IncBrakeLevelOld()) // T_MoverParameters:: - break; // wyjście awaryjne - while (x < BrakeCtrlPos && BrakeCtrlPos >= -1) // jeśli zmniejszyło się o 1 - if (!DecBrakeLevelOld()) // T_MoverParameters:: - break; - BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; // skopiowanie pozycji - /* - //youBy: obawiam sie, ze tutaj to nie dziala :P - //Ra 2014-03: było tak zrobione, że działało - po każdej zmianie pozycji była wywoływana ta - funkcja - // if (BrakeSystem==Pneumatic?BrakeSubsystem==Oerlikon:false) //tylko Oerlikon akceptuje ułamki - if(false) - if (fBrakeCtrlPos>0.0) - {//wartości pośrednie wyliczamy tylko dla hamowania - double u=fBrakeCtrlPos-double(x); //ułamek ponad wartość całkowitą - if (u>0.0) - {//wyliczamy wartości ważone - BrakePressureActual.PipePressureVal+=-u*BrakePressureActual.PipePressureVal+u*BrakePressureTable[BrakeCtrlPos+1+2].PipePressureVal; - //BrakePressureActual.BrakePressureVal+=-u*BrakePressureActual.BrakePressureVal+u*BrakePressureTable[BrakeCtrlPos+1].BrakePressureVal; - //to chyba nie będzie tak działać, zwłaszcza w EN57 - BrakePressureActual.FlowSpeedVal+=-u*BrakePressureActual.FlowSpeedVal+u*BrakePressureTable[BrakeCtrlPos+1+2].FlowSpeedVal; - } - } - */ -}; - -bool TMoverParameters::BrakeLevelAdd(double b) -{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) - // zwraca false, gdy po dodaniu było by poza zakresem - BrakeLevelSet(fBrakeCtrlPos + b); - return b > 0.0 ? fBrakeCtrlPos < BrakeCtrlPosNo : BrakeCtrlPos > -1.0; // true, jeśli można kontynuować -}; - -bool TMoverParameters::IncBrakeLevel() -{ // nowa wersja na użytek AI, false gdy osiągnięto pozycję BrakeCtrlPosNo - return BrakeLevelAdd(1.0); -}; - -bool TMoverParameters::DecBrakeLevel() -{ - return BrakeLevelAdd(-1.0); -}; // nowa wersja na użytek AI, false gdy osiągnięto pozycję -1 - -bool TMoverParameters::ChangeCab(int direction) -{ // zmiana kabiny i resetowanie ustawien - if (std::abs(CabOccupied + direction) < 2) - { - CabOccupied = CabOccupied + direction; - if (BrakeCtrlPosNo > 0 && (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic)) - { - BrakeLevelSet(Handle->GetPos(bh_NP)); - LimPipePress = PipePress; - ActFlowSpeed = 0; - } - else - BrakeLevelSet(Handle->GetPos(bh_NP)); - MainCtrlPos = MainCtrlNoPowerPos(); - ScndCtrlPos = 0; - return true; - } - return false; -}; - -// rozruch wysoki (true) albo niski (false) -bool TMoverParameters::CurrentSwitch(bool const State) -{ - // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that - // the diesels with a shunt mode have no motor overload relay threshold to switch, the switch sets their shunt mode alone. - // MaxCurrentSwitch() takes any change of the setting, so asked first it took the first move of the switch (eu07/maszyna#497) - if (true == ShuntModeAllow && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) - { - // dla 2Ls150 przed ustawieniem kierunku, for SM42/SP42 at the controller's zero position - if (EngineType == TEngineType::DieselEngine ? DirActive != 0 : false == IsMainCtrlNoPowerPos()) - { - return false; - } - ShuntMode = State; - return true; - } - - if (MaxCurrentSwitch(State)) - { - if (TrainType != dt_EZT) - { - MinCurrentSwitch(State); - } - return true; - } - - return false; -}; - -bool TMoverParameters::IsMotorOverloadRelayHighThresholdOn() const -{ - - return ImaxHi > ImaxLo && Imax > ImaxLo; -} - -// KURS90 - sprężarka pantografów; Ra 2014-07: teraz jest to zbiornik rozrządu, chociaż to jeszcze nie tak -void TMoverParameters::UpdatePantVolume(double dt) -{ - // check the pantograph compressor while at it - // TODO: move the check to a separate method - // automatic start if the pressure is too low - PantCompFlag |= PantPress < 4.2 && true == (Pantographs[end::front].is_active | Pantographs[end::rear].is_active) // TODO: any_pantograph_is_active method - && (PantographCompressorStart == start_t::automatic || PantographCompressorStart == start_t::manualwithautofallback); - - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - PantCompFlag &= lowvoltagepower; - - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector // tylko jeśli pantografujący - && EnginePowerSource.CollectorParameters.CollectorsNo > 0) - { - // Ra 2014-07: zasadniczo, to istnieje zbiornik rozrządu i zbiornik pantografów - na razie mamy razem - // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS - // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć - // WS i odpalić resztę - if (PantAutoValve ? PantPress < ScndPipePress : bPantKurek3) // kurek zamyka połączenie z ZG - { // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje - // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem - PantPress = ScndPipePress; - // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) - PantPress = safe_clamp(ScndPipePress, 0.0, EnginePowerSource.CollectorParameters.MaxPress); - PantVolume = (PantPress + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem - } - else - { // zbiornik główny odcięty, można pompować pantografy - if (PantCompFlag) - { - // włączona mała sprężarka - PantVolume += dt - // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 - * (TrainType == dt_EZT ? 0.003 : 0.005) / std::max(1.0, PantPress) * (0.45 - (0.1 / PantVolume / 10 - 0.1)) / 0.45; - } - PantPress = safe_clamp(10.0 * PantVolume - 1.0, 0.0, EnginePowerSource.CollectorParameters.MaxPress); // tu by się przydała objętość zbiornika - } - if (!PantCompFlag && PantVolume > 0.1) - PantVolume -= dt * 0.0003 * std::max(1.0, PantPress * 0.5); // nieszczelności: 0.0003=0.3l/s - - if (PantPress < EnginePowerSource.CollectorParameters.MinPress) - { - // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php - if (true == PantPressSwitchActive) - { - // opuszczenie pantografów przy niskim ciśnieniu - if (TrainType != dt_EZT) - { - // pressure switch safety measure -- open the line breaker, unless there's alternate source of traction voltage - if (GetTrainsetHighVoltage() < EnginePowerSource.CollectorParameters.MinV) - { - // TODO: check whether line breaker should be open EMU-wide - MainSwitch(false, TrainType == dt_EZT ? 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 - PantPressLockActive = true; - // TODO: separate 'heating allowed' from actual heating flag, so we can disable it here without messing up heating toggle - ConverterSwitch(false, range_t::unit); - } - // mark the pressure switch as spent - PantPressSwitchActive = false; - } - } - else - { - if (PantPress >= 4.6) - { - // NOTE: we require active low power source to prime the pressure switch - // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate - if (true == Power24vIsAvailable || true == Power110vIsAvailable) - { - // prime the pressure switch - PantPressSwitchActive = true; - // turn off the subsystems lock - PantPressLockActive = false; - } - - if (PantPress >= 4.8) - { - // Winger - automatyczne wylaczanie malej sprezarki - // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) - PantCompFlag = false; - } - } - } - } - else - { // a tu coś dla SM42 i SM31, aby pokazywać na manometrze - PantPress = CntrlPipePress; - } -}; - -void TMoverParameters::UpdateBatteryVoltage(double dt) -{ // przeliczenie obciążenia baterii - double sn1 = 0.0; - double sn2 = 0.0; - double sn3 = 0.0; - double sn4 = 0.0; - double sn5 = 0.0; // Ra: zrobić z tego amperomierz NN - if (BatteryVoltage > 0 && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven && 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{Power110vIsAvailable || (EngineType == TEngineType::DieselElectric && true == Mains) || (EngineType == TEngineType::DieselEngine && true == Mains)}; - - if (NominalBatteryVoltage / BatteryVoltage < 1.22 && Battery) - { // 110V - 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 (Mains) - sn3 = dt * 0.05; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu //rozpisać na poszczególne żarówki... - sn4 = dt * 0.003; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.001; - else - sn5 = 0; - } - if (NominalBatteryVoltage / BatteryVoltage >= 1.22 && Battery) - { // 90V - if (PantCompFlag) - sn1 = dt * 0.0046; - else - sn1 = 0; - if (converteractive) - sn2 = -(dt * 50); // szybki wzrost do 110V - else - sn2 = 0; - if (Mains) - sn3 = dt * 0.001; - else - sn3 = 0; - if (iLights[0] & 63) // 64=blachy, nie ciągną prądu - sn4 = dt * 0.0030; - else - sn4 = 0; - if (iLights[1] & 63) // 64=blachy, nie ciągną prądu - sn5 = dt * 0.0010; - else - sn5 = 0; - } - if (!Battery) - { - if (NominalBatteryVoltage / 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 - } - BatteryVoltage -= sn1 + sn2 + sn3 + sn4 + sn5; - if (NominalBatteryVoltage / BatteryVoltage > 1.57 && MainSwitch(false) && EngineType != TEngineType::DieselEngine && EngineType != TEngineType::WheelsDriven) - EventFlag = true; // wywalanie szybkiego z powodu zbyt niskiego napiecia - if (BatteryVoltage > NominalBatteryVoltage) - BatteryVoltage = NominalBatteryVoltage; // wstrzymanie ładowania pow. 110V - if (BatteryVoltage < 0.01) - BatteryVoltage = 0.01; - } - else - { - // TODO: check and implement proper way to handle this for diesel engines - BatteryVoltage = NominalBatteryVoltage; - } -}; - -/* Ukrotnienie EN57: -1 //układ szeregowy -2 //układ równoległy -3 //bocznik 1 -4 //bocznik 2 -5 //bocznik 3 -6 //do przodu -7 //do tyłu -8 //1 przyspieszenie -9 //minus obw. 2 przyspieszenia -10 //jazda na oporach -11 //SHP -12A //podnoszenie pantografu przedniego -12B //podnoszenie pantografu tylnego -13A //opuszczanie pantografu przedniego -13B //opuszczanie wszystkich pantografów -14 //załączenie WS -15 //rozrząd (WS, PSR, wał kułakowy) -16 //odblok PN -18 //sygnalizacja przetwornicy głównej -19 //luzowanie EP -20 //hamowanie EP -21 //rezerwa** (1900+: zamykanie drzwi prawych) -22 //zał. przetwornicy głównej -23 //wył. przetwornicy głównej -24 //zał. przetw. oświetlenia -25 //wył. przetwornicy oświetlenia -26 //sygnalizacja WS -28 //sprężarka -29 //ogrzewanie -30 //rezerwa* (1900+: zamykanie drzwi lewych) -31 //otwieranie drzwi prawych -32H //zadziałanie PN siln. trakcyjnych -33 //sygnał odjazdu -34 //rezerwa (sygnalizacja poślizgu) -35 //otwieranie drzwi lewych -ZN //masa -*/ - -// ***************************************************************************** -// Q: 20160714 -// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca pomocnicznego -// ***************************************************************************** -double TMoverParameters::LocalBrakeRatio(void) const -{ - double LBR; - if (BrakeHandle == TBrakeHandle::MHZ_EN57) - if (BrakeOpModeFlag >= bom_EP) - LBR = Handle->GetEP(BrakeCtrlPosR); - else - LBR = 0; - else - { - if (LocalBrakePosNo > 0) - LBR = LocalBrakePosA; - else - LBR = 0; - } - // if (TestFlag(BrakeStatus, b_antislip)) - // LBR = std::max(LBR, PipeRatio) + 0.4; - return LBR; -} - -// ***************************************************************************** -// Q: 20160714 -// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca ręcznego -// ***************************************************************************** -double TMoverParameters::ManualBrakeRatio(void) const -{ - double MBR; - - if (ManualBrakePosNo > 0) - MBR = (double)ManualBrakePos / ManualBrakePosNo; - else - MBR = 0; - return MBR; -} - -// ***************************************************************************** -// Q: 20160713 -// Zwraca objętość -// ***************************************************************************** -double TMoverParameters::BrakeVP(void) const -{ - if (BrakeVVolume > 0) - return Volume / (10.0 * BrakeVVolume); - else - return 0; -} - -// ***************************************************************************** -// Q: 20160713 -// Zwraca iloraz różnicy między przewodem kontrolnym i głównym oraz DeltaPipePress -// ***************************************************************************** -double TMoverParameters::RealPipeRatio(void) const -{ - double rpp; - - if (DeltaPipePress > 0) - rpp = (CntrlPipePress - PipePress) / DeltaPipePress; - else - rpp = 0; - return rpp; -} - -// ***************************************************************************** -// Q: 20160713 -// Zwraca iloraz ciśnienia w przewodzie do DeltaPipePress -// ***************************************************************************** -double TMoverParameters::PipeRatio(void) const -{ - double pr; - - if (DeltaPipePress > 0) - if (false) // SPKS!! no to jak nie wchodzimy to po co branch? - { - if (3.0 * PipePress > HighPipePress + LowPipePress + LowPipePress) - pr = (HighPipePress - std::min(HighPipePress, PipePress)) / (DeltaPipePress * 4.0 / 3.0); - else - pr = (HighPipePress - 1.0 / 3.0 * DeltaPipePress - std::max(LowPipePress, PipePress)) / (DeltaPipePress * 2.0 / 3.0); - // if (not TestFlag(BrakeStatus, b_Ractive)) - // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and - // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); - // if (Compressor > 0.5) - // then pr : = pr * 1.333; // dziwny rapid wywalamy - } - else - pr = (HighPipePress - std::max(LowPipePress, std::min(HighPipePress, PipePress))) / DeltaPipePress; - else - pr = 0; - return pr; -} - -double TMoverParameters::EngineRPMRatio() const -{ - - return std::clamp(EngineType == TEngineType::DieselElectric ? 60.0 * std::abs(enrot) / DElist[MainCtrlPosNo].RPM : - EngineType == TEngineType::DieselEngine ? std::abs(enrot) / nmax : - 1.0, // shouldn't ever get here but, eh - 0.0, 1.0); -} - -double TMoverParameters::EngineIdleRPM() const -{ - - return EngineType == TEngineType::DieselEngine ? dizel_nmin * 60 : - EngineType == TEngineType::DieselElectric ? DElist[MainCtrlNoPowerPos()].RPM : - std::numeric_limits::max(); // shouldn't ever get here but, eh -} - -double TMoverParameters::EngineMaxRPM() const -{ - - return EngineType == TEngineType::DieselEngine ? dizel_nmax * 60 : - EngineType == TEngineType::DieselElectric ? DElist[MainCtrlPosNo].RPM : - std::numeric_limits::max(); // shouldn't ever get here but, eh -} - -// ************************************************************************************************* -// prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h -// ************************************************************************************************* -double TMoverParameters::CollisionVelocity(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)}; - // the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower - return (End == end::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h -} - -double TMoverParameters::CouplerVelocityDifference(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the - // vehicles face each other (touch with the same ends) - return V - Other.V * DirPatch(End, OtherEnd); -} - -bool TMoverParameters::AutomaticCouplingSafe(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity; -} - -namespace -{ - -// the kind of traction a vehicle's engine stands for, as far as its multiple-unit control goes -enum class traction_kind -{ - none, - electric, - diesel -}; - -traction_kind traction_of(TEngineType const Engine) -{ - switch (Engine) - { - case TEngineType::ElectricSeriesMotor: - case TEngineType::ElectricInductionMotor: - return traction_kind::electric; - case TEngineType::DieselEngine: - case TEngineType::DieselElectric: - return traction_kind::diesel; - default: - return traction_kind::none; - } -} - -} // namespace - -bool TMoverParameters::ControlCouplingAllowed(int const End, TMoverParameters const &Other, int const OtherEnd) const -{ - if (false == Global.control_coupling_engine_check) - { - return true; - } - // the same control system named on both couplers is the vehicle authors' word that they work together - if (auto const &controltype{Couplers[End].control_type}; false == controltype.empty() && controltype == Other.Couplers[OtherEnd].control_type) - { - return true; - } - auto const traction{traction_of(EngineType)}; - auto const othertraction{traction_of(Other.EngineType)}; - return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; -} - -int TMoverParameters::CompatibleCoupling(int const End, TMoverParameters const &Other, int const OtherEnd, int const CouplingType) const -{ - if ((CouplingType & coupling::control) == 0 || (CouplingType & coupling::permanent) != 0 || ControlCouplingAllowed(End, Other, OtherEnd)) - { - return CouplingType; - } - return CouplingType & ~coupling::control; -} - -int TMoverParameters::SoundingHorns(int const Signal) const -{ - auto const supplied{[this](horn_supply const Supply) { - if (Supply == horn_supply::electric) - { - return Power24vIsAvailable || Power110vIsAvailable; - } - if (VeselVolume > 0.0) - { - return Compressor >= HornMinPressure; - } - // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either - // (a road vehicle, say) has no air to check - auto const mainpipe{((Couplers[end::front].AllowedFlag | Couplers[end::rear].AllowedFlag) & coupling::mainhose) != 0}; - return false == mainpipe || ScndPipePress >= HornMinPressure; - }}; - auto horns{0}; - if (supplied(HornSupply)) - { - horns |= Signal & (1 | 2); - } - if (supplied(Horn3Supply)) - { - horns |= Signal & 4; - } - return horns; -} - -// ************************************************************************************************* -// Q: 20160716 -// Wykrywanie kolizji -// ************************************************************************************************* -void TMoverParameters::CollisionDetect(int const End, double const dt) -{ - if (Neighbours[End].vehicle == nullptr) - { - return; - } // shouldn't normally happen but, eh - - auto const &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; - auto const &othercoupler{othervehicle->Couplers[otherend]}; - - auto const physical{coupler_physics_at(End)}; - if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) - { - return; - } - // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give - // for good, rather than spring back as the legacy model has it - auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; - - // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each - // other (touch with the same ends), as in CouplerForce() - auto const otherdirection{DirPatch(End, otherend)}; - auto velocity{V}; - auto othervehiclevelocity{othervehicle->V * otherdirection}; - // calculate collision force and new velocities for involved vehicles - auto const VirtualCoupling{(thiscoupler.CouplingFlag == coupling::faux)}; - auto CCF{0.0}; - - switch (End) - { - case 0: - { - CCF = ComputeCollision(velocity, othervehiclevelocity, TotalMass, othervehicle->TotalMass, loss, VirtualCoupling) / dt; - break; // yB: ej ej ej, a po - } - case 1: - { - CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->TotalMass, TotalMass, loss, VirtualCoupling) / dt; - break; - } - default: - { - break; - } - } - - if (Global.crash_damage) - { - // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) - if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) - { - // small chance to smash the coupler if it's hit with excessive force - damage_coupler(End); - } - - // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist - auto const outsideconsist{thiscoupler.CouplingFlag == coupling::faux || true == TestFlag(othervehicle->DamageFlag, dtrain_out)}; - auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0}; - - if (velocitydifference > SafeCollisionVelocity) - { - // HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio - if (false == TestFlag(DamageFlag, dtrain_out) || false == TestFlag(othervehicle->DamageFlag, dtrain_out)) - { - WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h"); - } - - if (velocitydifference > SafeCollisionVelocity * (TotalMass / othervehicle->TotalMass)) - { - Derail(COLLISION); - } - if (velocitydifference > SafeCollisionVelocity * (othervehicle->TotalMass / TotalMass)) - { - othervehicle->Derail(COLLISION); - } - } - } - - // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the - // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the - // velocity once more, and the vehicles would bounce off the stop faster than they hit it - auto const accelerationspike{physical ? 0.0 : 1.0}; - if (false == TestFlag(DamageFlag, dtrain_out)) - { - auto const accelerationchange{(velocity - V) / dt}; - AccS += accelerationchange * accelerationspike; - V = velocity; - } - if (false == TestFlag(othervehicle->DamageFlag, dtrain_out)) - { - auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis - auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->V) / dt}; - othervehicle->AccS += othervehicleaccelerationchange * accelerationspike; - othervehicle->V = othervehiclenewvelocity; - } -} - -void TMoverParameters::damage_coupler(int const End) -{ - - auto &thiscoupler{Couplers[End]}; - - if (thiscoupler.type() == TCouplerType::Articulated) - { - return; - } // HACK: don't break articulated couplings no matter what - - if (SetFlag(DamageFlag, dtrain_coupling)) - EventFlag = true; - - auto const hosetorn{(thiscoupler.CouplingFlag & coupling::brakehose) == coupling::brakehose}; - if (hosetorn) - { - // hamowanie nagle - zerwanie przewodow hamulcowych - AlarmChainFlag = true; - } - - thiscoupler.CouplingFlag = 0; - thiscoupler.broken = true; - - if (thiscoupler.Connected != nullptr) - { - // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too - // for vehicles facing each other - auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; - othercoupler.CouplingFlag = coupling::faux; - // the coupling broke between the two, either end can be repaired - othercoupler.broken = true; - if (hosetorn && coupler_physics_at(End)) - { - // the brake pipe of the other part of the train vents through the torn hose as well - thiscoupler.Connected->AlarmChainFlag = true; - } - } - - WriteLog("Bad driving: " + Name + " broke a coupler"); -} - -namespace -{ - -// the coupler as good as new, the vehicle without the coupler damage (and the emergency braking of the torn brake -// hose) once neither of its couplers is broken -void repair(TMoverParameters &Vehicle, TCoupling &Coupler) -{ - Coupler.broken = false; - Coupler.stretch_duration = 0.f; - Coupler.physics_state.couple(); - if (Vehicle.Couplers[end::front].broken || Vehicle.Couplers[end::rear].broken) - { - return; - } - ClearFlag(Vehicle.DamageFlag, dtrain_coupling); - // either vehicle of the pair may have been braking through the torn hose - Vehicle.AlarmChainFlag = false; -} - -} // namespace - -bool TMoverParameters::repair_coupler(int const End) -{ - auto &thiscoupler{Couplers[End]}; - if (false == thiscoupler.broken) - { - return false; - } - repair(*this, thiscoupler); - // the other half of the coupling, which may be the vehicle flagged with the damage - if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken) - { - repair(*other, other->Couplers[thiscoupler.ConnectedNr]); - } - WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == end::front ? "front" : "rear")); - return true; -} - -void TMoverParameters::Derail(DerailReason const Reason) -{ - if (SetFlag(DamageFlag, dtrain_out)) - { - EventFlag = true; - MainSwitch(false, range_t::local); - - AccS *= 0.65; - V *= 0.65; - RunningShape.R = 0; - if (Vel < 5.0) - { - // HACK: prevent permanent axle spin in static vehicle after a collision - nrot = 0.0; - SlippingWheels = false; - } - - // Print a message in the log. - if (Reason == END_OF_TRACK) - ErrorLog("Bad driving: " + Name + " derailed due to end of track"); - else if (Reason == TOO_HIGH_SPEED) - ErrorLog("Bad driving: " + Name + " derailed due to too high speed"); - else if (Reason == GAUGE_MISMATCH) - ErrorLog("Bad dynamic: " + Name + " derailed due to track width"); // błąd w scenerii - else if (Reason == WRONG_TRACK_TYPE) - ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii - else if (Reason == COLLISION) - WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `TMoverParameters::CollisionDetect()` - else if (Reason == TRAILED_SWITCH) - ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); - } -} - -// ************************************************************************************************* -// Oblicza przemieszczenie taboru -// ************************************************************************************************* -double TMoverParameters::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) -{ - - if (!TestFlag(DamageFlag, dtrain_out)) - { // Ra: to przepisywanie tu jest bez sensu - RunningShape = Shape; - RunningTrack = Track; - RunningTraction = ElectricTraction; - - // if (!DynamicBrakeFlag) - // RunningTraction.TractionVoltage = ElectricTraction.TractionVoltage /*- - // abs(ElectricTraction.TractionResistivity * - // (Itot + HVCouplers[0][0] + HVCouplers[1][0]))*/; - // else - // RunningTraction.TractionVoltage = - // ElectricTraction.TractionVoltage /*- - // abs(ElectricTraction.TractionResistivity * Itot * - // 0)*/; // zasadniczo ED oporowe nie zmienia napięcia w sieci - } - - if (CategoryFlag == 4) - OffsetTrackV = TotalMass / (Dim.L * Dim.W * 1000.0); - else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && TestFlag(DamageFlag, dtrain_out)) - { - OffsetTrackV = -0.2; - OffsetTrackH = Sign(RunningShape.R) * 0.2; - } - - // TODO: investigate, seems supplied NewRot is always 0 although the code here suggests some actual values are expected - Loc = NewLoc; - Rot = NewRot; - - if (dL == 0) // oblicz przesuniecie} - { - auto const AccSprev{AccS}; - // przyspieszenie styczne - AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); - // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - - if (TestFlag(DamageFlag, dtrain_out)) - AccS = -Sign(V) * g * 1; // random(0.0, 0.1) - - // przyspieszenie normalne - if (abs(Shape.R) > 0.01) - AccN = square(V) / Shape.R + g * Shape.dHrail / TrackW; // Q: zamieniam SQR() na sqr() - else - AccN = g * Shape.dHrail / TrackW; - - // velocity change - auto const Vprev{V}; - V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci - if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) - { - // tlumienie predkosci przy hamowaniu - // zahamowany - V = 0; - } - - // tangential acceleration, from velocity change - AccSVBased = std::lerp(AccSVBased, (V - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); - - // vertical acceleration - AccVert = std::abs(AccVert) < 0.01 ? 0.0 : AccVert * 0.5; - // szarpanie - /* - #ifdef EU07_USE_FUZZYLOGIC - if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * Mass * Vel / Vmax, 500000.0, p_accn ) ) { - // Ra: czemu tu masa bez ładunku? - AccV /= ( 2.0 * 0.95 + 2.0 * Random() * 0.1 ); // 95-105% of base modifier (2.0) - } - else - #endif - AccV = AccV / 2.0; - - if (AccV > 1.0) - AccN += (7.0 - Random(5)) * (100.0 + Track.DamageFlag / 2.0) * AccV / 2000.0; - */ - // wykolejanie na luku oraz z braku szyn - if (TestFlag(CategoryFlag, 1)) - { - if (TestFlag(Track.DamageFlag, dtrack_norail)) - Derail(END_OF_TRACK); - if (FuzzyLogic(AccN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) - Derail(TOO_HIGH_SPEED); - // wykolejanie na poszerzeniu toru - if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) - Derail(GAUGE_MISMATCH); - } - // wykolejanie wkutek niezgodnosci kategorii toru i pojazdu - if (!TestFlag(RunningTrack.CategoryFlag, CategoryFlag)) - Derail(WRONG_TRACK_TYPE); - - // dL:=(V+AccS*dt/2)*dt; - // przyrost dlugosci czyli przesuniecie - dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} - // ale jesli jest kolizja (zas. zach. pedu) to...} - for (int b = 0; b < 2; b++) - if (Couplers[b].CheckCollision) - CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - - } // liczone dL, predkosc i przyspieszenie - - auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu - dL)}; - - DistCounter += fabs(dL) / 1000.0; - Odometer.run(dL); - dL = 0; - - // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze - compute_movement_(dt); - - // security system - SecuritySystemCheck(dt1); - - return d; -}; - -// ************************************************************************************************* -// Oblicza przemieszczenie taboru - uproszczona wersja -// ************************************************************************************************* - -double TMoverParameters::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) -{ - // T_MoverParameters::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); - - Loc = NewLoc; - Rot = NewRot; - - if (dL == 0) // oblicz przesuniecie - { - auto const AccSprev{AccS}; - // przyspieszenie styczne - AccS = std::lerp(AccSprev, FTotal / TotalMass, 0.5); - // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) - - if (TestFlag(DamageFlag, dtrain_out)) - AccS = -Sign(V) * g * 1; // * random(0.0, 0.1) - - // simple mode skips calculation of normal acceleration - - // velocity change - auto const Vprev{V}; - V += (3.0 * AccS - AccSprev) * dt / 2.0; // przyrost predkosci - if (V * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) - { - // tlumienie predkosci przy hamowaniu - // zahamowany - V = 0; - } - - // simple mode skips calculation of tangential acceleration - - // simple mode skips calculation of vertical acceleration - AccVert = 0.0; - - if (true == TestFlag(DamageFlag, dtrain_out) && Vel < 1.0) - { - V = 0.0; - AccS = 0.0; - } - - dL = (3.0 * V - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha - // ale jesli jest kolizja (zas. zach. pedu) to... - for (int b = 0; b < 2; b++) - if (Couplers[b].CheckCollision) - CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! - } // liczone dL, predkosc i przyspieszenie - - auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu - dL)}; - - DistCounter += fabs(dL) / 1000.0; - Odometer.run(dL); - dL = 0; - - // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze - compute_movement_(dt); - - return d; -}; - -// updates shared between 'fast' and regular movement computation methods -void TMoverParameters::compute_movement_(double const Deltatime) -{ - - // sprawdzanie i ewentualnie wykonywanie->kasowanie poleceń - if (LoadStatus > 0) // czas doliczamy tylko jeśli trwa (roz)ładowanie - LastLoadChangeTime += Deltatime; // czas (roz)ładunku - - RunInternalCommand(); - - // relay settings - // adjust motor overload relay threshold - if (EngineType == TEngineType::ElectricSeriesMotor && ImaxHi > ImaxLo) - { - if (MotorOverloadRelayHighThreshold) - { // set high threshold - if (TrainType != dt_ET42 ? RList[MainCtrlPos].Bn < 2 : MainCtrlPos == 0) - { - Imax = ImaxHi; - } - } - else - { // set low threshold - if (TrainType != dt_ET42 || MainCtrlPos == 0) - { - Imax = ImaxLo; - } - } - } - - // Uproszczona symulacja wentylatorow rezystora hamowania - - // Prad oddawany na rezystor - - // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora - if (double Irh = abs(eimv[eimv_Pe]) - abs(eimv[eimv_Ipoj]); Irh > Imaxrpc && eimv[eimv_Ipoj] < 0) - { - BRVtimer = 0; - BRVentilators = true; - } - else - { - BRVtimer += Deltatime; - if (BRVtimer > BRVto) - BRVentilators = false; - } - - // the master controller set directly, not through IncMainCtrl()/DecMainCtrl() (AI, consist): the locked shunt follows it as well - ScndCtrlResistiveLockCheck(); - // automatyczny rozruch - if (EngineType == TEngineType::ElectricSeriesMotor && AutoRelayCheck()) - { - SetFlag(SoundFlag, sound::relay); - } - - if ((EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && dizel_Update(Deltatime)) - { - SetFlag(SoundFlag, sound::relay); - } - - // TODO: gather and move current calculations to dedicated method - TotalCurrent = 0; - - // low voltage power sources - LowVoltagePowerCheck(Deltatime); - // power sources - PantographsCheck(Deltatime); - // main circuit - MainsCheck(Deltatime); - // traction motors - MotorBlowersCheck(Deltatime); - // uklady hamulcowe: - ConverterCheck(Deltatime); - if (VeselVolume > 0) - Compressor = CompressedVolume / VeselVolume; - else - { - Compressor = 0; - CompressorFlag = false; - } - if (VeselVolume > 0.0) - { - // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę - CompressorCheck(Deltatime); - } - if (Power > 1.0) - { - // w rozrządczym nie (jest błąd w FIZ!) - Ra 2014-07: teraz we wszystkich - UpdatePantVolume(Deltatime); // Ra 2014-07: obsługa zbiornika rozrządu oraz pantografów - } - // heating - HeatingCheck(Deltatime); - // lighting - LightsCheck(Deltatime); - - UpdateBrakePressure(Deltatime); - UpdatePipePressure(Deltatime); - UpdateBatteryVoltage(Deltatime); - UpdateScndPipePressure(Deltatime); // druga rurka, youBy - - if ((DCEMUED_CC & 1) != 0 && (Couplers[end::front].CouplingFlag & coupling::control) != 0) - { - DynamicBrakeEMUStatus &= Couplers[end::front].Connected->DynamicBrakeEMUStatus; - } - if ((DCEMUED_CC & 2) != 0 && (Couplers[end::rear].CouplingFlag & coupling::control) != 0) - { - DynamicBrakeEMUStatus &= Couplers[end::rear].Connected->DynamicBrakeEMUStatus; - } - - if (BrakeSlippingTimer > 0.8 && ASBType != 128) - { // ASBSpeed=0.8 - // hamulec antypoślizgowy - wyłączanie - Hamulec->ASB(0); - } - BrakeSlippingTimer += Deltatime; - // automatic doors - update_doors(Deltatime); - - m_plc.update(Deltatime); - - PowerCouplersCheck(Deltatime, coupling::highvoltage); - PowerCouplersCheck(Deltatime, coupling::power110v); - PowerCouplersCheck(Deltatime, coupling::power24v); - - Power24vVoltage = std::max(PowerCircuits[0].first, GetTrainsetVoltage(coupling::power24v)); - Power24vIsAvailable = Power24vVoltage > 0; - Power110vIsAvailable = PowerCircuits[1].first > 0 || GetTrainsetVoltage(coupling::power110v) > 0; -} - -void TMoverParameters::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, PantographVoltage); - break; - } - case TPowerSource::Accumulator: - { - localvoltage = std::max(localvoltage, Power24vVoltage); - break; - } - default: - { - break; - } - } - // 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 || (PantographsRequireMains && (Power24vIsAvailable || Power110vIsAvailable))}; - - if (true == maincircuitpowersupply) - { - // all is well - if (MainsInitTimeCountdown >= 0.0) - { - // NOTE: we ensure main circuit readiness meets condition MainsInitTimeCountdown < 0 - // this allows for simpler rejection of cases where MainsInitTime == 0 - MainsInitTimeCountdown -= Deltatime; - } - else - { - // optional automatic circuit start - if (MainsStart != start_t::manual && false == (Mains || dizel_startup)) - { - MainSwitch(true); - } - } - } - else - { - // no power supply - MainsInitTimeCountdown = MainsInitTime; - } -} - -void TMoverParameters::LowVoltagePowerCheck(double const /*Deltatime*/) -{ - - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - - if (EngineType == TEngineType::ElectricSeriesMotor) - { - GroundRelay &= lowvoltagepower; - if (GroundRelayStart != start_t::manual) - { - // NOTE: we're ignoring intricaties of battery and converter types as they're unlikely to be used - // TODO: generic check method which takes these into account - GroundRelay |= lowvoltagepower; - } - } -} - -void TMoverParameters::PowerCouplersCheck(double const /*Deltatime*/, coupling const Coupling) -{ - if (Coupling != coupling::highvoltage && Coupling != coupling::power110v && Coupling != coupling::power24v) - { - // only power couplings carry voltage - return; - } - - auto localvoltage{0.0}; - - // local power sources - // TODO: make local voltage calculations a separate method, store results in PowerCircuit fields - switch (Coupling) - { - - case coupling::highvoltage: - { - // heating power sources - if (Heating) - { - switch (HeatingPowerSource.SourceType) - { - case TPowerSource::Generator: - { - localvoltage = HeatingPowerSource.EngineGenerator.voltage - TotalCurrent * 0.02; - break; - } - case TPowerSource::CurrentCollector: - { - localvoltage = PantographVoltage; - break; - } - case TPowerSource::Main: - { - // HACK: main circuit can be fed through couplers, so we explicitly check pantograph supply here - localvoltage = MainCircuitPowered() ? PantographVoltage : 0.0; - break; - } - default: - { - break; - } - } - } - // high voltage power sources - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { - localvoltage = std::max(localvoltage, PantographVoltage); - } - break; - } - - case coupling::power110v: - { - if (ConverterFlag) - { - localvoltage = NominalBatteryVoltage; - } - // TBD, TODO: reduce by current draw? - PowerCircuits[1].first = localvoltage; - break; - } - - case coupling::power24v: - { - if (Battery) - { - localvoltage = BatteryVoltage; - } - // TBD, TODO: reduce by current draw? - PowerCircuits[0].first = localvoltage; - break; - } - - default: - { - break; - } - } - - auto const abslocalvoltage{std::abs(localvoltage)}; - auto const localpowersource{(abslocalvoltage > 1.0)}; - - // przekazywanie napiec - for (auto side = 0; side < 2; ++side) - { - - 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[side == end::front ? end::rear : end::front]}; - - bool oppositecouplingispresent; - bool localpowerexportisenabled; - - switch (Coupling) - { - - case coupling::highvoltage: - { - auto const oppositehighvoltagecoupling{(oppositecoupler.CouplingFlag & coupling::highvoltage) != 0}; - auto const oppositeheatingcoupling{(oppositecoupler.CouplingFlag & coupling::heating) != 0}; - - oppositecouplingispresent = oppositehighvoltagecoupling || oppositeheatingcoupling; - localpowerexportisenabled = oppositehighvoltagecoupling || (oppositeheatingcoupling && localpowersource && Heating); - break; - } - - case coupling::power110v: - { - oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power110v) != 0; - localpowerexportisenabled = oppositecouplingispresent; - break; - } - - case coupling::power24v: - { - oppositecouplingispresent = TestFlag(oppositecoupler.CouplingFlag, oppositecoupler.PowerCoupling) && (oppositecoupler.PowerFlag & coupling::power24v) != 0; - localpowerexportisenabled = oppositecouplingispresent; - break; - } - - default: - { - break; - } - } - - auto const *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; - auto *oppositecoupling = Coupling == coupling::highvoltage ? &oppositecoupler.power_high : - Coupling == coupling::power110v ? &oppositecoupler.power_110v : - Coupling == coupling::power24v ? &oppositecoupler.power_24v : - nullptr; - - // 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 = Coupling == coupling::highvoltage ? &connectedcoupler.power_high : - Coupling == coupling::power110v ? &connectedcoupler.power_110v : - Coupling == coupling::power24v ? &connectedcoupler.power_24v : - nullptr; - 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; - } - } - - // przekazywanie pradow - auto couplervoltage{0}; - switch (Coupling) - { - case coupling::highvoltage: - { - couplervoltage = static_cast(Couplers[end::front].power_high.voltage + Couplers[end::rear].power_high.voltage); - break; - } - case coupling::power110v: - { - couplervoltage = static_cast(Couplers[end::front].power_110v.voltage + Couplers[end::rear].power_110v.voltage); - break; - } - case coupling::power24v: - { - couplervoltage = static_cast(Couplers[end::front].power_24v.voltage + Couplers[end::rear].power_24v.voltage); - break; - } - default: - { - break; - } - } - - auto *totalcurrent = Coupling == coupling::highvoltage ? &TotalCurrent : - Coupling == coupling::power110v ? &PowerCircuits[1].second : - Coupling == coupling::power24v ? &PowerCircuits[0].second : - nullptr; - - for (auto &thiscoupler : Couplers) - { - auto *coupling = Coupling == coupling::highvoltage ? &thiscoupler.power_high : - Coupling == coupling::power110v ? &thiscoupler.power_110v : - Coupling == coupling::power24v ? &thiscoupler.power_24v : - nullptr; - - coupling->current = 0.0; - - if (thiscoupler.Connected == nullptr) - { - continue; - } - - auto const &connectedothercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr == end::front ? end::rear : end::front]}; - auto const *connectedothercoupling = Coupling == coupling::highvoltage ? &connectedothercoupler.power_high : - Coupling == coupling::power110v ? &connectedothercoupler.power_110v : - Coupling == coupling::power24v ? &connectedothercoupler.power_24v : - nullptr; - auto const extracurrent = Coupling == 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; - } - } - } -} - -double TMoverParameters::ShowEngineRotation(int VehN) const -{ // Zwraca wartość prędkości obrotowej silnika wybranego pojazdu. Do 3 pojazdów (3×SN61). - int b; - switch (VehN) - { // numer obrotomierza - case 1: - return std::abs(enrot); - case 2: - for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->enrot); - break; - case 3: // to nie uwzględnia ewentualnego odwrócenia pojazdu w środku - for (b = 0; b <= 1; ++b) - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01 && TestFlag(Couplers[b].Connected->Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) - return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); - break; - default: - break; - } - return 0.0; -}; - -// sprawdzanie przetwornicy -void TMoverParameters::ConverterCheck(double const Timestep) -{ - // TODO: move other converter checks here, to have it all in one place for potential device object - if (ConverterStart != start_t::disabled && ConverterOverloadRelayOffWhenMainIsOff) - { - ConvOvldFlag |= !Mains && Power24vIsAvailable; - } - - switch (ConverterStart) - { - case start_t::disabled: - { - ConverterAllow = false; - // NOTE: if there's no converter in vehicle we can end the check here - return; - } - case start_t::automatic: - { - ConverterAllow = Mains; - break; - } - case start_t::direction: - { - ConverterAllow = DirActive != 0; - } - default: - { - break; - } - } - - if (ConverterAllow && ConverterAllowLocal && false == ConvOvldFlag && - false == PantPressLockActive - // HACK: allow carriages to operate converter without (missing) fuse prerequisite - && (Power > 1.0 ? MainCircuitPowered() : GetTrainsetHighVoltage() > 0.0)) - { - // delay timer can be optionally configured, and is set anew whenever converter goes off - if (ConverterStartDelayTimer <= 0.0) - { - ConverterFlag = true; - } - else - { - ConverterStartDelayTimer -= Timestep; - } - } - else - { - ConverterFlag = false; - ConverterStartDelayTimer = static_cast(ConverterStartDelay); - } - - if (ConverterOverloadRelayStart == start_t::converter && false == (ConverterAllow && ConverterAllowLocal) && false == TestFlag(EngDmgFlag, 4)) - { - // reset converter overload relay if the converter was switched off, unless it's damaged - ConvOvldFlag = false; - } -}; - -// heating system status check -void TMoverParameters::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 == HeatingAllow ? 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 == HeatingAllow) - { - Heating = 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 = PantographVoltage; - 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() ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; - break; - } - default: - { - break; - } - } - - Heating = voltage > heatingpowerthreshold; - - if (Heating) - { - TotalCurrent += 1000 * HeatingPower / voltage; // heater power cost presumably specified in kilowatts - } -} - -// water pump status check -void TMoverParameters::WaterPumpCheck(double const /*Timestep*/) -{ - // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker - WaterPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterPump.breaker && false == WaterPump.is_disabled && - (true == WaterPump.is_active || true == WaterPump.is_enabled || WaterPump.start_type == start_t::battery); -} - -// water heater status check -void TMoverParameters::WaterHeaterCheck(double const /*Timestep*/) -{ - - WaterHeater.is_active = false == WaterHeater.is_damaged && true == (Power24vIsAvailable || Power110vIsAvailable) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && - (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || dizel_heat.temperatura1 < WaterHeater.config.temp_min); - - WaterHeater.is_damaged = true == WaterHeater.is_damaged || (true == WaterHeater.is_active && false == WaterPump.is_active); - - if (WaterHeater.config.temp_max > 0 && dizel_heat.temperatura1 > WaterHeater.config.temp_max) - { - WaterHeater.is_active = false; - } -} - -// fuel pump status update -void TMoverParameters::FuelPumpCheck(double const /*Timestep*/) -{ - using enum start_t; - - FuelPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == FuelPump.is_disabled && - (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : - FuelPump.start_type == automatic ? dizel_startup || Mains : - FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || dizel_startup || Mains : - false)); // shouldn't ever get this far but, eh -} - -// oil pump status update -void TMoverParameters::OilPumpCheck(double const Timestep) -{ - - OilPump.is_active = true == (Power24vIsAvailable || Power110vIsAvailable) && false == Mains && false == OilPump.is_disabled && - (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : - OilPump.start_type == start_t::automatic ? dizel_startup : - OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || dizel_startup : - false)); // shouldn't ever get this far but, eh - - auto const minpressure{OilPump.pressure_minimum > 0.f ? OilPump.pressure_minimum : 0.15f}; // arbitrary fallback value - - OilPump.pressure_target = enrot > 0.1 ? std::lerp( minpressure, OilPump.pressure_maximum, static_cast( EngineRPMRatio() ) ) * OilPump.resource_amount : - true == OilPump.is_active ? std::min( minpressure + 0.1f, OilPump.pressure_maximum ) : // slight pressure margin to give time to switch off the pump and start the engine - 0.f; - - if (OilPump.pressure < OilPump.pressure_target) - { - // TODO: scale change rate from 0.01-0.05 with oil/engine temperature/idle time - OilPump.pressure = std::min(OilPump.pressure_target, static_cast(OilPump.pressure + (enrot > 5.0 ? 0.05 : 0.035) * Timestep)); - } - if (OilPump.pressure > OilPump.pressure_target) - { - OilPump.pressure = std::max(OilPump.pressure_target, static_cast(OilPump.pressure - (enrot > 5.0 ? 0.05 : 0.035) * 0.5 * Timestep)); - } - OilPump.pressure = std::clamp(OilPump.pressure, 0.f, 1.5f); -} - -void TMoverParameters::MotorBlowersCheck(double const Timestep) -{ - // activation check - for (auto &blower : MotorBlowers) - { - auto disable = blower.is_disabled; - auto const start{(Vel >= blower.min_start_velocity && std::abs(Im) > 0.5)}; - auto const stop{(Vel < 0.5 && std::abs(Im) < 0.5)}; - if (blower.min_start_velocity >= 0) - { - if (stop) - { - blower.stop_timer += static_cast(Timestep); - if (blower.stop_timer > blower.sustain_time) - { - disable = true; - } - } - else if (start) - { - blower.stop_timer = 0; - } - else - { - disable |= !blower.is_active; - } - } - blower.is_active = - // TODO: bind properly power source when ld is in place - MotorBlowerPowerIsAvailable(blower) // power source - // breaker condition disabled until it's implemented in the class data - // && ( true == blower.breaker ) - && false == disable && - (true == blower.is_active || (blower.stop_timer == 0.f // HACK: will be true for blower with exceeded start_velocity, and for one without start_velocity - && (blower.start_type == start_t::manual ? blower.is_enabled : true))); - } - // update - for (auto &fan : MotorBlowers) - { - - auto const revolutionstarget{(fan.is_active ? (fan.speed > 0.f ? fan.speed * static_cast(enrot) * 60 : fan.speed * -1) : 0.f)}; - - if (std::abs(fan.revolutions - revolutionstarget) < 0.01f) - { - fan.revolutions = revolutionstarget; - continue; - } - if (revolutionstarget > 0.f) - { - auto const speedincreasecap{std::max(50.f, fan.speed * 0.05f * -1)}; // 5% of fixed revolution speed, or 50 - fan.revolutions += static_cast(std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep); - } - else - { - fan.revolutions *= static_cast(std::max(0.0, 1.0 - Timestep)); - } - } -} - -bool TMoverParameters::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const -{ - switch (Blower.start_type) - { - case start_t::battery: - return Power24vIsAvailable; - case start_t::converter: - return Power110vIsAvailable; - default: - return MainCircuitPowered(); - } -} - -void TMoverParameters::PantographsCheck(double const /*Timestep*/) -{ - using enum start_t; - - { - auto const &valve{PantsValve}; - auto const lowvoltagepower{valve.solenoid ? Power24vIsAvailable || Power110vIsAvailable : true}; - auto const autostart{valve.start_type == automatic || valve.start_type == manualwithautofallback}; - auto const manualcontrol{valve.start_type == manual || valve.start_type == manualwithautofallback}; - - PantsValve.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 ? Power24vIsAvailable || Power110vIsAvailable : 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 == PantAllDown : true) && - (Mains || false == PantographsRequireMains) // 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 && PantsValve.is_active && pantographexists; - - pant_id++; - } -} - -void TMoverParameters::LightsCheck(double const /*Timestep*/) -{ - - auto &light{CompartmentLights}; - - light.is_active = - // TODO: bind properly power source when ld is in place - (Power24vIsAvailable || Power110vIsAvailable) // 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 - * (Power110vIsAvailable ? 1.0f : - Power24vIsAvailable ? 0.5f : - 0.0f) * - light.dimming; -} - -double TMoverParameters::ShowCurrent(int AmpN) const -{ // Odczyt poboru prądu na podanym amperomierzu - switch (EngineType) - { - case TEngineType::ElectricInductionMotor: - switch (AmpN) - { // do asynchronicznych - case 1: - return WindingRes * Mm / Vadd; - case 2: - return eimv_pr * WindingRes; - default: - return ShowCurrentP(AmpN); // T_MoverParameters:: - } - break; - case TEngineType::DieselElectric: - return fabs(Im); - break; - default: - return ShowCurrentP(AmpN); // T_MoverParameters:: - } -}; - -// ************************************************************************************************* -// queuedEU -// ************************************************************************************************* - -// ************************************************************************************************* -// Q: 20160710 -// zwiększenie nastawinika -// ************************************************************************************************* - -bool TMoverParameters::IncMainCtrl(int CtrlSpeed) -{ - // basic fail conditions: - if (MainCtrlPosNo <= 0 || CabActive == 0) - { - // nie ma sterowania - return false; - } - if (TrainType == dt_ET22 && ScndCtrlPos != 0) - { - // w ET22 nie da się kręcić nastawnikiem przy włączonym boczniku - return false; - } - if (TrainType == dt_EZT && DirActive == 0) - { - // w EZT nie da się załączyć pozycji bez ustawienia kierunku - return false; - } - - bool OK = false; - if (MainCtrlPos < MainCtrlPosNo) - { - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if (CtrlSpeed > 1) - { - OK = IncMainCtrl(1) && IncMainCtrl(CtrlSpeed - 1); // a fail will propagate up the recursion chain. should this be || instead? - break; - } - ++MainCtrlPos; - OK = true; - if (EIMCtrlType == 0 && ( SpeedCtrlAutoTurnOffFlag & 1 ) == 1 && MainCtrlActualPos != MainCtrlPos) - { - DecScndCtrl(2); - SpeedCtrlUnit.IsActive = false; - } - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (DirActive == 0) - { - return false; - } - - if (CtrlSpeed > 1) - { - // szybkie przejœcie na bezoporow¹ - if (TrainType == dt_ET40) - { - break; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? - } - while (RList[MainCtrlPos].R > 0.0 && IncMainCtrl(1)) - { - // all work is done in the loop header - } - OK = false; // shouldn't this be part of the loop above? - // if (TrainType=dt_ET40) then - // while Abs (Im)>IminHi do - // dec(MainCtrlPos); - // OK:=false ; - } - else - { // CtrlSpeed == 1 - ++MainCtrlPos; - OK = true; - if (Imax == ImaxHi && RList[MainCtrlPos].Bn > 1) - { - /* NOTE: disabled, relay configuration was moved to compute_movement_ - if( true == MaxCurrentSwitch( false )) { - // wylaczanie wysokiego rozruchu - SetFlag( SoundFlag, sound::relay ); - } - */ - if (TrainType == dt_ET42) - { - --MainCtrlPos; - OK = false; - } - } - // - // if (TrainType == "et40") - // if (Abs(Im) > IminHi) - // { - // MainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu - // OK = false; - // } - //} - } - - if (TrainType == dt_ET42 && true == DynamicBrakeFlag && MainCtrlPos > 20) - { - MainCtrlPos = 20; - OK = false; - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed > 1) - { - while (MainCtrlPos < MainCtrlPosNo && IncMainCtrl(1)) - { - // all work is done in the loop header - } - } - else - { - ++MainCtrlPos; - } - CompressorAllow = MainCtrlPowerPos() > 0; - OK = true; - break; - } - - case TEngineType::WheelsDriven: - { - OK = AddPulseForce(CtrlSpeed); - break; - } - default: - break; - } // switch EngineType of - } - else - { // MainCtrlPos>=MainCtrlPosNo - if (true == CoupledCtrl) - { - // wspólny wał nastawnika jazdy i bocznikowania - if (ScndCtrlPos < ScndCtrlPosNo) - { // 3<3 -> false - ++ScndCtrlPos; - OK = true; - } - else - { - OK = false; - } - } - } - - if (true == OK) - { - ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones - SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - - // hunter-101012: poprawka - // poprzedni warunek byl niezbyt dobry, bo przez to przy trzymaniu + - // styczniki tkwily na tej samej pozycji (LastRelayTime byl caly czas 0 i rosl - // po puszczeniu plusa) - - if (OK) - { - if (DelayCtrlFlag) - { - if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) - LastRelayTime = 0; - } - else if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; - } - return OK; -} - -// ***************************************************************************** -// Q: 20160710 -// zmniejszenie nastawnika -// ***************************************************************************** -bool TMoverParameters::DecMainCtrl(int CtrlSpeed) -{ - bool OK = false; - // basic fail conditions: - if (MainCtrlPosNo <= 0 || CabActive == 0) - { - // nie ma sterowania - OK = false; - } - else if (CtrlSpeed == 0) - { - return false; - } - else - { - // TBD, TODO: replace with mainctrlpowerpos() check? - if (MainCtrlPos > 0) - { - if (TrainType != dt_ET22 || ScndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku - { - if (CoupledCtrl && ScndCtrlPos > 0) - { - ScndCtrlPos--; // wspolny wal - OK = true; - } - else - switch (EngineType) - { - case TEngineType::None: - case TEngineType::Dumb: - case TEngineType::DieselElectric: - case TEngineType::ElectricInductionMotor: - { - if ((CtrlSpeed == 1 && EngineType != TEngineType::DieselElectric) || (CtrlSpeed == 1 && EngineType == TEngineType::DieselElectric)) - { - MainCtrlPos--; - OK = true; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1 && MainCtrlActualPos != MainCtrlPos) - { - DecScndCtrl(2); - SpeedCtrlUnit.IsActive = false; - } - } - else if (CtrlSpeed > 1) - OK = DecMainCtrl(1) && DecMainCtrl(CtrlSpeed - 1); // CtrlSpeed-1); - break; - } - - case TEngineType::ElectricSeriesMotor: - { - if (CtrlSpeed == 1) /*and (ScndCtrlPos=0)*/ - { - MainCtrlPos--; - // if (MainCtrlPos=0) and (ScndCtrlPos=0) and - // (TrainType<>dt_ET40)and(TrainType<>dt_EP05) then - // StLinFlag:=false; - // if (MainCtrlPos=0) and (TrainType<>dt_ET40) and - // (TrainType<>dt_EP05) then - // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) - OK = true; - } - else if (CtrlSpeed > 1) /*and (ScndCtrlPos=0)*/ - { - OK = true; - if (RList[MainCtrlPos].R == 0) // Q: tu zrobilem = ;] - DecMainCtrl(1); - while (RList[MainCtrlPos].R > 0 && DecMainCtrl(1)) - ; // takie chamskie, potem poprawie} - } - break; - } - - case TEngineType::DieselEngine: - { - if (CtrlSpeed == 1) - { - MainCtrlPos--; - OK = true; - } - else if (CtrlSpeed > 1) - { - while (MainCtrlPos > 0 || RList[MainCtrlPos].Mn > 0) - DecMainCtrl(1); - OK = true; - } - break; - } - default: - break; - } // switch EngineType - } - } - else if (EngineType == TEngineType::WheelsDriven) - OK = AddPulseForce(-CtrlSpeed); - else - OK = false; - - if (OK) - { - ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - } - // if OK then LastRelayTime:=0; - // hunter-101012: poprawka - if (OK) - { - if (DelayCtrlFlag) - { - if (LastRelayTime >= InitialCtrlDelay) - LastRelayTime = 0; - } - else if (LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; - } - return OK; -} - -bool TMoverParameters::IsMainCtrlActualNoPowerPos() const -{ - // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlActualPos <= MainCtrlNoPowerPos(); -} - -bool TMoverParameters::IsMainCtrlNoPowerPos() const -{ - // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlPos <= MainCtrlNoPowerPos(); -} - -bool TMoverParameters::IsMainCtrlMaxPowerPos() const -{ - // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems - return MainCtrlPos == MainCtrlPosNo; -} - -int TMoverParameters::MainCtrlNoPowerPos() const -{ - - switch (EIMCtrlType) - { - case 1: - { - return 3; - } - case 2: - { - return 3 + EIMCtrlEmergencyPositions(); - } - case 3: - { - return UniCtrlNoPowerPos; - } - default: - { - return 0; - } - } -} - -int TMoverParameters::MainCtrlActualPowerPos() const -{ - - return MainCtrlActualPos - MainCtrlNoPowerPos(); -} - -int TMoverParameters::MainCtrlPowerPos() const -{ - - return MainCtrlPos - MainCtrlNoPowerPos(); -} - -int TMoverParameters::EIMCtrlEmergencyPositions() const -{ - return (EIMCtrlType == 2 && EIMCtrlMainEmergency) ? 1 : 0; -} - -bool TMoverParameters::IsMainCtrlEmergencyPos() const -{ - return MainCtrlPos < EIMCtrlEmergencyPositions(); -} - -int TMoverParameters::MainCtrlPosForCoupled() const -{ - // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from - return std::max(0, MainCtrlPos - EIMCtrlEmergencyPositions()); -} - -int TMoverParameters::MainCtrlPosFromCoupled(int const Position) const -{ - return Position + EIMCtrlEmergencyPositions(); -} - -// ************************************************************************************************* -// Q: 20160710 -// zwiększenie bocznika -// ************************************************************************************************* -bool TMoverParameters::IncScndCtrl(int CtrlSpeed) -{ - bool OK = false; - - if (DynamicBrakeFlag && TrainType == dt_ET42 && CabActive != 0 && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0) - { - OK = DynamicBrakeSwitch(false); - } - else if (ScndCtrlPosNo > 0 && CabActive != 0 && !(TrainType == dt_ET42 && (Imax == ImaxHi || (DynamicBrakeFlag && MainCtrlPowerPos() > 0)))) - { - // if (RList[MainCtrlPos].R=0) and (MainCtrlPos>0) and (ScndCtrlPos 1) - { - ScndCtrlPos = ScndCtrlPosNo; // takie chamskie, potem poprawie - } - OK = true; - } - } - else // nie mozna zmienic - OK = false; - if (OK) - { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - } - else // nie ma sterowania - OK = false; - // if OK then LastRelayTime:=0; - // hunter-101012: poprawka - if (OK && LastRelayTime > CtrlDelay) - LastRelayTime = 0; - - if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1 && MainCtrlPos > 0) - { - SpeedCtrlValue = Vel; - if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1) - { - MainCtrlActualPos = MainCtrlPos; - } - SpeedCtrlUnit.IsActive = true; - } - - if (OK && SpeedCtrl && ScndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) - { - // NOTE: round() already adds 0.5, are the ones added here as well correct? - SpeedCtrlValue = static_cast(Round(Vel)); - SpeedCtrlUnit.IsActive = true; - } - - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// zmniejszenie bocznika -// ************************************************************************************************* -bool TMoverParameters::DecScndCtrl(int CtrlSpeed) -{ - bool OK = false; - - if (IsMainCtrlNoPowerPos() && CabActive != 0 && TrainType == dt_ET42 && ScndCtrlPos == 0 && !DynamicBrakeFlag && CtrlSpeed == 1) - { - // Ra: AI wywołuje z CtrlSpeed=2 albo gdy ScndCtrlPos>0 - OK = DynamicBrakeSwitch(true); - } - else if (ScndCtrlPosNo > 0 && CabActive != 0) - { - if (ScndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !AutoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) - { - if (CtrlSpeed == 1) - { - ScndCtrlPos--; - } - else if (CtrlSpeed > 1) - { - ScndCtrlPos = 0; // takie chamskie, potem poprawie - } - OK = true; - } - else - OK = false; - if (OK) - { - /*OK:=*/SendCtrlToNext("MainCtrl", MainCtrlPosForCoupled(), CabActive); //??? - /*OK:=*/SendCtrlToNext("ScndCtrl", ScndCtrlPos, CabActive); - } - } - else - OK = false; - // if OK then LastRelayTime:=0; - // hunter-101012: poprawka - if (OK && LastRelayTime > CtrlDownDelay) - LastRelayTime = 0; - - if (OK && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo == 1) - { - SpeedCtrlValue = 0; - SpeedCtrlUnit.IsActive = false; - if (SpeedCtrlUnit.ManualStateOverride) - { - eimic = 0.0; - } - } - - if (OK && SpeedCtrl && ScndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) - { - SpeedCtrlValue = 0; - SpeedCtrlUnit.IsActive = false; - if (SpeedCtrlUnit.ManualStateOverride) - { - eimic = 0.0; - } - } - - return OK; -} - -bool TMoverParameters::IsScndCtrlLockedByMainCtrl() const -{ - // ET21, ET22, EP09: the field shunting engages only on the resistance-free positions of the master controller (eu07/maszyna#402) - return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[MainCtrlPos].R >= 0.01); -} - -void TMoverParameters::ScndCtrlResistiveLockCheck() -{ - // the shunt controller, locked in both directions on zero and the resistive positions, would otherwise stay engaged there once the - // master controller is taken back (or set from elsewhere, e.g. by the AI or another vehicle of the consist) with the shunt on - if (ScndCtrlPos > 0 && !CoupledCtrl && IsScndCtrlLockedByMainCtrl()) - { - ScndCtrlPos = 0; - } -} - -int TMoverParameters::GetVirtualScndPos() const -{ - if (TrainType == dt_ET42 && DynamicBrakeFlag && !ScndCtrlPos) - return -1; - return ScndCtrlPos; -} - -bool TMoverParameters::IsScndCtrlNoPowerPos() const -{ - // TODO: refine the check on account of potential electric series vehicles with speed control - return ScndCtrlPos == 0 || true == SpeedCtrl; -} - -bool TMoverParameters::IsScndCtrlMaxPowerPos() const -{ - // TODO: refine the check on account of potential electric series vehicles with speed control - return ScndCtrlPos == ScndCtrlPosNo || true == SpeedCtrl; -} - -// ************************************************************************************************* -// Q: 20160710 -// załączenie rozrządu -// ************************************************************************************************* -bool TMoverParameters::CabActivisation(bool const Enforce) -{ - bool OK = false; - - OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie - if (OK) - { - CabActive = CabOccupied; // sterowanie jest z kabiny z obsadą - DirAbsolute = DirActive * CabActive; - CabMaster = true; - SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection - SendCtrlToNext("CabActivisation", 1, CabActive); - SendCtrlToNext("Direction", DirActive, CabActive); - if (InactiveCabFlag & activation::springbrakeoff) - { - SpringBrakeActivate(false); - } - } - return OK; -} - -bool TMoverParameters::CabActivisationAuto(bool const Enforce) -{ - bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false; - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// wyłączenie rozrządu -// ************************************************************************************************* -bool TMoverParameters::CabDeactivisation(bool const Enforce) -{ - bool OK = false; - - OK = Enforce || IsCabMaster(); // o ile obsada jest w kabinie ze sterowaniem - if (OK) - { - if (InactiveCabFlag & activation::springbrakeon) - { - SpringBrakeActivate(true); - } - if (InactiveCabFlag & activation::pantographsup) - { - InactiveCabPantsCheck = true; - } - if (InactiveCabFlag & activation::doorpermition) - { - PermitDoors(side::right, true, range_t::consist); - PermitDoors(side::left, true, range_t::consist); - } - if (InactiveCabFlag & activation::neutraldirection) - { - DirActive = 0; - SendCtrlToNext("Direction", 0, CabActive); - } - - CabActive = 0; - DirAbsolute = DirActive * CabActive; - CabMaster = false; - DepartureSignal = false; // nie buczeć z nieaktywnej kabiny - SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection - - SendCtrlToNext("CabActivisation", 0, CabOccupied); // CabActive==0! - } - return OK; -} - -bool TMoverParameters::CabDeactivisationAuto(bool const Enforce) -{ - bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false; - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// Siła napędzająca drezynę po naciśnięciu wajhy -// ************************************************************************************************* -bool TMoverParameters::AddPulseForce(int Multipler) -{ - bool APF; - if (EngineType == TEngineType::WheelsDriven && EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - { - DirActive = CabActive; - DirAbsolute = DirActive * CabActive; - if (Vel > 0) - PulseForce = std::min(1000.0 * Power / (abs(V) + 0.1), Ftmax); - else - PulseForce = Ftmax; - if (PulseForceCount > 1000.0) - PulseForce = 0; - else - PulseForce = PulseForce * Multipler; - PulseForceCount = PulseForceCount + abs(Multipler); - APF = PulseForce > 0; - } - else - APF = false; - return APF; -} - -// ************************************************************************************************* -// yB: 20190909 -// sypanie piasku reczne -// ************************************************************************************************* -bool TMoverParameters::SandboxManual(bool const State, range_t const Notify) -{ - bool result{false}; - - if (SandDoseManual != State) - { - if (SandDoseManual == false) - { - // switch on - if (Sand > 0) - { - SandDoseManual = true; - result = true; - } - } - else - { - // switch off - SandDoseManual = false; - result = true; - } - } - - Sandbox(SandDoseManual || SandDoseAuto, Notify); - - return result; -} - -// ************************************************************************************************* -// yB: 20190909 -// sypanie piasku automatyczne -// ************************************************************************************************* -bool TMoverParameters::SandboxAuto(bool const State, range_t const Notify) -{ - bool result{false}; - if (bool NewState = State && SandDoseAutoAllow; SandDoseAuto != NewState) - { - if (SandDoseAuto == false) - { - // switch on - if (Sand > 0) - { - SandDoseAuto = true; - result = true; - } - } - else - { - // switch off - SandDoseAuto = false; - result = true; - } - } - - Sandbox(SandDoseManual || SandDoseAuto, Notify); - - return result; -} - -// ************************************************************************************************* -// Q: 20160713 -// sypanie piasku -// ************************************************************************************************* -bool TMoverParameters::Sandbox(bool const State, range_t const Notify) -{ - bool result{false}; - - if (SandDose != State) - { - if (SandDose == false) - { - // switch on - if (Sand > 0 && DirActive != 0) - { - SandDose = true; - result = true; - } - } - else - { - // switch off - SandDose = false; - result = true; - } - } - - if (Notify != range_t::local) - { - // if requested pass the command on - auto const couplingtype = Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control; - - if (State == true) - { - // switch on - SendCtrlToNext("Sandbox", 1, CabActive, couplingtype); - } - else - { - // switch off - SendCtrlToNext("Sandbox", 0, CabActive, couplingtype); - } - } - - return result; -} - -// ************************************************************************************************* -// yB: 20190909 -// włączenie / wyłączenie automatycznej piasecznicy -// ************************************************************************************************* -bool TMoverParameters::SandboxAutoAllow(bool State) -{ - // SendCtrlToNext("SandboxAutoAllow", int(State), CabActive, ctrain_controll); - - if (SandDoseAutoAllow != State) - { - SandDoseAutoAllow = State; - return true; - } - else - return false; -} - -// ***************************************************************************** -// Q: 20160710 -// zbicie czuwaka / SHP -// ***************************************************************************** -// hunter-091012: rozbicie alarmow, dodanie testu czuwaka -void TMoverParameters::SecuritySystemReset(void) // zbijanie czuwaka/SHP -{ - // reset all, used by AI - SecuritySystem.acknowledge_press(); - SecuritySystem.acknowledge_release(); - SecuritySystem.cabsignal_reset(); -} - -// ************************************************************************************************* -// Q: 20160711 -// sprawdzanie stanu CA/SHP -// ************************************************************************************************* -void TMoverParameters::SecuritySystemCheck(double dt) -{ - bool isPower = Power24vIsAvailable || Power110vIsAvailable; - // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) - SecuritySystem.set_shunt_mode(ShuntMode); - SecuritySystem.update(dt, Vel, isPower, CabActive); - - if (!Battery || !Radio || !RadioFuse) - { // wyłączenie baterii deaktywuje sprzęt - RadiostopSwitch(false); - } -} - -// ************************************************************************************************* -// Q: 20160710 -// włączenie / wyłączenie baterii -// ************************************************************************************************* -bool TMoverParameters::BatterySwitch(bool State, range_t const Notify) -{ - using enum range_t; - auto const initialstate{Battery}; - - // Ra: ukrotnienie załączania baterii jest jakąś fikcją... - if (BatteryStart == start_t::manual) - { - Battery = State; - } - - // switching batteries does not require activation - if (Notify != local) - { - SendCtrlToNext("BatterySwitch", State ? 1 : 0, 1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); - SendCtrlToNext("BatterySwitch", State ? 1 : 0, -1, Notify == unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Battery != initialstate; -} - -// ************************************************************************************************* -// Q: 20160710 -// włączenie / wyłączenie hamulca elektro-pneumatycznego -// ************************************************************************************************* -bool TMoverParameters::EpFuseSwitch(bool State) -{ - if (EpFuse != State) - { - EpFuse = State; - return true; - } - else - return false; - // if (EpFuse == true) SendCtrlToNext("EpFuseSwitch", 1, CabActive) - // else SendCtrlToNext("EpFuseSwitch", 0, CabActive); -} - -// ************************************************************************************************* -// yB: 20190906 -// włączenie / wyłączenie hamulca sprezynowego -// ************************************************************************************************* -bool TMoverParameters::SpringBrakeActivate(bool State) -{ - if (Power24vIsAvailable || Power110vIsAvailable) - { - SendCtrlToNext("SpringBrakeActivate", int(State), CabActive, SpringBrake.MultiTractionCoupler); - - if (SpringBrake.Activate != State) - { - SpringBrake.Activate = State; - return true; - } - } - return false; -} - -// ************************************************************************************************* -// yB: 20190906 -// włączenie / wyłączenie odciecia hamulca sprezynowego -// ************************************************************************************************* -bool TMoverParameters::SpringBrakeShutOff(bool State) -{ - if (SpringBrake.ShuttOff != State) - { - SpringBrake.ShuttOff = State; - return true; - } - else - return false; -} - -// ************************************************************************************************* -// yB: 20190906 -// wyluzowanie hamulca sprezynowego -// ************************************************************************************************* -bool TMoverParameters::SpringBrakeRelease() -{ - if (SpringBrake.IsReady && SpringBrake.Cylinder->P() < SpringBrake.MinForcePressure) - { - SpringBrake.IsReady = false; - return true; - } - else - return false; -} - -// ************************************************************************************************* -// Q: 20160710 -// kierunek do tyłu -// ************************************************************************************************* -bool TMoverParameters::DirectionBackward(void) -{ - if (false == EIMDirectionChangeAllow()) - { - return false; - } - - if (DirActive == 1 && MainCtrlPos == 0 && TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) - { - return true; - } - if (MainCtrlPosNo > 0 && DirActive > -1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) - { - if (EngineType == TEngineType::WheelsDriven) - --CabActive; - // else - --DirActive; - DirAbsolute = DirActive * CabActive; - SendCtrlToNext("Direction", DirActive, CabActive); - return true; - } - - return false; -} - -bool TMoverParameters::EIMDirectionChangeAllow(void) const -{ - bool OK = false; - /* - // NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module - OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimic_real <= 0) && (Vel < 0.1))); - */ - OK = MainCtrlPos <= MainCtrlMaxDirChangePos; - return OK; -} - -// ************************************************************************************************* -// Q: 20160710 -// załączenie przycisku przeciwpoślizgowego -// ************************************************************************************************* -bool TMoverParameters::AntiSlippingButton(void) -{ - // NOTE: disabled the sandbox part, it's already controlled by another part of the AI routine - return AntiSlippingBrake() /*|| Sandbox(true)*/; -} - -// water pump breaker state toggle -bool TMoverParameters::WaterPumpBreakerSwitch(bool State, range_t const Notify) -{ - /* - if( FuelPump.start_type == start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - return false; - } - */ - bool const initialstate{WaterPump.breaker}; - - WaterPump.breaker = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterPumpBreakerSwitch", WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterPump.breaker != initialstate; -} - -// water pump state toggle -bool TMoverParameters::WaterPumpSwitch(bool State, range_t const Notify) -{ - - if (WaterPump.start_type == start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{WaterPump.is_enabled}; - - WaterPump.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterPumpSwitch", WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterPump.is_enabled != initialstate; -} - -// water pump state toggle -bool TMoverParameters::WaterPumpSwitchOff(bool State, range_t const Notify) -{ - - if (WaterPump.start_type == start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{WaterPump.is_disabled}; - - WaterPump.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterPumpSwitchOff", WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterPump.is_disabled != initialstate; -} - -// water heater breaker state toggle -bool TMoverParameters::WaterHeaterBreakerSwitch(bool State, range_t const Notify) -{ - /* - if( FuelPump.start_type == start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - return false; - } - */ - bool const initialstate{WaterHeater.breaker}; - - WaterHeater.breaker = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterHeaterBreakerSwitch", WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterHeater.breaker != initialstate; -} - -// water heater state toggle -bool TMoverParameters::WaterHeaterSwitch(bool State, range_t const Notify) -{ - /* - if( FuelPump.start_type == start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - return false; - } - */ - bool const initialstate{WaterHeater.is_enabled}; - - WaterHeater.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterHeaterSwitch", WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterHeater.is_enabled != initialstate; -} - -// water circuits link state toggle -bool TMoverParameters::WaterCircuitsLinkSwitch(bool State, range_t const Notify) -{ - - if (false == dizel_heat.auxiliary_water_circuit) - { - // can't link the circuits if the vehicle only has one - return false; - } - - bool const initialstate{WaterCircuitsLink}; - - WaterCircuitsLink = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("WaterCircuitsLinkSwitch", WaterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return WaterCircuitsLink != initialstate; -} - -// fuel pump state toggle -bool TMoverParameters::FuelPumpSwitch(bool State, range_t const Notify) -{ - - if (FuelPump.start_type == start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{FuelPump.is_enabled}; - - FuelPump.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("FuelPumpSwitch", FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return FuelPump.is_enabled != initialstate; -} - -bool TMoverParameters::FuelPumpSwitchOff(bool State, range_t const Notify) -{ - - if (FuelPump.start_type == start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - return false; - } - - bool const initialstate{FuelPump.is_disabled}; - - FuelPump.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("FuelPumpSwitchOff", FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return FuelPump.is_disabled != initialstate; -} - -// oil pump state toggle -bool TMoverParameters::OilPumpSwitch(bool State, range_t const Notify) -{ - - if (OilPump.start_type == start_t::automatic) - { - // automatic pump ignores 'manual' state commands - return false; - } - - bool const initialstate{OilPump.is_enabled}; - - OilPump.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("OilPumpSwitch", OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return OilPump.is_enabled != initialstate; -} - -bool TMoverParameters::OilPumpSwitchOff(bool State, range_t const Notify) -{ - - if (OilPump.start_type == start_t::automatic) - { - // automatic pump ignores 'manual' state commands - return false; - } - - bool const initialstate{OilPump.is_disabled}; - - OilPump.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("OilPumpSwitchOff", OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return OilPump.is_disabled != initialstate; -} - -bool TMoverParameters::MotorBlowersSwitch(bool State, end const Side, range_t const Notify) -{ - - auto &fan{MotorBlowers[Side]}; - - if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - return false; - } - - bool const initialstate{fan.is_enabled}; - - fan.is_enabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitch" : "MotorBlowersRearSwitch", fan.is_enabled ? 1 : 0, CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return fan.is_enabled != initialstate; -} - -bool TMoverParameters::MotorBlowersSwitchOff(bool State, end const Side, range_t const Notify) -{ - - auto &fan{MotorBlowers[Side]}; - - if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - return false; - } - - bool const initialstate{fan.is_disabled}; - - fan.is_disabled = State; - - if (Notify != range_t::local) - { - SendCtrlToNext(Side == end::front ? "MotorBlowersFrontSwitchOff" : "MotorBlowersRearSwitchOff", fan.is_disabled ? 1 : 0, CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return fan.is_disabled != initialstate; -} - -bool TMoverParameters::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("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 TMoverParameters::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("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 TMoverParameters::MainSwitch(bool const State, range_t const Notify) -{ - - bool const initialstate{Mains || dizel_startup}; - - MainSwitch_(State); - - if (Notify != range_t::local) - { - // pass the command to other vehicles - // TBD: pass the requested state, or the actual state? - SendCtrlToNext("MainSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return (Mains || dizel_startup) != initialstate; -} - -void TMoverParameters::MainSwitch_(bool const State) -{ - - if (Mains == State || MainCtrlPosNo == 0) - { - // nothing to do - return; - } - - bool const initialstate{Mains}; - - if (false == State || true == MainSwitchCheck()) - { - - if (true == State) - { - // switch on - if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) - { - // launch diesel engine startup procedure - dizel_startup = true; - } - else - { - // additional check, as vehicles without pantographs won't fail relay checks earlier - Mains = true; - } - } - else - { - Mains = false; - // 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 (Mains != initialstate) - { - LastSwitchingTime = 0; - Timer::subsystem.switching.note(Timer::switching_counter::mains, this, &TypeName, &Name); - } - } -} - -bool TMoverParameters::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{true}; - - switch (EngineType) - { - case DieselElectric: - case DieselEngine: - case Dumb: - { - powerisavailable = Power24vIsAvailable; - break; - } - case ElectricSeriesMotor: - case ElectricInductionMotor: - { - // TODO: check whether we can simplify this check and skip the outer EngineType switch - // closed ahead of the pantographs, the line breaker runs on the low voltage circuits - powerisavailable = PantographsRequireMains ? Power24vIsAvailable || Power110vIsAvailable : EnginePowerSourceVoltage() > 0.5 * EnginePowerSource.MaxVoltage; - break; - } - default: - { - break; - } - } - - return powerisavailable && (ScndCtrlPos == 0 || EngineType == ElectricInductionMotor) && MainsInitTimeCountdown <= 0.0 && - (ConvOvldFlag == false || ConverterOverloadRelayOffWhenMainIsOff) && true == GroundRelay && (true == NoVoltRelay || PantographsRequireMains) && true == OvervoltageRelay && - LastSwitchingTime > CtrlDelay && - (HasCamshaft ? IsMainCtrlActualNoPowerPos() : - LineBreakerClosesOnlyAtNoPowerPos ? IsMainCtrlNoPowerPos() : - true) && - false == TestFlag(DamageFlag, dtrain_out) && false == TestFlag(EngDmgFlag, 1); -} - -// ************************************************************************************************* -// Q: 20160713 -// włączenie / wyłączenie przetwornicy -// ************************************************************************************************* -bool TMoverParameters::ConverterSwitch(bool State, range_t const Notify) -{ - - auto const initialstate{ConverterAllow}; - - if (ConverterStart == start_t::manual) - { - ConverterAllow = State; - } - - if (Notify != range_t::local) - { - SendCtrlToNext("ConverterSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return ConverterAllow != initialstate; -} - -// ************************************************************************************************* -// Q: 20160713 -// włączenie / wyłączenie sprężarki -// ************************************************************************************************* -bool TMoverParameters::CompressorSwitch(bool State, range_t const Notify) -{ - - if (CompressorStart != start_t::manual) - { - // only pay attention if the compressor can be controlled manually - return false; - } - - auto const initialstate{CompressorAllow}; - - if (VeselVolume > 0.0 && CompressorSpeed > 0.0) - { - CompressorAllow = State; - } - - if (Notify != range_t::local) - { - SendCtrlToNext("CompressorSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return CompressorAllow != initialstate; -} - -bool TMoverParameters::ChangeCompressorPreset(int const State, range_t const Notify) -{ - - auto const initialstate{CompressorListPos}; - - CompressorListPos = safe_clamp(State, 0, CompressorListPosNo); - - if (Notify != range_t::local) - { - SendCtrlToNext("CompressorPreset", State, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return CompressorListPos != initialstate; -} - -bool TMoverParameters::HeatingSwitch(bool const State, range_t const Notify) -{ - - bool const initialstate{HeatingAllow}; - - HeatingSwitch_(State); - - if (Notify != range_t::local) - { - // pass the command to other vehicles - // TBD: pass the requested state, or the actual state? - SendCtrlToNext("HeatingSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return HeatingAllow != initialstate; -} - -void TMoverParameters::HeatingSwitch_(bool const State) -{ - - // TBD, TODO: activation dependencies? - HeatingAllow = State; -} - -// returns voltage of defined main engine power source -double TMoverParameters::EnginePowerSourceVoltage() const -{ - - return EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : - EnginePowerSource.SourceType == TPowerSource::Accumulator ? Power24vVoltage : - 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 TMoverParameters::MainCircuitPowered() const -{ - if (false == Mains) - { - return false; - } - if (false == PantographsRequireMains || 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() >= EnginePowerSource.CollectorParameters.MinV; -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie nastawy hamulca -// ************************************************************************************************* -bool TMoverParameters::IncBrakeLevelOld(void) -{ - bool IBLO = false; - - if (BrakeCtrlPosNo > 0) - { - if (BrakeCtrlPos < BrakeCtrlPosNo) - { - ++BrakeCtrlPos; - // youBy: EP po nowemu - IBLO = true; - if (BrakePressureActual.PipePressureVal < 0 && BrakePressureTable[BrakeCtrlPos - 1].PipePressureVal > 0) - LimPipePress = PipePress; - } - else - { - IBLO = false; - } - } - - return IBLO; -} - -// ***************************************************************************** -// Q: 20160711 -// zmniejszenie nastawy hamulca -// ***************************************************************************** -bool TMoverParameters::DecBrakeLevelOld(void) -{ - bool DBLO = false; - - if (BrakeCtrlPosNo > 0) - { - if (BrakeCtrlPos > (BrakeHandle == TBrakeHandle::FV4a ? -2 : -1)) - { - --BrakeCtrlPos; - // youBy: EP po nowemu - DBLO = true; - // if ((BrakePressureTable[BrakeCtrlPos].PipePressureVal<0.0) && - // (BrakePressureTable[BrakeCtrlPos+1].PipePressureVal > 0)) - // LimPipePress=PipePress; - } - else - DBLO = false; - } - - return DBLO; -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie nastawy hamulca pomocnicznego -// ************************************************************************************************* -bool TMoverParameters::IncLocalBrakeLevel(float const CtrlSpeed) -{ - bool IBL; - if (LocalBrakePosA < 1.0 /*and (BrakeCtrlPos<1)*/) - { - LocalBrakePosA = std::min(1.0, LocalBrakePosA + CtrlSpeed / LocalBrakePosNo); - IBL = true; - } - else - IBL = false; - - return IBL; -} - -// ************************************************************************************************* -// Q: 20160711 -// zmniejszenie nastawy hamulca pomocniczego -// ************************************************************************************************* -bool TMoverParameters::DecLocalBrakeLevel(float const CtrlSpeed) -{ - bool DBL; - if (LocalBrakePosA > 0) - { - LocalBrakePosA = std::max(0.0, LocalBrakePosA - CtrlSpeed / LocalBrakePosNo); - DBL = true; - } - else - DBL = false; - - return DBL; -} - -// ************************************************************************************************* -// zwiększenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// uzywane gdy SplitEDPneumaticBrake = true -// ************************************************************************************************* -bool TMoverParameters::IncDynamicBrakeLevel(float const CtrlSpeed) -{ - if (false == SplitEDPneumaticBrake) - return false; - if (DynamicBrakeCtrlPosNo < 1) - return false; - if (DynamicBrakeCtrlPos < 1.0) - { - DynamicBrakeCtrlPos = std::min(1.0, DynamicBrakeCtrlPos + (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); - return true; - } - return false; -} - -// ************************************************************************************************* -// zmniejszenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// ************************************************************************************************* -bool TMoverParameters::DecDynamicBrakeLevel(float const CtrlSpeed) -{ - if (false == SplitEDPneumaticBrake) - return false; - if (DynamicBrakeCtrlPosNo < 1) - return false; - if (DynamicBrakeCtrlPos > 0.0) - { - DynamicBrakeCtrlPos = std::max(0.0, DynamicBrakeCtrlPos - (double)CtrlSpeed / (double)DynamicBrakeCtrlPosNo); - return true; - } - return false; -} - -// ************************************************************************************************* -// bezposrednie ustawienie nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// ************************************************************************************************* -bool TMoverParameters::DynamicBrakeLevelSet(double Position) -{ - if (false == SplitEDPneumaticBrake) - return false; - DynamicBrakeCtrlPos = std::clamp(Position, 0.0, 1.0); - return true; -} - -// ************************************************************************************************* -// odczyt nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) -// zwraca 0 jezeli SplitEDPneumaticBrake nie jest aktywne (dla zachowania starej logiki) -// ************************************************************************************************* -double TMoverParameters::DynamicBrakeRatio(void) const -{ - if (false == SplitEDPneumaticBrake) - return 0.0; - return std::clamp(DynamicBrakeCtrlPos, 0.0, 1.0); -} - -// ************************************************************************************************* -// czy hamulec ED jest aktualnie dostepny w oknie predkosci Vh0..Vh1 -// ************************************************************************************************* -bool TMoverParameters::DynamicBrakeAvailable(void) const -{ - double const vh0{eimc[eimc_p_Vh0]}; - if (double const vh1{eimc[eimc_p_Vh1]}; vh1 <= 0.001) - { - // brak zdefiniowanej strefy - ED dziala zawsze - return true; - } - // strefa wylaczenia jest definiowana przez Vh0 (minimum); powyzej Vh0 ED dziala - return Vel >= vh0; -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie nastawy hamulca ręcznego -// ************************************************************************************************* -bool TMoverParameters::IncManualBrakeLevel(int CtrlSpeed) -{ - bool IMBL; - if (ManualBrakePos < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ - { - while (ManualBrakePos < ManualBrakePosNo && CtrlSpeed > 0) - { - ManualBrakePos++; - CtrlSpeed--; - } - IMBL = true; - } - else - IMBL = false; - - return IMBL; -} - -// ************************************************************************************************* -// Q: 20160711 -// zmniejszenie nastawy hamulca ręcznego -// ************************************************************************************************* -bool TMoverParameters::DecManualBrakeLevel(int CtrlSpeed) -{ - bool DMBL; - if (ManualBrakePos > 0) - { - while (CtrlSpeed > 0 && ManualBrakePos > 0) - { - ManualBrakePos--; - CtrlSpeed--; - } - DMBL = true; - } - else - DMBL = false; - return DMBL; -} - -// ************************************************************************************************* -// Q: 20160713 -// reczne przelaczanie hamulca elektrodynamicznego -// ************************************************************************************************* -bool TMoverParameters::DynamicBrakeSwitch(bool Switch) -{ - bool DBS; - - if (DynamicBrakeType == dbrake_switch && IsMainCtrlNoPowerPos()) - { - DynamicBrakeFlag = Switch; - DBS = true; - for (auto &thiscoupler : Couplers) - // with Couplers[b] do - if (TestFlag(thiscoupler.CouplingFlag, coupling::control)) - thiscoupler.Connected->DynamicBrakeFlag = Switch; - // end; - // if (DynamicBrakeType=dbrake_passive) and (TrainType=dt_ET42) then - // begin - // DynamicBrakeFlag:=false; - // DynamicBrakeSwitch:=false; - } - else - DBS = false; - - return DBS; -} - -// ************************************************************************************************* -// Q: 20160711 -// włączenie / wyłączenie hamowania awaryjnego -// ************************************************************************************************* -bool TMoverParameters::RadiostopSwitch(bool Switch) -{ - bool EBS; - if (BrakeSystem != TBrakeSystem::Individual && BrakeCtrlPosNo > 0) - { - - if (true == Switch && false == RadioStopFlag) - { - RadioStopFlag = Switch; - EBS = true; - } - else - { - if (Switch == false && std::abs(V) < 0.1) - { - // odblokowanie hamulca bezpieczenistwa tylko po zatrzymaniu - RadioStopFlag = Switch; - EBS = true; - } - else - { - EBS = false; - } - } - } - else - { - // nie ma hamulca bezpieczenstwa gdy nie ma hamulca zesp. - EBS = false; - } - - return EBS; -} - -bool TMoverParameters::AlarmChainSwitch(bool const State) -{ - - if (AlarmChainFlag != State) - { - // simple routine for the time being - AlarmChainFlag = State; - return true; - } - return false; -} - -// ************************************************************************************************* -// Q: 20160710 -// hamowanie przeciwpoślizgowe -// ************************************************************************************************* -bool TMoverParameters::AntiSlippingBrake(void) -{ - bool ASB = false; // Ra: przeniesione z końca - if (ASBType == 1) - { - ASB = true; // SPKS!! - Hamulec->ASB(1); - BrakeSlippingTimer = 0; - } - return ASB; -} - -// ************************************************************************************************* -// Q: 20160711 -// włączenie / wyłączenie odluźniacza -// ************************************************************************************************* -bool TMoverParameters::BrakeReleaser(int state) -{ - bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 - if (state != 0) - { - // additional limitations imposed by pressure switch - if (false == ControlPressureSwitch || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) - { - Hamulec->Releaser(state); - } - } - else - { - Hamulec->Releaser(state); - } - if (CabActive != 0) // rekurencyjne wysłanie do następnego - OK = SendCtrlToNext("BrakeReleaser", state, CabActive); - return OK; -} - -// ************************************************************************************************* -// yB: 20160711 -// włączenie / wyłączenie uniwersalnego przycisku hamulcowego -// ************************************************************************************************* -bool TMoverParameters::UniversalBrakeButton(int button, int state) -{ - bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 - UniversalBrakeButtonActive[button] = state > 0; - int flag = 0; - if (Power24vIsAvailable || Power110vIsAvailable) - { - for (int i = 0; i < 3; i++) - { - flag = flag | (UniversalBrakeButtonActive[i] ? UniversalBrakeButtonFlag[i] : 0); - } - } - - Hamulec->SetUniversalFlag(flag); - Handle->SetUniversalFlag(flag); - LocHandle->SetUniversalFlag(flag); - UnlockPipe = (flag & TUniversalBrake::ub_UnlockPipe) > 0; - - // if the releaser can be activated by switch - if (TestFlag(UniversalBrakeButtonFlag[0] & UniversalBrakeButtonFlag[1] & UniversalBrakeButtonFlag[2], TUniversalBrake::ub_Release)) - { - BrakeReleaser(TestFlag(flag, TUniversalBrake::ub_Release) ? 1 : 0); - } - return OK; -} - -// ************************************************************************************************* -// Q: 20160711 -// włączenie / wyłączenie hamulca elektro-pneumatycznego -// ************************************************************************************************* -bool TMoverParameters::SwitchEPBrake(int state) -{ - bool OK; - - OK = false; - if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0) - { - // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is - if (state > 0 && EPBrakeControlPowered()) - EpForce = Handle->GetEP(); // TODO: przetlumaczyc - else - EpForce = 0; - Hamulec->SetEPS(EpForce); - SendCtrlToNext("Brake", EpForce, CabActive); - } - // OK:=SetFlag(BrakeStatus,((2*State-1)*b_epused)); - // SendCtrlToNext('Brake',(state*(2*BrakeCtrlPos-1)),CabActive); - return OK; -} - -bool TMoverParameters::EPBrakeControlPowered() const -{ - return Power24vIsAvailable && DirActive != 0 && EpFuse; -} - -// ************************************************************************************************* -// Q: 20160711 -// zwiększenie ciśnienia hamowania -// ************************************************************************************************* -bool TMoverParameters::IncBrakePress(double &brake, double PressLimit, double dp) -{ - bool IBP; - // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and - // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then - if (DynamicBrakeType != dbrake_switch && DynamicBrakeType != dbrake_none && BrakePress > 2.0 && TrainType != dt_EZT) // yB radzi nie sprawdzać ciśnienia w przewodzie - // hunter-301211: dla EN57 silnikow nie odlaczamy - { - DynamicBrakeFlag = true; // uruchamianie hamulca ED albo odlaczanie silnikow - if (DynamicBrakeType == dbrake_automatic && abs(Im) > 60) // nie napelniaj wiecej, jak na EP09 - dp = 0.0; - } - if (brake + dp < PressLimit) - { - brake = brake + dp; - IBP = true; - } - else - { - IBP = false; - brake = PressLimit; - } - return IBP; -} - -// ************************************************************************************************* -// Q: 20160711 -// zmniejszenie ciśnienia hamowania -// ************************************************************************************************* -bool TMoverParameters::DecBrakePress(double &brake, double PressLimit, double dp) -{ - bool DBP; - - if (brake - dp > PressLimit) - { - brake = brake - dp; - DBP = true; - } - else - { - DBP = false; - brake = PressLimit; - } - // if ((DynamicBrakeType != dbrake_switch) && ((BrakePress < 0.1) && (PipePress > 0.45 - // /*(LowPipePress+0.06)*/ ))) - if (DynamicBrakeType != dbrake_switch && BrakePress < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie - DynamicBrakeFlag = false; // wylaczanie hamulca ED i/albo zalaczanie silnikow - - return DBP; -} - -// ************************************************************************************************* -// Q: 20160711 -// przełączenie nastawy hamulca O/P/T -// ************************************************************************************************* -bool TMoverParameters::BrakeDelaySwitch(int BDS) -{ - bool rBDS; - if (Hamulec->SetBDF(BDS)) - { - BrakeDelayFlag = BDS; - rBDS = true; - Hamulec->SetBrakeStatus(Hamulec->GetBrakeStatus() & ~64); - // kopowanie nastawy hamulca do kolejnego czlonu - do przemyślenia - if (CabActive != 0) - SendCtrlToNext("BrakeDelay", BrakeDelayFlag, CabActive); - } - else - rBDS = false; - - return rBDS; -} - -// ************************************************************************************************* -// Q: 20160712 -// zwiększenie przełożenia hamulca -// ************************************************************************************************* -bool TMoverParameters::IncBrakeMult(void) -{ - bool IBM; - - if (LoadFlag > 0 && MBPM < 2 && LoadFlag < 3) - { - if (MaxBrakePress[2] > 0 && LoadFlag == 1) - LoadFlag = 2; - else - LoadFlag = 3; - IBM = true; - if (BrakeCylMult[2] > 0) - BrakeCylMult[0] = BrakeCylMult[2]; - } - else - IBM = false; - - return IBM; -} - -// ************************************************************************************************* -// Q: 20160712 -// zmniejszenie przełożenia hamulca -// ************************************************************************************************* -bool TMoverParameters::DecBrakeMult(void) -{ - bool DBM; - if (LoadFlag > 1 && MBPM < 2) - { - if (MaxBrakePress[2] > 0 && LoadFlag == 3) - LoadFlag = 2; - else - LoadFlag = 1; - DBM = true; - if (BrakeCylMult[1] > 0) - BrakeCylMult[0] = BrakeCylMult[1]; - } - else - DBM = false; - - return DBM; -} - -// ************************************************************************************************* -// Q: 20160712 -// zaktualizowanie ciśnienia w hamulcach -// ************************************************************************************************* -void TMoverParameters::UpdateBrakePressure(double dt) -{ - // const double LBDelay = 5.0; // stala czasowa hamulca - // double Rate, Speed, dp, sm; - - dpLocalValve = 0; - dpBrake = 0; - - Hamulec->ForceLeak(dt * AirLeakRate * 0.25); // fake air leaks from brake system reservoirs - - BrakePress = Hamulec->GetBCP(); - // BrakePress:=(Hamulec as TEst4).ImplsRes.pa; - Volume = Hamulec->GetBRP(); -} - -// ************************************************************************************************* -// Q: 20160712 -// Obliczanie pracy sprężarki -// ************************************************************************************************* -void TMoverParameters::CompressorCheck(double dt) -{ - - if (CompressorSpeed == 0.0) - { - CompressorAllow = false; - return; - } - - if (CabDependentCompressor) - { - if (CabActive > 0) - { - MinCompressor = MinCompressor_cabA; - MaxCompressor = MaxCompressor_cabA; - } - if (CabActive < 0) - { - MinCompressor = MinCompressor_cabB; - MaxCompressor = MaxCompressor_cabB; - } - } - - // EmergencyValve - EmergencyValveOpen = Compressor > (EmergencyValveOpen ? EmergencyValveOff : EmergencyValveOn); - if (EmergencyValveOpen) - { - auto dV = static_cast(PF(0, Compressor, EmergencyValveArea) * dt); - CompressedVolume -= dV; - } - - CompressedVolume = std::max(0.0, CompressedVolume - dt * AirLeakRate * 0.1); // nieszczelności: 0.001=1l/s - - Compressor = CompressedVolume / VeselVolume; - - // assorted operational logic - auto const MaxCompressorF{CompressorList[TCompressorList::cl_MaxFactor][CompressorListPos] * MaxCompressor}; - auto const MinCompressorF{CompressorList[TCompressorList::cl_MinFactor][CompressorListPos] * MinCompressor}; - auto const CompressorSpeedF{CompressorList[TCompressorList::cl_SpeedFactor][CompressorListPos] * CompressorSpeed}; - // checking the impact on the compressor allowance - if (auto const AllowFactor{CompressorList[TCompressorList::cl_Allow][CompressorListPos]}; AllowFactor > 0.5) - { - CompressorAllow = AllowFactor > 1.5; - } - - switch (CompressorPower) - { - case 2: - { - CompressorAllow = ConverterAllow; - break; - } - case 3: - { - // HACK: make sure compressor coupled with diesel engine is always ready for work - CompressorStart = start_t::automatic; - break; - } - default: - { - break; - } - } - - // the main circuit, also for a compressor driven by the engine, otherwise the low voltage - auto const compressorpower{CompressorPower == 0 || CompressorPower == 3 ? MainCircuitPowered() : Power110vIsAvailable}; - CompressorPowerTime = compressorpower ? CompressorPowerTime + dt : 0.0; - auto const compressorready{compressorpower && CompressorPowerTime >= CompressorStartDelay}; - // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device - auto const compressorenable{CompressorAllowLocal && (CompressorStart == start_t::automatic || CompressorAllow)}; - auto const compressordisable{false == compressorenable}; - - auto const pressureistoolow{Compressor < MinCompressorF}; - auto const pressureistoohigh{Compressor > MaxCompressorF}; - - // TBD, TODO: break the lock with no low voltage power? - auto const governorlockispresent{MaxCompressorF - MinCompressorF > 0.0001}; - CompressorGovernorLock = governorlockispresent && false == pressureistoolow // unlock if pressure drops below minimal threshold - && (pressureistoohigh || CompressorGovernorLock); // lock if pressure goes above maximum threshold - // for these multi-unit engines compressors turn off whenever any of them was affected by the governor - // NOTE: this is crude implementation, limited only to adjacent vehicles - // TODO: re-implement when a more elegant/flexible system is in place - auto const coupledgovernorlock{ - (Couplers[end::rear].Connected != nullptr && true == TestFlag(Couplers[end::rear].CouplingFlag, coupling::permanent) && Couplers[end::rear].Connected->CompressorGovernorLock) || - (Couplers[end::front].Connected != nullptr && true == TestFlag(Couplers[end::front].CouplingFlag, coupling::permanent) && Couplers[end::front].Connected->CompressorGovernorLock)}; - auto const governorlock{CompressorGovernorLock || coupledgovernorlock}; - - auto const compressorflag{CompressorFlag}; - CompressorFlag = - compressorready && false == compressordisable && (false == governorlock || CompressorPower == 3) && (CompressorFlag || (compressorenable && LastSwitchingTime > CtrlDelay)); - - if (CompressorFlag && CompressorFlag != compressorflag) - { - // jeśli została załączona to trzeba ograniczyć ponowne włączenie - LastSwitchingTime = 0; - } - if (CompressorFlag != compressorflag) - { - Timer::subsystem.switching.note(CompressorFlag ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); - } - - if (false == CompressorFlag) - { - return; - } - - // working compressor adds air to the air reservoir - if (CompressorPower == 3) - { - // the compressor is coupled with the diesel engine, engine revolutions affect the output - CompressedVolume += - CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * EngineRPMRatio() * dt * (CompressorGovernorLock ? 0.0 : 1.0); // with the lock active air is vented out - } - else - { - // the compressor is a stand-alone device, working at steady pace - CompressedVolume += CompressorSpeedF * (2.0 * MaxCompressorF - Compressor) / MaxCompressorF * dt; - } - - if (pressureistoohigh && (false == governorlockispresent || CompressorPower == 3)) - { - // vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level - SetFlag(SoundFlag, sound::relay | sound::loud); - auto ventedfraction{0.999}; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly - if (false == governorlockispresent) - { - ventedfraction = 0.80; // arbitrary amount - } - else if (CompressorTankValve) - { - ventedfraction = MinCompressorF / MaxCompressorF; // drop to mincompressor level - } - CompressedVolume *= ventedfraction; - if (false == governorlockispresent || CompressorTankValve) - { - CompressorGovernorLock = false; - } - } - - // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet -} - -// ************************************************************************************************* -// Q: 20160712 -// aktualizacja ciśnienia w przewodzie głównym -// ************************************************************************************************* -void TMoverParameters::UpdatePipePressure(double dt) -{ - if (PipePress > 1.0) - { - Pipe->Flow(-PipePress*AirLeakRate * dt); - Pipe->Act(); - } - - // double dV; - // TMoverParameters *c; // T_MoverParameters - double temp; - // int b; - - PipePress = Pipe->P(); - // PPP:=PipePress; - - dpMainValve = 0; - - if (BrakeCtrlPosNo > 1) - { - - if (EngineType != TEngineType::ElectricInductionMotor) - { - double lbpa = LocHandleTimeTraxx ? eim_localbrake : LocalBrakePosA; - if (EIMCtrlType > 0 && UniCtrlIntegratedLocalBrakeCtrl) - { - lbpa = std::max(0.0, -eimic_real); - } - if (SpeedCtrlUnit.Parking) - { - lbpa = std::max(lbpa, StopBrakeDecc); - } - dpLocalValve = LocHandle->GetPF(std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - else - { - // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm - // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake - // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. - // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). - double lbpa; - if (LocHandleTimeTraxx) - { - lbpa = eim_localbrake; - } - else if (SplitEDPneumaticBrake) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. - { - lbpa = LocalBrakePosA; - } - else - { - lbpa = 0.0; - } - dpLocalValve = LocHandle->GetPF(std::max(lbpa, LocalBrakePosAEIM), Hamulec->GetBCP(), ScndPipePress, dt, 0); - } - - LockPipe = PipePress < (LockPipe ? LockPipeOff : LockPipeOn); - bool lock_new = (LockPipe && !UnlockPipe && BrakeCtrlPosR > HandleUnlock) || (EmergencyCutsOffHandle && EmergencyValveFlow > 0); // new simple codition based on .fiz - bool lock_old = BrakeHandle == TBrakeHandle::FV4a // old complex condition based on assumptions - && PipePress < 2.75 && (Hamulec->GetStatus() & b_rls) == 0 && BrakeSubsystem == TBrakeSubSystem::ss_LSt && TrainType != dt_EZT && !UnlockPipe; - - if (lock_old || lock_new) - { - temp = PipePress + 0.00001; - } - else - { - temp = ScndPipePress; - } - Handle->SetReductor(BrakeCtrlPos2); - - if ((BrakeOpModes & bom_PS) == 0 || (CabOccupied != 0 && BrakeOpModeFlag != bom_PS)) - { - - if (BrakeOpModeFlag < bom_EP || Handle->GetPos(bh_EB) - 0.5 < BrakeCtrlPosR || (BrakeHandle != TBrakeHandle::MHZ_EN57 && BrakeHandle != TBrakeHandle::MHZ_K8P)) - { - double pos = BrakeCtrlPosR; - if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && BrakeCtrlPos != Handle->GetPos(bh_EB)) - { - pos = Handle->GetPos(bh_NP); - if (SpeedCtrlUnit.BrakeInterventionBraking) - pos = Handle->GetPos(bh_FB); - if (SpeedCtrlUnit.BrakeInterventionUnbraking) - pos = Handle->GetPos(bh_RP); - } - dpMainValve = Handle->GetPF(pos, PipePress, temp, dt, EqvtPipePress); - } - else - { - dpMainValve = Handle->GetPF(0, PipePress, temp, dt, EqvtPipePress); - } - } - else if (BrakeCtrlPos == Handle->GetPos(bh_EB)) - { - dpMainValve = Handle->GetPF(BrakeCtrlPosR, PipePress, temp, dt, EqvtPipePress); - } - - if (dpMainValve < 0) // && (PipePressureVal > 0.01) //50 - { - if (Compressor > ScndPipePress) - { - CompressedVolume = CompressedVolume + dpMainValve / 1500.0; - Pipe2->Flow(dpMainValve / 3.0); - } - else - Pipe2->Flow(dpMainValve); - } - } - - // ulepszony hamulec bezp. - EmergencyValveFlow = 0.0; - - - // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with - // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position - // vents the pipe only from the vehicle driven from, whatever the controllers of the others show - if (RadioStopFlag || AlarmChainFlag || (EIMCtrlEmergency && LocalBrakePosA >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || - (SpringBrakeDriveEmergencyVel >= 0 && Vel > SpringBrakeDriveEmergencyVel && SpringBrake.IsActive) || - (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)) - { - EmergencyValveFlow = PF(0, PipePress, 0.15) * dt; - } - dpMainValve += EmergencyValveFlow; - - // 0.2*Spg - Pipe->Flow(-dpMainValve); - Pipe->Flow(-PipePress * 0.001 * dt); - // if Heating then - // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); - // if ConverterFlag then - // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); - dpMainValve = dpMainValve / (Dim.L * Spg * 20); - - CntrlPipePress = Hamulec->GetVRP(); // ciśnienie komory wstępnej rozdzielacza - - // if (Hamulec is typeid(TWest)) return 0; - - switch (BrakeValve) - { - - case TBrakeValve::K: - case TBrakeValve::W: - { - - if (BrakeLocHandle != TBrakeHandle::NoHandle) - { - LocBrakePress = LocHandle->GetCP(); - - //(Hamulec as TWest).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - } - if (MBPM < 2) - //(Hamulec as TWest).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - //(Hamulec as TWest).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); - break; - } - - case TBrakeValve::LSt: - case TBrakeValve::EStED: - { - - LocBrakePress = LocHandle->GetCP(); - for (auto const &couplerentry : Couplers) - // nie podoba mi się to rozwiązanie, chyba trzeba - // dodać jakiś wpis do fizyki na to - if ((TrainType & (dt_ET41 | dt_ET42)) != 0 && couplerentry.Connected != nullptr && (couplerentry.Connected->TrainType & (dt_ET41 | dt_ET42)) != 0 && (couplerentry.CouplingFlag & 36) == 36) - LocBrakePress = std::max(couplerentry.Connected->LocHandle->GetCP(), LocBrakePress); - - // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) - //{ - // //if (Vel > 10) - // // LocBrakePress = 0; - // //else if (Vel > 5) - // // LocBrakePress = (10 - Vel) / 5 * LocBrakePress; - // } - - //(Hamulec as TLSt).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - if (BrakeValve == TBrakeValve::EStED) - { - if (MBPM < 2) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - Hamulec->PLC(TotalMass - Mred); - } - break; - } - - case TBrakeValve::CV1_L_TR: - { - LocBrakePress = LocHandle->GetCP(); - //(Hamulec as TCV1L_TR).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - break; - } - - case TBrakeValve::EP2: - case TBrakeValve::EP1: - { - Hamulec->PLC(TotalMass - Mred); - break; - } - case TBrakeValve::ESt3AL2: - case TBrakeValve::NESt3: - case TBrakeValve::ESt4: - case TBrakeValve::ESt3: - { - if (MBPM < 2) - //(Hamulec as TNESt3).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - //(Hamulec as TNESt3).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); - LocBrakePress = LocHandle->GetCP(); - //(Hamulec as TNESt3).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - break; - } - case TBrakeValve::KE: - { - LocBrakePress = LocHandle->GetCP(); - //(Hamulec as TKE).SetLBP(LocBrakePress); - Hamulec->SetLBP(LocBrakePress); - if (MBPM < 2) - //(Hamulec as TKE).PLC(MaxBrakePress[LoadFlag]) - Hamulec->PLC(MaxBrakePress[LoadFlag]); - else - //(Hamulec as TKE).PLC(TotalMass); - Hamulec->PLC(TotalMass - Mred); - break; - } - default: - { - // unsupported brake valve type, we should never land here - // ErrorLog( "Unsupported brake valve type (" + std::to_string( BrakeValve ) + ") in " + TypeName ); - // ::PostQuitMessage( 0 ); - break; - } - } // switch - - if ((BrakeHandle == TBrakeHandle::FVel6 || BrakeHandle == TBrakeHandle::FVE408) && CabOccupied != 0) - { - if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - - // temp = (Handle as TFVel6).GetCP - EpForce = Handle->GetEP(); - else - EpForce = 0.0; - - DynamicBrakeEMUStatus = EpForce > 0.001 ? Power110vIsAvailable : true; - - double temp1 = EpForce; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) - temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) - temp1 = 0; - Hamulec->SetEPS(temp1); - TUHEX_StageActual = static_cast(EpForce); - TUHEX_Active = TUHEX_StageActual > 0; - // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach - SendCtrlToNext("Brake", EpForce, CabActive); - } - else if (BrakeHandle == TBrakeHandle::St113 && CabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) - { - // the EP brake switched on with the button drops out with the control's supply - SwitchEPBrake(0); - } - - Pipe->Act(); - PipePress = Pipe->P(); - if ((Hamulec->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony - temp = 0.0; // odetnij - else - temp = 1.0; // połącz - Pipe->Flow(temp * Hamulec->GetPF(temp * PipePress, dt, Vel) + GetDVc(dt)); - - if (ASBType == 128) - Hamulec->ASB(int(SlippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); - - dpPipe = 0; - - // yB: jednokrokowe liczenie tego wszystkiego - Pipe->Act(); - PipePress = Pipe->P(); - - dpMainValve = dpMainValve / (100.0 * dt); // normalizacja po czasie do syczenia; - - if (PipePress < -1.0) - { - PipePress = -1.0; - Pipe->CreatePress(-1.0); - Pipe->Act(); - } - - if (CompressedVolume < 0.0) - CompressedVolume = 0.0; -} - -// ************************************************************************************************* -// Q: 20160713 -// Aktualizacja ciśnienia w przewodzie zasilającym -// ************************************************************************************************* -namespace -{ -// whether the air flowing to a coupled vehicle along a pipe wakes its physics: any flow did, but a vehicle standing next to one -// whose physics is on gets a trickle of it all the time, as their pressures settle, and each wake kept it on for 5 s. with -// Global.physics_pipewake only a flow which brings its pressure, with what has flown in while it slept, that much away from the -// pressure of the vehicle the air comes from -bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Pipe) -{ - if (Flow * Flow <= 0.00000000000001) - return false; - return (Global.physics_pipewake <= 0.f) || (std::abs(Pressure - Pipe.P_pending()) > Global.physics_pipewake); -} -} // namespace - -void TMoverParameters::UpdateScndPipePressure(double dt) -{ - if (ScndPipePress > 1.0) - { - Pipe2->Flow(-ScndPipePress*AirLeakRate * dt); - Pipe2->Act(); - } - - const double Spz = 0.5067; - TMoverParameters *c; - double dv1; - double dv2; - double dV; - - UpdateSpringBrake(dt); - - dv1 = 0; - dv2 = 0; - - // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[0].Connected; // skrot - dv1 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - c->Pipe2->Flow(-dv1); - if (pipe_wakes(dv1, ScndPipePress, *c->Pipe2)) - c->switch_physics(true, wake_cause::scndpipe); - } - // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(ScndPipePress, c->ScndPipePress, Spz * 0.75); - c->Pipe2->Flow(-dv2); - if (pipe_wakes(dv2, ScndPipePress, *c->Pipe2)) - c->switch_physics(true, wake_cause::scndpipe); - } - if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_scndpneumatic) && TestFlag(Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - dV = 0.00025 * dt * PF(Couplers[0].Connected->ScndPipePress, Couplers[1].Connected->ScndPipePress, Spz * 0.25); - Couplers[0].Connected->Pipe2->Flow(+dV); - Couplers[1].Connected->Pipe2->Flow(-dV); - } - - Pipe2->Flow(Hamulec->GetHPFlow(ScndPipePress, dt)); - // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well - if (/* ( ( Compressor > ScndPipePress ) && ( */ VeselVolume > 0.0 /* ) ) || ( TrainType == dt_EZT ) || ( TrainType == dt_DMU ) */) - { - dV = PF(Compressor, ScndPipePress, Spz) * dt; - CompressedVolume += dV / 1000.0; - Pipe2->Flow(-dV); - } - Pipe2->Flow(dv1 + dv2); - Pipe2->Act(); - ScndPipePress = Pipe2->P(); - - if (ScndPipePress < -1) - { - ScndPipePress = -1; - Pipe2->CreatePress(-1); - Pipe2->Act(); - } -} - -// ************************************************************************************************* -// yB: 20190906 -// Aktualizacja ciśnienia w hamulcu sprezynowym -// ************************************************************************************************* -void TMoverParameters::UpdateSpringBrake(double /*dt*/) -{ - double BP = SpringBrake.PNBrakeConnection ? BrakePress : 0; - double MSP = SpringBrake.ShuttOff ? 0 : SpringBrake.MaxSetPressure; - if (!SpringBrake.Activate) - { - double desired_press = std::min(std::max(MSP, BP), Pipe2->P()); - double dv = PF(desired_press, SpringBrake.SBP, SpringBrake.ValveOffArea); - SpringBrake.Cylinder->Flow(-dv); - Pipe2->Flow(std::max(dv, 0.0)); - } - else - { - double dv = PF(BP, SpringBrake.SBP, SpringBrake.ValveOnArea); - SpringBrake.Cylinder->Flow(-dv); - } - if (SpringBrake.SBP > SpringBrake.ResetPressure) - SpringBrake.IsReady = true; - - SpringBrake.IsActive = SpringBrake.SBP < (SpringBrake.IsActive ? SpringBrake.PressureOff : SpringBrake.PressureOn); - - SpringBrake.Release = false; - SpringBrake.Cylinder->Act(); - SpringBrake.SBP = SpringBrake.Cylinder->P(); -} - -// ************************************************************************************************* -// Q: 20160715 -// oblicza i zwraca przepływ powietrza pomiędzy pojazdami -// ************************************************************************************************* -double TMoverParameters::GetDVc(double dt) -{ - // T_MoverParameters *c; - TMoverParameters *c; - double dv1; - double dv2; // , dV; - - dv1 = 0; - dv2 = 0; - // sprzeg 1 - if (Couplers[0].Connected != nullptr && TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) - { //*0.85 - c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L - dv1 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); - c->Pipe->Flow(-dv1); - if (pipe_wakes(dv1, PipePress, *c->Pipe)) - c->switch_physics(true, wake_cause::mainpipe); - } - // sprzeg 2 - if (Couplers[1].Connected != nullptr && TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic)) - { - c = Couplers[1].Connected; // skrot - dv2 = 0.5 * dt * PF(PipePress, c->PipePress, Spg / (1.0 + 0.015 / Spg * Dim.L)); - c->Pipe->Flow(-dv2); - if (pipe_wakes(dv2, PipePress, *c->Pipe)) - c->switch_physics(true, wake_cause::mainpipe); - } - // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) - // if ((TestFlag(Couplers[0].CouplingFlag, ctrain_pneumatic)) && - // (TestFlag(Couplers[1].CouplingFlag, ctrain_pneumatic))) - // { - // dV = 0.05 * dt * PF(Couplers[0].Connected->PipePress, Couplers[1].Connected->PipePress, - // (Spg * 0.85) / (1 + 0.03 * Dim.L)) * - // 0; // ktoś mi powie jaki jest sens tego bloku jeśli przepływ mnożony przez zero? - // Couplers[0].Connected->Pipe->Flow(+dV); - // Couplers[1].Connected->Pipe->Flow(-dV); - // } - // suma - return dv2 + dv1; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczenie stałych potrzebnych do dalszych obliczeń -// ************************************************************************************************* -void TMoverParameters::ComputeConstans(void) -{ - double BearingF; - double RollF; - double HideModifier; - double Curvature; // Ra 2014-07: odwrotność promienia - - TotalMassxg = TotalMass * g; // TotalMass*g - BearingF = (DamageFlag & dtrain_bearing) != 0 ? 2.0 : 0; - - HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); - - if (BearingType == 0) - RollF = 0.05; // slizgowe - else - RollF = 0.015; // toczne - RollF += BearingF / 200.0; - - // if (NPoweredAxles > 0) - // RollF = RollF * 1.5; //dodatkowe lozyska silnikow - - if (NPoweredAxles > 0) // drobna optymalka - { - RollF += 0.025; - // if (Ft * Ft < 1) - // HideModifier = HideModifier - 3; - } - Ff = TotalMassxg * (BearingF + RollF * V * V / 10.0) / 1000.0; - // dorobic liczenie temperatury lozyska! - FrictConst1 = TotalMassxg * RollF / 10000.0; - // drag calculation - { - // NOTE: draft effect of previous vehicle is simplified and doesn't have much to do with reality - auto const *previousvehicle{Couplers[V >= 0.0 ? end::front : end::rear].Connected}; - auto dragarea{Dim.W * Dim.H}; - if (previousvehicle) - { - dragarea = std::max(0.0, dragarea - 0.85 * previousvehicle->Dim.W * previousvehicle->Dim.H); - } - FrictConst1 += Cx * dragarea; - } - - if (CategoryFlag & 1) - { - Curvature = RunningShape.R == 0.0 ? // zero oznacza nieskończony promień - 0.0 : - 1.0 / std::abs(RunningShape.R); - } - else - { - // vehicles other than trains don't experience friction against the rail on curves - Curvature = 0.0; - } - // opór składu na łuku (youBy): +(500*TrackW/R)*TotalMassxg*0.001 do FrictConst2s/d - FrictConst2s = TotalMassxg * (500.0 * TrackW * Curvature + 2.5 - HideModifier + 2 * BearingF / dtrain_bearing) * 0.001; - FrictConst2d = TotalMassxg * (500.0 * TrackW * Curvature + 2.0 - HideModifier + BearingF / dtrain_bearing) * 0.001; -} - -// ************************************************************************************************* -// Q: 20160713 -// Oblicza masę ładunku -// ************************************************************************************************* -void TMoverParameters::ComputeMass() -{ - // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają - TotalMass = Mass + Mred; - - if (LoadAmount == 0) - { - return; - } - - // include weight of carried load - auto loadtypeunitweight{0.f}; - - if (ToLower(LoadQuantity) == "tonns") - { - loadtypeunitweight = 1000; - } - else - { - auto const lookup{simulation::Weights.find(LoadType.name)}; - loadtypeunitweight = lookup != simulation::Weights.end() ? lookup->second : 1000.f; // legacy default unit weight value - } - - TotalMass += LoadAmount * loadtypeunitweight; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczanie wypadkowej siły z wszystkich działających sił -// ************************************************************************************************* -// TBD, TODO: move some of the calculations out of the method, they're relevant to more than just force calculations -void TMoverParameters::ComputeTotalForce(double dt) -{ - - Vel = std::abs(V) * 3.6; // prędkość w km/h - - // McZapkie-031103: sprawdzanie czy warto liczyc fizyke i inne updaty - // ABu 300105: cos tu mieszalem , dziala teraz troche lepiej, wiec zostawiam - { - auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || TrainType == dt_EZT || TrainType == dt_DMU}; - - auto const movingvehicleahead{Neighbours[end::front].vehicle != nullptr && - (Neighbours[end::front].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::front].vehicle->MoverParameters->accelerating())}; - - auto const movingvehiclebehind{Neighbours[end::rear].vehicle != nullptr && - (Neighbours[end::rear].vehicle->MoverParameters->Vel > 0.0001 || Neighbours[end::rear].vehicle->MoverParameters->accelerating())}; - - auto const calculatephysics{vehicleisactive || movingvehicleahead || movingvehiclebehind}; - - switch_physics(calculatephysics, Vel > 0.0001 ? wake_cause::speed : - accelerating() ? wake_cause::acceleration : - vehicleisactive ? wake_cause::rest : - wake_cause::neighbour); - } - - if (false == PhysicActivation) - { - return; - } - - // juz zoptymalizowane: - FStand = FrictionForce(); // siła oporów ruchu - if (true == TestFlag(DamageFlag, dtrain_out)) - { - // HACK: crude way to reduce speed after derailment - // TBD, TODO: more accurate approach? - FStand *= 1e20; - } - double old_nrot = abs(nrot); - nrot = v2n(); // przeliczenie prędkości liniowej na obrotową - - if (true == TestFlag(BrakeMethod, bp_MHS) && PipePress < 3.0 // ustawione na sztywno na 3 bar - && Vel > 45 && true == TestFlag(BrakeDelayFlag, bdelay_M)) - { - // doliczenie hamowania hamulcem szynowym - FStand += TrackBrakeForce; - } - // w charakterystykach jest wartość siły hamowania zamiast nacisku - - LastSwitchingTime += dt; - if (EngineType == TEngineType::ElectricSeriesMotor) - { - LastRelayTime += dt; - } - - if (EngineType == TEngineType::ElectricSeriesMotor) // potem ulepszyc! pantogtrafy! - { // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik - EngineVoltage = Mains ? EnginePowerSourceVoltage() : 0.0; - if (CabActive == 0) - { - EngineVoltage *= DirActive; - } - else - { - EngineVoltage *= DirAbsolute; // the reverser of the active cab, relative to the couplers - } - } // bo nie dzialalo - else - { - EngineVoltage = Power > 1.0 ? std::max(GetTrainsetHighVoltage(), PantographVoltage) : 0.0; - } - - FTrain = Power > 0 ? TractionForce(dt) : 0; - double FT_factor = 1.0; - if (EngineType == TEngineType::ElectricInductionMotor && InvertersRatio > 0.0) - { - FT_factor = 1.0 / InvertersRatio; - FTrain *= FT_factor; - } - - Fb = BrakeForce(RunningTrack); - // poslizg - auto Fwheels{FTrain - Fb * Sign(V)}; - if (Vel > 0.1 // crude trap, to prevent braked stationary vehicles from passing fb > mass * adhesive test - && std::abs(Fwheels) > TotalMassxg * Adhesive(RunningTrack.friction)) - { - SlippingWheels = true; - } - if (true == SlippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle... - && std::abs(nrot * M_PI * WheelDiameter - V) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid - { - // locked wheels never pass the rotation speed test below once the vehicle stops, and a skidding vehicle - // keeps its braking force capped by the sliding adhesion, so the rest of the consist could push it around - SlippingWheels = false; - nrot = V / M_PI / WheelDiameter; - } - double temp_nrot = nrot; - if (true == SlippingWheels) - { - - temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrot * M_PI * WheelDiameter - V) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrot); - if (Sign(nrot * M_PI * WheelDiameter - V) * Sign(temp_nrot * M_PI * WheelDiameter - V) < 0) - { - SlippingWheels = false; - temp_nrot = V / M_PI / WheelDiameter; - } - } - if (true == SlippingWheels) - { - Fwheels = Sign(temp_nrot * M_PI * WheelDiameter - V) * TotalMassxg * Adhesive(RunningTrack.friction); - if (Fwheels * Sign(V) > 0) - { - FTrain = Fwheels + Fb * Sign(V); - } - else if (FTrain * Sign(V) > 0) - { - Fb = FTrain * Sign(V) - Fwheels * Sign(V); - } - else - { - double factor = FTrain - Fb * Sign(V) != 0 ? Fwheels / (FTrain - Fb * Sign(V)) : 1.0; - Fb *= factor; - FTrain *= factor; - } - if (std::abs(nrot) < 0.1) - { - WheelFlat = sqrt(square(WheelFlat) + abs(Fwheels) / NAxles * Vel * 0.000002); - } - - nrot = temp_nrot; - } - nrot_eps = (abs(nrot) - old_nrot) / dt; - // doliczenie sił z innych pojazdów - for (int end = end::front; end <= end::rear; ++end) - { - if (Neighbours[end].vehicle != nullptr) - { - Couplers[end].CForce = CouplerForce(end, dt); - FTrain += Couplers[end].CForce; - } - else - Couplers[end].CForce = 0; - } - - FStand += Fb; - // doliczenie składowej stycznej grawitacji - FTrain /= FT_factor; - FTrain += TotalMassxg * RunningShape.dHtrack; - //! niejawne przypisanie zmiennej! - FTotal = FTrain - Sign(V) * FStand; -} - -double TMoverParameters::BrakeForceR(double ratio, double velocity) const -{ - double press = 0; - ratio = Hamulec->GetBrakeRatio(ratio); - if (MBPM > 2) - { - press = MaxBrakePress[1] + (MaxBrakePress[3] - MaxBrakePress[1]) * std::min(1.0, (TotalMass - Mass) / (MBPM - Mass)); - } - else - { - if (MaxBrakePress[1] > 0.1) - { - press = MaxBrakePress[LoadFlag]; - } - else - { - press = MaxBrakePress[3]; - if (DynamicBrakeType == dbrake_automatic) - ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); - if (BrakeDelayFlag & bdelay_R && BrakeMethod % 128 != bp_Cosid && BrakeMethod % 128 != bp_D1 && BrakeMethod % 128 != bp_D2 && Power < 1) - ratio *= Hamulec->GetRapidRatio(velocity); - if (TrainType == dt_DMU && velocity < 30.0) - { - ratio -= 0.3; - } - } - } - return BrakeForceP(press * ratio, velocity); -} - -double TMoverParameters::BrakeForceP(double press, double velocity) const -{ - double BFP = 0; - double K = ((press * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj) * BrakeRigEff; - K *= static_cast(BrakeCylNo) / (NAxles * std::max(1, NBpA)); - BFP = Hamulec->GetFC(velocity, K) * K * (NAxles * std::max(1, NBpA)) * 1000; - return BFP; -} - -// ************************************************************************************************* -// Q: 20160713 -// oblicza siłę na styku koła i szyny -// ************************************************************************************************* -double TMoverParameters::BrakeForce(TTrackParam const & /*Track*/) -{ - - double K{0}; - double brakeforce{0}; - - switch (LocalBrake) - { - case TLocalBrake::ManualBrake: - { - K = MaxBrakeForce * ManualBrakeRatio(); - break; - } - case TLocalBrake::HydraulicBrake: - { - K = MaxBrakeForce * LocalBrakeRatio(); - break; - } - default: - { - break; - } - } - - if (MBrake == true) - { - K = MaxBrakeForce * ManualBrakeRatio(); - } - - if (SpringBrake.IsReady) - K += std::max(0.0, SpringBrake.MinForcePressure - SpringBrake.Cylinder->P()) * SpringBrake.MaxBrakeForce; - - u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; - if (u * BrakeRigEff > Ntotal) // histereza na nacisku klockow - Ntotal = u * BrakeRigEff; - else - { - u = (BrakePress * P2FTrans - BrakeCylSpring) * BrakeCylMult[0] - BrakeSlckAdj; - if (u * (2.0 - BrakeRigEff) < Ntotal) // histereza na nacisku klockow - Ntotal = u * (2.0 - BrakeRigEff); - } - - auto const NBrakeAxles{NAxles}; - - if (NBrakeAxles * NBpA > 0) - { - if (Ntotal > 0) // nie luz - K += Ntotal; // w kN - K *= static_cast(BrakeCylNo) / (NBrakeAxles * static_cast(NBpA)); // w kN na os - } - if (BrakeSystem == TBrakeSystem::Pneumatic || BrakeSystem == TBrakeSystem::ElectroPneumatic) - { - u = Hamulec->GetFC(Vel, K); - UnitBrakeForce = u * K * 1000.0; // sila na jeden klocek w N - } - else - UnitBrakeForce = K * 1000.0; - // if (LocalBrake=ManualBrake)or(MBrake=true)) and (BrakePress<0.3) then - // Fb:=UnitBrakeForce*NBpA {ham. reczny dziala na jedna os} - // else //yB: to nie do konca ma sens, ponieważ ręczny w wagonie działa na jeden cylinder - // hamulcowy/wózek, dlatego potrzebne są oddzielnie liczone osie - brakeforce = UnitBrakeForce * NBrakeAxles * std::max(1, NBpA); - - // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; - // { end; } - return brakeforce; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczanie siły tarcia -// ************************************************************************************************* -double TMoverParameters::FrictionForce() const -{ - double FF = 0; - // ABu 240205: chyba juz ekstremalnie zoptymalizowana funkcja liczaca sily tarcia - if (abs(V) > 0.01) - FF = FrictConst1 * V * V + FrictConst2d; - else - FF = FrictConst1 * V * V + FrictConst2s; - return FF; -} - -// ************************************************************************************************* -// Q: 20160713 -// Oblicza przyczepność -// ************************************************************************************************* -double TMoverParameters::Adhesive(double staticfriction) const -{ - double adhesion = 0.0; - const double adh_factor = 0.25; // współczynnik określający, jak bardzo spada tarcie przy poślizgu - const double slipfactor = 0.33; // współczynnik określający, jak szybko spada tarcie przy poślizgu - const double sandfactor = 1.25; // współczynnik określający, jak mocno pomaga piasek - /* - // ABu: male przerobki, tylko czy to da jakikolwiek skutek w FPS? - // w kazdym razie zaciemni kod na pewno :) - if (SlippingWheels == false) - { - if (SandDose) - adhesion = (std::max(staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 11.0), 0.048)) * - (11.0 - 2.0 * Random(0.0, 1.0)); - else - adhesion = (staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 10.0)) * - (11.0 - 2.0 * Random(0.0, 1.0)); - } - else - { - if (SandDose) - adhesion = (0.048) * (11.0 - 2.0 * Random(0.0, 1.0)); - else - adhesion = (staticfriction * 0.02) * (11.0 - 2.0 * Random(0.0, 1.0)); - } - // WriteLog(FloatToStr(adhesive)); // tutaj jest na poziomie 0.2 - 0.3 - return adhesion; - - //wersja druga - if( true == SlippingWheels ) { - - if( true == SandDose ) { adhesion = 0.48; } - else { adhesion = staticfriction * 0.2; } - } - else { - - if( true == SandDose ) { adhesion = std::max( staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ) * 1.1, 0.48 ); } - else { adhesion = staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ); } - } - // adhesion *= ( 0.9 + 0.2 * Random() ); - */ - // wersja3 by youBy - uwzględnia naturalne mikropoślizgi i wpływ piasecznicy, usuwa losowość z pojazdu - double Vwheels = nrot * M_PI * WheelDiameter; // predkosc liniowa koła wynikająca z obrotowej - double deltaV = V - Vwheels; // poślizg - różnica prędkości w punkcie styku koła i szyny - deltaV = std::max(0.0, std::abs(deltaV) - 0.25); // mikropoślizgi do ok. 0,25 m/s nie zrywają przyczepności - Vwheels = std::abs(Vwheels); - adhesion = staticfriction * (28 + Vwheels) / (14 + Vwheels) * ((SandDose ? sandfactor : 1) - (1 - adh_factor) * (deltaV / (deltaV + slipfactor))); - - return adhesion; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczanie sił dzialających na sprzęgach -// ************************************************************************************************* -double TMoverParameters::CouplerForce(int const End, double dt) -{ - if (coupler_physics_at(End)) - { - return coupler_force_physical(End, dt); - } - - auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; - - auto const othervehiclemove{(othervehicle->dMoveLen * DirPatch(End, otherend))}; - auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada - auto const distancedelta{(End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - - auto const newdistance{initialdistance + 10.0 * distancedelta}; - - auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; - auto const absdV{std::abs(dV)}; - - // potentially generate sounds on clash or stretch - if (newdistance < 0.0 && thiscoupler.Dist > newdistance && dV < -0.1 && false == thiscoupler.has_adapter()) - { // HACK: with adapter present we presume buffers won't clash - // 090503: dzwieki pracy zderzakow - SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); - } - else if (thiscoupler.CouplingFlag != coupling::faux && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) - { - // 090503: dzwieki pracy sprzegu - SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); - } - - thiscoupler.CheckCollision = false; - thiscoupler.Dist = 0.0; - - double CF{0.0}; - - if (thiscoupler.CouplingFlag == coupling::faux && initialdistance > 0.05) - { // arbitrary distance - // potentially reset auto coupling lock - thiscoupler.AutomaticCouplingAllowed = true; - } - - if (thiscoupler.CouplingFlag != coupling::faux || initialdistance < 0) - { - - thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); - - double BetaAvg = 0; - double Fmax = 0; - - if (thiscoupler.CouplingFlag == coupling::faux) - { - - BetaAvg = thiscoupler.beta; - Fmax = (thiscoupler.FmaxC + thiscoupler.FmaxB) * CouplerTune; - } - else - { - // usrednij bo wspolny sprzeg - BetaAvg = 0.5 * (thiscoupler.beta + othercoupler.beta); - Fmax = 0.5 * (thiscoupler.FmaxC + thiscoupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune; - } - auto const distDelta{std::abs(newdistance) - std::abs(thiscoupler.Dist)}; // McZapkie-191103: poprawka na histereze - - if (newdistance > 0) - { - - if (distDelta > 0) - { - CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; - } - else - { - CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; - } - // liczenie sily ze sprezystosci sprzegu - if (newdistance > thiscoupler.DmaxC + othercoupler.DmaxC) - { - // zderzenie - thiscoupler.CheckCollision = true; - } - if (std::abs(CF) > thiscoupler.FmaxC) - { - // coupler is stretched with excessive force, may break - thiscoupler.stretch_duration += static_cast(dt); - // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks - // (arbitrary) chance to break grows from 10-100% over 10 sec period - if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) - { - damage_coupler(End); - } - } - else - { - thiscoupler.stretch_duration = 0.f; - } - } - if (newdistance < 0) - { - - if (distDelta > 0) - { - CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; - } - else - { - CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; - } - // liczenie sily ze sprezystosci zderzaka - auto const collisiondistance{(thiscoupler.has_adapter() || othercoupler.has_adapter() ? - std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler - thiscoupler.DmaxB + othercoupler.DmaxB)}; - if (-newdistance > collisiondistance) - { - // zderzenie - thiscoupler.CheckCollision = true; - } - if (-newdistance >= std::min(collisiondistance, dEpsilon)) - { - automatic_coupling(End, *othervehicle, otherend); - } - } - } - - if (thiscoupler.CouplingFlag != coupling::faux) - { - // uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's - // axis: turned around once more when the vehicles face each other - othervehicle->Couplers[otherend].CForce = -CF * DirPatch(End, otherend); - } - - return CF; -} - -bool TMoverParameters::coupler_physics_at(int const End) const -{ - if (false == Global.coupler_physics) - { - return false; - } - if (Global.coupler_physics_all || CouplerPhysics) - { - return true; - } - // either vehicle of the pair covered takes the pair in, so both of them compute it the same way - auto const *other{Neighbours[End].vehicle}; - return other != nullptr && other->MoverParameters->CouplerPhysics; -} - -void TMoverParameters::automatic_coupling(int const End, TMoverParameters &Other, int const OtherEnd) -{ - auto &thiscoupler{Couplers[End]}; - auto &othercoupler{Other.Couplers[OtherEnd]}; - - if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != coupling::faux || false == thiscoupler.AutomaticCouplingAllowed || - false == othercoupler.AutomaticCouplingAllowed) - { - return; - } - // sprzeganie wagonow z samoczynnymi sprzegami - auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; - // potentially exclude incompatible control coupling - if (thiscoupler.control_type != othercoupler.control_type) - { - couplingtype &= ~coupling::control; - } - couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); - - // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) - auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; - auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; - // HACK: we're reusing sound enum to mark whether vehicle was connected to another - AIFlag |= (caught ? sound::attachcoupler : 0); - // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down - thiscoupler.AutomaticCouplingAllowed = safe && false == caught; - othercoupler.AutomaticCouplingAllowed = safe && false == caught; -} - -namespace -{ - -// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train -constexpr double coupler_stretch_threshold{0.001}; - -// the sounds of the buffers hitting each other, and of the coupling taking up its play -struct coupler_sound_input -{ - double gap{0.0}; // between the ends [m] - double previous_gap{0.0}; - double gap_rate{0.0}; // [m/s] - double draw_gear{0.0}; // deflection [m] - double previous_draw_gear{0.0}; - bool coupled{false}; - bool adapter{false}; - bool moving{false}; -}; - -int coupler_sounds(coupler_sound_input const &Input) -{ - if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter) - { - // 090503: dzwieki pracy zderzakow - return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash; - } - if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005) - { - // 090503: dzwieki pracy sprzegu - return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch; - } - return sound::none; -} - -} // namespace - -double TMoverParameters::coupler_force_physical(int const End, double const dt) -{ - auto &thiscoupler{Couplers[End]}; - auto *othervehicle{Neighbours[End].vehicle->MoverParameters}; - auto const otherend{Neighbours[End].vehicle_end}; - auto &othercoupler{othervehicle->Couplers[otherend]}; - auto &state{thiscoupler.physics_state}; - - // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since - auto const othervehiclemove{othervehicle->dMoveLen * DirPatch(End, otherend)}; - auto const gap{Neighbours[End].distance + (End == end::front ? othervehiclemove - dMoveLen : dMoveLen - othervehiclemove)}; - // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one behind - auto const gaprate{CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; - auto const coupled{thiscoupler.CouplingFlag != coupling::faux}; - auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; - - if (false == coupled && Neighbours[End].distance > 0.05) - { // arbitrary distance - // potentially reset auto coupling lock - thiscoupler.AutomaticCouplingAllowed = true; - } - - auto const previousgap{state.gap}; - auto const previousdrawgear{state.draw_gear.deflection}; - auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage})}; - - SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); - - thiscoupler.CheckCollision = state.stop != 0; - // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end - thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0); - // the link pulled past its yield force, which the AI drivers ease off on - thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f; - - if (result.broken) - { - damage_coupler(End); - } - if (false == coupled && gap < 0.0) - { - auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB}; - if (-gap >= std::min(collisiondistance, dEpsilon)) - { - automatic_coupling(End, *othervehicle, otherend); - } - } - - // tension pulls this vehicle towards the other one - auto const force{result.force * -DirF(End)}; - if (thiscoupler.CouplingFlag != coupling::faux) - { - // uzgadnianie prawa Newtona, as in CouplerForce() - othercoupler.CForce = -force * DirPatch(End, otherend); - } - return force; -} - -bool TMoverParameters::coupler_stop_hit(int const End, TMoverParameters &Other, int const OtherEnd) -{ - auto &thiscoupler{Couplers[End]}; - auto &othercoupler{Other.Couplers[OtherEnd]}; - auto &state{thiscoupler.physics_state}; - - // the draw gear went solid with the gap opening up, the buffers with it closing - auto const gaprate{CouplerVelocityDifference(End, Other, OtherEnd) * DirF(End)}; - auto const closing{state.stop > 0 ? gaprate : -gaprate}; - if (state.stop == 0 || closing <= 0.0) - { - // parting from the stop already, after the hit on the other vehicle's end - return false; - } - if (false == Global.crash_damage) - { - return true; - } - auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, TotalMass, Other.TotalMass)}; - // the other vehicle keeps the state of the pair alike - othercoupler.physics_state.elongation = state.elongation; - if (hit.broken || hit.crushed) - { - damage_coupler(End); - } - // a broken coupling lets the vehicles part - return false == hit.broken; -} - -// ************************************************************************************************* -// Q: 20160714 -// oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) -// ************************************************************************************************* -double TMoverParameters::TractionForce(double dt) -{ - double PosRatio; - double dmoment; - double dtrans; - double tmp; - - Ft = 0; - dtrans = 0; - dmoment = 0; - // youBy - switch (EngineType) - { - case TEngineType::DieselElectric: - { - if (true == Mains && true == FuelPump.is_active) - { - - if (EIMCtrlType > 0) // sterowanie cyfrowe - tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimic_real)) / 60.0; - else - tmp = DElist[ControlPressureSwitch ? MainCtrlNoPowerPos() : MainCtrlPos].RPM / 60.0; - - if (true == HeatingAllow && HeatingPower > 0 && EngineHeatingRPM > 0) - { - // bump engine revolutions up if needed, when heating is on - tmp = std::max(tmp, std::min(EngineMaxRPM(), EngineHeatingRPM) / 60.0); - } - // NOTE: fake dizel_fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity - dizel_fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); - } - else - { - tmp = 0.0; - dizel_fill = 0.0; - } - - if (enrot != tmp) - { - enrot = safe_clamp(enrot + dt / dizel_AIM * (enrot < tmp ? 1.0 : -1.0 * dizel_RevolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise - 0.0, std::max(tmp, enrot)); - if (std::abs(tmp - enrot) < 0.001) - { - enrot = tmp; - } - } - break; - } - case TEngineType::DieselEngine: - { - if (ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 - dtrans = AnPos * Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; - else - dtrans = Transmision.Ratio * motor_param(ScndCtrlActualPos).mIsat; - - dmoment = dizel_Momentum(dizel_fill, dtrans * nrot * DirActive, dt); // oblicza tez enrot - break; - } - default: - { - enrot = Transmision.Ratio * nrot; - break; - } - } - - eAngle += enrot * dt; - if (eAngle > M_PI * 2.0) - eAngle = std::fmod(eAngle, M_PI * 2.0); - /* - while (eAngle > M_PI * 2.0) - // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? - eAngle -= M_PI * 2.0; - */ - // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) - // wentylatory rozruchowe - // TBD, TODO: move this to update, it doesn't exactly have much to do with traction - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - if (MainCircuitPowered()) - { - switch (RVentType) - { - - case 1: - { // manual - if (true == RVentForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case 2: - { // automatic - auto const motorcurrent{std::min(ImaxHi, std::abs(Im))}; - if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) - { - - RventRot += (RVentnmax * std::min(1.0, motorcurrent / NPoweredAxles / RVentMinI) * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (DynamicBrakeType == dbrake_automatic && true == DynamicBrakeFlag) - { - RventRot += (RVentnmax * motorcurrent / ImaxLo - RventRot) * RVentSpeed * dt; - } - else if (RVentForceOn) - { - RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - default: - { - break; - } - } // rventtype - } // mains - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - } - break; - } - - case TEngineType::DieselElectric: - { - // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it - if (true == Mains) - { - // TBD, TODO: currently ignores RVentType, fix this? - RventRot += std::clamp(enrot - RventRot, -100.0, 50.0) * dt; - dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); - dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); - } - else - { - RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); - dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); - dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); - } - break; - } - - case TEngineType::DieselEngine: - { - // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators - if (true == Mains) - { - dizel_heat.rpmw += static_cast(std::clamp(dizel_heat.rpmwz - dizel_heat.rpmw, -100.f, 50.f) * dt); - dizel_heat.rpmw2 += static_cast(std::clamp(dizel_heat.rpmwz2 - dizel_heat.rpmw2, -100.f, 50.f) * dt); - } - else - { - dizel_heat.rpmw *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw * dt)); - dizel_heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - dizel_heat.rpmw2 * dt)); - } - break; - } - - default: - { - break; - } - } - - switch (EngineType) - { - case TEngineType::Dumb: - { - PosRatio = (MainCtrlPos + ScndCtrlPos) / (MainCtrlPosNo + ScndCtrlPosNo + 0.01); - EnginePower = /*1000.0 **/ Power * PosRatio; - break; - } - case TEngineType::DieselEngine: - { - dizel_Power = Mm * enrot * (2.0 * M_PI / 1000.0); - EnginePower = (dizel_Mstand + Mm) * enrot * (2.0 * M_PI / 1000.0); - if (MainCtrlPowerPos() > 1) - { - // dodatkowe opory z powodu sprezarki} - // dmoment -= dizel_Mstand * ( 0.2 * enrot / dizel_nmax ); //yB: skąd to w ogóle się bierze?! - } - break; - } - case TEngineType::DieselElectric: - { - EnginePower = 0; // the actual calculation is done in two steps later in the method - break; - } - default: - { - break; - } - } - - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - // update the state of voltage relays - auto const voltage{std::max(GetTrainsetHighVoltage(), PantographVoltage)}; - // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the - // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back - // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at - // zero, or at the first position, which is the first resistance step, where the line contactors close on any - // start, and where the AI waits for them rather than going back to zero - auto const novoltrelaypicksup{false == PantographsRequireMains || NoVoltRelay || MainCtrlPowerPos() <= 1}; - NoVoltRelay = EnginePowerSource.SourceType != TPowerSource::CurrentCollector || (voltage >= EnginePowerSource.CollectorParameters.MinV && novoltrelaypicksup); - OvervoltageRelay = - EnginePowerSource.SourceType != TPowerSource::CurrentCollector || voltage <= EnginePowerSource.CollectorParameters.MaxV || false == EnginePowerSource.CollectorParameters.OVP; - // wywalanie szybkiego z powodu niewłaściwego napięcia - // (a line breaker closed ahead of the pantographs holds without voltage) - EventFlag |= true == Mains && ((false == NoVoltRelay && false == PantographsRequireMains) || false == OvervoltageRelay) && - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - break; - } - - case TEngineType::ElectricInductionMotor: - { - // TODO: check if we can use instead the code for electricseriesmotor - // nie wchodzić w funkcję bez potrzeby - // (a line breaker closed ahead of the pantographs holds without voltage) - if (Mains && ((std::max(GetTrainsetHighVoltage(), PantographVoltage) < EnginePowerSource.CollectorParameters.MinV && false == PantographsRequireMains) || - std::max(GetTrainsetHighVoltage(), PantographVoltage) > EnginePowerSource.CollectorParameters.MaxV + 200)) - { - MainSwitch(false, TrainType == dt_EZT ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide - } - break; - } - - case TEngineType::DieselElectric: - { - // TODO: move this to the auto relay check when the electric engine code paths are unified - StLinFlag |= Mains && false == StLinFlag && MainCtrlPowerPos() == 1; - StLinFlag &= MotorConnectorsCheck(); - StLinFlag &= MainCtrlPowerPos() > 0; - - break; - } - - default: - { - break; - } - } - - if (DirActive != 0) - switch (EngineType) - { - case TEngineType::Dumb: - { - if (Mains && CabActive != 0) - { - if (Vel > 0.1) - { - Ft = std::min(1000.0 * Power / std::abs(V), Ftmax) * PosRatio; - } - else - { - Ft = Ftmax * PosRatio; - } - Ft = Ft * DirAbsolute; // DirActive*CabActive; - } - else - { - Ft = 0; - } - break; - } // Dumb - - case TEngineType::WheelsDriven: - { - if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) - Ft = Sign(sin(eAngle)) * PulseForce * Transmision.Ratio; - PulseForceTimer = PulseForceTimer + dt; - if (PulseForceTimer > CtrlDelay) - { - PulseForce = 0; - if (PulseForceCount > 0) - PulseForceCount--; - } - EnginePower = Ft * (1.0 + Vel); - break; - } // WheelsDriven - - case TEngineType::ElectricSeriesMotor: - { - // enrot:=Transmision.Ratio*nrot; - // yB: szereg dwoch sekcji w ET42 - if (TrainType == dt_ET42 && Imax == ImaxHi) - EngineVoltage = EngineVoltage / 2.0; - Mm = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik - - if (TrainType == dt_ET42) - { - if (Imax == ImaxHi) - EngineVoltage = EngineVoltage * 2; - if (DynamicBrakeFlag && abs(Im) > 300) // przeiesione do mover.cpp - FuseOff(); - } - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - { - if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne - { - if (Vel > 100) - TUHEX_StageActual = std::min(TUHEX_StageActual, 1); - switch (TUHEX_StageActual) - { - case 1: - TUHEX_Sum = TUHEX_Sum1; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 2: - TUHEX_Sum = TUHEX_Sum2; - DynamicBrakeRes = DynamicBrakeRes1; - break; - case 3: - TUHEX_Sum = TUHEX_Sum3; - if (Vadd > 0.99 * TUHEX_MaxIw && DynamicBrakeRes == DynamicBrakeRes1) - TUHEX_ResChange = true; - if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) - { - TUHEX_ResChange = false; - DynamicBrakeRes = DynamicBrakeRes2; - } - break; - default: - DynamicBrakeRes = DynamicBrakeRes1; - TUHEX_Sum = 0; - break; - } - } - if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || Hamulec->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) - { - Vadd -= 500.0 * dt; - if (Vadd < TUHEX_MinIw) - { - Vadd = 0; - DynamicBrakeFlag = false; - } - } - else if (DynamicBrakeFlag && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) - { - Vadd += 70.0 * dt; - Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); - } - if (Vadd > 0) - Mm = MomentumF(Im, Vadd, 0); - } - - if (TrainType == dt_ET22 && DelayCtrlFlag) // szarpanie przy zmianie układu w byku - Mm = Mm * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił - - if (abs(Im) > Imax) - Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN - else - Vhyp = 0; - if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony - FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow - - if ((DynamicBrakeType == dbrake_automatic || DynamicBrakeType == dbrake_switch) && DynamicBrakeFlag) - Itot = Im * 2; // 2x2 silniki w EP09 - else if (TrainType == dt_EZT && Imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie - Itot = Im; - else - Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles; // sila trakcyjna - break; - } - - case TEngineType::DieselEngine: - { - Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation - if (hydro_R && hydro_R_Placement == 0) - Mw -= dizel_MomentumRetarder(nrot * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter / NPoweredAxles; - Ft = Fw * NPoweredAxles; // sila trakcyjna - Ft = Ft * DirAbsolute; // DirActive*CabActive; - break; - } - - case TEngineType::DieselElectric: // youBy - { - // tmpV:=V*CabActive*DirActive; - auto const tmpV{nrot * Pirazy2 * 0.5 * WheelDiameter * DirAbsolute}; //*CabActive*DirActive; - auto tempUmax = 0.0; - auto tempImax = 0.0; - auto tempPmax = 0.0; - // jazda manewrowa - if (EIMCtrlType > 0) // sterowanie cyfrowe - { - auto eimic_positive = std::max(0.0, eimic_real); - auto const rpmratio{EngineRPMRatio()}; - tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; - tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); - tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); - tmp = tempPmax; - if (true == StLinFlag) - { - - if (tmpV < Vhyp * tempPmax / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = - (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * eimic_positive; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tempPmax / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tempPmax / DElist[MainCtrlPosNo].GenPower; - } - else if (true == ShuntMode) - { - if (true == StLinFlag) - { - EngineVoltage = SST[MainCtrlPos].Umax * AnPos + SST[MainCtrlPos].Umin * (1.0 - AnPos); - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - tmp = EngineRPMRatio() * (SST[MainCtrlPos].Pmax * AnPos) + SST[MainCtrlPos].Pmin * (1.0 - AnPos); - Ft = tmp * 1000.0 / (abs(tmpV) + 1.6); - } - else - { - EngineVoltage = 0; - Ft = 0; - } - PosRatio = 1; - } - else // jazda ciapongowa - { - auto power = Power; - tempImax = DElist[MainCtrlPos].Imax; - tempUmax = DElist[MainCtrlPos].Umax; - if (true == Heating) - { - power -= HeatingPower; - } - if (power < 0.0) - { - power = 0.0; - } - // NOTE: very crude way to approximate power generated at current rpm instead of instant top output - // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it - auto const currentgenpower{(DElist[MainCtrlPos].RPM > 0 ? DElist[MainCtrlPos].GenPower * (60.0 * enrot / DElist[MainCtrlPos].RPM) : 0.0)}; - - tmp = std::min(power, currentgenpower); - - PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; - // stosunek mocy teraz do mocy max - // NOTE: Mains in this context is working diesel engine - if (true == StLinFlag) - { - - if (tmpV < Vhyp * power / DElist[MainCtrlPosNo].GenPower) - { - // czy na czesci prostej, czy na hiperboli - Ft = (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * PosRatio; // posratio - bo sila jakos tam sie rozklada - } - else - { - // na hiperboli - // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka - Ft = 1000.0 * tmp / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy - } - } - else - Ft = 0; // jak nastawnik na zero, to sila tez zero - - PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; - } - - if (FuseFlag) - Ft = 0; - else - Ft = Ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc - Fw = Ft / NPoweredAxles; // sila na obwodzie kola - Mw = Fw * WheelDiameter / 2.0; // moment na osi kola - Mm = Mw / Transmision.Ratio; // moment silnika trakcyjnego - - // with MotorParam[ScndCtrlPos] do - if (abs(Mm) > motor_param(ScndCtrlPos).fi) - Im = NPoweredAxles * abs(abs(Mm) / motor_param(ScndCtrlPos).mfi + motor_param(ScndCtrlPos).mIsat); - else - Im = NPoweredAxles * sqrt(abs(Mm * motor_param(ScndCtrlPos).Isat)); - - if (ShuntMode) - { - EnginePower = EngineVoltage * Im / 1000.0; - if (EnginePower > tmp) - { - EnginePower = tmp; - EngineVoltage = EnginePower * 1000.0 / Im; - } - if (EnginePower < tmp) - { - Ft *= EnginePower / tmp; - } - } - else - { - if (abs(Im) > tempImax) - { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy - Ft = Ft / Im * tempImax; - Im = tempImax; - } - - if (Im > 0) - { - // jak pod obciazeniem - if (true == Flat) - { - // ograniczenie napiecia w pradnicy - plaszczak u gory - EngineVoltage = 1000.0 * tmp / std::abs(Im); - } - else - { - auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimic_real) : MainCtrlPos; - auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; - // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa - EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); - EngineVoltage /= tempMCPN - 1; - EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); - } - } - - if (EngineVoltage > tempUmax || Im == 0) - { - // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) - EngineVoltage = tempUmax * (ConverterFlag ? 1 : 0); - } - - EnginePower = EngineVoltage * Im / 1000.0; - /* - // power curve drop - // NOTE: disabled for the time being due to side-effects - if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { - Ft = std::lerp( - Ft, EnginePower / tmp, - std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); - } - */ - } - - if (Imax > 1 && Im > Imax) - FuseOff(); - if (FuseFlag) - EngineVoltage = 0; - - // przekazniki bocznikowania, kazdy inny dla kazdej pozycji - if (false == StLinFlag || ShuntMode) - { - ScndCtrlPos = 0; - } - else - { - if (AutoRelayFlag) - { - - auto const shuntfieldstate{ScndCtrlPos}; - - switch (RelayType) - { - - case 0: - { - - if (ScndCtrlPos < ScndCtrlPosNo && Im <= MPTRelay[ScndCtrlPos].Iup * PosRatio) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && Im >= MPTRelay[ScndCtrlPos].Idown * PosRatio) - { - --ScndCtrlPos; - } - break; - } - case 1: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - break; - } - case 2: - { - - if (ScndCtrlPos < ScndCtrlPosNo && MPTRelay[ScndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) - { - ++ScndCtrlPos; - } - if (ScndCtrlPos > 0 && MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - break; - } - case 41: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - enrot = enrot * 0.73; - } - if (ScndCtrlPos > 0 && Im > MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - break; - } - case 45: - { - if (ScndCtrlPos < ScndCtrlPosNo && MainCtrlPos >= 11) - { - - if (Im < MPTRelay[ScndCtrlPos].Iup) - { - ++ScndCtrlPos; - } - // check for cases where the speed drops below threshold for level 2 or 3 - if (ScndCtrlPos > 1 && Vel < MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - // malenie - if (ScndCtrlPos > 0 && MainCtrlPos < 11) - { - - if (ScndCtrlPos == 1) - { - if (Im > MPTRelay[ScndCtrlPos - 1].Idown) - { - --ScndCtrlPos; - } - } - else - { - if (Vel < MPTRelay[ScndCtrlPos].Idown) - { - --ScndCtrlPos; - } - } - } - // 3rd level drops with master controller at position lower than 10... - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - // ...and below position 7 field shunt drops altogether - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - /* - // crude woodward approximation; difference between rpm for consecutive positions is ~5% - // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction - auto const woodward { std::clamp( - ( DElist[ MainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, - 0.0, 1.0 ) }; - */ - break; - } - case 46: - { - // wzrastanie - if (MainCtrlPos >= 12 && ScndCtrlPos < ScndCtrlPosNo) - { - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Iup > Im) - { - ++ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos - 1].Iup > Im && MPTRelay[ScndCtrlPos].Iup < Vel) - { - ++ScndCtrlPos; - } - } - } - // malenie - if (MainCtrlPos < 12 && ScndCtrlPos > 0 && Vel < 50.0) - { - // above 50 km/h already active shunt field can be maintained until lower controller setting - if (ScndCtrlPos % 2 == 0) - { - if (MPTRelay[ScndCtrlPos].Idown < Im) - { - --ScndCtrlPos; - } - } - else - { - if (MPTRelay[ScndCtrlPos + 1].Idown < Im && MPTRelay[ScndCtrlPos].Idown > Vel) - { - --ScndCtrlPos; - } - } - } - if (MainCtrlPos < 11) - { - ScndCtrlPos = std::min(2, ScndCtrlPos); - } - if (MainCtrlPos < 8) - { - ScndCtrlPos = 0; - } - break; - } - default: - { - break; - } - } // switch RelayType - - if (ScndCtrlPos != shuntfieldstate) - { - SetFlag(SoundFlag, sound::relay | sound::shuntfield); - } - } - } - break; - } // DieselElectric - - case TEngineType::ElectricInductionMotor: - { - if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) - { - double ActiveInverters = 0.0; - for (auto const &inv : Inverters) - { - if (inv.IsActive) - ActiveInverters += 1.0; - } - InvertersRatio = ActiveInverters / (double)InvertersNo; - if (EIM_Pmax_Table.size() > 1) - { - eimc[eimc_p_Pmax] = TableInterpolation(EIM_Pmax_Table, Vel); - } - // tempomat - if (ScndCtrlPosNo == 4 && SpeedCtrlTypeTime) - { - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - switch (ScndCtrlPos) - { - case 0: - NewSpeed = 0; - SpeedCtrlValue = 0; - SpeedCtrlTimer = 10; - break; - case 1: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed -= 10; - if (NewSpeed < 0) - NewSpeed = 0; - } - else - SpeedCtrlTimer += dt; - break; - case 2: - SpeedCtrlTimer = 10; - SpeedCtrlValue = NewSpeed; - break; - case 3: - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - SpeedCtrlTimer = 0; - NewSpeed += 10; - if (NewSpeed > Vmax) - NewSpeed = Vmax; - } - else - SpeedCtrlTimer += dt; - break; - case 4: - NewSpeed = Vmax; - SpeedCtrlValue = Vmax; - SpeedCtrlTimer = 10; - break; - default: - break; - } - } - else if (ScndCtrlPosNo > 1) - { - if (ScndCtrlPos != NewSpeed) - { - - SpeedCtrlTimer = 0; - NewSpeed = ScndCtrlPos; - } - else - { - SpeedCtrlTimer += dt; - if (SpeedCtrlTimer > SpeedCtrlDelay) - { - auto NewSCAP = static_cast((float)ScndCtrlPos / (float)ScndCtrlPosNo * Vmax); - if (NewSCAP != SpeedCtrlValue) - { - SpeedCtrlValue = NewSCAP; - // SendCtrlToNext("SpeedCntrl", SpeedCtrlValue, CabActive); - } - } - } - SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; - } - double edBCP = Hamulec->GetEDBCP(); - auto const localbrakeactive{CabOccupied != 0 && LocHandle->GetCP() > 0.25}; - // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza - // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem - auto const dynbrakectrlactive{SplitEDPneumaticBrake && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; - auto const localbrakeforED{SplitEDPneumaticBrake ? false : localbrakeactive}; - if (false == Doors.instances[side::left].is_closed || false == Doors.instances[side::right].is_closed || - (Doors.permit_needed && (Doors.instances[side::left].open_permit || Doors.instances[side::right].open_permit))) - { - DynamicBrakeFlag = true; - } - else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && AnPos < 0.01) || - (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && LocalBrakePosA < 0.01)) - DynamicBrakeFlag = false; - else if (BrakePress > 0.25 && edBCP > 0.25 || localbrakeforED || AnPos > 0.02 || dynbrakectrlactive) - DynamicBrakeFlag = true; - edBCP = Hamulec->GetEDBCP() * eimc[eimc_p_abed]; // stala napedu - if (DynamicBrakeFlag) - { - // ustalanie współczynnika blendingu do luzowania hamulca PN - if (eimv[eimv_Fmax] * Sign(V) * DirAbsolute < -1) - { - PosRatio = -Sign(V) * DirAbsolute * eimv[eimv_Fr] / (eimc[eimc_p_Fh] * std::max(edBCP, std::max(0.01, Hamulec->GetEDBCP())) / MaxBrakePress[0]); - PosRatio = std::clamp(PosRatio, 0.0, 1.0); - } - else - { - PosRatio = 0; - } - PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED - if (PosRatio < 19.5 / 20.0) - PosRatio *= 0.9; - Hamulec->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia - // ustalanie siły hamowania ED - if (Hamulec->GetEDBCP() > 0.25 && eimc[eimc_p_abed] < 0.001 || ActiveInverters < InvertersNo) // jeśli PN wyłącza ED - { - PosRatio = 0; - eimv[eimv_Fzad] = 0; - } - else - { - // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci - double const vhRamp = std::max(0.0, std::min(1.0, (Vel - eimc[eimc_p_Vh0]) / (eimc[eimc_p_Vh1] - eimc[eimc_p_Vh0]))); - if (SplitEDPneumaticBrake) - { - // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl - // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) - double const edLeverDemand = DynamicBrakeRatio(); - PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / MaxBrakePress[0], 1.0)), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(edLeverDemand, edBCP / MaxBrakePress[0])); - } - else - { - PosRatio = -std::max(std::min(edBCP * 1.0 / MaxBrakePress[0], 1.0), AnPos) * vhRamp; - eimv[eimv_Fzad] = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / MaxBrakePress[0])); - } - } - tmp = 5; - } - else - { - PosRatio = std::max(eimic_real, 0.); - eimv[eimv_Fzad] = PosRatio; - if (Flat && eimc[eimc_p_F0] * eimv[eimv_Fful] > 0) - PosRatio = std::min(PosRatio * eimc[eimc_p_F0] / eimv[eimv_Fful], 1.); - /* if (ScndCtrlActualPos > 0) //speed control - if (Vmax < 250) - PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); - else - PosRatio = - std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ - // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio - Hamulec->SetED(0); - // (Hamulec as TLSt).SetLBP(LocBrakePress); - tmp = 4; // szybkie malenie, powolne wzrastanie - } - // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions - // TODO: gather these in single place so they can be resolved together - if (SlippingWheels) - { - PosRatio = 0; - tmp = 10; - SandboxAuto(true, range_t::unit); - } // przeciwposlizg - else - { - // switch sandbox off - SandboxAuto(false, range_t::unit); - } - if (ActiveInverters == 0.0) - { - PosRatio = 0; - eimv_pr = 0; - } - - eimv_pr += std::max(std::min(PosRatio - eimv_pr, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio= 0) - Vadd *= 1.0 - 2.0 * dt; - else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) - Vadd *= 1.0 - dt; - else - Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); - Itot = eimv[eimv_Ipoj] * (0.01 + std::min(0.99, 0.99 - Vadd)); - - EnginePower = abs(eimv[eimv_Ic] * eimv[eimv_U] * NPoweredAxles) / 1000; - // power inverters - auto const tmpV{std::abs(eimv[eimv_fp])}; - auto const useFFEDList = FFEDListSize > 0 && DynamicBrakeFlag; - auto const list = useFFEDList ? FFEDlist : FFlist; - - if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(eimv[eimv_If]) > 1.0 && tmpV > 0.0001) - { - - int i = 0; - while (i < listSize - 1 && list[i + 1].v < tmpV) - { - ++i; - } - InverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; - } - else - { - InverterFrequency = 0.0; - } - - Mm = eimv[eimv_M] * DirAbsolute; - Mw = Mm * Transmision.Ratio * Transmision.Efficiency; - Fw = Mw * 2.0 / WheelDiameter; - Ft = Fw * NPoweredAxles * InvertersRatio; - eimv[eimv_Fr] = DirAbsolute * Ft / 1000; - } // mains - else - { - for (auto &inv : Inverters) - { - inv.Freal = 0.0; - inv.IsActive = false; - } - Im = 0.0; - Mm = 0.0; - Mw = 0.0; - Fw = 0.0; - Ft = 0.0; - Itot = 0.0; - eimv_pr = 0.0; - EnginePower = 0.0; - { - for (auto &eimvvalue : eimv) - eimvvalue = 0.0; - } - Hamulec->SetED(0.0); - InverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); - } - break; - } // ElectricInductionMotor - - case TEngineType::None: - default: - { - break; - } - } // case EngineType - - if (EngineType == TEngineType::DieselElectric) - { - // rough approximation of extra effort to overcome friction etc - EnginePower += EngineRPMRatio() * 0.15 * DElist[MainCtrlPosNo].GenPower; - } - - return Ft; -} - -// ************************************************************************************************* -// Q: 20160713 -// Obliczenie predkości obrotowej kół??? -// ************************************************************************************************* -double TMoverParameters::ComputeRotatingWheel(double WForce, double dt, double n) const -{ - double newn = 0; - double eps = 0; - if (n == 0 && WForce * Sign(V) < 0) - newn = 0; - else - { - eps = WForce * WheelDiameter / (2.0 * AxleInertialMoment); - newn = n + eps * dt; - if (newn * n <= 0 && eps * n < 0) - newn = 0; - } - return newn; -} - -// ************************************************************************************************* -// Q: 20160713 -// Sprawdzenie bezpiecznika nadmiarowego -// ************************************************************************************************* -bool TMoverParameters::FuseFlagCheck(void) const -{ - bool FFC; - - FFC = false; - if (Power > 0.01) - FFC = FuseFlag; - else // pobor pradu jezeli niema mocy - for (auto &thiscoupler : Couplers) - if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) - FFC = thiscoupler.Connected->FuseFlagCheck(); - - return FFC; -} - -// ************************************************************************************************* -// Q: 20160713 -// Załączenie bezpiecznika nadmiarowego -// ************************************************************************************************* -bool TMoverParameters::FuseOn(range_t const Notify) -{ - auto const result{RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload, Notify)}; - - return result; -} - -// ************************************************************************************************* -// Q: 20160713 -// Wyłączenie bezpiecznika nadmiarowego -// ************************************************************************************************* -void TMoverParameters::FuseOff(void) -{ - if (!FuseFlag) - { - FuseFlag = true; - EventFlag = true; - SetFlag(SoundFlag, sound::relay | sound::loud); - } -} - -// resets relays assigned to specified customizable reset button -bool TMoverParameters::UniversalResetButton(int const Button, range_t const Notify) -{ - - if (auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; false == lowvoltagepower) - { - return false; - } - - auto const relays{UniversalResetButtonFlag[Button]}; - if (relays == 0) - { - return false; - } - - auto const result{RelayReset(relays, Notify)}; - - return result; -} - -// resets state of specified relays -bool TMoverParameters::RelayReset(int const Relays, range_t const Notify) -{ - - auto const lowvoltagepower{Power24vIsAvailable || Power110vIsAvailable}; - bool reset{false}; - - if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && - (GroundRelayStart == start_t::manual || GroundRelayStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && - !TestFlag(EngDmgFlag, 1)) - { - // NOTE: true means the relay is operational - reset |= !GroundRelay && lowvoltagepower; - GroundRelay |= lowvoltagepower; - } - - if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && ScndCtrlPos == 0 && DirActive != 0 && - !TestFlag(EngDmgFlag, 1)) - { - // NOTE: false means the relay is operational - // TODO: cleanup, flip the FuseFlag code to match other relays - // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= FuseFlag && lowvoltagepower; - FuseFlag &= !lowvoltagepower; - } - - if (TestFlag(Relays, relay_t::primaryconverteroverload) && ConverterOverloadRelayStart == start_t::manual - // && ( false == Mains ) - && false == ConverterAllow) - { - // NOTE: false means the relay is operational - // TODO: cleanup, flip the FuseFlag code to match other relays - // TODO: check whether the power is required, TBD, TODO: make it configurable? - reset |= ConvOvldFlag && lowvoltagepower; - ConvOvldFlag &= !lowvoltagepower; - } - - if (reset) - { - SetFlag(SoundFlag, sound::relay | sound::loud); - } - - if (Notify != range_t::local) - { - SendCtrlToNext("RelayReset", Relays, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return reset; -} - -// ************************************************************************************************* -// Q: 20160713 -// Przeliczenie prędkości liniowej na obrotową -// ************************************************************************************************* -double TMoverParameters::v2n(void) -{ - // przelicza predkosc liniowa na obrotowa - const double dmgn = 0.5; - double n; - double deltan = 0; - - n = V / (M_PI * WheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] - deltan = n - nrot; //"pochodna" prędkości obrotowej - /* if (SlippingWheels) - if (std::abs(deltan) < 0.001) - SlippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też - if (SlippingWheels) // nie ma zwiazku z predkoscia liniowa V - { // McZapkie-221103: uszkodzenia kol podczas poslizgu - if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_wheelwear)) // podkucie - EventFlag = true; - if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && SetFlag(DamageFlag, dtrain_thinwheel)) // wycieranie sie obreczy - EventFlag = true; - n = nrot; // predkosc obrotowa nie zalezy od predkosci liniowej - } - return n; -} - -// ************************************************************************************************* -// Q: 20160714 -// Oblicza moment siły wytwarzany przez silnik -// ************************************************************************************************* -double TMoverParameters::Momentum(double I) const -{ - // liczy moment sily wytwarzany przez silnik elektryczny} - int SP; - - SP = ScndCtrlActualPos; - if (ScndInMain && !(RList[MainCtrlActualPos].ScndAct == 255)) - SP = RList[MainCtrlActualPos].ScndAct; - - // Momentum:=mfi*I*(1-1.0/(Abs(I)/mIsat+1)); - return motor_param(SP).mfi * I * (abs(I) / (abs(I) + motor_param(SP).mIsat) - motor_param(SP).mfi0); -} - -// ************************************************************************************************* -// Q: 20160714 -// Oblicza moment siły do sterowania wzbudzeniem -// ************************************************************************************************* -double TMoverParameters::MomentumF(double I, double Iw, int SCP) const -{ - // umozliwia dokladne sterowanie wzbudzeniem - - return motor_param(SCP).mfi * I * std::max(abs(Iw) / (abs(Iw) + motor_param(SCP).mIsat) - motor_param(SCP).mfi0, 0.); -} - -// ************************************************************************************************* -// Q: 20160713 -// Odłączenie uszkodzonych silników -// ************************************************************************************************* -bool TMoverParameters::CutOffEngine(void) -{ - bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba - if (NPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && SetFlag(DamageFlag, -dtrain_engine)) - { - NPoweredAxles = NPoweredAxles / 2; // bylo div czyli mod? - COE = true; - } - return COE; -} - -// ************************************************************************************************* -// Q: 20160713 -// Przełączenie wysoki / niski prąd rozruchu -// ************************************************************************************************* -bool TMoverParameters::MaxCurrentSwitch(bool State, range_t const Notify) -{ - auto const initialstate{MotorOverloadRelayHighThreshold}; - - MotorOverloadRelayHighThreshold = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("MaxCurrentSwitch", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return State != initialstate; -} - -// ************************************************************************************************* -// Q: 20160713 -// Przełączenie wysoki / niski prąd rozruchu automatycznego -// ************************************************************************************************* -bool TMoverParameters::MinCurrentSwitch(bool State) -{ - bool MCS = false; - if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (TrainType == dt_EZT && EngineType != TEngineType::ElectricInductionMotor)) - { - - if (State && Imin == IminLo) - { - Imin = IminHi; - MCS = true; - if (CabActive != 0) - SendCtrlToNext("MinCurrentSwitch", 1, CabActive); - } - if (!State && Imin == IminHi) - { - Imin = IminLo; - MCS = true; - if (CabActive != 0) - SendCtrlToNext("MinCurrentSwitch", 0, CabActive); - } - } - return MCS; -} - -// ************************************************************************************************* -// Q: 20160713 -// Sprawdzenie wskaźnika jazdy na oporach -// ************************************************************************************************* -bool TMoverParameters::ResistorsFlagCheck(void) const -{ - bool RFC = false; - - if (Power > 0.01) - RFC = ResistorsFlag; - else // pobor pradu jezeli niema mocy - { - for (auto &thiscoupler : Couplers) - if (TestFlag(thiscoupler.CouplingFlag, coupling::control) && thiscoupler.Connected->Power > 0.01) - RFC = thiscoupler.Connected->ResistorsFlagCheck(); - } - return RFC; -} - -// ************************************************************************************************* -// Q: 20160713 -// Włączenie / wyłączenie automatycznego rozruchu -// ************************************************************************************************* -bool TMoverParameters::AutoRelaySwitch(bool State) -{ - bool ARS; - if (AutoRelayType == 2 && AutoRelayFlag != State) - { - AutoRelayFlag = State; - ARS = true; - SendCtrlToNext("AutoRelaySwitch", int(State), CabActive); - } - else - ARS = false; - - return ARS; -} - -// ************************************************************************************************* -// Q: 20160724 -// Sprawdzenie warunków pracy automatycznego rozruchu -// ************************************************************************************************* - -bool TMoverParameters::AutoRelayCheck(void) -{ - bool OK = false; // b:int; - - auto const motorconnectorsoff{false == MotorConnectorsCheck()}; - - // Ra 2014-06: dla SN61 nie działa prawidłowo - // yBARC - rozlaczenie stycznikow liniowych - if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) - { - StLinFlag = false; - OK = false; - if (false == DynamicBrakeFlag) - { - Im = 0; - Itot = 0; - ResistorsFlag = false; - } - } - - // sprawdzenie wszystkich warunkow (AutoRelayFlag, AutoSwitch, Im 0 || ScndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == MainCtrlPos)) - { // zmieniaj scndctrlactualpos - // scnd bez samoczynnego rozruchu - if (ScndCtrlActualPos < ScndCtrlPos) - { - if (LastRelayTime > CtrlDelay && ARFASI2) - { - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else if (ScndCtrlActualPos > ScndCtrlPos) - { - if (LastRelayTime > CtrlDownDelay && TrainType != dt_EZT) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; - } - else - { // zmieniaj mainctrlactualpos - // running backwards, the motors don't get joined in more branches than allowed (the series connection - // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it - // was, the line contactors closed, whatever the driver did with the master controller) - auto const backwardslimit{DirActive < 0 && TrainType != dt_PseudoDiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; - // main bez samoczynnego rozruchu - if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table - && (RList[MainCtrlActualPos].Relay < MainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == MainCtrlPos && MainCtrlActualPos < RlistSize) || - (TrainType == dt_ET22 && DelayCtrlFlag))) - { - - // prevent switch to parallel mode if motor overload relay is set to high threshold mode - if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) - { - return false; - } - - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && MainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - ++MainCtrlActualPos; - if (MainCtrlPos - MainCtrlActualPos == 1) - { - // HACK: ensure we play only single sound of basic relays for entire trasition; return false - // for all but last step despite configuration change, to prevent playback of the basic relay sound - // TBD, TODO: move the basic sound event here and enable it with call parameter - OK = true; - } - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel | sound::loud); - OK = true; - } - } - else if (LastRelayTime > CtrlDelay && ARFASI) - { - // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + - // FloatToStr(CtrlDelay)); - if (TrainType == dt_ET22 && MainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || DelayCtrlFlag)) - { - // et22 z walem grupowym - if (!DelayCtrlFlag) // najpierw przejscie - { - ++MainCtrlActualPos; - DelayCtrlFlag = true; // tryb przejscia - OK = true; - } - else if (LastRelayTime > 4 * CtrlDelay) // przejscie - { - - DelayCtrlFlag = false; - OK = true; - } - /* - else - ; - */ - } - else // nie ET22 z wałem grupowym - { - ++MainCtrlActualPos; - OK = true; - } - //--------- - // hunter-111211: poprawki - if (MainCtrlActualPos > 0) - { - if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) - { - // wejscie na bezoporowa - SetFlag(SoundFlag, sound::parallel | sound::loud); - } - else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) - { - // wejscie na drugi uklad - SetFlag(SoundFlag, sound::parallel); - } - } - } - } - else if (RList[MainCtrlActualPos].Relay > MainCtrlPos) - { - if (RList[MainCtrlPos].R == 0 && MainCtrlPos > 0 && !(MainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) - { - // szybkie wchodzenie na bezoporowa (303E) - // MainCtrlActualPos:=MainCtrlPos; //hunter-111012: - --MainCtrlActualPos; - OK = true; - if (RList[MainCtrlActualPos].R == 0) - { - SetFlag(SoundFlag, sound::parallel); - } - } - else if (LastRelayTime > CtrlDownDelay) - { - if (TrainType != dt_EZT) // tutaj powinien być tryb sterowania wałem - { - --MainCtrlActualPos; - OK = true; - } - // hunter-111211: poprawki - if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) - { - // dzwieki schodzenia z bezoporowej} - SetFlag(SoundFlag, sound::parallel); - } - } - } - else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) - { - if (LastRelayTime > CtrlDownDelay) - { - --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych - SetFlag(SoundFlag, sound::shuntfield); - OK = true; - } - } - else - OK = false; - } - } - else // not StLinFlag - { - OK = false; - // ybARC - zalaczenie stycznikow liniowych - if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (TrainType == dt_EZT || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) - { - - DelayCtrlFlag = true; - if (LastRelayTime >= InitialCtrlDelay) - { - StLinFlag = true; - MainCtrlActualPos = 1; - DelayCtrlFlag = false; - SetFlag(SoundFlag, sound::relay | sound::loud); - OK = true; - } - } - else - { - DelayCtrlFlag = false; - } - - if (false == StLinFlag && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) - { - - if (CoupledCtrl) - { - - if (TrainType == dt_EZT) - { - // EN57 wal jednokierunkowy calosciowy - if (MainCtrlActualPos == 1) - { - - MainCtrlActualPos = 0; - OK = true; - } - else - { - - if (LastRelayTime > CtrlDownDelay) - { - - if (MainCtrlActualPos < RlistSize) - { - // dojdz do konca - ++MainCtrlActualPos; - } - else if (ScndCtrlActualPos < ScndCtrlPosNo) - { - // potem boki - ++ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - // i sie przewroc na koniec - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - } - OK = true; - } - } - } - else - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (ScndCtrlActualPos > 0) - { - --ScndCtrlActualPos; - SetFlag(SoundFlag, sound::shuntfield); - } - else - { - --MainCtrlActualPos; - } - OK = true; - } - } - } - else if (HasCamshaft) - { - // wal kulakowy dwukierunkowy - if (LastRelayTime > CtrlDownDelay) - { - if (MainCtrlActualPos > 0) - { - --MainCtrlActualPos; - } - ScndCtrlActualPos = 0; - OK = true; - } - } - else - { - MainCtrlActualPos = 0; - ScndCtrlActualPos = 0; - OK = true; - } - } - } - if (OK) - LastRelayTime = 0; - - return OK; - } -} - -bool TMoverParameters::MotorConnectorsCheck() -{ - - // hunter-111211: wylacznik cisnieniowy - ControlPressureSwitch = HasControlPressureSwitch && (BrakePress > 2.0 || PipePress < 3.6); - - if (true == ControlPressureSwitch) - { - return false; - } - - // a line breaker closed ahead of the pantographs holds without voltage; what cuts the motors off there is its - // undervoltage relay, which elsewhere opens the line breaker - auto const undervoltage{PantographsRequireMains && false == NoVoltRelay}; - - auto const connectorsoff{false == Mains || undervoltage || true == FuseFlag || true == StLinSwitchOff || DirActive == 0}; - - return false == connectorsoff && LineContactorsInterlockReleased(); -} - -bool TMoverParameters::LineContactorsInterlockReleased() const -{ - switch (LineContactorsInterlock) - { - case line_contactors_interlock::converter: - // the converter of this very vehicle, not the 110 V of the trainset: a section with its fans off doesn't start - return ConverterFlag; - case line_contactors_interlock::motor_blowers: - return std::ranges::all_of(MotorBlowers, [this](auto const &Blower) { - if (Blower.min_start_velocity < 0) - { - return Blower.is_active; - } - // a blower which starts with the speed and the motor current (MotorBlowersStartVelocity) can't run before - // the contactors close, nor after a stop longer than it keeps running for: it's enough that it's - // switched on and has power, so it starts once the vehicle moves - return MotorBlowerPowerIsAvailable(Blower) && false == Blower.is_disabled && (Blower.start_type == start_t::manual ? Blower.is_enabled : true); - }); - default: - return true; - } -} - -bool TMoverParameters::OperatePantographsValve(operation_t const State, range_t const Notify) -{ - - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && EnginePowerSource.CollectorParameters.CollectorsNo > 0) - { - - auto &valve{PantsValve}; - - 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("PantsValve", static_cast(State), CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return true; -} - -bool TMoverParameters::OperatePantographValve(end 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("PantValve", - // 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(0x80 * (End == end::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(State)), CabActive, - Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return true; -} - -bool TMoverParameters::DropAllPantographs(bool const State, range_t const Notify) -{ - - auto const initialstate{PantAllDown}; - - PantAllDown = State; - - if (Notify != range_t::local) - { - SendCtrlToNext("PantAllDown", State ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return State != initialstate; -} - -namespace -{ -// the setting of the universal controller one UniCtrlValStep further from Value towards Limit, never past it -double next_uc_step(double const Value, double const Limit, double const Step) -{ - constexpr double epsilon{1e-6}; - if (Limit > Value) - { - return std::min((std::floor(Value / Step + epsilon) + 1.0) * Step, Limit); - } - return std::max((std::ceil(Value / Step - epsilon) - 1.0) * Step, Limit); -} - -// the universal controller with UniCtrlValStep: the setting the continuous ramp got to (Ramped) turned into whole steps. -// a move of the controller onto a position which changes the setting makes one step at once, the ramp then one step each -// time it covers a step's length; the steps stop at the position's set value (or its bound, past which the ramp doesn't go) -double stepped_uc_value(double const Current, double const Ramped, TUniversalCtrl const &Position, double const Step, bool const Moved, double &Progress) -{ - if (Moved) - { - Progress = 0.0; - } - double const delta{Ramped - Current}; - if (std::abs(delta) < 1e-9) - { - Progress = 0.0; - return Ramped; - } - double limit{0.0}; - if (delta > 0.0) - { - limit = Position.SetCtrlVal > Current ? Position.SetCtrlVal : Position.MaxCtrlVal; - } - else - { - limit = Position.SetCtrlVal < Current ? Position.SetCtrlVal : Position.MinCtrlVal; - } - Progress = Moved ? Step : Progress + std::abs(delta); - double value{Current}; - bool reached{std::abs(value - limit) < 1e-9}; - while (!reached && Progress >= Step - 1e-9) - { - value = next_uc_step(value, limit, Step); - Progress -= Step; - reached = std::abs(value - limit) < 1e-9; - } - if (reached) - { - Progress = 0.0; - } - // added after the move to std::clamp: bounds given the other way round are put in order, as master did it - auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); - return std::clamp(value, lowest, highest); -} -} // namespace - -void TMoverParameters::CheckEIMIC(double dt) -{ - double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; - double multiplier = (EIMCtrlEmergency ? 1.0 : 0.0) + offset; - // gdy SplitEDPneumaticBrake jest wlaczone, sterowanie ujemne (hamowanie ED) bierzemy - // z osobnego nastawnika DynamicBrakeCtrl, a nie z hamulca pomocniczego (LocalBrake). - // Dodatkowo zapotrzebowanie ED jest ograniczone przez strefe Vh0..Vh1: powyzej Vh1 - pelny ED, - // pomiedzy Vh1 a Vh0 - liniowe zanikanie, ponizej Vh0 - zerowe (brak hamowania pneumatycznego - // jako uzupelnienia, poniewaz LocalBrake jest oddzielny i operuje wylacznie pneumatyka). - double brakeDemand = SplitEDPneumaticBrake ? DynamicBrakeRatio() : LocalBrakeRatio(); - if (SplitEDPneumaticBrake) - { - double const vh0 = eimc[eimc_p_Vh0]; - double const vh1 = eimc[eimc_p_Vh1]; - if (vh1 > vh0 + 0.001) - { - double const vhRamp = std::clamp((Vel - vh0) / (vh1 - vh0), 0.0, 1.0); - brakeDemand *= vhRamp; - } - } - switch (EIMCtrlType) - { - case 0: - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic_analog > 0.01 ? eimic_analog : (double)MainCtrlPos / (double)MainCtrlPosNo; - if (EIMCtrlAdditionalZeros || EIMCtrlEmergency) - { - if (eimic > 0.001) - eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); - if (eimic < -0.001 && BrakeHandle != TBrakeHandle::MHZ_EN57) - eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); - } - if (eimic > 0.001 && SpeedCtrlUnit.IsActive) - eimic = std::max(eimic, SpeedCtrlUnit.MinPower); - break; - case 1: - switch (MainCtrlPos) - { - case 0: // B+ - eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 - break; - case 1: // B - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 - break; - case 2: // B- - case 3: // 0 - case 4: // T- - eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 - break; - case 5: // T - eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 - break; - case 6: // T+ - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 - break; - case 7: // TMax - eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max - break; - default: - break; - } - if (MainCtrlPos >= 3 && eimic < 0) - eimic = 0; - if (MainCtrlPos <= 3 && eimic > 0) - eimic = 0; - break; - case 2: - if (IsMainCtrlEmergencyPos()) - { - // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() - eimic = -1.0; - } - else if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - double delta = MainCtrlActualPos == MainCtrlPos ? dt * CtrlDelay : 0.01; - // the positions below are those of the controller without the emergency brake position - switch (MainCtrlPos - EIMCtrlEmergencyPositions()) - { - case 0: - case 1: - eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 - if (eimic > 0) - eimic = 0; - break; - case 2: - eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 - break; - case 3: - eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 - break; - case 4: - eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 - if (eimic < 0) - eimic = 0; - break; - default: - break; - } - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - break; - case 3: - if (UniCtrlIntegratedBrakePNCtrl) - { - if (UniCtrlList[MainCtrlPos].mode != BrakeCtrlPos && MainCtrlActualPos == MainCtrlPos) // there was no move of controller, but brake only - { - if (BrakeCtrlPos < UniCtrlList[MainCtrlPosNo].mode) - BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping - if (BrakeCtrlPos > UniCtrlList[0].mode) - BrakeLevelSet(UniCtrlList[0].mode); // top clamping - if (IsCabMaster()) - { - while (BrakeCtrlPos > UniCtrlList[MainCtrlPos].mode) - DecMainCtrl(1); // find nearest position - while (BrakeCtrlPos < UniCtrlList[MainCtrlPos].mode) - IncMainCtrl(1); // find nearest position - } - } - else // controller was moved - BrakeLevelSet(UniCtrlList[MainCtrlPos].mode); - } - - if (MainCtrlActualPos != MainCtrlPos || LastRelayTime > InitialCtrlDelay) - { - auto const &position{UniCtrlList[MainCtrlPos]}; - double ramped{eimic}; - ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X - ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, - MainCtrlActualPos == MainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X - ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); - eimic = UniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, UniCtrlValStep, MainCtrlActualPos != MainCtrlPos, eimic_step_progress) : ramped; - } - if (MainCtrlActualPos == MainCtrlPos) - LastRelayTime += dt; - else - { - LastRelayTime = 0; - MainCtrlActualPos = MainCtrlPos; - } - if (Hamulec->GetEDBCP() > 0.3 && eimic < 0 && !UniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake - eimic = 0; // shut off retarder - if (UniCtrlIntegratedBrakeCtrl == false && UniCtrlIntegratedLocalBrakeCtrl == false) - { - // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, - // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy - eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; - } - } - if (LocHandleTimeTraxx) - { - if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie - { - eim_localbrake -= dt * 0.17; - } - - if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie - { - eim_localbrake += dt * 0.17; - eim_localbrake = std::max(eim_localbrake, BrakePress / MaxBrakePress[0]); - } - else // pozycja 1, utrzymanie cisnienia - { - if (eim_localbrake < Hamulec->GetEDBCP() / MaxBrakePress[0]) - eim_localbrake = 0; - } - eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); - if (eim_localbrake > 0.04 && eimic > 0) - eimic = 0; - } - - auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!SpringBrake.IsActive || !SpringBrakeCutsOffDrive) && !LockPipe && DirAbsolute != 0}; - auto const eimicdoorenabled{(SpringBrake.IsActive && ReleaseParkingBySpringBrakeWhenDoorIsOpen)}; - double eimic_max = 0.0; - if (Doors.instances[side::left].open_permit == false && Doors.instances[side::right].open_permit == false) - { - if (eimicpowerenabled) - { - eimic_max = 1.0; - } - else - { - eimic_max = 0.001; - } - } - else - { - if (eimicdoorenabled) - { - eimic_max = 0.001; - } - } - eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); -} - -void TMoverParameters::CheckSpeedCtrl(double dt) -{ - if (EIMCtrlType == 0) - { - SpeedCtrlUnit.DesiredPower = std::max(eimic, 0.0); - } - double accfactor = SpeedCtrlUnit.DesiredPower; - if (EIMCtrlType >= 2) - { - if (MainCtrlPos < MainCtrlPosNo - 2) - { - SpeedCtrlUnit.Standby = true; - } - if (MainCtrlPos > MainCtrlPosNo - 1) - { - SpeedCtrlUnit.Standby = false; - } - if (!SpeedCtrlUnit.BrakeIntervention && (Hamulec->GetEDBCP() > 0.4 || PipePress < HighPipePress - 0.2)) - SpeedCtrlUnit.Standby = true; - if (EIMCtrlType >= 3 && UniCtrlList[MainCtrlPos].SpeedUp <= 0) - { - accfactor = 0.0; - eimicSpeedCtrl = 0; - } - } - if (SpeedCtrlUnit.IsActive) - { // speed control - if (true) - { - if (!SpeedCtrlUnit.Standby) - { - if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) - eimic = 1.0; - double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; - double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; - double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module - bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; - if (eSCP < -1.0) - { - SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrl < -0.99 * SpeedCtrlUnit.DesiredPower; - eSCP = -1.0; - } - SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; - if (abs(eSCP) < 0.999) - { - // TODO: check how to disable integral part when braking in smart way - // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; - eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); - } - else - { - eimicSpeedCtrlIntegral = 0; - } - auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; - eimicSpeedCtrl = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrl - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrl + SpeedCtrlUnit.PowerUpSpeed * dt); - if (Vel < SpeedCtrlUnit.FullPowerVelocity) - { - eimicSpeedCtrl = std::min(eimicSpeedCtrl, SpeedCtrlUnit.InitialPower); - } - if (Vel < SpeedCtrlUnit.StartVelocity && MainCtrlPos < MainCtrlPosNo) - { - eimicSpeedCtrl = 0; - eimic = 0; - } - } - else - { - eimicSpeedCtrl = 0; - eimicSpeedCtrlIntegral = 0; - } - SpeedCtrlUnit.Parking = Vel == 0.0 && eimic <= 0 && EngineType != TEngineType::ElectricInductionMotor; - SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); - } - else - { - if (Vmax < 250) - eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue - Vel), -1.0, 1.0); - else - eimicSpeedCtrl = std::clamp(0.5 * (SpeedCtrlValue * 2 - Vel), -1.0, 1.0); - } - if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && Hamulec->GetEDBCP() > 0.25) - { - DecScndCtrl(2); - SpeedCtrlUnit.IsActive = false; - } - } - else - { - eimicSpeedCtrl = 1; - eimicSpeedCtrlIntegral = 0; - SpeedCtrlUnit.Parking = false; - SendCtrlToNext("SpeedCtrlUnit.Parking", SpeedCtrlUnit.Parking, CabActive); - } -} - -void TMoverParameters::SpeedCtrlButton(int button) -{ - if (SpeedCtrl && ScndCtrlPos > 0) - { - SpeedCtrlValue = SpeedCtrlButtons[button]; - } -} - -void TMoverParameters::SpeedCtrlInc() -{ - if (SpeedCtrl && ScndCtrlPos > 0) - { - double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; - SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); - } -} - -void TMoverParameters::SpeedCtrlDec() -{ - if (SpeedCtrl && ScndCtrlPos > 0) - { - double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; - SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); - } -} - -bool TMoverParameters::SpeedCtrlPowerInc() -{ - if (!(SpeedCtrl && ScndCtrlPos > 0)) - return false; - - if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) - return false; - - SpeedCtrlUnit.DesiredPower = std::min(SpeedCtrlUnit.DesiredPower + SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MaxPower); - return true; -} - -bool TMoverParameters::SpeedCtrlPowerDec() -{ - if (!(SpeedCtrl && ScndCtrlPos > 0)) - return false; - - if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) - return false; - - SpeedCtrlUnit.DesiredPower = std::max(SpeedCtrlUnit.DesiredPower - SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MinPower); - return true; -} - -// ************************************************************************************************* -// Q: 20160715 -// Zmienia parametr do którego dąży sprzęgło -// ************************************************************************************************* -bool TMoverParameters::dizel_EngageSwitch(double state) -{ - if (EngineType == TEngineType::DieselEngine && state <= 1 && state >= 0 && state != dizel_engagestate) - { - dizel_engagestate = state; - return true; - } - else - return false; -} - -// ************************************************************************************************* -// Q: 20160715 -// Zmienia parametr do którego dąży sprzęgło -// ************************************************************************************************* -bool TMoverParameters::dizel_EngageChange(double dt) -{ - double engagespeed = 0; // OK:boolean; - bool DEC; - - DEC = false; - if (dizel_engage - dizel_engagestate > 0) - engagespeed = engagedownspeed; - else - engagespeed = engageupspeed; - if (dt > 0.2) - dt = 0.1; - if (abs(dizel_engage - dizel_engagestate) < 0.11) - { - if (dizel_engage != dizel_engagestate) - { - DEC = true; - dizel_engage = dizel_engagestate; - } - // else OK:=false; //już jest false - } - else - { - dizel_engage = dizel_engage + engagespeed * dt * (dizel_engagestate - dizel_engage); - // OK:=false; - } - // dizel_EngageChange:=OK; - return DEC; -} - -// ************************************************************************************************* -// Q: 20160715 -// Automatyczna zmiana biegów gdy prędkość przekroczy widełki -// ************************************************************************************************* -bool TMoverParameters::dizel_AutoGearCheck(void) -{ - auto OK{false}; - - auto const VelUp{(motor_param(ScndCtrlActualPos).mfi0 != 0.0 ? - motor_param(ScndCtrlActualPos).mfi0 + (motor_param(ScndCtrlActualPos).mfi - motor_param(ScndCtrlActualPos).mfi0) * std::max(0.0, eimic_real) : - motor_param(ScndCtrlActualPos).mfi)}; - - auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimic_real <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; - - if (motor_param(ScndCtrlActualPos).AutoSwitch && Mains) - { - if (RList[MainCtrlPos].Mn == 0 && !hydro_TC) - { - if (dizel_engagestate > 0) - dizel_EngageSwitch(0); - if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) - dizel_automaticgearstatus = -1; - } - else - { - if (motor_param(ScndCtrlActualPos).AutoSwitch && dizel_automaticgearstatus == 0) // sprawdz czy zmienic biegi - { - if (Vel > VelUp) - { - // shift up - if (ScndCtrlActualPos < ScndCtrlPosNo) - { - dizel_automaticgearstatus = 1; - OK = true; - } - } - else if (Vel < VelDown) - { - // shift down - if (ScndCtrlActualPos > 0) - { - dizel_automaticgearstatus = -1; - OK = true; - } - } - } - } - if (dizel_engage < 0.1 && dizel_automaticgearstatus != 0) - { - if (dizel_automaticgearstatus == 1) - ScndCtrlActualPos++; - else - ScndCtrlActualPos--; - dizel_automaticgearstatus = 0; - dizel_EngageSwitch(1.0); - OK = true; - } - } - - if (Mains) - { - if (EIMCtrlType > 0) // sterowanie komputerowe - { - if (dizel_automaticgearstatus == 0) - { - if ((hydro_TC && hydro_TC_Fill > 0.01) || eimic_real > 0.005) - dizel_EngageSwitch(1.0); - else if (Vel > hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_EngageSwitch(0.5); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - } - else if (dizel_automaticgearstatus == 0) // ustaw cisnienie w silowniku sprzegla} - switch (RList[MainCtrlPos].Mn) - { - case 1: - dizel_EngageSwitch(0.5); - break; - case 2: - dizel_EngageSwitch(1.0); - break; - case 3: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.5); - break; - case 4: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.66); - break; - case 5: - if (Vel > dizel_minVelfullengage) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.35 * (1 + RList[MainCtrlPos].R) * RList[MainCtrlPos].R); - break; - default: - if (hydro_TC && hydro_TC_Fill > 0.01) - dizel_EngageSwitch(1.0); - else - dizel_EngageSwitch(0.0); - } - else - dizel_EngageSwitch(0.0); - if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) - dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych - if (!AutoRelayFlag) - ScndCtrlActualPos = ScndCtrlPos; - } - return OK; -} - -// performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise -bool TMoverParameters::dizel_StartupCheck() -{ - - auto engineisready{true}; // make inital optimistic presumption, then watch the reality crush it - - // test the fuel pump - // TODO: add fuel pressure check - if (false == FuelPump.is_active || (EngineType == TEngineType::DieselEngine && RList[MainCtrlPos].R == 0.0)) - { - engineisready = false; - // if( FuelPump.start_type == start_t::manual ) { - // with manual pump control startup procedure is done only once per starter switch press - dizel_startup = false; - // } - } - // test the oil pump - if (false == OilPump.is_active || OilPump.pressure < OilPump.pressure_minimum) - { - engineisready = false; - if (OilPump.start_type == start_t::manual) - { - // with manual pump control startup procedure is done only once per starter switch press - dizel_startup = false; - } - } - // test the water circuits and water temperature - if (true == dizel_heat.PA) - { - engineisready = false; - // TBD, TODO: reset startup procedure depending on pump and heater control mode - dizel_startup = false; - } - - return engineisready; -} - -// ************************************************************************************************* -// Q: 20160715 -// Aktualizacja stanu silnika -// ************************************************************************************************* -bool TMoverParameters::dizel_Update(double dt) -{ - - WaterPumpCheck(dt); - WaterHeaterCheck(dt); - OilPumpCheck(dt); - FuelPumpCheck(dt); - // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over - dizel_FiringCountdown = (Mains ? std::max(0.0, dizel_FiringCountdown - dt) : 0.0); - - if (true == dizel_startup && true == dizel_StartupCheck()) - { - dizel_ignition = true; - } - - if (true == dizel_ignition && LastSwitchingTime >= InitialCtrlDelay) - { - - dizel_startup = false; - dizel_ignition = false; - // TODO: split engine and main circuit state indicator in two separate flags - LastSwitchingTime = 0; - Timer::subsystem.switching.note(Timer::switching_counter::diesel, this, &TypeName, &Name); - Mains = true; - dizel_spinup = true; - dizel_FiringCountdown = dizel_SmokeDelay; - enrot = std::max(enrot, - 0.35 * ( // TODO: dac zaleznie od temperatury i baterii - EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0)); - } - - dizel_spinup = dizel_spinup && Mains && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? dizel_nmin : DElist[0].RPM / 60.0); - - if (true == Mains && false == FuelPump.is_active) - { - // knock out the engine if the fuel pump isn't feeding it - // TBD, TODO: grace period before the engine is starved for fuel and knocked out - // an engine started on its own stops on its own - MainSwitch(false, MainSwitchRange()); - } - - bool DU{false}; - - if (EngineType == TEngineType::DieselEngine) - { - dizel_EngageChange(dt); - DU = dizel_AutoGearCheck(); - double const fillspeed{2}; - dizel_fill = dizel_fill + fillspeed * dt * (dizel_fillcheck(MainCtrlPos, dt) - dizel_fill); - } - - dizel_Heat(dt); - - return DU; -} - -// ************************************************************************************************* -// Q: 20160715 -// oblicza napelnienie, uzwglednia regulator obrotow -// ************************************************************************************************* -double TMoverParameters::dizel_fillcheck(int mcp, double dt) -{ - auto realfill{0.0}; - - if (true == Mains && MainCtrlPosNo > 0 && true == FuelPump.is_active) - { - - if (true == dizel_ignition && LastSwitchingTime >= 0.9 * InitialCtrlDelay) - { - // wzbogacenie przy rozruchu - // NOTE: ignition flag is reset before this code is executed - // TODO: sort this out - realfill = 1; - } - else - { - // napelnienie zalezne od MainCtrlPos - if (EIMCtrlType > 0) - { - realfill = std::max(0.0, std::min(eimic_real, 1 - motor_param(ScndCtrlActualPos).Isat)); - if (eimic_real > 0.005 && !hydro_TC_Lockup) - { - dizel_nreg_min = std::min(dizel_nreg_min + 2.5 * dt, dizel_nmin_hdrive + eimic_real * dizel_nmin_hdrive_factor); - } - else - { - if (Vel < hydro_R_EngageVel && hydro_R && hydro_R_Fill > 0.01) - dizel_nreg_min = std::min(dizel_nreg_min + 5.0 * dt, dizel_nmin_retarder); - else - dizel_nreg_min = dizel_nmin; - } - if (!dizel_vel2nmax_Table.empty() && !hydro_TC_Lockup) - { - dizel_nreg_max = std::min(std::min(dizel_nreg_max, enrot) + dizel_nreg_acc * dt, TableInterpolation(dizel_vel2nmax_Table, Vel)); - } - else - { - dizel_nreg_max = dizel_nmax; - } - } - else - { - dizel_nreg_max = dizel_nmax; - realfill = RList[mcp].R; - } - } - if (dizel_nmax_cutoff > 0) - { - auto nreg{0.0}; - if (EIMCtrlType > 0) - nreg = eimic_real > 0.005 ? dizel_nreg_max : dizel_nmin; - else - switch (RList[MainCtrlPos].Mn) - { - case 0: - case 1: - nreg = dizel_nmin; - break; - case 2: - if (dizel_automaticgearstatus == 0 && true /*(!hydro_TC) || (dizel_engage>dizel_fill)*/) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 3: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin; - break; - case 4: - if (dizel_automaticgearstatus == 0 && Vel > dizel_minVelfullengage) - nreg = dizel_nmax; - else - nreg = dizel_nmin * 0.75 + dizel_nreg_max * 0.25; - break; - case 5: - if (Vel > dizel_minVelfullengage) - nreg = dizel_nreg_max; - else - nreg = dizel_nmin + 0.8 * (dizel_nreg_max - dizel_nmin) * RList[mcp].R; - break; - default: - realfill = 0; // sluczaj - break; - } - if (enrot > nreg) // nad predkoscia regulatora zeruj dawke - realfill = 0; - if (enrot < dizel_nreg_min && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna - realfill = 1; - } - } - - return std::clamp(realfill, 0.0, 1.0); -} - -// ************************************************************************************************* -// Q: 20160715 -// Oblicza moment siły wytwarzany przez silnik spalinowy -// ************************************************************************************************* -double TMoverParameters::dizel_Momentum(double Fill, double n, double dt) -{ // liczy moment sily wytwarzany przez silnik spalinowy} - double Moment = 0; - double enMoment = 0; - double gearMoment = 0; - double eps = 0; - double newn = 0; - double friction = 0; - double TorqueH = 0; - double TorqueL = 0; - double TorqueC = 0; - n = n * CabActive; - if (motor_param(ScndCtrlActualPos).mIsat < 0.001 || DirActive == 0) - n = enrot; - friction = dizel_engagefriction; - hydro_TC_nIn = enrot; // wal wejsciowy przetwornika momentu - hydro_TC_nOut = dizel_n_old; // wal wyjsciowy przetwornika momentu - - if (enrot > 0) - { - if (dizel_Momentum_Table.size() > 1) - { - Moment = TableInterpolation(dizel_Momentum_Table, enrot) * Fill - dizel_Mstand; - } - else - { - Moment = (dizel_Mmax - (dizel_Mmax - dizel_Mnmax) * square((enrot - dizel_nMmax) / (dizel_nMmax - dizel_nmax))) * Fill - dizel_Mstand; - } - Mm = Moment; - dizel_FuelConsumptionActual = dizel_FuelConsumption * enrot * Fill; - dizel_FuelConsumptedTotal += dizel_FuelConsumptionActual * dt / 3600.0; - if (hydro_R && hydro_R_Placement == 2) - Moment -= dizel_MomentumRetarder(enrot, dt); - } - else - { - Moment = -dizel_Mstand; - } - if (enrot < dizel_nmin / 10.0 && eAngle < M_PI_2) - { - // wstrzymywanie przy malych obrotach - Moment -= dizel_Mstand; - } - if (true == dizel_spinup) - Moment += dizel_Mstand / (0.3 + std::max(0.0, enrot / dizel_nmin)); // rozrusznik - - dizel_Torque = Moment; - - if (hydro_TC) // jesli przetwornik momentu - { - // napelnianie przetwornika - bool IsPower = EIMCtrlType > 0 ? eimic_real > 0.005 : MainCtrlPowerPos() > 0; - if (IsPower && Mains && enrot > dizel_nmin * 0.9) - hydro_TC_Fill += hydro_TC_FillRateInc * dt; - // oproznianie przetwornika - if ((!IsPower && Vel < dizel_maxVelANS) || !Mains || enrot < dizel_nmin * 0.8) - hydro_TC_Fill -= hydro_TC_FillRateDec * dt; - // obcinanie zakresu - hydro_TC_Fill = std::clamp(hydro_TC_Fill, 0.0, 1.0); - - // blokowanie sprzegla blokującego - if (Vel > hydro_TC_LockupSpeed && Mains && enrot > 0.9 * dizel_nmin && IsPower) - { - hydro_TC_Lockup = true; - hydro_TC_LockupRate += hydro_TC_FillRateInc * dt; - } - // luzowanie sprzegla blokujacego - if (Vel < (IsPower ? hydro_TC_LockupSpeed : hydro_TC_UnlockSpeed) || !Mains || enrot < 0.8 * dizel_nmin) - { - hydro_TC_Lockup = false; - hydro_TC_LockupRate -= hydro_TC_FillRateDec * dt; - } - // obcinanie zakresu - hydro_TC_LockupRate = std::clamp(hydro_TC_LockupRate, 0.0, 1.0); - } - else - { - hydro_TC_Fill = 0.0; - hydro_TC_LockupRate = 0.0; - } - - // obliczanie momentow poszczegolnych sprzegiel - // sprzeglo glowne (skrzynia biegow) - TorqueC = dizel_engageMaxForce * dizel_engage * dizel_engageDia * friction; - - if (hydro_TC) // jesli hydro - { - double HydroTorque = 0; - HydroTorque += hydro_TC_nIn * hydro_TC_nIn * hydro_TC_TorqueInIn; - HydroTorque += (hydro_TC_nIn - hydro_TC_nOut) * hydro_TC_TorqueInOut; - HydroTorque += hydro_TC_nOut * hydro_TC_nOut * hydro_TC_TorqueOutOut; - double nOut2In = hydro_TC_nOut / std::max(0.01, hydro_TC_nIn); - if (hydro_TC_Table.size() > 1) - { - hydro_TC_TMRatio = TableInterpolation(hydro_TC_Table, nOut2In); - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * std::min(1.0, hydro_TC_TMRatio); - } - else - { - if (nOut2In < hydro_TC_CouplingPoint) - { - hydro_TC_TMRatio = 1 + (hydro_TC_TMMax - 1) * square(1 - nOut2In / hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - else - { - hydro_TC_TMRatio = (1 - nOut2In) / (1 - hydro_TC_CouplingPoint); - hydro_TC_TorqueIn = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - hydro_TC_TorqueOut = HydroTorque * hydro_TC_Fill * hydro_TC_TMRatio; - } - } - TorqueH = hydro_TC_TorqueOut; - TorqueL = hydro_TC_LockupTorque * hydro_TC_LockupRate; - } - else - { - TorqueH = 0; // brak przetwornika oznacza brak momentu - TorqueL = 1 + TorqueC * 2; // zabezpieczenie, polaczenie trwale - } - - // sprawdzanie dociskow poszczegolnych sprzegiel - if (abs(Moment) > std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) || abs(dizel_n_old - enrot) > 0.1) // slizga sie z powodu roznic predkosci albo przekroczenia momentu - { - dizel_engagedeltaomega = enrot - dizel_n_old; - - if (TorqueC > TorqueL) - { - if (TorqueC > TorqueL + abs(TorqueH)) - { - hydro_TC_nOut = n; - gearMoment = TorqueL + abs(TorqueH) * sign(dizel_engagedeltaomega); - enMoment = Moment - (TorqueL + abs(hydro_TC_TorqueIn)) * sign(dizel_engagedeltaomega); - } - else - { - hydro_TC_nOut = enrot - (n - enrot) * (TorqueC - TorqueL) / TorqueH; // slizganie proporcjonalne, zeby przetwornik nadrabial - gearMoment = TorqueC * sign(dizel_engagedeltaomega); - enMoment = Moment - gearMoment; - } - } - else - { - hydro_TC_nOut = enrot; - gearMoment = TorqueC*sign(dizel_engagedeltaomega); - enMoment = Moment - gearMoment; - } - eps = enMoment / dizel_AIM; - newn = enrot + eps * dt; - if ((newn - n) * (enrot - dizel_n_old) < 0 && TorqueC > 0.1) // przejscie przez zero - slizgalo sie i przestało - newn = n; - if (newn * enrot <= 0 && eps * enrot < 0) // przejscie przez zero obrotow - newn = 0; - enrot = newn; - } - else // nie slizga sie (jeszcze) - { - dizel_engagedeltaomega = 0; - gearMoment = Moment; - double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) - Moment) / dizel_AIM * dt; - double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(hydro_TC_TorqueIn)) + Moment) / dizel_AIM * dt; - enrot = safe_clamp(n, enrot_min, enrot_max); - } - if (hydro_R && hydro_R_Placement == 1) - gearMoment -= dizel_MomentumRetarder(hydro_TC_nOut, dt); - - if (enrot <= 0 && false == dizel_spinup) - { - // an engine stalling stops those started together with it, once. one already stopped, from its own switch or - // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame - // the engines started on their own or from the separate switches (eu07/maszyna#80) - if (true == Mains) - { - MainSwitch(false, MainSwitchRange()); - } - enrot = 0; - } - - dizel_n_old = n; // obecna predkosc katowa na potrzeby kolejnej klatki - - return gearMoment; -} - -double TMoverParameters::dizel_MomentumRetarder(double n, double dt) -{ - double RetarderRequest = Mains ? std::max(0.0, -eimic_real) : 0; - if (hydro_R_WithIndividual) - RetarderRequest = LocalBrakeRatio(); - if (Vel < hydro_R_MinVel) - RetarderRequest = 0; - if (hydro_R_Placement == 2 && enrot < dizel_nmin) - { - RetarderRequest = 0; - } - - hydro_R_ClutchActive = !hydro_R_Clutch || RetarderRequest > 0; - if (!hydro_R_Clutch || (hydro_R_ClutchActive && hydro_R_ClutchSpeed == 0)) - { - hydro_R_n = n * 60; - } - else if (hydro_R_ClutchActive) - { - hydro_R_n = sign(n) * std::min(std::abs(hydro_R_n + hydro_R_ClutchSpeed * dt), std::abs(n * 60)); - } - else - { - hydro_R_n = 0; - } - n = hydro_R_n / 60.f; - - if (hydro_R_Fill < RetarderRequest) // gdy zadane hamowanie - { - hydro_R_Fill = std::min(hydro_R_Fill + hydro_R_FillRateInc * dt, RetarderRequest); - } - else - { - hydro_R_Fill = std::max(hydro_R_Fill - hydro_R_FillRateDec * dt, RetarderRequest); - } - - double Moment = hydro_R_MaxTorque; - if (double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; pwr > hydro_R_MaxPower) - Moment = Moment * hydro_R_MaxPower / pwr; - double moment_in = n * n * hydro_R_TorqueInIn; - Moment = std::min(moment_in, Moment * hydro_R_Fill); - - hydro_R_Torque = Moment; - - return Moment; -} - -// sets component temperatures to specified value -void TMoverParameters::dizel_HeatSet(float const Value) -{ - - // TODO: don't include ambient temperature, pull it from environment data instead - dizel_heat.Te = Value; - dizel_heat.Ts = Value; - dizel_heat.To = Value; - dizel_heat.Tsr = Value; - dizel_heat.Twy = Value; - dizel_heat.Tsr2 = Value; - dizel_heat.Twy2 = Value; - dizel_heat.temperatura1 = Value; - dizel_heat.temperatura2 = Value; -} - -// calculates diesel engine temperature and heat transfers -// adapted from scripts written by adamst -// NOTE: originally executed twice per second -void TMoverParameters::dizel_Heat(double const dt) -{ - - auto const qs{44700.0}; - auto const Cs{11000.0}; - auto const Cw{4.189}; - auto const Co{1.885}; - auto const gwmin{400.0}; - auto const gwmax{4000.0}; - auto const gwmin2{400.0}; - auto const gwmax2{4000.0}; - - dizel_heat.Te = Global.AirTemperature; - - auto const engineon{(Mains ? 1 : 0)}; - auto const engineoff{(Mains ? 0 : 1)}; - auto const rpm{enrot * 60}; - // TODO: calculate this once and cache for further use, instead of doing it repeatedly all over the place - auto const revolutionsfactor{EngineRPMRatio()}; - auto const waterpump{WaterPump.is_active ? 1 : 0}; - - auto const gw = engineon * std::lerp(gwmin, gwmax, revolutionsfactor) + waterpump * 1000 + engineoff * 200; - auto const gw2 = engineon * std::lerp(gwmin2, gwmax2, revolutionsfactor) + waterpump * 1000 + engineoff * 200; - auto const gwO = std::lerp(gwmin, gwmax, revolutionsfactor); - - dizel_heat.water.is_cold = dizel_heat.water.config.temp_min > 0 && dizel_heat.temperatura1 < dizel_heat.water.config.temp_min - (Mains ? 5 : 0); - dizel_heat.water.is_hot = dizel_heat.water.config.temp_max > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_max - (dizel_heat.water.is_hot ? 8 : 0); - dizel_heat.water_aux.is_cold = dizel_heat.water_aux.config.temp_min > 0 && dizel_heat.temperatura2 < dizel_heat.water_aux.config.temp_min - (Mains ? 5 : 0); - dizel_heat.water_aux.is_hot = dizel_heat.water_aux.config.temp_max > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_max - (dizel_heat.water_aux.is_hot ? 8 : 0); - dizel_heat.oil.is_cold = dizel_heat.oil.config.temp_min > 0 && dizel_heat.To < dizel_heat.oil.config.temp_min - (Mains ? 5 : 0); - dizel_heat.oil.is_hot = dizel_heat.oil.config.temp_max > 0 && dizel_heat.To > dizel_heat.oil.config.temp_max - (dizel_heat.oil.is_hot ? 8 : 0); - // engine overheat check - dizel_heat.engine_is_hot = dizel_heat.engine_max_temp > 0 && dizel_heat.Ts > dizel_heat.engine_max_temp - (dizel_heat.engine_is_hot ? 8 : 0); - - auto const PT = false == dizel_heat.water.is_cold && false == dizel_heat.water.is_hot && false == dizel_heat.water_aux.is_cold && false == dizel_heat.water_aux.is_hot && - false == dizel_heat.oil.is_cold && false == dizel_heat.oil.is_hot && false == dizel_heat.engine.is_hot /* && ( false == awaria_termostatow ) */ - /* || PTp */; - auto const PPT = false == PT /* && ( false == PPTp ) */; - dizel_heat.PA = /* ( ( !zamkniecie or niedomkniecie ) and !WBD ) || */ PPT /* || nurnik || ( woda < 7 ) */; - - // engine heat transfers - auto const Ge{engineon * (0.21 * dizel_heat.powerfactor * EnginePower + 12) / 3600}; - // TODO: replace fixed heating power cost with more accurate calculation - auto const obciazenie{engineon * (dizel_heat.powerfactor * EnginePower / 950 + (Heating ? HeatingPower : 0) + 70)}; - auto const Qd{qs * Ge - obciazenie}; - // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko - auto const Qs{(Qd - dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) - dizel_heat.kfe * /* ( 0.3 + 0.7 * ( dizel_heat.okienko ? 1 : 0 ) ) * */ (dizel_heat.Ts - dizel_heat.Te))}; - auto const dTss{Qs / Cs}; - dizel_heat.Ts += static_cast(dTss * dt); - - // oil heat transfers - // olej oddaje cieplo do wody gdy krazy przez wymiennik ciepla == wlaczona pompka lub silnik - auto const dTo{(dizel_heat.auxiliary_water_circuit ? (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2)) / (gwO * Co) : - (dizel_heat.kfo * (dizel_heat.Ts - dizel_heat.To) - dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gwO * Co))}; - dizel_heat.To += static_cast(dTo * dt); - - // heater - /* - if( typ == "SP45" ) - Qp = (float)( podgrzewacz and ( true == WaterPump.is_active ) and ( Twy < 55 ) and ( Twy2 < 55 ) ) * 1000; - else - */ - auto const Qp = (true == WaterHeater.is_active && true == WaterPump.is_active && dizel_heat.Twy < 60 && dizel_heat.Twy2 < 60 ? 1 : 0) * 1000; - - auto const kurek07{1}; // unknown/unimplemented device TBD, TODO: identify and implement? - - if (true == dizel_heat.auxiliary_water_circuit) - { - // auxiliary water circuit setup - dizel_heat.water_aux.is_warm = true == dizel_heat.cooling || - (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ - && dizel_heat.water_aux.config.temp_cooling > 0 && dizel_heat.temperatura2 > dizel_heat.water_aux.config.temp_cooling - (dizel_heat.water_aux.is_warm ? 8 : 0)); - auto const PTC2{(dizel_heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; - dizel_heat.rpmwz2 = static_cast(PTC2 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); - dizel_heat.zaluzje2 = dizel_heat.water_aux.config.shutters ? PTC2 == 1 : true; // no shutters is an equivalent to having them open - auto const zaluzje2{(dizel_heat.zaluzje2 ? 1 : 0)}; - // auxiliary water circuit heat transfer values - auto const kf2{kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje2) * dizel_heat.rpmw2 + dizel_heat.kv * (0.3 + 0.7 * zaluzje2) * Vel / 3.6) + 2}; - auto const dTs2{dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr2) / (gw2 * Cw)}; - // przy otwartym kurku B ma³y obieg jest dogrzewany przez du¿y - stosujemy przy korzystaniu z podgrzewacza oraz w zimie - auto const Qch2{-kf2 * (dizel_heat.Tsr2 - dizel_heat.Te) + 80 * (true == WaterCircuitsLink ? 1 : 0) * (dizel_heat.Twy - dizel_heat.Tsr2)}; - auto const dTch2{Qch2 / (gw2 * Cw)}; - // auxiliary water circuit heat transfers finalization - // NOTE: since primary circuit doesn't read data from the auxiliary one, we can pretty safely finalize auxiliary updates before touching the primary circuit - auto const Twe2{dizel_heat.Twy2 + dTch2 * dt}; - dizel_heat.Twy2 = static_cast(Twe2 + dTs2 * dt); - dizel_heat.Tsr2 = static_cast(0.5 * (dizel_heat.Twy2 + Twe2)); - dizel_heat.temperatura2 = dizel_heat.Twy2; - } - // primary water circuit setup - dizel_heat.water.is_flowing = dizel_heat.water.config.temp_flow < 0 || dizel_heat.temperatura1 > dizel_heat.water.config.temp_flow - (dizel_heat.water.is_flowing ? 5 : 0); - auto const obieg{(dizel_heat.water.is_flowing ? 1 : 0)}; - dizel_heat.water.is_warm = - true == dizel_heat.cooling || (true == Mains && BatteryVoltage > 0.75 * NominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ - && dizel_heat.water.config.temp_cooling > 0 && dizel_heat.temperatura1 > dizel_heat.water.config.temp_cooling - (dizel_heat.water.is_warm ? 8 : 0)); - auto const PTC1{(dizel_heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; - dizel_heat.rpmwz = static_cast(PTC1 * (dizel_heat.fan_speed >= 0 ? rpm * dizel_heat.fan_speed : dizel_heat.fan_speed * -1)); - dizel_heat.zaluzje1 = dizel_heat.water.config.shutters ? PTC1 == 1 : true; // no shutters is an equivalent to having them open - auto const zaluzje1{(dizel_heat.zaluzje1 ? 1 : 0)}; - // primary water circuit heat transfer values - auto const kf{obieg * kurek07 * (dizel_heat.kw * (0.3 + 0.7 * zaluzje1) * dizel_heat.rpmw + dizel_heat.kv * (0.3 + 0.7 * zaluzje1) * Vel / 3.6 + 3) + 2}; - auto const dTs{(dizel_heat.auxiliary_water_circuit ? dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) / (gw * Cw) : - (dizel_heat.kfs * (dizel_heat.Ts - dizel_heat.Tsr) + dizel_heat.kfo2 * (dizel_heat.To - dizel_heat.Tsr)) / (gw * Cw))}; - auto const Qch{-kf * (dizel_heat.Tsr - dizel_heat.Te) + Qp}; - auto const dTch{Qch / (gw * Cw)}; - // primary water circuit heat transfers finalization - auto const Twe{dizel_heat.Twy + dTch * dt}; - dizel_heat.Twy = static_cast(Twe + dTs * dt); - dizel_heat.Tsr = static_cast(0.5 * (dizel_heat.Twy + Twe)); - dizel_heat.temperatura1 = dizel_heat.Twy; - /* - fuelConsumed = fuelConsumed + ( Ge * 0.5 ); - - while( fuelConsumed >= 0.83 ) { - fuelConsumed = fuelConsumed - 0.83; - fuelQueue.DestroyProductMatching( null, 1 ); - }//if - - if( engineon ) - temp_turbo = temp_turbo + 0.3 * ( t_pozycja ); - if( t_pozycja == 0 and cisnienie > 0.04 ) - temp_turbo = temp_turbo - 1; - - if( temp_turbo > 400 ) - temp_turbo = 400; - if( temp_turbo < 0 ) - temp_turbo = 0; - - if( temp_turbo > 50 and cisnienie < 0.05 ) - timer_turbo = timer_turbo + 1; - - if( temp_turbo == 0 ) - timer_turbo = 0; - - if( timer_turbo > 360 ) { - awaria_turbo = true; - timer_turbo = 400; - } - - if( Ts < 50 ) - p_odpal = 3; - if( Ts > 49 and Ts < 76 ) - p_odpal = 4; - if( Ts > 75 ) - p_odpal = 7; - - stukanie = stukanie or awaria_oleju; - - if( awaria_oleju == true and ilosc_oleju > 0 ) { - ilosc_oleju = ilosc_oleju - ( 0.002 * rpm / 1500 ); - } - if( awaria_oleju == true and cisnienie < 0.06 ) - damage = 1; - */ -} - -bool TMoverParameters::AssignLoad(std::string const &Loadname, float const Amount) -{ - - if (Loadname == "pantstate") - { - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { - // wartość niby "pantstate" - nazwa dla formalności, ważna jest ilość - auto const pantographsetup{static_cast(Amount)}; - if (pantographsetup & 1 << 2) - { - DoubleTr = -1; - } - if (pantographsetup & 1 << 0) - { - if (DoubleTr == 1) - { - OperatePantographValve(end::front, operation_t::enable, range_t::local); - } - else - { - OperatePantographValve(end::rear, operation_t::enable, range_t::local); - } - } - if (pantographsetup & 1 << 1) - { - if (DoubleTr == 1) - { - OperatePantographValve(end::rear, operation_t::enable, range_t::local); - } - else - { - OperatePantographValve(end::front, operation_t::enable, range_t::local); - } - } - return true; - } - else - { - return false; - } - } - - if (Loadname.empty()) - { - // empty the vehicle if requested - LoadTypeChange = LoadType.name != Loadname; - LoadType = load_attributes(); - LoadAmount = 0.f; - return true; - } - // can't mix load types, at least for the time being - if (LoadAmount > 0 && LoadType.name != Loadname) - { - return false; - } - - auto const loadattributes = std::ranges::find_if(LoadAttributes, [&](auto const &attributes) { return attributes.name == Loadname; }); - if (loadattributes == std::end(LoadAttributes)) - { - // didn't find matching load configuration, this type is unsupported - return false; - } - LoadTypeChange = LoadType.name != Loadname; - LoadType = *loadattributes; - LoadAmount = safe_clamp(Amount, 0.f, MaxLoad); - ComputeMass(); - return true; -} - -// ************************************************************************************************* -// Q: 20160713 -// Test zakończenia załadunku / rozładunku -// ************************************************************************************************* -bool TMoverParameters::LoadingDone(double const LSpeed, std::string_view Loadname) -{ - - if (LSpeed == 0.0) - { - // zerowa prędkość zmiany, to koniec - LoadStatus = 4; - return true; - } - - if (Loadname.empty()) - { - return LoadStatus >= 4; - } - if (Loadname != LoadType.name) - { - return LoadStatus >= 4; - } - - // test zakończenia załadunku/rozładunku - // load exchange speed is reduced if the wagon is overloaded - auto const loadchange{static_cast(std::abs(LSpeed * LastLoadChangeTime) * (LoadAmount > MaxLoad ? 0.5 : 1.0))}; - - if (LSpeed < 0) - { - // gdy rozładunek - LoadStatus = 2; // trwa rozładunek (włączenie naliczania czasu) - if (loadchange > 0) // jeśli coś przeładowano - { - LastLoadChangeTime = 0; // naliczony czas został zużyty - LoadAmount -= loadchange; // zmniejszenie ilości ładunku - CommandIn.Value1 -= loadchange; // zmniejszenie ilości do rozładowania - if (LoadAmount <= 0 || CommandIn.Value1 <= 0) - { - // pusto lub rozładowano żądaną ilość - LoadStatus = 4; // skończony rozładunek - LoadAmount = safe_clamp(LoadAmount, 0.f, MaxLoad); // ładunek nie może być ujemny - } - if (LoadAmount == 0.f) - { - AssignLoad(""); // jak nic nie ma, to nie ma też nazwy - } - ComputeMass(); - } - } - else if (LSpeed > 0) - { - // gdy załadunek - LoadStatus = 1; // trwa załadunek (włączenie naliczania czasu) - if (loadchange > 0) // jeśli coś przeładowano - { - LastLoadChangeTime = 0; // naliczony czas został zużyty - LoadAmount += loadchange; // zwiększenie ładunku - CommandIn.Value1 -= loadchange; - if (LoadAmount >= MaxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) - { - LoadStatus = 4; // skończony załadunek - LoadAmount = std::min(static_cast(MaxLoad * (1.0 + OverLoadFactor)), LoadAmount); - } - ComputeMass(); - } - } - - return LoadStatus >= 4; -} - -bool TMoverParameters::ChangeDoorPermitPreset(int const Change, range_t const Notify) -{ - - auto const initialstate{Doors.permit_preset}; - - if (false == Doors.permit_presets.empty()) - { - - Doors.permit_preset = safe_clamp(Doors.permit_preset + Change, 0, static_cast(Doors.permit_presets.size() - 1)); - auto const doors{Doors.permit_presets[Doors.permit_preset]}; - auto const permitleft{((doors & 1) != 0)}; - auto const permitright{((doors & 2) != 0)}; - - PermitDoors(CabActive > 0 ? side::left : side::right, permitleft, Notify); - PermitDoors(CabActive > 0 ? side::right : side::left, permitright, Notify); - } - - return Doors.permit_preset != initialstate; -} - -bool TMoverParameters::PermitDoorStep(bool const State, range_t const Notify) -{ - - auto const initialstate{Doors.step_enabled}; - - Doors.step_enabled = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorStep", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Doors.step_enabled != initialstate; -} - -bool TMoverParameters::PermitDoors(side const Door, bool const State, range_t const Notify) -{ - - bool const initialstate{Doors.instances[Door].open_permit}; - - PermitDoors_(Door, State); - - if (Notify != range_t::local) - { - - SendCtrlToNext("DoorPermit", - (State ? 1 : -1) // positive: grant, negative: revoke - * (Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) - 1 : - 2), - CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Doors.instances[Door].open_permit != initialstate; -} - -void TMoverParameters::PermitDoors_(side const Door, bool const State) -{ - - if (State && State != Doors.instances[Door].open_permit) - { - SetFlag(SoundFlag, sound::doorpermit); - } - Doors.instances[Door].open_permit = State; -} - -bool TMoverParameters::ChangeDoorControlMode(bool const State, range_t const Notify) -{ - - auto const initialstate{Doors.remote_only}; - - Doors.remote_only = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorMode", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - if (true == State) - { - // when door are put in remote control mode they're automatically open - // TBD, TODO: make it dependant on config switch? - OperateDoors(side::left, true); - OperateDoors(side::right, true); - } - - return Doors.remote_only != initialstate; -} - -bool TMoverParameters::OperateDoors(side const Door, bool const State, range_t const Notify) -{ - - auto &door{Doors.instances[Door]}; - /* - if( ( State == true ? door.is_open : door.is_closed ) ) { - // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? - // (for the time being no, methods are often invoked blindly which would lead to commands spam) - return false; - } - */ - bool result{false}; - - if (Notify == range_t::local) - { - door.local_open = State; - door.local_close = false == State; - result = true; - } - else - { - // remote door operation signals require power to propagate - if (Power24vIsAvailable || Power110vIsAvailable) - { - door.remote_open = State; - door.remote_close = false == State; - result = true; - } - } - - if (Notify != range_t::local) - { - - SendCtrlToNext(State == true ? "DoorOpen" : "DoorClose", - Door == (CabActive > 0 ? side::left : side::right) ? // 1=lewe, 2=prawe (swap if reversed) - 1 : - 2, - CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return result; -} - -// toggle door lock -bool TMoverParameters::LockDoors(bool const State, range_t const Notify) -{ - - auto const initialstate{Doors.lock_enabled}; - - Doors.lock_enabled = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DoorLock", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return Doors.lock_enabled != initialstate; -} - -// toggles departure warning -bool TMoverParameters::signal_departure(bool const State, range_t const Notify) -{ - - if (DepartureSignal == State) - { - // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? - return false; - } - - DepartureSignal = State; - if (Notify != range_t::local) - { - // wysłanie wyłączenia do pozostałych? - SendCtrlToNext("DepartureSignal", State == true ? 1 : 0, CabActive, Notify == range_t::unit ? coupling::control | coupling::permanent : coupling::control); - } - - return true; -} - -// state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while -// the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise. -// doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist -door_closure_t TMoverParameters::door_closure() const -{ - if (Doors.range == 0.f || Doors.close_control == control_t::autonomous) - { - return door_closure_t::none; - } - if (std::ranges::any_of(Doors.instances, [](basic_door const &Door) { return false == Door.is_closed; })) - { - return door_closure_t::open; - } - if (Doors.is_locked) - { - return door_closure_t::locked; - } - if (Doors.permit_needed && std::ranges::none_of(Doors.instances, [](basic_door const &Door) { return Door.open_permit; })) - { - return door_closure_t::locked; - } - return door_closure_t::released; -} - -bool TMoverParameters::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const -{ - return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked; -} - -bool door_closure_lamp(door_closure_t const State, bool const BlinkLit) -{ - switch (State) - { - case door_closure_t::locked: - return true; - case door_closure_t::released: - return BlinkLit; - default: - return false; - } -} - -// automatic door controller update -void TMoverParameters::update_doors(double const Deltatime) -{ - - if (Doors.range == 0.f) - { - return; - } // HACK: crude way to distinguish vehicles with actual doors - - // NBMX Obsluga drzwi, MC: zuniwersalnione - auto const localopencontrol{false == Doors.remote_only && (Doors.open_control == control_t::passenger || Doors.open_control == control_t::mixed)}; - auto const remoteopencontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; - auto const localclosecontrol{false == Doors.remote_only && (Doors.close_control == control_t::passenger || Doors.close_control == control_t::mixed)}; - auto const remoteclosecontrol{Doors.close_control == control_t::driver || Doors.close_control == control_t::conductor || Doors.close_control == control_t::mixed}; - - Doors.is_locked = true == Doors.has_lock && true == Doors.lock_enabled && Vel >= Doors.doorLockSpeed; - - for (auto &door : Doors.instances) - { - // revoke permit if... - door.open_permit = true == door.open_permit // ...we already have one... - && (false == Doors.permit_presets.empty() // ...there's no preset switch controlling permit state... - || (false == Doors.is_locked // ...and the door lock is engaged... - && false == door.remote_close)); // ...or the door is about to be closed - - door.is_open = door.position >= Doors.range && (false == Doors.step_enabled || door.step_position >= (Doors.step_range != 0.f ? 1.f : 0.f)); - door.is_closed = door.position <= 0.f && door.step_position <= 0.f; - door.is_door_closed = door.position <= 0.f; - - door.local_open = door.local_open && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.remote_open = (door.remote_open || Doors.remote_only) && false == door.is_open && (false == Doors.permit_needed || door.open_permit); - door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); - door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); - - auto const autoopenrequest{Doors.open_control == control_t::autonomous && (false == Doors.permit_needed || door.open_permit)}; - auto const openrequest{(localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open)}; - - auto const autocloserequest{(Doors.auto_velocity != -1.f && Vel > Doors.auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || - (Doors.permit_needed && false == door.open_permit)}; - auto const closerequest{(door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open)}; - - auto const ispowered{(Doors.voltage == 0 ? true : Doors.voltage == 24 ? Power24vIsAvailable || Power110vIsAvailable : Doors.voltage == 110 ? Power110vIsAvailable : false)}; - - door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == Doors.is_locked)); - door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); - door.step_unfolding = Doors.step_range != 0.f && Doors.step_enabled && false == Doors.is_locked && door.step_position < 1.f && door.is_opening; - door.step_folding = door.step_position > 0.f // is unfolded - && (false == Doors.step_enabled // we lost permission to stay open or our door is calling the shots - || (Doors.permit_needed ? false == door.open_permit : door.is_closing)) && - (door.close_delay > Doors.close_delay || door.position <= 0.f); // door is about to close, or already done - - if (true == door.is_opening) - { - door.auto_timer = localopencontrol && door.local_open ? Doors.auto_duration : remoteopencontrol && door.remote_open && Doors.auto_include_remote ? Doors.auto_duration : -1.f; - } - // doors - if (true == door.is_opening) - { - // open door - if (false == door.step_unfolding // no wait if no doorstep - || Doors.step_type == 2) - { // no wait for rotating doorstep - door.open_delay += static_cast(Deltatime); - if (door.open_delay > Doors.open_delay) - { - door.position = std::min(Doors.range, static_cast(door.position + Doors.open_rate * Deltatime)); - } - } - door.close_delay = 0.f; - } - if (true == door.is_closing) - { - // close door - door.close_delay += static_cast(Deltatime); - if (door.close_delay > Doors.close_delay) - { - door.position = std::max(0.f, static_cast(door.position - Doors.close_rate * Deltatime)); - } - door.open_delay = 0.f; - } - // doorsteps - if (door.step_unfolding) - { - // unfold left doorstep - door.step_position = std::min(1.f, static_cast(door.step_position + Doors.step_rate * Deltatime)); - } - if (door.step_folding) - { - // fold left doorstep - if (TrainType == dt_EZT || TrainType == dt_DMU) - { - // multi-unit vehicles typically fold the doorstep only after closing the door - if (door.position <= 0.f) - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } - else - { - door.step_position = std::max(0.f, static_cast(door.step_position - Doors.step_rate * Deltatime)); - } - } - } - - if (false == Doors.instances[side::right].is_open && false == Doors.instances[side::left].is_open) - { - return; - } - - if (Doors.auto_duration > 0.f) - { - // update door timers if the door close after defined time - for (auto &door : Doors.instances) - { - - if (false == door.is_open) - { - continue; - } - - if (door.auto_timer > 0.f) - { - door.auto_timer -= static_cast(Deltatime); - } - // if there's load exchange in progress, reset the timer(s) for already open doors - if (door.auto_timer != -1.f && (LoadStatus & (2 | 1)) != 0) - { - door.auto_timer = Doors.auto_duration; - } - } - } - /* - // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold - std::array const doorids { side::right, side::left }; - for( auto const doorid : doorids ) { - auto const &door { Doors.instances[ doorid ] }; - if( true == door.is_open ) { - if( ( ( Doors.auto_velocity != -1.f ) && ( Vel > Doors.auto_velocity ) ) - || ( ( door.auto_timer != -1.f ) && ( door.auto_timer <= 0.f ) ) ) { - // close the door and set the timer to expired state (closing may happen sooner if vehicle starts moving) - OperateDoors( doorid, false, range_t::local ); - } - } - } - */ -} - -// ************************************************************************************************* -// Q: 20160713 -// Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) -// ************************************************************************************************* -bool TMoverParameters::ChangeOffsetH(double DeltaOffset) -{ - bool COH = false; - if (TestFlag(CategoryFlag, 2) && TestFlag(RunningTrack.CategoryFlag, 2)) - { - OffsetTrackH = OffsetTrackH + DeltaOffset; - // if (abs(OffsetTrackH) > (RunningTrack.Width / 1.95 - TrackW / 2.0)) - if (abs(OffsetTrackH) > 0.5 * (RunningTrack.Width - Dim.W) - 0.05) // Ra: może pół pojazdu od brzegu? - COH = false; // kola na granicy drogi - else - COH = true; - } - else - COH = false; - - return COH; -} - -// ************************************************************************************************* -// Q: 20160713 -// Testuje zmienną (narazie tylko 0) i na podstawie uszkodzenia zwraca informację tekstową -// ************************************************************************************************* -std::string TMoverParameters::EngineDescription(int what) const -{ - std::string outstr{"OK"}; - if (what == 0) - { - if (DamageFlag == 255) - { - outstr = "WRECKED"; - } - else - { - if (TestFlag(DamageFlag, dtrain_thinwheel)) - { - if (Power > 0.1) - outstr = "Thin wheel"; - else - outstr = "Load shifted"; - } - if (WheelFlat > 5.0 || TestFlag(DamageFlag, dtrain_wheelwear)) - { - outstr = "Wheel wear"; - } - if (TestFlag(DamageFlag, dtrain_bearing)) - { - outstr = "Bearing damaged"; - } - if (TestFlag(DamageFlag, dtrain_coupling)) - { - outstr = "Coupler broken"; - } - if (TestFlag(DamageFlag, dtrain_loaddamage)) - { - if (Power > 0.1) - outstr = "Ventilator damaged"; - else - outstr = "Load damaged"; - } - if (TestFlag(DamageFlag, dtrain_loaddestroyed)) - { - if (Power > 0.1) - outstr = "Engine damaged"; - else - outstr = "LOAD DESTROYED"; - } - if (TestFlag(DamageFlag, dtrain_axle)) - { - outstr = "Axle broken"; - } - if (TestFlag(DamageFlag, dtrain_out)) - { - outstr = "DERAILED"; - } - } - } - else - { - outstr = "Invalid qualifier"; - } - return outstr; -} - -// ************************************************************************************************* -// Q: 20160709 -// Funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT -// ************************************************************************************************* -double TMoverParameters::GetTrainsetVoltage(int const Coupling) const -{ // ABu: funkcja zwracajaca napiecie dla calego skladu, przydatna dla EZT - // TBD, TODO: call once per vehicle update, return cached results? - std::array voltages{0.0, 0.0}; - for (int end = end::front; end <= end::rear; ++end) - { - if (Couplers[end].Connected == nullptr) - { - continue; - } - auto const &thiscoupler{Couplers[end]}; - if (auto const fullcoupling{thiscoupler.CouplingFlag | (TestFlag(thiscoupler.CouplingFlag, thiscoupler.PowerCoupling) ? thiscoupler.PowerFlag : 0)}; (fullcoupling & Coupling) == 0) - { - continue; - } - auto const *connectedpowercoupling = (Coupling & (coupling::highvoltage | coupling::heating)) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_high : - (Coupling & coupling::power110v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_110v : - (Coupling & coupling::power24v) != 0 ? &thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr].power_24v : - nullptr; - if (connectedpowercoupling != nullptr && connectedpowercoupling->is_live) - { - voltages[end] = connectedpowercoupling->voltage; - } - } - return std::max(voltages[end::front], voltages[end::rear]); -} - -double TMoverParameters::GetTrainsetHighVoltage() const -{ - - return std::max(GetTrainsetVoltage(coupling::highvoltage), HeatingAllow ? GetTrainsetVoltage(coupling::heating) : 0.0); -} - -// ************************************************************************************************* -// whether the vehicle accelerates, for the test which turns the physics off in vehicles standing still -// ************************************************************************************************* -bool TMoverParameters::accelerating() const -{ - if (std::abs(AccS) <= 0.0001) - return false; - // standing still and held by the brakes and the resistance, against the slope and the couplers: the test ComputeMovement() - // sets the speed to zero by. the forces are of the last ComputeTotalForce(), the ones the movement went by - auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain)}; - return false == held; -} - -// ************************************************************************************************* -// Kasowanie zmiennych pracy fizyki -// ************************************************************************************************* -bool TMoverParameters::switch_physics(bool const State, wake_cause const Cause) // DO PRZETLUMACZENIA NA KONCU -{ - if (PhysicActivation == State) - { - return false; - } - - PhysicActivation = State; - if (true == State) - { - LastSwitchingTime = 0; - Timer::subsystem.switching.note(static_cast(Timer::switching_counter::wake + static_cast(Cause)), this, &TypeName, &Name); - } - - return true; -} - -// ************************************************************************************************* -// FUNKCJE PARSERA WCZYTYWANIA PLIKU FIZYKI POJAZDU -// ************************************************************************************************* -bool startBPT; -bool startMPT; -bool startMPT0; -bool startRLIST; -bool startUCLIST; -bool startDIZELMOMENTUMLIST; -bool startDIZELV2NMAXLIST; -bool startHYDROTCLIST; -bool startPMAXLIST; -bool startDLIST; -bool startFFLIST; -bool startWWLIST; -bool startWiperList; -bool startDimmerList; -bool startFFEDLIST; -bool startLIGHTSLIST; -bool startCOMPRESSORLIST; -int LISTLINE; - -bool issection(std::string_view Name, std::string_view Input) -{ - - return Input.compare(0, Name.size(), Name) == 0; -} - -int s2NPW(std::string s) -{ // wylicza ilosc osi napednych z opisu ukladu osi - const char A = 64; - int NPW = 0; - for (char const chentry : s) - { - if (chentry >= (char)65 && chentry <= (char)90) - NPW += chentry - A; - } - return NPW; -} - -int s2NNW(std::string s) -{ // wylicza ilosc osi nienapedzanych z opisu ukladu osi - const char Zero = 48; - int NNW = 0; - for (char const ch : s) - { - if (ch >= (char)49 && ch <= (char)57) - NNW += ch - Zero; - } - return NNW; -} - -// ************************************************************************************************* -// Q: 20160717 -// ************************************************************************************************* -// parsowanie Motor Param Table -// checks a motor parameter table position read from the .fiz file against the table size -static bool is_valid_mpt_index(int const Index) -{ - if (Index >= 0 && Index <= MotorParametersArraySize) - { - return true; - } - WriteLog("Read MPT: position " + std::to_string(Index) + " out of range 0-" + std::to_string(MotorParametersArraySize) + " in line " + std::to_string(LISTLINE)); - return false; -} - -bool TMoverParameters::readMPT0(std::string const &line) -{ - - // TBD, TODO: split into separate functions similar to readMPT if more varied schemes appear? - cParser parser(line); - if (false == parser.getTokens(7, false)) - { - WriteLog("Read MPT0: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - if (EngineType == TEngineType::DieselEngine) - { - parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi0 >> MotorParam[idx].fi >> MotorParam[idx].mfi0 >> MotorParam[idx].mfi >> MotorParam[idx].Isat; - } - else - { - parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].mfi0 >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MotorParam[idx].fi0; - } - if (true == parser.getTokens(1, false)) - { - int autoswitch{0}; - parser >> autoswitch; - MotorParam[idx].AutoSwitch = autoswitch == 1; - } - else - { - MotorParam[idx].AutoSwitch = false; - } - return true; -} - -bool TMoverParameters::readMPT(std::string const &line) -{ - - ++LISTLINE; - - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - return readMPTElectricSeries(line); - } - case TEngineType::DieselElectric: - { - return readMPTDieselElectric(line); - } - case TEngineType::DieselEngine: - { - return readMPTDieselEngine(line); - } - default: - { - return false; - } - } -} - -bool TMoverParameters::readMPTElectricSeries(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(5, false)) - { - WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat; - if (true == parser.getTokens(1, false)) - { - int autoswitch{0}; - parser >> autoswitch; - MotorParam[idx].AutoSwitch = autoswitch == 1; - } - else - { - MotorParam[idx].AutoSwitch = false; - } - return true; -} - -bool TMoverParameters::readMPTDieselElectric(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(7, false)) - { - WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MPTRelay[idx].Iup >> MPTRelay[idx].Idown; - - return true; -} - -bool TMoverParameters::readMPTDieselEngine(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); - return false; - } - int idx = 0; // numer pozycji - parser >> idx; - if (false == is_valid_mpt_index(idx)) - { - return false; - } - parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].mfi; - if (true == parser.getTokens(1, false)) - { - int autoswitch{0}; - parser >> autoswitch; - MotorParam[idx].AutoSwitch = autoswitch == 1; - } - else - { - MotorParam[idx].AutoSwitch = false; - } - return true; -} - -bool TMoverParameters::readBPT(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(5, false)) - { - - WriteLog("Read BPT: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - std::string braketype; - int idx = 0; - parser >> idx; - parser >> BrakePressureTable[idx].PipePressureVal >> BrakePressureTable[idx].BrakePressureVal >> BrakePressureTable[idx].FlowSpeedVal >> braketype; - if (braketype == "Pneumatic") - { - BrakePressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; - } - else if (braketype == "ElectroPneumatic") - { - BrakePressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; - } - else - { - BrakePressureTable[idx].BrakeType = TBrakeSystem::Individual; - } - - return true; -} - -bool TMoverParameters::readRList(std::string const &Input) -{ - - cParser parser(Input); - if (false == parser.getTokens(5, false)) - { - - WriteLog("Read RList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - auto idx = LISTLINE++; - if (idx >= std::size(RList)) - { - WriteLog("Read RList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Bn >> RList[idx].Mn >> RList[idx].AutoSwitch; - - if (true == parser.getTokens(1, false)) - { - parser >> RList[idx].ScndAct; - } - else - { - RList[idx].ScndAct = 0; - } - - return true; -} - -bool TMoverParameters::readUCList(std::string const &line) -{ - - cParser parser(line); - parser.getTokens(10, false); - auto idx = LISTLINE++; - if (idx >= std::size(UniCtrlList)) - { - WriteLog("Read UCList: number of entries exceeded capacity of the data table"); - return false; - } - int i = 0; - parser >> i >> UniCtrlList[idx].mode >> UniCtrlList[idx].MinCtrlVal >> UniCtrlList[idx].MaxCtrlVal >> UniCtrlList[idx].SetCtrlVal >> UniCtrlList[idx].SpeedUp >> UniCtrlList[idx].SpeedDown >> - UniCtrlList[idx].ReturnPosition >> UniCtrlList[idx].NextPosFastInc >> UniCtrlList[idx].PrevPosFastDec; - - return true; -} - -bool TMoverParameters::readDList(std::string const &line) -{ - - cParser parser(line); - parser.getTokens(3, false); - auto idx = LISTLINE++; - if (idx >= std::size(RList)) - { - WriteLog("Read DList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Mn; - - return true; -} - -bool TMoverParameters::readDMList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read DMList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - dizel_Momentum_Table.emplace(x / 60.0, y); - - return true; -} - -bool TMoverParameters::readV2NMAXList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read V2nmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - dizel_vel2nmax_Table.emplace(x, y / 60.0); - - return true; -} - -bool TMoverParameters::readHTCList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read HTCList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - hydro_TC_Table.emplace(x, y); - - return true; -} - -bool TMoverParameters::readPmaxList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - - WriteLog("Read PmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - double x = 0.0; - double y = 0.0; - parser >> x >> y; - - EIM_Pmax_Table.emplace(x, y); - - return true; -} - -bool TMoverParameters::readFFList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(FFlist)) - { - WriteLog("Read FList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> FFlist[idx].v >> FFlist[idx].freq; - - return true; -} - -bool TMoverParameters::readFFEDList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(2, false)) - { - WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(FFEDlist)) - { - WriteLog("Read FList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> FFEDlist[idx].v >> FFEDlist[idx].freq; - - return true; -} - -// parsowanie wiperList -bool TMoverParameters::readWiperList(std::string const &line) -{ - cParser parser(line); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read WiperList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(WiperList)) - { - WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> WiperList[idx].byteSum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; - return true; -} - -bool TMoverParameters::readDimmerList(std::string const &line) -{ - cParser parser(line); - if (false == parser.getTokens(3, false)) - { - WriteLog("Read DimmerList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - ++LISTLINE; - - dimPosition dps; - parser >> dps.isHighBeam >> dps.isDimmed >> dps.isOff; - dimPositions.push_back(dps); - return true; -} - -int TMoverParameters::clampDimmerPosition(int const Position) const -{ - if (dimPositions.empty()) - { - return 0; - } - return std::clamp(Position, 0, static_cast(dimPositions.size()) - 1); -} - -TMoverParameters::dimPosition TMoverParameters::currentDimPosition() const -{ - if (modernDimmerPosition < 0 || modernDimmerPosition >= static_cast(dimPositions.size())) - { - return {}; - } - return dimPositions[modernDimmerPosition]; -} - -bool TMoverParameters::stepDimmerPosition(int const Step) -{ - if (dimPositions.empty()) - { - return false; - } - auto const last{static_cast(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; -} - -// parsowanie WWList -bool TMoverParameters::readWWList(std::string const &line) -{ - - cParser parser(line); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read WWList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx >= std::size(DElist)) - { - WriteLog("Read WWList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> DElist[idx].RPM >> DElist[idx].GenPower >> DElist[idx].Umax >> DElist[idx].Imax; - - if (true == parser.getTokens(3, false)) - { - // optional parameters for shunt mode - parser >> SST[idx].Umin >> SST[idx].Umax >> SST[idx].Pmax; - - SST[idx].Pmin = std::sqrt(std::pow(SST[idx].Umin, 2) / 47.6); - SST[idx].Pmax = std::min(SST[idx].Pmax, std::pow(SST[idx].Umax, 2) / 47.6); - } - return true; -} - -bool TMoverParameters::readLightsList(std::string const &Input) -{ - - cParser parser(Input); - if (false == parser.getTokens(2, false)) - { - WriteLog("Read LightsList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx > 16) - { - WriteLog("Read LightsList: number of entries exceeded capacity of the data table"); - return false; - } - parser >> Lights[0][idx] >> Lights[1][idx]; - // optional third column: the cab interior light the preset sets (eu07/maszyna#529). anything but a whole number - // (some rows carry stray notes after the two columns) leaves the cab light to its own switch - LightsCabLight[idx] = -1; - if (true == parser.getTokens(1, false)) - { - std::string cablight; - parser >> cablight; - int flags{-1}; - auto const [end, error]{std::from_chars(cablight.data(), cablight.data() + cablight.size(), flags)}; - if (error == std::errc{} && end == cablight.data() + cablight.size() && flags >= 0) - { - LightsCabLight[idx] = flags; - } - } - - return true; -} - -std::optional TMoverParameters::LightsPresetCabLight(int const Position) const -{ - if (Position < 1 || Position > static_cast(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}; -} - -bool TMoverParameters::readCompressorList(std::string const &Input) -{ - - cParser parser(Input); - if (false == parser.getTokens(4, false)) - { - WriteLog("Read CompressorList: arguments missing in line " + std::to_string(LISTLINE + 1)); - return false; - } - int idx = LISTLINE++; - if (idx > 8 - 1) - { - WriteLog("Read CompressorList: number of entries exceeded capacity of the data table"); - return false; - } - // NOTE: content of slot [x][0] is hardcoded elsewhere - parser >> CompressorList[0][idx + 1] >> CompressorList[1][idx + 1] >> CompressorList[2][idx + 1] >> CompressorList[3][idx + 1]; - - return true; -} - -// ************************************************************************************************* -// Q: 20160719 -// ************************************************************************************************* -void TMoverParameters::BrakeValveDecode(std::string const &Valve) -{ - using enum TBrakeValve; - - std::map> valvetypes{{"W", W}, - {"W_Lu_L", W_Lu_L}, - {"W_Lu_XR", W_Lu_XR}, - {"W_Lu_VI", W_Lu_VI}, - {"K", K}, - {"Kg", Kg}, - {"Kp", Kp}, - {"Kss", Kss}, - {"Kkg", Kkg}, - {"Kkp", Kkp}, - {"Kks", Kks}, - {"Hikp1", Hikp1}, - {"Hikss", Hikss}, - {"Hikg1", Hikg1}, - {"KE", KE}, - {"SW", SW}, - {"EStED", EStED}, - {"NESt3", NESt3}, - {"ESt3", ESt3}, - {"LSt", LSt}, - {"ESt4", ESt4}, - {"ESt3AL2", ESt3AL2}, - {"EP1", EP1}, - {"EP2", EP2}, - {"M483", M483}, - {"CV1_L_TR", CV1_L_TR}, - {"CV1", CV1}, - {"CV1_R", CV1_R}}; - auto lookup = valvetypes.find(Valve); - BrakeValve = lookup != valvetypes.end() ? lookup->second : Other; - - if (BrakeValve == Other && contains(Valve, "ESt")) - { - - BrakeValve = ESt3; - } -} - -// ************************************************************************************************* -// Q: 20160719 -// ************************************************************************************************* -void TMoverParameters::BrakeSubsystemDecode() -{ - using enum TBrakeSubSystem; - BrakeSubsystem = ss_None; - switch (BrakeValve) - { - using enum TBrakeValve; - case W: - case W_Lu_L: - case W_Lu_VI: - case W_Lu_XR: - BrakeSubsystem = ss_W; - break; - case ESt3: - case ESt3AL2: - case ESt4: - case EP2: - case EP1: - BrakeSubsystem = ss_ESt; - break; - case KE: - BrakeSubsystem = ss_KE; - break; - case CV1: - case CV1_L_TR: - BrakeSubsystem = ss_Dako; - break; - case LSt: - case EStED: - BrakeSubsystem = ss_LSt; - break; - default: - break; - } -} - -// ************************************************************************************************* -// Q: 20160717 -// Funkcja pelniaca role pierwotnej LoadChkFile wywolywana w dynobj.cpp w double -// TDynamicObject::Init() -// Po niej wykonywana jest CreateBrakeSys(), ktora jest odpowiednikiem CheckLocomotiveParameters() -// ************************************************************************************************* -bool TMoverParameters::LoadFIZ(std::string const &chkpath) -{ - chkPath = chkpath; // assign class path for reloading - - ConversionError = 666; - std::string file = TypeName + ".fiz"; - - WriteLog("LOAD FIZ FROM " + file); - /* - std::ifstream in(file); - if (!in.is_open()) - { - WriteLog("E8 - FIZ FILE NOT EXIST."); - return false; - } - */ - cParser fizparser(file, cParser::buffer_FILE, chkpath); - if (false == fizparser.ok()) - { - WriteLog("E8 - FIZ FILE NOT EXIST."); - return false; - } - - return LoadFIZ_Parse(fizparser); -} - -// reads the vehicle definition from text in the .fiz format, e.g. one made up by a unit test -bool TMoverParameters::LoadFIZ_Text(std::string const &Text) -{ - ConversionError = 666; - cParser fizparser(Text, cParser::buffer_TEXT); - return LoadFIZ_Parse(fizparser); -} - -bool TMoverParameters::LoadFIZ_Parse(cParser &fizparser) // NOSONAR the former body of LoadFIZ(), moved as it was; splitting it up is a change of its own -{ - LISTLINE = 0; - startBPT = false; - startMPT = false; - startMPT0 = false; - startRLIST = false; - startUCLIST = false; - startDLIST = false; - startDIZELMOMENTUMLIST = false; - startDIZELV2NMAXLIST = false; - startHYDROTCLIST = false; - startPMAXLIST = false; - startFFLIST = false; - startFFEDLIST = false; - startWWLIST = false; - startWiperList = false; - startDimmerList = false; - startLIGHTSLIST = false; - startCOMPRESSORLIST = false; - - ConversionError = 0; - - // Zbieranie danych zawartych w pliku FIZ - // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - std::unordered_map fizlines; - std::string inputline; - /* - while (std::getline(in, inputline)) - */ - while (fizparser.ok()) - { - - inputline = fizparser.getToken(false, "\n\r"); - - if (inputline.starts_with("//") || contains(inputline, '#')) - { - // skip commented lines - continue; - } - - if (!inputline.empty() && inputline.front() == ' ') - { - // guard against malformed config files with leading spaces - inputline.erase(0, inputline.find_first_not_of(' ')); - } - - // trim CR at end (mainly for linux) - if (!inputline.empty() && inputline.back() == '\r') - inputline.pop_back(); - - if (inputline.length() == 0) - { - startBPT = false; - continue; - } - - // checking if table parsing should be switched off goes first... - if (issection("END-MPT", inputline)) - { - startBPT = false; - startMPT = false; - startMPT0 = false; - continue; - } - if (issection("END-RL", inputline)) - { - startBPT = false; - startRLIST = false; - continue; - } - if (issection("END-UCL", inputline)) - { - startBPT = false; - startUCLIST = false; - continue; - } - if (issection("END-DL", inputline)) - { - startBPT = false; - startDLIST = false; - continue; - } - if (issection("END-DML", inputline)) - { - startBPT = false; - startDIZELMOMENTUMLIST = false; - continue; - } - if (issection("END-V2NL", inputline)) - { - startBPT = false; - startDIZELV2NMAXLIST = false; - continue; - } - if (issection("END-HTCL", inputline)) - { - startBPT = false; - startHYDROTCLIST = false; - continue; - } - if (issection("END-PML", inputline)) - { - startBPT = false; - startPMAXLIST = false; - continue; - } - if (issection("endff", inputline)) - { - startBPT = false; - startFFLIST = false; - startFFEDLIST = false; - continue; - } - if (issection("endwl", inputline)) - { - // skonczylismy czytac liste konfiguracji wycieraczek - startBPT = false; - startWiperList = false; - continue; - } - if (issection("endDimmerList", inputline)) - { - // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia - startBPT = false; - startDimmerList = false; - continue; - } - if (issection("END-WWL", inputline)) - { - startBPT = false; - startWWLIST = false; - continue; - } - if (issection("endL", inputline)) - { - startBPT = false; - startLIGHTSLIST = false; - continue; - } - if (issection("endCL", inputline)) - { - startBPT = false; - startCOMPRESSORLIST = false; - continue; - } - // ...then all recognized sections... - if (issection("Param.", inputline)) - { - startBPT = false; - fizlines.try_emplace("Param", inputline); - LoadFIZ_Param(inputline); - continue; - } - - if (issection("Load:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Load", inputline); - LoadFIZ_Load(inputline); - continue; - } - - if (issection("Dimensions:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Dimensions", inputline); - LoadFIZ_Dimensions(inputline); - continue; - } - - if (issection("Wheels:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Wheels", inputline); - LoadFIZ_Wheels(inputline); - continue; - } - - if (issection("Brake:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Brake", inputline); - LoadFIZ_Brake(inputline); - continue; - } - - if (issection("Doors:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Doors", inputline); - LoadFIZ_Doors(inputline); - continue; - } - - if (issection("BuffCoupl.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl", inputline); - LoadFIZ_BuffCoupl(inputline, 0); - continue; - } - - else if (issection("BuffCoupl1.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl1", inputline); - LoadFIZ_BuffCoupl(inputline, 1); - continue; - } - - else if (issection("BuffCoupl2.", inputline)) - { - - startBPT = false; - fizlines.try_emplace("BuffCoupl2", inputline); - LoadFIZ_BuffCoupl(inputline, 2); - continue; - } - - if (issection("TurboPos:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("TurboPos", inputline); - LoadFIZ_TurboPos(inputline); - continue; - } - - if (issection("Cntrl.", inputline)) - { - - startBPT = true; - LISTLINE = 0; - fizlines.try_emplace("Cntrl", inputline); - LoadFIZ_Cntrl(inputline); - continue; - } - - if (issection("Headlights:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Headlights", inputline); - LoadFIZ_Headlights(inputline); - continue; - } - - if (issection("Blending:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("Blending", inputline); - LoadFIZ_Blending(inputline); - continue; - } - - if (issection("DCEMUED:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("DCEMUED", inputline); - LoadFIZ_DCEMUED(inputline); - continue; - } - - if (issection("SpringBrake:", inputline)) - { - - startBPT = false; - LISTLINE = 0; - fizlines.try_emplace("SpringBrake", inputline); - LoadFIZ_SpringBrake(inputline); - continue; - } - - if (issection("Light:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Light", inputline); - LoadFIZ_Light(inputline); - continue; - } - - if (issection("Security:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Security", inputline); - SecuritySystem.load(inputline, Vmax); - extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); - continue; - } - - if (issection("Clima:", inputline)) - { - - startBPT = false; - fizlines.try_emplace("Clima", inputline); - LoadFIZ_Clima(inputline); - continue; - } - - if (issection("Power:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Power", inputline); - LoadFIZ_Power(inputline); - continue; - } - - if (issection("SpeedControl:", inputline)) - { - startBPT = false; - fizlines.try_emplace("SpeedControl", inputline); - LoadFIZ_SpeedControl(inputline); - continue; - } - - if (issection("Engine:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Engine", inputline); - LoadFIZ_Engine(inputline); - continue; - } - - if (issection("Switches:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Switches", inputline); - LoadFIZ_Switches(inputline); - continue; - } - - if (issection("MotorParamTable:", inputline)) - { - startBPT = false; - startMPT = true; - LISTLINE = 0; - fizlines.try_emplace("MotorParamTable", inputline); - LoadFIZ_MotorParamTable(inputline); - continue; - } - - if (issection("MotorParamTable0:", inputline)) - { - startBPT = false; - startMPT0 = true; - LISTLINE = 0; - continue; - } - - if (issection("Circuit:", inputline)) - { - startBPT = false; - fizlines.try_emplace("Circuit", inputline); - LoadFIZ_Circuit(inputline); - continue; - } - - if (issection("AI:", inputline)) - { - startBPT = false; - fizlines.try_emplace("AI", inputline); - LoadFIZ_AI(inputline); - continue; - } - - if (issection("RList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("RList", inputline); - startRLIST = true; - LISTLINE = 0; - LoadFIZ_RList(inputline); - continue; - } - - if (issection("UCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("UCList", inputline); - startUCLIST = true; - LISTLINE = 0; - LoadFIZ_UCList(inputline); - continue; - } - - if (issection("DList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DList", inputline); - startDLIST = true; - LISTLINE = 0; - LoadFIZ_DList(inputline); - continue; - } - - if (issection("DMList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("DMList", inputline); - startDIZELMOMENTUMLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("HTCList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("HTCList", inputline); - startHYDROTCLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("PmaxList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("PmaxList", inputline); - startPMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("V2NList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("V2NList", inputline); - startDIZELV2NMAXLIST = true; - LISTLINE = 0; - continue; - } - - if (issection("ffList:", inputline)) - { - startBPT = false; - startFFLIST = true; - LISTLINE = 0; - LoadFIZ_FFList(inputline); - continue; - } - - if (issection("ffBrakeList:", inputline)) - { - startBPT = false; - startFFEDLIST = true; - LISTLINE = 0; - LoadFIZ_FFEDList(inputline); - continue; - } - - if (issection("WWList:", inputline)) - { - startBPT = false; - startWWLIST = true; - LISTLINE = 0; - - continue; - } - - if (issection("WiperList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("WiperList", inputline); - startWiperList = true; - LISTLINE = 0; - LoadFIZ_WiperList(inputline); - - continue; - } - - if (issection("DimmerList:", inputline)) - { - dimPositions.clear(); // uzywamy customowej listy - startBPT = false; - startDimmerList = true; - fizlines.try_emplace("DimmerList", inputline); - LoadFIZ_DimmerList(inputline); - continue; - } - - if (issection("LightsList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("LightsList", inputline); - startLIGHTSLIST = true; - LISTLINE = 0; - LoadFIZ_LightsList(inputline); - continue; - } - - if (issection("CompressorList:", inputline)) - { - startBPT = false; - fizlines.try_emplace("CompressorList", inputline); - startCOMPRESSORLIST = true; - LISTLINE = 0; - LoadFIZ_CompressorList(inputline); - continue; - } - - // ...and finally, table parsers. - // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized - if (true == startBPT) - { - readBPT(inputline); - continue; - } - if (true == startMPT) - { - readMPT(inputline); - continue; - } - if (true == startMPT0) - { - readMPT0(inputline); - continue; - } - if (true == startRLIST) - { - readRList(inputline); - continue; - } - if (true == startUCLIST) - { - readUCList(inputline); - continue; - } - if (true == startDLIST) - { - readDList(inputline); - continue; - } - if (true == startDIZELMOMENTUMLIST) - { - readDMList(inputline); - continue; - } - if (true == startDIZELV2NMAXLIST) - { - readV2NMAXList(inputline); - continue; - } - if (true == startHYDROTCLIST) - { - readHTCList(inputline); - continue; - } - if (true == startPMAXLIST) - { - readPmaxList(inputline); - continue; - } - if (true == startFFLIST) - { - readFFList(inputline); - continue; - } - if (true == startFFEDLIST) - { - readFFEDList(inputline); - continue; - } - if (true == startWWLIST) - { - readWWList(inputline); - continue; - } - if (true == startWiperList) - { - readWiperList(inputline); - continue; - } - if (true == startDimmerList) - { - readDimmerList(inputline); - } - if (true == startLIGHTSLIST) - { - readLightsList(inputline); - continue; - } - if (true == startCOMPRESSORLIST) - { - readCompressorList(inputline); - continue; - } - } // while line - /* - in.close(); - */ - // Operacje na zebranych parametrach - przypisywanie do wlasciwych zmiennych i ustawianie - // zaleznosci - - bool result; - if (ConversionError == 0) - result = true; - else - result = false; - - // ustawiamy domyslna pozycje dimmera - // the DefaultPos of a short or an empty DimmerList would put the dimmer outside of it - modernDimmerDefaultPosition = clampDimmerPosition(modernDimmerDefaultPosition); - modernDimmerPosition = clampDimmerPosition(modernDimmerPosition); - if (!enableModernDimmer) - { - modernDimmerPosition = modernDimmerDefaultPosition; - } - - WriteLog("CERROR: " + std::to_string(ConversionError) + ", SUCCES: " + std::to_string(result)); - return result; -} - -void TMoverParameters::LoadFIZ_Param(std::string const &line) -{ - - extract_value(Mass, "M", line, "0"); - extract_value(Mred, "Mred", line, "0"); - extract_value(Vmax, "Vmax", line, "0"); - extract_value(Power, "PWR", line, "0"); - extract_value(SandCapacity, "SandCap", line, "0"); - extract_value(HeatingPower, "HeatingP", line, "0"); - extract_value(LightPower, "LightP", line, "0"); - - { - std::map> categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; - std::string category; - extract_value(category, "Category", line, "none"); - auto lookup = categories.find(category); - CategoryFlag = lookup != categories.end() ? lookup->second : 0; - if (CategoryFlag == 0) - { - ErrorLog("Unknown vehicle category: \"" + category + "\"."); - } - } - - { - std::map> types{ - {"pseudodiesel", dt_PseudoDiesel}, - {"ezt", dt_EZT}, - {"dmu", dt_DMU}, - {"sn61", dt_SN61}, - {"et22", dt_ET22}, - {"et40", dt_ET40}, - {"et41", dt_ET41}, - {"et42", dt_ET42}, - {"ep05", dt_EP05}, - {"181", dt_181}, - {"182", dt_181} // na razie tak - }; - std::string type; - extract_value(type, "Type", line, "none"); - auto lookup = types.find(ToLower(type)); - TrainType = lookup != types.end() ? lookup->second : dt_Default; - } - - if (TrainType == dt_EZT) - { - - IminLo = 1; - IminHi = 2; - Imin = 1; - } -} - -void TMoverParameters::LoadFIZ_Load(std::string const &line) -{ - - auto const acceptedloads{Split(extract_value("LoadAccepted", line), ',')}; - - if (acceptedloads.empty()) - { - return; - } - - auto const minoffsets{Split(extract_value("LoadMinOffset", line), ',')}; - auto minoffset{0.f}; - auto minoffsetsiterator{std::begin(minoffsets)}; - // NOTE: last (if any) offset parameter retrieved from the list applies to the remainder of the list - // TBD, TODO: include other load parameters in this system - for (auto &load : acceptedloads) - { - if (minoffsetsiterator != std::end(minoffsets)) - { - minoffset = std::stof(*minoffsetsiterator); - ++minoffsetsiterator; - } - LoadAttributes.emplace_back(ToLower(load), minoffset); - } - - extract_value(MaxLoad, "MaxLoad", line, ""); - extract_value(LoadQuantity, "LoadQ", line, ""); - extract_value(OverLoadFactor, "OverLoadFactor", line, ""); - extract_value(LoadSpeed, "LoadSpeed", line, ""); - extract_value(UnLoadSpeed, "UnLoadSpeed", line, ""); -} - -void TMoverParameters::LoadFIZ_Headlights(std::string const &line) -{ - extract_value(refR, "LampRed", line, ""); - extract_value(refG, "LampGreen", line, ""); - extract_value(refB, "LampBlue", line, ""); - - extract_value(dimMultiplier, "DimmedMultiplier", line, ""); - extract_value(normMultiplier, "NormalMultiplier", line, ""); - extract_value(highDimMultiplier, "HighbeamDimmedMultiplier", line, ""); - extract_value(highMultiplier, "HighBeamMultiplier", line, ""); -} - -void TMoverParameters::LoadFIZ_Dimensions(std::string const &line) -{ - - extract_value(Dim.L, "L", line, ""); - extract_value(Dim.H, "H", line, ""); - extract_value(Dim.W, "W", line, ""); - - extract_value(Cx, "Cx", line, "0.3"); - if (Dim.H <= 2.0) - { - // gdyby nie było parametru, lepsze to niż zero - Floor = static_cast(Dim.H); - } - else - { - // zgodność wsteczna - Floor = 0.0; - } - extract_value(Floor, "Floor", line, ""); -} - -void TMoverParameters::LoadFIZ_Wheels(std::string const &line) -{ - - extract_value(WheelDiameter, "D", line, ""); - WheelDiameterL = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero - extract_value(WheelDiameterL, "Dl", line, ""); - WheelDiameterT = WheelDiameter; // gdyby nie było parametru, lepsze to niż zero - extract_value(WheelDiameterT, "Dt", line, ""); - - extract_value(TrackW, "Tw", line, ""); - extract_value(AxleInertialMoment, "AIM", line, ""); - - extract_value(AxleArangement, "Axle", line, ""); - NPoweredAxles = s2NPW(AxleArangement); - NAxles = NPoweredAxles + s2NNW(AxleArangement); - - BearingType = extract_value("BearingType", line) == "Roll" ? 1 : 0; - - extract_value(ADist, "Ad", line, ""); - extract_value(BDist, "Bd", line, ""); - - if (AxleInertialMoment <= 0.0) - { - /* - AxleInertialMoment = 1.0; - */ - // approximation formula by youby - auto const k = 472.0; // arbitrary constant - AxleInertialMoment = k / 4.0 * std::pow(WheelDiameter, 4.0) * NAxles; - Mred = k * std::pow(WheelDiameter, 2.0) * NAxles; - } -} - -void TMoverParameters::LoadFIZ_Brake(std::string const &line) -{ - - extract_value(BrakeValveParams, "BrakeValve", line, ""); - BrakeValveDecode(BrakeValveParams); - BrakeSubsystemDecode(); - - extract_value(NBpA, "NBpA", line, ""); - extract_value(MaxBrakeForce, "MBF", line, ""); - extract_value(BrakeValveSize, "Size", line, ""); - extract_value(TrackBrakeForce, "TBF", line, ""); - TrackBrakeForce *= 1000.0; - - extract_value(MaxBrakePress[3], "MaxBP", line, ""); - if (MaxBrakePress[3] > 0.0) - { - - extract_value(BrakeCylNo, "BCN", line, ""); - if (BrakeCylNo > 0) - { - - extract_value(MaxBrakePress[0], "MaxLBP", line, ""); - if (MaxBrakePress[0] < 0.01) - { - MaxBrakePress[0] = MaxBrakePress[3]; - } - extract_value(MaxBrakePress[1], "TareMaxBP", line, ""); - extract_value(MaxBrakePress[2], "MedMaxBP", line, ""); - extract_value(MaxBrakePress[4], "MaxASBP", line, ""); - if (MaxBrakePress[4] < 0.01) - { - MaxBrakePress[4] = 0.0; - } - - extract_value(BrakeCylRadius, "BCR", line, ""); - extract_value(BrakeCylDist, "BCD", line, ""); - extract_value(BrakeCylSpring, "BCS", line, ""); - extract_value(BrakeSlckAdj, "BSA", line, ""); - extract_value(BrakeRigEff, "BRE", line, "1"); - - extract_value(BrakeCylMult[0], "BCM", line, ""); - extract_value(BrakeCylMult[1], "BCMlo", line, ""); - extract_value(BrakeCylMult[2], "BCMHi", line, ""); - - P2FTrans = 100 * M_PI * std::pow(BrakeCylRadius, 2); // w kN/bar - - if (BrakeCylMult[1] > 0.0 || MaxBrakePress[1] > 0.0) - { - LoadFlag = 1; - } - else - { - LoadFlag = 0; - } - - BrakeVolume = M_PI * std::pow(BrakeCylRadius, 2) * BrakeCylDist * BrakeCylNo; - extract_value(BrakeVVolume, "BVV", line, ""); - - { - std::map> brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, - {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; - auto lookup = brakemethods.find(extract_value("BM", line)); - BrakeMethod = lookup != brakemethods.end() ? lookup->second : 0; - } - - extract_value(RapidMult, "RM", line, "1"); - extract_value(RapidVel, "RV", line, "55"); - } - } - else - { - // maxbrakepress[3] == 0 or less - P2FTrans = 0; - } - - // Ra 2014-07: trochę niedokładności - // the draws are sequenced: the order of the operands of '-' is unspecified, and GCC and MSVC draw them the other way round - auto const firstdraw{Random(10)}; - CntrlPipePress = 5 + 0.001 * (Random(10) - firstdraw); - extract_value(CntrlPipePress, "HiPP", line, ""); - HighPipePress = CntrlPipePress; - LowPipePress = std::min(HighPipePress, 3.5); - extract_value(LowPipePress, "LoPP", line, ""); - DeltaPipePress = HighPipePress - LowPipePress; - - extract_value(VeselVolume, "Vv", line, ""); - /* - if( VeselVolume == 0.0 ) { VeselVolume = 0.01; } - */ - extract_value(MinCompressor, "MinCP", line, ""); - extract_value(MaxCompressor, "MaxCP", line, ""); - extract_value(MinCompressor_cabB, "MinCP_B", line, ""); - extract_value(MaxCompressor_cabB, "MaxCP_B", line, ""); - extract_value(CompressorTankValve, "CompressorTankValve", line, ""); - extract_value(CompressorSpeed, "CompressorSpeed", line, ""); - extract_value(EmergencyValveOff, "MinEVP", line, ""); - extract_value(EmergencyValveOn, "MaxEVP", line, ""); - extract_value(EmergencyValveArea, "EVArea", line, ""); - extract_value(UniversalBrakeButtonFlag[0], "UBB1", line, ""); - extract_value(UniversalBrakeButtonFlag[1], "UBB2", line, ""); - extract_value(UniversalBrakeButtonFlag[2], "UBB3", line, ""); - extract_value(LockPipeOn, "LPOn", line, "-1"); - extract_value(LockPipeOff, "LPOff", line, "-1"); - extract_value(HandleUnlock, "HandlePipeUnlockPos", line, "-3"); - extract_value(EmergencyCutsOffHandle, "EmergencyCutsOffHandle", line, ""); - { - std::map> compressorpowers{ - {"Main", 0}, - // 1: default, powered by converter, with manual state control - {"Converter", 2}, - {"Engine", 3}, // equivalent of 0, TODO: separate 'main' and 'engine' in the code - {"Coupler1", 4}, // włączana w silnikowym EZT z przodu - {"Coupler2", 5} // włączana w silnikowym EZT z tyłu - }; - auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); - CompressorPower = lookup != compressorpowers.end() ? lookup->second : 1; - } - extract_value(CompressorStartDelay, "CompressorStartDelay", line, ""); - - if (true == extract_value(AirLeakRate, "AirLeakRate", line, "")) - { - // the parameter is provided in form of a multiplier, where 1.0 means the default rate of 0.01 - AirLeakRate *= 0.01; - } - - extract_value(ReleaserEnabledOnlyAtNoPowerPos, "ReleaserPowerPosLock", line, EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric ? "yes" : "no"); - - if (MinCompressor_cabB > 0.0) - { - MinCompressor_cabA = MinCompressor; - CabDependentCompressor = true; - } - else - { - MinCompressor_cabB = MinCompressor; - } - if (MaxCompressor_cabB > 0.0) - { - MaxCompressor_cabA = MaxCompressor; - CabDependentCompressor = true; - } - else - { - MaxCompressor_cabB = MaxCompressor; - } -} - -void TMoverParameters::LoadFIZ_Doors(std::string const &line) -{ - - std::map> doorcontrols{ - {"Passenger", control_t::passenger}, {"AutomaticCtrl", control_t::autonomous}, {"DriverCtrl", control_t::driver}, {"Conductor", control_t::conductor}, {"Mixed", control_t::mixed}}; - // opening method - { - auto lookup = doorcontrols.find(extract_value("OpenCtrl", line)); - Doors.open_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; - } - // closing method - { - auto lookup = doorcontrols.find(extract_value("CloseCtrl", line)); - Doors.close_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; - } - // automatic closing conditions - extract_value(Doors.auto_duration, "DoorStayOpen", line, ""); - extract_value(Doors.auto_velocity, "DoorAutoCloseVel", line, ""); - extract_value(Doors.auto_include_remote, "DoorAutoCloseRemote", line, ""); - // operation permit - extract_value(Doors.permit_needed, "DoorNeedPermit", line, ""); - // the door closure lamp (SOD) of the cab signals the doors of the whole consist - extract_value(Doors.closure_signal, "DoorClosureSignal", line, ""); - { - auto permitpresets = Split(extract_value("DoorPermitList", line), '|'); - for (auto const &permit : permitpresets) - { - Doors.permit_presets.emplace_back(std::stoi(permit)); - } - if (false == Doors.permit_presets.empty()) - { - // HACK: legacy position indices start from 1, so we deduct 1 to arrive at proper index into the array - extract_value(Doors.permit_preset, "DoorPermitListDefault", line, "1"); - Doors.permit_preset = std::min(static_cast(Doors.permit_presets.size()), Doors.permit_preset) - 1; - } - } - - extract_value(Doors.open_rate, "OpenSpeed", line, ""); - extract_value(Doors.open_delay, "DoorOpenDelay", line, ""); - extract_value(Doors.close_rate, "CloseSpeed", line, ""); - extract_value(Doors.close_delay, "DoorCloseDelay", line, ""); - extract_value(Doors.range, "DoorMaxShiftL", line, ""); - extract_value(Doors.range, "DoorMaxShiftR", line, ""); - extract_value(Doors.range_out, "DoorMaxShiftPlug", line, ""); - - std::map> doortypes{ - {"Shift", 1}, - {"Rotate", 2}, - {"Fold", 3}, - {"Plug", 4}, - }; - // opening method - { - auto lookup = doortypes.find(extract_value("DoorOpenMethod", line)); - Doors.type = lookup != doortypes.end() ? lookup->second : 2; // default type is plain, rotating door - } - - extract_value(Doors.has_warning, "DoorClosureWarning", line, ""); - extract_value(Doors.has_autowarning, "DoorClosureWarningAuto", line, ""); - extract_value(Doors.has_lock, "DoorBlocked", line, ""); - extract_value(Doors.doorLockSpeed, "DoorLockSpeed", line, ""); - { - auto const remotedoorcontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; - - extract_value(Doors.voltage, "DoorVoltage", line, remotedoorcontrol ? "24" : "0"); - } - - extract_value(Doors.step_rate, "PlatformSpeed", line, ""); - extract_value(Doors.step_range, "PlatformMaxShift", line, ""); - - std::string platformopenmethod; - extract_value(platformopenmethod, "PlatformOpenMethod", line, ""); - if (platformopenmethod == "Shift") - { - Doors.step_type = 1; - } // przesuw - - extract_value(MirrorMaxShift, "MirrorMaxShift", line, ""); - extract_value(MirrorVelClose, "MirrorVelClose", line, ""); - - extract_value(DoorsOpenWithPermitAfter, "DoorOpenWithPermit", line, ""); - extract_value(DoorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); -} - -namespace -{ - -// the value of an optional key of the line, or the default without it -double optional_value(std::string const &Line, std::string const &Key, double const Default) -{ - auto value{Default}; - extract_value(value, Key, Line, ""); - return value; -} - -// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it -double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default) -{ - auto value{0.0}; - return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default; -} - -// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of -// an automatic coupler have about a centimetre between them, a chain hangs loose -double default_slack(TCouplerType const Type) -{ - switch (Type) - { - case TCouplerType::Automatic: - return 0.005; - case TCouplerType::Chain: - return 0.05; - default: - return 0.0; - } -} - -// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from -// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have: -// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in -// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9 -// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one -// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks -// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it -// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid -coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line) -{ - coupler_physics::end_parameters parameters; - parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)}; - parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)}; - // only a screw coupling can be tightened to press the buffers in, and not past their travel - auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0}; - parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest); - // the legacy model sprang back at beta of the force it was loaded with - auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5}; - parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0); - parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0); - // as much as the legacy model had - parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0); - - // FmaxC is the rated breaking force of the coupling - auto const ultimate{std::max(Coupler.FmaxC, 1.0)}; - auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)}; - auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)}; - parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated}; - // the steel parts give a few millimetres under the rated force - parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003); - parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC)); - parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95); - return parameters; -} - -void scale_strength(coupler_physics::link_strength &Link, double const Factor) -{ - Link.yield *= Factor; - Link.ultimate *= Factor; -} - -} // namespace - -void TMoverParameters::LoadFIZ_BuffCoupl(std::string const &line, int const Index) -{ - - TCoupling *thiscoupler; - if (Index == 2) - { - thiscoupler = &Couplers[1]; - } - else - { - thiscoupler = &Couplers[0]; - } - - std::map> couplertypes{ - {"Automatic", TCouplerType::Automatic}, {"Screw", TCouplerType::Screw}, {"Chain", TCouplerType::Chain}, {"Bare", TCouplerType::Bare}, {"Articulated", TCouplerType::Articulated}, - }; - auto lookup = couplertypes.find(extract_value("CType", line)); - thiscoupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; - - extract_value(thiscoupler->SpringKC, "kC", line, ""); - extract_value(thiscoupler->DmaxC, "DmaxC", line, ""); - extract_value(thiscoupler->FmaxC, "FmaxC", line, ""); - extract_value(thiscoupler->SpringKB, "kB", line, ""); - extract_value(thiscoupler->DmaxB, "DmaxB", line, ""); - extract_value(thiscoupler->FmaxB, "FmaxB", line, ""); - extract_value(thiscoupler->beta, "beta", line, ""); - extract_value(thiscoupler->AutomaticCouplingFlag, "AutomaticFlag", line, ""); - extract_value(thiscoupler->AllowedFlag, "AllowedFlag", line, ""); - if (thiscoupler->AllowedFlag < 0) - { - thiscoupler->AllowedFlag = -thiscoupler->AllowedFlag | coupling::permanent; - } - extract_value(thiscoupler->PowerCoupling, "PowerCoupling", line, ""); - extract_value(thiscoupler->PowerFlag, "PowerFlag", line, ""); - extract_value(thiscoupler->control_type, "ControlType", line, ""); - - if (thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated) - { - - thiscoupler->SpringKC *= 1000; - thiscoupler->FmaxC *= 1000; - thiscoupler->SpringKB *= 1000; - thiscoupler->FmaxB *= 1000; - } - else if (thiscoupler->CouplerType == TCouplerType::Bare) - { - - thiscoupler->SpringKC = 50.0 * Mass + Ftmax / 0.05; - thiscoupler->DmaxC = 0.05; - thiscoupler->FmaxC = 100.0 * Mass + 2 * Ftmax; - thiscoupler->SpringKB = 60.0 * Mass + Ftmax / 0.05; - thiscoupler->DmaxB = 0.05; - thiscoupler->FmaxB = 50.0 * Mass + 2.0 * Ftmax; - thiscoupler->beta = 0.3; - } - else if (thiscoupler->CouplerType == TCouplerType::Articulated) - { - /* - coupler->SpringKC = 60.0 * Mass + 1000; - coupler->DmaxC = 0.05; - coupler->FmaxC = 20000000.0 + 2.0 * Ftmax; - coupler->SpringKB = 70.0 * Mass + 1000; - coupler->DmaxB = 0.05; - coupler->FmaxB = 4000000.0 + 2.0 * Ftmax; - coupler->beta = 0.55; - */ - thiscoupler->SpringKC = 4500 * 1000; - thiscoupler->FmaxC = 850 * 1000; - thiscoupler->SpringKB = 9200 * 1000; - thiscoupler->FmaxB = 320 * 1000; - thiscoupler->beta = 0.55; - // the spring force is taken up to Dmax only, past it the vehicles collide (CollisionDetect()); so the joint - // carries the full FmaxC either way before it gives. with 0.05 m it carried 225 kN, short of what a loaded - // articulated wagon in a freight train takes, which then collided at every step (eu07/maszyna#553) - thiscoupler->DmaxC = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKC); - thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); - } - - thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); - - if (Index == 0) - { - // 0 indicates single entry for both couplers - Couplers[1] = Couplers[0]; - } - // each coupling as made is a little stronger than its rated force, a different one at each end - for (int end = end::front; end <= end::rear; ++end) - { - if (Index == 0 || end == (Index == 2 ? end::rear : end::front)) - { - scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, end)); - } - } -} - -void TMoverParameters::LoadFIZ_TurboPos(std::string const &Input) -{ - - extract_value(TurboTest, "TurboPos", Input, ""); -} - -void TMoverParameters::LoadFIZ_Cntrl(std::string const &line) -{ - - { - using enum TBrakeSystem; - std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; - auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); - BrakeSystem = lookup != brakesystems.end() ? lookup->second : Individual; - } - if (BrakeSystem != TBrakeSystem::Individual) - { - using enum TBrakeHandle; - - extract_value(BrakeCtrlPosNo, "BCPN", line, ""); - for (int idx = 0; idx < 4; ++idx) - { - - extract_value(BrakeDelay[idx], std::format("BDelay{}", idx + 1), line, ""); - } - // brakedelays, brakedelayflag - { - std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, - {"PR", bdelay_P + bdelay_R}, - {"GP", bdelay_G + bdelay_P}, - {"R", bdelay_R}, - {"P", bdelay_P}, - {"G", bdelay_G}, - {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, - {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; - std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; - std::string brakedelay; - extract_value(brakedelay, "BrakeDelays", line, ""); - auto lookup = brakedelays.find(brakedelay); - BrakeDelays = lookup != brakedelays.end() ? lookup->second : 0; - lookup = brakedelayflags.find(brakedelay); - BrakeDelayFlag = lookup != brakedelayflags.end() ? lookup->second : 0; - } - // brakeopmode - { - std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; - auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); - BrakeOpModes = lookup != brakeopmodes.end() ? lookup->second : 0; - } - // brakehandle - { - std::map> brakehandles{ - {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, - {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, - {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; - auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); - BrakeHandle = lookup != brakehandles.end() ? lookup->second : NoHandle; - } - extract_value(Handle_AutomaticOverload, "HAO", line, ""); - extract_value(Handle_ManualOverload, "HMO", line, ""); - extract_value(Handle_GenericDoubleParameter1, "HGDP1", line, ""); - extract_value(Handle_GenericDoubleParameter2, "HGDP2", line, ""); - extract_value(Handle_OverloadMaxPressure, "OMP", line, ""); - extract_value(Handle_OverloadPressureDecrease, "OPD", line, ""); - // brakelochandle - { - std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; - auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); - BrakeLocHandle = lookup != locbrakehandles.end() ? lookup->second : NoHandle; - } - - // mbpm - if (true == extract_value(MBPM, "MaxBPMass", line, "")) - { - // NOTE: only convert the value from tons to kilograms if the entry is present in the config file - MBPM *= 1000.0; - } - - // asbtype - std::string const asb{ToLower(extract_value("ASB", line))}; - if (BrakeCtrlPosNo > 0) - { - - if (asb == "manual") - { - ASBType = 1; - } - else if (asb == "automatic") - { - ASBType = 2; - } - else if (asb == "yes") - { - ASBType = 128; - } - } - else - { - - if (asb == "yes") - { - ASBType = 128; - } - } - } // brakesystem != individual - - // localbrake - { - using enum TLocalBrake; - std::map> localbrakes{{"ManualBrake", ManualBrake}, {"PneumaticBrake", PneumaticBrake}, {"HydraulicBrake", HydraulicBrake}}; - auto lookup = localbrakes.find(extract_value("LocalBrake", line)); - LocalBrake = lookup != localbrakes.end() ? lookup->second : NoBrake; - } - // mbrake - extract_value(MBrake, "ManualBrake", line, ""); - - // maksymalna predkosc dostepna na tarczce predkosciomierza - extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); - - // horns - { - using enum horn_supply; - std::map> const hornsupplies{{"Pneumatic", air}, {"Electric", electric}}; - auto lookup = hornsupplies.find(extract_value("HornType", line)); - HornSupply = lookup != hornsupplies.end() ? lookup->second : air; - lookup = hornsupplies.find(extract_value("Horn3Type", line)); - Horn3Supply = lookup != hornsupplies.end() ? lookup->second : HornSupply; - } - - // dynamicbrake - { - std::map> dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}}; - auto lookup = dynamicbrakes.find(extract_value("DynamicBrake", line)); - DynamicBrakeType = lookup != dynamicbrakes.end() ? lookup->second : dbrake_none; - extract_value(DynamicBrakeAmpmeters, "DBAM", line, ""); - } - - // split ED/pneumatic brake control: when true the local brake operates only on the - // pneumatic locomotive cylinder while electrodynamic braking is commanded by a - // separate "dynamicbrakectrl" lever (or the negative range of jointctrl). - extract_value(SplitEDPneumaticBrake, "SplitEDPneumaticBrake", line, ""); - // number of stepped positions for the dedicated ED brake controller (default 10) - DynamicBrakeCtrlPosNo = 10; - extract_value(DynamicBrakeCtrlPosNo, "DBPN", line, ""); - if (DynamicBrakeCtrlPosNo < 1) - { - DynamicBrakeCtrlPosNo = 10; - } - - extract_value(MainCtrlPosNo, "MCPN", line, ""); - extract_value(ScndCtrlPosNo, "SCPN", line, ""); - extract_value(ScndInMain, "SCIM", line, ""); - extract_value(MainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); - - if (auto const autorelay{ToLower(extract_value("AutoRelay", line))}; autorelay == "optional") - { - AutoRelayType = 2; - } - else if (autorelay == "yes") - { - AutoRelayType = 1; - } - else - { - AutoRelayType = 0; - } - - extract_value(CoupledCtrl, "CoupledCtrl", line, ""); - extract_value(HasCamshaft, "Camshaft", line, ""); - extract_value(EIMCtrlType, "EIMCtrlType", line, ""); - EIMCtrlType = std::clamp(EIMCtrlType, 0, 3); - extract_value(LocHandleTimeTraxx, "LocalBrakeTraxx", line, ""); - extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); - extract_value(EIMCtrlEmergency, "EIMCtrlEmergency", line, ""); - // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one - extract_value(EIMCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); - if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) - { - // the old positions in the file: without the fix-up the controller would have no power position, and the - // reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions) - MainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); - ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, MainCtrlMaxDirChangePos)); - MainCtrlPosNo = elfpositions; - } - - extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR - extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych - - extract_value(InitialCtrlDelay, "IniCDelay", line, ""); - extract_value(CtrlDelay, "SCDelay", line, ""); - CtrlDownDelay = CtrlDelay; // hunter-101012: jesli nie ma SCDDelay; - extract_value(CtrlDownDelay, "SCDDelay", line, ""); - - // hunter-111012: dla siodemek 303E - FastSerialCircuit = ToLower(extract_value("FSCircuit", line)) == "yes" ? 1 : 0; - extract_value(BackwardsBranchesAllowed, "BackwardsBranchesAllowed", line, ""); - - extract_value(AutomaticCabActivation, "AutomaticCabActivation", line, ""); - extract_value(InactiveCabFlag, "InactiveCabFlag", line, ""); - - extract_value(StopBrakeDecc, "SBD", line, ""); - extract_value(ReleaseParkingBySpringBrake, "ReleaseParkingBySpringBrake", line, ""); - extract_value(ReleaseParkingBySpringBrakeWhenDoorIsOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); - extract_value(SpringBrakeCutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); - extract_value(SpringBrakeDriveEmergencyVel, "SpringBrakeDriveEmergencyVel", line, ""); - - extract_value(HideDirStatusWhenMoving, "HideDirStatusWhenMoving", line, ""); - extract_value(HideDirStatusSpeed, "HideDirStatusSpeed", line, ""); - extract_value(isDoubleClickForMeasureNeeded, "DCMB", line, ""); - extract_value(DistanceCounterDoublePressPeriod, "DCDPP", line, ""); - - extract_value(isBatteryButtonImpulse, "IBTB", line, ""); - extract_value(shouldHoldBatteryButton, "SBBBH", line, ""); - extract_value(BatteryButtonHoldTime, "BBHT", line, ""); - - std::map> starts{{"Disabled", start_t::disabled}, {"Manual", start_t::manual}, {"Automatic", start_t::automatic}, {"Mixed", start_t::manualwithautofallback}, - {"Battery", start_t::battery}, {"Converter", start_t::converter}, {"Direction", start_t::direction}}; - - // main circuit - extract_value(MainsInitTime, "MainInitTime", line, ""); - { - auto lookup = starts.find(extract_value("MainStart", line)); - MainsStart = lookup != starts.end() ? lookup->second : start_t::manual; - } - extract_value(PantographsRequireMains, "PantRequiresMain", line, ""); - // battery - { - auto lookup = starts.find(extract_value("BatteryStart", line)); - BatteryStart = lookup != starts.end() ? lookup->second : start_t::manual; - } - // converter - { - auto lookup = starts.find(extract_value("ConverterStart", line)); - ConverterStart = lookup != starts.end() ? lookup->second : start_t::manual; - } - extract_value(ConverterStartDelay, "ConverterStartDelay", line, ""); - extract_value(ConverterOverloadRelayOffWhenMainIsOff, "ConverterOverloadWhenMainIsOff", line, TrainType == dt_EZT ? "yes" : "no"); - // compressor - { - auto lookup = starts.find(extract_value("CompressorStart", line)); - CompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; - } - // pantograph compressor - { - auto lookup = starts.find(extract_value("PantCompressorStart", line)); - PantographCompressorStart = lookup != starts.end() ? lookup->second : start_t::manual; - } - // pantograph compressor valve - PantAutoValve = TrainType == dt_EZT; // legacy code behaviour, automatic valve was initially installed in all EMUs - extract_value(PantAutoValve, "PantAutoValve", line, ""); - // pantographs valve - { - auto lookup = starts.find(extract_value("PantEPValveStart", line)); - PantsValve.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy code behaviour, there was no pantographs valve - extract_value(PantsValve.spring, "PantEPValveSpring", line, ""); - } - // pantograph valve configuration - { - auto lookup = starts.find(extract_value("PantValveStart", line)); - auto valvestarttype = lookup != starts.end() ? lookup->second : start_t::manual; - auto valvespring{true}; - extract_value(valvespring, "PantValveSpring", line, ""); - auto valvesolenoid{true}; - extract_value(valvesolenoid, "PantValveSolenoid", line, ""); - for (auto &pantograph : Pantographs) - { - pantograph.valve.spring = valvespring; - pantograph.valve.solenoid = valvesolenoid; - pantograph.valve.start_type = valvestarttype; - } - } - // fuel pump - { - auto lookup = starts.find(extract_value("FuelStart", line)); - FuelPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; - } - // oil pump - { - auto lookup = starts.find(extract_value("OilStart", line)); - OilPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; - } - // water pump - { - auto lookup = starts.find(extract_value("WaterStart", line)); - WaterPump.start_type = lookup != starts.end() ? lookup->second : start_t::manual; - } - // traction motor fans - { - auto lookup = starts.find(extract_value("MotorBlowersStart", line)); - MotorBlowers[end::rear].start_type = lookup != starts.end() ? lookup->second : start_t::manual; - MotorBlowers[end::front].start_type = MotorBlowers[end::rear].start_type; - } - // what else the line contactors need to close - { - std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, - {"MotorBlowers", line_contactors_interlock::motor_blowers}}; - auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); - LineContactorsInterlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; - } - extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); - // compartment lights - { - auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); - CompartmentLights.start_type = lookup != starts.end() ? lookup->second : start_t::automatic; // legacy behaviour - } - // ground relay - { - auto lookup = starts.find(extract_value("GroundRelayStart", line)); - auto const defaultstart{TrainType == dt_EZT ? start_t::automatic : start_t::manual}; - GroundRelayStart = lookup != starts.end() ? lookup->second : defaultstart; - } - // converter overload relay - { - auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); - // the relay of a multiple unit activates when the converter is switched off - auto const defaultstart{TrainType == dt_EZT ? start_t::converter : start_t::manual}; - ConverterOverloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; - } -} - -void TMoverParameters::LoadFIZ_Blending(std::string const &line) -{ - - extract_value(MED_Vmax, "MED_Vmax", line, std::to_string(Vmax)); - extract_value(MED_Vmin, "MED_Vmin", line, "0"); - extract_value(MED_Vref, "MED_Vref", line, std::to_string(Vmax)); - extract_value(MED_amax, "MED_amax", line, "9.81"); - extract_value(MED_EPVC, "MED_EPVC", line, ""); - extract_value(MED_Ncor, "MED_Ncor", line, ""); - extract_value(MED_MinBrakeReqED, "MED_MinBrakeReqED", line, ""); - extract_value(MED_FrED_factor, "MED_FrEDFactor", line, ""); - extract_value(MED_ED_Delay1, "MED_FirstDelayED", line, ""); - extract_value(MED_ED_Delay2, "MED_ScndDelayED", line, ""); -} - -void TMoverParameters::LoadFIZ_DCEMUED(std::string const &line) -{ - - extract_value(DCEMUED_CC, "CouplerCheck", line, "0"); - extract_value(DCEMUED_EP_max_Vel, "EP_max_Vel", line, "0"); - extract_value(DCEMUED_EP_min_Im, "EP_min_Im", line, "0"); - extract_value(DCEMUED_EP_delay, "EP_delay", line, "0"); -} - -void TMoverParameters::LoadFIZ_SpringBrake(std::string const &line) -{ - - double vol{1.0}; - extract_value(vol, "Volume", line, "1"); - if (!SpringBrake.Cylinder) - SpringBrake.Cylinder = std::make_shared(); - SpringBrake.Cylinder->CreateCap(vol); - extract_value(SpringBrake.MaxBrakeForce, "MBF", line, ""); - extract_value(SpringBrake.MaxSetPressure, "MaxSP", line, ""); - extract_value(SpringBrake.ResetPressure, "ResetP", line, ""); - extract_value(SpringBrake.MinForcePressure, "MinFP", line, ""); - extract_value(SpringBrake.PressureOff, "PressOff", line, ""); - extract_value(SpringBrake.PressureOn, "PressOn", line, ""); - extract_value(SpringBrake.ValveOffArea, "ValveOnArea", line, ""); - extract_value(SpringBrake.ValveOnArea, "ValveOffArea", line, ""); - extract_value(SpringBrake.ValvePNBrakeArea, "ValvePNBArea", line, ""); - SpringBrake.PNBrakeConnection = SpringBrake.ValvePNBrakeArea > 0; - extract_value(SpringBrake.MultiTractionCoupler, "MTC", line, ""); - SpringBrake.ShuttOff = false; - SpringBrake.Activate = false; - SpringBrake.IsReady = true; -} - -void TMoverParameters::LoadFIZ_Light(std::string const &line) -{ - - LightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Light", line)); - LoadFIZ_PowerParamsDecode(LightPowerSource, "L", line); - - AlterLightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterLight", line)); - LoadFIZ_PowerParamsDecode(AlterLightPowerSource, "AlterL", line); - - extract_value(NominalVoltage, "Volt", line, ""); - extract_value(BatteryVoltage, "LMaxVoltage", line, ""); - NominalBatteryVoltage = static_cast(BatteryVoltage); -} - -void TMoverParameters::LoadFIZ_Clima(std::string const &line) -{ - - HeatingPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Heating", line)); - LoadFIZ_PowerParamsDecode(HeatingPowerSource, "H", line); - AlterHeatPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterHeating", line)); - LoadFIZ_PowerParamsDecode(AlterHeatPowerSource, "AlterH", line); -} - -void TMoverParameters::LoadFIZ_Power(std::string const &Line) -{ - - EnginePowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("EnginePower", Line)); - LoadFIZ_PowerParamsDecode(EnginePowerSource, "", Line); - /* - if( ( EnginePowerSource.SourceType == TPowerSource::Generator ) - && ( EnginePowerSource.GeneratorEngine == TEngineType::WheelsDriven ) ) { - // perpetuum mobile? - ConversionError = 666; - } - */ - if (Power == 0.0) - { - // jeśli nie ma mocy, np. rozrządcze EZT - EnginePowerSource.SourceType = TPowerSource::NotDefined; - } - - SystemPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("SystemPower", Line)); - LoadFIZ_PowerParamsDecode(SystemPowerSource, "", Line); -} - -void TMoverParameters::LoadFIZ_SpeedControl(std::string const &Line) -{ - // speed control - extract_value(SpeedCtrl, "SpeedCtrl", Line, ""); - if (!SpeedCtrl && EngineType == TEngineType::ElectricInductionMotor && ScndCtrlPosNo > 0) // backward compatibility - SpeedCtrl = true; - extract_value(SpeedCtrlDelay, "SpeedCtrlDelay", Line, ""); - SpeedCtrlTypeTime = extract_value("SpeedCtrlType", Line) == "Time" ? true : false; - extract_value(SpeedCtrlAutoTurnOffFlag, "SpeedCtrlATOF", Line, ""); - - auto speedpresets = Split(extract_value("SpeedButtons", Line), '|'); - int speed_no = 0; - for (auto const &speed : speedpresets) - { - SpeedCtrlButtons[speed_no++] = std::stod(speed); - if (speed_no > 9) - break; - } - extract_value(SpeedCtrlUnit.ManualStateOverride, "OverrideManual", Line, ""); - extract_value(SpeedCtrlUnit.BrakeIntervention, "BrakeIntervention", Line, ""); - extract_value(SpeedCtrlUnit.InitialPower, "InitPwr", Line, ""); - extract_value(SpeedCtrlUnit.FullPowerVelocity, "MaxPwrVel", Line, ""); - extract_value(SpeedCtrlUnit.StartVelocity, "StartVel", Line, ""); - extract_value(SpeedCtrlUnit.VelocityStep, "VelStep", Line, ""); - extract_value(SpeedCtrlUnit.PowerStep, "PwrStep", Line, ""); - extract_value(SpeedCtrlUnit.MinPower, "MinPwr", Line, ""); - extract_value(SpeedCtrlUnit.MaxPower, "MaxPwr", Line, ""); - extract_value(SpeedCtrlUnit.MinVelocity, "MinVel", Line, ""); - extract_value(SpeedCtrlUnit.MaxVelocity, "MaxVel", Line, ""); - extract_value(SpeedCtrlUnit.Offset, "Offset", Line, ""); - extract_value(SpeedCtrlUnit.FactorPpos, "kPpos", Line, ""); - extract_value(SpeedCtrlUnit.FactorPneg, "kPneg", Line, ""); - extract_value(SpeedCtrlUnit.FactorIpos, "kIpos", Line, ""); - extract_value(SpeedCtrlUnit.FactorIneg, "kIneg", Line, ""); - extract_value(SpeedCtrlUnit.BrakeInterventionVel, "BrakeIntMaxVel", Line, ""); - extract_value(SpeedCtrlUnit.PowerUpSpeed, "PowerUpSpeed", Line, ""); - extract_value(SpeedCtrlUnit.PowerDownSpeed, "PowerDownSpeed", Line, ""); -} - -void TMoverParameters::LoadFIZ_Engine(std::string const &Input) -{ - - EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); - extract_value(JointEngineStart, "JointEngineStart", Input, ""); - - if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) - { - // transmission type. moved here because more than one engine type has this entry - auto ratios = Split(transmission, ':'); // e.g. 18:79 - - if (ratios.size() != 2) - { - ErrorLog("Wrong transmition definition: " + transmission); - } - - Transmision.NToothM = std::atoi(ratios[0].c_str()); // ToothM to pierwszy czyli 18 - Transmision.NToothW = std::atoi(ratios[1].c_str()); // ToothW to drugi parametr czyli 79 - - if (Transmision.NToothM > 0) - Transmision.Ratio = static_cast(Transmision.NToothW) / Transmision.NToothM; - else - Transmision.Ratio = 1.0; - extract_value(Transmision.Efficiency, "TransEff", Input, ""); - } - - switch (EngineType) - { - - case TEngineType::ElectricSeriesMotor: - { - - extract_value(NominalVoltage, "Volt", Input, ""); - extract_value(WindingRes, "WindingRes", Input, ""); - if (WindingRes == 0.0) - { - - WindingRes = 0.01; - } - extract_value(nmax, "nmax", Input, ""); - nmax /= 60.0; - break; - } - case TEngineType::WheelsDriven: - case TEngineType::Dumb: - { - - extract_value(Ftmax, "Ftmax", Input, ""); - break; - } - case TEngineType::DieselEngine: - { - - extract_value(dizel_nmin, "nmin", Input, ""); - dizel_nmin /= 60.0; - dizel_nreg_min = dizel_nmin * 0.98; - extract_value(dizel_nmin_hdrive, "nmin_hdrive", Input, ""); - dizel_nmin_hdrive /= 60.0; - if (dizel_nmin_hdrive == 0.0) - { - dizel_nmin_hdrive = dizel_nmin; - } - extract_value(dizel_nmin_hdrive_factor, "nmin_hdrive_factor", Input, ""); - dizel_nmin_hdrive_factor /= 60.0; - extract_value(dizel_nmin_retarder, "nmin_retarder", Input, ""); - dizel_nmin_retarder /= 60.0; - if (dizel_nmin_retarder == 0.0) - { - dizel_nmin_retarder = dizel_nmin; - } - // TODO: unify naming scheme and sort out which diesel engine params are used where and how - extract_value(nmax, "nmax", Input, ""); - nmax /= 60.0; - extract_value(dizel_nmax_cutoff, "nmax_cutoff", Input, "0.0"); - dizel_nmax_cutoff /= 60.0; - extract_value(dizel_nreg_acc, "nreg_acc", Input, ""); - dizel_nreg_acc /= 60.0; - extract_value(dizel_AIM, "AIM", Input, "1.0"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - - extract_value(engageupspeed, "EUS", Input, "0.5"); - extract_value(engagedownspeed, "EDS", Input, "0.9"); - - if (true == extract_value(AnPos, "ShuntMode", Input, "")) - { - // dodatkowa przekładnia dla SM03 (2Ls150) - ShuntModeAllow = true; - ShuntMode = false; - if (AnPos < 1.0) - { - //"rozruch wysoki" ma dawać większą siłę - AnPos = 1.0 / AnPos; // im większa liczba, tym wolniej jedzie - } - } - extract_value(hydro_TC, "IsTC", Input, ""); - if (true == hydro_TC) - { - extract_value(hydro_TC_TMMax, "TC_TMMax", Input, ""); - extract_value(hydro_TC_CouplingPoint, "TC_CP", Input, ""); - extract_value(hydro_TC_LockupTorque, "TC_LT", Input, ""); - extract_value(hydro_TC_LockupRate, "TC_LR", Input, ""); - extract_value(hydro_TC_UnlockRate, "TC_ULR", Input, ""); - extract_value(hydro_TC_FillRateInc, "TC_FRI", Input, ""); - extract_value(hydro_TC_FillRateDec, "TC_FRD", Input, ""); - extract_value(hydro_TC_TorqueInIn, "TC_TII", Input, ""); - extract_value(hydro_TC_TorqueInOut, "TC_TIO", Input, ""); - extract_value(hydro_TC_TorqueOutOut, "TC_TOO", Input, ""); - extract_value(hydro_TC_LockupSpeed, "TC_LS", Input, ""); - extract_value(hydro_TC_UnlockSpeed, "TC_ULS", Input, ""); - extract_value(dizel_maxVelANS, "MaxVelANS", Input, ""); - - extract_value(hydro_R, "IsRetarder", Input, ""); - if (true == hydro_R) - { - extract_value(hydro_R_Placement, "R_Place", Input, ""); - extract_value(hydro_R_TorqueInIn, "R_TII", Input, ""); - extract_value(hydro_R_MaxTorque, "R_MT", Input, ""); - extract_value(hydro_R_MaxPower, "R_MP", Input, ""); - extract_value(hydro_R_FillRateInc, "R_FRI", Input, ""); - extract_value(hydro_R_FillRateDec, "R_FRD", Input, ""); - extract_value(hydro_R_MinVel, "R_MinVel", Input, ""); - extract_value(hydro_R_EngageVel, "R_EngageVel", Input, ""); - extract_value(hydro_R_Clutch, "R_IsClutch", Input, ""); - extract_value(hydro_R_ClutchSpeed, "R_ClutchSpeed", Input, ""); - extract_value(hydro_R_WithIndividual, "R_WithIndividual", Input, ""); - } - } - break; - } - case TEngineType::DieselElectric: - { // youBy - - extract_value(Ftmax, "Ftmax", Input, ""); - Flat = extract_value("Flat", Input) == "1"; - extract_value(Vhyp, "Vhyp", Input, ""); - Vhyp /= 3.6; - extract_value(Vadd, "Vadd", Input, ""); - Vadd /= 3.6; - extract_value(PowerCorRatio, "Cr", Input, ""); - extract_value(RelayType, "RelayType", Input, ""); - if (extract_value("ShuntMode", Input) == "1") - { - - ShuntModeAllow = true; - ShuntMode = false; - AnPos = 0.0; - ImaxHi = 2; - ImaxLo = 1; - } - extract_value(EngineHeatingRPM, "HeatingRPM", Input, ""); - extract_value(dizel_AIM, "AIM", Input, "1.25"); - extract_value(dizel_RevolutionsDecreaseRate, "RPMDecRate", Input, ""); - break; - } - case TEngineType::ElectricInductionMotor: - { - - RVentnmax = 1.0; - extract_value(NominalVoltage, "Volt", Input, ""); - - extract_value(eimc[eimc_s_dfic], "dfic", Input, ""); - extract_value(eimc[eimc_s_dfmax], "dfmax", Input, ""); - extract_value(eimc[eimc_s_p], "p", Input, ""); - extract_value(eimc[eimc_s_cfu], "cfu", Input, ""); - extract_value(eimc[eimc_s_cim], "cim", Input, ""); - extract_value(eimc[eimc_s_icif], "icif", Input, ""); - extract_value(eimc[eimc_f_Uzmax], "Uzmax", Input, ""); - extract_value(eimc[eimc_f_Uzh], "Uzh", Input, ""); - extract_value(eimc[eimc_f_DU], "DU", Input, ""); - extract_value(eimc[eimc_f_I0], "I0", Input, ""); - extract_value(eimc[eimc_f_cfu], "fcfu", Input, ""); - extract_value(eimc[eimc_f_cfuH], "fcfuH", Input, std::to_string(eimc[eimc_f_cfu])); - extract_value(eimc[eimc_p_F0], "F0", Input, ""); - extract_value(eimc[eimc_p_a1], "a1", Input, ""); - extract_value(eimc[eimc_p_Pmax], "Pmax", Input, ""); - extract_value(eimc[eimc_p_Fh], "Fh", Input, ""); - extract_value(eimc[eimc_p_Ph], "Ph", Input, ""); - extract_value(eimc[eimc_p_Vh0], "Vh0", Input, ""); - extract_value(eimc[eimc_p_Vh1], "Vh1", Input, ""); - extract_value(eimc[eimc_p_Imax], "Imax", Input, ""); - extract_value(eimc[eimc_p_abed], "abed", Input, ""); - extract_value(eimc[eimc_p_eped], "edep", Input, ""); - extract_value(EIMCLogForce, "eimclf", Input, ""); - extract_value(InvertersNo, "InvNo", Input, ""); - extract_value(InverterControlCouplerFlag, "InvCtrCplFlag", Input, ""); - extract_value(Imaxrpc, "Imaxrpc", Input, ""); - extract_value(BRVto, "BRVto", Input, ""); - extract_value(Flat, "Flat", Input, ""); - - if (eimc[eimc_p_Pmax] > 0 && Power > 0 && InvertersNo == 0) - { - InvertersNo = 1; - } - Inverters.resize(InvertersNo); - /*for (int i = 0; i > InvertersNo; i++) - { - inverter x; - Inverters.emplace_back(x); - }*/ - break; - } - default: - { - // nothing here - } - } // engine type - - // NOTE: elements shared by both diesel engine variants; crude but, eh - if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) - { - // oil pump - extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); - extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); - // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) - extract_value(dizel_SmokeDelay, "SmokeDelay", Input, "0"); - dizel_SmokeDelay = std::max(0.0, dizel_SmokeDelay); - // engine cooling factore - extract_value(dizel_heat.kw, "HeatKW", Input, ""); - extract_value(dizel_heat.kv, "HeatKV", Input, ""); - extract_value(dizel_heat.kfe, "HeatKFE", Input, ""); - extract_value(dizel_heat.kfs, "HeatKFS", Input, ""); - extract_value(dizel_heat.kfo, "HeatKFO", Input, ""); - extract_value(dizel_heat.kfo2, "HeatKFO2", Input, ""); - // engine cooling systems - extract_value(dizel_heat.water.config.temp_min, "WaterMinTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); - extract_value(dizel_heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); - extract_value(dizel_heat.water.config.shutters, "WaterShutters", Input, ""); - extract_value(dizel_heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); - extract_value(dizel_heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); - extract_value(dizel_heat.oil.config.temp_min, "OilMinTemperature", Input, ""); - extract_value(dizel_heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); - extract_value(dizel_heat.engine_max_temp, "EngineMaxTemperature", Input, ""); - extract_value(dizel_heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); - // water heater - extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); - extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); - float pf{ 1235.f }; - extract_value(pf, "NominalCoolingPower", Input, "1235"); - dizel_heat.powerfactor = 1235 / pf; - } - - // traction motors - extract_value(MotorBlowers[end::front].speed, "MotorBlowersSpeed", Input, ""); - extract_value(MotorBlowers[end::front].sustain_time, "MotorBlowersSustainTime", Input, ""); - extract_value(MotorBlowers[end::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); - MotorBlowers[end::rear] = MotorBlowers[end::front]; - // pressure switch - extract_value(HasControlPressureSwitch, "PressureSwitch", Input, TrainType != dt_EZT ? "yes" : "no"); -} - -void TMoverParameters::LoadFIZ_Switches(std::string const &Input) -{ - - extract_value(PantSwitchType, "Pantograph", Input, ""); - extract_value(ConvSwitchType, "Converter", Input, ""); - extract_value(StLinSwitchType, "MotorConnectors", Input, ""); - HeatingSwitchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; - // because people can't make up their minds whether it's "impulse" or "Impulse"... - PantSwitchType = ToLower(PantSwitchType); - ConvSwitchType = ToLower(ConvSwitchType); - StLinSwitchType = ToLower(StLinSwitchType); - // universal reset buttons assignments - extract_value(UniversalResetButtonFlag[0], "RelayResetButton1", Input, ""); - extract_value(UniversalResetButtonFlag[1], "RelayResetButton2", Input, ""); - extract_value(UniversalResetButtonFlag[2], "RelayResetButton3", Input, ""); - extract_value(enableModernDimmer, "ModernDimmer", Input, ""); - // pantograph presets - { - auto &presets{PantsPreset.first}; - extract_value(presets, "PantographPresets", Input, "0|1|3|2"); - std::erase(presets, '|'); - } -} - -void TMoverParameters::LoadFIZ_MotorParamTable(std::string const &Input) -{ - - switch (EngineType) - { - - case TEngineType::DieselEngine: - { - - extract_value(dizel_minVelfullengage, "minVelfullengage", Input, ""); - extract_value(dizel_engageDia, "engageDia", Input, ""); - extract_value(dizel_engageMaxForce, "engageMaxForce", Input, ""); - extract_value(dizel_engagefriction, "engagefriction", Input, ""); - break; - } - default: - { - // nothing here - } - } -} - -void TMoverParameters::LoadFIZ_Circuit(std::string const &Input) -{ - - extract_value(CircuitRes, "CircuitRes", Input, ""); - extract_value(IminLo, "IminLo", Input, ""); - extract_value(IminHi, "IminHi", Input, ""); - extract_value(ImaxLo, "ImaxLo", Input, ""); - extract_value(ImaxHi, "ImaxHi", Input, ""); - Imin = IminLo; - Imax = ImaxLo; - extract_value(TUHEX_Sum, "TUHEX_Sum", Input, ""); - extract_value(TUHEX_Diff, "TUHEX_Diff", Input, ""); - extract_value(TUHEX_MaxIw, "TUHEX_MaxIw", Input, ""); - extract_value(TUHEX_MinIw, "TUHEX_MinIw", Input, ""); - extract_value(TUHEX_Sum1, "TUHEX_Sum1", Input, ""); - extract_value(TUHEX_Sum2, "TUHEX_Sum2", Input, ""); - extract_value(TUHEX_Sum3, "TUHEX_Sum3", Input, ""); - extract_value(TUHEX_Stages, "TUHEX_Stages", Input, "0"); -} - -void TMoverParameters::LoadFIZ_AI(std::string const &Input) -{ - - extract_value(AIHintPantstate, "Pantstate", Input, ""); - extract_value(AIHintShuntPantstate, "ShuntPantstate", Input, ""); - extract_value(AIHintPantUpIfIdle, "IdlePantUp", Input, ""); - extract_value(AIHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); -} - -void TMoverParameters::LoadFIZ_RList(std::string const &Input) -{ - - extract_value(RlistSize, "Size", Input, ""); - - if (auto const venttype{ToLower(extract_value("RVent", Input))}; venttype == "automatic") - { - - RVentType = 2; - } - else - { - - RVentType = venttype == "yes" ? 1 : 0; - } - - if (RVentType > 0) - { - - extract_value(RVentnmax, "RVentnmax", Input, ""); - RVentnmax /= 60.0; - extract_value(RVentCutOff, "RVentCutOff", Input, ""); - } - extract_value(RVentMinI, "RVentMinI", Input, ""); - extract_value(RVentSpeed, "RVentSpeed", Input, ""); - extract_value(DynamicBrakeRes, "DynBrakeRes", Input, ""); - extract_value(DynamicBrakeRes1, "DynBrakeRes1", Input, ""); - extract_value(DynamicBrakeRes2, "DynBrakeRes2", Input, ""); -} - -void TMoverParameters::LoadFIZ_UCList(std::string const &Input) -{ - - extract_value(UniCtrlListSize, "Size", Input, ""); - extract_value(UniCtrlIntegratedBrakeCtrl, "IntegratedBrake", Input, ""); - extract_value(UniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, ""); - extract_value(UniCtrlIntegratedBrakePNCtrl, "IntegratedBrakePN", Input, ""); - extract_value(UniCtrlValStep, "CtrlValStep", Input, ""); - UniCtrlValStep = std::max(UniCtrlValStep, 0.0); -} - -void TMoverParameters::LoadFIZ_DList(std::string const &Input) -{ - - extract_value(dizel_Mmax, "Mmax", Input, ""); - extract_value(dizel_nMmax, "nMmax", Input, ""); - extract_value(dizel_Mnmax, "Mnmax", Input, ""); - extract_value(dizel_nmax, "nmax", Input, ""); - extract_value(dizel_nominalfill, "nominalfill", Input, ""); - extract_value(dizel_Mstand, "Mstand", Input, ""); - extract_value(dizel_NominalFuelConsumptionRate, "NomFuelConsRate", Input, ""); - - if (dizel_nMmax == dizel_nmax) - { - // HACK: guard against cases where nMmax == nmax, leading to division by 0 in momentum calculation - dizel_nMmax = dizel_nmax - 1.0 / 60.0; - } - - // Calculation of fuel consumption coefficient for futher calculation - double dizel_max_power = dizel_nmax * (dizel_Mnmax - dizel_Mstand) * M_PI * 2 * 0.001; // power in kW - double dizel_max_energy = dizel_max_power; // energy per one hour in kWh is equal to power in kW times 1 h - double fuel_density = 850; // g/l - dizel_FuelConsumption = dizel_NominalFuelConsumptionRate * dizel_max_energy / fuel_density / dizel_nmax; -} - -void TMoverParameters::LoadFIZ_FFList(std::string const &Input) -{ - extract_value(FFListSize, "Size", Input, ""); -} - -void TMoverParameters::LoadFIZ_FFEDList(std::string const &Input) -{ - extract_value(FFEDListSize, "Size", Input, ""); -} - -void TMoverParameters::LoadFIZ_WiperList(std::string const &Input) -{ - extract_value(WiperListSize, "Size", Input, ""); - extract_value(WiperAngle, "Angle", Input, ""); - extract_value(WiperDefaultPos, "Default", Input, ""); -} - -void TMoverParameters::LoadFIZ_DimmerList(std::string const &Input) -{ - // extract_value(modernWpierListSize, "Size", Input, ""); - extract_value(modernDimmerCanCycle, "Cycle", Input, ""); - extract_value(modernDimmerDefaultPosition, "DefaultPos", Input, ""); -} -void TMoverParameters::LoadFIZ_LightsList(std::string const &Input) -{ - - extract_value(LightsPosNo, "Size", Input, ""); - extract_value(LightsWrap, "Wrap", Input, ""); - extract_value(LightsDefPos, "Default", Input, ""); -} - -void TMoverParameters::LoadFIZ_CompressorList(std::string const &Input) -{ - - extract_value(CompressorListPosNo, "Size", Input, ""); - extract_value(CompressorListWrap, "Wrap", Input, ""); - extract_value(CompressorListDefPos, "Default", Input, ""); -} - -void TMoverParameters::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) -{ - - switch (Powerparameters.SourceType) - { - - case TPowerSource::NotDefined: - case TPowerSource::InternalSource: - { - - Powerparameters.PowerType = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerType", Line)); - break; - } - case TPowerSource::Transducer: - { - - extract_value(Powerparameters.Transducer.InputVoltage, Prefix + "TransducerInputV", Line, ""); - break; - } - case TPowerSource::Generator: - { - // prime mover for the generator - auto &generatorparameters{Powerparameters.EngineGenerator}; - - if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) - { - generatorparameters.engine_revolutions = &enrot; - } - else - { - // TODO: for engine types other than Main create requested engine object and link to its revolutions - generatorparameters.engine_revolutions = nullptr; - generatorparameters.revolutions = 0; - generatorparameters.voltage = 0; - } - // config - extract_value(generatorparameters.voltage_min, Prefix + "GeneratorMinVoltage", Line, "0"); - extract_value(generatorparameters.voltage_max, Prefix + "GeneratorMaxVoltage", Line, "0"); - // NOTE: for consistency the fiz file specifies revolutions per minute - extract_value(generatorparameters.revolutions_min, Prefix + "GeneratorMinRPM", Line, "0"); - extract_value(generatorparameters.revolutions_max, Prefix + "GeneratorMaxRPM", Line, "0"); - generatorparameters.revolutions_min /= 60; - generatorparameters.revolutions_max /= 60; - break; - } - case TPowerSource::Accumulator: - { - - extract_value(Powerparameters.RAccumulator.MaxCapacity, Prefix + "Cap", Line, ""); - Powerparameters.RAccumulator.RechargeSource = LoadFIZ_SourceDecode(extract_value(Prefix + "RS", Line)); - break; - } - case TPowerSource::CurrentCollector: - { - - auto &collectorparameters = Powerparameters.CollectorParameters; - - collectorparameters = TCurrentCollector{0, 0, 0, 0, 0, 0, false, 0, 0, 0, false, 0}; - - std::string PantType = ""; - extract_value(PantType, "PantType", Line, ""); - if (PantType == "AKP_4E") - collectorparameters.PantographType = TPantType::AKP_4E; - if (PantType.size() >= 3 && PantType.compare(0, 3, "DSA") == 0) - collectorparameters.PantographType = TPantType::DSAx; - if (PantType == "EC160" || PantType == "EC200") - collectorparameters.PantographType = TPantType::EC160_200; - if (PantType == "WBL85") - collectorparameters.PantographType = TPantType::WBL85; - - extract_value(collectorparameters.CollectorsNo, "CollectorsNo", Line, ""); - extract_value(collectorparameters.MinH, "MinH", Line, ""); - extract_value(collectorparameters.MaxH, "MaxH", Line, ""); - extract_value(collectorparameters.CSW, "CSW", Line, ""); // szerokość części roboczej - extract_value(collectorparameters.MaxV, "MaxVoltage", Line, ""); - extract_value(collectorparameters.OVP, "OverVoltProt", Line, ""); // przekaźnik nadnapięciowy - // napięcie rozłączające WS - collectorparameters.MinV = 0.5 * collectorparameters.MaxV; // gdyby parametr nie podany - extract_value(collectorparameters.MinV, "MinV", Line, ""); - // napięcie wymagane do załączenia WS - collectorparameters.InsetV = 0.6 * collectorparameters.MaxV; // gdyby parametr nie podany - extract_value(collectorparameters.InsetV, "InsetV", Line, ""); - // ciśnienie rozłączające WS - extract_value(collectorparameters.MinPress, "MinPress", Line, "3.5"); // domyślnie 2 bary do załączenia WS - // maksymalne ciśnienie za reduktorem - // collectorparameters.MaxPress = 5.0 + 0.001 * ( Random( 50 ) - Random( 50 ) ); - extract_value(collectorparameters.MaxPress, "MaxPress", Line, "5.0"); - extract_value(collectorparameters.FakePower, "FakePower", Line, ""); - if (extract_value(collectorparameters.PhysicalLayout, "PhysicalLayout", Line, "3")) - collectorparameters.CollectorsNo = std::min(collectorparameters.PhysicalLayout, 2); - break; - } - case TPowerSource::PowerCable: - { - - Powerparameters.RPowerCable.PowerTrans = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerTrans", Line)); - if (Powerparameters.RPowerCable.PowerTrans == TPowerType::SteamPower) - { - - extract_value(Powerparameters.RPowerCable.SteamPressure, Prefix + "SteamPress", Line, ""); - } - break; - } - case TPowerSource::Heater: - { - // jeszcze nie skonczone! - break; - } - default:; // nothing here - } - - if (Powerparameters.SourceType != TPowerSource::Heater && Powerparameters.SourceType != TPowerSource::InternalSource) - { - - extract_value(Powerparameters.MaxVoltage, Prefix + "MaxVoltage", Line, ""); - extract_value(Powerparameters.MaxCurrent, Prefix + "MaxCurrent", Line, ""); - extract_value(Powerparameters.IntR, Prefix + "IntR", Line, ""); - } -} - -TPowerType TMoverParameters::LoadFIZ_PowerDecode(std::string const &Powertype) const -{ - using enum TPowerType; - - std::map> powertypes{ - {"BioPower", BioPower}, {"MechPower", MechPower}, {"ElectricPower", ElectricPower}, {"SteamPower", SteamPower}}; - auto lookup = powertypes.find(Powertype); - return lookup != powertypes.end() ? lookup->second : NoPower; -} - -TPowerSource TMoverParameters::LoadFIZ_SourceDecode(std::string const &Source) const -{ - using enum TPowerSource; - - std::map> powersources{{"Transducer", Transducer}, {"Generator", Generator}, - {"Accu", Accumulator}, // legacy compatibility leftover. TODO: check if we can get rid of it - {"Accumulator", Accumulator}, {"CurrentCollector", CurrentCollector}, - {"PowerCable", PowerCable}, {"Heater", Heater}, - {"Internal", InternalSource}, {"Main", Main}}; - auto lookup = powersources.find(Source); - return lookup != powersources.end() ? lookup->second : NotDefined; -} - -TEngineType TMoverParameters::LoadFIZ_EngineDecode(std::string const &Engine) const -{ - using enum TEngineType; - - std::map> enginetypes{{"ElectricSeriesMotor", ElectricSeriesMotor}, - {"DieselEngine", DieselEngine}, - {"SteamEngine", SteamEngine}, - {"WheelsDriven", WheelsDriven}, - {"Dumb", Dumb}, - {"DieselElectric", DieselElectric}, - {"DumbDE", DieselElectric}, - {"ElectricInductionMotor", ElectricInductionMotor}, - {"Main", Main}}; - auto lookup = enginetypes.find(Engine); - return lookup != enginetypes.end() ? lookup->second : None; -} - -// ************************************************************************************************* -// Q: 20160717 -// ************************************************************************************************* - -bool TMoverParameters::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) -{ - WriteLog("check locomotive parameters..."); - bool OK = true; - - AutoRelayFlag = AutoRelayType == 1; - - if (NominalBatteryVoltage == 0.0) - { - BatteryStart = start_t::disabled; - } - - Sand = SandCapacity; - - // NOTE: for diesel-powered vehicles we automatically convert legacy "main" power source to more accurate "engine" - if (CompressorPower == 0 && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) - { - CompressorPower = 3; - } - - // for these engine types secondary controller positions index MotorParam table - if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && - ScndCtrlPosNo > MotorParametersArraySize) - { - WriteLog("SCPN=" + std::to_string(ScndCtrlPosNo) + " exceeds motor parameter table size, limited to " + std::to_string(MotorParametersArraySize)); - ScndCtrlPosNo = MotorParametersArraySize; - } - - // WriteLog("aa = " + AxleArangement + " " + std::string( Pos("o", AxleArangement)) ); - - if (contains(AxleArangement, "o") && EngineType == TEngineType::ElectricSeriesMotor) - { - // test poprawnosci ilosci osi indywidualnie napedzanych - OK = RList[1].Bn * RList[1].Mn == NPoweredAxles; - // WriteLogSS("aa ok", BoolToYN(OK)); - } - - if (BrakeSystem == TBrakeSystem::Individual && BrakeSubsystem != TBrakeSubSystem::ss_None) - OK = false; //! - - if (BrakeVVolume == 0 && MaxBrakePress[3] > 0 && BrakeSystem != TBrakeSystem::Individual) - { - BrakeVVolume = MaxBrakePress[3] / (5.0 - MaxBrakePress[3]) * (BrakeCylRadius * BrakeCylRadius * BrakeCylDist * BrakeCylNo * M_PI) * 1000; - } - if (BrakeVVolume == 0.0) - { - BrakeVVolume = 0.01; - } - // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); - - switch (BrakeValve) - { - case TBrakeValve::W: - case TBrakeValve::K: - { - WriteLog("XBT W, K"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::KE: - { - WriteLog("XBT WKE"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::NESt3: - case TBrakeValve::ESt3: - case TBrakeValve::ESt3AL2: - case TBrakeValve::ESt4: - { - WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - static_cast(Hamulec.get())->SetSize(BrakeValveSize, BrakeValveParams); - if (MBPM < 2) // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - else - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::LSt: - { - WriteLog("XBT LSt"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - break; - } - case TBrakeValve::EStED: - { - WriteLog("XBT EStED"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetRM(RapidMult); - if (MBPM < 2) - { - // jesli przystawka wazaca - Hamulec->SetLP(0, MaxBrakePress[3], 0); - } - else - { - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - } - break; - } - case TBrakeValve::EP2: - { - WriteLog("XBT EP2"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - break; - } - case TBrakeValve::EP1: - { - WriteLog("XBT EP1"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - Hamulec->SetLP(Mass, MBPM, MaxBrakePress[1]); - Hamulec->SetRM(RapidMult); - break; - } - case TBrakeValve::CV1: - { - WriteLog("XBT CV1"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - break; - } - case TBrakeValve::CV1_L_TR: - { - WriteLog("XBT CV1_L_T"); - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - break; - } - default: - Hamulec = std::make_shared(MaxBrakePress[3], BrakeCylRadius, BrakeCylDist, BrakeVVolume, BrakeCylNo, BrakeDelays, BrakeMethod, NAxles, NBpA); - } - - Hamulec->SetASBP(MaxBrakePress[4]); - Hamulec->SetRV(RapidVel); - - switch (BrakeHandle) - { - using enum TBrakeHandle; - case FV4a: - Handle = std::make_shared(); - break; - case MHZ_EN57: - case MHZ_K8P: - Handle = std::make_shared(); - break; - case FVel6: - Handle = std::make_shared(); - break; - case FVE408: - Handle = std::make_shared(); - break; - case testH: - Handle = std::make_shared(); - break; - case M394: - Handle = std::make_shared(); - break; - case Knorr: - Handle = std::make_shared(); - break; - case St113: - Handle = std::make_shared(); - break; - case MHZ_K5P: - Handle = std::make_shared(); - break; - case MHZ_6P: - Handle = std::make_shared(); - break; - default: - Handle = std::make_shared(); - } - Handle->SetParams(Handle_AutomaticOverload, Handle_ManualOverload, Handle_GenericDoubleParameter1, Handle_GenericDoubleParameter2, Handle_OverloadMaxPressure, Handle_OverloadPressureDecrease); - - switch (BrakeLocHandle) - { - case TBrakeHandle::FD1: - { - LocHandle = std::make_shared(); - LocHandle->Init(MaxBrakePress[0]); - if (TrainType == dt_EZT) - { - - dynamic_cast(LocHandle.get())->SetSpeed(3.5); - } - break; - } - case TBrakeHandle::Knorr: - { - LocHandle = std::make_shared(); - LocHandle->Init(MaxBrakePress[0]); - break; - } - default: - LocHandle = std::make_shared(); - } - - if (true == TestFlag(BrakeDelays, bdelay_G) && (false == TestFlag(BrakeDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy - Spg = 0.792; - else - Spg = 0.507; - // WriteLog("SPG = " + FloatToStr(Spg)); - - Pipe = std::make_shared(); - Pipe2 = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( - Pipe->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); // dlugosc x przekroj x odejscia i takie tam - Pipe2->CreateCap((std::max(Dim.L, 14.0) + 0.5) * Spg * 1); - if (!SpringBrake.Cylinder) - { - SpringBrake.Cylinder = std::make_shared(); - SpringBrake.Cylinder->CreateCap(1); - } - - if (LightsPosNo > 0) - LightsPos = LightsDefPos; - - // set default wiper switch position - wiperSwitchPos = WiperDefaultPos; - - if (CompressorListPosNo > 0) - CompressorListPos = CompressorListDefPos; - - // NOTE: legacy compatibility behaviour for vehicles without defined heating power source - if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) - { - HeatingPowerSource.SourceType = TPowerSource::Main; - } - if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && HeatingPower > 0) - { - HeatingPowerSource.SourceType = TPowerSource::PowerCable; - HeatingPowerSource.PowerType = TPowerType::ElectricPower; - } - - // checking ready flag - // to dac potem do init - if (ReadyFlag) // gotowy do drogi - { - WriteLog("Ready to depart"); - CompressedVolume = VeselVolume * MinCompressor * 9.8 / 10.0; - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.0 : - 0.0; - PipePress = CntrlPipePress; - BrakePress = 0.0; - LocalBrakePosA = 0.0; - if (CabActive == 0) - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - else - BrakeCtrlPos = static_cast(Handle->GetPos(bh_RP)); - /* - // NOTE: disabled and left up to the driver, if there's any - MainSwitch( false ); - PantFront( true ); - PantRear( true ); - MainSwitch( true ); - */ - DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! - DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów - LimPipePress = CntrlPipePress; - - Battery = BatteryStart != start_t::disabled; - } - else - { // zahamowany} - WriteLog("Braked"); - Volume = BrakeVVolume * MaxBrakePress[3]; - CompressedVolume = VeselVolume * MinCompressor * 0.55; - /* - ScndPipePress = 5.1; - */ - ScndPipePress = VeselVolume > 0.0 ? CompressedVolume / VeselVolume : - (Couplers[end::front].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - (Couplers[end::rear].AllowedFlag & coupling::mainhose) != 0 ? 5.1 : - 0.0; - PipePress = LowPipePress; - PipeBrakePress = MaxBrakePress[3] * 0.5; - BrakePress = MaxBrakePress[3] * 0.5; - LocalBrakePosA = 0.0; - BrakeCtrlPos = static_cast(Handle->GetPos(bh_NP)); - LimPipePress = LowPipePress; - if (LocalBrake == TLocalBrake::ManualBrake || MBrake == true) - { - IncManualBrakeLevel(ManualBrakePosNo); - } - if (SpringBrake.MaxBrakeForce > 0.0) - { - SpringBrake.Activate = true; - } - } - - ActFlowSpeed = 0.0; - BrakeCtrlPosR = BrakeCtrlPos; - - if (BrakeLocHandle == TBrakeHandle::Knorr) - LocalBrakePosA = 0.5; - - Pipe->CreatePress(PipePress); - Pipe2->CreatePress(ScndPipePress); - Pipe->Act(); - Pipe2->Act(); - - EqvtPipePress = PipePress; - - Handle->Init(PipePress); - - ComputeConstans(); - - if (LoadFlag > 0) - { - - if (LoadAmount < MaxLoad * 0.45) - { - IncBrakeMult(); - IncBrakeMult(); - DecBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount < MaxLoad * 0.35) - DecBrakeMult(); - } - else - { - IncBrakeMult(); // TODO: przeinesiono do mover.cpp - if (LoadAmount >= MaxLoad * 0.55) - IncBrakeMult(); - } - } - - // taki mini automat - powinno byc ladnie dobrze :) - BrakeDelayFlag = bdelay_P; - if (TestFlag(BrakeDelays, bdelay_G) && !TestFlag(BrakeDelays, bdelay_R)) - BrakeDelayFlag = bdelay_G; - if (TestFlag(BrakeDelays, bdelay_R) && !TestFlag(BrakeDelays, bdelay_G)) - BrakeDelayFlag = bdelay_R; - /* - // disabled, as test mode is used in specific situations and not really a default - if (BrakeOpModes & bom_PS) - BrakeOpModeFlag = bom_PS; - else - */ - BrakeOpModeFlag = bom_PN; - - // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% - std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; - - for (int b = 1; b < 4; b++) - { - if (BrakeDelay[b] == 0) - BrakeDelay[b] = DefBrakeTable[b]; - BrakeDelay[b] = BrakeDelay[b] * (2.5 + Random(0.0, 0.2)) / 3.0; - } - - Hamulec->Init(PipePress, HighPipePress, LowPipePress, BrakePress, BrakeDelayFlag); - /* - ScndPipePress = Compressor; - */ - // WriteLogSS("OK=", BoolTo10(OK)); - // WriteLog(""); - - if (EIMCtrlType == 3) - { - for (auto idx = 0; idx < MainCtrlPosNo; ++idx) - { - if (UniCtrlList[idx].MaxCtrlVal > 0.0) - { - UniCtrlNoPowerPos = std::max(0, idx - 1); - break; - } - } - } - - // security system - // by default place the magnet in the vehicle centre - if (SecuritySystem.MagnetLocation == 0) - { - SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; - } - SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); - - return OK; -} - -// ************************************************************************************************* -// Q: 20160714 -// Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu -// ************************************************************************************************* -void TMoverParameters::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) -{ - CommandLast = NewCommand; // zapamiętanie komendy - - CommandIn.Command = NewCommand; - CommandIn.Value1 = NewValue1; - CommandIn.Value2 = NewValue2; - CommandIn.Location = NewLocation; - // czy uruchomic tu RunInternalCommand? nie wiem -} - -// ************************************************************************************************* -// Q: 20160714 -// Pobiera komendę z parametru funkcji oraz wartość zmiennej jako return -// ************************************************************************************************* -double TMoverParameters::GetExternalCommand(std::string &Command) const -{ - Command = CommandOut; - return ValueOut; -} - -// ************************************************************************************************* -// Q: 20160714 -// Ustawienie komendy wraz z parametrami -// ************************************************************************************************* -bool TMoverParameters::SetInternalCommand(std::string const &NewCommand, double NewValue1, double NewValue2, int const Couplertype) -{ - bool SIC; - if (CommandIn.Command == NewCommand && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.Coupling == Couplertype) - SIC = false; - else - { - CommandIn.Command = NewCommand; - CommandIn.Value1 = NewValue1; - CommandIn.Value2 = NewValue2; - CommandIn.Coupling = Couplertype; - SIC = true; - LastLoadChangeTime = 0; // zerowanie czasu (roz)ładowania - } - - return SIC; -} - -// ************************************************************************************************* -// Q: 20160714 -// wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) -// ************************************************************************************************* -bool TMoverParameters::SendCtrlToNext(std::string const &CtrlCommand, double const ctrlvalue, double const dir, int const Couplertype) -{ - bool OK; - int d; // numer sprzęgu w kierunku którego wysyłamy - - // Ra: był problem z propagacją, jeśli w składzie jest pojazd wstawiony odwrotnie - // Ra: problem jest również, jeśli AI będzie na końcu składu - OK = true; // ( dir != 0 ); // experimentally disabled - d = (1 + static_cast(Sign(dir))) / 2; // dir=-1=>d=0, dir=1=>d=1 - wysyłanie tylko w tył - // musi być wybrana niezerowa kabina - if (OK && Couplers[d].Connected != nullptr && TestFlag(Couplers[d].CouplingFlag, Couplertype)) - { - - if (Couplers[d].ConnectedNr != d) - { - // jeśli ten nastpęny jest zgodny z aktualnym - if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, dir, Couplertype)) - OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja - } - else - { - // jeśli następny jest ustawiony przeciwnie, zmieniamy kierunek - if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, -dir, Couplertype)) - OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja - } - } - return OK; -} - -// ************************************************************************************************* -// Q: 20160723 -// ************************************************************************************************* -// wysłanie komendy otrzymanej z kierunku CValue2 (względem sprzęgów: 1=przod,-1=tył) -// Ra: Jest tu problem z rekurencją. Trzeba by oddzielić wykonywanie komend od mechanizmu -// ich propagacji w składzie. Osobnym problemem może być propagacja tylko w jedną stronę. -// Jeśli jakiś człon jest wstawiony odwrotnie, to również odwrotnie musi wykonywać -// komendy związane z kierunkami (PantFront, PantRear, DoorLeft, DoorRight). -// Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może -// sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania -// jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. -bool TMoverParameters::RunCommand(std::string const &Command, double CValue1, double CValue2, int const Couplertype) -{ - bool OK{false}; - - if (Command == "MainCtrl") - { - // sent as MainCtrlPosForCoupled(), passed on unchanged - if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) - { - MainCtrlPos = position; - if (DelayCtrlFlag) - { - if (LastRelayTime >= InitialCtrlDelay && MainCtrlPos == 1) - LastRelayTime = 0; - } - else if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "ScndCtrl") - { - if (ScndCtrlPosNo >= floor(CValue1)) - { - ScndCtrlPos = static_cast(floor(CValue1)); - if (LastRelayTime > CtrlDelay) - LastRelayTime = 0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - /* else if command='BrakeCtrl' then - begin - if BrakeCtrlPosNo>=Trunc(CValue1) then - begin - BrakeCtrlPos:=Trunc(CValue1); - OK:=SendCtrlToNext(command,CValue1,CValue2); - end; - end */ - else if (Command == "EIMIC") // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values - { - eimic_real = CValue1; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "Brake") // youBy - jak sie EP hamuje, to trza sygnal wyslac... - { - if (CValue1 < 0.001) - DynamicBrakeEMUStatus = true; - double temp1 = CValue1; - if (DCEMUED_EP_max_Vel > 0.001 && Vel > DCEMUED_EP_max_Vel && DynamicBrakeEMUStatus) - temp1 = 0; - if (DCEMUED_EP_min_Im > 0.001 && abs(Im) > DCEMUED_EP_min_Im && DynamicBrakeEMUStatus) - temp1 = 0; - Hamulec->SetEPS(temp1); - TUHEX_StageActual = static_cast(CValue1); - TUHEX_Active = TUHEX_StageActual > 0; - if (CValue1 < 0.001) - DynamicBrakeEMUStatus = true; - // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! - BrakePressureActual = BrakePressureTable[BrakeCtrlPos]; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } // youby - odluzniacz hamulcow, przyda sie - else if (Command == "BrakeReleaser") - { - OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej - // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n - } - else if (Command == "WaterPumpBreakerSwitch") - { - /* - if( FuelPump.start_type != start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - */ - WaterPump.breaker = CValue1 == 1; - /* - } - */ - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterPumpSwitch") - { - - if (WaterPump.start_type != start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - WaterPump.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterPumpSwitchOff") - { - - if (WaterPump.start_type != start_t::battery) - { - // automatic fuel pump ignores 'manual' state commands - WaterPump.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterHeaterBreakerSwitch") - { - /* - if( FuelPump.start_type != start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - */ - WaterHeater.breaker = CValue1 == 1; - /* - } - */ - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterHeaterSwitch") - { - /* - if( FuelPump.start_type != start::automatic ) { - // automatic fuel pump ignores 'manual' state commands - */ - WaterHeater.is_enabled = CValue1 == 1; - /* - } - */ - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "WaterCircuitsLinkSwitch") - { - if (true == dizel_heat.auxiliary_water_circuit) - { - // can only link circuits if the vehicle has more than one of them - WaterCircuitsLink = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "FuelPumpSwitch") - { - if (FuelPump.start_type != start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - FuelPump.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "FuelPumpSwitchOff") - { - if (FuelPump.start_type != start_t::automatic) - { - // automatic fuel pump ignores 'manual' state commands - FuelPump.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "OilPumpSwitch") - { - if (OilPump.start_type != start_t::automatic) - { - // automatic pump ignores 'manual' state commands - OilPump.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "OilPumpSwitchOff") - { - if (OilPump.start_type != start_t::automatic) - { - // automatic pump ignores 'manual' state commands - OilPump.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MotorBlowersFrontSwitch") - { - if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::front].is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MotorBlowersFrontSwitchOff") - { - if (MotorBlowers[end::front].start_type != start_t::manual && MotorBlowers[end::front].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::front].is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MotorBlowersRearSwitch") - { - if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::rear].is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MotorBlowersRearSwitchOff") - { - if (MotorBlowers[end::rear].start_type != start_t::manual && MotorBlowers[end::rear].start_type != start_t::manualwithautofallback) - { - // automatic device ignores 'manual' state commands - MotorBlowers[end::rear].is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompartmentLightsSwitch") - { - - if (CompartmentLights.start_type != start_t::automatic) - { - // automatic lights ignore 'manual' state commands - CompartmentLights.is_enabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompartmentLightsSwitchOff") - { - - if (CompartmentLights.start_type != start_t::automatic) - { - // automatic lights ignore 'manual' state commands - CompartmentLights.is_disabled = CValue1 == 1; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MainSwitch") - { - MainSwitch_(CValue1 > 0.0); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "HeatingSwitch") - { - HeatingSwitch_(CValue1 > 0.0); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "Direction") - { - DirActive = static_cast(floor(CValue1)); - DirAbsolute = DirActive * CabActive; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CabActivisation") - { - // OK:=Power>0.01; - switch (static_cast(CValue1 * CValue2)) - { // CValue2 ma zmieniany znak przy niezgodności sprzęgów - case 1: - { - CabActive = 1; - break; - } - case -1: - { - CabActive = -1; - break; - } - default: - { - CabActive = 0; // gdy CValue1==0 - break; - } - } - DirAbsolute = DirActive * CabActive; - CabMaster = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "AutoRelaySwitch") - { - if (CValue1 == 1 && AutoRelayType == 2) - AutoRelayFlag = true; - else - AutoRelayFlag = false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "RelayReset") - { - RelayReset(static_cast(CValue1), range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "ConverterSwitch") /*NBMX*/ - { - if (ConverterStart == start_t::manual) - { - ConverterAllow = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "BatterySwitch") /*NBMX*/ - { - if (BatteryStart == start_t::manual) - { - Battery = CValue1 > 0.0; - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - // else if command='EpFuseSwitch' then {NBMX} - // begin - // if (CValue1=1) then EpFuse:=true - // else if (CValue1=0) then EpFuse:=false; - // OK:=SendCtrlToNext(command,CValue1,CValue2); - // end - else if (Command == "CompressorSwitch") /*NBMX*/ - { - CompressorSwitch(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "CompressorPreset") - { - CompressorListPos = safe_clamp(static_cast(CValue1), 0, CompressorListPosNo); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorPermit") - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) - { - PermitDoors_(side::right, CValue1 > 0); - } - if (std::abs(static_cast(CValue1)) & leftside) - { - PermitDoors_(side::left, CValue1 > 0); - } - - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorOpen") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.open_control == control_t::conductor || Doors.open_control == control_t::driver || Doors.open_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_open = true; - Doors.instances[side::right].remote_close = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_open = true; - Doors.instances[side::left].remote_close = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorClose") /*NBMX*/ - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - // ignore remote command if the door is only operated locally - if ((Doors.close_control == control_t::conductor || Doors.close_control == control_t::driver || Doors.close_control == control_t::mixed) && (Power24vIsAvailable || Power110vIsAvailable)) - { - - auto const leftside{CValue2 > 0 ? 1 : 2}; - - if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) - { - Doors.instances[side::right].remote_close = true; - Doors.instances[side::right].remote_open = false; - } - if (static_cast(CValue1) & leftside) - { - Doors.instances[side::left].remote_close = true; - Doors.instances[side::left].remote_open = false; - } - } - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorLock") - { - Doors.lock_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorStep") - { - Doors.step_enabled = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DoorMode") - { - Doors.remote_only = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "DepartureSignal") - { - DepartureSignal = CValue1 == 1 ? true : false; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "PantValve") // Winger 160204 - { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów - auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; - auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; - auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; - auto const noswap{TrainType == dt_EZT || TrainType == dt_ET41}; - auto swap{false == noswap && TestFlag(Couplers[CValue2 == -1 ? end::rear : end::front].CouplingFlag, coupling::control)}; - if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) - { - swap = !swap; - } // TODO: check whether this part has RL equivalent - OperatePantographValve(static_cast(swap ? 1 - inputend : inputend), static_cast(inputoperation), range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "PantsValve") - { - OperatePantographsValve(static_cast(static_cast(CValue1)), range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "PantAllDown") - { - DropAllPantographs(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MaxCurrentSwitch") - { - MaxCurrentSwitch(CValue1 == 1, range_t::local); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "MinCurrentSwitch") - { - OK = MinCurrentSwitch(CValue1 == 1); - } - /*test komend oddzialywujacych na tabor*/ - else if (Command == "SetDamage") - { - if (CValue2 == 1) - OK = SetFlag(DamageFlag, static_cast(floor(CValue1))); - if (CValue2 == -1) - OK = SetFlag(DamageFlag, static_cast(-floor(CValue1))); - } - else if (Command == "Emergency_brake") - { - if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? - OK = true; - else - OK = false; - } - else if (Command == "BrakeDelay") - { - if (auto const brakesetting = static_cast(std::floor(CValue1)); true == Hamulec->SetBDF(brakesetting)) - { - BrakeDelayFlag = brakesetting; - OK = true; - } - else - { - OK = false; - } - SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "Sandbox") - { - OK = Sandbox(CValue1 == 1, range_t::local); - } - else if (Command == "CabSignal") /*SHP,Indusi*/ - { // Ra: to powinno działać tylko w członie obsadzonym - SecuritySystem.set_cabsignal(); - // else OK:=false; - OK = true; // true, gdy można usunąć komendę - } - /*naladunek/rozladunek*/ - // TODO: have these commands leverage load exchange system instead - // TODO: CValue1 defines amount to load/unload - else if (issection("Load=", Command)) - { - OK = false; // będzie powtarzane aż się załaduje - if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist - && MaxLoad > 0 && LoadAmount < MaxLoad * (1.0 + OverLoadFactor) && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) - { // ten peron/rampa - - auto const loadname{ToLower(extract_value("Load", Command))}; - if (LoadAmount == 0.f) - { - AssignLoad(loadname); - } - OK = LoadingDone(LoadSpeed, - loadname); // zmienia LoadStatus - } - else - { - // no loading can be done if conditions aren't met - LastLoadChangeTime = 0.0; - } - } - else if (issection("UnLoad=", Command)) - { - OK = false; // będzie powtarzane aż się rozładuje - if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist - && LoadAmount > 0 // czy jest co rozladowac? - && Distance(Loc, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) - { // ten peron - /*mozna to rozladowac*/ - OK = LoadingDone(-1.f * LoadSpeed, ToLower(extract_value("UnLoad", Command))); - } - else - { - // no loading can be done if conditions aren't met - LastLoadChangeTime = 0.0; - } - } - else if (Command == "SpeedCntrl") - { - if (EngineType == TEngineType::ElectricInductionMotor || SpeedCtrl) - SpeedCtrlValue = static_cast(round(CValue1)); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpeedCtrlUnit.Parking") - { - SpeedCtrlUnit.Parking = static_cast(CValue1); - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else if (Command == "SpringBrakeActivate") - { - if (Power24vIsAvailable || Power110vIsAvailable) - { - SpringBrake.Activate = CValue1 > 0; - OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); - } - else - OK = true; - } - - return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie -} - -// ************************************************************************************************* -// Q: 20160714 -// Uruchamia funkcję RunCommand aż do skutku. Jeśli będzie pozytywny to kasuje komendę. -// ************************************************************************************************* -bool TMoverParameters::RunInternalCommand() -{ - bool OK; - - if (!CommandIn.Command.empty()) - { - OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.Coupling); - if (OK) - { - - CommandIn.Command.clear(); // kasowanie bo rozkaz wykonany - CommandIn.Value1 = 0; - CommandIn.Value2 = 0; - CommandIn.Coupling = 0; - CommandIn.Location.X = 0; - CommandIn.Location.Y = 0; - CommandIn.Location.Z = 0; - switch_physics(true, wake_cause::command); - } - } - else - OK = false; - return OK; -} - -// ************************************************************************************************* -// Q: 20160714 -// Zwraca wartość natężenia prądu na wybranym amperomierzu. Podfunkcja do ShowCurrent. -// ************************************************************************************************* -double TMoverParameters::ShowCurrentP(int AmpN) const -{ - int Bn; - bool Grupowy; - - // ClearPendingExceptions; - Grupowy = DelayCtrlFlag && TrainType == dt_ET22; // przerzucanie walu grupowego w ET22; - Bn = RList[MainCtrlActualPos].Bn; // ile równoległych gałęzi silników - - if (DynamicBrakeType == dbrake_automatic && DynamicBrakeFlag) - Bn = DynamicBrakeAmpmeters; - if (Power > 0.01) - { - if (AmpN > 0) // podać prąd w gałęzi - { - if (Bn < AmpN || (Grupowy && AmpN == Bn - 1)) - return 0; - else // normalne podawanie pradu - return floor(abs(Im)); - } - else // podać całkowity - return floor(abs(Itot)); - } - else // pobor pradu jezeli niema mocy - { - int current = 0; - for (int b = 0; b < 2; b++) - // with Couplers[b] do - if (TestFlag(Couplers[b].CouplingFlag, coupling::control) && Couplers[b].Connected->Power > 0.01) - current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); - return current; - } -} - -bool TMoverParameters::reload_FIZ() -{ - WriteLog("[DEV] Reloading FIZ for " + Name); - // pause simulation - Global.iPause |= 0b1000; - if (bool result = LoadFIZ(chkPath); result == true) - { - // jesli sie udalo przeladowac FIZ - Global.iPause &= 0b0111; - WriteLog("[DEV] FIZ reloaded for " + Name); - } - else - { - // failed to reload - exit simulator - ErrorLog("[DEV] Failed to reload fiz for vehicle " + Name); - } - return true; -} - -namespace simulation -{ - -weights_table Weights; - -} // namespace simulation diff --git a/README.md b/README.md index d733db765..208526b0b 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ MaSzyna compiles and runs natively on **Linux** and **Windows**. Other platforms | `-DCMAKE_BUILD_TYPE=Debug` | Debug build | | `-DCMAKE_BUILD_TYPE=Release` | Release build | | `-DCMAKE_BUILD_TYPE=RelWithDebInfo` | Release build with debug symbols | +| `-DUSE_SYSTEM_JSON=ON/OFF` | Use an installed **nlohmann_json** 3.9 or newer (e.g. `nlohmann-json3-dev`, vcpkg `nlohmann-json`) instead of the `ref/json` submodule (default `OFF`) | | `-DPython3_ROOT_DIR=` | Root of the **Python 3.14** install on Windows (`python.exe`, `Lib`, `DLLs`) for embed/copy steps; on Linux, optional if CMake picks the wrong interpreter | > **macOS note:** macOS provides OpenGL only up to 4.1, so the OpenGL 4.6 renderer does not run there. @@ -226,7 +227,7 @@ If detection still fails, padding the file (with comments) up to ~1 MB may hel ## Minimum requirements - OS: **Windows 10 64-bit** -- Processor: **2 core at least 2 GHz (e.g. Intel Core i3-2100 / AMD Athlon II X2)** +- Processor: **4 cores with AVX2 support (e.g. Intel Core i5-4430 / AMD Ryzen 3 1200)** - RAM: **6 GB RAM** - Graphics Card: **supporting OpenGL 4.6 with at least 1GB VRAM** - **150 GB of free disk space** diff --git a/application/application.cpp b/application/application.cpp index 145106b62..fa74c3d7d 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -25,6 +25,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/renderer.h" #include "application/uilayer.h" #include "utilities/Logs.h" +#include "utilities/logfiles.h" #include "world/SleeperWorker.h" #include "rendering/screenshot.h" #include "utilities/translation.h" @@ -32,17 +33,21 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/memorystats.h" #include "utilities/framepacer.h" +#include "utilities/hardwareprobe.h" #include "utilities/dictionary.h" #include "version_info.h" #include "simulation/simulationtest.h" #include "utilities/physicslog.h" #include +#include #include +#include #include #include #include #include #include "utilities/translation.h" +#include "physics/vehicle.h" #if WITH_DISCORD_RPC #include "ref/discord-rpc/include/discord_rpc.h" @@ -98,6 +103,41 @@ void end_timer_period() timer_period_set = false; #endif } + +// debug.perflog: every so many seconds the tables of the debug panel of the renderer, its times on the cpu and the gpu by the pass +// and its counts of the draws, appended to perf.txt beside the log (emptied at the first write of the run), to tell what slows the +// frame down while the game runs +void write_performance_log() +{ + if ((Global.debug_perflog <= 0.f) || (GfxRenderer == nullptr) || (false == simulation::is_ready)) + return; + // the frames between two writes: the longest and how many took long, which the averages of the tables don't show + static auto last{std::chrono::steady_clock::now()}; + static auto next{last + std::chrono::seconds(5)}; + static bool started{false}; + static double longest{0.0}; + static int slow{0}; + static int stalled{0}; + static int frames{0}; + auto const now{std::chrono::steady_clock::now()}; + auto const frame{std::chrono::duration(now - last).count()}; + last = now; + longest = std::max(longest, frame); + slow += (frame > 25.0 ? 1 : 0); + stalled += (frame > 50.0 ? 1 : 0); + ++frames; + if (now < next) + return; + next = now + std::chrono::milliseconds(static_cast(Global.debug_perflog * 1000.f)); + std::ofstream out{"perf.txt", started ? std::ios::app : std::ios::trunc}; + started = true; + out << std::format("==== {:.1f} s, {} frames, the longest {:.1f} ms, {} over 25 ms, {} over 50 ms\n", Timer::GetTime(), frames, longest, slow, stalled); + longest = 0.0; + slow = 0; + stalled = 0; + frames = 0; + out << GfxRenderer->info_times() << "\n" << GfxRenderer->info_stats() << "\n"; +} } // namespace #ifdef _WIN32 @@ -195,6 +235,56 @@ void glfw_error_callback(int const Code, char const *Description) ErrorLog(message); } +#ifdef WITH_CRASHPAD +// there while the renderer starts (init_gfx()): left behind by a start which crashed in it +constexpr char const *GFX_START_MARK{"crashdumps/gfx_start.pending"}; +#endif + +// the mark of the start of the renderer put down (Starting) or taken away +void mark_gfx_start(bool const Starting) +{ +#ifdef WITH_CRASHPAD + std::error_code error; + if (Starting) + { + std::ofstream mark(GFX_START_MARK, std::ios::trunc); + } + else + { + std::filesystem::remove(GFX_START_MARK, error); + } +#else + (void)Starting; +#endif +} + +// the question about the report of the last crash, asked before the renderer starts when that crash came while it started: the window +// of the question is drawn by the renderer (run_crashgui()), so a crash in its start, which repeats at every start, would never let it +// show. a box of the system asks instead, on Windows, where the reports are made +void ask_crash_report_before_gfx() +{ +#if defined(WITH_CRASHPAD) && defined(_WIN32) + std::error_code error; + if ((false == crashreport_is_pending()) || Global.test.enabled || (false == std::filesystem::exists(GFX_START_MARK, error))) + { + return; + } + auto const polish{Global.asLang == "pl"}; + auto const *text{ + polish ? L"Podczas ostatniego uruchomienia symulator uległ awarii przy uruchamianiu grafiki.\nWysłać raport o błędzie do deweloperów?" : + L"The simulator crashed while starting the graphics during the last launch.\nSend the crash report to the developers?"}; + auto const *caption{polish ? L"Raportowanie błędów" : L"Crash reporting"}; + if (::MessageBoxW(nullptr, text, caption, MB_YESNO | MB_ICONERROR) == IDYES) + { + crashreport_upload_accept(); + } + else + { + crashreport_upload_reject(); + } +#endif +} + } // namespace // public: @@ -414,8 +504,10 @@ int eu07_application::init(int Argc, char *Argv[]) Global.threads.emplace("LogService", std::move(sLoggingService)); init_debug(); + result = init_settings(Argc, Argv); + // the log files are named by the settings (multiplelogs), so they are cleared and opened once those are read init_files(); - if ((result = init_settings(Argc, Argv)) != 0) + if (result != 0) { ErrorLog("Failed to initialize settings! Maybe you're missing eu07.ini file?"); return result; @@ -426,7 +518,7 @@ int eu07_application::init(int Argc, char *Argv[]) // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is // the seed somebody can write down and pass on - if (!Global.random_seed) + if (false == Global.random_seed_given) Global.random_seed = static_cast(true_random_seed()); Global.random_engine.seed(Global.random_seed); Global.local_random_engine.seed(Global.random_seed); @@ -452,6 +544,9 @@ int eu07_application::init(int Argc, char *Argv[]) WriteLog(settingspipe.str()); } + // the cpu, the memory and the graphics adapters, for the bug reports + hardware::log_system(); + WriteLog("// startup"); if ((result = init_glfw()) != 0) @@ -466,17 +561,23 @@ int eu07_application::init(int Argc, char *Argv[]) return result; } + ask_crash_report_before_gfx(); + mark_gfx_start(true); if ((result = init_gfx()) != 0) { + // a start which failed, not one which crashed + mark_gfx_start(false); ErrorLog("Failed to initialize GFX!"); return result; } if ((result = init_ui()) != 0) { // ui now depends on activated renderer + mark_gfx_start(false); ErrorLog("Failed to init UI!"); return result; } + mark_gfx_start(false); if (crashreport_is_pending() && false == Global.test.enabled) { // run crashgui as early as possible: it's drawn by the renderer if ((result = run_crashgui()) != 0) @@ -760,6 +861,7 @@ int eu07_application::run() m_network->update(); Timer::subsystem.mainloop_total.stop(); + write_performance_log(); // fpslimit: wait for the next frame's slot (eu07/maszyna#416) if (auto const nextframe{framepacer.next_frame(frame_pacer::clock::now(), Global.minframetime)}) { @@ -1274,16 +1376,19 @@ void eu07_application::init_console() void eu07_application::init_files() { - + // without multiplelogs the run writes the shared log.txt / errors.txt, and those of the run before go. with it the + // run writes files of its own in logs/, and the shared ones are left to whoever ran the game last without it + for (auto const &file : stale_log_files(Global.MultipleLogs)) + { + std::error_code error; // not there is fine + std::filesystem::remove(file, error); + } #ifdef _WIN32 - DeleteFile("log.txt"); - DeleteFile("errors.txt"); CreateDirectory("logs", nullptr); #elif __unix__ - unlink("log.txt"); - unlink("errors.txt"); mkdir("logs", 0750); #endif + OpenLogFiles(); } namespace fs = std::filesystem; @@ -1366,11 +1471,16 @@ int eu07_application::init_settings(int Argc, char *Argv[]) else if (token == "-seed") { // a number is the seed; anything else is a word that stands for one. said in the - // log as it was given, because that is what gets passed on to somebody else + // log as it was given, because that is what gets passed on to somebody else. 0 is a seed + // too; an empty word gives none, as randomseed with nothing after it if (i + 1 < Argc) { - Global.random_seed = seed_of(Argv[++i]); - WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + if (auto const seed{seed_given(Argv[++i])}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + } } } else if (token == "--test") @@ -1418,6 +1528,9 @@ int eu07_application::init_settings(int Argc, char *Argv[]) simulation::apply_test_mode_settings(); } + // a renderer this build doesn't have: the values of the removed renderers are taken for "default" as eu07.ini is read + // (global_settings::ConfigParse), and a vulkan renderer which can't run here falls back to opengl (select_gfx_backend()) + return 0; } diff --git a/application/consistviews.cpp b/application/consistviews.cpp new file mode 100644 index 000000000..55da9ca81 --- /dev/null +++ b/application/consistviews.cpp @@ -0,0 +1,317 @@ +/* +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 "application/consistviews.h" + +#include +#include + +#include "vehicle/Camera.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" + +namespace { + +// more vehicles than any train has: a guard against a loop in the couplings +std::size_t constexpr train_limit{1000}; +// metres the vehicle picked moves before the trackside view takes the way it went for the way of the train +double constexpr direction_step{0.5}; + +cameraviews::vehicle_pose pose_of(TDynamicObject const *Vehicle) { + cameraviews::vehicle_pose pose; + pose.position = Vehicle->GetPosition(); + pose.front = Vehicle->VectorFront(); + pose.length = Vehicle->physics->Dim.L; + pose.width = Vehicle->physics->Dim.W; + pose.height = Vehicle->physics->Dim.H; + return pose; +} + +// the end of the Vehicle the Other vehicle is beyond, -1 when it's beyond neither +int end_towards(TDynamicObject const *Vehicle, TDynamicObject const *Other) { + for (auto const side : VehicleEnds) { + if (Vehicle->physics->Neighbours[side].vehicle == Other) { + return NumberOf(side); + } + } + return -1; +} + +// the end of the Vehicle at an end of the train, away from the Inner vehicle next to it (nullptr when it's alone) +int outer_end(TDynamicObject const *Vehicle, TDynamicObject const *Inner, int const Alone) { + if (Inner == nullptr) { + return Alone; + } + auto const inner{end_towards(Vehicle, Inner)}; + return inner < 0 ? Alone : 1 - inner; +} + +cameraviews::coupler coupler_of(TDynamicObject const *Vehicle, VehicleEnd const End) { + cameraviews::coupler coupler; + coupler.position = Vehicle->CouplerPosition(End); + coupler.outward = Vehicle->VectorFront() * (End == VehicleEnd::front ? 1.0 : -1.0); + coupler.width = Vehicle->physics->Dim.W; + return coupler; +} + +// the driver's way: the front (1) or the rear (-1) of the Driven vehicle, as the user drives it +int driven_way(TDynamicObject const *Driven) { + auto const cab{Driven->physics->CabOccupied() < 0 ? -1 : 1}; + auto const direction{Driven->physics->DirActive < 0 ? -1 : 1}; + return cab * direction; +} + +// the coupler of the Vehicle furthest along the Way (or furthest back, with a negative Way) +glm::dvec3 end_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{Vehicle->CouplerPosition(VehicleEnd::front)}; + auto const rear{Vehicle->CouplerPosition(VehicleEnd::rear)}; + return glm::dot(front - rear, Way) >= 0.0 ? front : rear; +} + +// the front of the Vehicle, or its rear when that faces the Way +glm::dvec3 facing_along(TDynamicObject const *Vehicle, glm::dvec3 const &Way) { + auto const front{cameraviews::flat_front(Vehicle->VectorFront())}; + return glm::dot(front, Way) < 0.0 ? -front : front; +} + +bool usable(cameraviews::placement const &Place) { + auto const finite{[](glm::dvec3 const &Value) { return std::isfinite(Value.x) && std::isfinite(Value.y) && std::isfinite(Value.z); }}; + if (false == (finite(Place.eye) && finite(Place.target) && finite(Place.up))) { + return false; + } + auto const look{Place.target - Place.eye}; + if (glm::length(look) < 0.01 || glm::length(Place.up) < 0.5) { + return false; + } + // a camera looking along its own up has no way to tell left from right + return std::abs(glm::dot(glm::normalize(look), glm::normalize(Place.up))) < 0.999; +} + +} // namespace + +std::vector consist_views::train_of(TDynamicObject *Driven) { + std::vector train; + if (Driven == nullptr) { + return train; + } + auto const *controller{Driven->Mechanik != nullptr ? Driven->Mechanik : Driven->ctOwner}; + auto *first{controller != nullptr ? controller->Vehicle(VehicleEnd::front) : nullptr}; + if (first == nullptr) { + first = Driven; + } + for (auto *vehicle{first}; vehicle != nullptr && train.size() < train_limit; vehicle = vehicle->Next()) { + if (std::ranges::find(train, vehicle) != train.end()) { + break; + } + train.push_back(vehicle); + } + if (std::ranges::find(train, Driven) == train.end()) { + // the controller's list is behind the couplings: the driven vehicle alone, until it catches up + train.assign(1, Driven); + } + return train; +} + +TDynamicObject *consist_views::pick(std::vector const &Train, TDynamicObject *Driven) { + auto picked{std::ranges::find(Train, m_vehicle)}; + if (m_vehicle == nullptr || picked == Train.end()) { + picked = std::ranges::find(Train, Driven); + } + if (picked == Train.end()) { + picked = Train.begin(); + } + auto index{static_cast(picked - Train.begin())}; + if (m_view != kind::coupling) { + index = cameraviews::step_index(index, static_cast(Train.size()), m_step); + m_step = 0; + } + if (Train[index] != m_vehicle) { + // m_lastposition is of the vehicle before: the way the train goes is set again from the way the user drives, + // or the step between the two vehicles would be taken for a move + m_moved = false; + } + m_vehicle = Train[index]; + return m_vehicle; +} + +double consist_views::gap_beyond(TDynamicObject const *Vehicle, VehicleEnd const End) { + auto const &neighbour{Vehicle->physics->Neighbours[End]}; + if (neighbour.vehicle == nullptr || false == Vehicle->physics->Couplers[End].CouplingFlag.Empty()) { + return -1.0; + } + if (neighbour.distance > cameraviews::coupler_watch_range) { + return -1.0; + } + return std::max(0.0, static_cast(neighbour.distance)); +} + +consist_views::coupling_place consist_views::coupling_at(std::vector const &Train, int const Index) { + auto const count{static_cast(Train.size())}; + coupling_place place; + if (Index > 0 && Index < count) { + // between two vehicles of the train + auto *ahead{Train[Index - 1]}; + auto const *behind{Train[Index]}; + auto const aheadend{end_towards(ahead, behind)}; + auto const behindend{end_towards(behind, ahead)}; + place.vehicle = ahead; + place.coupler = coupler_of(ahead, aheadend < 0 ? VehicleEnd::rear : EndOf(aheadend)); + place.other = true; + place.otherposition = behind->CouplerPosition(behindend < 0 ? VehicleEnd::front : EndOf(behindend)); + return place; + } + // an end of the train, perhaps with another vehicle coming closer to it + auto const front{Index <= 0}; + auto *vehicle{front ? Train.front() : Train.back()}; + auto const *inner{count > 1 ? Train[front ? 1 : count - 2] : nullptr}; + auto const outer{outer_end(vehicle, inner, NumberOf(front ? VehicleEnd::front : VehicleEnd::rear))}; + place.vehicle = vehicle; + place.coupler = coupler_of(vehicle, EndOf(outer)); + auto const &neighbour{vehicle->physics->Neighbours[outer]}; + place.gap = gap_beyond(vehicle, EndOf(outer)); + if (place.gap >= 0.0 && (neighbour.FacingEnd() == VehicleEnd::front || neighbour.FacingEnd() == VehicleEnd::rear)) { + place.other = true; + place.otherposition = neighbour.vehicle->CouplerPosition(neighbour.FacingEnd()); + } + return place; +} + +cameraviews::train_motion consist_views::motion_of(std::vector const &Train, TDynamicObject const *Driven) { + auto const position{m_vehicle->GetPosition()}; + if (false == m_moved) { + // standing, the train is to go the way the user drives + m_direction = cameraviews::flat_front(m_vehicle->VectorFront()) * + static_cast(cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), driven_way(Driven))); + m_lastposition = position; + m_moved = true; + } + else if (std::hypot(position.x - m_lastposition.x, position.z - m_lastposition.z) > direction_step) { + m_direction = cameraviews::flat_front(position - m_lastposition); + m_lastposition = position; + } + std::vector positions; + positions.reserve(Train.size()); + for (auto const *vehicle : Train) { + positions.emplace_back(vehicle->GetPosition()); + } + auto const [head, tail]{cameraviews::train_ends(positions, m_direction)}; + cameraviews::train_motion motion; + motion.direction = m_direction; + motion.head = end_along(Train[head], m_direction); + motion.tail = end_along(Train[tail], -m_direction); + motion.speed = std::abs(m_vehicle->GetVelocity()) / 3.6; + motion.width = m_vehicle->physics->Dim.W; + if (Train.size() > 1) { + auto const *behind{Train[head == 0 ? 1 : head - 1]}; + motion.curvature = cameraviews::line_curvature(Train[head]->GetPosition(), facing_along(Train[head], m_direction), behind->GetPosition(), facing_along(behind, m_direction)); + } + return motion; +} + +cameraviews::placement consist_views::place_orbit(TCamera &Camera, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + if (m_orbit.radius <= 0.0) { + m_orbit = cameraviews::orbit_start(pose); + } + // the mouse turns the camera around the vehicle rather than the view away from it + glm::dvec2 const turn{Camera.Angle.x, Camera.Angle.y}; + Camera.Angle = {}; + m_orbit = cameraviews::orbit_moved(m_orbit, Camera.Velocity, turn, Seconds, pose); + return cameraviews::orbit_placement(m_orbit, pose); +} + +cameraviews::placement consist_views::place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double const Seconds) { + auto const pose{pose_of(m_vehicle)}; + auto length{0.0}; + for (auto const *vehicle : Train) { + length += vehicle->physics->Dim.L; + } + m_topdown = cameraviews::topdown_moved(m_topdown, Camera.Velocity, Seconds, pose, 0.5 * length + 50.0); + auto const facing{cameraviews::driving_facing(m_vehicle->VectorFront(), Driven->VectorFront(), Driven->physics->CabOccupied())}; + return cameraviews::topdown_placement(m_topdown, pose, facing); +} + +cameraviews::placement consist_views::place_coupling(TCamera const &Camera, std::vector const &Train, double const Seconds) { + auto const count{static_cast(Train.size())}; + if (m_coupling < 0) { + auto const front{coupling_at(Train, 0)}; + auto const rear{coupling_at(Train, count)}; + m_coupling = cameraviews::first_coupling(front.gap, rear.gap, count); + } + m_coupling = cameraviews::step_index(std::min(m_coupling, count), count + 1, m_step); + m_step = 0; + auto const place{coupling_at(Train, m_coupling)}; + m_vehicle = place.vehicle; + m_coupler = cameraviews::coupler_moved(m_coupler, Camera.Velocity, Seconds); + return cameraviews::coupler_placement(m_coupler, place.coupler, place.other ? &place.otherposition : nullptr); +} + +cameraviews::placement consist_views::place_trackside(std::vector const &Train, TDynamicObject const *Driven) { + auto const motion{motion_of(Train, Driven)}; + if (cameraviews::trackside_expired(m_trackside, motion)) { + m_trackside = cameraviews::trackside_next(m_trackside, motion); + } + return cameraviews::trackside_placement(m_trackside, cameraviews::orbit_centre(pose_of(m_vehicle))); +} + +TDynamicObject *consist_views::enter(kind const View, TDynamicObject *Driven) { + m_view = View; + m_step = 0; + if (View == kind::coupling) { + // each time the view starts at the end of the train something comes closer to, or at its front + m_coupling = -1; + } + if (View == kind::trackside) { + // and the railfan finds a new spot ahead of the train + m_trackside.placed = false; + m_moved = false; + } + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + return pick(train, Driven); +} + +void consist_views::select(int const Step) { + m_step += Step; +} + +TDynamicObject *consist_views::update(TCamera &Camera, TDynamicObject *Driven, double const Seconds) { + auto const train{train_of(Driven)}; + if (train.empty()) { + return nullptr; + } + pick(train, Driven); + cameraviews::placement place; + switch (m_view) { + case kind::orbit: + place = place_orbit(Camera, Seconds); + break; + case kind::shunting: + // straight down, the mouse would only tilt it off the train + Camera.Angle = {}; + place = place_shunting(Camera, train, Driven, Seconds); + break; + case kind::coupling: + place = place_coupling(Camera, train, Seconds); + break; + case kind::trackside: + place = place_trackside(train, Driven); + break; + } + if (usable(place)) { + Camera.Pos = place.eye; + Camera.LookAt = place.target; + Camera.vUp = place.up; + } + return m_vehicle; +} diff --git a/application/consistviews.h b/application/consistviews.h new file mode 100644 index 000000000..d5bf6641e --- /dev/null +++ b/application/consistviews.h @@ -0,0 +1,75 @@ +/* +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 + +#include +#include "physics/vehicletypes.h" + +#include "vehicle/cameraviews.h" + +class TCamera; +class TDynamicObject; + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551), after the four views +// [Shift]+[F4] had before: the orbit around a vehicle, the shunting view from above, the view beside a coupling +// and the trackside view of a railfan. [ and ] pick the vehicle (the coupling) the view goes with. The camera +// follows from cameraviews.h; this class hands over the vehicles of the train and keeps what the user set. +class consist_views { + +public: + enum class kind { orbit, shunting, coupling, trackside }; + + // starts the View of the train of the Driven vehicle, with the vehicle (or the coupling) picked before when it's + // still in the train; returns the vehicle the camera goes with, nullptr when there's no train + TDynamicObject *enter(kind View, TDynamicObject *Driven); + // picks the vehicle Step places towards the rear of the train (towards its front for a negative Step); the + // coupling in the coupling view + void select(int Step); + // places the Camera for this frame of Seconds (real time): the movement keys come from its Velocity, the mouse of + // the orbit from its Angle. returns the vehicle the camera goes with, nullptr when the train is gone + TDynamicObject *update(TCamera &Camera, TDynamicObject *Driven, double Seconds); + +private: + struct coupling_place { + TDynamicObject *vehicle{nullptr}; // the vehicle the coupler is on + cameraviews::coupler coupler; + bool other{false}; + glm::dvec3 otherposition{}; // the facing coupler of the vehicle beyond, coupled or coming closer + double gap{-1.0}; // at an end of the train: the distance to a vehicle coming closer, negative for none + }; + + // the vehicles of the train of the Driven vehicle, from its front to its rear + static std::vector train_of(TDynamicObject *Driven); + // the vehicle the camera goes with in the Train: the one picked before, or the Driven one + TDynamicObject *pick(std::vector const &Train, TDynamicObject *Driven); + // the Index coupling of the Train, 0 its front end, Train.size() its rear end + static coupling_place coupling_at(std::vector const &Train, int Index); + // the distance to a vehicle not coupled beyond the End of the Vehicle, negative for none + static double gap_beyond(TDynamicObject const *Vehicle, VehicleEnd End); + // keeps up the way the train goes and works out where its ends are, for the trackside view + cameraviews::train_motion motion_of(std::vector const &Train, TDynamicObject const *Driven); + + cameraviews::placement place_orbit(TCamera &Camera, double Seconds); + cameraviews::placement place_shunting(TCamera const &Camera, std::vector const &Train, TDynamicObject const *Driven, double Seconds); + cameraviews::placement place_coupling(TCamera const &Camera, std::vector const &Train, double Seconds); + cameraviews::placement place_trackside(std::vector const &Train, TDynamicObject const *Driven); + + kind m_view{kind::orbit}; + TDynamicObject *m_vehicle{nullptr}; // the vehicle picked; only compared with the vehicles of the train, never followed + int m_step{0}; // vehicles to step over in the next update, from [ and ] + int m_coupling{-1}; // the coupling picked in the coupling view, -1 not yet + cameraviews::orbit m_orbit; + cameraviews::topdown m_topdown; + cameraviews::coupler_view m_coupler; + cameraviews::trackside m_trackside; + glm::dvec3 m_lastposition{}; // of the vehicle picked, where the trackside view last saw it move + glm::dvec3 m_direction{0.0, 0.0, -1.0}; // the way the train goes, for the trackside view + bool m_moved{false}; // m_lastposition is known +}; diff --git a/application/driverhints.cpp b/application/driverhints.cpp index 0c6f02cc8..6c00c66f0 100644 --- a/application/driverhints.cpp +++ b/application/driverhints.cpp @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include "utilities/Globals.h" #include "utilities/utilities.h" +#include "physics/vehicle.h" void TController::hint( driver_hint const Value, hintpredicate const Predicate, float const Predicateparameter ) { @@ -81,75 +82,75 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) switch( Action ) { // battery case driver_hint::batteryon: { - if( AIControllFlag ) { - mvOccupied->BatterySwitch( true ); + if( aiControlled ) { + occupied->BatterySwitch( true ); } remove_hint( driver_hint::batteryoff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == true; } ); + return occupied->lowVoltage.config.batteryStart != start_t::manual || occupied->lowVoltage.Is24vAvailable() == true; } ); break; } case driver_hint::batteryoff: { - if( AIControllFlag ) { - mvOccupied->BatterySwitch( false ); + if( aiControlled ) { + occupied->BatterySwitch( false ); } remove_hint( driver_hint::batteryon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->BatteryStart != start_t::manual || mvOccupied->Power24vIsAvailable == false; } ); + return occupied->lowVoltage.config.batteryStart != start_t::manual || occupied->lowVoltage.Is24vAvailable() == false; } ); break; } // battery case driver_hint::cabactivation: { - if (AIControllFlag && mvOccupied->Power24vIsAvailable) { - mvOccupied->CabActivisation(); + if (aiControlled && occupied->lowVoltage.Is24vAvailable()) { + occupied->CabActivisation(); CheckVehicles(); } remove_hint( driver_hint::cabdeactivation ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->AutomaticCabActivation || mvOccupied->IsCabMaster(); } ); + return occupied->AutomaticCabActivation || occupied->IsCabMaster(); } ); break; } case driver_hint::cabdeactivation: { - if (AIControllFlag) { - mvOccupied->CabDeactivisation(); + if (aiControlled) { + occupied->CabDeactivisation(); } remove_hint( driver_hint::cabactivation ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->AutomaticCabActivation || (mvOccupied->CabMaster == false && mvOccupied->CabActive == 0); } ); + return occupied->AutomaticCabActivation || (occupied->CabMaster() == false && occupied->CabActive == 0); } ); break; } // radio case driver_hint::radioon: { - if( AIControllFlag ) { - mvOccupied->Radio = true; + if( aiControlled ) { + occupied->SetRadio(true); } remove_hint( driver_hint::radiooff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Radio == true; } ); + return occupied->Radio() == true; } ); break; } case driver_hint::radiofuseon: { - if( AIControllFlag ) { - mvOccupied->RadioFuse = true; + if( aiControlled ) { + occupied->SetRadioFuse(true); } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->RadioFuse == true; } ); + return occupied->RadioFuse() == true; } ); break; } case driver_hint::radiochannel: { - if( AIControllFlag ) { + if( aiControlled ) { iRadioChannel = static_cast( Actionparameter ); } hint( @@ -160,180 +161,180 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::radiooff: { - if( AIControllFlag ) { - mvOccupied->Radio = false; + if( aiControlled ) { + occupied->SetRadio(false); } remove_hint( driver_hint::radioon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Radio == false; } ); + return occupied->Radio() == false; } ); break; } // oil pump case driver_hint::oilpumpon: { - if( AIControllFlag ) { - mvOccupied->OilPumpSwitch( true ); + if( aiControlled ) { + occupied->OilPumpSwitch( true ); } remove_hint( driver_hint::oilpumpoff ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->OilPump }; - return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || mvOccupied->Mains; } ); + auto const &device { occupied->OilPump }; + return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true || occupied->lineBreaker.IsClosed(); } ); break; } case driver_hint::oilpumpoff: { - if( AIControllFlag ) { - mvOccupied->OilPumpSwitch( false ); + if( aiControlled ) { + occupied->OilPumpSwitch( false ); } remove_hint( driver_hint::oilpumpon ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->OilPump }; + auto const &device { occupied->OilPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; } // fuel pump case driver_hint::fuelpumpon: { - if( AIControllFlag ) { - mvOccupied->FuelPumpSwitch( true ); + if( aiControlled ) { + occupied->FuelPumpSwitch( true ); } remove_hint( driver_hint::fuelpumpoff ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->FuelPump }; + auto const &device { occupied->FuelPump }; return device.start_type != start_t::manual || device.is_enabled == true || device.is_active == true; } ); break; } case driver_hint::fuelpumpoff: { - if( AIControllFlag ) { - mvOccupied->FuelPumpSwitch( false ); + if( aiControlled ) { + occupied->FuelPumpSwitch( false ); } remove_hint( driver_hint::fuelpumpon ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->FuelPump }; + auto const &device { occupied->FuelPump }; return device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; } // pantographs case driver_hint::pantographairsourcesetmain: { - if( AIControllFlag ) { - mvPantographUnit->bPantKurek3 = true; + if( aiControlled ) { + pantographUnit->pantographAir.ConnectToMainReservoir(true); } remove_hint( driver_hint::pantographairsourcesetauxiliary ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->bPantKurek3 == true; } ); + return pantographUnit->pantographAir.IsConnectedToMainReservoir() == true; } ); break; } case driver_hint::pantographairsourcesetauxiliary: { - if( AIControllFlag ) { - mvPantographUnit->bPantKurek3 = false; + if( aiControlled ) { + pantographUnit->pantographAir.ConnectToMainReservoir(false); } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->bPantKurek3 == false; } ); + return pantographUnit->pantographAir.IsConnectedToMainReservoir() == false; } ); break; } case driver_hint::pantographcompressoron: { - if( AIControllFlag ) { - mvPantographUnit->PantCompFlag = true; + if( aiControlled ) { + pantographUnit->pantographAir.SwitchCompressor(true); } remove_hint( driver_hint::pantographcompressoroff ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantCompFlag == true; } ); + return pantographUnit->pantographAir.IsCompressorRunning() == true; } ); break; } case driver_hint::pantographcompressoroff: { - if( AIControllFlag ) { - mvPantographUnit->PantCompFlag = false; + if( aiControlled ) { + pantographUnit->pantographAir.SwitchCompressor(false); } remove_hint( driver_hint::pantographcompressoron ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantCompFlag == false; } ); + return pantographUnit->pantographAir.IsCompressorRunning() == false; } ); break; } case driver_hint::pantographsvalveon: { - if( AIControllFlag ) { - mvOccupied->OperatePantographsValve( operation_t::enable ); + if( aiControlled ) { + occupied->OperatePantographsValve( operation_t::enable ); } remove_hint( driver_hint::pantographsvalveoff ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantsValve.is_active == true; } ); + return pantographUnit->pantographAir.valve.is_active == true; } ); break; } case driver_hint::frontpantographvalveon: { - if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::front, operation_t::enable ); + if( aiControlled ) { + occupied->OperatePantographValve( VehicleEnd::front, operation_t::enable ); } remove_hint( driver_hint::frontpantographvalveoff ); hint( Action, [ this ]( float const Parameter ) { - return mvPantographUnit->Pantographs[end::front].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, + return pantographUnit->pantographs[VehicleEnd::front].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, Actionparameter ); break; } case driver_hint::frontpantographvalveoff: { - if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::front, operation_t::disable ); + if( aiControlled ) { + occupied->OperatePantographValve( VehicleEnd::front, operation_t::disable ); } remove_hint( driver_hint::frontpantographvalveon ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->Pantographs[end::front].valve.is_active == false; } ); + return pantographUnit->pantographs[VehicleEnd::front].valve.is_active == false; } ); break; } case driver_hint::rearpantographvalveon: { - if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::rear, operation_t::enable ); + if( aiControlled ) { + occupied->OperatePantographValve( VehicleEnd::rear, operation_t::enable ); } remove_hint( driver_hint::rearpantographvalveoff ); hint( Action, [ this ]( float const Parameter ) { - return mvPantographUnit->Pantographs[end::rear].valve.is_active == true || (Parameter > 0 && mvOccupied->Vel > Parameter); }, + return pantographUnit->pantographs[VehicleEnd::rear].valve.is_active == true || (Parameter > 0 && occupied->Vel > Parameter); }, Actionparameter ); break; } case driver_hint::rearpantographvalveoff: { - if( AIControllFlag ) { - mvOccupied->OperatePantographValve( end::rear, operation_t::disable ); + if( aiControlled ) { + occupied->OperatePantographValve( VehicleEnd::rear, operation_t::disable ); } remove_hint( driver_hint::rearpantographvalveon ); hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->Pantographs[end::rear].valve.is_active == false; } ); + return pantographUnit->pantographs[VehicleEnd::rear].valve.is_active == false; } ); break; } // converter case driver_hint::converteron: { - if( AIControllFlag ) { - mvOccupied->ConverterSwitch( true ); + if( aiControlled ) { + occupied->ConverterSwitch( true ); // the local switch of the converter too, where the line contactors wait for the vehicle's own converter // (LineContactorsInterlock): left off by the human driver, that vehicle would never take power pVehicle->for_each( - coupling::control, + Coupling::control, []( TDynamicObject * Vehicle ) { - auto *vehicle { Vehicle->MoverParameters }; + auto *vehicle { Vehicle->physics }; if( vehicle->LineContactorsHeldByLocalConverterSwitch() ) { - vehicle->ConverterAllowLocal = true; } } ); + vehicle->converter.SetLocalSwitch(true); } } ); } remove_hint( driver_hint::converteroff ); hint( @@ -343,8 +344,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::converteroff: { - if( AIControllFlag ) { - mvOccupied->ConverterSwitch( false ); + if( aiControlled ) { + occupied->ConverterSwitch( false ); } remove_hint( driver_hint::converteron ); hint( @@ -355,39 +356,39 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // relays case driver_hint::primaryconverteroverloadreset: { - if( AIControllFlag ) { - mvOccupied->RelayReset( relay_t::primaryconverteroverload ); + if( aiControlled ) { + occupied->RelayReset( relay_t::primaryconverteroverload ); } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->ConverterOverloadRelayStart != start_t::manual || mvOccupied->ConvOvldFlag == false; } ); + return occupied->converter.config.overloadRelayStart != start_t::manual || occupied->converter.IsOverloaded() == false; } ); break; } case driver_hint::maincircuitgroundreset: { - if( AIControllFlag ) { - mvOccupied->RelayReset( relay_t::maincircuitground ); + if( aiControlled ) { + occupied->RelayReset( relay_t::maincircuitground ); } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->GroundRelayStart != start_t::manual || mvOccupied->GroundRelay == true; } ); + return occupied->protection.config.groundStart != start_t::manual || occupied->protection.GroundHolds() == true; } ); break; } case driver_hint::tractionnmotoroverloadreset: { - if( AIControllFlag ) { - mvOccupied->RelayReset( relay_t::tractionnmotoroverload ); + if( aiControlled ) { + occupied->RelayReset( relay_t::tractionnmotoroverload ); } hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->FuseFlag == false; } ); + return occupied->FuseFlag == false; } ); break; } // line breaker case driver_hint::linebreakerclose: { - if( AIControllFlag ) { - mvOccupied->MainSwitch( true ); + if( aiControlled ) { + occupied->MainSwitch( true ); } remove_hint( driver_hint::linebreakeropen ); hint( @@ -397,21 +398,21 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::linebreakeropen: { - if( AIControllFlag ) { - mvOccupied->MainSwitch( false ); + if( aiControlled ) { + occupied->MainSwitch( false ); } remove_hint( driver_hint::linebreakerclose ); hint( Action, [this](float const /*Parameter*/) { // TBD, TODO: replace with consist-wide flag set true if any line breaker is closed? - return mvControlling->Mains == false; } ); + return mvControlling->lineBreaker.IsClosed() == false; } ); break; } // compressor case driver_hint::compressoron: { - if( AIControllFlag ) { - mvOccupied->CompressorSwitch( true ); + if( aiControlled ) { + occupied->CompressorSwitch( true ); } remove_hint( driver_hint::compressoroff ); hint( @@ -421,8 +422,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::compressoroff: { - if( AIControllFlag ) { - mvOccupied->CompressorSwitch( false ); + if( aiControlled ) { + occupied->CompressorSwitch( false ); } remove_hint( driver_hint::compressoron ); hint( @@ -432,81 +433,81 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::frontmotorblowerson: { - if( AIControllFlag ) { - mvOccupied->MotorBlowersSwitchOff( false, end::front ); - mvOccupied->MotorBlowersSwitch( true, end::front ); + if( aiControlled ) { + occupied->MotorBlowersSwitchOff( false, VehicleEnd::front ); + occupied->MotorBlowersSwitch( true, VehicleEnd::front ); } remove_hint( driver_hint::frontmotorblowersoff ); hint( Action, [this]( float const /*Parameter*/ ) { - auto const &device { mvOccupied->MotorBlowers[ end::front ] }; + auto const &device { occupied->MotorBlowers[ VehicleEnd::front ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; } case driver_hint::rearmotorblowerson: { - if( AIControllFlag ) { - mvOccupied->MotorBlowersSwitchOff( false, end::rear ); - mvOccupied->MotorBlowersSwitch( true, end::rear ); + if( aiControlled ) { + occupied->MotorBlowersSwitchOff( false, VehicleEnd::rear ); + occupied->MotorBlowersSwitch( true, VehicleEnd::rear ); } remove_hint( driver_hint::rearmotorblowersoff ); hint( Action, [this]( float const /*Parameter*/ ) { - auto const &device { mvOccupied->MotorBlowers[ end::rear ] }; + auto const &device { occupied->MotorBlowers[ VehicleEnd::rear ] }; return device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false); } ); break; } // spring brake case driver_hint::springbrakeon: { - if( AIControllFlag ) { - mvOccupied->SpringBrakeActivate( true ); + if( aiControlled ) { + occupied->SpringBrakeActivate( true ); } remove_hint( driver_hint::springbrakeoff ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->SpringBrake.Activate == true; } ); + return occupied->brakes.spring.activate == true; } ); break; } case driver_hint::springbrakeoff: { - if( AIControllFlag ) { - mvOccupied->SpringBrakeActivate( false ); + if( aiControlled ) { + occupied->SpringBrakeActivate( false ); } remove_hint( driver_hint::springbrakeon ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->SpringBrake.Activate == false; } ); + return occupied->brakes.spring.activate == false; } ); break; } // manual brake case driver_hint::manualbrakon: { - if( AIControllFlag ) { - mvOccupied->IncManualBrakeLevel( ManualBrakePosNo ); + if( aiControlled ) { + occupied->IncManualBrakeLevel( ManualBrakePosNo ); } remove_hint( driver_hint::manualbrakoff ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == ManualBrakePosNo; } ); + return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.HandBrakePosition() == ManualBrakePosNo; } ); break; } case driver_hint::manualbrakoff: { - if( AIControllFlag ) { - mvOccupied->DecManualBrakeLevel( ManualBrakePosNo ); + if( aiControlled ) { + occupied->DecManualBrakeLevel( ManualBrakePosNo ); } remove_hint( driver_hint::manualbrakon ); hint( Action, [this]( float const /*Parameter*/ ) { - return mvOccupied->LocalBrake != TLocalBrake::ManualBrake || mvOccupied->MBrake == false || mvOccupied->ManualBrakePos == 0; } ); + return occupied->brakes.config.localKind != TLocalBrake::ManualBrake || occupied->brakes.config.hasHandBrake == false || occupied->brakes.HandBrakePosition() == 0; } ); break; } // master controller case driver_hint::mastercontrollersetidle: { - if( AIControllFlag ) { - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 + if( aiControlled ) { + while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn == 0 && mvControlling->IncMainCtrl(1) ) { // all work is done in the loop header } @@ -515,16 +516,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0; } ); + return mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0; } ); break; } case driver_hint::mastercontrollersetseriesmode: { - if (AIControllFlag && mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1) { + if (aiControlled && mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1) { // limit yourself to series mode - if( mvControlling->ScndCtrlPos ) { + if( mvControlling->ScndCtrlPos() ) { mvControlling->DecScndCtrl( 2 ); } - while( mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 + while( mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1 && mvControlling->DecMainCtrl(1) ) { // all work is performed in the header } @@ -533,11 +534,11 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this]( float const /*Parameter*/ ) { - return mvControlling->RList[mvControlling->MainCtrlPos].Bn < 2; } ); + return mvControlling->RList[mvControlling->MainCtrlPos()].Bn < 2; } ); break; } case driver_hint::mastercontrollersetzerospeed: { - if( AIControllFlag ) { + if( aiControlled ) { ZeroSpeed(); } remove_master_controller_hints(); @@ -548,7 +549,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::mastercontrollersetreverserunlock: { - if( AIControllFlag ) { + if( aiControlled ) { while( false == mvControlling->EIMDirectionChangeAllow() && mvControlling->DecMainCtrl(1) ) { // all work is done in the loop header @@ -559,27 +560,27 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) Action, [this](float const /*Parameter*/) { return mvControlling->EIMDirectionChangeAllow(); }, - static_cast(mvControlling->MainCtrlMaxDirChangePos) ); + static_cast(mvControlling->MainCtrlMaxDirChangePos()) ); break; } case driver_hint::tractiveforcedecrease: { - if( AIControllFlag ) { + if( aiControlled ) { DecSpeed(); } remove_master_controller_hints(); hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Ft) <= Parameter; }, + return std::abs(mvControlling->Ft()) <= Parameter; }, static_cast(std::min( 0.0, std::max( - std::abs( mvControlling->Ft ) * 0.95, - std::abs( mvControlling->Ft ) - 5.0 ) )) ); + std::abs( mvControlling->Ft() ) * 0.95, + std::abs( mvControlling->Ft() ) - 5.0 ) )) ); break; } case driver_hint::tractiveforceincrease: { - if( AIControllFlag ) { + if( aiControlled ) { IncSpeed(); } remove_master_controller_hints(); @@ -592,24 +593,24 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return AccDesired <= EU07_AI_NOACCELERATION || (false == Ready && false == mvOccupied->ShuntMode) || AccDesired - AbsAccS <= 0.05 || - (mvOccupied->EIMCtrlType > 0 ? mvControlling->eimic_real >= 1.0 : mvControlling->IsScndCtrlMaxPowerPos() && mvControlling->IsMainCtrlMaxPowerPos()); } ); + return AccDesired <= EU07_AI_NOACCELERATION || (false == Ready && false == occupied->ShuntMode) || AccDesired - AbsAccS <= 0.05 || + (occupied->EIMCtrlType > 0 ? mvControlling->EimicReal() >= 1.0 : mvControlling->IsScndCtrlMaxPowerPos() && mvControlling->IsMainCtrlMaxPowerPos()); } ); break; } case driver_hint::bufferscompress: { - if (AIControllFlag && std::abs( mvControlling->Ft ) < 50000.0) { + if (aiControlled && std::abs( mvControlling->Ft() ) < 50000.0) { IncSpeed(); } remove_master_controller_hints(); hint( Action, [this](float const /*Parameter*/) { - return std::abs(mvControlling->Ft) > 30.0 || (OrderCurrentGet() & Disconnect) == 0; } ); + return std::abs(mvControlling->Ft()) > 30.0 || false == OrderCurrentGet().HasAny(DriverOrder::disconnect); } ); break; } case driver_hint::secondcontrollersetzero: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->DecScndCtrl( 2 ); } remove_master_controller_hints(); @@ -621,7 +622,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } case driver_hint::waterpumpon: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpSwitch( true ); } remove_hint( driver_hint::waterpumpoff ); @@ -633,7 +634,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterpumpoff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpSwitch( false ); } remove_hint( driver_hint::waterpumpon ); @@ -645,7 +646,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterpumpbreakeron: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpBreakerSwitch( true ); } remove_hint( driver_hint::waterpumpbreakeroff ); @@ -657,7 +658,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterpumpbreakeroff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterPumpBreakerSwitch( false ); } remove_hint( driver_hint::waterpumpbreakeron ); @@ -669,7 +670,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheateron: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterSwitch( true ); } remove_hint( driver_hint::waterheateroff ); @@ -681,7 +682,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheateroff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterSwitch( false ); } remove_hint( driver_hint::waterheateron ); @@ -693,7 +694,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheaterbreakeron: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterBreakerSwitch( true ); } remove_hint( driver_hint::waterheaterbreakeroff ); @@ -705,7 +706,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::waterheaterbreakeroff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterHeaterBreakerSwitch( false ); } remove_hint( driver_hint::waterheaterbreakeron ); @@ -717,25 +718,25 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::watercircuitslinkon: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterCircuitsLinkSwitch( true ); } remove_hint( driver_hint::watercircuitslinkoff ); hint( Action, [this](float const /*Parameter*/) { - return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == true; } ); + return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink() == true; } ); break; } case driver_hint::watercircuitslinkoff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->WaterCircuitsLinkSwitch( false ); } remove_hint( driver_hint::watercircuitslinkon ); hint( Action, [this](float const /*Parameter*/) { - return mvControlling->dizel_heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink == false; } ); + return mvControlling->diesel.heat.auxiliary_water_circuit == false || mvControlling->WaterCircuitsLink() == false; } ); break; } case driver_hint::waittemperaturetoolow: { @@ -751,7 +752,7 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0; } ); + return mvControlling->mainPipe.Pressure() > 4.5 || mvControlling->air.config.mainReservoirVolume == 0.0; } ); break; } case driver_hint::waitpantographpressuretoolow: { @@ -759,7 +760,15 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvPantographUnit->PantPress >= (is_emu() ? (mvPantographUnit->PantPressLockActive ? 4.6 : 2.6) : 4.2); } ); + return pantographUnit->pantographAir.Pressure() >= (is_emu() ? (pantographUnit->pantographAir.IsPressureLockActive() ? 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: { @@ -787,8 +796,8 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) // driver_hint_brakingforcesetzero // driver_hint_brakingforcelap case driver_hint::trainbrakesetpipeunlock: { - if (AIControllFlag && mvOccupied->HandleUnlock != -3) { - while( BrakeCtrlPosition >= mvOccupied->HandleUnlock + if (aiControlled && occupied->brakes.pipeLock.unlockHandlePosition != -3) { + while( BrakeCtrlPosition >= occupied->brakes.pipeLock.unlockHandlePosition && BrakeLevelAdd(-1) ) { // all work is done in the header } @@ -797,27 +806,27 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->HandleUnlock == -3 || BrakeCtrlPosition == mvOccupied->HandleUnlock; } ); + return occupied->brakes.pipeLock.unlockHandlePosition == -3 || BrakeCtrlPosition == occupied->brakes.pipeLock.unlockHandlePosition; } ); break; } case driver_hint::trainbrakerelease: { - if( AIControllFlag ) { -// mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_RP ) ); + if( aiControlled ) { +// occupied->BrakeLevelSet( occupied->Handle->GetPos( bh_RP ) ); BrakeLevelSet( gbh_RP ); } remove_train_brake_hints(); hint( Action, [this](float const /*Parameter*/) { - return is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) || (mvOccupied->Handle->Time && mvOccupied->Handle->GetCP() > mvOccupied->HighPipePress - 0.05); } ); + return is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_RP), 0.2) || (occupied->brakes.driverValve->Time && occupied->brakes.driverValve->GetCP() > occupied->brakes.config.pipeHighPressure - 0.05); } ); // return ( BrakeCtrlPosition == gbh_RP ); } ); break; } case driver_hint::trainbrakeapply: { - if( AIControllFlag ) { + if( aiControlled ) { // za radą yB ustawiamy pozycję 3 kranu (ruszanie kranem w innych miejscach powino zostać wyłączone) if( BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPB ) ); + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPB ) ); } else { BrakeCtrlPosition = 3; @@ -827,11 +836,11 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return IsConsistBraked /*|| ( ( OrderCurrentGet() & Disconnect ) == 0 ) */; } ); + return IsConsistBraked /*|| ( false == OrderCurrentGet().HasAny(DriverOrder::disconnect) ) */; } ); break; } case driver_hint::brakingforcedecrease: { - if( AIControllFlag ) { + if( aiControlled ) { auto const brakingcontrolschange { DecBrake() }; // set optional delay between brake adjustments if( brakingcontrolschange && Actionparameter > 0 ) { @@ -842,12 +851,12 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Fb) <= Parameter; }, - static_cast(std::min( 0.0, 0.95 * std::abs( mvControlling->Fb ) )) ); // keep hint until 5% decrease + return std::abs(mvControlling->Fb()) <= Parameter; }, + static_cast(std::min( 0.0, 0.95 * std::abs( mvControlling->Fb() ) )) ); // keep hint until 5% decrease break; } case driver_hint::brakingforceincrease: { - if( AIControllFlag ) { + if( aiControlled ) { auto const brakingcontrolschange { IncBrake() }; // set optional delay between brake adjustments if( brakingcontrolschange && Actionparameter > 0 ) { @@ -858,16 +867,16 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) { - return std::abs(mvControlling->Fb) > Parameter || is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_EB), 0.2); }, + return std::abs(mvControlling->Fb()) > Parameter || is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_EB), 0.2); }, static_cast(std::max( 0.0, std::max( - std::abs( mvControlling->Fb ) * 1.05, - std::abs( mvControlling->Fb ) + 5.0 ) )) ); + std::abs( mvControlling->Fb() ) * 1.05, + std::abs( mvControlling->Fb() ) + 5.0 ) )) ); break; } case driver_hint::brakingforcesetzero: { // releases both train and independent brake - if( AIControllFlag ) { + if( aiControlled ) { while( true == DecBrake() ) { // all work is done in the loop condition } @@ -876,11 +885,11 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return Ready && fReady < 0.4 && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2); } ); + return Ready && fReady < 0.4 && is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_RP), 0.2); } ); break; } case driver_hint::brakingforcelap: { - if( AIControllFlag ) { + if( aiControlled ) { LapBrake(); } remove_train_brake_hints(); @@ -890,58 +899,58 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) } // independent brake case driver_hint::independentbrakeapply: { - if (AIControllFlag && mvOccupied->LocalBrakePosA < 1.0) { - mvOccupied->IncLocalBrakeLevel( LocalBrakePosNo ); - if (mvOccupied->EIMCtrlEmergency) { - mvOccupied->DecLocalBrakeLevel(1); + if (aiControlled && occupied->brakes.IndependentPosition() < 1.0) { + occupied->IncLocalBrakeLevel( LocalBrakePosNo ); + if (occupied->EIMCtrlEmergency()) { + occupied->DecLocalBrakeLevel(1); } } remove_hint( driver_hint::independentbrakerelease ); hint( Action, [this](float const Parameter) { - return mvOccupied->LocalBrakePosA >= Parameter; }, - ( LocalBrakePosNo - ( mvOccupied->EIMCtrlEmergency ? 1 : 0 ) ) / LocalBrakePosNo ); + return occupied->brakes.IndependentPosition() >= Parameter; }, + ( LocalBrakePosNo - ( occupied->EIMCtrlEmergency() ? 1 : 0 ) ) / LocalBrakePosNo ); break; } case driver_hint::independentbrakerelease: { - if( AIControllFlag ) { + if( aiControlled ) { ZeroLocalBrake(); } remove_hint( driver_hint::independentbrakeapply ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->LocalBrakePosA < 0.05; } ); + return occupied->brakes.IndependentPosition() < 0.05; } ); break; } // reverser case driver_hint::directionforward: { - if( AIControllFlag ) { - OrderDirectionChange( 1, mvOccupied ); + if( aiControlled ) { + OrderDirectionChange( 1, occupied ); } remove_reverser_hints(); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->DirActive * mvOccupied->CabActive > 0; } ); + return occupied->DirActive * occupied->CabActive > 0; } ); break; } case driver_hint::directionbackward: { - if( AIControllFlag ) { - OrderDirectionChange( -1, mvOccupied ); + if( aiControlled ) { + OrderDirectionChange( -1, occupied ); } remove_reverser_hints(); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->DirActive * mvOccupied->CabActive < 0; } ); + return occupied->DirActive * occupied->CabActive < 0; } ); break; } case driver_hint::directionother: { - if( AIControllFlag ) { -// DirectionForward( mvOccupied->DirAbsolute < 0 ); - OrderDirectionChange( iDirectionOrder, mvOccupied ); + if( aiControlled ) { +// DirectionForward( occupied->DirAbsolute < 0 ); + OrderDirectionChange( iDirectionOrder, occupied ); DirectionChange(); } remove_reverser_hints(); @@ -952,65 +961,65 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) break; } case driver_hint::directionnone: { - if( AIControllFlag ) { + if( aiControlled ) { ZeroDirection(); } remove_reverser_hints(); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->DirActive == 0; } ); + return occupied->DirActive == 0; } ); break; } // anti-slip systems case driver_hint::sandingon: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->Sandbox( true ); } remove_hint( driver_hint::sandingoff ); hint( Action, [this](float const /*Parameter*/) { - return mvControlling->Sand == 0 || mvControlling->SandDose == true || mvControlling->SlippingWheels == false; } ); + return mvControlling->Sand == 0 || mvControlling->SandDose() == true || mvControlling->SlippingWheels() == false; } ); break; } case driver_hint::sandingoff: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->Sandbox( false ); } remove_hint( driver_hint::sandingon ); hint( Action, [this](float const /*Parameter*/) { - return mvControlling->Sand == 0 || mvControlling->SandDose == false; } ); + return mvControlling->Sand == 0 || mvControlling->SandDose() == false; } ); break; } case driver_hint::antislip: { - if( AIControllFlag ) { + if( aiControlled ) { mvControlling->AntiSlippingButton(); } hint( Action, [this](float const /*Parameter*/) { - return mvControlling->ASBType != 1 || (mvControlling->Hamulec->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels == false; } ); + return mvControlling->brakes.config.antiSlipType != 1 || (mvControlling->brakes.distributor->GetBrakeStatus() & b_asb) != 0 || mvControlling->SlippingWheels() == false; } ); break; } // horns case driver_hint::hornon: { - if( AIControllFlag ) { - mvOccupied->WarningSignal = static_cast( Actionparameter ); + if( aiControlled ) { + occupied->SetWarningSignal(static_cast( Actionparameter )); } remove_hint( driver_hint::hornoff ); hint( Action, [this](float const /*Parameter*/) { // NOTE: we provide slightly larger horn activation window for human driver - return fWarningDuration + 5.0 < 0.05 || mvOccupied->WarningSignal != 0; } ); + return fWarningDuration + 5.0 < 0.05 || occupied->WarningSignal() != 0; } ); break; } case driver_hint::hornoff: { - if( AIControllFlag ) { - mvOccupied->WarningSignal = 0; + if( aiControlled ) { + occupied->SetWarningSignal(0); } /* // NOTE: for human driver the hint to switch horn on will disappear automatically @@ -1018,234 +1027,257 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const Parameter) -> bool { - return ( mvOccupied->WarningSignal == 0 ); } ); + return ( occupied->WarningSignal() == 0 ); } ); */ break; } // door locks case driver_hint::consistdoorlockson: { - if( AIControllFlag ) { - mvOccupied->LockDoors( true ); + if( aiControlled ) { + occupied->LockDoors( true ); } // TODO: remove other door lock hints hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.has_lock == false || mvOccupied->Doors.lock_enabled == true; } ); + return occupied->Doors.has_lock == false || occupied->Doors.lock_enabled == true; } ); break; } // departure signal case driver_hint::departuresignalon: { - if( AIControllFlag ) { - mvOccupied->signal_departure( true ); + if( aiControlled ) { + occupied->signal_departure( true ); } remove_hint( driver_hint::departuresignaloff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == true || mvOccupied->Vel > 5.0; } ); + return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal() == true || occupied->Vel > 5.0; } ); break; } case driver_hint::departuresignaloff: { - if( AIControllFlag ) { - mvOccupied->signal_departure( false ); + if( aiControlled ) { + occupied->signal_departure( false ); } remove_hint( driver_hint::departuresignalon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->Doors.has_warning == false || mvOccupied->Doors.has_autowarning == true || mvOccupied->DepartureSignal == false; } ); + return occupied->Doors.has_warning == false || occupied->Doors.has_autowarning == true || occupied->DepartureSignal() == false; } ); break; } // consist doors case driver_hint::doorrightopen: { - if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::right, true ); + if( aiControlled + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::right, true ); } remove_hint( driver_hint::doorrightclose ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::right] == true; } ); + return IsAnyDoorOpen[VehicleSide::right] == true; } ); break; } case driver_hint::doorrightclose: { - if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::right, false ); + if( aiControlled + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::right, false ); } remove_hint( driver_hint::doorrightopen ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::right] == false; } ); + return IsAnyDoorOpen[VehicleSide::right] == false; } ); break; } case driver_hint::doorleftopen: { - if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::left, true ); + if( aiControlled + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::left, true ); } remove_hint( driver_hint::doorleftclose ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::left] == true; } ); + return IsAnyDoorOpen[VehicleSide::left] == true; } ); break; } case driver_hint::doorleftclose: { - if( AIControllFlag - || pVehicle->MoverParameters->Doors.open_control == control_t::conductor ) { - pVehicle->MoverParameters->OperateDoors( side::left, false ); + if( aiControlled + || pVehicle->physics->Doors.open_control == control_t::conductor ) { + pVehicle->physics->OperateDoors( VehicleSide::left, false ); } remove_hint( driver_hint::doorleftopen ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorOpen[side::left] == false; } ); + return IsAnyDoorOpen[VehicleSide::left] == false; } ); break; } case driver_hint::doorrightpermiton: { - if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::right, true ); + if( aiControlled ) { + pVehicle->physics->PermitDoors( VehicleSide::right, true ); } remove_hint( driver_hint::doorrightpermitoff ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::right] == true; } ); + return IsAnyDoorPermitActive[VehicleSide::right] == true; } ); break; } case driver_hint::doorrightpermitoff: { - if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::right, false ); + if( aiControlled ) { + pVehicle->physics->PermitDoors( VehicleSide::right, false ); } remove_hint( driver_hint::doorrightpermiton ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::right] == false; } ); + return IsAnyDoorPermitActive[VehicleSide::right] == false; } ); break; } case driver_hint::doorleftpermiton: { - if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::left, true ); + if( aiControlled ) { + pVehicle->physics->PermitDoors( VehicleSide::left, true ); } remove_hint( driver_hint::doorleftpermitoff ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::left] == true; } ); + return IsAnyDoorPermitActive[VehicleSide::left] == true; } ); break; } case driver_hint::doorleftpermitoff: { - if( AIControllFlag ) { - pVehicle->MoverParameters->PermitDoors( side::left, false ); + if( aiControlled ) { + pVehicle->physics->PermitDoors( VehicleSide::left, false ); } remove_hint( driver_hint::doorleftpermiton ); hint( Action, [this](float const /*Parameter*/) { - return IsAnyDoorPermitActive[side::left] == false; } ); + return IsAnyDoorPermitActive[VehicleSide::left] == false; } ); + break; + } + // doorsteps, as the timetable asks (eu07/maszyna#95) + case driver_hint::doorstepon: { + if( aiControlled ) { + occupied->PermitDoorStep( true ); + } + remove_hint( driver_hint::doorstepoff ); + hint( + Action, + [this](float const /*Parameter*/) { + return occupied->Doors.step_enabled == true; } ); + break; + } + case driver_hint::doorstepoff: { + if( aiControlled ) { + occupied->PermitDoorStep( false ); + } + remove_hint( driver_hint::doorstepon ); + hint( + Action, + [this](float const /*Parameter*/) { + return occupied->Doors.step_enabled == false; } ); break; } // consist lights case driver_hint::consistlightson: { - if( AIControllFlag ) { - mvOccupied->CompartmentLightsSwitch( true ); - mvOccupied->CompartmentLightsSwitchOff( false ); + if( aiControlled ) { + occupied->CompartmentLightsSwitch( true ); + occupied->CompartmentLightsSwitchOff( false ); } remove_hint( driver_hint::consistlightsoff ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->CompartmentLights }; + auto const &device { occupied->CompartmentLights }; return Global.fLuminance * ConsistShade > 0.40 || device.start_type != start_t::manual || (device.is_enabled == true && device.is_disabled == false) || device.is_active == true; } ); break; } case driver_hint::consistlightsoff: { - if( AIControllFlag ) { - mvOccupied->CompartmentLightsSwitch( false ); - mvOccupied->CompartmentLightsSwitchOff( true ); + if( aiControlled ) { + occupied->CompartmentLightsSwitch( false ); + occupied->CompartmentLightsSwitchOff( true ); } remove_hint( driver_hint::consistlightson ); hint( Action, [this](float const /*Parameter*/) { - auto const &device { mvOccupied->CompartmentLights }; + auto const &device { occupied->CompartmentLights }; return Global.fLuminance * ConsistShade < 0.35 || device.start_type != start_t::manual || (device.is_enabled == false && device.is_active == false); } ); break; } // consist heating case driver_hint::consistheatingon: { - if( AIControllFlag ) { - mvOccupied->HeatingSwitch( true ); + if( aiControlled ) { + occupied->HeatingSwitch( true ); } remove_hint( driver_hint::consistheatingoff ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->HeatingAllow == true; } ); + return occupied->trainHeating.IsAllowed() == true; } ); break; } case driver_hint::consistheatingoff: { - if( AIControllFlag ) { - mvOccupied->HeatingSwitch( false ); + if( aiControlled ) { + occupied->HeatingSwitch( false ); } remove_hint( driver_hint::consistheatingon ); hint( Action, [this](float const /*Parameter*/) { - return mvOccupied->HeatingAllow == false; } ); + return occupied->trainHeating.IsAllowed() == false; } ); break; } case driver_hint::securitysystemreset: { - if (AIControllFlag && mvOccupied->SecuritySystem.is_blinking()) - mvOccupied->SecuritySystemReset(); + if (aiControlled && occupied->SecuritySystem.is_blinking()) + occupied->SecuritySystemReset(); hint( Action, [this](float const /*Parameter*/) { - return !mvOccupied->SecuritySystem.is_vigilance_blinking(); } ); + return !occupied->SecuritySystem.is_vigilance_blinking(); } ); break; } case driver_hint::shpsystemreset: { - if (AIControllFlag && mvOccupied->SecuritySystem.is_cabsignal_blinking()) - mvOccupied->SecuritySystem.cabsignal_reset(); + if (aiControlled && occupied->SecuritySystem.is_cabsignal_blinking()) + occupied->SecuritySystem.cabsignal_reset(); hint( Action, [this](float const /*Parameter*/) { - return !mvOccupied->SecuritySystem.is_cabsignal_blinking(); } ); + return !occupied->SecuritySystem.is_cabsignal_blinking(); } ); break; } case driver_hint::couplingadapterattach: { // TODO: run also for potential settings-based virtual assistant - if( AIControllFlag ) { - pVehicles[ end::front ]->attach_coupler_adapter( static_cast(Actionparameter) ); + if( aiControlled ) { + pVehicles[ VehicleEnd::front ]->attach_coupler_adapter( EndOf( static_cast(Actionparameter) ) ); } hint( Action, [this](float const Parameter) { - auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; + auto const &device { pVehicles[ VehicleEnd::front ]->physics->Couplers[ static_cast( Parameter ) ] }; return device.type() == TCouplerType::Automatic; } ); break; } case driver_hint::couplingadapterremove: { - if( AIControllFlag || Global.AITrainman ) { - pVehicles[ end::front ]->remove_coupler_adapter( static_cast(Actionparameter) ); + if( aiControlled || Global.AITrainman ) { + pVehicles[ VehicleEnd::front ]->remove_coupler_adapter( EndOf( static_cast(Actionparameter) ) ); } hint( Action, [this](float const Parameter) { - auto const &device { pVehicles[ end::front ]->MoverParameters->Couplers[ static_cast( Parameter ) ] }; + auto const &device { pVehicles[ VehicleEnd::front ]->physics->Couplers[ static_cast( Parameter ) ] }; return false == device.has_adapter(); } ); break; } // lights case driver_hint::headcodepc1: { - if( AIControllFlag ) { - pVehicles[ end::front ]->RaLightsSet( light::headlight_left | light::headlight_right | light::headlight_upper, -1 ); + if( aiControlled ) { + pVehicles[ VehicleEnd::front ]->RaLightsSet( light::headlight_left | light::headlight_right | light::headlight_upper, -1 ); } remove_hint( driver_hint::headcodepc2 ); remove_hint( driver_hint::headcodetb1 ); @@ -1253,12 +1285,12 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pVehicles[end::front]->has_signal_pc1_on(); } ); + return pVehicles[VehicleEnd::front]->has_signal_pc1_on(); } ); break; } case driver_hint::headcodepc2: { - if( AIControllFlag ) { - pVehicles[ end::front ]->RaLightsSet( light::redmarker_left | light::headlight_right | light::headlight_upper, -1 ); + if( aiControlled ) { + pVehicles[ VehicleEnd::front ]->RaLightsSet( light::redmarker_left | light::headlight_right | light::headlight_upper, -1 ); } remove_hint( driver_hint::headcodepc1 ); remove_hint( driver_hint::headcodetb1 ); @@ -1266,14 +1298,14 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - return pVehicles[end::front]->has_signal_pc2_on(); } ); + return pVehicles[VehicleEnd::front]->has_signal_pc2_on(); } ); break; } case driver_hint::headcodetb1: { // HACK: the 'front' and 'rear' of the consist is determined by current consist direction // since direction shouldn't affect Tb1 light configuration, we 'counter' this behaviour by virtually swapping end vehicles - if( AIControllFlag ) { - if( mvOccupied->DirActive >= 0 ) { Lights( light::headlight_right, light::headlight_left ); } + if( aiControlled ) { + if( occupied->DirActive >= 0 ) { Lights( light::headlight_right, light::headlight_left ); } else { Lights( light::headlight_left, light::headlight_right ); } } remove_hint( driver_hint::headcodepc1 ); @@ -1283,26 +1315,26 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - auto const activeend { mvOccupied->CabActive >= 0 ? end::front : end::rear }; - auto const consistfront { mvOccupied->DirActive >= 0 ? end::front : end::rear }; - return pVehicles[consistfront]->has_signal_on(activeend, light::headlight_right) && pVehicles[1 - consistfront]->has_signal_on(1 - activeend, light::headlight_left); } ); + auto const activeend { occupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const consistfront { occupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + return pVehicles[consistfront]->has_signal_on(activeend, light::headlight_right) && pVehicles[Opposite(consistfront)]->has_signal_on(Opposite(activeend), light::headlight_left); } ); break; } case driver_hint::headcodepc5: { - if( AIControllFlag - || ( Global.AITrainman && false == pVehicles[end::rear]->is_connected(pVehicle, coupling::control) ) ) { - pVehicles[ end::rear ]->RaLightsSet( -1, light::redmarker_left | light::redmarker_right | light::rearendsignals ); + if( aiControlled + || ( Global.AITrainman && false == pVehicles[VehicleEnd::rear]->is_connected(pVehicle, Coupling::control) ) ) { + pVehicles[ VehicleEnd::rear ]->RaLightsSet( -1, light::redmarker_left | light::redmarker_right | light::rearendsignals ); } remove_hint( driver_hint::headcodetb1 ); remove_hint( driver_hint::lightsoff ); hint( Action, [this](float const /*Parameter*/) { - return pVehicles[end::rear]->has_signal_pc5_on(); } ); + return pVehicles[VehicleEnd::rear]->has_signal_pc5_on(); } ); break; } case driver_hint::lightsoff: { - if( AIControllFlag ) { + if( aiControlled ) { Lights( 0, 0 ); } remove_hint( driver_hint::headcodepc1 ); @@ -1312,32 +1344,32 @@ TController::cue_action( driver_hint const Action, float const Actionparameter ) hint( Action, [this](float const /*Parameter*/) { - auto const activeend { mvOccupied->CabActive >= 0 ? end::front : end::rear }; - auto const consistfront { mvOccupied->DirActive >= 0 ? end::front : end::rear }; - return pVehicles[consistfront]->has_signal_on(activeend, 0) && pVehicles[1 - consistfront]->has_signal_on(1 - activeend, 0); } ); + auto const activeend { occupied->CabActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const consistfront { occupied->DirActive >= 0 ? VehicleEnd::front : VehicleEnd::rear }; + return pVehicles[consistfront]->has_signal_on(activeend, 0) && pVehicles[Opposite(consistfront)]->has_signal_on(Opposite(activeend), 0); } ); break; } // releaser case driver_hint::releaseron: { - if( AIControllFlag ) { - mvOccupied->BrakeReleaser( 1 ); + if( aiControlled ) { + occupied->BrakeReleaser( 1 ); } remove_hint( driver_hint::releaseroff ); hint( Action, [this](float const /*Parameter*/) { - return true == mvOccupied->Hamulec->Releaser(); } ); + return true == occupied->brakes.distributor->Releaser(); } ); break; } case driver_hint::releaseroff: { - if( AIControllFlag ) { - mvOccupied->BrakeReleaser( 0 ); + if( aiControlled ) { + occupied->BrakeReleaser( 0 ); } remove_hint( driver_hint::releaseron ); hint( Action, [this](float const /*Parameter*/) { - return false == mvOccupied->Hamulec->Releaser(); } ); + return false == occupied->brakes.distributor->Releaser(); } ); break; } diff --git a/application/driverhints_def.h b/application/driverhints_def.h index 2ce896679..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")) @@ -72,6 +73,8 @@ DRIVER_HINT_DEF(doorrightpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorrightpermitoff, STRN("Revoke permit to open doors")) DRIVER_HINT_DEF(doorleftpermiton, STRN("Grant permit to open doors")) DRIVER_HINT_DEF(doorleftpermitoff, STRN("Revoke permit to open doors")) +DRIVER_HINT_DEF(doorstepon, STRN("Switch on doorsteps")) +DRIVER_HINT_DEF(doorstepoff, STRN("Switch off doorsteps")) DRIVER_HINT_DEF(hornon, STRN("Sound the horn")) DRIVER_HINT_DEF(hornoff, STRN("Switch off horn")) DRIVER_HINT_DEF(consistlightson, STRN("Switch on consist lights")) diff --git a/application/drivermode.cpp b/application/drivermode.cpp index aeb4a5635..99c3ff31e 100644 --- a/application/drivermode.cpp +++ b/application/drivermode.cpp @@ -27,10 +27,12 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "model/Model3d.h" #include "world/Event.h" +#include "world/deer.h" #include "input/messaging.h" #include "utilities/Timer.h" #include "rendering/renderer.h" #include "utilities/Logs.h" +#include "physics/vehicle.h" #include @@ -346,6 +348,7 @@ bool driver_mode::update() Timer::subsystem.sim_lights.start(); simulation::Lights.update(); Timer::subsystem.sim_lights.stop(); + simulation::Deer.update(deltatime); { // where the user looks from, for the black box auto const &camera{DebugCameraFlag ? DebugCamera : Camera}; @@ -681,7 +684,7 @@ void driver_mode::update_camera(double const Deltatime) if (controlled && glm::length2(controlled->GetPosition() - Camera.Pos) < sq(1500)) // length2 is better than length for comparing because it does not require sqrt function { // gdy bliżej niż 1.5km - Camera.LookAt = controlled->GetPosition() + 0.4 * controlled->VectorUp() * controlled->MoverParameters->Dim.H; + Camera.LookAt = controlled->GetPosition() + 0.4 * controlled->VectorUp() * controlled->physics->Dim.H; } else { @@ -701,7 +704,7 @@ void driver_mode::update_camera(double const Deltatime) if (d) pDynamicNearest = d; // zmiana na nowy, jeśli coś znaleziony niepusty if (pDynamicNearest) - Camera.LookAt = pDynamicNearest->GetPosition() + 0.4 * pDynamicNearest->VectorUp() * pDynamicNearest->MoverParameters->Dim.H; + Camera.LookAt = pDynamicNearest->GetPosition() + 0.4 * pDynamicNearest->VectorUp() * pDynamicNearest->physics->Dim.H; } Camera.RaLook(); // jednorazowe przestawienie kamery } @@ -777,11 +780,16 @@ void driver_mode::update_camera(double const Deltatime) // reset window state, it'll be set again if applicable in a check below Global.CabWindowOpen = false; - if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) + if (consist_view_active()) + { + // the orbit, shunting, coupling and trackside views place the camera themselves + update_consist_view(Deltatime); + } + else if (simulation::Train != nullptr && controlled != nullptr && Camera.m_owner != nullptr && false == DebugCameraFlag) { // jeśli jazda w kabinie, przeliczyć trzeba parametry kamery /* - auto tempangle = controlled->VectorFront() * ( controlled->MoverParameters->CabOccupied == -1 ? -1 : 1 ); + auto tempangle = controlled->VectorFront() * ( controlled->physics->CabOccupied() == -1 ? -1 : 1 ); double modelrotate = atan2( -tempangle.x, tempangle.z ); */ if (false == FreeFlyModeFlag && true == Global.ctrlState && (m_input.keyboard.key(GLFW_KEY_LEFT) != GLFW_RELEASE || m_input.keyboard.key(GLFW_KEY_RIGHT) != GLFW_RELEASE)) @@ -793,7 +801,7 @@ void driver_mode::update_camera(double const Deltatime) // Camera.Yaw powinno być wyzerowane, aby po powrocie patrzeć do przodu Camera.Pos = controlled->GetPosition() + simulation::Train->MirrorPosition(lr); // pozycja lusterka // NOSONAR Camera.Angle.y = 0; // odchylenie na bok od Camera.LookAt - if (simulation::Train->Occupied()->CabOccupied == 0) + if (simulation::Train->Occupied()->CabOccupied() == 0) { // gdy w korytarzu Camera.LookAt = Camera.Pos - simulation::Train->GetDirection(); @@ -801,12 +809,12 @@ void driver_mode::update_camera(double const Deltatime) else if (Global.shiftState) { // patrzenie w bok przez szybę - Camera.LookAt = Camera.Pos - (lr ? -1.0 : 1.0) * controlled->VectorLeft() * (double)simulation::Train->Occupied()->CabOccupied; + Camera.LookAt = Camera.Pos - (lr ? -1.0 : 1.0) * controlled->VectorLeft() * (double)simulation::Train->Occupied()->CabOccupied(); } else { // patrzenie w kierunku osi pojazdu, z uwzględnieniem kabiny - jakby z lusterka, // ale bez odbicia - Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 + Camera.LookAt = Camera.Pos - simulation::Train->GetDirection() * (double)simulation::Train->Occupied()->CabOccupied(); //-1 albo 1 } auto const *dynamic{simulation::Train->Dynamic()}; auto const shakeangles{dynamic->shake_angles(dynamic->shake_between(shake_fraction()))}; @@ -861,7 +869,7 @@ void driver_mode::update_camera(double const Deltatime) Controlled->ABuSetModelShake( temp ); // ABu: koniec rzucania */ - if (simulation::Train->Occupied()->CabOccupied == 0) + if (simulation::Train->Occupied()->CabOccupied() == 0) { // gdy w korytarzu Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0; @@ -869,7 +877,7 @@ void driver_mode::update_camera(double const Deltatime) else { // patrzenie w kierunku osi pojazdu, z uwzględnieniem kabiny - Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)simulation::Train->Occupied()->CabOccupied; //-1 albo 1 + Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)simulation::Train->Occupied()->CabOccupied(); //-1 albo 1 } Camera.vUp = simulation::Train->GetUp(); } @@ -1142,6 +1150,17 @@ void driver_mode::OnKeyDown(int cKey) } break; } + case GLFW_KEY_LEFT_BRACKET: + case GLFW_KEY_RIGHT_BRACKET: + { + // in the orbit, shunting, coupling and trackside views: the vehicle (coupling) towards the front, or the rear, + // of the train. [Ctrl] with them moves the train in the debug mode, bound in the keyboard settings + if (false == Global.ctrlState && consist_view_active()) + { + m_consistviews.select(cKey == GLFW_KEY_LEFT_BRACKET ? -1 : 1); + } + break; + } default: { break; @@ -1151,6 +1170,18 @@ void driver_mode::OnKeyDown(int cKey) return; // nie są przekazywane do pojazdu wcale } +bool driver_mode::consist_view_active() const +{ + return FreeFlyModeFlag && m_externalview && m_externalviewmode >= view::orbit && Camera.m_owner != nullptr && false == DebugCameraFlag; +} + +void driver_mode::update_consist_view(double const Deltatime) +{ + auto *controlled{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + // the camera goes with the vehicle picked, or stays where it is once the train is gone + Camera.m_owner = m_consistviews.update(Camera, controlled, Deltatime); +} + // places camera outside the controlled vehicle, or nearest if nothing is under control // depending on provided switch the view is placed right outside, or at medium distance void driver_mode::DistantView(bool const Near) @@ -1163,7 +1194,7 @@ void driver_mode::DistantView(bool const Near) return; } - auto const cab = vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied; + auto const cab = vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied(); auto const left = vehicle->VectorLeft() * (double)cab; if (true == Near) @@ -1174,7 +1205,7 @@ void driver_mode::DistantView(bool const Near) else { - Camera.Pos = vehicle->GetPosition() + vehicle->VectorFront() * (double)vehicle->MoverParameters->CabOccupied * 50.0 + glm::dvec3(-10.0 * left.x, 1.6, -10.0 * left.z); + Camera.Pos = vehicle->GetPosition() + vehicle->VectorFront() * (double)vehicle->physics->CabOccupied() * 50.0 + glm::dvec3(-10.0 * left.x, 1.6, -10.0 * left.z); } Camera.m_owner = nullptr; @@ -1199,7 +1230,8 @@ void driver_mode::ExternalView() if (true == m_externalview) { // we're already in some external view mode, so select next one on the list - m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(view::count_)); + // the views of the train's vehicles come after the four older ones, unless they're turned off in eu07.ini + m_externalviewmode = clamp_circular(++m_externalviewmode, static_cast(Global.ConsistViews ? view::count_ : view::orbit)); } FreeFlyModeFlag = true; @@ -1212,7 +1244,7 @@ void driver_mode::ExternalView() case view::consistfront: { // bind camera with the vehicle - auto *owner{vehicle->Mechanik->Vehicle(end::front)}; + auto *owner{vehicle->Mechanik->Vehicle(VehicleEnd::front)}; Camera.m_owner = owner; @@ -1226,12 +1258,12 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied) * - (vehicle->MoverParameters->DirActive == 0 ? 1 : vehicle->MoverParameters->DirActive)}; + auto const offsetflip{(vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied()) * + (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive)}; - Camera.m_owneroffset = {1.5 * owner->MoverParameters->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->MoverParameters->Dim.H), -0.4 * owner->MoverParameters->Dim.L * offsetflip}; + Camera.m_owneroffset = {1.5 * owner->physics->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->physics->Dim.H), -0.4 * owner->physics->Dim.L * offsetflip}; - Camera.Angle.y = glm::radians(vehicle->MoverParameters->DirActive < 0 ? 180.0 : 0.0); + Camera.Angle.y = glm::radians(vehicle->physics->DirActive < 0 ? 180.0 : 0.0); } auto const shakeangles{owner->shake_angles()}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl @@ -1242,7 +1274,7 @@ void driver_mode::ExternalView() case view::consistrear: { // bind camera with the vehicle - auto *owner{vehicle->Mechanik->Vehicle(end::rear)}; + auto *owner{vehicle->Mechanik->Vehicle(VehicleEnd::rear)}; Camera.m_owner = owner; @@ -1256,12 +1288,12 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied) * - (vehicle->MoverParameters->DirActive == 0 ? 1 : vehicle->MoverParameters->DirActive) * -1}; + auto const offsetflip{(vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied()) * + (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive) * -1}; - Camera.m_owneroffset = {1.5 * owner->MoverParameters->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->MoverParameters->Dim.H), 0.2 * owner->MoverParameters->Dim.L * offsetflip}; + Camera.m_owneroffset = {1.5 * owner->physics->Dim.W * offsetflip, std::max(5.0, 1.25 * owner->physics->Dim.H), 0.2 * owner->physics->Dim.L * offsetflip}; - Camera.Angle.y = glm::radians(vehicle->MoverParameters->DirActive < 0 ? 0.0 : 180.0); + Camera.Angle.y = glm::radians(vehicle->physics->DirActive < 0 ? 0.0 : 180.0); } auto const shakeangles{owner->shake_angles()}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl @@ -1270,7 +1302,7 @@ void driver_mode::ExternalView() } case view::bogie: { - auto *owner{vehicle->Mechanik->Vehicle(end::front)}; + auto *owner{vehicle->Mechanik->Vehicle(VehicleEnd::front)}; Camera.m_owner = owner; @@ -1284,12 +1316,12 @@ void driver_mode::ExternalView() else { // default view setup - auto const offsetflip{(vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied) * - (vehicle->MoverParameters->DirActive == 0 ? 1 : vehicle->MoverParameters->DirActive)}; + auto const offsetflip{(vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied()) * + (vehicle->physics->DirActive == 0 ? 1 : vehicle->physics->DirActive)}; - Camera.m_owneroffset = {-0.65 * owner->MoverParameters->Dim.W * offsetflip, 0.90, 0.15 * owner->MoverParameters->Dim.L * offsetflip}; + Camera.m_owneroffset = {-0.65 * owner->physics->Dim.W * offsetflip, 0.90, 0.15 * owner->physics->Dim.L * offsetflip}; - Camera.Angle.y = glm::radians(vehicle->MoverParameters->DirActive < 0 ? 180.0 : 0.0); + Camera.Angle.y = glm::radians(vehicle->physics->DirActive < 0 ? 180.0 : 0.0); } auto const shakeangles{owner->shake_angles()}; Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl @@ -1302,6 +1334,17 @@ void driver_mode::ExternalView() DistantView(false); break; } + case view::orbit: + case view::shunting: + case view::coupling: + case view::trackside: + { + // the camera goes with a vehicle of the train, placed by update_consist_view() from the next frame on + auto const kind{static_cast(m_externalviewmode - view::orbit)}; + Camera.m_owner = m_consistviews.enter(kind, vehicle); + Camera.m_owneroffset = {}; + break; + } default: { break; @@ -1341,14 +1384,14 @@ void driver_mode::CabView() Camera.Angle.x -= 0.5 * shakeangles.second; // hustanie kamery przod tyl Camera.Angle.z = shakeangles.first; // hustanie kamery na boki - if (train->Occupied()->CabOccupied == 0) + if (train->Occupied()->CabOccupied() == 0) { Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0; } else { // patrz w strone wlasciwej kabiny - Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)Camera.m_owner->MoverParameters->CabOccupied; + Camera.LookAt = Camera.m_owner->GetWorldPosition(Camera.m_owneroffset) + Camera.m_owner->VectorFront() * 5.0 * (double)Camera.m_owner->physics->CabOccupied(); } train->pMechOffset = Camera.m_owneroffset; } diff --git a/application/drivermode.h b/application/drivermode.h index 06ce32ee4..7e5b48573 100644 --- a/application/drivermode.h +++ b/application/drivermode.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "input/gamepadinput.h" #include "Console.h" #include "vehicle/Camera.h" +#include "application/consistviews.h" #include "utilities/Classes.h" #ifdef WITH_UART #include "utilities/uart.h" @@ -55,6 +56,11 @@ private: consistrear, bogie, driveby, + // the views of consist_views (eu07/maszyna#551), left out of the cycle with consistviews off in eu07.ini + orbit, + shunting, + coupling, + trackside, count_ }; @@ -98,6 +104,10 @@ private: void CabView(); void ExternalView(); void DistantView( bool const Near = false ); + // whether the camera shows one of the views of consist_views now + bool consist_view_active() const; + // places the camera of the view of consist_views for the frame + void update_consist_view( double const Deltatime ); void set_picking( bool const Picking ); // members @@ -108,6 +118,7 @@ private: int m_externalviewmode { view::consistfront }; // selected external view mode bool m_externalview { true }; std::array m_externalviewconfigs; + consist_views m_consistviews; // the orbit, shunting, coupling and trackside views TDynamicObject *pDynamicNearest { nullptr }; // vehicle nearest to the active camera. TODO: move to camera double fTime50Hz { 0.0 }; // bufor czasu dla komunikacji z PoKeys double const m_primaryupdaterate { 1.0 / 100.0 }; diff --git a/application/driveruipanels.cpp b/application/driveruipanels.cpp index 91fb2ff62..ede3f887e 100644 --- a/application/driveruipanels.cpp +++ b/application/driveruipanels.cpp @@ -23,8 +23,10 @@ http://mozilla.org/MPL/2.0/. #include "world/catenary_span.h" #include "vehicle/Camera.h" #include "world/mtable.h" +#include "world/stationnames.h" #include "vehicle/Train.h" #include "vehicle/Driver.h" +#include "vehicle/drivingaid.h" #include "model/AnimModel.h" #include "vehicle/DynObj.h" #include "model/Model3d.h" @@ -32,6 +34,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "widgets/vehicleparams.h" #include "utilities/U8.h" +#include "physics/vehicle.h" #define DRIVER_HINT_CONTENT #include "application/driverhints.h" @@ -41,6 +44,10 @@ http://mozilla.org/MPL/2.0/. #endif #include +#include +#include + +#include "audio/audiorenderer.h" namespace { @@ -48,13 +55,13 @@ namespace { constexpr float coupler_repair_radius { 5.f }; // the broken coupler nearest to the camera, within reach: the vehicle and its end, or no vehicle -std::pair broken_coupler_nearby( glm::dvec3 const &Camera ) { +std::pair broken_coupler_nearby( glm::dvec3 const &Camera ) { auto const *vehicle { std::get( simulation::Region->find_vehicle( Camera, coupler_repair_radius, false, true ) ) }; - if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { return { nullptr, end::front }; } - auto const front { glm::distance( vehicle->CouplerPosition( end::front ), Camera ) }; - auto const rear { glm::distance( vehicle->CouplerPosition( end::rear ), Camera ) }; - auto const nearest { front <= rear ? end::front : end::rear }; - if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->MoverParameters->Couplers[ nearest ].broken ) { return { nullptr, end::front }; } + if( vehicle == nullptr || vehicle->physics == nullptr ) { return { nullptr, VehicleEnd::front }; } + auto const front { glm::distance( vehicle->CouplerPosition( VehicleEnd::front ), Camera ) }; + auto const rear { glm::distance( vehicle->CouplerPosition( VehicleEnd::rear ), Camera ) }; + auto const nearest { front <= rear ? VehicleEnd::front : VehicleEnd::rear }; + if( std::min( front, rear ) > coupler_repair_radius || false == vehicle->physics->Couplers[ nearest ].broken ) { return { nullptr, VehicleEnd::front }; } return { vehicle, nearest }; } @@ -75,16 +82,23 @@ drivingaid_panel::update() { if( controlled == nullptr || controlled->Mechanik == nullptr ) { return; } - auto const *mover = controlled->MoverParameters; + auto const *physics = controlled->physics; auto const *vehicledriver = controlled->Mechanik; auto const *owner = controlled->ctOwner != nullptr ? controlled->ctOwner : controlled->Mechanik; + // the numbers of the throttle and brakes lines, with the controls of the cab the driver is in + auto const readout { drivingaid::compute( drivingaid::from_vehicles( + *physics, + *vehicledriver->Controlling(), + drivingaid::cab_controls { + train->ggLocalBrake.SubModel != nullptr, + train->ggJointCtrl.SubModel != nullptr } ) ) }; { // throttle, velocity, speed limits and grade std::string expandedtext; if( is_expanded ) { // grade std::string gradetext; - auto const reverser { ( mover->DirActive > 0 ? 1 : -1 ) }; + auto const reverser { ( physics->DirActive > 0 ? 1 : -1 ) }; if( auto const grade { controlled->VectorFront().y * 100 * ( controlled->DirectionGet() == reverser ? 1 : -1 ) * reverser }; std::abs( grade ) >= 0.25 ) { std::snprintf( m_buffer.data(), m_buffer.size(), @@ -108,7 +122,7 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C(" Speed: %d km/h (limit %d km/h%s)%s"), - static_cast( std::floor( mover->Vel ) ), + static_cast( std::floor( physics->Vel ) ), speedlimit, nextspeedlimittext.c_str(), gradetext.c_str() ); @@ -118,11 +132,11 @@ drivingaid_panel::update() { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Throttle: %3d+%d %c%s"), - mover->EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * mover->eimic_real)) : vehicledriver->Controlling()->MainCtrlPos, - mover->EIMCtrlType > 0 ? vehicledriver->Controlling()->MainCtrlPos : vehicledriver->Controlling()->ScndCtrlPos, - mover->SpeedCtrlUnit.IsActive ? 'T' : - mover->DirActive > 0 ? 'D' : - mover->DirActive < 0 ? 'R' : + readout.throttle_first, + readout.throttle_second, + physics->SpeedCtrlUnit.IsActive ? 'T' : + physics->DirActive > 0 ? 'D' : + physics->DirActive < 0 ? 'R' : 'N', expandedtext.c_str()); @@ -135,20 +149,36 @@ drivingaid_panel::update() { std::snprintf ( m_buffer.data(), m_buffer.size(), STR_C(" Pressure: %.2f kPa (train pipe: %.2f kPa)"), - mover->BrakePress * 100, - mover->PipePress * 100 ); + physics->brakes.cylinderPressure * 100, + physics->brakePipe.Pressure() * 100 ); expandedtext = m_buffer.data(); } - auto const basicbraking { mover->fBrakeCtrlPos }; - auto const eimicbraking { std::max( 0.0, -100.0 * mover->eimic_real ) }; - std::snprintf( - m_buffer.data(), m_buffer.size(), - STR_C("Brakes: %5.1f+%-2.0f%c%s"), -// ( mover->EIMCtrlType == 0 ? basicbraking : mover->EIMCtrlType == 3 ? ( mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking ) : eimicbraking ), - mover->UniCtrlIntegratedBrakeCtrl ? eimicbraking : basicbraking, - mover->LocalBrakePosA * LocalBrakePosNo, - mover->SlippingWheels ? '!' : ' ', - expandedtext.c_str() ); + if( readout.ed_percent ) { + // the ED braking demand, ahead of the expanded data (eu07/maszyna#558) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C(" ED brake: %d%%%%"), + *readout.ed_percent ); + expandedtext.insert( 0, m_buffer.data() ); + } + if( readout.show_local_brake ) { + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f+%-2.0f%c%s"), + readout.brake_first, + readout.local_brake, + physics->SlippingWheels() ? '!' : ' ', + expandedtext.c_str() ); + } + else { + // the cab has no local brake control: its setting is left out (eu07/maszyna#555) + std::snprintf( + m_buffer.data(), m_buffer.size(), + STR_C("Brakes: %5.1f%c%s"), + readout.brake_first, + physics->SlippingWheels() ? '!' : ' ', + expandedtext.c_str() ); + } text_lines.emplace_back( m_buffer.data(), Global.UITextColor ); } @@ -176,9 +206,9 @@ drivingaid_panel::update() { } } std::string textline = - mover->SecuritySystem.is_vigilance_blinking() && (train != nullptr ? train->fBlinkTimer > 0 : true) ? STR("!ALERTER! ") : " "; + physics->SecuritySystem.is_vigilance_blinking() && (train != nullptr ? train->fBlinkTimer > 0 : true) ? STR("!ALERTER! ") : " "; textline += - mover->SecuritySystem.is_cabsignal_blinking() ? STR("!SHP!") : " "; + physics->SecuritySystem.is_cabsignal_blinking() ? STR("!SHP!") : " "; text_lines.emplace_back( textline + " " + expandedtext, Global.UITextColor ); } @@ -192,7 +222,7 @@ drivingaid_panel::render_contents() { auto const *driver = (simulation::Train && simulation::Train->Dynamic()) ? simulation::Train->Dynamic()->Mechanik : nullptr; if (driver && (false == Global.RealisticControlMode || DebugModeFlag)) { - bool autopilot = driver->AIControllFlag; + bool autopilot = driver->AIControllFlag(); if (ImGui::Checkbox(STR_C("autopilot"), &autopilot)) { command_relay commandrelay; commandrelay.post(autopilot ? user_command::aidriverenable : user_command::aidriverdisable, 0.0, 0.0, GLFW_PRESS, 0); @@ -202,7 +232,7 @@ drivingaid_panel::render_contents() { // only the coupler the camera is next to, and the one of the vehicle it was coupled with if( m_brokenvehicle != nullptr && ImGui::Button( STR_C( "Repair coupler" ) ) ) { command_relay commandrelay; - commandrelay.post( user_command::repaircoupler, m_brokenend, 0.0, GLFW_PRESS, 0, glm::vec3( 0.0f ), &m_brokenvehicle->name() ); + commandrelay.post( user_command::repaircoupler, NumberOf( m_brokenend ), 0.0, GLFW_PRESS, 0, glm::vec3( 0.0f ), &m_brokenvehicle->name() ); } ui_panel::render_contents(); @@ -328,9 +358,10 @@ timetable_panel::update() { // destination { - auto textline = Bezogonkow( owner->Relation(), true ); + // the names with the letters their files have, in utf-8 as the user interface takes it + auto textline = table.relation_caption(); if( false == textline.empty() ) { - textline += " (" + Bezogonkow( owner->TrainName(), true ) + ")"; + textline += " (" + data_name_to_utf8( owner->TrainName(), true ) + ")"; } text_lines.emplace_back( textline, Global.UITextColor ); } @@ -355,11 +386,11 @@ timetable_panel::update() { if( false == owner->is_dmu() && false == owner->is_emu() ) { //odejmij lokomotywy czynne, a przynajmniej aktualną - consistmass -= owner->pVehicle->MoverParameters->TotalMass; + consistmass -= owner->pVehicle->physics->TotalMass(); // subtract potential other half of a two-part vehicle - if( auto const *previous { owner->pVehicle->Prev( coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->MoverParameters->TotalMass; } - auto const *next { owner->pVehicle->Next( coupling::permanent ) }; - if( next != nullptr ) { consistmass -= next->MoverParameters->TotalMass; } + if( auto const *previous { owner->pVehicle->Prev( Coupling::permanent ) }; previous != nullptr ) { consistmass -= previous->physics->TotalMass(); } + auto const *next { owner->pVehicle->Next( Coupling::permanent ) }; + if( next != nullptr ) { consistmass -= next->physics->TotalMass(); } } std::snprintf( m_buffer.data(), m_buffer.size(), @@ -397,10 +428,9 @@ timetable_panel::update() { vmax += to_string( tableline->vmax, 0 ); vmax = vmax.substr( vmax.size() - 3, 3 ); // z wyrównaniem do prawej } - auto const station { ( - Bezogonkow( tableline->StationName, true ) - + " " ) - .substr( 0, 34 ) }; + // the name as the timetable spells it; in utf-8 a letter can take more than one byte, the column is + // 34 characters wide + auto const station { utf8_fit( timetable::station_caption( tableline->StationLabel ), 34 ) }; auto const location { ( ( tableline->km > 0.0 ? to_string( tableline->km, 2 ) : @@ -422,7 +452,7 @@ timetable_panel::update() { || tableline->is_maintenance // maintenance stop, always valid || time.wHour * 60 + time.wMinute + time.wSecond * 0.0167 >= static_cast(tableline->Dh * 60) + tableline->Dm ) ) }; auto const loadchangeinprogress { ( static_cast(std::ceil(-1.0 * owner->fStopTime)) > 0 ) }; - auto const isatpassengerstop { true == owner->IsAtPassengerStop && vehicle->MoverParameters->Vel < 1.0 }; + auto const isatpassengerstop { true == owner->IsAtPassengerStop && vehicle->physics->Vel < 1.0 }; auto const traveltime { ( i < 2 ? " " : tableline->Ah >= 0 ? to_minutes_str( static_cast(CompareTime( table.TimeTable[ i - 1 ].Dh, table.TimeTable[ i - 1 ].Dm, tableline->Ah, tableline->Am )), false, 3 ) : @@ -507,8 +537,8 @@ void debug_panel::update() m_input.vehicle = false == FreeFlyModeFlag ? m_input.controlled : m_input.camera->m_owner != nullptr ? m_input.camera->m_owner : std::get(simulation::Region->find_vehicle(m_input.camera->Pos, 20, false, false)); // w trybie latania lokalizujemy wg mapy - m_input.mover = - m_input.vehicle != nullptr ? m_input.vehicle->MoverParameters : nullptr; + m_input.physics = + m_input.vehicle != nullptr ? m_input.vehicle->physics : nullptr; m_input.mechanik = m_input.vehicle != nullptr ? m_input.vehicle->Mechanik : nullptr; // header section @@ -588,7 +618,7 @@ debug_panel::render() { } // sections ImGui::Separator(); - if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.mover && m_input.mover->DamageFlag != 0 && true == ImGui::Button( "Stop and repair consist" )) { + if (true == render_section( "Vehicle", m_vehiclelines ) && DebugModeFlag && m_input.physics && false == m_input.physics->DamageFlag.Empty() && true == ImGui::Button( "Stop and repair consist" )) { command_relay commandrelay; commandrelay.post(user_command::resetconsist, 0.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &m_input.vehicle->name()); } @@ -758,27 +788,27 @@ void debug_panel::update_section_vehicle( std::vector &Output ) { if( m_input.vehicle == nullptr ) { return; } - if( m_input.mover == nullptr ) { return; } + if( m_input.physics == nullptr ) { return; } auto const &vehicle { *m_input.vehicle }; - auto const &mover { *m_input.mover }; + auto const &physics { *m_input.physics }; auto const isowned { /* ( vehicle.Mechanik == nullptr ) && */ vehicle.ctOwner != nullptr && vehicle.ctOwner->Vehicle() != m_input.vehicle }; - auto const isdieselenginepowered { mover.EngineType == TEngineType::DieselElectric || mover.EngineType == TEngineType::DieselEngine }; - auto const isdieselinshuntmode { mover.ShuntMode && mover.EngineType == TEngineType::DieselElectric }; + auto const isdieselenginepowered { physics.EngineType == TEngineType::DieselElectric || physics.EngineType == TEngineType::DieselEngine }; + auto const isdieselinshuntmode { physics.ShuntMode && physics.EngineType == TEngineType::DieselElectric }; std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("Name: %s%s\nLoad: %.0f %s\nStatus: %s%s\nCouplers:\n front: %s\n rear: %s"), - mover.Name.c_str(), + physics.Name.c_str(), std::string( isowned ? STR(", owned by: ") + vehicle.ctOwner->OwnerName() : "" ).c_str(), - mover.LoadAmount, - mover.LoadType.name.c_str(), - mover.EngineDescription( 0 ).c_str(), + physics.LoadAmount(), + physics.LoadType.name.c_str(), + physics.EngineDescription( 0 ).c_str(), // TODO: put wheel flat reporting in the enginedescription() - std::string( mover.WheelFlat > 0.01 ? " Flat: " + to_string( mover.WheelFlat, 1 ) + " mm" : "" ).c_str(), - update_vehicle_coupler( end::front ).c_str(), - update_vehicle_coupler( end::rear ).c_str() ); + std::string( physics.WheelFlat() > 0.01 ? " Flat: " + to_string( physics.WheelFlat(), 1 ) + " mm" : "" ).c_str(), + update_vehicle_coupler( VehicleEnd::front ).c_str(), + update_vehicle_coupler( VehicleEnd::rear ).c_str() ); Output.emplace_back( std::string{ m_buffer.data() }, Global.UITextColor ); @@ -786,71 +816,71 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s[%.0f]%s%.0f@%.0f :: %.0f@%.0f%s[%.0f]%s%.0f@%.0f"), // devices - mover.Battery ? 'B' : '.', - mover.PantsValve.is_active ? '+' : '.', - mover.Pantographs[end::rear].valve.is_active ? 'O' : - mover.Pantographs[end::rear].valve.is_enabled ? 'o' : + physics.lowVoltage.IsBatteryOn() ? 'B' : '.', + physics.pantographAir.valve.is_active ? '+' : '.', + physics.pantographs[VehicleEnd::rear].valve.is_active ? 'O' : + physics.pantographs[VehicleEnd::rear].valve.is_enabled ? 'o' : '.', - mover.Pantographs[end::front].valve.is_active ? 'P' : - mover.Pantographs[end::front].valve.is_enabled ? 'p' : + physics.pantographs[VehicleEnd::front].valve.is_active ? 'P' : + physics.pantographs[VehicleEnd::front].valve.is_enabled ? 'p' : '.', - mover.PantPressLockActive ? '!' : - mover.PantPressSwitchActive ? '*' : + physics.pantographAir.IsPressureLockActive() ? '!' : + physics.pantographAir.IsPressureSwitchPrimed() ? '*' : '.', - mover.WaterPump.is_active ? 'W' : - false == mover.WaterPump.breaker ? '-' : - mover.WaterPump.is_enabled ? 'w' : + physics.WaterPump.is_active ? 'W' : + false == physics.WaterPump.breaker ? '-' : + physics.WaterPump.is_enabled ? 'w' : '.', - mover.WaterHeater.is_damaged ? '!' : - mover.WaterHeater.is_active ? 'H' : - false == mover.WaterHeater.breaker ? '-' : - mover.WaterHeater.is_enabled ? 'h' : + physics.WaterHeater.is_damaged ? '!' : + physics.WaterHeater.is_active ? 'H' : + false == physics.WaterHeater.breaker ? '-' : + physics.WaterHeater.is_enabled ? 'h' : '.', - mover.FuelPump.is_active ? 'F' : - mover.FuelPump.is_enabled ? 'f' : + physics.FuelPump.is_active ? 'F' : + physics.FuelPump.is_enabled ? 'f' : '.', - mover.OilPump.is_active ? 'O' : - mover.OilPump.is_enabled ? 'o' : + physics.OilPump.is_active ? 'O' : + physics.OilPump.is_enabled ? 'o' : '.', - mover.Mains ? 'M' : '.', - mover.FuseFlag ? '!' : '.', - mover.ConverterFlag ? 'X' : - false == mover.ConverterAllowLocal ? '-' : - mover.ConverterAllow ? 'x' : + physics.lineBreaker.IsClosed() ? 'M' : '.', + physics.FuseFlag ? '!' : '.', + physics.converter.IsRunning() ? 'X' : + false == physics.converter.LocalSwitchOn() ? '-' : + physics.converter.IsAllowed() ? 'x' : '.', - mover.ConvOvldFlag ? '!' : '.', - mover.CompressorFlag ? 'C' : - false == mover.CompressorAllowLocal ? '-' : - mover.CompressorAllow || (mover.CompressorStart == start_t::automatic && mover.CompressorSpeed > 0.0) ? 'c' : + physics.converter.IsOverloaded() ? '!' : '.', + physics.air.compressor.IsRunning() ? 'C' : + false == physics.air.compressor.LocalSwitchOn() ? '-' : + physics.air.compressor.IsAllowed() || (physics.air.compressor.config.start == start_t::automatic && physics.air.compressor.config.speed > 0.0) ? 'c' : '.', - mover.CompressorGovernorLock ? '!' : '.', - mover.StLinSwitchOff ? '-' : - mover.ControlPressureSwitch ? '!' : - mover.StLinFlag ? '+' : + physics.air.compressor.IsGovernorLocked() ? '!' : '.', + physics.lineContactors.IsForcedOpen() ? '-' : + physics.protection.PressureSwitchTripped() ? '!' : + physics.lineContactors.IsClosed() ? '+' : '.', - mover.Heating ? 'H' : - mover.HeatingAllow ? 'h' : + physics.trainHeating.IsOn() ? 'H' : + physics.trainHeating.IsAllowed() ? 'h' : '.', - mover.Hamulec->Releaser() ? '^' : '.', - std::string( m_input.mechanik ? STR(" R") + ( mover.Radio && mover.RadioFuse ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), - std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( mover.OilPump.pressure, 2 ) : "" ).c_str(), + physics.brakes.distributor->Releaser() ? '^' : '.', + std::string( m_input.mechanik ? STR(" R") + ( physics.Radio() && physics.RadioFuse() ? std::to_string( m_input.mechanik->iRadioChannel ) : "-" ) : "" ).c_str(), + std::string( isdieselenginepowered ? STR(" oil pressure: ") + to_string( physics.OilPump.pressure, 2 ) : "" ).c_str(), // power transfers // 3000v - mover.Couplers[ end::front ].power_high.voltage, - mover.Couplers[ end::front ].power_high.current, - std::string( mover.Couplers[ end::front ].power_high.is_local ? ":" : ":=" ).c_str(), - mover.EngineVoltage, - std::string( mover.Couplers[ end::rear ].power_high.is_local ? ":" : "=:" ).c_str(), - mover.Couplers[ end::rear ].power_high.voltage, - mover.Couplers[ end::rear ].power_high.current, + physics.Couplers[ VehicleEnd::front ].power_high.voltage, + physics.Couplers[ VehicleEnd::front ].power_high.current, + std::string( physics.Couplers[ VehicleEnd::front ].power_high.is_local ? ":" : ":=" ).c_str(), + physics.EngineVoltage, + std::string( physics.Couplers[ VehicleEnd::rear ].power_high.is_local ? ":" : "=:" ).c_str(), + physics.Couplers[ VehicleEnd::rear ].power_high.voltage, + physics.Couplers[ VehicleEnd::rear ].power_high.current, // 110v - mover.Couplers[ end::front ].power_110v.voltage, - mover.Couplers[ end::front ].power_110v.current, - std::string( mover.Couplers[ end::front ].power_110v.is_local ? ":" : ":=" ).c_str(), - mover.PowerCircuits[ 1 ].first, - std::string( mover.Couplers[ end::rear ].power_110v.is_local ? ":" : "=:" ).c_str(), - mover.Couplers[ end::rear ].power_110v.voltage, - mover.Couplers[ end::rear ].power_110v.current ); + physics.Couplers[ VehicleEnd::front ].power_110v.voltage, + physics.Couplers[ VehicleEnd::front ].power_110v.current, + std::string( physics.Couplers[ VehicleEnd::front ].power_110v.is_local ? ":" : ":=" ).c_str(), + physics.PowerCircuits[ 1 ].first, + std::string( physics.Couplers[ VehicleEnd::rear ].power_110v.is_local ? ":" : "=:" ).c_str(), + physics.Couplers[ VehicleEnd::rear ].power_110v.voltage, + physics.Couplers[ VehicleEnd::rear ].power_110v.current ); Output.emplace_back( m_buffer.data(), Global.UITextColor ); @@ -858,20 +888,20 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, cooling fans: %.0f+%.0f"), // controllers - mover.MainCtrlPos, - mover.MainCtrlActualPos, - std::string( isdieselinshuntmode ? to_string( mover.AnPos, 2 ) + STR(" (shunt mode)") : std::to_string( mover.ScndCtrlPos ) + "(" + std::to_string( mover.ScndCtrlActualPos ) + ")" ).c_str(), + physics.MainCtrlPos(), + physics.MainCtrlActualPos, + std::string( isdieselinshuntmode ? to_string( physics.AnPos(), 2 ) + STR(" (shunt mode)") : std::to_string( physics.ScndCtrlPos() ) + "(" + std::to_string( physics.ScndCtrlActualPos ) + ")" ).c_str(), // engine - mover.EnginePower, - std::abs( mover.TrainType == dt_EZT ? mover.ShowCurrent( 0 ) : mover.Im ), + physics.EnginePower, + std::abs( physics.TrainType() == train_type::emu ? physics.ShowCurrent( 0 ) : physics.Im ), // revolutions - std::abs( mover.enrot ) * 60, - std::abs( mover.nrot ) * mover.Transmision.Ratio * 60, - mover.RventRot * 60, - std::abs( mover.MotorBlowers[end::front].revolutions ), - std::abs( mover.MotorBlowers[end::rear].revolutions ), - mover.dizel_heat.rpmw, - mover.dizel_heat.rpmw2 ); + std::abs( physics.enrot ) * 60, + std::abs( physics.nrot() ) * physics.Transmision.Ratio * 60, + physics.RventRot * 60, + std::abs( physics.MotorBlowers[VehicleEnd::front].revolutions ), + std::abs( physics.MotorBlowers[VehicleEnd::rear].revolutions ), + physics.diesel.heat.rpmw, + physics.diesel.heat.rpmw2 ); std::string textline { m_buffer.data() }; @@ -879,11 +909,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), - mover.dizel_heat.Ts, - mover.dizel_heat.To, - mover.dizel_heat.temperatura1, - mover.WaterCircuitsLink ? '-' : '|', - mover.dizel_heat.temperatura2 ); + physics.diesel.heat.Ts, + physics.diesel.heat.To, + physics.diesel.heat.temperatura1, + physics.WaterCircuitsLink() ? '-' : '|', + physics.diesel.heat.temperatura2 ); textline += m_buffer.data(); } @@ -893,36 +923,36 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Brakes:\n train: %.2f (mode: %d, delay: %s, load flag: %d)\n independent: %.2f (%.2f), manual: %.2f, spring: %.2f\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - mover.fBrakeCtrlPos, - mover.BrakeOpModeFlag, + physics.brakes.HandlePositionSmooth(), + physics.brakes.operatingMode, update_vehicle_brake().c_str(), - mover.LoadFlag, - mover.LocalBrakePosA, - mover.LocalBrakePosAEIM, - static_cast(mover.ManualBrakePos) / static_cast(ManualBrakePosNo), - mover.SpringBrake.Activate ? 1.f : 0.f, + physics.brakes.loadSetting, + physics.brakes.IndependentPosition(), + physics.brakes.IndependentPositionEim(), + static_cast(physics.brakes.HandBrakePosition()) / static_cast(ManualBrakePosNo), + physics.brakes.spring.activate ? 1.f : 0.f, // cylinders - mover.BrakePress, - mover.LocBrakePress, - mover.Hamulec->GetBrakeStatus(), + physics.brakes.cylinderPressure, + physics.brakes.independentCylinderPressure, + physics.brakes.distributor->GetBrakeStatus(), // pipes - mover.PipePress, - mover.BrakeCtrlPos2, - mover.ScndPipePress, - mover.CntrlPipePress, + physics.brakePipe.Pressure(), + physics.brakes.HandleCapPosition(), + physics.mainPipe.Pressure(), + physics.brakes.controlReservoirPressure, // tanks - mover.Hamulec->GetBRP(), - mover.Compressor, - mover.Hamulec->GetCRP() ); + physics.brakes.distributor->GetBRP(), + physics.air.MainReservoirPressure(), + physics.brakes.distributor->GetCRP() ); textline = m_buffer.data(); - if( mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { + if( physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { std::snprintf( m_buffer.data(), m_buffer.size(), STR_C(" pantograph: %.2f%cMT"), - mover.PantPress, - mover.bPantKurek3 ? '-' : '|' ); + physics.pantographAir.Pressure(), + physics.pantographAir.IsConnectedToMainReservoir() ? '-' : '|' ); textline += m_buffer.data(); } @@ -932,17 +962,17 @@ debug_panel::update_section_vehicle( std::vector &Output ) { m_buffer.data(), m_buffer.size(), STR_C("Forces:\n tractive: %.1f, brake: %.1f, drag: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: [%.2f, %.2f, %.2f]"), // forces - mover.Ft * 0.001f * ( mover.CabOccupied ? mover.CabOccupied : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied : 1 ) + 0.001f, - mover.Fb * 0.001f, - mover.FrictionForce() * 0.001f, - mover.SlippingWheels ? " (!)" : "", + physics.Ft() * 0.001f * ( physics.CabOccupied() ? physics.CabOccupied() : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabOccupied() : 1 ) + 0.001f, + physics.Fb() * 0.001f, + physics.FrictionForce() * 0.001f, + physics.SlippingWheels() ? " (!)" : "", // acceleration - mover.AccSVBased, - mover.AccN + 0.001f, - std::string( std::abs( mover.RunningShape.R ) > 15000.0 ? "~0" : to_string( mover.RunningShape.R, 0 ) ).c_str(), + physics.AccSVBased(), + physics.AccN() + 0.001f, + std::string( std::abs( physics.RunningShape.R ) > 15000.0 ? "~0" : to_string( physics.RunningShape.R, 0 ) ).c_str(), // velocity vehicle.GetVelocity(), - mover.DistCounter, + physics.DistCounter(), // position vehicle.GetPosition().x, vehicle.GetPosition().y, @@ -950,9 +980,9 @@ debug_panel::update_section_vehicle( std::vector &Output ) { Output.emplace_back( m_buffer.data(), Global.UITextColor ); - if( mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { + if( physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { std::snprintf(m_buffer.data(), m_buffer.size(), STR_C("Power use:\n drawn: %.1f kWh\n returned: %.1f kWh\n balance: %.1f kWh"), - mover.EnergyMeter.first, -mover.EnergyMeter.second, mover.EnergyMeter.first + mover.EnergyMeter.second); + physics.EnergyMeter.first, -physics.EnergyMeter.second, physics.EnergyMeter.first + physics.EnergyMeter.second); textline = m_buffer.data(); if( DebugTractionFlag ) { for( int i = 0; i < vehicle.iAnimType[ ANIM_PANTS ]; ++i ) { // pętla po wszystkich pantografach @@ -977,11 +1007,11 @@ debug_panel::update_section_vehicle( std::vector &Output ) { if (!std::isnan(last_time)) { double dt = Timer::GetTime() - last_time; - AccN_jerk_graph.update(static_cast((mover.AccN - last_AccN) / dt)); - AccN_acc_graph.update(static_cast(mover.AccN)); + AccN_jerk_graph.update(static_cast((physics.AccN() - last_AccN) / dt)); + AccN_acc_graph.update(static_cast(physics.AccN())); } - last_AccN = static_cast(mover.AccN); + last_AccN = static_cast(physics.AccN()); last_time = Timer::GetTime(); } @@ -1003,15 +1033,15 @@ void debug_panel::graph_data::render() { } std::string -debug_panel::update_vehicle_coupler( int const Side ) { - // NOTE: mover and vehicle are guaranteed to be valid by the caller - auto const &mover { *m_input.mover }; +debug_panel::update_vehicle_coupler( VehicleEnd const Side ) { + // NOTE: physics and vehicle are guaranteed to be valid by the caller + auto const &physics { *m_input.physics }; - std::string const controltype{ ( mover.Couplers[ Side ].control_type.empty() ? "[*]" : "[" + mover.Couplers[ Side ].control_type + "]" ) }; + std::string const controltype{ ( physics.Couplers[ Side ].control_type.empty() ? "[*]" : "[" + physics.Couplers[ Side ].control_type + "]" ) }; std::string couplerstatus { STR("none") }; - std::string const adapterstatus { ( mover.Couplers[ Side ].adapter_type == TCouplerType::NoCoupler ? "" : "[A]" ) }; + std::string const adapterstatus { ( physics.Couplers[ Side ].adapter_type == TCouplerType::NoCoupler ? "" : "[A]" ) }; - auto const *connected { m_input.vehicle->MoverParameters->Neighbours[ Side ].vehicle }; + auto const *connected { m_input.vehicle->physics->Neighbours[ Side ].vehicle }; if( connected == nullptr ) { @@ -1024,16 +1054,16 @@ debug_panel::update_vehicle_coupler( int const Side ) { controltype.c_str(), connected->name().c_str(), adapterstatus.c_str(), - mover.Couplers[ Side ].CouplingFlag, - mover.Neighbours[ Side ].distance ); + physics.Couplers[ Side ].CouplingFlag.Bits(), + physics.Neighbours[ Side ].distance ); return { m_buffer.data() }; } std::string debug_panel::update_vehicle_brake() const { - // NOTE: mover is guaranteed to be valid by the caller - auto const &mover { *m_input.mover }; + // NOTE: physics is guaranteed to be valid by the caller + auto const &physics { *m_input.physics }; std::string brakedelay; @@ -1044,7 +1074,7 @@ debug_panel::update_vehicle_brake() const { { bdelay_M, "+Mg" } }; for( auto const &[delayflag, delayname] : delays ) { - if( ( mover.BrakeDelayFlag & delayflag ) == delayflag ) { + if( ( physics.brakes.delaySetting & delayflag ) == delayflag ) { brakedelay += delayname; } } @@ -1056,21 +1086,23 @@ void debug_panel::update_section_engine( std::vector &Output ) const { if( m_input.vehicle == nullptr ) { return; } - if( m_input.mover == nullptr ) { return; } + if( m_input.physics == nullptr ) { return; } auto const &vehicle{ *m_input.vehicle }; - auto const &mover{ *m_input.mover }; + auto const &physics{ *m_input.physics }; // induction motor data - if( mover.EngineType == TEngineType::ElectricInductionMotor ) { + if( physics.EngineType == TEngineType::ElectricInductionMotor ) { Output.emplace_back( " eimc: eimv: press:", Global.UITextColor ); + auto const config{ physics.inductionMotor.ConfigListing() }; + auto const state{ physics.inductionMotor.StateListing() }; for( int i = 0; i <= 20; ++i ) { std::string parameters = - TMoverParameters::eimc_labels[ i ] + to_string( mover.eimc[ i ], 2, 9 ) + std::string( config[ i ].first ) + to_string( config[ i ].second, 2, 9 ) + " | " - + TMoverParameters::eimv_labels[ i ] + to_string( mover.eimv[ i ], 2, 9 ); + + std::string( state[ i ].first ) + to_string( state[ i ].second, 2, 9 ); if( i < 10 ) { parameters += @@ -1080,34 +1112,34 @@ debug_panel::update_section_engine( std::vector &Output ) const { parameters += " med:"; } else if( i >= 13 ) { - parameters += " | " + TDynamicObject::MED_labels[ i - 13 ] + to_string( vehicle.MED[ 0 ][ i - 13 ], 2, 9 ); + parameters += " | " + std::string( physics::ConsistBrakeBlending::Labels[ i - 13 ] ) + to_string( vehicle.brakeBlending.Figures()[ i - 13 ], 2, 9 ); } Output.emplace_back( parameters, Global.UITextColor ); } - Output.emplace_back( "Inverter:\n frequency: " + to_string( mover.InverterFrequency, 2 ), Global.UITextColor ); + Output.emplace_back( "Inverter:\n frequency: " + to_string( physics.inductionMotor.inverterFrequency, 2 ), Global.UITextColor ); } // diesel engine data - if( mover.EngineType == TEngineType::DieselEngine ) { + if( physics.EngineType == TEngineType::DieselEngine ) { double fuel_mean = 0.0; - if (mover.DistCounter > 0.5) { - fuel_mean = 100 * mover.dizel_FuelConsumptedTotal / mover.DistCounter; + if (physics.DistCounter() > 0.5) { + fuel_mean = 100 * physics.diesel.fuelConsumedTotal / physics.DistCounter(); } std::string parameterstext = "param value"; std::vector< std::pair > const paramvalues { - { " rpm: ", mover.enrot * 60.0 }, - { "efill: ", mover.dizel_fill }, - { "etorq: ", mover.dizel_Torque }, - { "power: ", mover.dizel_Power }, - { "f_act: ", mover.dizel_FuelConsumptionActual }, - { "f_tot: ", mover.dizel_FuelConsumptedTotal }, + { " rpm: ", physics.enrot * 60.0 }, + { "efill: ", physics.diesel.fill }, + { "etorq: ", physics.diesel.torque }, + { "power: ", physics.diesel.power }, + { "f_act: ", physics.diesel.fuelConsumptionActual }, + { "f_tot: ", physics.diesel.fuelConsumedTotal }, { "fmean: ", fuel_mean }, - { "creal: ", mover.dizel_engage }, - { "cdesi: ", mover.dizel_engagestate }, - { "cdelt: ", mover.dizel_engagedeltaomega }, - { "gears: ", mover.dizel_automaticgearstatus} }; + { "creal: ", physics.diesel.clutchPressure }, + { "cdesi: ", physics.diesel.clutchState }, + { "cdelt: ", physics.diesel.clutchSlip }, + { "gears: ", physics.diesel.automaticGearShift} }; for( auto const &[parametername, parametervalue] : paramvalues ) { parameterstext += "\n" + parametername + to_string( parametervalue, 2, 9 ); } @@ -1115,15 +1147,15 @@ debug_panel::update_section_engine( std::vector &Output ) const { parameterstext = "hydro value"; std::vector< std::pair > const hydrovalues { - { "hTCnI: ", mover.hydro_TC_nIn }, - { "hTCnO: ", mover.hydro_TC_nOut }, - { "hTCTM: ", mover.hydro_TC_TMRatio }, - { "hTCTI: ", mover.hydro_TC_TorqueIn }, - { "hTCTO: ", mover.hydro_TC_TorqueOut }, - { "hTCfl: ", mover.hydro_TC_Fill }, - { "hRtFl: ", mover.hydro_R_Fill } , - { " hRtn: ", mover.hydro_R_n } , - { "hRtTq: ", mover.hydro_R_Torque } + { "hTCnI: ", physics.torqueConverter.revolutionsIn }, + { "hTCnO: ", physics.torqueConverter.revolutionsOut }, + { "hTCTM: ", physics.torqueConverter.torqueRatio }, + { "hTCTI: ", physics.torqueConverter.torqueIn }, + { "hTCTO: ", physics.torqueConverter.torqueOut }, + { "hTCfl: ", physics.torqueConverter.fill }, + { "hRtFl: ", physics.retarder.fill } , + { " hRtn: ", physics.retarder.revolutions } , + { "hRtTq: ", physics.retarder.torque } }; for( auto const &[parametername, parametervalue] : hydrovalues ) { @@ -1136,10 +1168,10 @@ debug_panel::update_section_engine( std::vector &Output ) const { void debug_panel::update_section_ai( std::vector &Output ) const { - if( m_input.mover == nullptr ) { return; } + if( m_input.physics == nullptr ) { return; } if( m_input.mechanik == nullptr ) { return; } - auto const &mover{ *m_input.mover }; + auto const &physics{ *m_input.physics }; auto const &mechanik{ *m_input.mechanik }; // biezaca komenda dla AI @@ -1159,7 +1191,7 @@ debug_panel::update_section_ai( std::vector &Output ) const { if( mechanik.VelNext == 0.0 && mechanik.eSignNext ) { // jeśli ma zapamiętany event semafora, nazwa eventu semafora - Output.emplace_back( "Current signal: " + Bezogonkow( mechanik.eSignNext->m_name ), Global.UITextColor ); + Output.emplace_back( "Current signal: " + data_name_to_utf8( mechanik.eSignNext->m_name ), Global.UITextColor ); } // distances @@ -1188,14 +1220,14 @@ debug_panel::update_section_ai( std::vector &Output ) const { textline = "Velocity:\n desired: " + to_string( mechanik.VelDesired, 0 ) + ", next: " + to_string( mechanik.VelNext, 0 ) - + "\n current: " + to_string( mover.Vel + 0.001f, 2 ); + + "\n current: " + to_string( physics.Vel + 0.001f, 2 ); std::vector< std::pair< double, std::string > > const restrictions{ { mechanik.VelSignalLast, "signal" }, { mechanik.VelLimitLast, "limit" }, { mechanik.VelRoad, "road" }, { mechanik.VelRestricted, "restricted" }, - { mover.RunningTrack.Velmax, "track" } }; + { physics.RunningTrack.Velmax, "track" } }; std::string restrictionstext; for( auto const &[restrictionspeed, restrictionsource] : restrictions ) { @@ -1223,7 +1255,7 @@ debug_panel::update_section_ai( std::vector &Output ) const { "-" ) + ")" + "\n desired diesel percentage: " + std::to_string(mechanik.DizelPercentage) + "/" + std::to_string(mechanik.DizelPercentage_Speed) - + "/" + to_string(100.4*mechanik.mvControlling->eimic_real, 0); + + "/" + to_string(100.4*mechanik.mvControlling->EimicReal(), 0); Output.emplace_back( textline, Global.UITextColor ); @@ -1233,25 +1265,18 @@ debug_panel::update_section_ai( std::vector &Output ) const { + "\n activation threshold: " + to_string( mechanik.fAccThreshold, 2 ) + ", delays: " + to_string( mechanik.fBrake_a0[ 0 ], 2 ) + " + " + to_string( mechanik.fBrake_a1[ 0 ], 2 ) + "\n virtual brake position: " + to_string( mechanik.BrakeCtrlPosition, 2 ) - + "\n test stage: " + std::to_string( mechanik.DynamicBrakeTest ) - + ", applied at: " + to_string( mechanik.DBT_VelocityBrake, 0 ) - + ", release at: " + to_string( mechanik.DBT_VelocityRelease, 0 ) - + ", done at: " + to_string( mechanik.DBT_VelocityFinish, 0 ); + + "\n test stage: " + std::to_string( static_cast( mechanik.brakeTest.stage ) ) + + ", applied at: " + to_string( mechanik.brakeTest.velocityBrake, 0 ) + + ", release at: " + to_string( mechanik.brakeTest.velocityRelease, 0 ) + + ", done at: " + to_string( mechanik.brakeTest.velocityFinish, 0 ); Output.emplace_back( textline, Global.UITextColor ); // ai driving flags - std::vector const drivingflagnames { - "StopCloser", "StopPoint", "Active", "Press", "Connect", "Primary", "Late", "StopHere", - "StartHorn", "StartHornNow", "StartHornDone", "Oerlikons", "IncSpeed", "TrackEnd", "SwitchFound", "GuardSignal", - "Visibility", "DoorOpened", "PushPull", "SignalFound", "StopPointFound", "GuardOpenDoor", "DepartureWarned" - /*"SemaphorWasElapsed", "TrainInsideStation", "SpeedLimitFound"*/ }; - textline = "Driving flags:"; - for( int idx = 0, flagbit = 1; idx < drivingflagnames.size(); ++idx, flagbit <<= 1 ) { - if( mechanik.DrivigFlags() & flagbit ) { - textline += "\n " + drivingflagnames[ idx ]; - } + for( auto const name : mechanik.DrivingFlagsState().ActiveNames() ) { + textline += "\n "; + textline += name; } Output.emplace_back( textline, Global.UITextColor ); @@ -1270,7 +1295,7 @@ debug_panel::update_section_scantable( std::vector &Output ) const { do { auto const scanline = mechanik.TableText( i ); if( scanline.empty() ) { break; } - Output.emplace_back( Bezogonkow( scanline ), Global.UITextColor ); + Output.emplace_back( data_name_to_utf8( scanline ), Global.UITextColor ); ++i; } while( i < speedtablesize ); if( Output.size() == 1 ) { @@ -1584,16 +1609,16 @@ debug_panel::update_section_coupler( std::vector &Output ) { if( m_input.camera == nullptr ) { return; } auto const &camera { m_input.camera->Pos }; auto const *vehicle { std::get( simulation::Region->find_vehicle( camera, coupler_pick_radius, false, true ) ) }; - if( vehicle == nullptr || vehicle->MoverParameters == nullptr ) { + if( vehicle == nullptr || vehicle->physics == nullptr ) { Output.emplace_back( std::format( "No coupler within {:.0f} m of the camera", coupler_pick_radius ), Global.UITextColor ); return; } - auto const nearerfront { glm::distance( vehicle->CouplerPosition( end::front ), camera ) <= glm::distance( vehicle->CouplerPosition( end::rear ), camera ) }; - m_coupler = { vehicle, nearerfront ? end::front : end::rear }; + auto const nearerfront { glm::distance( vehicle->CouplerPosition( VehicleEnd::front ), camera ) <= glm::distance( vehicle->CouplerPosition( VehicleEnd::rear ), camera ) }; + m_coupler = { vehicle, nearerfront ? VehicleEnd::front : VehicleEnd::rear }; - auto const &mover { *vehicle->MoverParameters }; - auto const &coupler { mover.Couplers[ m_coupler.end ] }; - auto const &neighbour { mover.Neighbours[ m_coupler.end ] }; + auto const &physics { *vehicle->physics }; + auto const &coupler { physics.Couplers[ m_coupler.end ] }; + auto const &neighbour { physics.Neighbours[ m_coupler.end ] }; auto const &state { coupler.physics_state }; Output.emplace_back( @@ -1602,14 +1627,14 @@ debug_panel::update_section_coupler( std::vector &Output ) { Output.emplace_back( std::format( "Model: {} (couplerphysics {}, vehicle {}covered), crash damage {}", - mover.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy", + physics.coupler_physics_at( m_coupler.end ) ? "physical" : "legacy", coupler_physics_setting(), - mover.CouplerPhysics ? "" : "not ", + physics.CouplerPhysics() ? "" : "not ", Global.crash_damage ? "on" : "off" ), Global.UITextColor ); if( neighbour.vehicle != nullptr ) { Output.emplace_back( - std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.vehicle_end == end::front ? "front" : "rear", coupler.CouplingFlag, neighbour.distance * 1000.0 ), + std::format( "Neighbour: {} ({} end), coupling [{}], gap {:.1f} mm", neighbour.vehicle->name(), neighbour.FacingEnd() == VehicleEnd::front ? "front" : "rear", coupler.CouplingFlag.Bits(), neighbour.distance * 1000.0 ), Global.UITextColor ); } else { @@ -1640,10 +1665,10 @@ debug_panel::render_section_coupler() { ImGui::Checkbox( "Crash damage", &Global.crash_damage ); ImGui::Checkbox( "Apply to the other end of the pair too", &m_couplerbothends ); - auto &mover { *m_coupler.vehicle->MoverParameters }; - auto &coupler { mover.Couplers[ m_coupler.end ] }; - auto const &neighbour { mover.Neighbours[ m_coupler.end ] }; - auto *othercoupler { neighbour.vehicle != nullptr ? &neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] : nullptr }; + auto &physics { *m_coupler.vehicle->physics }; + auto &coupler { physics.Couplers[ m_coupler.end ] }; + auto const &neighbour { physics.Neighbours[ m_coupler.end ] }; + auto *othercoupler { neighbour.vehicle != nullptr ? &neighbour.vehicle->physics->Couplers[ neighbour.vehicle_end ] : nullptr }; if( auto parameters { coupler.physics }; edit_coupler_parameters( parameters ) ) { coupler.physics = parameters; @@ -1715,12 +1740,87 @@ bool debug_panel::render_section_developer() const ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "These settings may crash your simulator!"); if (ImGui::Button("Reload current vehicle .fiz") == true) { - m_input.vehicle->MoverParameters->reload_FIZ(); // reload fiz + m_input.vehicle->physics->reload_FIZ(); // reload fiz } ImGui::PopStyleColor(); return true; } +namespace { + +// a combo choosing one of the names, the first entry standing for the library's own choice. the names are asked for +// each time the list opens, as devices come and go. returns: true if the choice changed +template +bool name_combo( char const *Label, std::string &Value, Names_ const &Names, char const *Defaultlabel, std::string_view const Defaultvalue ) { + + auto const preview { Value == Defaultvalue ? std::string{ Defaultlabel } : Value }; + if( false == ImGui::BeginCombo( Label, preview.c_str() ) ) { return false; } + + static std::vector names; // one list per call site, as each passes its own lambda + if( ImGui::IsWindowAppearing() ) { + names = Names(); + } + auto changed { false }; + if( ImGui::Selectable( Defaultlabel, Value == Defaultvalue ) ) { + Value = Defaultvalue; + changed = true; + } + for( auto const &name : names ) { + if( ImGui::Selectable( name.c_str(), name == Value ) ) { + Value = name; + changed = true; + } + } + ImGui::EndCombo(); + return changed; +} + +// options of the audio device, applied by reopening it: output device, output mode, HRTF, limiter, mixing rate, sources +void render_audio_device_settings() { + + auto changed { false }; + changed |= name_combo( "Output device###audiodevice", Global.AudioRenderer, + [] { return audio::renderer.output_devices(); }, "System default", "" ); + changed |= name_combo( "Output mode###audiooutputmode", Global.AudioOutputMode, + [] { return std::vector{ "mono", "stereo", "stereo-basic", "uhj", "headphones", "quad", "5.1", "6.1", "7.1" }; }, + "Automatic", "auto" ); + changed |= name_combo( "HRTF###audiohrtf", Global.AudioHrtf, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + changed |= name_combo( "HRTF data set###audiohrtfprofile", Global.AudioHrtfProfile, + [] { return audio::renderer.hrtf_profiles(); }, "Library's choice", "" ); + changed |= name_combo( "Limiter###audiolimiter", Global.AudioLimiter, + [] { return std::vector{ "on", "off" }; }, "Automatic", "auto" ); + + auto frequency { Global.AudioFrequency > 0 ? std::to_string( Global.AudioFrequency ) : std::string{} }; + if( name_combo( "Mixing rate###audiofrequency", frequency, + [] { return std::vector{ "22050", "32000", "44100", "48000", "96000" }; }, "Device's", "" ) ) { + Global.AudioFrequency = ( frequency.empty() ? 0 : std::stoi( frequency ) ); + changed = true; + } + + if( changed ) { + audio::renderer.apply_device_settings(); + } +} + +// options of the sources, applied to the playing ones right away: resampler, Doppler effect, EFX +void render_audio_source_settings() { + + auto changed { false }; + changed |= name_combo( "Resampler###audioresampler", Global.AudioResampler, + [] { return audio::renderer.resamplers(); }, "Library's default", "" ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioDoppler, 2 ) + "###audiodoppler" ).c_str(), &Global.AudioDoppler, 0.0f, 1.0f, "Doppler effect" ); + changed |= ImGui::Checkbox( "Soundproofing muffles high frequencies###audiolowpass", &Global.AudioLowpass ); + changed |= ImGui::SliderFloat( ( to_string( Global.AudioAirAbsorption, 1 ) + "###audioairabsorption" ).c_str(), &Global.AudioAirAbsorption, 0.0f, 10.0f, "Air absorption" ); + + if( changed ) { + audio::renderer.apply_source_settings(); + } + ImGui::TextWrapped( "%s", audio::renderer.device_status().c_str() ); +} + +} // namespace + bool debug_panel::render_section_settings() const { @@ -1775,6 +1875,10 @@ debug_panel::render_section_settings() const { commandrelay.post(user_command::radiovolumeset, val, 0.0, GLFW_PRESS, 0); } } + if( Global.bSoundEnabled ) { + render_audio_device_settings(); + render_audio_source_settings(); + } return true; } diff --git a/application/driveruipanels.h b/application/driveruipanels.h index 0e8b6917e..4d685806d 100644 --- a/application/driveruipanels.h +++ b/application/driveruipanels.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include "application/uilayer.h" #include "utilities/Classes.h" +#include "physics/vehicletypes.h" #include "rendering/renderer.h" class drivingaid_panel : public ui_expandable_panel { @@ -28,7 +29,7 @@ private: std::array m_buffer; // the broken coupler next to the camera, which the panel offers to repair: the vehicle and its end TDynamicObject const *m_brokenvehicle { nullptr }; - int m_brokenend { 0 }; + VehicleEnd m_brokenend { VehicleEnd::front }; }; class timetable_panel : public ui_expandable_panel { @@ -79,7 +80,7 @@ private: TDynamicObject const *controlled; TCamera const *camera; TDynamicObject const *vehicle; - TMoverParameters *mover; + physics::Vehicle *physics; TController const *mechanik; }; // methods @@ -99,7 +100,7 @@ private: void update_section_uart( std::vector &Output ) const; #endif // section update helpers - std::string update_vehicle_coupler( int const Side ); + std::string update_vehicle_coupler( VehicleEnd const Side ); std::string update_vehicle_brake() const; // renders provided lines, under specified collapsing header bool render_section( std::string const &Header, std::vector const &Lines ); @@ -130,7 +131,7 @@ private: // the coupler nearest to the camera struct coupler_pick { TDynamicObject const *vehicle { nullptr }; - int end { 0 }; + VehicleEnd end { VehicleEnd::front }; }; coupler_pick m_coupler; bool m_couplerbothends { true }; // changes to the parameters apply to the end of the other vehicle of the pair too diff --git a/application/editormode.cpp b/application/editormode.cpp index 42d6ea00f..7c9231d2b 100644 --- a/application/editormode.cpp +++ b/application/editormode.cpp @@ -20,6 +20,8 @@ http://mozilla.org/MPL/2.0/. #include "application/editorgestures.h" #include "scene/scenenodegroups.h" #include "application/editoruilayer.h" +#include "physics/vehicle.h" +#include "vehicle/DynObj.h" #ifndef _WIN32 #include #include @@ -35,6 +37,7 @@ extern char **environ; #include "editor/editorIncludeInfo.hpp" #include "editor/editorGroundMesh.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorCatenaryFile.hpp" #include "editor/editorAlignmentStore.hpp" #include "editor/editorSwitchStore.hpp" #include "world/catenary_scene.h" @@ -583,7 +586,16 @@ editor_mode::editor_mode() { ui()->set_open_scenery([this]() { m_openscenery_asked = true; }); ui()->set_memcell_focus([this](scene::basic_node *Node) { start_focus(Node); }); ui()->set_edit_menu([this]() { render_edit_menu(); }); - ui()->set_tools_menu([this]() { render_track_presets_menu(); }); + ui()->set_tools_menu([this]() { + render_track_presets_menu(); + if (ImGui::MenuItem(STR_C("Track names outside of ASCII..."), nullptr, m_track_names_open)) + { + check_track_names(false); + m_track_names_open = true; + } + if (ImGui::IsItemHovered()) + ImGui::SetTooltip("%s", STR_C("The tracks whose names have Polish letters or other characters outside of ASCII, and what an ASCII name would collide with; nothing is changed")); + }); ui()->set_menu_options([this]() { render_object_menu(); render_view_menu(); @@ -1714,6 +1726,7 @@ bool editor_mode::update() m_gauge.update(); m_gauge.render_windows(); m_minimap.render_windows(); + render_track_names_window(); // roads: trajectories of the lanes, and the tools of the road window update_road_tool(); @@ -3314,33 +3327,16 @@ bool editor_mode::save() } first_step_done(first_step::save); - // the heightmap terrain is kept in files of its own, the scenery only needs the directive which loads it, in a layer of its own - std::vector rootstatements; - std::map> statements; - if (m_streamer.active()) + // what can refuse the save is checked before anything is written, and the catenary files go first, all of them or none: + // a save refused there leaves the files on the disk as they were + for (auto const &file : catenary_scene_new_files()) { - std::string error; - if (false == m_streamer.save(&error)) - { - ui()->set_status(format(STR_C("The terrain couldn't be saved: %s"), error.c_str()), true); - return false; - } - if (false == scene::Layers.terrain_directive()) - { - auto const directive{"heightmap_terrain " + m_streamer.name() + " endheightmap_terrain"}; - if (auto const layer{output_layer("teren")}; layer != null_handle) - statements[layer].push_back(directive); - else - rootstatements.push_back(directive); - } + if (catenary_file_name_valid(file)) + continue; + ui()->set_status(format(STR_C("The catenary in \"%s\" couldn't be saved: %s"), file.c_str(), STR_C("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it")), true); + return false; } - - auto const terrainadded{false == rootstatements.empty() || false == statements.empty()}; - if (m_profile.changed) - profile_store(); - switch_store::tidy(); - switch_store::settle(); - infra_store(); + bool catenarywritten{false}; // the catenary (cantilevers on the poles) lives in files of its own; a file made in the editor needs the directive, in the file // of the layer it was made on (the scenario file when that layer can't take it) std::vector catenarynew; @@ -3383,8 +3379,40 @@ bool editor_mode::save() ui()->set_status(format(STR_C("The catenary couldn't be saved: %s"), message.c_str()), true); return false; } + catenarywritten = false == message.empty(); WriteLog("Editor: catenary written: " + message, logtype::generic); } + + // the heightmap terrain is kept in files of its own, the scenery only needs the directive which loads it, in a layer of its own + std::vector rootstatements; + std::map> statements; + if (m_streamer.active()) + { + std::string error; + if (false == m_streamer.save(&error)) + { + if (catenarywritten) + ui()->set_status(format(STR_C("The terrain couldn't be saved: %s. The catenary files are written already, the scenery files aren't: save again once it's fixed"), error.c_str()), true); + else + ui()->set_status(format(STR_C("The terrain couldn't be saved: %s"), error.c_str()), true); + return false; + } + if (false == scene::Layers.terrain_directive()) + { + auto const directive{"heightmap_terrain " + m_streamer.name() + " endheightmap_terrain"}; + if (auto const layer{output_layer("teren")}; layer != null_handle) + statements[layer].push_back(directive); + else + rootstatements.push_back(directive); + } + } + + auto const terrainadded{false == rootstatements.empty() || false == statements.empty()}; + if (m_profile.changed) + profile_store(); + switch_store::tidy(); + switch_store::settle(); + infra_store(); for (auto const &file : catenary_scene_new_files()) { auto const layer{static_cast(catenary_scene_file_layer(file))}; @@ -3444,6 +3472,13 @@ bool editor_mode::save() if (result.success) for (auto const &file : catenarynew) catenary_scene_file_included(file); + if (false == result.success && (catenarywritten || m_streamer.active())) + { + // the files of the terrain and of the catenary went before the scenery files + ui()->set_status(format("%s %s", result.message.c_str(), STR_C("Files of the terrain or of the catenary may be written already, the scenery files aren't: save again once it's fixed")), true); + WriteLog("Editor: " + result.message, logtype::generic); + return false; + } ui()->set_status(result.message, false == result.success); WriteLog("Editor: " + result.message, logtype::generic); return result.success; @@ -7573,7 +7608,7 @@ void editor_mode::enter() auto const *vehicle = Camera.m_owner; if (vehicle) { - const int cab = vehicle->MoverParameters->CabOccupied == 0 ? 1 : vehicle->MoverParameters->CabOccupied; + const int cab = vehicle->physics->CabOccupied() == 0 ? 1 : vehicle->physics->CabOccupied(); const glm::dvec3 left = vehicle->VectorLeft() * (double)cab; Camera.Pos = glm::dvec3(Camera.Pos.x, vehicle->GetPosition().y, Camera.Pos.z) + left * vehicle->GetWidth() + glm::dvec3(1.25f * left.x, 1.6f, 1.25f * left.z); Camera.m_owner = nullptr; @@ -7586,6 +7621,7 @@ void editor_mode::enter() if (Global.editor_session && false == m_opened_at_track) { m_opened_at_track = true; + check_track_names(true); auto const saved{scene::Layers.empty() ? std::vector{} : scene::Layers.marked(scene::layer_handle{1}, "//$c")}; if (false == saved.empty()) { @@ -8027,7 +8063,12 @@ void editor_mode::on_key(int const Key, int const Scancode, int const Action, in } if (is_press(Action)) { + // in the road window the first Esc gives up the road being drawn, the next one goes back to the selection + auto const &road{m_roadtool}; + auto const next{editor_road::tool_after_escape(road.tool, road.chain || road.branchroad != nullptr || road.branchjunction != nullptr, road.lifting)}; road_cancel(); + if (road.window && ui()->mode() != nodebank_panel::TRACK) + road_choose_tool(next); } // the first Esc drops what is going on in the track mode, the next one goes back to the selection if (is_press(Action) && ui()->mode() == nodebank_panel::TRACK) diff --git a/application/editormode.h b/application/editormode.h index 900d84383..ad09e9d5e 100644 --- a/application/editormode.h +++ b/application/editormode.h @@ -40,6 +40,7 @@ http://mozilla.org/MPL/2.0/. #include "editor/editorSwitchStore.hpp" #include "editor/editorFillStore.hpp" #include "editor/editorSwitchCurve.hpp" +#include "editor/editorSwitchDrives.hpp" #include "editor/editorKilometrage.hpp" #include "editor/editorSpeed.hpp" #include "editor/editorRoad.hpp" @@ -947,6 +948,20 @@ class editor_mode : public application_mode, private editor_track::observer, pri bool restart_editor(std::string const &Scenery); bool m_openscenery_asked{false}; bool m_opened_at_track{false}; + // the tracks whose names have letters outside of ASCII, listed once the scenery is opened for editing and in a window of their + // own: nothing is renamed, the names the scenery has go on working as they did; the editor gives no new name outside of ASCII + struct track_name_entry + { + std::string name; // as it reads (UTF-8) + std::string ascii; // the name without the letters outside of ASCII + bool clash{false}; // another path has that name already, or another name gives the same + bool include{false}; // given by a parameter of an include, which names more than the track with it + bool written{true}; // in a file the editor writes + }; + std::vector m_track_names; + bool m_track_names_open{false}; + void check_track_names(bool Report); + void render_track_names_window(); bool m_turntable_included{false}; bool turntable_controls(std::vector &Rootstatements); bool m_nose_included{false}; @@ -2811,7 +2826,7 @@ class editor_mode : public application_mode, private editor_track::observer, pri // "a".."d" for one of a double switch, whose switches are named a..d. none for a template which isn't a drive. the ones not // described for the editor have no family (-1) std::vector const &drive_switches(std::string const &File, std::map, std::less<>> const &Variants); - std::map, std::less<>> m_drive_templates; // read once for each file + switch_drives::template_switches m_drive_templates; // read once for each file, again when the templates change // a drive set to a switch the scenery hasn't got: left by a switch deleted or renamed by hand or in an earlier editor, its events // throw nothing struct stray_drive @@ -2830,10 +2845,19 @@ class editor_mode : public application_mode, private editor_track::observer, pri std::size_t instances{0}; }; std::optional m_drives_named; + // the drives whose switch isn't in the scenery, told once a frame for the list in the switch tool and the marks in the view, and again + // after a step made, undone or redone in the frame + struct drives_stray + { + std::vector drives; + std::optional frame; // none: to be told again + std::size_t history{0}; // the revision of the undo history + }; + drives_stray m_drives_stray; // the include of a drive or a template changed: what's kept of the drives standing is read again void drives_changed(); - // the drives whose switch isn't in the scenery, checked against the tracks each time - std::vector stray_drives(bool Wait = false); + // the drives whose switch isn't in the scenery, checked against the tracks once a frame. the list holds until the next call + std::vector const &stray_drives(bool Wait = false); void render_stray_drives(); void draw_stray_drives(); scene::layer_handle output_layer(std::string const &Part) override; diff --git a/application/editormodecatenary.cpp b/application/editormodecatenary.cpp index 5e8557d24..b2bbb61c4 100644 --- a/application/editormodecatenary.cpp +++ b/application/editormodecatenary.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "application/editormodecatenary.h" #include "application/editoruilayer.h" #include "application/editorprojection.h" +#include "editor/editorCatenaryFile.hpp" #include "editor/editorFormat.hpp" #include "editor/editorGeometry.hpp" @@ -399,6 +400,27 @@ bool grouped_items(std::vector const &Names, int &Chosen, std::func char const *const kStates[] = {"new", "worn", "tarnished"}; int const kStateValues[] = {0, 2, 1}; +// the chain the other way round: what is at its ends (the anchors, the holders of the middle anchor's rope) changes ends with the list +void reverse_chain(catenary::chain &Chain) +{ + std::ranges::reverse(Chain.suspensions); + std::swap(Chain.anchor_start, Chain.anchor_end); + std::swap(Chain.anchor_start_contact, Chain.anchor_end_contact); + std::swap(Chain.middle_heights[0], Chain.middle_heights[1]); +} + +// the new entries can go into the file: a scenery file (layer), a catenary file the scenery includes already, or a new one +// whose name the directive including it can carry +bool file_takes_entries(std::string const &File) +{ + if (catenary_scene_file_inline(File)) + return true; + auto const files{catenary_scene_files()}; + auto const fresh{catenary_scene_new_files()}; + auto const included{std::ranges::find(files, File) != files.end() && std::ranges::find(fresh, File) == fresh.end()}; + return included || catenary_file_name_valid(File); +} + } // namespace void catenary_editor::catenary_scan() @@ -1626,8 +1648,12 @@ void catenary_editor::catenary_apply(catenary_spot const &Spot) std::copy(std::begin(current->spread), std::end(current->spread), data.spread); // dragging a slider changes it many times: all of that is taken back at once auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; - if (tool.undo.empty() || last.chain || last.index != index || last.removed || false == last.before.has_value()) + if (tool.undo.empty() || last.group != tool.slider_group || tool.slider != 1 || last.chain || last.index != index || last.removed || false == last.before.has_value()) + { tool.undo.push_back({++tool.group, false, index, *current, std::nullopt, false}); + tool.slider_group = tool.group; + tool.slider = 1; + } catenary_scene_update(index, data); tool.spots[index] = Spot; tool.spots[index].data = data; @@ -2123,6 +2149,11 @@ void catenary_editor::catenary_place(catenary_spot const &Spot) chain_insert insert; auto const inserting{catenary_insert_at(Spot, insert)}; std::string const file{inserting ? catenary_chain_file(static_cast(insert.chain)) : std::string{tool.file}}; + if (false == inserting && false == file_takes_entries(file)) + { + tool.status = STR("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it"); + return; + } data.name = catenary_scene_new_name(file); // a drop on a gantry takes the texture of the gantry if (auto const *gantry{tool.gantry_selected >= 0 ? catenary_gantry_get(static_cast(tool.gantry_selected)) : nullptr}; gantry != nullptr && data.pole_type != tool.poles[std::clamp(tool.pole, 0, static_cast(tool.poles.size()) - 1)]) @@ -2674,13 +2705,23 @@ void catenary_editor::catenary_connect(std::size_t const To) // From's chain with From last, then To (and To's chain from To on) auto changed{*chaina}; if (pa == 0 && changed.suspensions.size() > 1) - std::reverse(changed.suspensions.begin(), changed.suspensions.end()); + reverse_chain(changed); if (chainb != nullptr) { - auto other{chainb->suspensions}; + auto other{*chainb}; if (pb != 0) - std::reverse(other.begin(), other.end()); - changed.suspensions.insert(changed.suspensions.end(), other.begin(), other.end()); + reverse_chain(other); + changed.suspensions.insert(changed.suspensions.end(), other.suspensions.begin(), other.suspensions.end()); + // the joined ends are inside the chain now: it ends where To's chain ended, with what that end had + changed.anchor_end = other.anchor_end; + changed.anchor_end_contact = other.anchor_end_contact; + changed.messenger_from.insert(changed.messenger_from.end(), other.messenger_from.begin(), other.messenger_from.end()); + if (changed.middle.empty() && false == other.middle.empty()) + { + changed.middle = other.middle; + changed.middle_device = other.middle_device; + std::copy(std::begin(other.middle_heights), std::end(other.middle_heights), changed.middle_heights); + } tool.undo.push_back({tool.group, true, static_cast(cb), std::nullopt, *chainb, false}); catenary_chain_remove(static_cast(cb)); } @@ -2857,6 +2898,11 @@ void catenary_editor::catenary_press(track_intent const &Intent) return; catenary::gantry gantry; std::string const file{tool.file}; + if (false == file_takes_entries(file)) + { + tool.status = STR("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it"); + return; + } gantry.name = catenary_scene_new_gantry_name(file); gantry.beam = beam; gantry.high = tool.gantry_high; @@ -2992,8 +3038,12 @@ void catenary_editor::catenary_chain_apply() if (false == tool.networks.empty()) changed.type = tool.networks[std::clamp(tool.network, 0, static_cast(tool.networks.size()) - 1)]; auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; - if (tool.undo.empty() || false == last.chain || last.index != index || false == last.chain_before.has_value()) + if (tool.undo.empty() || last.group != tool.slider_group || tool.slider != 2 || false == last.chain || last.index != index || false == last.chain_before.has_value()) + { tool.undo.push_back({++tool.group, true, index, std::nullopt, *chain, false}); + tool.slider_group = tool.group; + tool.slider = 2; + } catenary_chain_update(index, changed); } @@ -4292,6 +4342,8 @@ void catenary_editor::render_catenary_cantilever_ui() if (ImGui::IsItemHovered()) ImGui::SetTooltip("%s", STR_C("The catenary file follows the active layer again")); } + if (tool.file[0] != '\0' && false == file_takes_entries(tool.file)) + ImGui::TextColored(ImVec4(1.0f, 0.4f, 0.3f, 1.0f), "%s", STR_C("The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it")); { // where it ends up: straight in the file of a layer, or a catenary file of its own and the layer whose file includes it if (catenary_scene_file_inline(tool.file)) @@ -5017,10 +5069,12 @@ void catenary_editor::render_catenary_ui() // both together, and each by itself no more than 0.20 m from the other auto const heighten = [&](catenary::gantry const &Changed) { auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; - if (tool.undo.empty() || false == last.gantry || last.index != static_cast(tool.gantry_selected) || false == last.gantry_before.has_value()) + if (tool.undo.empty() || last.group != tool.slider_group || tool.slider != 3 || false == last.gantry || last.index != static_cast(tool.gantry_selected) || false == last.gantry_before.has_value()) { catenary_change change; change.group = ++tool.group; + tool.slider_group = tool.group; + tool.slider = 3; change.gantry = true; change.index = static_cast(tool.gantry_selected); change.gantry_before = *gantry; @@ -5734,9 +5788,11 @@ void catenary_editor::catenary_gantry_reshape(std::string const &Beam, double co } auto const &last{tool.undo.empty() ? catenary_change{} : tool.undo.back()}; // turning in small steps is taken back at once - if (Turn == 0.0 || tool.undo.empty() || false == last.gantry || last.index != selected || false == last.gantry_before.has_value()) + if (Turn == 0.0 || tool.undo.empty() || last.group != tool.slider_group || tool.slider != 4 || false == last.gantry || last.index != selected || false == last.gantry_before.has_value()) { ++tool.group; + tool.slider_group = Turn == 0.0 ? 0 : tool.group; + tool.slider = 4; // the selected span last: the next small turn finds it at the top of the undo and joins this group for (auto move{moves.rbegin()}; move != moves.rend(); ++move) { diff --git a/application/editormodecatenary.h b/application/editormodecatenary.h index cdafc45eb..7d78df61f 100644 --- a/application/editormodecatenary.h +++ b/application/editormodecatenary.h @@ -113,6 +113,9 @@ struct catenary_editor std::map spots; // where the suspensions are by the track, by their numbers std::vector undo; int group{0}; + // the undo group a control of the panel opened: its next changes join it only while nothing else came between + int slider_group{0}; + int slider{0}; // ... which control: 1 the settings of the pole, 2 of the chain, 3 the heights of a gantry, 4 its turn catenary::cantilever_result probe; bool probed{false}; bool probe_good{false}; diff --git a/application/editormodejoints.cpp b/application/editormodejoints.cpp index 12c1e4357..9a3bf5bf6 100644 --- a/application/editormodejoints.cpp +++ b/application/editormodejoints.cpp @@ -490,30 +490,30 @@ bool joints_tool::joint_fix(joint_issue &Issue, std::vectoreType == tt_Normal && editor_track::can_edit_geometry(*Track, reason) && scene::Layers.editable(Track); }; - TTrack *mover{nullptr}; + TTrack *physics{nullptr}; editor_track::point_ref moved; TTrack *fixed{nullptr}; editor_track::point_ref held; if (movable(Issue.track)) { - mover = Issue.track; + physics = Issue.track; moved = Issue.point; fixed = Issue.other; held = Issue.theirs; } else if (movable(Issue.other) && (Issue.type != kind::gap || false == editor_track::is_connected(*Issue.other, Issue.theirs))) { - mover = Issue.other; + physics = Issue.other; moved = Issue.theirs; fixed = Issue.track; held = Issue.point; } - if (mover == nullptr) + if (physics == nullptr) return false; - if (std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == mover; })) - States.emplace_back(mover, editor_track::capture(*mover)); - if (std::find(Changed.begin(), Changed.end(), mover) == Changed.end()) - Changed.push_back(mover); + if (std::none_of(States.begin(), States.end(), [&](auto const &Entry) { return Entry.first == physics; })) + States.emplace_back(physics, editor_track::capture(*physics)); + if (std::find(Changed.begin(), Changed.end(), physics) == Changed.end()) + Changed.push_back(physics); editor_track::snap_target target; target.track = fixed; target.point = held; @@ -524,14 +524,14 @@ bool joints_tool::joint_fix(joint_issue &Issue, std::vectorm_paths[moved.path]}; + auto &path{physics->m_paths[moved.path]}; auto const roll{static_cast(roll_into(*fixed, held))}; if (at_start(moved)) path.rolls[0] = -roll; diff --git a/application/editormodeminimap.cpp b/application/editormodeminimap.cpp index 2717cd447..e11fe57d4 100644 --- a/application/editormodeminimap.cpp +++ b/application/editormodeminimap.cpp @@ -122,16 +122,19 @@ void minimap_tool::gather_stations() if (false == stale(m_stations_seen)) return; std::map found; - // the texts are in windows-1250; the ones of the events lost their polish letters as they were read - auto const add = [&](std::string const &Text, bool const Letters, glm::dvec3 const &Point, TTrack *Track) { + // the texts are in windows-1250; the stop points of a station can spell it with or without its polish letters + std::unordered_set lettered; + auto const add = [&](std::string const &Text, glm::dvec3 const &Point, TTrack *Track) { auto const name{stop_name(Text)}; if (name.empty()) return; auto const key{folded(name)}; auto &entry{found[key]}; entry.key = key; + // the station is shown by a spelling with the letters, when any of its stop points has one + auto const letters{std::ranges::any_of(name, [](char const Character) { return static_cast(Character) >= 0x80; })}; // the timetables join the words with underscores - if (entry.name.empty() || Letters) + if (entry.name.empty() || (letters && lettered.insert(key).second)) { entry.name = win1250_to_utf8(name); std::replace(entry.name.begin(), entry.name.end(), '_', ' '); @@ -145,10 +148,10 @@ void minimap_tool::gather_stations() }; for (auto *cell : simulation::Memory.sequence()) if (cell != nullptr && cell->Text().starts_with(stop_prefix)) - add(cell->Text(), true, cell->location(), cell->Track); + add(cell->Text(), cell->location(), cell->Track); for (auto *event : simulation::Events.sequence()) if (auto const *values{dynamic_cast(event)}; values != nullptr && values->input_command() == TCommandType::cm_PassengerStopPoint) - add(values->input_text(), false, values->input_location(), nullptr); + add(values->input_text(), values->input_location(), nullptr); std::vector stations; for (auto &entry : found) stations.push_back(std::move(entry.second)); diff --git a/application/editormoderoad.cpp b/application/editormoderoad.cpp index 7c2a69da3..917699037 100644 --- a/application/editormoderoad.cpp +++ b/application/editormoderoad.cpp @@ -1026,7 +1026,8 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) auto const centre{road != nullptr ? road->definition().point(t) : junction->definition().centre}; // seen from the junction the road comes from where it's being led from glm::dvec2 const from{tool.point.x - centre.x, tool.point.z - centre.z}; - if (false == (road != nullptr ? editor_road::branch_from(*road, t, from, arriving, leaving, lanewidth, plan.end, plan.error) : editor_road::branch_from(*junction, from, arriving, leaving, lanewidth, plan.end, plan.error))) + if (false == (road != nullptr ? editor_road::branch_from(*road, t, from, arriving, leaving, lanewidth, layout.surfacetype, plan.end, plan.error) : + editor_road::branch_from(*junction, from, arriving, leaving, lanewidth, layout.surfacetype, plan.end, plan.error))) return plan; plan.hasend = true; auto const &arm{plan.end.layout.arms[plan.end.arm]}; @@ -1057,8 +1058,9 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) return plan; } // the axis of the road goes away from the junction, so the lanes going against it are the ones leading into the junction - if (false == (tool.branchroad != nullptr ? editor_road::branch_from(*tool.branchroad, tool.branchat, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error) : - editor_road::branch_from(*tool.branchjunction, away, layout.backward, layout.forward, lanewidth, plan.start, plan.error))) + if (false == (tool.branchroad != nullptr ? + editor_road::branch_from(*tool.branchroad, tool.branchat, away, layout.backward, layout.forward, lanewidth, layout.surfacetype, plan.start, plan.error) : + editor_road::branch_from(*tool.branchjunction, away, layout.backward, layout.forward, lanewidth, layout.surfacetype, plan.start, plan.error))) return plan; plan.hasstart = true; auto const &arm{plan.start.layout.arms[plan.start.arm]}; @@ -1091,7 +1093,8 @@ editor_mode::road_plan editor_mode::road_preview(bool const Fresh) plan.error = STR_C("Too far from the last point"); return plan; } - plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, plan.error); + plan.pieces = editor_road::plan(start, hasdirection ? &direction : nullptr, target, tied ? &enddirection : nullptr, Global.ctrlState, layout.surfacetype, + 0.5 * std::max(layout.span(0.0), layout.span(1.0)), plan.error); road_profile(plan.pieces, hasgrade ? &startgrade : nullptr, tied ? &endgrade : nullptr, Fresh); return plan; } @@ -2129,6 +2132,28 @@ bool editor_mode::render_road_layout(road_node::state &State) // appearance ImGui::Separator(); + // what the road is made of sets how tight it can be laid out, and a road made dirt gets the look of a field road + char const *surfacetypes[]{STR_C("paved"), STR_C("dirt")}; + int surfacetype{State.surfacetype == road_surface_type::dirt ? 1 : 0}; + ImGui::SetNextItemWidth(120.0f); + if (ImGui::Combo(STR_C("Road type"), &surfacetype, surfacetypes, 2)) + { + auto const previous{State.surfacetype}; + State.surfacetype = (surfacetype == 1 ? road_surface_type::dirt : road_surface_type::paved); + if (State.surfacetype != previous) + { + // a surface left as the other type has it goes with the type, a surface picked by hand stays + if (State.surface == road_surface::default_material(previous)) + State.surface = road_surface::default_material(State.surfacetype); + if (State.surfacetype == road_surface_type::dirt && State.markings == road_node::marking_colour::white) + State.markings = road_node::marking_colour::none; + changed = true; + } + } + item_tooltip("Paved: asphalt, concrete or setts, with the bends and the junction angles of a built road.\n" + "Dirt: a track between fields or through a forest. It bends tighter (3 m radius instead of 6 m), can be shorter (1 m instead of 2 m),\n" + "leaves other roads at sharper angles (15 degrees instead of 30) and can turn back in a hairpin.\n" + "Made dirt, a road with the default asphalt gets the field road texture and loses the white lines"); char const *colours[]{STR_C("no markings"), STR_C("white"), STR_C("orange")}; int colour{State.markings == road_node::marking_colour::white ? 1 : State.markings == road_node::marking_colour::orange ? 2 : 0}; ImGui::SetNextItemWidth(120.0f); diff --git a/application/editormodeselftestscene.cpp b/application/editormodeselftestscene.cpp index df5d62622..93387ff72 100644 --- a/application/editormodeselftestscene.cpp +++ b/application/editormodeselftestscene.cpp @@ -47,6 +47,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include "application/editormodeselftest.h" +#include "physics/vehicle.h" editor_mode::selftest_result editor_mode::selftest_scene(std::string const &command, std::istringstream &words) { @@ -266,8 +267,8 @@ editor_mode::selftest_result editor_mode::selftest_scene(std::string const &comm auto const head{vehicle->HeadPosition()}; auto const front{vehicle->VectorFront()}; auto const coupler = [&](int const End) { - auto const &coupler{vehicle->MoverParameters->Couplers[End]}; - return coupler.Connected != nullptr ? coupler.Connected->Name + "/" + std::to_string(coupler.CouplingFlag) : std::string{"-"}; + auto const &coupler{vehicle->physics->Couplers[End]}; + return coupler.Connected != nullptr ? coupler.Connected->Name + "/" + std::to_string(coupler.CouplingFlag.Bits()) : std::string{"-"}; }; WriteLog(format("SELFTEST vehicle %s head %.2f %.2f front %.2f %.2f dir %d coupler0 %s coupler1 %s", vehicle->name().c_str(), head.x, head.z, front.x, front.z, vehicle->iDirection, coupler(0).c_str(), coupler(1).c_str())); } diff --git a/application/editormodeshared.h b/application/editormodeshared.h index 516aada88..312241a9b 100644 --- a/application/editormodeshared.h +++ b/application/editormodeshared.h @@ -58,6 +58,18 @@ inline void item_tooltip(char const *Text) ImGui::SetTooltip("%s", STR_C(Text)); } +// the callback of a name field with ImGuiInputTextFlags_CallbackCharFilter: the names the editor gives are plain ASCII +// (editor_track::name_valid), so a letter outside of it is dropped as it's typed or pasted and never shows in the field. +// UserData, when given, is a bool set to true once a letter was dropped +inline int ascii_only_filter(ImGuiInputTextCallbackData *Data) +{ + if (Data->EventChar < 0x80) + return 0; + if (Data->UserData != nullptr) + *static_cast(Data->UserData) = true; + return 1; +} + // grid points without a height (or another value) take the one of the nearest point which has it (by steps along the grid) template inline void fill_from_nearest(std::vector &Heights, std::vector &Found, std::size_t const Side) { diff --git a/application/editormodesrk.cpp b/application/editormodesrk.cpp index b31178e04..15ec62ba5 100644 --- a/application/editormodesrk.cpp +++ b/application/editormodesrk.cpp @@ -1443,19 +1443,26 @@ void srk_tool::render_station() auto const &layout{*m_layout}; if (begin_fields("##srkstation")) { - auto const text = [&](char const *Label, char const *Id, std::string const &Value, char const *Hint, auto const &Set) { + // Ascii: the value goes into the names the editor gives (editor_track::name_valid), so a letter outside of ASCII is dropped as it's typed + auto const text = [&](char const *Label, char const *Id, std::string const &Value, char const *Hint, auto const &Set, bool const Ascii = false) { field_row(Label); std::array buffer{}; Value.copy(buffer.data(), buffer.size() - 1); - if (ImGui::InputTextWithHint(Id, Hint, buffer.data(), buffer.size())) + bool dropped{false}; + if (ImGui::InputTextWithHint(Id, Hint, buffer.data(), buffer.size(), Ascii ? ImGuiInputTextFlags_CallbackCharFilter : ImGuiInputTextFlags_None, ascii_only_filter, &dropped)) { Set(std::string{buffer.data()}); m_changed = true; } + if (dropped) + { + begin_status(); + refuse(STR("The name can hold ASCII only: no Polish letters or other characters outside of it")); + } }; auto const *entry{m_record >= 0 ? &m_records[m_record] : nullptr}; text("Name", "##srkname", entry != nullptr ? entry->name : std::string{}, example("Biała Podlaska").c_str(), [&](std::string const &Value) { record_of_open().name = Value; }); - text("Code", "##srkcode", entry != nullptr ? entry->code : std::string{}, example("BPd").c_str(), [&](std::string const &Value) { record_of_open().code = word_of(Value) == "-" ? std::string{} : word_of(Value); }); + text("Code", "##srkcode", entry != nullptr ? entry->code : std::string{}, example("BPd").c_str(), [&](std::string const &Value) { record_of_open().code = word_of(Value) == "-" ? std::string{} : word_of(Value); }, true); item_tooltip("The abbreviation of the station: the names of its switches, track circuits and signals begin with it"); auto const line_hint{line_of_open()}; text("Line", "##srkline", entry != nullptr ? entry->line : std::string{}, line_hint.empty() ? example("2").c_str() : line_hint.c_str(), [&](std::string const &Value) { record_of_open().line = word_of(Value) == "-" ? std::string{} : word_of(Value); }); diff --git a/application/editormodeswitchdrive.cpp b/application/editormodeswitchdrive.cpp index 931350af1..e9e6a6313 100644 --- a/application/editormodeswitchdrive.cpp +++ b/application/editormodeswitchdrive.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "application/editorprojection.h" #include "editor/editorFormat.hpp" #include "editor/editorIncludeInfo.hpp" +#include "editor/editorSwitchDrives.hpp" #include "world/Segment.h" #include "world/Track.h" @@ -35,15 +36,14 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include namespace { std::string drive_file(std::string Text) { - std::replace(Text.begin(), Text.end(), '\\', '/'); - std::transform(Text.begin(), Text.end(), Text.begin(), [](unsigned char Character) { return static_cast(std::tolower(Character)); }); - return Text; + return switch_drives::game_name(std::move(Text)); } // the track the events of a drive find by the name: the game reads the names of the tracks lower case, the parameters of an include as @@ -54,6 +54,30 @@ TTrack *track_named(std::string const &Name) return track != nullptr ? track : simulation::Paths.find(drive_file(Name)); } +// whether the track a name finds is removed, none when it finds no track +std::optional named_removed(std::string const &Name) +{ + auto const *track{track_named(Name)}; + return track != nullptr ? std::optional{track->m_editorremoved} : std::nullopt; +} + +// the names of all the tracks of the scenery not removed +std::vector standing_names() +{ + std::vector names; + for (auto const *track : simulation::Paths.sequence()) + if (track != nullptr && false == track->m_editorremoved) + names.push_back(track->name()); + return names; +} + +// the switches standing, told by the names as the events of the drives find them in the game; with no track found by a name, a track of +// the name left by the deletion of the other of two is looked for in the whole scenery +switch_drives::standing_switches switches_standing() +{ + return switch_drives::standing_switches{named_removed, standing_names}; +} + // a template by the name of its file, with no folder: told to the user, who picks the drives by their names std::string file_name(std::string const &File) { @@ -307,10 +331,8 @@ std::vector const &editor_mode::drive_switches(std::string const &F static std::vector const single{std::string{}}; if (Variants.contains(File)) return single; - auto const [found, fresh]{m_drive_templates.try_emplace(File)}; - if (fresh) - editor_includes::switched_tracks(File, found->second); - return found->second; + // a template changed is read again with the next revision of the templates, one which couldn't be read in the next frame + return m_drive_templates.of(File, EditorIncludes.revision(), ImGui::GetFrameCount(), editor_includes::switched_tracks); } std::map, std::less<>> editor_mode::drive_variants() const @@ -330,7 +352,7 @@ void editor_mode::drives_changed() m_drives_named.reset(); } -std::vector editor_mode::stray_drives(bool const Wait) +std::vector const &editor_mode::stray_drives(bool const Wait) { scan_switch_drives(Wait); auto const instances{static_cast(scene::Layers.instance_count())}; @@ -348,31 +370,38 @@ std::vector editor_mode::stray_drives(bool const Wait) drive.switches.push_back(standing.values[0] + suffix); kept->drives.push_back(std::move(drive)); } + m_drives_stray.frame.reset(); } - // a switch is told by the name, as the events of the drive find it in the game; a drive of a double switch is stray with all of its - // switches gone, while one stands it still throws it - std::vector stray; + // the list in the switch tool and the marks in the view ask in each frame: told once, and again after a step in the frame + auto &stray{m_drives_stray}; + auto const frame{ImGui::GetFrameCount()}; + auto const history{history_revision()}; + if (stray.frame == frame && stray.history == history) + return stray.drives; + stray.frame = frame; + stray.history = history; + stray.drives.clear(); + // a switch is told by the name, as the events of the drive find it in the game, by the same test the deletion of a switch takes its + // drive away by; a drive of a double switch is stray with all of its switches gone, while one stands it still throws it + auto switches{switches_standing()}; for (auto const &drive : kept->drives) { auto const &included{scene::Layers.instance(drive.instance)}; // a gate, a derailer or a turntable of the same kind of template throws a track of another kind: only a track gone counts - if (included.removed || included.dead || std::any_of(drive.switches.begin(), drive.switches.end(), [](std::string const &Name) { - auto const *track{track_named(Name)}; - return track != nullptr && false == track->m_editorremoved; - })) + if (included.removed || included.dead || switches.any_stands(drive.switches)) continue; std::string missing; for (auto const &name : drive.switches) missing += (missing.empty() ? "" : ", ") + name; - stray.push_back(drive); - stray.back().name = std::move(missing); + stray.drives.push_back(drive); + stray.drives.back().name = std::move(missing); } - return stray; + return stray.drives; } void editor_mode::render_stray_drives() { - auto const stray{stray_drives()}; + auto const &stray{stray_drives()}; if (stray.empty()) return; ImGui::PushID("straydrives"); @@ -400,7 +429,7 @@ void editor_mode::render_stray_drives() // a red mark by each drive with no switch in sight, so it's seen in the view and over the photo, not only in the list void editor_mode::draw_stray_drives() { - auto const stray{stray_drives()}; + auto const &stray{stray_drives()}; if (stray.empty()) return; // the ones far off would only crowd the view of the whole line @@ -528,13 +557,8 @@ void editor_mode::drives_deleted(std::vector const &Switches) auto const named = [&](std::string const &Name) { return std::find(deleted.begin(), deleted.end(), drive_file(Name)) != deleted.end(); }; // an older scenery may have two tracks of a name, the name finding the later; the earlier one, left by the deletion of the other, // still has the drive and the ballast, so it's looked for too - auto const stands = [](std::string const &Name) { - if (auto const *track{track_named(Name)}; track != nullptr) - return false == track->m_editorremoved; - auto const name{drive_file(Name)}; - auto const &tracks{simulation::Paths.sequence()}; - return std::any_of(tracks.begin(), tracks.end(), [&](TTrack const *Track) { return Track != nullptr && false == Track->m_editorremoved && drive_file(Track->name()) == name; }); - }; + auto switches{switches_standing()}; + auto const stands = [&switches](std::string const &Name) { return switches.stands(Name); }; auto const take_away = [&](scene::instance_handle const Instance) { if (false == scene::Layers.removable(Instance)) return; diff --git a/application/editormodeswitchtool.cpp b/application/editormodeswitchtool.cpp index 878e18aa3..f13b7429f 100644 --- a/application/editormodeswitchtool.cpp +++ b/application/editormodeswitchtool.cpp @@ -255,7 +255,11 @@ void editor_mode::render_switch_ui() if (begin_fields("##switchnamefields", 0.3f)) { field_row("Name##switchname"); - ImGui::InputTextWithHint("##switchname", switch_name_for_new().c_str(), tool.name, sizeof(tool.name)); + // the names the editor gives are plain ASCII (editor_track::name_valid): a letter outside of it is dropped as it's typed + bool dropped{false}; + ImGui::InputTextWithHint("##switchname", switch_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CallbackCharFilter, ascii_only_filter, &dropped); + if (dropped) + tool.status = refused(STR("The name can hold ASCII only: no Polish letters or other characters outside of it")); item_tooltip("Name of the next switch, its drive events are named after it; empty: the next free z1, z2...; a number at the end goes up with each switch"); ImGui::EndTable(); } diff --git a/application/editormodetracknames.cpp b/application/editormodetracknames.cpp new file mode 100644 index 000000000..19eed5770 --- /dev/null +++ b/application/editormodetracknames.cpp @@ -0,0 +1,122 @@ +/* +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 tracks whose names have letters outside of ASCII: listed, nothing renamed. The names the sceneries have go on working as they +// always did, in the editor and in the game; the editor gives no new name outside of ASCII (editor_track::name_valid) + +#include "stdafx.h" + +#include "application/editormode.h" +#include "application/editoruilayer.h" +#include "editor/editorFormat.hpp" +#include "editor/editorTrack.hpp" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "utilities/asciiname.h" +#include "utilities/translation.h" + +#include +#include +#include +#include +#include + +namespace +{ + +// the tracks listed: the lanes take their names from their road, the removed ones are gone +bool listed(TTrack const *Track) +{ + return Track != nullptr && false == Track->m_editorremoved && (Track->iCategoryFlag & 0x80) == 0 && Track->m_road == nullptr && false == Track->name().empty() && + false == ascii_name::plain(Track->name()); +} + +char const *yes_no(bool const Value) +{ + return Value ? STR_C("yes") : STR_C("no"); +} + +} // namespace + +void editor_mode::check_track_names(bool const Report) +{ + m_track_names.clear(); + std::vector found; + std::map folded; // how many of the names listed give each ASCII name + for (auto const *track : simulation::Paths.sequence()) + { + if (false == listed(track)) + continue; + found.push_back(track); + ++folded[ascii_name::fold(track->name())]; + } + for (auto const *track : found) + { + track_name_entry entry; + entry.name = ascii_name::readable(track->name()); + entry.ascii = ascii_name::fold(track->name()); + // another path named so already, or another name listed giving the same + auto const *other{simulation::Paths.find(entry.ascii)}; + entry.clash = (other != nullptr && other != track && false == other->m_editorremoved) || folded[entry.ascii] > 1; + entry.include = track->from_template() && editor_track::uses_of_name(*track).includes > 0; + entry.written = track->from_template() ? entry.include : scene::Layers.editable(track); + m_track_names.push_back(std::move(entry)); + } + if (false == Report || m_track_names.empty()) + return; + for (auto const &entry : m_track_names) + WriteLog(std::format(R"(Editor: track "{}" has characters outside of ASCII in its name; in ASCII "{}"{})", entry.name, entry.ascii, entry.clash ? ", a name taken already" : "")); + ui()->set_status(format(STR_C("%zu track names have characters outside of ASCII; they work as they are, the list is in Tools"), m_track_names.size())); +} + +void editor_mode::render_track_names_window() +{ + if (false == m_track_names_open) + return; + ImGui::SetNextWindowSize(ImVec2(620.0f * Global.ui_scale, 380.0f * Global.ui_scale), ImGuiCond_FirstUseEver); + if (false == ImGui::Begin((std::string(STR_C("Track names outside of ASCII")) + "###tracknamesascii").c_str(), &m_track_names_open)) + { + ImGui::End(); + return; + } + ImGui::TextWrapped("%s", STR_C("These names work as they are and nothing here changes them. New names given in the editor are ASCII only. To give one of these tracks an ASCII name, rename it in the track properties: the memory cells and the includes which name it go along, the events named after it are listed there. A track named by a parameter of an include (From an include: yes) can't be renamed there: change that parameter in the line of the scenery which puts the include.")); + if (ImGui::SmallButton(STR_C("Check again"))) + check_track_names(false); + ImGui::SameLine(); + ImGui::TextDisabled(STR_C("Tracks: %zu"), m_track_names.size()); + auto constexpr flags{ImGuiTableFlags_RowBg | ImGuiTableFlags_Borders | ImGuiTableFlags_ScrollY | ImGuiTableFlags_Resizable}; + if (ImGui::BeginTable("##tracknamesascii", 5, flags)) + { + ImGui::TableSetupScrollFreeze(0, 1); + ImGui::TableSetupColumn(STR_C("Name")); + ImGui::TableSetupColumn(STR_C("In ASCII")); + ImGui::TableSetupColumn(STR_C("Taken")); + ImGui::TableSetupColumn(STR_C("From an include")); + ImGui::TableSetupColumn(STR_C("In a file the editor writes")); + ImGui::TableHeadersRow(); + for (auto const &entry : m_track_names) + { + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(entry.name.c_str()); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(entry.ascii.c_str()); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(yes_no(entry.clash)); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(yes_no(entry.include)); + ImGui::TableNextColumn(); + ImGui::TextUnformatted(yes_no(entry.written)); + } + ImGui::EndTable(); + } + ImGui::End(); +} diff --git a/application/editormodeturntable.cpp b/application/editormodeturntable.cpp index 6052bf5c8..ac5bb98aa 100644 --- a/application/editormodeturntable.cpp +++ b/application/editormodeturntable.cpp @@ -1011,7 +1011,11 @@ void editor_mode::render_turntable_ui() if (begin_fields("##turntablenamefields", 0.3f)) { field_row("Name##turntablename"); - ImGui::InputTextWithHint("##turntablename", turntable_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CharsNoBlank); + // the name of the bridge track: plain ASCII as every name the editor gives (editor_track::name_valid) + bool dropped{false}; + ImGui::InputTextWithHint("##turntablename", turntable_name_for_new().c_str(), tool.name, sizeof(tool.name), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CallbackCharFilter, ascii_only_filter, &dropped); + if (dropped) + tool.status = refused(STR("The name can hold ASCII only: no Polish letters or other characters outside of it")); ImGui::EndTable(); } gesture_rows({{"Drag", "from where the centre goes, turning the bridge"}, {"LMB on a free end", "the turntable lines up with it, at its end"}, {"Shift+LMB", "no lining up"}}); diff --git a/application/editoruipanels.cpp b/application/editoruipanels.cpp index fa78e645b..305508f4b 100644 --- a/application/editoruipanels.cpp +++ b/application/editoruipanels.cpp @@ -168,14 +168,14 @@ void itemproperties_panel::update(scene::basic_node *Node) } } */ - textline = format(STR_C("Name: %s"), (node->name().empty() ? std::string{STR_C("(no name)")} : Bezogonkow(node->name())).c_str()) + "\n" + format(STR_C("Type: %s"), node->node_type.c_str()); + textline = format(STR_C("Name: %s"), (node->name().empty() ? std::string{STR_C("(no name)")} : data_name_to_utf8(node->name())).c_str()) + "\n" + format(STR_C("Type: %s"), node->node_type.c_str()); text_lines.emplace_back(textline, Global.UITextColor); textline = format(STR_C("Location: %.2f, %.2f, %.2f (distance %.1f m)"), node->location().x, node->location().y, node->location().z, glm::length(glm::dvec3{node->location().x, 0.0, node->location().z} - glm::dvec3{camera.Pos.x, 0.0, camera.Pos.z})) + "\nUUID: " + node->uuid.to_string(); if (scene::Layers.valid(node->layer())) { - textline += "\n" + format(STR_C("Layer: %s"), Bezogonkow(scene::Layers.layer(node->layer()).name).c_str()); + textline += "\n" + format(STR_C("Layer: %s"), data_name_to_utf8(scene::Layers.layer(node->layer()).name).c_str()); } text_lines.emplace_back(textline, Global.UITextColor); @@ -288,7 +288,7 @@ void itemproperties_panel::update(scene::basic_node *Node) { textline += ", "; } - textline += event.second != nullptr ? Bezogonkow(event.second->m_name) : event.first + STR_C(" (missing)"); + textline += event.second != nullptr ? data_name_to_utf8(event.second->m_name) : event.first + STR_C(" (missing)"); } textline += "] "; } @@ -301,7 +301,7 @@ void itemproperties_panel::update(scene::basic_node *Node) textline = format(STR_C("Data: [%s] [%.2f] [%.2f]"), subnode->Text().c_str(), subnode->Value1(), subnode->Value2()); text_lines.emplace_back(textline, Global.UITextColor); - textline = format(STR_C("Track: %s"), (subnode->asTrackName.empty() ? std::string{STR_C("(none)")} : Bezogonkow(subnode->asTrackName)).c_str()); + textline = format(STR_C("Track: %s"), (subnode->asTrackName.empty() ? std::string{STR_C("(none)")} : data_name_to_utf8(subnode->asTrackName)).c_str()); text_lines.emplace_back(textline, Global.UITextColor); } @@ -890,7 +890,7 @@ void nodebank_panel::render_templates_list(std::string const &Filter) ImGui::TextDisabled(" %s", entry.category.c_str()); } category = &entry.category; - auto const label{(entry.category.empty() ? " " : " ") + entry.name + " (" + Bezogonkow(entry.file) + ")##inc" + std::to_string(entryidx)}; + auto const label{(entry.category.empty() ? " " : " ") + entry.name + " (" + data_name_to_utf8(entry.file) + ")##inc" + std::to_string(entryidx)}; if (list_item(label.c_str(), entry.statement == m_selectedtemplate)) m_selectedtemplate = entry.statement; ++listed; @@ -1706,7 +1706,7 @@ std::string layer_content(scene::basic_layer const &Layer) std::string layer_name(scene::layer_handle const Layer) { - return scene::Layers.valid(Layer) ? Bezogonkow(scene::Layers.layer(Layer).name) : std::string{STR_C("(none)")}; + return scene::Layers.valid(Layer) ? data_name_to_utf8(scene::Layers.layer(Layer).name) : std::string{STR_C("(none)")}; } // button which can be greyed out, with an explanation shown when it's hovered @@ -1750,7 +1750,7 @@ void itemproperties_panel::render_include() auto &include{*m_include}; include.active = false; - ImGui::Text(STR_C("include: %s"), Bezogonkow(include.target).c_str()); + ImGui::Text(STR_C("include: %s"), data_name_to_utf8(include.target).c_str()); if (false == include.info.name.empty()) { ImGui::TextDisabled("%s", include.info.name.c_str()); @@ -2282,7 +2282,7 @@ void includes_panel::render_list() { auto const &entry{entries[m_listed[row]]}; auto const marker{entry.complete ? std::string{STR_C("[ready]")} + " " : entry.described ? std::string{STR_C("[incomplete]")} + " " : std::string{}}; - auto const label{marker + Bezogonkow(entry.file) + (entry.name.empty() ? "" : " - " + entry.name) + "##" + std::to_string(m_listed[row])}; + auto const label{marker + data_name_to_utf8(entry.file) + (entry.name.empty() ? "" : " - " + entry.name) + "##" + std::to_string(m_listed[row])}; if (false == entry.described) { ImGui::PushStyleColor(ImGuiCol_Text, ImGui::GetStyleColorVec4(ImGuiCol_TextDisabled)); @@ -2312,7 +2312,7 @@ void includes_panel::render_list() void includes_panel::render_description() { ImGui::Separator(); - ImGui::Text("%s", Bezogonkow(m_file).c_str()); + ImGui::Text("%s", data_name_to_utf8(m_file).c_str()); input_text(STR_C("Name"), m_info.name); input_text(STR_C("Category"), m_info.category); input_text(STR_C("Description"), m_info.description); @@ -2390,7 +2390,7 @@ void includes_panel::render_description() { std::string error; m_statuserror = false == editor_includes::save(m_file, m_info, error); - m_status = m_statuserror ? error : format(STR_C("Description saved in \"%s\""), Bezogonkow(m_file).c_str()); + m_status = m_statuserror ? error : format(STR_C("Description saved in \"%s\""), data_name_to_utf8(m_file).c_str()); if (false == m_statuserror) { EditorIncludes.update(m_file); diff --git a/application/scenarioloadermode.cpp b/application/scenarioloadermode.cpp index 568966503..85f81a337 100644 --- a/application/scenarioloadermode.cpp +++ b/application/scenarioloadermode.cpp @@ -40,6 +40,20 @@ bool scenarioloader_mode::update() { // waiting for network connection return true; + if (m_closing > 0) { + // the programs of the materials made ready a few at a frame, the loading screen with its bar kept on the screen and the + // window answering meanwhile; then on to the simulation + auto const [done, total] { GfxRenderer->Prewarm_Shaders( 50.0 ) }; + if( done < total ) { + m_userinterface->set_progress( static_cast( done ) * 100.f / static_cast( total ), 0.f ); + return true; + } + m_closing = 0; + Application.pop_mode(); + Application.push_mode( eu07_application::mode::driver ); + return true; + } + if (!state) { WriteLog("using simulation seed: " + std::to_string(Global.random_seed), logtype::generic); WriteLog("using simulation starting timestamp: " + std::to_string(Global.starting_timestamp), logtype::generic); @@ -98,8 +112,12 @@ bool scenarioloader_mode::update() { WriteLog( "Scenario loading time: " + std::to_string( std::chrono::duration_cast( std::chrono::system_clock::now() - timestart ).count() ) + " seconds" ); // TODO: implement and use next mode cue - Application.pop_mode(); - Application.push_mode( eu07_application::mode::driver ); + // the loading screen stays, saying the graphics are being prepared, until the programs are ready (above). + // at the top of the screen: the bottom is taken by the trivia and by the texts some backgrounds carry. the interface + // of this mode is always the loader's, made in the constructor + m_userinterface->set_progress(std::string{}); + static_cast(*m_userinterface).set_notice(STR("Preparing the graphics (takes longer at the first start of a new version)")); + m_closing = 1; return true; } @@ -117,6 +135,8 @@ void scenarioloader_mode::enter() { Application.set_title( Global.AppName + " (" + Global.SceneryFile + ")" ); m_userinterface->set_progress(STR("Loading scenery")); + // the notice of a load before is gone + static_cast(*m_userinterface).set_notice({}); } // maintenance method, called when the mode is deactivated diff --git a/application/scenarioloadermode.h b/application/scenarioloadermode.h index db23458dd..41ae75f68 100644 --- a/application/scenarioloadermode.h +++ b/application/scenarioloadermode.h @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. class scenarioloader_mode : public application_mode { std::shared_ptr state; std::chrono::system_clock::time_point timestart; + // the scenery is loaded: the loading screen kept while the renderer prepares the programs (gfx_renderer::Prewarm_Shaders()) + int m_closing{0}; public: // constructors diff --git a/application/scenarioloaderuilayer.cpp b/application/scenarioloaderuilayer.cpp index 75a8af3cb..cb7f1045b 100644 --- a/application/scenarioloaderuilayer.cpp +++ b/application/scenarioloaderuilayer.cpp @@ -287,7 +287,9 @@ void scenarioloader_ui::render_() ImVec2 text_pos = ImVec2(screen_size.x - 16 * scale - text_size.x, 16 * scale); draw_list->AddText(text_pos, IM_COL32_WHITE, sceneryName.c_str()); } - + + render_notice(draw_list, scale, font_scale_mult); + // Progress bar at the bottom of the screen const auto p1 = ImVec2(0, Global.window_size.y - 2); const auto p2 = ImVec2(Global.window_size.x * m_progress, Global.window_size.y); @@ -296,6 +298,25 @@ void scenarioloader_ui::render_() ImGui::End(); } +// the notice centred at the top of the screen on a dark plate, so it reads on any background. the bottom of the screen +// is taken by the trivia and by the texts some backgrounds carry +void scenarioloader_ui::render_notice( ImDrawList *Drawlist, float const Scale, float const Fontscale ) const +{ + if (m_notice.empty()) + return; + + ImGui::SetWindowFontScale(Fontscale * 0.6f); + auto const text_size{ImGui::CalcTextSize(m_notice.c_str())}; + auto const padding{16.f * Scale}; + auto const top{48.f * Scale}; + ImVec2 const text_pos{(static_cast(Global.window_size.x) - text_size.x) * 0.5f, top + padding}; + Drawlist->AddRectFilled( + ImVec2{text_pos.x - padding, top}, + ImVec2{text_pos.x + text_size.x + padding, text_pos.y + text_size.y + padding}, + IM_COL32(0, 0, 0, 170), 8.f * Scale); + Drawlist->AddText(text_pos, IM_COL32_WHITE, m_notice.c_str()); +} + void scenarioloader_ui::generate_gradient_tex() { constexpr int image_width = 1; diff --git a/application/scenarioloaderuilayer.h b/application/scenarioloaderuilayer.h index 45a0ba5bd..edea429f8 100644 --- a/application/scenarioloaderuilayer.h +++ b/application/scenarioloaderuilayer.h @@ -12,16 +12,23 @@ http://mozilla.org/MPL/2.0/. #include "application/uilayer.h" #include "launcher/deferred_image.h" +#include +#include + class scenarioloader_ui : public ui_layer { int m_gradient_overlay_width; int m_gradient_overlay_height; std::uint64_t m_gradient_overlay_tex; // imgui_renderer image deferred_image m_loading_wheel_frames[60]; std::vector m_trivia; + std::string m_notice; // shown at the top of the screen, clear of the trivia and the texts of the backgrounds at the bottom public: scenarioloader_ui(); void render_() override; + // a notice for the player at the top of the screen, such as that the graphics are being prepared; empty hides it + void set_notice( std::string_view const Text ) { m_notice = Text; } private: + void render_notice( ImDrawList *Drawlist, float Scale, float Fontscale ) const; /// /// Loads random trivia from lang/trivia.json diff --git a/application/uitranscripts.cpp b/application/uitranscripts.cpp index 7ce360530..dc0aec0eb 100644 --- a/application/uitranscripts.cpp +++ b/application/uitranscripts.cpp @@ -38,8 +38,8 @@ TTranscripts::Add( std::string const &txt, bool /*backgorund*/ ) { if( true == txt.empty() ) { return; } - std::string asciitext{ txt }; win1250_to_ascii( asciitext ); // TODO: launch relevant conversion table based on language - cParser parser( asciitext ); + // the captions are read as their files have them (windows-1250, the newer ones utf-8) and shown with their letters + cParser parser( txt ); while( true == parser.getTokens( 3, false, "[]\n" ) ) { float begin{ 0.f }; @@ -49,14 +49,14 @@ TTranscripts::Add( std::string const &txt, bool /*backgorund*/ ) { >> begin >> end >> transcript; - AddLine( transcript, static_cast(0.10 * begin), static_cast(0.12 * end), false ); + AddLine( data_text_to_utf8( transcript ), static_cast(0.10 * begin), static_cast(0.12 * end), false ); } // try to handle malformed(?) cases with no show/hide times std::string transcript; parser >> transcript; while( false == transcript.empty() ) { // WriteLog( "Transcript text with no display/hide times: \"" + transcript + "\"" ); - AddLine( transcript, 0.0, static_cast(0.12 * static_cast(transcript.size())), false ); + AddLine( data_text_to_utf8( transcript ), 0.0, static_cast(0.12 * static_cast(transcript.size())), false ); transcript = ""; parser >> transcript; } } diff --git a/audio/audio.cpp b/audio/audio.cpp index 9965909e1..7e3c3e44b 100644 --- a/audio/audio.cpp +++ b/audio/audio.cpp @@ -407,7 +407,7 @@ buffer_manager::find_file( std::string const &Filename ) const { auto const lookup { FileExists( { Filename }, - { ".ogg", ".flac", ".wav" } ) }; + { ".ogg", ".flac", ".wav", ".opus", ".mp3" } ) }; return lookup.first + lookup.second; } diff --git a/audio/audiorenderer.cpp b/audio/audiorenderer.cpp index 0d4c94ff2..2323c6b82 100644 --- a/audio/audiorenderer.cpp +++ b/audio/audiorenderer.cpp @@ -14,14 +14,131 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "vehicle/Camera.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "simulation/simulation.h" #include "vehicle/Train.h" +#include +#include +#include +#include + namespace audio { openal_renderer renderer; bool event_volume_change { false }; +namespace { + +struct named_value { + std::string_view name; + ALCint value; +}; + +// values of sound.outputmode, as ALC_OUTPUT_MODE_SOFT takes them +constexpr std::array output_modes { + named_value{ "mono", ALC_MONO_SOFT }, + named_value{ "stereo", ALC_STEREO_SOFT }, + named_value{ "stereo-basic", ALC_STEREO_BASIC_SOFT }, + named_value{ "uhj", ALC_STEREO_UHJ_SOFT }, + named_value{ "headphones", ALC_STEREO_HRTF_SOFT }, + named_value{ "quad", ALC_QUAD_SOFT }, + named_value{ "5.1", ALC_SURROUND_5_1_SOFT }, + named_value{ "6.1", ALC_SURROUND_6_1_SOFT }, + named_value{ "7.1", ALC_SURROUND_7_1_SOFT } }; + +// returns: ALC_OUTPUT_MODE_SOFT value for given sound.outputmode, or nothing for auto +std::optional output_mode_value( std::string_view const Name ) { + + if( Name == "auto" ) { return std::nullopt; } + if( auto const lookup { std::ranges::find( output_modes, Name, &named_value::name ) }; lookup != std::end( output_modes ) ) { + return lookup->value; + } + WriteLog( std::format( "sound: unknown output mode \"{}\", left to the library", Name ) ); + return std::nullopt; +} + +// returns: name of given ALC_OUTPUT_MODE_SOFT value +std::string_view output_mode_name( ALCint const Value ) { + + if( auto const lookup { std::ranges::find( output_modes, Value, &named_value::value ) }; lookup != std::end( output_modes ) ) { + return lookup->name; + } + return "other"; +} + +// returns: ALC_TRUE or ALC_FALSE for given on/off option, or nothing for auto +std::optional switch_value( std::string_view const Name ) { + + if( Name == "on" ) { return ALC_TRUE; } + if( Name == "off" ) { return ALC_FALSE; } + return std::nullopt; +} + +// returns: name of an output device without the prefix OpenAL Soft may put before the names of the devices it lists on +// Windows. it opens a device named either way, so the name in eu07.ini can come with it or without +std::string_view bare_output_name( std::string_view const Name ) { + + constexpr std::string_view prefix { "OpenAL Soft on " }; + return Name.starts_with( prefix ) ? Name.substr( prefix.size() ) : Name; +} + +// opens the output device of sound.openal.renderer. the library names devices in UTF-8, but the starter writes eu07.ini +// in code page 1250, so a name that fails as written is tried as 1250 text too. a device found neither way, unplugged +// say, leaves the default one rather than no sound at all: Fallback is set then, and the name stays as it is, for +// follow_output() to go back to that device once it's there again. the name is set to what got opened, for a later reopen +ALCdevice *open_output_device( bool &Fallback ) { + + Fallback = false; + if( Global.AudioRenderer.empty() ) { + return ::alcOpenDevice( nullptr ); + } + if( auto *device { ::alcOpenDevice( Global.AudioRenderer.c_str() ) } ) { + return device; + } + if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) { + if( auto *device { ::alcOpenDevice( utf8name.c_str() ) } ) { + Global.AudioRenderer = utf8name; + return device; + } + } + ErrorLog( std::format( "sound: audio device \"{}\" set in eu07.ini isn't available, using the default one", Global.AudioRenderer ) ); + Fallback = true; + return ::alcOpenDevice( nullptr ); +} + +// splits a list of null-terminated names ending with an empty name, as alcGetString gives device lists +std::vector split_name_list( ALCchar const *List ) { + + std::vector names; + while( List != nullptr && *List != '\0' ) { + auto const &name { names.emplace_back( List ) }; + List += name.size() + 1; + } + return names; +} + +// returns: the file the OpenAL library the game plays through was loaded from, in UTF-8, or nothing where that can't +// be told. the game takes OpenAL32.dll from its own folder before the one of the system, so this shows which one it got +std::optional openal_library_path() { +#ifdef _WIN32 + auto *module { ::GetModuleHandleW( L"OpenAL32.dll" ) }; + if( module == nullptr ) { return std::nullopt; } + std::wstring path( 4096, wchar_t{} ); + auto const length { static_cast( ::GetModuleFileNameW( module, path.data(), static_cast( path.size() ) ) ) }; + if( ( length <= 0 ) || ( length >= static_cast( path.size() ) ) ) { return std::nullopt; } + auto const size { ::WideCharToMultiByte( CP_UTF8, 0, path.data(), length, nullptr, 0, nullptr, nullptr ) }; + if( size <= 0 ) { return std::nullopt; } + std::string result( static_cast( size ), char{} ); + ::WideCharToMultiByte( CP_UTF8, 0, path.data(), length, result.data(), size, nullptr, nullptr ); + return result; +#else + return std::nullopt; +#endif +} + +} // namespace + float const EU07_SOUND_CUTOFFRANGE { 3000.f }; // 2750 m = max expected emitter spawn range, plus safety margin float const EU07_SOUND_VELOCITYLIMIT { 250 / 3.6f }; // 343 m/sec ~= speed of sound; arbitrary limit of 250 km/h @@ -94,18 +211,16 @@ openal_source::update( double const Deltatime, glm::vec3 const &Listenervelocity --sound_index; sound_change = true; // potentially adjust starting point of the last buffer (to reduce chance of reverb effect with multiple, looping copies playing) - if( controller->start() > 0.f && sounds.size() == 1 ) { - ALint bufferid; - ::alGetSourcei( - id, - AL_BUFFER, - &bufferid ); - ALint buffersize; - ::alGetBufferi( bufferid, AL_SIZE, &buffersize ); + if( controller->start() > 0.f && sounds.size() == 1 && last_buffer != audio::null_resource ) { + // NOTE: the buffer is the one queued last, not the one the source reports: for a source with queued + // buffers AL_BUFFER is 0 in OpenAL Soft 1.18 (the one the game comes with), and in the newer ones + // once the source has stopped. alGetBufferi() on buffer 0 fails with AL_INVALID_NAME + ALint buffersize { 0 }; + ::alGetBufferi( last_buffer, AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } @@ -178,6 +293,7 @@ openal_source::sync_with( sound_properties const &State ) { sound_range : 5 ) }; // range of -1 means sound of unlimited range, positioned at the listener ::alSourcef( id, AL_REFERENCE_DISTANCE, range * ( 1.f / 16.f ) * State.soundproofing ); + renderer.soundproofing_filter( id, State.soundproofing_hf ); } if( sound_range != -1 ) { auto const rangesquared { sound_range * sound_range }; @@ -276,22 +392,159 @@ openal_renderer::~openal_renderer() { if( m_context != nullptr ) { m_fmradio.release(); } // the receiver owns implementation-side resources, which have to go before the context does + if( m_lowpassfilter != 0 ) { m_alDeleteFilters( 1, &m_lowpassfilter ); } + ::alcMakeContextCurrent( nullptr ); if( m_context != nullptr ) { ::alcDestroyContext( m_context ); } if( m_device != nullptr ) { ::alcCloseDevice( m_device ); } } -// invoked by OpenAL (possibly on an internal thread) on device events; only flags the change, -// the actual reopen is done on the main thread in update() +// invoked by OpenAL (possibly on an internal thread) on device events; only notes what happened, +// the device is checked and opened again on the main thread, in follow_output() void ALC_APIENTRY openal_renderer::device_event_callback( ALCenum eventtype, ALCenum devicetype, ALCdevice */*device*/, ALCsizei /*length*/, ALCchar const */*message*/, void *userparam ) noexcept { if( userparam == nullptr ) { return; } if( devicetype == ALC_CAPTURE_DEVICE_SOFT ) { return; } // only care about playback output - if( eventtype != ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT - && eventtype != ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT ) { return; } - static_cast( userparam )->m_outputchanged.store( true ); + auto event { 0u }; + switch( eventtype ) { + case ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT: { event = output_follower::default_changed; break; } + case ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT: { event = output_follower::device_removed; break; } + case ALC_EVENT_TYPE_DEVICE_ADDED_SOFT: { event = output_follower::device_added; break; } + default: { return; } + } + static_cast( userparam )->m_outputevents.fetch_or( event ); +} + +// true unless the device is known to have lost its output +bool +openal_renderer::output_connected() const { + + if( false == m_candetectdisconnect ) { return true; } + ALCint connected { ALC_TRUE }; + ::alcGetIntegerv( m_device, ALC_CONNECTED, 1, &connected ); + return connected != ALC_FALSE; +} + +// name of the output the device plays on +std::string +openal_renderer::output_name() const { + + auto const *name { ::alcGetString( m_device, ALC_DEVICE_SPECIFIER ) }; + return name != nullptr ? name : "?"; +} + +// moves the playback to the specified output, null being the default one of the system. the context, the buffers +// and the sources stay as they are. returns true when the device plays on that output afterwards +bool +openal_renderer::reopen_output_on( ALCchar const *Devicename ) { + + auto const reopened { m_alcReopenDeviceSOFT( m_device, Devicename, m_contextattributes.data() ) == ALC_TRUE }; + ::alcGetError( m_device ); // a failure is handled here, don't leave its error code behind + // NOTE: the library reports success also when the new output was opened but failed to start, + // leaving the device disconnected. the result alone can't be trusted + return reopened && output_connected(); +} + +// returns: the name under which the library lists the device set in eu07.ini, or nothing if it isn't listed. the name +// is matched as written and read as code page 1250 text (the starter writes eu07.ini in it), with or without the prefix +// of the library. every attempt to open a device stops the playback for a moment, even one that fails, so a device that +// isn't there isn't tried +std::optional +openal_renderer::find_preferred_output() const { + + if( Global.AudioRenderer.empty() ) { return std::nullopt; } + auto const devices { output_devices() }; + auto const listed = [&devices]( std::string_view const Name ) -> std::optional { + auto const match { std::ranges::find_if( devices, [Name]( std::string_view const Device ) { + return bare_output_name( Device ) == bare_output_name( Name ); } ) }; + if( match == std::end( devices ) ) { return std::nullopt; } + return *match; + }; + if( auto name { listed( Global.AudioRenderer ) } ) { return name; } + if( auto const utf8name { win1250_to_utf8( Global.AudioRenderer ) }; utf8name != Global.AudioRenderer ) { + return listed( utf8name ); + } + return std::nullopt; +} + +// opens the output anew: the device set in eu07.ini if there is one and it works, the default one of the system otherwise +void +openal_renderer::reopen_output( output_follower::clock::time_point const Now ) { + + auto const pinned { false == Global.AudioRenderer.empty() }; + if( pinned ) { + auto name { find_preferred_output() }; + if( false == name.has_value() && false == output_connected() ) { + // not listed under a name that matches, but there is no sound to break anyway: the library may know it still + name = Global.AudioRenderer; + } + if( name.has_value() && reopen_output_on( name->c_str() ) ) { + Global.AudioRenderer = *name; + m_output.succeeded( false, Now ); + WriteLog( std::format( "sound: audio output changed, reopened playback on \"{}\"", output_name() ) ); + return; + } + } + reopen_default_output( pinned, Now ); +} + +// opens the default output of the system. Pinned: it stands in for the device set in eu07.ini +void +openal_renderer::reopen_default_output( bool const Pinned, output_follower::clock::time_point const Now ) { + + if( reopen_output_on( nullptr ) ) { + m_output.succeeded( Pinned, Now ); + WriteLog( std::format( "sound: audio output changed, reopened playback on \"{}\"{}", output_name(), + Pinned ? " (the default output; the device set in eu07.ini isn't available)" : "" ) ); + return; + } + if( m_output.failed( Now ) ) { + // logged once, the following attempts are silent until one works + ErrorLog( "sound: audio output lost and no output could be opened, retrying until one works" ); + } +} + +// while the default output plays in place of the device set in eu07.ini: moves back to that device if it is listed again +void +openal_renderer::restore_preferred_output( output_follower::clock::time_point const Now ) { + + auto const name { find_preferred_output() }; + if( false == name.has_value() ) { + // some other device came, or the one set isn't listed yet: nothing tried, the playback goes on undisturbed + m_output.restore_failed( Now ); + return; + } + if( reopen_output_on( name->c_str() ) ) { + Global.AudioRenderer = *name; + m_output.succeeded( false, Now ); + WriteLog( std::format( "sound: the audio device set in eu07.ini is available again, reopened playback on \"{}\"", output_name() ) ); + return; + } + WriteLog( std::format( "sound: warning: the audio device \"{}\" set in eu07.ini is listed again but doesn't play, staying on the default output", *name ) ); + if( false == output_connected() ) { + // the device opened but didn't start. the library had let go of the default output before it tried, so that's gone too + reopen_default_output( true, Now ); + } + m_output.restore_failed( Now ); +} + +// keeps the sound on an output that works. OpenAL neither moves to another output on its own nor recovers one it lost: +// a device whose output is gone stops all its sources and stays silent, even after the very same output comes back, +// until it is opened again +void +openal_renderer::follow_output() { + + if( m_alcReopenDeviceSOFT == nullptr ) { return; } + + auto const now { output_follower::clock::now() }; + auto const events { m_outputevents.exchange( 0u ) }; + switch( m_output.update( events, now, [this]() { return output_connected(); } ) ) { + case output_follower::action::reopen: { reopen_output( now ); break; } + case output_follower::action::restore_preferred: { restore_preferred_output( now ); break; } + default: { break; } + } } audio::buffer_handle @@ -327,7 +580,9 @@ openal_renderer::init() { return false; } ::alDistanceModel( AL_INVERSE_DISTANCE_CLAMPED ); - ::alDopplerFactor( 0.25f ); + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + WriteLog( "sound: " + device_status() ); // all done m_ready = true; return true; @@ -392,36 +647,8 @@ openal_renderer::update( double const Deltatime ) { if (m_alcDeviceResumeSOFT) m_alcDeviceResumeSOFT(m_device); - // keep audio on the correct output (OpenAL won't re-route on its own). Reopen playback on the - // current default output when the active device is lost (headphones unplugged) or the system - // default output changes (headphones plugged back in, or default switched in Windows). NULL - // device name selects the current default; context and sources are preserved. - if( m_alcReopenDeviceSOFT != nullptr && Global.AudioRenderer.empty() ) { - bool needsreopen{ false }; - if( m_usedeviceevents ) { - // event-driven: the callback (any thread) flags default-output / device-removal changes - needsreopen = m_outputchanged.exchange( false ); - } - else if( m_candetectdisconnect ) { - // fallback without ALC_SOFT_system_events: poll for a hard disconnect at ~1 Hz - m_devicechecktime += Deltatime; - if( m_devicechecktime >= 1.0 ) { - m_devicechecktime = 0.0; - ALCint connected{ ALC_TRUE }; - ::alcGetIntegerv( m_device, ALC_CONNECTED, 1, &connected ); - needsreopen = ( connected == ALC_FALSE ); - } - } - if( needsreopen ) { - if( m_alcReopenDeviceSOFT( m_device, nullptr, m_contextattributes ) == ALC_TRUE ) { - auto const *nowon { (char const *)::alcGetString( nullptr, ALC_DEFAULT_ALL_DEVICES_SPECIFIER ) }; - WriteLog( "sound: audio output changed, reopened playback on \"" + std::string{ nowon ? nowon : "?" } + "\"" ); - } - else { - ErrorLog( "sound: audio output changed but reopening on the default device failed (will retry)" ); - } - } - } + // keep the sound on an output that works + follow_output(); // update listener // gain @@ -569,6 +796,7 @@ openal_renderer::fetch_source() { glm::vec3 zero_pos{ 0.f, 0.f, 0.f }; ::alSourcefv( newsource.id, AL_POSITION, glm::value_ptr( zero_pos ) ); ::alSourcefv( newsource.id, AL_VELOCITY, glm::value_ptr( zero_pos ) ); + configure_source( newsource.id ); } return newsource; @@ -590,7 +818,9 @@ openal_renderer::init_caps() { } // NOTE: default value of audio renderer variable is empty string, meaning argument of NULL i.e. 'preferred' device - m_device = ::alcOpenDevice( Global.AudioRenderer.empty() ? nullptr : Global.AudioRenderer.c_str() ); + auto const pinned { false == Global.AudioRenderer.empty() }; + auto fallback { false }; + m_device = open_output_device( fallback ); if( m_device == nullptr ) { ErrorLog( "Failed to obtain audio device" ); return false; @@ -611,10 +841,16 @@ openal_renderer::init_caps() { WriteLog( "Supported extensions: " + std::string{ (char *)::alcGetString( m_device, ALC_EXTENSIONS ) } ); - ALCint attr[3] = { ALC_MONO_SOURCES, Global.audio_max_sources, 0 }; // request more sounds - std::copy( std::begin( attr ), std::end( attr ), std::begin( m_contextattributes ) ); // cached for device reopen + // the device options (output mode, HRTF and the like) are known once the device is open + m_hasoutputmode = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_mode" ) == ALC_TRUE ); + m_haslimiter = ( alcIsExtensionPresent( m_device, "ALC_SOFT_output_limiter" ) == ALC_TRUE ); + if( alcIsExtensionPresent( m_device, "ALC_SOFT_HRTF" ) == ALC_TRUE ) { + m_alcGetStringiSOFT = (LPALCGETSTRINGISOFT)alcGetProcAddress( m_device, "alcGetStringiSOFT" ); + m_alcResetDeviceSOFT = (LPALCRESETDEVICESOFT)alcGetProcAddress( m_device, "alcResetDeviceSOFT" ); + } + m_contextattributes = device_attributes(); // cached for device reopen - m_context = ::alcCreateContext( m_device, attr ); + m_context = ::alcCreateContext( m_device, m_contextattributes.data() ); if( m_context == nullptr ) { ErrorLog( "Failed to create audio context" ); return false; @@ -628,9 +864,11 @@ openal_renderer::init_caps() { // the version reported above is the OpenAL API spec level (always 1.1); the real implementation // version string (e.g. "1.1 ALSOFT 1.24.2") is only queryable once a context is current + std::string libraryversion; if( auto const *libversion { (char const *)::alGetString( AL_VERSION ) } ) { crashreport_add_info( "openal_lib_version", libversion ); WriteLog( "sound: library version: " + std::string{ libversion } ); + libraryversion = libversion; } // Initialize all extension function pointers @@ -656,22 +894,301 @@ openal_renderer::init_caps() { if( !m_alcReopenDeviceSOFT ) WriteLog( "sound: warning: extension ALC_SOFT_reopen_device not found; audio output device changes won't be followed" ); - // prefer event-driven output following (ALC_SOFT_system_events) over polling: it reliably - // catches both device removal and default-output changes, incl. re-plugging headphones + // have the system report the changes of the outputs (ALC_SOFT_system_events) where it can. this goes next to + // the periodic check of the connection done by follow_output(), as not every loss of the output is reported if( m_alcReopenDeviceSOFT != nullptr && alcIsExtensionPresent( m_device, "ALC_SOFT_system_events" ) == ALC_TRUE ) { m_alcEventControlSOFT = (LPALCEVENTCONTROLSOFT)alcGetProcAddress( m_device, "alcEventControlSOFT" ); m_alcEventCallbackSOFT = (LPALCEVENTCALLBACKSOFT)alcGetProcAddress( m_device, "alcEventCallbackSOFT" ); if( m_alcEventControlSOFT != nullptr && m_alcEventCallbackSOFT != nullptr ) { m_alcEventCallbackSOFT( &openal_renderer::device_event_callback, this ); - ALCenum const events[]{ ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT, ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT }; - m_alcEventControlSOFT( 2, events, ALC_TRUE ); + std::array const events { ALC_EVENT_TYPE_DEFAULT_DEVICE_CHANGED_SOFT, ALC_EVENT_TYPE_DEVICE_REMOVED_SOFT, ALC_EVENT_TYPE_DEVICE_ADDED_SOFT }; + m_alcEventControlSOFT( static_cast( events.size() ), events.data(), ALC_TRUE ); m_usedeviceevents = true; WriteLog( "sound: following audio output device changes via ALC_SOFT_system_events" ); } } + if( m_alcReopenDeviceSOFT != nullptr && false == m_usedeviceevents ) { + WriteLog( "sound: warning: extension ALC_SOFT_system_events not found; a lost audio output is recovered, a change of the default one and the return of the device set in eu07.ini aren't followed" ); + } + m_output.start( pinned, fallback, output_follower::clock::now() ); + log_output_following( libraryversion, pinned ); + + init_extensions(); return true; } +// says in one line which OpenAL library the game got and whether the sound follows the output device with it. an old +// library (OpenAL Soft before 1.23, as the one the game came with) is left as it is: the sound plays on the device opened +// at the start, as it always did, and only the log says why it doesn't move +void +openal_renderer::log_output_following( std::string_view const Version, bool const Pinned ) const { + + auto const library { openal_library_path() }; + auto const name { std::format( "\"{}\"{}", Version.empty() ? std::string_view{ "unknown" } : Version, + library.has_value() ? std::format( " from \"{}\"", *library ) : std::string{} ) }; + if( ( m_alcReopenDeviceSOFT == nullptr ) || ( false == m_usedeviceevents ) ) { + WriteLog( std::format( "sound: warning: the OpenAL library {} is too old to follow a change of the audio output; " + "the sound stays on the device opened at the start. OpenAL Soft 1.23 or newer, as OpenAL32.dll in the game folder, follows it", name ) ); + return; + } + if( Pinned ) { + WriteLog( std::format( "sound: the OpenAL library {} follows the audio output: the device set in eu07.ini (sound.openal.renderer), " + "the default output of the system while that one isn't there", name ) ); + return; + } + WriteLog( std::format( "sound: the OpenAL library {} follows the audio output: the default output of the system", name ) ); +} + +// resolves the entry points of the context extensions the settings use: source resampler, EFX filters +void +openal_renderer::init_extensions() { + + if( alIsExtensionPresent( "AL_SOFT_source_resampler" ) == AL_TRUE ) { + m_alGetStringiSOFT = (LPALGETSTRINGISOFT)alGetProcAddress( "alGetStringiSOFT" ); + } + if( alcIsExtensionPresent( m_device, "ALC_EXT_EFX" ) == ALC_TRUE ) { + m_alGenFilters = (LPALGENFILTERS)alGetProcAddress( "alGenFilters" ); + m_alDeleteFilters = (LPALDELETEFILTERS)alGetProcAddress( "alDeleteFilters" ); + m_alFilteri = (LPALFILTERI)alGetProcAddress( "alFilteri" ); + m_alFilterf = (LPALFILTERF)alGetProcAddress( "alFilterf" ); + m_hasefx = ( m_alGenFilters != nullptr && m_alDeleteFilters != nullptr && m_alFilteri != nullptr && m_alFilterf != nullptr ); + } + if( false == m_hasefx ) { + return; + } + ::alGetError(); + m_alGenFilters( 1, &m_lowpassfilter ); + m_alFilteri( m_lowpassfilter, AL_FILTER_TYPE, AL_FILTER_LOWPASS ); + if( ::alGetError() != AL_NO_ERROR ) { + WriteLog( "sound: warning: EFX low-pass filter not available" ); + m_lowpassfilter = 0; + } +} + +// returns: attributes of the device and the context made from the settings. with the defaults they are as before the +// settings existed, which leaves output mode, HRTF, limiter and mixing rate to the library +std::vector +openal_renderer::device_attributes() const { + + // sound.maxsources, kept for an OpenAL other than OpenAL Soft: that one gives at least 256 sources whatever is asked + std::vector attributes { ALC_MONO_SOURCES, Global.audio_max_sources }; + auto const add { [ &attributes ]( ALCint const Key, ALCint const Value ) { + attributes.push_back( Key ); + attributes.push_back( Value ); } }; + + if( auto const mode { output_mode_value( Global.AudioOutputMode ) }; mode && m_hasoutputmode ) { + add( ALC_OUTPUT_MODE_SOFT, *mode ); + } + if( m_alcGetStringiSOFT != nullptr ) { + if( auto const hrtf { switch_value( Global.AudioHrtf ) } ) { + add( ALC_HRTF_SOFT, *hrtf ); + } + if( auto const index { hrtf_index( Global.AudioHrtfProfile ) }; index >= 0 ) { + add( ALC_HRTF_ID_SOFT, index ); + } + } + if( auto const limiter { switch_value( Global.AudioLimiter ) }; limiter && m_haslimiter ) { + add( ALC_OUTPUT_LIMITER_SOFT, *limiter ); + } + if( Global.AudioFrequency > 0 ) { + add( ALC_FREQUENCY, Global.AudioFrequency ); + } + attributes.push_back( 0 ); + return attributes; +} + +// returns: index of the named HRTF data set, or -1 if the name is empty or unknown +int +openal_renderer::hrtf_index( std::string const &Name ) const { + + if( Name.empty() ) { return -1; } + auto const profiles { hrtf_profiles() }; + if( auto const lookup { std::ranges::find( profiles, Name ) }; lookup != std::end( profiles ) ) { + return static_cast( std::distance( std::begin( profiles ), lookup ) ); + } + WriteLog( std::format( "sound: unknown HRTF data set \"{}\", left to the library", Name ) ); + return -1; +} + +// returns: index of the resampler of the settings, the library's default with none set, or -1 without the extension +ALint +openal_renderer::resampler_index() const { + + if( m_alGetStringiSOFT == nullptr ) { return -1; } + if( false == Global.AudioResampler.empty() ) { + auto const names { resamplers() }; + if( auto const lookup { std::ranges::find( names, Global.AudioResampler ) }; lookup != std::end( names ) ) { + return static_cast( std::distance( std::begin( names ), lookup ) ); + } + WriteLog( std::format( "sound: unknown resampler \"{}\", the library's default used", Global.AudioResampler ) ); + } + return ::alGetInteger( AL_DEFAULT_RESAMPLER_SOFT ); +} + +// sets the options of the settings on a source +void +openal_renderer::configure_source( ALuint const Source ) const { + + if( m_resampler >= 0 ) { + ::alSourcei( Source, AL_SOURCE_RESAMPLER_SOFT, m_resampler ); + } + if( m_hasefx ) { + ::alSourcef( Source, AL_AIR_ABSORPTION_FACTOR, Global.AudioAirAbsorption ); + } +} + +// sets the EFX low-pass filter of a source for given soundproofing: the stronger the soundproofing, the more muffled +void +openal_renderer::soundproofing_filter( ALuint const Source, float const Soundproofing ) const { + + if( m_lowpassfilter == 0 ) { return; } + // a soundproofing left undefined by the data (-1, which OpenAL doesn't take as the gain either) isn't muffled + if( false == Global.AudioLowpass || Soundproofing < 0.f || Soundproofing >= 1.f ) { + ::alSourcei( Source, AL_DIRECT_FILTER, AL_FILTER_NULL ); + return; + } + // the level is set by the gain already, the filter takes away only the high frequencies + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAIN, 1.f ); + m_alFilterf( m_lowpassfilter, AL_LOWPASS_GAINHF, std::clamp( Soundproofing, 0.f, 1.f ) ); + ::alSourcei( Source, AL_DIRECT_FILTER, static_cast( m_lowpassfilter ) ); +} + +// returns: names of the output devices +std::vector +openal_renderer::output_devices() const { + + if( ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ) { + return split_name_list( ::alcGetString( nullptr, ALC_ALL_DEVICES_SPECIFIER ) ); + } + return split_name_list( ::alcGetString( nullptr, ALC_DEVICE_SPECIFIER ) ); +} + +// returns: names of the HRTF data sets of the device +std::vector +openal_renderer::hrtf_profiles() const { + + std::vector names; + if( m_device == nullptr || m_alcGetStringiSOFT == nullptr ) { return names; } + ALCint count { 0 }; + ::alcGetIntegerv( m_device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &count ); + for( ALCint index = 0; index < count; ++index ) { + auto const *name { m_alcGetStringiSOFT( m_device, ALC_HRTF_SPECIFIER_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: names of the resamplers +std::vector +openal_renderer::resamplers() const { + + std::vector names; + if( m_alGetStringiSOFT == nullptr ) { return names; } + auto const count { ::alGetInteger( AL_NUM_RESAMPLERS_SOFT ) }; + for( ALint index = 0; index < count; ++index ) { + auto const *name { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, index ) }; + names.emplace_back( name != nullptr ? name : "" ); + } + return names; +} + +// returns: what the device ended up with +std::string +openal_renderer::device_status() const { + + if( m_device == nullptr ) { return "no audio device"; } + + auto const namequery { ::alcIsExtensionPresent( nullptr, "ALC_ENUMERATE_ALL_EXT" ) == ALC_TRUE ? ALC_ALL_DEVICES_SPECIFIER : ALC_DEVICE_SPECIFIER }; + auto const *devicename { ::alcGetString( m_device, namequery ) }; + ALCint frequency { 0 }; + ::alcGetIntegerv( m_device, ALC_FREQUENCY, 1, &frequency ); + auto status { std::format( "device \"{}\", {} Hz", devicename != nullptr ? devicename : "?", frequency ) }; + + if( m_hasoutputmode ) { + ALCint mode { 0 }; + ::alcGetIntegerv( m_device, ALC_OUTPUT_MODE_SOFT, 1, &mode ); + status += std::format( ", output {}", output_mode_name( mode ) ); + } + if( m_alcGetStringiSOFT != nullptr ) { + ALCint hrtf { ALC_FALSE }; + ::alcGetIntegerv( m_device, ALC_HRTF_SOFT, 1, &hrtf ); + if( hrtf == ALC_TRUE ) { + auto const *hrtfname { ::alcGetString( m_device, ALC_HRTF_SPECIFIER_SOFT ) }; + status += std::format( ", HRTF \"{}\"", hrtfname != nullptr ? hrtfname : "?" ); + } + else { + status += ", HRTF off"; + } + } + if( m_resampler >= 0 ) { + auto const *resamplername { m_alGetStringiSOFT( AL_RESAMPLER_NAME_SOFT, m_resampler ) }; + status += std::format( ", resampler {}", resamplername != nullptr ? resamplername : "?" ); + } + if( m_lowpassfilter != 0 ) { + status += ", EFX"; + } + return status; +} + +// applies changed device options without a restart: reopens the device, or resets it with an older library +bool +openal_renderer::apply_device_settings() { + + if( false == m_ready ) { return false; } + + m_contextattributes = device_attributes(); + auto applied { false }; + if( m_alcReopenDeviceSOFT != nullptr ) { + auto const pinned { false == Global.AudioRenderer.empty() }; + if( pinned ) { + // the playback is opened anew here anyway, so a name the list doesn't match is tried too + auto const name { find_preferred_output().value_or( Global.AudioRenderer ) }; + applied = reopen_output_on( name.c_str() ); + if( applied ) { Global.AudioRenderer = name; } + } + auto const fallback { pinned && false == applied }; + if( false == applied ) { + // no device set, or the one set isn't there: the default one, which follow_output() leaves once the other is back + applied = reopen_output_on( nullptr ); + } + if( applied ) { + // the device may have been changed in the settings: the output is followed by what is set now + m_output.start( pinned, fallback, output_follower::clock::now() ); + } + } + else if( m_alcResetDeviceSOFT != nullptr ) { + // without ALC_SOFT_reopen_device another output device takes a restart + applied = ( m_alcResetDeviceSOFT( m_device, m_contextattributes.data() ) == ALC_TRUE ); + if( applied ) { + WriteLog( "sound: this audio library can't switch the output device while running, a changed device takes a restart" ); + } + } + if( applied ) { + WriteLog( "sound: audio settings applied, " + device_status() ); + } + else { + ErrorLog( "sound: the audio device settings take a restart to apply" ); + } + return applied; +} + +// applies changed source options to every source; spare sources get them when taken +void +openal_renderer::apply_source_settings() { + + if( false == m_ready ) { return; } + + ::alDopplerFactor( Global.AudioDoppler ); + m_resampler = resampler_index(); + for( auto const &source : m_sources ) { + if( source.id != audio::null_resource ) { + configure_source( source.id ); + } + } + // the filters follow with the gain, which this flag makes every source set anew + audio::event_volume_change = true; +} + } // audio \ No newline at end of file diff --git a/audio/audiorenderer.h b/audio/audiorenderer.h index 9dbd8b168..afa73ee93 100644 --- a/audio/audiorenderer.h +++ b/audio/audiorenderer.h @@ -10,7 +10,9 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "audio/audio.h" +#include "audio/outputfollow.h" #include "audio/fmradio.h" +#include "audio/startsample.h" #include "model/ResourceManager.h" #include "application/uitranscripts.h" @@ -19,6 +21,8 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include +#include // Definicje dla OpenAL 1.25 jeśli brakuje #ifndef ALC_CONNECTED @@ -48,6 +52,9 @@ struct sound_properties { sound_category category { sound_category::unknown }; float gain { 1.f }; float soundproofing { 1.f }; + // the soundproofing of what stands between the sound and the listener, without the volume trim of the sounds placed + // on top of the listener: what the low-pass filter muffles the sound by (sound.efx.lowpass) + float soundproofing_hf { 1.f }; std::uintptr_t soundproofing_stamp { ~std::uintptr_t{0} }; }; @@ -66,6 +73,7 @@ struct openal_source { using buffer_sequence = std::vector; ALuint id { audio::null_resource }; + ALuint last_buffer { audio::null_resource }; // the buffer queued last, the one left playing once those before it are done sound_source *controller { nullptr }; uint32_sequence sounds; int sound_index { 0 }; @@ -124,6 +132,20 @@ public: // provides access to the broadcast radio receiver audio::fm_radio &fmradio() { return m_fmradio; } + // choices the library offers, for the settings + std::vector output_devices() const; + std::vector hrtf_profiles() const; + std::vector resamplers() const; + // what the device ended up with: device, mixing rate, output mode, HRTF, resampler + std::string device_status() const; + // applies changed device options (sound.openal.renderer, outputmode, hrtf, limiter, frequency) + // without a restart. returns: false if the library can't do it + bool apply_device_settings(); + // applies changed source options (sound.resampler, doppler, efx.*) to every source + void apply_source_settings(); + // sets the EFX low-pass filter of a source for given soundproofing (sound.efx.lowpass) + void soundproofing_filter( ALuint const Source, float const Soundproofing ) const; + glm::dvec3 cached_camerapos; private: @@ -131,6 +153,21 @@ private: using source_sequence = std::stack; bool init_caps(); + void init_extensions(); + void log_output_following( std::string_view Version, bool Pinned ) const; + std::vector device_attributes() const; + int hrtf_index( std::string const &Name ) const; + ALint resampler_index() const; + void configure_source( ALuint const Source ) const; + // keeps the sound on an output that works, see audio::output_follower + void follow_output(); + void reopen_output( output_follower::clock::time_point const Now ); + void restore_preferred_output( output_follower::clock::time_point const Now ); + void reopen_default_output( bool const Pinned, output_follower::clock::time_point const Now ); + std::optional find_preferred_output() const; + bool reopen_output_on( ALCchar const *Devicename ); + bool output_connected() const; + std::string output_name() const; audio::openal_source fetch_source(); ALCdevice *m_device { nullptr }; @@ -152,18 +189,31 @@ private: LPALCDEVICEPAUSESOFT m_alcDevicePauseSOFT { nullptr }; LPALCDEVICERESUMESOFT m_alcDeviceResumeSOFT { nullptr }; LPALCREOPENDEVICESOFT m_alcReopenDeviceSOFT { nullptr }; + LPALCRESETDEVICESOFT m_alcResetDeviceSOFT { nullptr }; + LPALCGETSTRINGISOFT m_alcGetStringiSOFT { nullptr }; + LPALGETSTRINGISOFT m_alGetStringiSOFT { nullptr }; + LPALGENFILTERS m_alGenFilters { nullptr }; + LPALDELETEFILTERS m_alDeleteFilters { nullptr }; + LPALFILTERI m_alFilteri { nullptr }; + LPALFILTERF m_alFilterf { nullptr }; + + bool m_hasoutputmode { false }; // ALC_SOFT_output_mode + bool m_haslimiter { false }; // ALC_SOFT_output_limiter + bool m_hasefx { false }; // ALC_EXT_EFX, with its filter entry points + ALuint m_lowpassfilter { 0 }; // shared low-pass filter, its parameters are copied to a source when attached + ALint m_resampler { -1 }; // index of the resampler set on the sources, or -1 to leave the library's default bool m_candetectdisconnect { false }; - ALCint m_contextattributes[3] { 0, 0, 0 }; - double m_devicechecktime { 0.0 }; + std::vector m_contextattributes; // cached for device reopen + output_follower m_output; // decides when the device is opened again - // ALC_SOFT_system_events: event-driven following of output-device / default-output changes. - // Preferred over polling because it reliably catches both device removal and default changes - // (e.g. re-plugging headphones), which alcGetString(DEFAULT_ALL_DEVICES) does not report live. + // ALC_SOFT_system_events: the system reports output devices coming, going and the default one changing. + // Used next to the periodic check of the connection, not in place of it: the events catch a change of the + // default output at once (e.g. re-plugging headphones), the check catches the losses the system doesn't report. LPALCEVENTCONTROLSOFT m_alcEventControlSOFT { nullptr }; LPALCEVENTCALLBACKSOFT m_alcEventCallbackSOFT { nullptr }; bool m_usedeviceevents { false }; - std::atomic m_outputchanged { false }; // set from the (possibly off-thread) event callback + std::atomic m_outputevents { 0u }; // bits of output_follower::event, set from the (possibly off-thread) event callback static void ALC_APIENTRY device_event_callback( ALCenum eventtype, ALCenum devicetype, ALCdevice *device, ALCsizei length, ALCchar const *message, void *userparam ) noexcept; }; diff --git a/audio/audiorenderer_extra.h b/audio/audiorenderer_extra.h index 430f594b3..fb38816fc 100644 --- a/audio/audiorenderer_extra.h +++ b/audio/audiorenderer_extra.h @@ -19,6 +19,7 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ if( id != audio::null_resource && !buffers.empty()) { ::alSourceQueueBuffers( id, static_cast( buffers.size() ), buffers.data() ); + last_buffer = buffers.back(); ::alSourceRewind( id ); // sound controller can potentially request playback to start from certain buffer point // for multipart sounds the offset is applied only to last piece during playback @@ -29,12 +30,12 @@ openal_source::bind( sound_source *Controller, uint32_sequence Sounds, Iterator_ } else { // move playback start to specified point in 0-1 range - ALint buffersize; + ALint buffersize { 0 }; ::alGetBufferi( buffers.front(), AL_SIZE, &buffersize ); ::alSourcei( id, AL_SAMPLE_OFFSET, - static_cast( controller->start() * ( buffersize / sizeof( std::int16_t ) ) ) ); + audio::start_sample( controller->start(), buffersize ) ); } } diff --git a/audio/outputfollow.h b/audio/outputfollow.h new file mode 100644 index 000000000..46d36dff7 --- /dev/null +++ b/audio/outputfollow.h @@ -0,0 +1,154 @@ +/* +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 + +#include +#include + +namespace audio { + +// decides when the playback device has to be opened again, so the sound follows the output of the system: +// headphones pulled out or plugged in, another default output chosen, the device taken away and given back. +// holds no OpenAL state of its own: the renderer feeds it the events of the system and the state of the device, +// and does what it answers. kept apart from the renderer so the unit tests can run it +class output_follower { + +public: + using clock = std::chrono::steady_clock; + + // what the system reported since the last update, combined as bits + enum event : unsigned { + default_changed = 1u << 0, // another output became the default one + device_removed = 1u << 1, // an output is gone, possibly the one in use + device_added = 1u << 2 // an output appeared, possibly the one set in eu07.ini + }; + + enum class action { + none, + reopen, // open the output anew: the one set in eu07.ini if there is one and it works, the default one otherwise + restore_preferred // playing on the default output in place of the one set in eu07.ini: see whether that one is back + }; + + // how often a working device is asked whether it is still connected. the system doesn't report every loss of the + // output (a stream invalidated without the device being removed), so the events alone leave the game silent + static constexpr std::chrono::milliseconds check_interval { 1000 }; + // delays between the attempts to open an output while there is none that works. every attempt runs on the main + // thread and may take tens of milliseconds, so after the first minute without an output they thin out + static constexpr std::chrono::milliseconds retry_min { 500 }; + static constexpr std::chrono::milliseconds retry_max { 4000 }; + static constexpr std::chrono::milliseconds retry_late_after { 60000 }; + static constexpr std::chrono::milliseconds retry_late { 30000 }; + // while there is no output an event of the system has the next attempt made at once, but not sooner than this after + // the last one: a device coming (a bluetooth headset, say) reports a burst of events over a few frames + static constexpr std::chrono::milliseconds event_retry_min { 250 }; + // the device set in eu07.ini can be reported before it is ready to play. a move back to it that didn't work out is + // tried again after 1, 2 and 4 s; then the next arrival of a device is waited for, so a device that never works + // (taken in exclusive mode by another program, say) doesn't break the sound every few seconds + static constexpr std::chrono::milliseconds restore_retry_min { 1000 }; + static constexpr int restore_retries { 3 }; + + // Pinned: a device is set in eu07.ini (sound.openal.renderer); Fallback: it couldn't be opened and the default one plays instead + void + start( bool const Pinned, bool const Fallback, clock::time_point const Now ) { + m_pinned = Pinned; + m_fallback = Pinned && Fallback; + m_lost = false; + m_retrydelay = retry_min; + m_nextcheck = Now + check_interval; + m_restorefailures = 0; + } + + // Events: bits of event; Connected: callable telling whether the device still works, called only when a check is due + template + action + update( unsigned const Events, clock::time_point const Now, Probe_ const &Connected ) { + if( m_lost ) { + // no working output: whatever the system reports may be the output coming back, so it brings the next attempt + // forward. otherwise it comes after a growing delay + if( Events != 0u ) { m_nextcheck = std::min( m_nextcheck, m_lastattempt + event_retry_min ); } + return ( Now >= m_nextcheck ) ? action::reopen : action::none; + } + if( ( Now >= m_nextcheck ) || ( ( Events & device_removed ) != 0u ) ) { + m_nextcheck = Now + check_interval; + if( false == Connected() ) { return action::reopen; } + } + if( follows_default() && ( ( Events & default_changed ) != 0u ) ) { return action::reopen; } + if( m_fallback ) { + if( ( Events & device_added ) != 0u ) { + // a device that appears may be the one set: a fresh round of attempts + m_restorefailures = 0; + return action::restore_preferred; + } + if( ( m_restorefailures > 0 ) && ( m_restorefailures <= restore_retries ) && ( Now >= m_nextrestore ) ) { + return action::restore_preferred; + } + } + return action::none; + } + + // an output was opened and works. Fallback: it is the default one, in place of the one set in eu07.ini + void + succeeded( bool const Fallback, clock::time_point const Now ) { + m_fallback = m_pinned && Fallback; + m_lost = false; + m_retrydelay = retry_min; + m_nextcheck = Now + check_interval; + // the default output standing in again doesn't end the round of attempts to move back to the device set + if( false == m_fallback ) { m_restorefailures = 0; } + } + + // no output could be opened. returns true for the first failure in a row, the one worth a line in the log + bool + failed( clock::time_point const Now ) { + auto const first { false == m_lost }; + if( first ) { + m_loststart = Now; + m_retrydelay = retry_min; + } + else if( Now - m_loststart >= retry_late_after ) { + m_retrydelay = retry_late; + } + else { + m_retrydelay = std::min( m_retrydelay * 2, retry_max ); + } + m_lost = true; + m_lastattempt = Now; + m_nextcheck = Now + m_retrydelay; + return first; + } + + // the move back to the device set in eu07.ini didn't work out: the device isn't listed, or it didn't open or start. + // schedules the next attempt of the round, if there is one left + void + restore_failed( clock::time_point const Now ) { + ++m_restorefailures; + if( m_restorefailures <= restore_retries ) { + m_nextrestore = Now + restore_retry_min * ( 1 << ( m_restorefailures - 1 ) ); + } + } + + bool lost() const { return m_lost; } + bool fallback() const { return m_fallback; } + // a device set in eu07.ini is left alone for as long as it works; otherwise the sound goes where the system sends it + bool follows_default() const { return false == m_pinned || m_fallback; } + +private: + bool m_pinned { false }; + bool m_fallback { false }; + bool m_lost { false }; // the output is gone and none could be opened so far + std::chrono::milliseconds m_retrydelay { retry_min }; + clock::time_point m_nextcheck {}; // of the connection while the output works, the next attempt to open one while it doesn't + clock::time_point m_loststart {}; // the first failed attempt of the current loss + clock::time_point m_lastattempt {}; // the last failed attempt, while the output is lost + int m_restorefailures { 0 }; // failed moves back to the device set since it last appeared, 0 when none is due + clock::time_point m_nextrestore {}; +}; + +} // namespace audio diff --git a/audio/radiostream.cpp b/audio/radiostream.cpp index 6d231265a..b2673dfa5 100644 --- a/audio/radiostream.cpp +++ b/audio/radiostream.cpp @@ -738,7 +738,7 @@ radio_stream::~radio_stream() { // out of memory while retiring the worker: its thread still stops and is joined by its own destructor below } - // NOTE: destructors of retired workers wait for their threads to finish + // NOTE: destructors of retired workers wait for their threads to finish, before the buffers and the mutexes go (radiostream.h) } // starts reception of specified stream, dropping current one if there's any diff --git a/audio/radiostream.h b/audio/radiostream.h index 5088f1fcc..6300016b2 100644 --- a/audio/radiostream.h +++ b/audio/radiostream.h @@ -92,8 +92,6 @@ class radio_stream void reap(); // members std::string m_url; - worker m_worker; - std::vector m_retired; // workers which were told to stop but may still be busy closing their connection std::atomic m_state{state::idle}; std::atomic m_rate{0}; mutable std::mutex m_mutex; // guards the sample buffer and the generation counter @@ -103,6 +101,10 @@ class radio_stream std::size_t m_samplescount{0}; std::mutex m_messagesmutex; std::deque m_messages; + // the workers last: the members go in the reverse order, so their threads, which store() and post() to the members above, are + // joined before those go + worker m_worker; + std::vector m_retired; // workers which were told to stop but may still be busy closing their connection }; } // namespace audio diff --git a/audio/sound.cpp b/audio/sound.cpp index 0cd17e0f7..020ea4601 100644 --- a/audio/sound.cpp +++ b/audio/sound.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "simulation/simulation.h" #include "audio/audiorenderer_extra.h" +#include "physics/vehicle.h" // constructors sound_source::sound_source( sound_placement const Placement, float const Range ) : @@ -977,7 +978,7 @@ sound_source::update_soundproofing() { listenervehicle ? 3 : // external view 4 ) : // free roam view - listenervehicle->MoverParameters->CabOccupied ) }; // some internal view so we can be sure listener isn't a nullptr + listenervehicle->physics->CabOccupied() ) }; // some internal view so we can be sure listener isn't a nullptr // location-based gain factor: std::uintptr_t soundproofingstamp = reinterpret_cast( listenervehicle ) @@ -1010,6 +1011,8 @@ sound_source::update_soundproofing() { occupiedcab ); } } + // the walls muffle the sound, the trim below only lowers its volume + m_properties.soundproofing_hf = m_properties.soundproofing; // for ambient sounds reduce their volume to account for their placement right on top of the listener if( m_range < -1 ) { m_properties.soundproofing *= 0.4f; diff --git a/audio/startsample.cpp b/audio/startsample.cpp new file mode 100644 index 000000000..673dda151 --- /dev/null +++ b/audio/startsample.cpp @@ -0,0 +1,28 @@ +/* +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 "audio/startsample.h" + +#include +#include + +namespace audio { + +int start_sample( float const Start, int const Buffersize ) { + + auto const samples { Buffersize / static_cast( sizeof( std::int16_t ) ) }; + if( samples <= 0 + || false == ( Start > 0.f ) ) { // also a NaN + return 0; + } + return std::min( static_cast( std::min( Start, 1.f ) * static_cast( samples ) ), samples - 1 ); +} + +} // audio diff --git a/audio/startsample.h b/audio/startsample.h new file mode 100644 index 000000000..e9837a3a9 --- /dev/null +++ b/audio/startsample.h @@ -0,0 +1,19 @@ +/* +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 + +namespace audio { + +// the sample a sound set to start at Start (a fraction of its length, 0-1) begins to play from, in a buffer of +// Buffersize bytes of 16 bit mono samples (the sound buffers are all made so, see upload_sound()). always a sample +// the buffer has: OpenAL rejects an offset at or past the end with AL_INVALID_VALUE. 0 for an empty buffer +int start_sample( float const Start, int const Buffersize ); + +} // audio diff --git a/blackbox_doc.md b/blackbox_doc.md index 5dc8f7b71..ce2108484 100644 --- a/blackbox_doc.md +++ b/blackbox_doc.md @@ -411,7 +411,7 @@ moved more than 0.5 m or turned more than 0.05 rad. |---------|------------------------------------------------------------------------------| | `f64` | t | | `u8` | mode: 0 from the cab, 1 an outside view of the user's train, 2 the free camera, 3 the debug camera | -| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by; 0 in the other modes | +| `u8` | the outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 the orbit around a vehicle, 5 the shunting view from above, 6 beside a coupling, 7 trackside; 0 in the other modes | | `u32` | number of the vehicle the camera goes with, 0 for none | | `dvec3` | position | | `f32` | heading [rad] of where it looks, as that of a vehicle: towards (sin, cos) in (x, z) | @@ -550,6 +550,26 @@ What is coupled: 0x01 the coupler, 0x02 the brake pipe, 0x04 the control (multip voltage, 0x10 the gangway, 0x20 the main reservoir pipe, 0x40 the train heating, 0x80 a coupling not to be undone in shunting (between the cars of a unit). +### 0x38 derailment + +A vehicle off the track, with `physics.derailment new` in `eu07.ini`: it doesn't follow the track any more +and moves on the ground by itself until it stops. Written when it leaves the track, and when it comes to +rest off it, looked at every second. A vehicle put back on the rails and derailed again is written again. + +| type | field | +|---------|--------------------------------------------------------------------------------| +| `f64` | t | +| `u32` | number of the vehicle | +| `u8` | 0 it left the track, 1 it came to rest off it | +| `u8` | what derailed it: 1 the flange climbed the rail, 2 it overturned in a curve, 3 the end of the track, 4 a coupling of a vehicle off the track pulled it off, 5 a collision | +| `dvec3` | position of the vehicle | +| `f32` | heading [rad] of its front, from +z towards +x | +| `f32` | speed [km/h], positive along its front | +| `f32` | offset [m] from the axis of the track at the place nearest to it, to the left of its front positive | +| `f32` | roll [rad] of its body, to the left positive: about 1.57 on its side | +| `f32` | distance [m] it went on the ground since it left the rails | +| `u8` | 1 lying on its side, 0 upright | + ### 0x3F end Last, when the simulator closes. diff --git a/ci_shadervalidator/build.sh b/ci_shadervalidator/build.sh index f299f63c9..fbf4ab39c 100755 --- a/ci_shadervalidator/build.sh +++ b/ci_shadervalidator/build.sh @@ -10,11 +10,14 @@ # Every .vert/.frag/.geom/.comp of shaders/ogl46 is compiled as the game compiles the source (features on and off, and the # variant of the multi draws) and to SPIR-V for opengl from the file as it is (as glslc makes the binaries of # shaders/ogl46bin); the constants written in shaders/ogl46/common.glsl are compared with those of the game. The shaders of -# shaders/vk14 are compiled to SPIR-V for vulkan. +# shaders/vk14 are compiled to SPIR-V for vulkan1.4 (vulkan1.3, said at the start and at the end of the run, where +# glslangValidator doesn't know 1.4; ./validateshaders --vulkan-env vulkan1.4 fails then instead), and the constants written in +# shaders/vk14/common.glsl are compared with rendering/vulkan14/vulkan14bindings.h and those of the game. The temporary files +# are made with unique names and removed afterwards. # Exit code is 0 when all shaders pass, 1 otherwise; failing shaders are listed at the end. # # The validator's own stdafx.h and utilities/{Globals,Logs}.h stand in for the game's headers: its directory comes first # on the include path, before the repository root. set -e cd "$(dirname "$0")" -g++ -std=c++20 -O1 ../ref/glad/src/glad.c ../gl/glsl_common.cpp ../rendering/common/shadersource.cpp main.cpp -I. -I.. -I../ref/glad/include -I../ref/glm -o validateshaders +${CXX:-g++} -std=c++20 -O1 ../ref/glad/src/glad.c ../gl/glsl_common.cpp ../rendering/common/shadersource.cpp main.cpp -I. -I.. -I../ref/glad/include -I../ref/glm -o validateshaders diff --git a/ci_shadervalidator/main.cpp b/ci_shadervalidator/main.cpp index 171324d5e..96af5c0ed 100644 --- a/ci_shadervalidator/main.cpp +++ b/ci_shadervalidator/main.cpp @@ -4,11 +4,22 @@ #include "utilities/Globals.h" #include "utilities/Logs.h" #include -#include -#include +#include #include #include +#include +#include +#include +#include +#include +#include +#include #include +#ifdef _WIN32 +#include +#else +#include +#endif _global Global; @@ -17,9 +28,91 @@ namespace std::string const ogl46_dir{"../shaders/ogl46/"}; std::string const vk14_dir{"../shaders/vk14/"}; -// the vulkan environment glslang is asked for: 1.4 where it knows it +std::string const vk14_bindings_header{"../rendering/vulkan14/vulkan14bindings.h"}; +// the vulkan environment glslang is asked for: 1.4 where it knows it, or the one given with --vulkan-env std::string vulkan_env{"vulkan1.4"}; +// writes the text to a new file with a unique name in the temporary directory of the system and returns its path, or an empty +// string when it cannot be written. the file is created exclusively, so nothing put in a shared /tmp under a name known in +// advance (a file or a link) is written through +std::string write_temp_file(std::string_view const Text) +{ + std::string path{(std::filesystem::temp_directory_path() / "maszyna-shader-XXXXXX").string()}; + std::FILE *file{nullptr}; +#ifdef _WIN32 + // no mkstemp() in the CRT; a random name, opened with "x", which fails when the file is there already + std::random_device random; + for (int attempt = 0; (attempt < 100) && (file == nullptr); ++attempt) + { + path.replace(path.size() - 6, 6, std::to_string(100000 + random() % 900000)); + if (fopen_s(&file, path.c_str(), "wx") != 0) + file = nullptr; + } +#else + if (int const descriptor{mkstemp(path.data())}; descriptor != -1) + { + file = fdopen(descriptor, "w"); + if (file == nullptr) + { + close(descriptor); + std::remove(path.c_str()); + } + } +#endif + if (file == nullptr) + return {}; + + bool const written{std::fwrite(Text.data(), 1, Text.size(), file) == Text.size()}; + if ((std::fclose(file) != 0) || !written) + { + std::remove(path.c_str()); + return {}; + } + return path; +} + +// a file of the validator in the temporary directory, removed when it goes. glslangValidator writes its output and the shell +// its log into files made this way, so they too are made exclusively beforehand +class temp_file +{ + public: + explicit temp_file(std::string_view const Text) : m_path{write_temp_file(Text)} {} + ~temp_file() + { + if (false == m_path.empty()) + std::remove(m_path.c_str()); + } + temp_file(temp_file const &) = delete; + temp_file &operator=(temp_file const &) = delete; + + std::string const &path() const + { + return m_path; + } + + private: + std::string m_path; +}; + +// runs glslangValidator with the arguments, what it writes into a log file. false when the file can't be made; Result is the +// exit code, Log what it wrote +bool run_glslang(std::string_view const Arguments, int &Result, std::string &Log) +{ + temp_file const log{std::string_view{}}; + if (log.path().empty()) + { + std::cerr << "cannot make a file in the temporary directory" << std::endl; + return false; + } + auto const command{std::format("glslangValidator {} > \"{}\" 2>&1", Arguments, log.path())}; + Result = system(command.c_str()); + std::ifstream file(log.path()); + std::ostringstream text; + text << file.rdbuf(); + Log = text.str(); + return true; +} + char const *stage_name(gfx::shader_stage const Stage) { switch (Stage) @@ -44,17 +137,25 @@ bool check_text(gfx::shader_source const &Source, std::string const &Mode) ErrorLogged = false; return false; } - std::ofstream file("/tmp/shader"); - file << Source.text; - file.close(); + temp_file const source{Source.text}; + temp_file const output{std::string_view{}}; + if (source.path().empty() || output.path().empty()) + { + std::cerr << "cannot write the shader to the temporary directory" << std::endl; + return false; + } // the output only when it fails (glslangValidator names the file it compiled to spir-v) - auto const command{"glslangValidator " + Mode + " -S " + stage_name(Source.stage) + " /tmp/shader" + (Mode.empty() ? "" : " -o /tmp/shader.spv") + " > /tmp/shader.log 2>&1"}; - int ret = system(command.c_str()); + std::string arguments{std::format("{} -S {} \"{}\"", Mode, stage_name(Source.stage), source.path())}; + if (false == Mode.empty()) + arguments += std::format(" -o \"{}\"", output.path()); + int ret{-1}; + std::string log; + if (false == run_glslang(arguments, ret, log)) + return false; if (ret != 0) { - std::ifstream log("/tmp/shader.log"); - std::cerr << std::endl << log.rdbuf(); + std::cerr << std::endl << log; std::cerr << "(source strings:"; for (std::size_t i = 0; i < Source.files.size(); ++i) std::cerr << " " << i << ": " << Source.files[i]; @@ -146,49 +247,159 @@ bool is_stage(std::filesystem::path const &Path) return (ext == ".frag" || ext == ".geom" || ext == ".vert" || ext == ".comp"); } +// whether glslangValidator compiles a shader for the vulkan environment +bool knows_vulkan_env(std::string_view const Env) +{ + temp_file const source{"#version 460\nvoid main() { gl_Position = vec4(0.0); }\n"}; + temp_file const output{std::string_view{}}; + if (source.path().empty() || output.path().empty()) + return false; + int ret{-1}; + std::string log; + return run_glslang(std::format("-V --target-env {} -S vert \"{}\" -o \"{}\"", Env, source.path(), output.path()), ret, log) && (ret == 0); +} + +// the bindings of rendering/vulkan14/vulkan14bindings.h as the #define lines vk14::binding_preamble() makes of them, read from +// the header as it is (the code of the renderer needs vulkan and glslang, which the validator is built without). Names: all +// the constants of the header +std::string vk14_binding_defines(std::unordered_set &Names) +{ + std::ifstream file(vk14_bindings_header); + std::regex const constant{R"(^\s*constexpr\s+std::uint32_t\s+(\w+)\s*=\s*(\d+)\s*;)"}; + std::string defines; + std::string line; + while (std::getline(file, line)) + { + std::smatch match; + if (false == std::regex_search(line, match, constant)) + continue; + Names.insert(match[1].str()); + // the number of the bindings with dynamic offsets is the renderer's own, the shaders aren't given it + if (match[1].str() == "PASS_DYNAMIC_OFFSETS") + continue; + defines += std::format("#define {} {}\n", match[1].str(), match[2].str()); + } + return defines; +} + +// the constants of the game the vulkan renderer gives the shaders as the opengl one does (gl::glsl_common), those of them which +// shaders/vk14/common.glsl writes too; the bindings, which differ between the renderers, left out +std::string vk14_shared_defines(std::unordered_set const &Bindings) +{ + auto const file{gfx::shader_file_defines(gfx::shader_api::vulkan14, "common.glsl", vk14_dir)}; + std::istringstream stream(gl::glsl_common); + std::string defines; + std::string line; + while (std::getline(stream, line)) + { + std::istringstream linestream(line); + std::string directive; + std::string name; + if (!(linestream >> directive >> name) || (directive != "#define") || Bindings.contains(name) || !file.contains(name)) + continue; + defines += line + '\n'; + } + return defines; +} + +// the constants written in common.glsl of a directory compared with those of the game: the binaries are compiled with the +// constants of the file, the game compiles the sources with its own +bool check_constants(std::string_view const Label, gfx::shader_api const Api, std::string const &Directory, std::string const &Preamble) +{ + std::vector differences; + std::cout << "== constants of " << Label << ": " << std::flush; + if (gfx::shader_constants_match(Api, "common.glsl", Preamble, Directory, differences)) + { + std::cout << "the same as in the game" << std::endl; + return true; + } + std::cout << "not the same as in the game:" << std::endl; + for (auto const &difference : differences) + std::cout << " " << difference << std::endl; + return false; +} + +// the vulkan environment from the arguments (--vulkan-env ), empty without it. false on arguments it doesn't know +bool parse_arguments(std::vector const &Arguments, std::string &Required) +{ + if (Arguments.empty()) + return true; + if ((Arguments.size() != 2) || (Arguments[0] != "--vulkan-env")) + return false; + Required = Arguments[1]; + return true; +} + } // namespace -int main() +// --vulkan-env : the vulkan environment to check the shaders of shaders/vk14 against, which glslangValidator has to know; +// without it vulkan1.4, or vulkan1.3 (said at the start and at the end) where glslangValidator doesn't know 1.4 +int main(int argc, char *argv[]) { - if (system("glslangValidator --version > /dev/null 2>&1") != 0) + std::string required; + if (false == parse_arguments(std::vector(argv + 1, argv + argc), required)) + { + std::cerr << "usage: validateshaders [--vulkan-env ]" << std::endl; + return 1; + } + + int ret{-1}; + std::string version; + if (!run_glslang("--version", ret, version) || (ret != 0)) { std::cerr << "glslangValidator not found in PATH" << std::endl; return 1; } + std::cout << "== " << version.substr(0, version.find('\n')) << std::endl; + bool fallback{false}; + if (false == required.empty()) { - std::ofstream file("/tmp/shader_env.vert"); - file << "#version 460\nvoid main() { gl_Position = vec4(0.0); }\n"; + if (false == knows_vulkan_env(required)) + { + std::cerr << "glslangValidator doesn't know the vulkan environment " << required << std::endl; + return 1; + } + vulkan_env = required; } - if (system("glslangValidator -V --target-env vulkan1.4 /tmp/shader_env.vert -o /tmp/shader_env.spv > /dev/null 2>&1") != 0) + else if (false == knows_vulkan_env(vulkan_env)) { vulkan_env = "vulkan1.3"; - std::cout << "== glslangValidator doesn't know vulkan 1.4, the vulkan shaders are checked against vulkan 1.3" << std::endl; + fallback = true; + std::cout << "== WARNING: glslangValidator doesn't know vulkan1.4, the vulkan shaders are checked against vulkan1.3 only" << std::endl; } + std::cout << "== the vulkan shaders are checked against " << vulkan_env << std::endl; bool suc = true; std::vector failed; - // the binaries are compiled with the constants written in common.glsl, the game compiles the sources with its own gl::glsl_common_setup(); - std::vector differences; - std::cout << "== constants of shaders/ogl46/common.glsl: " << std::flush; - if (gl::glsl_common_matches(ogl46_dir, differences)) + if (false == check_constants("shaders/ogl46/common.glsl", gfx::shader_api::opengl46, ogl46_dir, gl::glsl_common)) { - std::cout << "the same as in the game" << std::endl; - } - else - { - std::cout << "not the same as in the game:" << std::endl; - for (auto const &difference : differences) - std::cout << " " << difference << std::endl; suc = false; - failed.push_back("common.glsl"); + failed.emplace_back("ogl46/common.glsl"); + } + std::unordered_set bindings; + if (auto const bindingdefines{vk14_binding_defines(bindings)}; bindingdefines.empty()) + { + std::cout << "== constants of shaders/vk14/common.glsl: " << vk14_bindings_header << " can't be read" << std::endl; + suc = false; + failed.emplace_back("vk14/common.glsl"); + } + else if (false == check_constants("shaders/vk14/common.glsl", gfx::shader_api::vulkan14, vk14_dir, bindingdefines + vk14_shared_defines(bindings))) + { + suc = false; + failed.emplace_back("vk14/common.glsl"); } for (auto const &[directory, api] : {std::pair{ogl46_dir, gfx::shader_api::opengl46}, std::pair{vk14_dir, gfx::shader_api::vulkan14}}) { if (false == std::filesystem::is_directory(directory)) + { + std::cout << "== the directory " << directory << " isn't there" << std::endl; + suc = false; + failed.push_back(directory); continue; + } std::vector names; for (auto &f : std::filesystem::directory_iterator(directory)) if (f.is_regular_file() && is_stage(f.path())) @@ -216,6 +427,8 @@ int main() } } + if (fallback) + std::cout << "==== the vulkan shaders were checked against vulkan1.3, not vulkan1.4" << std::endl; if (suc) std::cout << "==== all checks ok" << std::endl; else { diff --git a/directoryDescription.md b/directoryDescription.md index 6daf6a693..a26eeed9a 100644 --- a/directoryDescription.md +++ b/directoryDescription.md @@ -2,7 +2,7 @@ # File structure | Directory| Description| |--|--| -| McZapkie/ | Train Physics Engine | +| physics/ | Vehicle physics: the physics, brakes, couplers, collisions, derailment | | gl/ | OpenGL Abstraction Layer| | network/ | Multiplayer Support | launcher/ | Scenario/Vehicle Selection (built in starter)| @@ -21,3 +21,4 @@ | utilities/ | Logging, timing, parsing, math, globals, crash reporter | | world/ | Tracks, traction, events, memory cells, stations | | vehicle/ | Train, dynamic objects, driver, gauges, camera | +| docs/ | Documentation | diff --git a/docs/behaviour-changes.md b/docs/behaviour-changes.md new file mode 100644 index 000000000..069bb6e90 --- /dev/null +++ b/docs/behaviour-changes.md @@ -0,0 +1,135 @@ +# Behaviour changes + +Changes accepted in review that players, scenery authors or data makers can notice, for release notes and for +triaging new bug reports ("it worked differently before"). Each entry says what changed, who notices, what +data or eu07.ini it needs, and the pull request (#NNN, MaSzyna-EU07/maszyna). Written against `staging` as of +2026-11-24; the list starts at #266 (merged 2026-11-08). Keys marked "optional" change nothing until the data uses them. +#443 (2026-11-22) reverted #408 and merged `master` into `staging`; of the changes it brought from `master` only the +physics log ones, which replace those of #408, are listed here. + +The last section lists the new optional data keys, so that data makers can find them; they change nothing for +existing data. + +## Logs and files + +- **physicslog has a new last column `VehicleVelocity[km/h]`** (#266). The header line of every physics log + (`physicslog yes`, the black box tapes) changed: `WaterAuxTemp[Deg]` is now followed by a space and the new column, + the vehicle's speed (the second column is the speed of the wheels, which stays 0 while they are locked). + Notices: anyone parsing the logs by column count or by the exact header. The old columns keep their positions. + Needs: nothing. +- **Passing a signal at stop is logged in every session** (#266). The line ` passed signal at danger` + goes to the log for AI and player drivers alike, rail vehicles only, for a signal showing `SetVelocity 0 0` + (not an automatic block signal with `SetVelocity 0 x`). Before it was only counted in test runs. Notices: log.txt + of any scenery with trains running red signals. Needs: nothing. +- **The settings dump at the start of log.txt lists the `test.*` keys** (#266): `test.timeout`, `test.standstill`, + `test.pass_on_standstill`, `test.fail_if_stop_overran`, `test.no_movement_before_pass` (and `test.wall_timeout`, + `test.vehicle` when set), also in normal sessions, with their defaults. They are ignored outside the test mode. +- **The physics logs are written every 2 s by a thread of their own** (#385 on `master`, on `staging` with #443). + The files are opened only for the moment of writing; a crash loses the last 2 s. A log whose file can't be written + keeps its lines and is retried (up to 64 MB in all). `physicslog yes` still logs every driver, road vehicles + included. The closing writes out everything left, with no time limit; only the test mode stops waiting after 2 s. +- **Characters illegal in Windows file names are replaced by `_` in log file names, on every system** (#385, with + #443): a spawned vehicle `spawn_ezt:12` logs to `spawn_ezt_12.dat`. +- **`physicslog.trains yes`** (#385, with #443, new): `.dat` logs of the drivers of rail vehicles only (no passengers, + no road vehicles). **`blackbox yes|no`** (#385, with #443, new): the black box on its own; with no entry it goes with + `physicslog` (or `physicslog.trains`) as before. +- **A failed start ends with exit code 1 and the reason in the log** (#425); a closing from the player's side still + ends with 0. The crash dump written by the Windows crash handler is small by default (stacks and data segments, + tens of MB instead of the whole memory); `crashdump.full yes` brings back the full one. +- **The region cache `.sbt` is written through a temporary file and checked whole when read** (#351): a + damaged file is turned down ("Bad file: ... ignored") and the scenery loads from the text and writes the cache again. + Format unchanged. +- **Test mode** (#266, `--test`; see `tests/scenarios/README.md`): takes no input from outside, does not read the + player's own eu07.ini, writes only its verdict to the standard output, and has exit codes of its own (kept clear of 1 + and 3). + +## AI + +- **AI on a diesel with a shunting gear drives in the shunting mode** (#275). For a `DieselEngine` with + `ShuntModeAllow` (the SM03's 2Ls150 gear) the AI sets the shunting mode when its order is Shunt/Loose_shunt or the + consist is over 224 t. Before, `CurrentSwitch()` took the call for the motor overload relay threshold and the mode + was never set, so the AI always ran in the running mode. Notices: trains of SM03 on a shunting order or over 224 t + get another speed/power curve, so running times in timetables can change. The same PR makes the first move of the + SM42/SP42 switch set the shunt mode at once. Needs: nothing. +- **A Connect first order releases the hand brake** (#339). +- **The AI's wagon inspector sets G/P/R by Cw-1 par. 18-19 and cuts out the brake of wagons without G in a G train** + (#282 and its review commits). A cut-out skipped on the run is done once the train stands. `ai.brakesetting.cw1 no` + in eu07.ini restores the earlier behaviour (default yes). Notices: another brake setting of formed freight and + passenger trains, brakes cut out on some wagons. Needs: nothing. +- **Braking for a stop**: making for a passenger stop leaves room for the brake's fill time only, no look-ahead floor + (#297); the passenger-stop flag no longer flips on every scan (#295); the W4 stop point is shifted by the margin the + stop is judged by (#321); the shunting AI brakes for a stop point again (#409); gradients of 2.5 per mille and more + count as up gradients for the hold and the start (#265). Notices: stops at platforms and signals look different, + running times can move a little. +- **A reduced signal speed ends at a marked end of the interlocking area** (#305): only where the scenery puts the + `SignalAreaEnd` putvalues event. Without it the old rule holds. +- **No multiple-unit control between electric and diesel traction vehicles** (#279): `Attach()` leaves the control + connection out, also for the scenery and the AI (a Vectron and an SM42 no longer run in multiple); logged. + `controlcoupling.enginecheck no` in eu07.ini brings the old behaviour back (default yes). + +## Cab controls + +- **A lone two-state `main_sw` with a latch needs two presses to switch on after a trip** (#277). The single toggle + lever of the line breaker (no `main_on_bt`/`main_off_bt` in the cab) stays where it was put; after the breaker was + knocked out (the converter overload relay of the EP05) the first press puts the lever off, the second closes the + breaker. Applies to every cab with a lone two-state `main_sw`: e6act, ep03, ep05, et21, et22-2000, eu05, wmb10 (list + from the review; the cab files are in the SVN and were not checked here). Notices: whoever expects one press. +- **A `main_off_bt` declared `type: toggle` is the bistable hold coil lever of the ET22 and EP09** (#268): off opens the + breaker and keeps it from closing, back on only feeds the coil. Cabs keep a push button unless their `.mmd` says + `toggle`. +- **The cruise control has a switch of its own** where the secondary controller shunts the field (6Dg, ST45, BR285) + (#391): `tempomat_sw`/`tempomatoff_sw` follow the cruise control, not `ScndCtrl`. Vehicles with only one of the two + are unchanged. No new keys. +- **The compartment lights keyboard toggle** latches also in cabs without `compartmentlights_sw:` or with the on/off + push buttons (#353); the light preset selector with `Wrap=Yes` turns past its end with animation and sound (#345). +- **The HUD shows the radio channel only with the radio fuse closed**; the radio has a fuse and a hint "Close radio + fuse" (#280). +- **Door closure lamp (SOD) of the whole consist** (#291): the three-state lamp (lit locked, blinking released, dark + open) works only on vehicles with `Doors: DoorClosureSignal=Yes` in the `.fiz`. Old EN57/ED72 consists without + `DoorNeedPermit` do not get the key (they would blink at every standstill) and keep the old lamp that shows the lock + of the vehicle's own doors. The eu07.ini switch `doorclosuresignal` was removed: the data decides. Needs: the key + in the `.fiz` of the vehicle whose cab shows the lamp. +- **Separate engine start buttons work only with new data** (#294): the cab controls `mainb_*` and `mainc_*` + (`_sw`, `_on_bt`, `_off_bt`) start the second and third vehicle of a train in multiple, and `Engine: JointEngineStart=No` + stops the cab's `main_*` from touching the other vehicles. According to the data owners no cab in the SVN has + `mainb_*`/`mainc_*` yet (not checked here); without them and without `JointEngineStart=No` nothing changes + (default `Yes`). New commands `linebreakertoggleb/c`, `linebreakeropenb/c`, `linebreakercloseb/c`, no default keys. + +## Physics and scenery + +- **`physics.collisions` defaults to `new`** (#379, with #377 and #378): rail vehicle collisions past the buffers + crush the ends, a vehicle may ride up or be pushed off the track; road traffic keeps the old rule. `old` or + `monitor` in eu07.ini bring back the earlier behaviour. Notices: harder collisions, derailments of struck vehicles, + crushed ends that stay until repaired (resetconsist or repair). `physics.derailment` defaults to `monitor` (the + legacy draw decides, the log tells what the criteria would do); `new` is opt-in. `physics.trackcheck` and + `couplerphysics` (slack, hysteresis and breaking of the coupler; commits c85aab4f to 226155d4, no PR number) are + off by default. +- **Welded track buckles in the heat** (#378) when the scenery or an event sets it; no effect otherwise. +- **The cab shake is taken at the frame's moment** (#403, #414) and no longer moves in steps. +- **Station names keep their Polish letters** in the interface and timetables, a W4 finds its station by one key + (#418). A station of departure written in capitals is still a stop (#343). +- **Timetable service flags** (#398): the header row `[ Flagi AI | ... ]` and station entries such as + `kierownik=nie` change how the AI serves the train; a timetable without them drives as before. Old builds skip the + header row. +- **New putvalues commands** for sceneries: `Crew: ` puts an AI driver in a vehicle or takes + it off (#422); `SignalAreaEnd` (#305, above); the parameter `H` after the coupling of a vehicle prepares it for + hauling dead in a train, the "pullee mode" (#419). + +## Data keys that need new data + +All optional; without the key everything is as before. The data files are in the SVN, not here. + +| Key / file | What it does | Data to change | PR | +|---|---|---|---| +| `.fiz` Cntrl `SBDReleaseDelay` (s, default 0) | The holding brake of a unit with the MED (SBD) lets go only after power was demanded for that long. | Elf files with SBD would get `1.0` (its `IniCDelay`). | #424 | +| `.fiz` Engine `PressureSwitchBrakeCylinder=No`, Cntrl `EmergencyBrakeMainOff=` | Pressure switch of the EP05 with the brake pipe alone; an emergency application on a power position opens the line breaker (pantographs drop with `PantRequiresMain`). | `ep05_v2/ep05.fiz`, `ep05v1.fiz`: `No` and `2.5`. | #421 | +| `.fiz` Cntrl `PantRequiresMain=Yes` | Line breaker closes before the pantographs, on the low voltage; pantograph valve stays open only with the breaker closed; the AI closes the breaker first. | `ep05_v2`, `ep05v1`, `181_cz1.fiz`. | #272 | +| `.fiz` Cntrl `ScndCtrlResistiveLock=Yes` | The field shunt can't be stepped up or down at zero or on a resistive position; it drops to 0 there. | ET21, ET22, EP09 files. | #278 | +| `.fiz` AI `ShuntPantstate=1/2/3` | Pantographs the AI keeps up while shunting. | ET41 files (`203e-a.fiz`, `203e-b.fiz`, `_dsa150`). | #281 | +| `.fiz` Engine `EDBrake`, `EDBrakeFmax/Pmax/V0/V1/Rate/Blending` | Dynamic brake of diesel-electric vehicles. | BR285 and the like. | #394 | +| `.fiz` Doors `DoorClosureSignal=Yes` | SOD lamp of the whole consist, see above. | Vehicles with `DoorNeedPermit`. | #291 | +| `.fiz` Engine `JointEngineStart=No`, `.mmd` `mainb_*`, `mainc_*` | Separate engine start per vehicle (ST43, SP32, SN61), see above. | Cabs and `.fiz` of those vehicles. | #294 | +| `.fiz` security system `AwareOffInShuntMode=Yes` | The SM42's vigilance device (CA) is off in the shunt mode. | SM42/SP42 files. | #275 | +| `.mmd` `animdoor` per door wing | Door wings of different kinds on one side. | Vehicles with mixed doors. | #397 | +| `.mmd` `i-compartmentlights`, `radioon_sw:` etc. | New lamps and radio fuse switches. | Cabs that have them. | #352, #280 | +| eu07.ini `sound.*` | The OpenAL Soft options, each defaulting to what the simulator did before. | Optional. | #404 | diff --git a/docs/imgui_patches.md b/docs/imgui_patches.md new file mode 100644 index 000000000..3266158b5 --- /dev/null +++ b/docs/imgui_patches.md @@ -0,0 +1,52 @@ +# Local changes of the bundled ImGui + +`imgui/` holds Dear ImGui **v1.91.9b-docking** (`IMGUI_VERSION "1.91.9b"`, the docking branch: upstream tag +[`v1.91.9b-docking`](https://github.com/ocornut/imgui/tree/v1.91.9b-docking)), the GLFW, OpenGL 2 and OpenGL 3 backends +of the same tag, and ImGuizmo. The changes below are ours: an update of ImGui has to carry them over, or drop them on +purpose. Most of them are marked in the code with a `MaSzyna` comment (`grep -n MaSzyna imgui/*`), but not every +changed line is. + +Compared with the upstream tag, these files are unchanged: `imgui_demo.cpp`, `imgui_draw.cpp`, `imgui_internal.h`, +`imgui_tables.cpp`, `imstb_rectpack.h`, `imstb_textedit.h`, `imstb_truetype.h`, `LICENSE.txt` and the backend headers +(`imgui_impl_glfw.h`, `imgui_impl_opengl2.h`, `imgui_impl_opengl3.h`). The backends are in `backends/` upstream, here +next to the rest. + +## ImGui itself + +| Change | Files | Since | Used by | +|--------|-------|-------|---------| +| `io.ConfigViewportsNoAutoDetach` (default `false`): a floating window stays inside its host viewport. A resize stops at the viewport's edge, a window left past the edge or too big for it is moved back and shrunk, and it gets a viewport (an OS window) of its own only when dragged with the cursor outside the host viewport. Tooltips and popups over the main viewport, or begun outside any window, stay in the main viewport. Upstream has no such option ([#236](https://github.com/MaSzyna-EU07/maszyna/pull/236); the closest upstream report is [ocornut/imgui#9594](https://github.com/ocornut/imgui/issues/9594)) | `imgui.h` (`ImGuiIO` field), `imgui.cpp`: its default in `ImGuiIO::ImGuiIO()`; `WindowStaysInHostViewport()`, `IsWindowBeingMoved()`, `KeepWindowInsideRect()`; the resize limit in `UpdateWindowManualResize()`; two places in `Begin()` (no late viewport, window kept inside the work rect); the fallback and `ViewportAllowPlatformMonitorExtend` in `UpdateSelectWindowViewport()` | 5fa03304e (#236), be4000880, d0ca44cd6 | `application/uilayer.cpp`, with the viewports on | +| `io.ConfigTooltipsWrapWidth` (default `0`, no wrapping): the text of `SetTooltip()` / `SetItemTooltip()` wraps at that width. `BeginTooltip()` is not affected | `imgui.h` (`ImGuiIO` field), `imgui.cpp` (default, `SetTooltipV()`) | be4000880 | `application/uilayer.cpp` (40 font sizes) | +| `ImGui::BufferingBar()` and `ImGui::Spinner()`, by zfedoran from [ocornut/imgui#1901](https://github.com/ocornut/imgui/issues/1901) | `imgui.h`, end of `imgui_widgets.cpp` | ae3cecfa4 (2019, for the progress bar of the loading screen of the time), carried over in 344034ec7 | nothing at present: can be dropped | +| `#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM`: the OpenGL 3 backend uses glad, loaded by the simulator, instead of its own loader | `imconfig.h` | 344034ec7 | the OpenGL 3 backend | + +## Backends + +| Change | File | Since | +|--------|------|-------| +| With multi-viewports, ImGui positions are relative to the simulator's main window instead of the desktop, so the main viewport stays at (0,0) and the overlays, picking and editor gizmo work in window coordinates as without viewports. `MainWindowOrigin` in the backend data, `ImGui_ImplGlfw_UpdateMainWindowOrigin()` called from `NewFrame()`; the origin is subtracted from the mouse position (callback and `UpdateMouseData()`), the monitors' `MainPos` / `WorkPos` and `GetWindowPos()`, and added back in `CreateWindow()` and `SetWindowPos()` | `imgui_impl_glfw.cpp` | 476f3bf1b | +| GL functions from glad (``) instead of the system's `GL/gl.h` | `imgui_impl_opengl2.cpp` | 344034ec7 | +| GL functions from glad, with `stdafx.h` and `utilities/Globals.h` included for the renderer's settings | `imgui_impl_opengl3.cpp` | 344034ec7 | +| `GlslVersionString` is 128 bytes instead of 32, for the longer GLES version string the simulator passes | `imgui_impl_opengl3.cpp` | 344034ec7 | +| Gamma of the UI follows the renderer: the vertex shaders linearise the vertex colour (`pow(Color.rgb, 2.2)`); each fragment shader's output goes through `FBOUT()`, which applies `1/2.2` when `Global.gfx_shadergamma` is set and passes it through otherwise; with desktop GL and no shader gamma `GL_FRAMEBUFFER_SRGB` is enabled while the UI is drawn and restored after | `imgui_impl_opengl3.cpp` (`RenderDrawData()`, the shader sources, `CreateDeviceObjects()`) | 344034ec7 | + +## ImGuizmo + +From [CedricGuillemet/ImGuizmo](https://github.com/CedricGuillemet/ImGuizmo), added in 5a39ed519; the upstream commit +it was taken from isn't recorded. Changed in 344034ec7 for the ImGui API of 1.91: + +- `IMGUI_DEFINE_MATH_OPERATORS` is defined before the first `#include "imgui.h"` (ImGui 1.86 and later want it so). +- `ImGui::CaptureMouseFromApp()` is replaced by `ImGui::SetNextFrameWantCaptureMouse(true)` (six places). + +And since 5a39ed519, for the ImGui of the time: + +- A compatibility shim, `#define ImAbs(X)` when `ImAbs` isn't a macro (`ImGuizmo.cpp:42-44`). ImGui 1.91 has `ImAbs` + as an inline function in `imgui_internal.h`, so the macro is always defined now and hides that function in + `ImGuizmo.cpp`. It can be dropped. + +## Checking an update + +Download the files of the new tag (`imgui*.cpp`, `imgui*.h`, `imstb_*.h`, `imconfig.h`, and from `backends/` +`imgui_impl_glfw.*`, `imgui_impl_opengl2.*`, `imgui_impl_opengl3.*`), diff the files here against the tag listed at the +top, and apply that diff to the new files. The diff of the files here against `v1.91.9b-docking` is exactly the list +above. diff --git a/track_uneven_doc.md b/docs/track_uneven_doc.md similarity index 100% rename from track_uneven_doc.md rename to docs/track_uneven_doc.md diff --git a/docs/vehicle-architecture.md b/docs/vehicle-architecture.md new file mode 100644 index 000000000..ed70c2f5e --- /dev/null +++ b/docs/vehicle-architecture.md @@ -0,0 +1,450 @@ +# The vehicle: physics, driving and dependencies + +How, after the refactorings of `cleanup/mover` (as of 2026-11-29, at `969864f2`), the physics of a vehicle (`physics/`), +the vehicle in the scenery (`vehicle/`, `vehicle/dynamic/`), the AI driver (`vehicle/ai/`) and the player's cab +(`vehicle/cab/`) work together, and which files outside these folders use them. The rules this split follows are in +`AGENTS.md` ("Naming and the vehicle code"); this is a picture of what came of them. + +The diagrams are Mermaid (GitHub and most editors draw them). + +## 1. Layers + +```mermaid +flowchart TB + subgraph outside["The rest of the simulator"] + app["application/
drivermode, UI panels, editor"] + input["input/
command_relay, mouse, keyboard"] + world["world/
Track, TrkFoll, Event, MemCell"] + sim["simulation/
state_manager, serializer, blackbox"] + script["scripting/
lua, PyInt, Python screens"] + render["rendering/, audio/, scene/"] + end + + subgraph veh["vehicle/ (the vehicle in the scenery)"] + cab["vehicle/cab/
TTrain: the player's cab"] + ai["vehicle/ai/
TController: the driver"] + dyn["vehicle/dynamic/
TDynamicObject, vehicle_table"] + helpers["vehicle/*.h, *.cpp
small modules without the scene
(brakesetting, handover, horn, ...)"] + end + + subgraph phys["physics/ (the physics of the vehicle)"] + pv["physics::Vehicle
vehicle.h + components/*.cpp"] + comp["components
components/*.h"] + models["standalone models
brakes, friction, oerlikonest,
couplerphysics, collision,
derailment, consistbraking"] + vocab["vocabulary
vehicletypes.h, vehiclecommand.h"] + end + + app --> cab + app --> dyn + input -->|user_command| cab + sim --> dyn + world --> dyn + world --> ai + script --> ai + render --> dyn + + cab --> ai + cab --> dyn + ai --> dyn + dyn --> ai + cab --> pv + ai --> pv + dyn --> pv + helpers --> pv + + pv --> comp + pv --> models + comp --> vocab + pv --> vocab +``` + +An arrow means "knows / calls". The rule: `physics/` doesn't know the scene, `vehicle/` knows the physics, and the rest of +the simulator reads a vehicle through `TDynamicObject` (its dimensions, speed, cab, lights), not through +`physics/vehicle.h`. The exceptions to the rule that are still left are in section 7. + +## 2. The objects at run time + +```mermaid +classDiagram + direction LR + class vehicle_table { + simulation::Vehicles + update(dt, iterations) + update_brake_pipes() + update_coupler_physics() + } + class train_table { + simulation::Trains + update(dt) / updateAsync(dt) + } + class TDynamicObject { + physics : physics::Vehicle* + Mechanik : TController* + ctOwner : TController* + Axle0, Axle1 : TTrackFollower + Update() UpdateForce() FastUpdate() + Prev() Next() + } + class TController { + pVehicle : TDynamicObject* + mvControlling : physics::Vehicle* + occupied : physics::Vehicle* + sSpeedTable : TSpeedPos[] + Update(dt) + PutCommand() + } + class TTrain { + DynamicObject : TDynamicObject* + controlled, occupied : physics::Vehicle* + secondUnit, thirdUnit + m_commandhandlers + Update(dt) + } + class Vehicle["physics::Vehicle"] { + Couplers : ByEnd~TCoupling~ + Neighbours + ComputeTotalForce() + FastComputeMovement() + ComputeMovement() + RunCommand() SendCtrlToNext() + } + + vehicle_table "1" o-- "*" TDynamicObject + train_table "1" o-- "*" TTrain + TDynamicObject "1" *-- "1" Vehicle : creates (lifecycle.cpp) + TDynamicObject "1" *-- "0..1" TController : Mechanik (lifecycle.cpp) + TDynamicObject --> TController : ctOwner (runs the consist) + TController --> TDynamicObject : pVehicle, pVehicles + TController --> Vehicle : mvControlling, occupied + TTrain --> TDynamicObject : DynamicObject + TTrain --> Vehicle : controlled, occupied + Vehicle --> Vehicle : Couplers.Connected +``` + +- `TDynamicObject` creates its `physics::Vehicle` (`vehicle/dynamic/lifecycle.cpp`) and, when it is manned, its + `TController` (`Mechanik`). `ctOwner` points at the driver who runs the whole consist. +- A `TTrain` exists for the vehicles the player can get into (`simulation::Trains`; `simulation::Train` is the one the + player is in). It doesn't own its vehicle, it only points at it; when the player changes vehicles (`MoveToVehicle()`, + F5) it moves its pointers. +- `TController` works for the AI and for the player alike (`AIControllFlag()`): with the player it still keeps the speed + table, the hints and the black box, it only leaves the controls alone. +- The vehicles of a consist are linked in the physics (`physics::Vehicle::Couplers[].Connected`) and in the scene + (`TDynamicObject::Prev()` / `Next()`). + +## 3. A frame of the simulation + +```mermaid +sequenceDiagram + autonumber + participant DM as driver_mode::update
(application/drivermode.cpp) + participant SM as state_manager::update
(simulation/simulation.cpp) + participant VT as vehicle_table::update
(vehicle/dynamic/vehicletable.cpp) + participant DO as TDynamicObject + participant PV as physics::Vehicle + participant AI as TController + participant TR as TTrain::Update
(vehicle/cab/update.cpp) + + DM->>SM: update(dt, iterations) + SM->>SM: animations, power grid, road junctions + SM->>VT: update(dt, iterations) + VT->>DO: update_traction() (overhead voltage), update_neighbours() + VT->>VT: update_coupler_physics() + loop iterations - 1 steps (optionally on threads) + VT->>DO: UpdateForce(dt) + DO->>PV: ComputeTotalForce(dt) + VT->>DO: FastUpdate(dt) + DO->>PV: FastComputeMovement(dt) + VT->>VT: update_brake_pipes(dt) + end + VT->>DO: UpdateForce(dt) + VT->>DO: Update(dt, dt1) (the full step) + DO->>DO: updateTrackParameters, updateCouplingState, updateTractionVoltage + DO->>AI: updateDriver: Mechanik->Update(dt1) + AI->>PV: operations (IncMainCtrl, BrakeLevelSet, MainSwitch, ...) + DO->>PV: ConsistBrakeBlending.Update(vehicles of the consist) + DO->>PV: ComputeMovement(dt, dt1, track, overhead line) + DO->>DO: animations, pantographs, wipers, mirrors, load + VT->>VT: update_brake_pipes(dt) + SM->>SM: TTrack::update_buckling + DM->>TR: simulation::Trains.update(dt) + TR->>TR: simulation::Commands.pop() -> OnCommand_*() + TR->>PV: operations from the player's cab + TR->>TR: UpdateCab: gauges, buttons, sounds, screens + DM->>DM: Events.update, Lights.update, process_commands +``` + +Inside `physics::Vehicle` the step goes like this (`physics/components/body.cpp`): + +- `ComputeTotalForce()`: the tractive force (`TractionForce()`, `traction.cpp`, through `Drive()` for the kind of engine), + the braking (`BrakeForce()`, `FrictionForce()`), adhesion and slipping, the forces in the couplers. +- `FastComputeMovement()` / `ComputeMovement()`: the movement along the track, derailment (`check_derailment()`), + collisions (`CollisionDetect()`), the odometer, and in their shared part `compute_movement_()`: the internal commands + (`RunInternalCommand()`), the circuits (`MainsCheck`, `PantographsCheck`, `ConverterCheck`, `CompressorCheck`, + `LowVoltagePowerCheck`, `HeatingCheck`, `LightsCheck`, ...), the air (`UpdatePipePressure`, `UpdateBrakePressure`, + `air.UpdatePressure`), the engine (`UpdateEngine`), the doors, the PLC (`m_plc`). + +## 4. Commands: who changes the state of a vehicle + +```mermaid +flowchart LR + subgraph sources["Sources"] + kb["keyboard / mouse / UART / ZMQ
input/"] + events["scenery events, MemCell
world/Event.cpp, MemCell.cpp"] + lua["Lua
scripting/lua.cpp"] + scn["loading the scenery
simulationstateserializer.cpp"] + end + + relay["command_relay
simulation::Commands"] + train["TTrain::Update
m_commandhandlers
(cab/commandtable.cpp)
OnCommand_* in cab/*commands.cpp"] + ctrl["TController
PutCommand(), Update()
(ai/orders.cpp, ai/*.cpp)"] + pv["physics::Vehicle
public operations"] + next["neighbouring vehicles
RunCommand()"] + + kb -->|user_command| relay --> train + train -->|"Set..., Inc..., Switch..."| pv + train -->|"AI on/off, direction, doors of the consist"| ctrl + events -->|"PutCommand, as text"| ctrl + events -->|"PutCommand: load and the like"| pv + lua --> ctrl + lua --> pv + scn -->|"first orders"| ctrl + ctrl -->|"the same operations as the cab"| pv + pv -->|"SendCtrlToNext: VehicleCommand"| next +``` + +- The vehicles of a consist pass `VehicleCommand`s (`physics/vehiclecommand.h`) to each other through their couplings + (`SendCtrlToNext()` → `RunCommand()` of the neighbour, carried out in `RunInternalCommand()` in a later step). The text + names of the commands only matter where a command comes as text (events, Lua) or is shown (the log, the AI). +- Outside `physics/` the state of a `physics::Vehicle` changes only through its operations (`SetMainCtrlPos()`, + `SetLitLights()`, `UnloadStep()`, ...), never by writing its fields. The exception is the definition of the vehicle, + which the scenery and the `.mmd` adjust as it loads. +- The cab and the events read `TController` through its queries; only the debug, timetable, scenario and driving aid + panels (`application/driveruipanels.cpp`) are its friends. + +## 5. Inside `physics/` + +```mermaid +flowchart TB + subgraph vehicle_h["physics/vehicle.h: class physics::Vehicle"] + direction TB + def["the definition from the .fiz
(fizparser.cpp, fizsections.cpp, setup.cpp)"] + state["state and steps
body, traction, controllers, electrics,
pneumatics, diesel, doors, couplers,
collisions, commands, cab, securitysystem"] + end + + subgraph components["physics/components/*.h: the parts of the vehicle"] + mc["maincircuit.h
LineBreaker, LineContactors,
ProtectionRelays, PowerConverter"] + lv["lowvoltage.h
LowVoltageSupply, TrainHeating"] + pa["pantographs.h
PantographCircuit, PantographAir"] + as["airsupply.h
AirCompressor, AirSupply, TrainPipe"] + br["braking.h
Braking: blending, holding,
spring brake, ED"] + de["dieselengine.h
DieselEngine, TorqueConverter,
Retarder, EngineHeat"] + im["inductionmotor.h
InductionMotor (inverters)"] + dv["devices.h
pumps, fans, valves,
doors, genset, pantograph"] + dr["drive.h
TractionDrive: one class
for each EngineType"] + end + + subgraph models["standalone models (without physics::Vehicle)"] + brakes["brakes.h
TReservoir, TBrake and the distributors
(TWest, TESt*, TLSt, TEStED, TKE, ...),
the driver's brake valves"] + oer["oerlikonest.h
TNESt3"] + fr["friction.h
brake block materials"] + cp["couplerphysics.h
coupler_physics::"] + col["collision.h
collision::"] + der["derailment.h
derailment::"] + cb["consistbraking.h
ConsistBrakeBlending"] + end + + vocab["vehicletypes.h, vehiclecommand.h"] + + vehicle_h --> components + vehicle_h --> brakes + vehicle_h --> cp + vehicle_h --> col + vehicle_h --> der + oer --> brakes + brakes --> fr + col --> cp + col --> der + cb -.->|"works on the vehicles of a consist"| vehicle_h + components --> vocab + vehicle_h --> vocab +``` + +The pattern of a component (from `maincircuit.h`, `lowvoltage.h`, `pantographs.h`, `airsupply.h`): + +```mermaid +flowchart LR + fiz[".fiz"] -->|"written by the parser and the setup"| config["config (public)
the definition, only read afterwards"] + veh["physics::Vehicle
decides WHEN the part acts"] -->|"plain values
ConverterSupply, CompressorInputs, ..."| update["Update() / Close() /
ResetGround() / Switch()"] + update --> privstate["private state"] + privstate -->|"queries: IsClosed(), ..."| veh + update -->|"what the step reports
CompressorStep, ..."| veh + tests["tests/unit"] -->|"...ForTest()"| privstate +``` + +| Field of `physics::Vehicle` | Type | File | +|---|---|---| +| `lowVoltage`, `trainHeating` | `LowVoltageSupply`, `TrainHeating` | `components/lowvoltage.h` | +| `lineBreaker`, `lineContactors`, `protection`, `converter` | `LineBreaker`, `LineContactors`, `ProtectionRelays`, `PowerConverter` | `components/maincircuit.h` | +| `pantographs`, `pantographCircuit`, `pantographAir` | `ByEnd`, `PantographCircuit`, `PantographAir` | `components/devices.h`, `components/pantographs.h` | +| `air`, `brakePipe`, `mainPipe` | `AirSupply`, `TrainPipe` | `components/airsupply.h` | +| `brakes` | `Braking` (the distributor `TBrake`, the driver's valves `TDriverHandle`) | `components/braking.h`, `brakes.h` | +| `diesel`, `torqueConverter`, `retarder` | `DieselEngine`, `TorqueConverter`, `Retarder` | `components/dieselengine.h` | +| `inductionMotor` | `InductionMotor` | `components/inductionmotor.h` | +| `Drive()` | `TractionDrive const &` (`DriveOf(EngineType)`) | `components/drive.h` | +| `SecuritySystem` | `TSecuritySystem` | `vehicle.h`, `components/securitysystem.cpp` | +| `Couplers`, `Neighbours` | `ByEnd`, `ByEnd` | `vehicle.h`, `couplerphysics.h` | +| `Doors`, `Genset` | `door_data`, `genset_device` | `components/devices.h` | +| `OffTrack`, `Odometer`, `m_plc` | `derail_motion::body`, `odometer::reading`, `plc::basic_controller` | `vehicle/derailmotion.h`, `vehicle/odometerreading.h`, `scripting/ladderlogic.h` | + +The files `physics/components/*.cpp` are the parts of the one class `physics::Vehicle`, cut by subsystem; the helpers +they share are in `components/internal.h`, which only they include. + +| File | What it computes | +|---|---| +| `body.cpp` | construction, the forces on the body, the movement along the track, adhesion, sand, the step (`ComputeTotalForce`, `ComputeMovement`) | +| `traction.cpp` | the traction motors and their forces for each kind of drive, the relays, the fuses, the dynamic brake | +| `controllers.cpp` | the master and the secondary controllers, the camshaft, the integrated controller, the speed control | +| `electrics.cpp` | the batteries, the main switch, the pantographs, the converter, heating, lights, the genset | +| `pneumatics.cpp` | the brake controls, the pipes, the valves, the compressor, the spring brake | +| `diesel.cpp` | the revolutions of the diesel engine, the gearbox, the clutch, the hydraulic transmission, its heat, the pumps | +| `drive.cpp` | the `TractionDrive` classes, one for each `EngineType` | +| `couplers.cpp` | coupling, the forces in the couplers, automatic coupling | +| `collisions.cpp` | collisions, crush, derailment and putting back on the rails | +| `commands.cpp` | the `VehicleCommand`s between vehicles (`RunCommand`, `RunInternalCommand`, `SendCtrlToNext`) | +| `cab.cpp` | activating the cab, the direction, the horns, the pullee mode | +| `doors.cpp` | the doors and the exchange of the load | +| `securitysystem.cpp` | vigilance, cab signalling, radio-stop | +| `fizparser.cpp`, `fizsections.cpp` | reading the `.fiz` | +| `setup.cpp` | setting the vehicle up after loading: the checks, the valves, the pipes | + +## 6. `vehicle/`: the scene, the AI and the cab + +```mermaid +flowchart TB + subgraph dynamic["vehicle/dynamic/ (TDynamicObject, vehicle_table)"] + dlife["lifecycle.cpp, mmd.cpp, load.cpp
creation, the .mmd, the load"] + dupd["update.cpp, movement.cpp, vehicletable.cpp
the step of a vehicle and of the whole table"] + dcons["consist.cpp, couplers.cpp, neighbours.cpp
the consist, the couplers, the neighbours"] + dvis["visual.cpp, animations.cpp, lights.cpp,
sounds.cpp, destinations.cpp, offtrack.cpp"] + end + + subgraph aidir["vehicle/ai/ (TController, Driver.h)"] + adrv["driver.cpp, orders.cpp
construction, Update, orders"] + aroute["routescan.cpp, speedtable.cpp, speedpos.cpp,
obstacles.cpp, situation.cpp
the speed table, the signals, the obstacles"] + acontrol["speed.cpp, force.cpp, controls.cpp,
engine.cpp, doors.cpp, consist.cpp
target speed, controllers, brakes, doors, consist"] + alog["physicslog.cpp"] + end + + subgraph cabdir["vehicle/cab/ (TTrain, Train.h)"] + ctrain["train.cpp, setup.cpp, cab.cpp
the player's train, gauges, buttons"] + cupd["update.cpp, sounds.cpp, screens.cpp
the step of the cab, sounds, Python screens"] + ccmd["commandtable.cpp + *commands.cpp
handling user_command"] + end + + subgraph small["vehicle/*.h, *.cpp: modules testable without the scene"] + sai["for the AI: brakesetting, brakecharge, brakereleaser,
brakingcurve, uphillstart, aipower, aiwire,
signalpassing, timetableservice, handover,
driverorders, fieldshunting"] + scab["for the cab: horn, linebreaker, holdcoillever,
enginestart, mainctrlact, compartmentlightsswitch,
gaugescale, gaugewrap, gaugepositions,
gaugeduplicates, universaldrag, drivingaid"] + sdyn["for the vehicle in the scene: derailmotion, doorwings,
mirrors, lightsprogrammer, pulleemode, smoke,
odometer, driverfigure, cameraviews"] + sother["crew, crewchange, blackbox,
Camera, Gauge, Button, AirCoupler"] + end + + dynamic --> aidir + aidir --> dynamic + cabdir --> dynamic + cabdir --> aidir + aidir --> sai + cabdir --> scab + dynamic --> sdyn +``` + +- `Driver.h` (`TController`) includes `DynObj.h`; `Train.h` (`TTrain`) includes `DynObj.h` and `Driver.h`. The files of + `vehicle/ai/`, `vehicle/cab/` and `vehicle/dynamic/` each share one `internal.h` with their list of includes. +- The AI looks for a `TTrain` in two places only, through `simulation::Trains.find()`: when it changes cabs + (`ai/consist.cpp`), and for the pantographs and lights of the player's train (`ai/situation.cpp`). +- The cab uses `TController` to take over and hand back the controls (`TakeControl`, `AIControllFlag`), to change the + direction, for the doors of the consist (`ConsistDoors*`) and to check the consist (`CheckVehicles`). +- The modules of `vehicle/*.h` are mostly plain functions or small structures on plain values, tested in `tests/unit` + without the scene. Some of them include `physics/vehicle.h` (`lightsprogrammer.h` and `mainctrlact.h` in the header; + `brakesetting.cpp`, `drivingaid.cpp`, `enginestart.cpp`, `handover.cpp`, `crew.cpp`, `smoke.cpp` and + `timetableservice.cpp` in the implementation). + +## 7. Include dependencies + +```mermaid +flowchart LR + classDef up stroke:#d33,stroke-width:2px,color:#d33 + + vt["physics/vehicletypes.h"] --> vc["physics/vehiclecommand.h"] + vt --> es["utilities/enumset.h"] + vh["physics/vehicle.h"] --> vt + vh --> comps["physics/components/*.h"] + vh --> bh["physics/brakes.h"] --> fh["physics/friction.h"] + vh --> colh["physics/collision.h"] --> cph["physics/couplerphysics.h"] + colh --> dh["physics/derailment.h"] + vh --> ll["scripting/ladderlogic.h"]:::up + vh --> dm["vehicle/derailmotion.h"]:::up + vh --> odo["vehicle/odometerreading.h"]:::up + + ccpp["physics/components/*.cpp"] --> vh + ccpp --> dynh["vehicle/DynObj.h"]:::up + ccpp --> simh["simulation/simulation.h"]:::up + ccpp --> fsh["vehicle/fieldshunting.h"]:::up + ccpp --> glob["utilities/Globals.h"] + + dynobj["vehicle/DynObj.h"] --> vt + dynobj --> dh + dynobj --> cbh["physics/consistbraking.h"] + dynobj --> dm2["vehicle/derailmotion.h"] + dynobj --> trk["world/TrkFoll.h"] + driver["vehicle/Driver.h"] --> dynobj + driver --> vt + train["vehicle/Train.h"] --> dynobj + train --> driver + classes["utilities/Classes.h
declares physics::Vehicle,
TDynamicObject, TController, TTrain"] +``` + +In red is what goes "up", against the layers of section 1. As it stands: + +- `physics/vehicle.h` includes three headers from outside `physics/`, but all of them are data without the scene: + `vehicle/derailmotion.h` (the movement of a vehicle off the track, the field `OffTrack`), `vehicle/odometerreading.h` + (the field `Odometer`) and `scripting/ladderlogic.h` (the PLC, the field `m_plc`). The natural place for the first two is + `physics/`. +- `physics/components/*.cpp` share a block of includes with `vehicle/DynObj.h` and `simulation/simulation.h`. They don't + use `TDynamicObject` (it appears only in comments); of `simulation/` they take only `simulation::Weights` (the unit + weights of the loads, `body.cpp`). `vehicle/fieldshunting.h` (a plain function) is used by `controllers.cpp` and + `diesel.cpp`. These are candidates for a cleanup: drop `DynObj.h` from the block, move `fieldshunting.h` to `physics/`, + and hand the physics the `Weights` as a value. +- The physics reads settings from `Global` (`utilities/Globals.h`): `collisions`, `derailment`, `crash_damage`, + `coupler_physics*`, `physics_sleepheld`, `physics_pipewake`, `AirTemperature`; and `fizparser.cpp` sets + `Global.iPause` while it loads. + +## 8. Other files that use the vehicle + +| File | Through | What for | +|---|---|---| +| `utilities/Classes.h` | declarations | `physics::Vehicle`, `TDynamicObject`, `TController`, `TTrain` for the headers that only point at them | +| `application/drivermode.cpp` | `Train.h`, `DynObj.h`, `Driver.h` | the frame loop, getting in, changing vehicles, the camera | +| `application/driveruipanels.cpp`, `consistviews.cpp`, `driverhints.cpp` | `Driver.h` (friend), `physics/vehicle.h` | the debug, timetable, scenario and driving aid panels, the hints | +| `application/editormode*.cpp` | `DynObj.h` | the editor and its self-tests | +| `input/command.cpp`, `drivermouseinput.cpp`, `zmq_input.cpp` | `Train.h` | `user_command`s for the cab, mapping clicks to the controls of the cab | +| `input/messaging.cpp`, `utilities/uart.cpp`, `utilities/motiontelemetry.cpp` | `physics/vehicle.h`, `Train.h` | the state of the vehicle for external programs, desks, motion platforms | +| `simulation/simulation.cpp` | `vehicle_table`, `train_table` | `state_manager::update()`, `process_commands()` | +| `simulation/simulationstateserializer.cpp` | `DynObj.h`, `Driver.h` | loading the vehicles and consists of the `.scn`, the first orders | +| `simulation/blackboxrecorder.cpp` | `physics/vehicle.h`, `Driver.h`, `Train.h` | recording the session (`vehicle/blackbox.h` is the format) | +| `simulation/simulationtest.cpp` | `DynObj.h` | the test mode (`--test`) | +| `world/TrkFoll.cpp` | `DynObj.h`, `Driver.h` | the axles of a vehicle on the track, the events it runs over | +| `world/Track.cpp`, `TrackBuckle.cpp` | `DynObj.h`, `physics/vehicle.h` | the vehicles on a track, derailing on buckled track | +| `world/Event.cpp`, `world/MemCell.cpp` | `PutCommand()` | the commands of the scenery for the driver and the vehicle | +| `world/station.cpp`, `RoadPoint.cpp`, `Road.cpp`, `deer.cpp` | `DynObj.h` | the exchange of passengers, road traffic, animals | +| `scripting/lua.cpp` | `Driver.h`, `physics/vehicle.h` | `PutCommand()` from Lua | +| `scripting/PyInt.cpp`, `pythonscreenviewer`, `vehicle/cab/screens.cpp` | `Train.h` | the Python screens of the cab (the state dictionaries) | +| `audio/sound.cpp`, `audio/audiorenderer.cpp` | `DynObj.h`, `Train.h` | the sounds of the vehicle and the cab | +| `rendering/common/*`, `rendering/opengl46/*`, `rendering/vulkan14/*`, `rendering/particles.cpp`, `lightarray.cpp` | `DynObj.h`, `Train.h` | drawing the vehicles, the cab, the lights, the smoke | +| `scene/scene.cpp`, `widgets/map*.cpp`, `widgets/vehicle*.cpp`, `widgets/trainingcard.cpp` | `DynObj.h`, `Driver.h` | the scenery, the map, the vehicle lists, the training card | +| `utilities/Globals.cpp` | | the `eu07.ini` settings the physics and the AI read | +| `tests/unit/*` | `physics/vehicle.h`, `physics/brakes.h`, `DynObj.h` | the tests: `vehicle.h` / `consist.h` (a vehicle and a consist without the scenery, stepped as `vehicle_table::update()` does), `golden.*` (against a recorded run), `fiz.*` (`.fiz` definitions in a test), `scenario.*` | + +`physics/vehicletypes.h` (the vocabulary: ends, sides, couplings, lights, types of drive and brake) and +`physics/vehiclecommand.h` (`VehicleCommand`) are what the rest of the simulator should include when it needs only these +names; outside `physics/` and `vehicle/`, `application/consistviews.h`, `application/driveruipanels.h` and +`rendering/common/scenewalk.h` do so today. diff --git a/editor/editorCatenaryFile.hpp b/editor/editorCatenaryFile.hpp new file mode 100644 index 000000000..446f7ee79 --- /dev/null +++ b/editor/editorCatenaryFile.hpp @@ -0,0 +1,39 @@ +/* +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 + +#include + +// whether a catenary file made in the editor can be named so: the save writes it into the folder of the scenery and +// includes it with "catenary endcatenary", which the parser reads as one token. So no white space, no ';' (both +// end a token), no quotes, no ':' (a drive), no empty part of the path (a leading or a doubled separator, which is also +// the start of a comment) and no ".." (out of the folder of the scenery). A subfolder of it is fine +inline bool catenary_file_name_valid(std::string_view const Name) +{ + if (Name.empty()) + return false; + for (auto const character : Name) + { + auto const code{static_cast(character)}; + if (code <= ' ' || code == 127 || character == ';' || character == '"' || character == ':') + return false; + } + std::size_t start{0}; + while (start <= Name.size()) + { + auto end{Name.find_first_of("/\\", start)}; + if (end == std::string_view::npos) + end = Name.size(); + if (auto const part{Name.substr(start, end - start)}; part.empty() || part == "..") + return false; + start = end + 1; + } + return true; +} diff --git a/editor/editorHttp.cpp b/editor/editorHttp.cpp index cbda581f0..2a8c90c00 100644 --- a/editor/editorHttp.cpp +++ b/editor/editorHttp.cpp @@ -13,12 +13,20 @@ http://mozilla.org/MPL/2.0/. #if defined(_WIN32) #include #elif defined(EU07_WITH_CURL) +// of libcurl only the types and the constants: its functions are looked up at run time (libcurl() below), so the game +// starts on a system without libcurl and only the editor's downloads are off there. no deprecation warnings for the +// options kept for a libcurl older than these headers +#ifndef CURL_DISABLE_DEPRECATION +#define CURL_DISABLE_DEPRECATION +#endif #include +#include +#include +#include "utilities/Logs.h" #endif #include #include -#include #include namespace editor_http @@ -308,9 +316,10 @@ bool client::get(std::string const &Url, std::vector &Out, std::st namespace { -// the file of the certificates https is checked with. the libcurl bundled with the game knows only the one of the system it -// was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL and openSUSE don't have: there -// every download failed. the file named by the user first, then the ones the distributions keep; empty leaves libcurl's own +// the file of the certificates https is checked with. a libcurl built elsewhere (as the one once bundled with the game) knows +// only the one of the system it was built on (/etc/ssl/certs/ca-certificates.crt of Debian and Ubuntu), which Fedora, RHEL +// and openSUSE don't have: there every download failed. the file named by the user first, then the ones the distributions +// keep; empty leaves libcurl's own std::string const &certificates_file() { static std::string const file{[]() { @@ -335,30 +344,99 @@ std::string const &certificates_file() }()}; return file; } + +// the functions of libcurl the client uses, looked up in the system's libcurl. their types are those the headers declare +// them with, so a call through them is the call of the function itself +struct curl_library +{ + decltype(&::curl_global_init) global_init{nullptr}; + decltype(&::curl_easy_init) easy_init{nullptr}; + decltype(&::curl_easy_cleanup) easy_cleanup{nullptr}; + decltype(&::curl_easy_reset) easy_reset{nullptr}; + decltype(&::curl_easy_setopt) easy_setopt{nullptr}; + decltype(&::curl_easy_perform) easy_perform{nullptr}; + decltype(&::curl_easy_getinfo) easy_getinfo{nullptr}; + decltype(&::curl_easy_strerror) easy_strerror{nullptr}; + bool loaded{false}; // all of them found +}; + +// the system's libcurl: the name of its runtime package (libcurl4 of Debian and Ubuntu, libcurl of Fedora and Arch), that of +// the GnuTLS build of Debian and Ubuntu, then that of its development files. null when there's none +void *open_curl() +{ + for (char const *const name : {"libcurl.so.4", "libcurl-gnutls.so.4", "libcurl.so"}) + { + if (void *const library{::dlopen(name, RTLD_NOW | RTLD_LOCAL)}; library != nullptr) + return library; + } + return nullptr; +} + +// the function Name of the library into Function, false when the library has none +template +bool resolve(void *const Library, char const *const Name, Function &Into) +{ + // dlsym() gives a function's address as void *, which POSIX lets be converted back to the function's type + Into = reinterpret_cast(::dlsym(Library, Name)); + if (Into == nullptr) + WriteLog(std::format("Editor: the libcurl of the system has no {}, the downloads of the editor are off", Name)); + return Into != nullptr; +} + +// the system's libcurl, opened and initialised once, when the editor first needs it, and kept for the rest of the run +curl_library load_curl() +{ + curl_library curl; + void *const library{open_curl()}; + if (library == nullptr) + { + WriteLog("Editor: no libcurl (libcurl.so.4) on this system, the downloads of the editor (orthophoto, terrain model, topo map) are off"); + return curl; + } + curl.loaded = resolve(library, "curl_global_init", curl.global_init) && resolve(library, "curl_easy_init", curl.easy_init) && + resolve(library, "curl_easy_cleanup", curl.easy_cleanup) && resolve(library, "curl_easy_reset", curl.easy_reset) && + resolve(library, "curl_easy_setopt", curl.easy_setopt) && resolve(library, "curl_easy_perform", curl.easy_perform) && + resolve(library, "curl_easy_getinfo", curl.easy_getinfo) && resolve(library, "curl_easy_strerror", curl.easy_strerror); + if (false == curl.loaded) + { + ::dlclose(library); + return curl_library{}; + } + curl.global_init(CURL_GLOBAL_DEFAULT); + return curl; +} + +curl_library const &libcurl() +{ + static curl_library const curl{load_curl()}; + return curl; +} } // namespace client::client() : m_platform(std::make_unique()) { - static std::once_flag initialized; - std::call_once(initialized, []() { ::curl_global_init(CURL_GLOBAL_DEFAULT); }); - m_platform->curl = ::curl_easy_init(); + if (auto const &curl{libcurl()}; curl.loaded) + m_platform->curl = curl.easy_init(); } client::~client() { + // set only with libcurl loaded if (m_platform->curl != nullptr) - ::curl_easy_cleanup(m_platform->curl); + libcurl().easy_cleanup(m_platform->curl); } bool client::get(std::string const &Url, std::vector &Out, std::string &Error, stop_check const &Stop) { Out.clear(); + auto const &curl{libcurl()}; if (m_platform->curl == nullptr) { - Error = "curl_easy_init failed"; + Error = (curl.loaded ? "curl_easy_init failed" : "no libcurl on this system"); return false; } + CURL *const handle{m_platform->curl}; struct sink { @@ -378,47 +456,52 @@ bool client::get(std::string const &Url, std::vector &Out, std::st }; auto const progress = +[](void *User, curl_off_t, curl_off_t, curl_off_t, curl_off_t) -> int { return (*static_cast(User))() ? 1 : 0; }; - ::curl_easy_reset(m_platform->curl); - ::curl_easy_setopt(m_platform->curl, CURLOPT_URL, Url.c_str()); - ::curl_easy_setopt(m_platform->curl, CURLOPT_USERAGENT, "MaSzyna-editor"); + curl.easy_reset(handle); + curl.easy_setopt(handle, CURLOPT_URL, Url.c_str()); + curl.easy_setopt(handle, CURLOPT_USERAGENT, "MaSzyna-editor"); if (auto const &certificates{certificates_file()}; false == certificates.empty()) { - ::curl_easy_setopt(m_platform->curl, CURLOPT_CAINFO, certificates.c_str()); + curl.easy_setopt(handle, CURLOPT_CAINFO, certificates.c_str()); #if LIBCURL_VERSION_NUM >= 0x073400 // an https proxy is checked with the same file - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROXY_CAINFO, certificates.c_str()); + curl.easy_setopt(handle, CURLOPT_PROXY_CAINFO, certificates.c_str()); #endif } - ::curl_easy_setopt(m_platform->curl, CURLOPT_FOLLOWLOCATION, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXREDIRS, 10L); - // http kept for the services the user types; nothing else, also where a redirect leads + curl.easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L); + curl.easy_setopt(handle, CURLOPT_MAXREDIRS, 10L); + // http kept for the services the user types; nothing else, also where a redirect leads. the system's libcurl can be older + // than the headers: one without the options by name (before 7.85.0) refuses them, and takes the bit masks #if LIBCURL_VERSION_NUM >= 0x075500 - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROTOCOLS_STR, "https,http"); - ::curl_easy_setopt(m_platform->curl, CURLOPT_REDIR_PROTOCOLS_STR, "https,http"); + bool const named{(curl.easy_setopt(handle, CURLOPT_PROTOCOLS_STR, "https,http") == CURLE_OK) && + (curl.easy_setopt(handle, CURLOPT_REDIR_PROTOCOLS_STR, "https,http") == CURLE_OK)}; #else - ::curl_easy_setopt(m_platform->curl, CURLOPT_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); - ::curl_easy_setopt(m_platform->curl, CURLOPT_REDIR_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + bool const named{false}; #endif - ::curl_easy_setopt(m_platform->curl, CURLOPT_MAXFILESIZE_LARGE, static_cast(kLargest)); - ::curl_easy_setopt(m_platform->curl, CURLOPT_NOSIGNAL, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_CONNECTTIMEOUT, 10L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_LOW_SPEED_LIMIT, 1L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_LOW_SPEED_TIME, 20L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_WRITEFUNCTION, write); - ::curl_easy_setopt(m_platform->curl, CURLOPT_WRITEDATA, &received); - ::curl_easy_setopt(m_platform->curl, CURLOPT_NOPROGRESS, 0L); - ::curl_easy_setopt(m_platform->curl, CURLOPT_XFERINFOFUNCTION, progress); - ::curl_easy_setopt(m_platform->curl, CURLOPT_XFERINFODATA, const_cast(&Stop)); + if (false == named) + { + curl.easy_setopt(handle, CURLOPT_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + curl.easy_setopt(handle, CURLOPT_REDIR_PROTOCOLS, static_cast(CURLPROTO_HTTPS | CURLPROTO_HTTP)); + } + curl.easy_setopt(handle, CURLOPT_MAXFILESIZE_LARGE, static_cast(kLargest)); + curl.easy_setopt(handle, CURLOPT_NOSIGNAL, 1L); + curl.easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, 10L); + curl.easy_setopt(handle, CURLOPT_LOW_SPEED_LIMIT, 1L); + curl.easy_setopt(handle, CURLOPT_LOW_SPEED_TIME, 20L); + curl.easy_setopt(handle, CURLOPT_WRITEFUNCTION, write); + curl.easy_setopt(handle, CURLOPT_WRITEDATA, &received); + curl.easy_setopt(handle, CURLOPT_NOPROGRESS, 0L); + curl.easy_setopt(handle, CURLOPT_XFERINFOFUNCTION, progress); + curl.easy_setopt(handle, CURLOPT_XFERINFODATA, const_cast(&Stop)); - CURLcode const code = ::curl_easy_perform(m_platform->curl); + CURLcode const code = curl.easy_perform(handle); if (code != CURLE_OK) { - Error = (received.over || code == CURLE_FILESIZE_EXCEEDED ? kTooLarge : ::curl_easy_strerror(code)); + Error = (received.over || code == CURLE_FILESIZE_EXCEEDED ? kTooLarge : curl.easy_strerror(code)); Out.clear(); return false; } long status{0}; - ::curl_easy_getinfo(m_platform->curl, CURLINFO_RESPONSE_CODE, &status); + curl.easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &status); if (status != 200) { Error = "HTTP " + std::to_string(status); @@ -443,8 +526,11 @@ bool client::get(std::string const &, std::vector &Out, std::strin bool available() { -#if defined(_WIN32) || defined(EU07_WITH_CURL) +#if defined(_WIN32) return true; +#elif defined(EU07_WITH_CURL) + // libcurl opened here when nothing needed it yet + return libcurl().loaded; #else return false; #endif diff --git a/editor/editorOrthophoto.cpp b/editor/editorOrthophoto.cpp index d3254a2c1..7ea68acae 100644 --- a/editor/editorOrthophoto.cpp +++ b/editor/editorOrthophoto.cpp @@ -739,11 +739,8 @@ editor_orthophoto::service_info editor_orthophoto::describe(std::string const &S bool editor_orthophoto::can_download() { -#if defined(_WIN32) || defined(EU07_WITH_CURL) - return true; -#else - return false; -#endif + // on Linux, whether the system has libcurl as well + return editor_http::available(); } std::string editor_orthophoto::cache_directory() diff --git a/editor/editorRingRoom.hpp b/editor/editorRingRoom.hpp new file mode 100644 index 000000000..9051da616 --- /dev/null +++ b/editor/editorRingRoom.hpp @@ -0,0 +1,63 @@ +/* +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 + +#include +#include +#include + +// the room a road leaving the side of a roundabout takes of the ring, seen from above. on a straight road the edge of the road +// leaving meets the edge of the road it leaves where the two straight lines cross; the ring bends away from the road leaving it +// to the outside, so there the edges meet sooner; and a road leaving at a slant meets the edge of the ring sooner on the side +// it leans away from than on the side it leans towards +namespace editor_ring +{ + +// the shortest piece of the ring a junction leaves before the next junction, or before the end of the arc it's cut from. +// the ring goes on past it, so it can be much shorter than a road of its own; a junction which would leave less takes +// the rest of the arc, and the shorter this is the less a junction grows next to the end of an arc +double constexpr shortest_piece{0.5}; + +// how far along the axis of the ring, from the point a road leaves it, the edge of that road meets the outer edge of the ring. +// Centre: of the ring, Radius: of its axis, Point: where the axis of the road leaving meets the axis of the ring, +// Direction: the way the road leaves, Along: the way along the ring the room is measured, Halfwidth: of the ring, +// Branchhalfwidth: of the road leaving. returns: the distance along the axis of the ring, 0 if the edges cross before they get +// past the point the road leaves, or a negative value if there's no such point: the road doesn't leave towards the outside, +// or it leans so far that the edge on that side stays outside the ring all along +inline double edge_room(glm::dvec2 const &Centre, double const Radius, glm::dvec2 const &Point, glm::dvec2 const &Direction, glm::dvec2 const &Along, double const Halfwidth, + double const Branchhalfwidth) +{ + if (Radius <= 0.0 || glm::length(Direction) < 1e-9 || glm::length(Point - Centre) < 1e-9) + return -1.0; + auto const direction{glm::normalize(Direction)}; + auto const outwards{glm::normalize(Point - Centre)}; + if (glm::dot(direction, outwards) < 1e-6) + return -1.0; + // the edge of the road leaving on the side the room is measured for + glm::dvec2 side{-direction.y, direction.x}; + if (glm::dot(side, Along) < 0.0) + side = -side; + auto const start{Point - Centre + side * Branchhalfwidth}; + auto const edge{Radius + Halfwidth}; + // start + direction * t on the circle of the outer edge, where the edge leaves it going out. a road wide enough, or leaning + // far enough, has the start of that edge outside the circle already: the edges crossed before it + auto const b{glm::dot(start, direction)}; + auto const discriminant{b * b + edge * edge - glm::dot(start, start)}; + if (discriminant < 0.0) + return -1.0; + auto const t{-b + std::sqrt(discriminant)}; + auto const meet{start + direction * t}; + // the angle from the point the road leaves to that point, around the centre and the way the room is measured, carried onto the axis + auto const turn{outwards.x * Along.y - outwards.y * Along.x < 0.0 ? -1.0 : 1.0}; + auto const angle{std::atan2(turn * (outwards.x * meet.y - outwards.y * meet.x), glm::dot(outwards, meet))}; + return std::max(0.0, Radius * angle); +} + +} // namespace editor_ring diff --git a/editor/editorRoad.cpp b/editor/editorRoad.cpp index 530b9bb2a..8d6ee10c7 100644 --- a/editor/editorRoad.cpp +++ b/editor/editorRoad.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "editor/editorRoad.hpp" #include "editor/editorFormat.hpp" +#include "editor/editorRingRoom.hpp" #include "editor/editorTrack.hpp" #include "world/Track.h" @@ -19,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Globals.h" #include "utilities/utilities.h" #include "utilities/translation.h" +#include "editor/editorRoadLimits.hpp" #include #include @@ -29,10 +31,8 @@ namespace double const kSamePoint{0.25}; // ends of two pieces this close are taken for joined double const kPieceLength{50.0}; // longest piece the planner makes double const kPieceTurn{glm::radians(30.0)}; // largest turn of a single piece -double const kShortestRoad{2.0}; -double const kTightestRadius{6.0}; +// the shortest road, the tightest bend and the sharpest angle between roads go by what the road is made of: road_limits_for() double const kCornerRoom{4.0}; // length of an arm of a junction past the point where its edge meets the edge of the next one, taken by the rounded corner -double const kSharpestBranch{glm::radians(30.0)}; // smallest angle between two roads leaving a junction double const kWidestCorner{glm::radians(120.0)}; // arms further apart than this don't have to make room for each other double const kTransitionLength{30.0}; // length of the road taken by a change of its lanes @@ -274,7 +274,9 @@ bool follow(road_node &Road, double const T, bool const Forward, double const Di auto const lengths{stations(state)}; auto const here{station_at(lengths, from)}; auto const available{forward ? lengths.back() - here : here}; - if (remaining <= 0.0 || available >= remaining + kShortestRoad) + // what's left of a piece of a roundabout carries on round, so it can be shorter than a road of its own + auto const shortest{state.roundabout ? editor_ring::shortest_piece : road_limits_for(state.surfacetype).shortest_road}; + if (remaining <= 0.0 || available >= remaining + shortest) { // the cut is put here; with nothing left to go the piece is kept whole Cut.road = piece; @@ -339,6 +341,27 @@ double edge_reach(double const Halfwidth, double const Otherhalfwidth, double co return (Otherhalfwidth + Halfwidth * std::cos(Angle)) / std::sin(Angle); } +// the circle the axis of a piece bends along at specified value of its curve parameter, seen from above. returns: false if it's straight there +bool ring_circle(road_node::state const &State, double const T, glm::dvec2 &Centre, double &Radius) +{ + auto const points{curve_points(State.axis)}; + auto const u{1.0 - T}; + auto const first{3.0 * u * u * (points[1] - points[0]) + 6.0 * u * T * (points[2] - points[1]) + 3.0 * T * T * (points[3] - points[2])}; + auto const second{6.0 * u * (points[2] - 2.0 * points[1] + points[0]) + 6.0 * T * (points[3] - 2.0 * points[2] + points[1])}; + glm::dvec2 const velocity{first.x, first.z}; + auto const speed{glm::length(velocity)}; + if (speed < 1e-9) + return false; + auto const curvature{(velocity.x * second.z - velocity.y * second.x) / (speed * speed * speed)}; + if (std::abs(curvature) < 1e-5) + return false; + auto const point{curve_point(points, T)}; + auto const tangent{velocity / speed}; + Centre = glm::dvec2{point.x, point.z} + glm::dvec2{-tangent.y, tangent.x} / curvature; + Radius = 1.0 / std::abs(curvature); + return true; +} + // the look of a junction goes after the road it's made on void dress(junction_node::state &Junction, road_node::state const &Road) { @@ -1363,12 +1386,15 @@ editor_road::loose_end editor_road::find_end(glm::dvec3 const &Point, double con return result; } -std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, std::string &Error) +std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, + road_surface_type const Type, double const Halfwidth, std::string &Error) { std::vector pieces; glm::dvec2 const chord{Target.x - Start.x, Target.z - Start.z}; auto const span{glm::length(chord)}; - if (span < kShortestRoad) + auto const limits{road_limits_for(Type)}; + auto const tightest{editor_road_limits::tightest_bend(limits, Halfwidth)}; + if (span < limits.shortest_road) { Error = "Too short"; return pieces; @@ -1388,7 +1414,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 if (Direction != nullptr && Enddirection != nullptr) { // both ends are tied, which leaves a single curve with the tangents set - if (glm::dot(*Direction, chord) < 0.1 * span || glm::dot(*Enddirection, chord) < 0.1 * span) + if (glm::dot(*Direction, chord) < limits.tied_lead * span || glm::dot(*Enddirection, chord) < limits.tied_lead * span) { Error = "The road would have to turn back to meet the end"; return pieces; @@ -1406,7 +1432,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 straight(Target); return pieces; } - if (radius < kTightestRadius) + if (radius < tightest) { Error = "The bend is too tight"; return pieces; @@ -1419,7 +1445,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 { // only the far end is tied: the same road as the one leading back from there, turned around glm::dvec2 const back{-*Enddirection}; - auto reversed{plan(Target, &back, Start, nullptr, Straight, Error)}; + auto reversed{plan(Target, &back, Start, nullptr, Straight, Type, Halfwidth, Error)}; for (auto &piece : reversed) { std::swap(piece.points[segment_data::point::start], piece.points[segment_data::point::end]); @@ -1441,7 +1467,7 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 auto const side{glm::dot(chord, left)}; if (Straight || std::abs(side) < 0.02 * span) { - if (along < kShortestRoad) + if (along < limits.shortest_road) { Error = "The target is behind the start"; return pieces; @@ -1451,12 +1477,12 @@ std::vector editor_road::plan(glm::dvec3 const &Start, glm::dvec2 } auto const turn{2.0 * std::atan2(side, along)}; // positive to the left auto const radius{span * span / (2.0 * side)}; // likewise - if (std::abs(turn) > glm::radians(170.0)) + if (std::abs(turn) > limits.widest_turn) { Error = "The road would have to turn back to reach the target"; return pieces; } - if (std::abs(radius) < kTightestRadius) + if (std::abs(radius) < tightest) { Error = "The bend is too tight"; return pieces; @@ -1817,7 +1843,8 @@ bool editor_road::lane_width(road_node::state const &State, double const T, floa return true; } -bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error) +bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error) { Result = branch{}; auto const &layout{Road.definition()}; @@ -1826,7 +1853,7 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const auto const direction{glm::length(Direction) > 1e-9 ? glm::normalize(Direction) : glm::dvec2{0.0, 1.0}}; // the sharper the angle the road leaves at, the further from the centre the edges of the roads part auto const angle{std::acos(std::clamp(std::abs(glm::dot(direction, along)), 0.0, 1.0))}; - if (angle < kSharpestBranch) + if (angle < road_limits_for(Type).sharpest_branch) { Error = "The road would leave at too sharp an angle"; return false; @@ -1846,11 +1873,27 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const auto const branchhalfwidth{0.5 * (Incoming + Outgoing) * Width}; auto const reach{edge_reach(halfwidth, branchhalfwidth, angle) + kCornerRoom}; auto const branchreach{edge_reach(branchhalfwidth, halfwidth, angle) + kCornerRoom}; + // how far the junction takes the road back along it and ahead of the centre + std::array reaches{reach, reach}; + glm::dvec2 ringcentre{0.0}; + double ringradius{0.0}; + if (layout.roundabout && ring_circle(layout, T, ringcentre, ringradius)) + { + // the ring bends away from a road leaving it to the outside, so their edges meet sooner than on a straight road; and a road + // leaving at a slant meets the edge of the ring sooner on the side it leans away from. the room of a straight road, measured + // on the side the road leans towards, is the most a side takes + for (int side = 0; side < 2; ++side) + { + auto const room{editor_ring::edge_room(ringcentre, ringradius, glm::dvec2{centre.x, centre.z}, direction, side == 0 ? -along : along, halfwidth, branchhalfwidth)}; + if (room >= 0.0) + reaches[side] = std::min(reach, room + kCornerRoom); + } + } // where the road is cut on both sides of the centre road_cut cuts[2]; std::vector consumed; - if (false == follow(Road, T, false, reach, cuts[0], consumed, Error) || false == follow(Road, T, true, reach, cuts[1], consumed, Error)) + if (false == follow(Road, T, false, reaches[0], cuts[0], consumed, Error) || false == follow(Road, T, true, reaches[1], cuts[1], consumed, Error)) return false; if (cuts[0].road == cuts[1].road && cuts[0].road != &Road) { @@ -1928,7 +1971,8 @@ bool editor_road::branch_from(road_node &Road, double const T, glm::dvec2 const return true; } -bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error) +bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error) { Result = branch{}; auto const &layout{Junction.definition()}; @@ -1951,7 +1995,7 @@ bool editor_road::branch_from(junction_node &Junction, glm::dvec2 const &Directi { auto const &other{layout.arms[idx]}; auto const angle{std::acos(std::clamp(glm::dot(direction, other.direction), -1.0, 1.0))}; - if (angle < kSharpestBranch) + if (angle < road_limits_for(Type).sharpest_branch) { Error = "The road would leave too close to another road of the junction"; return false; diff --git a/editor/editorRoad.hpp b/editor/editorRoad.hpp index c1b23433f..fc70f846f 100644 --- a/editor/editorRoad.hpp +++ b/editor/editorRoad.hpp @@ -142,11 +142,14 @@ class editor_road // width shared by all lanes of the road at specified value of the curve parameter of its axis. returns: false if the lanes differ in width static bool lane_width(road_node::state const &State, double const T, float &Width); // lays out a junction for a road leaving the side of specified piece at specified value of the curve parameter of its axis. - // Direction: the way the road leaves; Incoming, Outgoing: lanes of that road leading into the junction and out of it. + // Direction: the way the road leaves; Incoming, Outgoing: lanes of that road leading into the junction and out of it; + // Type: what that road is made of, which sets how sharp an angle it can leave at. // nothing is changed until the result is carried out. returns: false if it can't be done, with the reason in Error - static bool branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error); + static bool branch_from(road_node &Road, double const T, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error); // the same for a road leaving a junction between its arms, which gives the junction another arm - static bool branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, branch &Result, std::string &Error); + static bool branch_from(junction_node &Junction, glm::dvec2 const &Direction, int const Incoming, int const Outgoing, float const Width, road_surface_type const Type, branch &Result, + std::string &Error); // makes the junction laid out for a branch, or gives the existing one its new arm, and cuts the roads to fit. what it does is added to Record. // returns: the junction static junction_node *carry_out(branch const &Branch, record &Record); @@ -156,8 +159,11 @@ class editor_road static loose_end find_end(glm::dvec3 const &Point, double const Radius, bool const Junctions = true); // lays out axes of the pieces for a road leading from a point to another. the directions are optional requirements // for the road at its ends; without them it starts straight at the target, with them it bends to meet them. + // Type: what the road is made of, which sets how tight it can bend and how short it can be; Halfwidth: of the road on each side + // of its axis, which no bend is tighter than (with some room). // returns: the axes in order, or nothing if there's no reasonable road to make, with the reason in Error - static std::vector plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, std::string &Error); + static std::vector plan(glm::dvec3 const &Start, glm::dvec2 const *Direction, glm::dvec3 const &Target, glm::dvec2 const *Enddirection, bool const Straight, + road_surface_type const Type, double const Halfwidth, std::string &Error); // cuts the pieces so none is longer than specified static std::vector refine(std::vector const &Pieces, double const Length); // gives a string of pieces a smooth profile running through provided heights. @@ -173,6 +179,13 @@ class editor_road // Radius: of the axis of that road; Layout: what the road is like. the lanes it has along its axis are the ones the roundabout gets. // Island: what the middle is covered with, "none" to leave the ground showing static std::vector roundabout(glm::dvec3 const &Centre, double const Radius, road_node::state const &Layout, std::string const &Island); + // the tool of the road window (0 select, 1 build, 2 place) Esc leaves. while a road is being drawn, or led out of the side of + // a road or a junction, or the selected points are dragged up or down, the tool in use stays and Esc gives that up; with + // nothing going on Esc goes back to the selection + static constexpr int tool_after_escape(int const Tool, bool const Drawing, bool const Lifting) + { + return (Drawing || Lifting) ? Tool : 0; + } private: // takes down what depends on the listed pieces and junctions, lets the caller change them, then builds it all again diff --git a/editor/editorRoadLimits.hpp b/editor/editorRoadLimits.hpp new file mode 100644 index 000000000..11822c6a8 --- /dev/null +++ b/editor/editorRoadLimits.hpp @@ -0,0 +1,52 @@ +/* +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 + +#include "world/RoadSurfaceType.h" + +#include +#include + +// how tight a road the road editor lays out, by what the road is made of +struct road_limits +{ + double tightest_radius; // smallest radius of a bend [m] + double shortest_road; // shortest road, and shortest piece left of a road cut for a junction [m] + double sharpest_branch; // smallest angle between two roads leaving a junction [rad] + // a road with both ends tied to a direction: the least part of the distance between the ends each end has to lead towards the other + double tied_lead; + double widest_turn; // a road with its start tied to a direction: the largest turn of the arc leading to the target [rad] +}; + +namespace editor_road_limits +{ + +inline constexpr double degree{std::numbers::pi / 180.0}; +// a paved road: the limits the editor had for every road before the types +inline constexpr road_limits paved{6.0, 2.0, 30.0 * degree, 0.1, 170.0 * degree}; +// a dirt road follows the ground between the fields: a tractor's bend, short stretches between the bends, a fork at a sharp angle, +// a hairpin, an end leading off square to the way to the other end +inline constexpr road_limits dirt{3.0, 1.0, 15.0 * degree, 0.0, 240.0 * degree}; +// room the inner edge of a bend keeps from the centre of the bend, as on a roundabout [m] +inline constexpr double inner_edge_room{1.0}; + +// smallest radius of a bend of a road with these limits, Halfwidth [m] wide on each side of its axis: the limit, and no less than +// leaves the inner edge of the road short of the centre of the bend, where the surface would fold over itself +inline double tightest_bend(road_limits const &Limits, double const Halfwidth) +{ + return std::max(Limits.tightest_radius, Halfwidth + inner_edge_room); +} + +} // namespace editor_road_limits + +inline constexpr road_limits road_limits_for(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? editor_road_limits::dirt : editor_road_limits::paved; +} diff --git a/editor/editorSwitchDrives.cpp b/editor/editorSwitchDrives.cpp new file mode 100644 index 000000000..8a6bbecfe --- /dev/null +++ b/editor/editorSwitchDrives.cpp @@ -0,0 +1,68 @@ +/* +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 "editor/editorSwitchDrives.hpp" + +#include +#include +#include + +namespace switch_drives +{ + +std::string game_name(std::string Name) +{ + std::ranges::replace(Name, '\\', '/'); + std::ranges::transform(Name, Name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return Name; +} + +standing_switches::standing_switches(finder Find, lister Names) : m_find{std::move(Find)}, m_names{std::move(Names)} {} + +bool standing_switches::stands(std::string const &Name) +{ + if (auto const removed{m_find(Name)}; removed.has_value()) + return false == *removed; + if (false == m_standing.has_value()) + { + m_standing.emplace(); + for (auto const &name : m_names()) + m_standing->insert(game_name(name)); + } + return m_standing->contains(game_name(Name)); +} + +bool standing_switches::any_stands(std::vector const &Names) +{ + return std::ranges::any_of(Names, [this](std::string const &Name) { return stands(Name); }); +} + +std::vector const &template_switches::of(std::string const &File, int const Revision, int const Frame, reader const &Read) +{ + if (m_revision != Revision) + { + m_files.clear(); + m_revision = Revision; + } + auto const [found, fresh]{m_files.try_emplace(File)}; + auto &entry{found->second}; + // read once; one that couldn't be read again in each frame at most, as each include of it asks + if (false == fresh && (false == entry.failed.has_value() || *entry.failed == Frame)) + return entry.suffixes; + entry.failed.reset(); + if (false == Read(File, entry.suffixes)) + { + entry.suffixes.clear(); + entry.failed = Frame; + } + return entry.suffixes; +} + +} // namespace switch_drives diff --git a/editor/editorSwitchDrives.hpp b/editor/editorSwitchDrives.hpp new file mode 100644 index 000000000..d21df9bec --- /dev/null +++ b/editor/editorSwitchDrives.hpp @@ -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 + +#include +#include +#include +#include +#include +#include + +// what the switch tool of the editor tells of the drives of the switches, with no track and no window of its own +namespace switch_drives +{ + +// a name as the game finds a track by it: '/' for '\', lower case +std::string game_name(std::string Name); + +// whether the switches a drive throws stand in the scenery, told by their names as the events of the drive find them in the game +class standing_switches +{ + public: + // nullopt when the name finds no track, else whether the track it finds is removed + using finder = std::function(std::string const &Name)>; + // the names of all the tracks of the scenery not removed, as they're written + using lister = std::function()>; + + standing_switches(finder Find, lister Names); + + // the track the name finds stands while it isn't removed. an older scenery may have two tracks of a name, the name finding the later + // one; deleted, it takes the name away, and the earlier one left still stands, so with no track found by the name any track of this + // name not removed counts + bool stands(std::string const &Name); + // a drive of a double switch throws four of them: it still throws one while one of them stands + bool any_stands(std::vector const &Names); + + private: + finder m_find; + lister m_names; + // the game names of the tracks not removed, read once, at the first name finding none + std::optional> m_standing; +}; + +// the switches each template of a drive throws, read once from each file while the templates found stay the same: a template changed +// on the disk is found again by a rescan or by its save in the editor, either changing the revision of the templates. a file which +// can't be read is read again, in a later frame, so a template missing for a moment isn't taken for one that isn't a drive until the +// next rescan +class template_switches +{ + public: + // what follows the first parameter in the names of the switches File throws, as editor_includes::switched_tracks() tells it. + // returns: false if the file can't be read + using reader = std::function &Suffixes)>; + + // the switches File throws, none for a template which isn't a drive or can't be read. Revision: of the templates found, Frame: the + // frame asked in. the reference holds until a call with another revision + std::vector const &of(std::string const &File, int Revision, int Frame, reader const &Read); + + private: + struct entry + { + std::vector suffixes; + std::optional failed; // the frame the file couldn't be read in + }; + std::map> m_files; + std::optional m_revision; +}; + +} // namespace switch_drives diff --git a/editor/editorTrack.cpp b/editor/editorTrack.cpp index f7237655e..e380cd440 100644 --- a/editor/editorTrack.cpp +++ b/editor/editorTrack.cpp @@ -26,6 +26,7 @@ http: #include "utilities/utilities.h" #include "utilities/parser.h" #include "utilities/Logs.h" +#include "utilities/asciiname.h" #include #include @@ -483,6 +484,12 @@ bool editor_track::name_valid(TTrack const &Track, std::string &Name, std::strin Reason = "The name can't hold blanks, quotes, semicolons or //"; return false; } + // the names the editor gives are plain ASCII: the code page of a scenery file decides what other letters turn into + if (false == ascii_name::plain(Name)) + { + Reason = "The name can hold ASCII only: no Polish letters or other characters outside of it"; + return false; + } auto *owner{simulation::Paths.find(Name)}; if (owner != nullptr && owner != &Track && false == owner->m_editorremoved) { @@ -3397,6 +3404,9 @@ void write_ending(std::ostream &Text, TTrack const &Style, bool const Switch) if ((Style.iCategoryFlag & 15) == 1 && false == Style.m_profile1.first.empty()) Text << "railprofile " << Style.m_profile1.first << ' '; Text << track_uneven::write_attribute(Style.m_uneven, Switch); + // the welded rail goes on in the piece; a buckle stays where it was + if (false == Switch && (Style.iCategoryFlag & 15) == 1) + Text << track_buckle::write_cwr(Style.m_cwr); // a piece of the track made from another one stays in its track circuit and under the same overhead line for (auto const *isolated : Style.Isolated) Text << "isolated " << isolated->asName << ' '; diff --git a/environment/weather.cpp b/environment/weather.cpp index df83e220d..74b2f1e82 100644 --- a/environment/weather.cpp +++ b/environment/weather.cpp @@ -15,6 +15,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include "simulation/simulationenvironment.h" +#include + namespace { @@ -57,9 +59,12 @@ std::string lower(std::string_view Text) return result; } +// a whole number of up to 9 digits, which std::stoi() reads without going out of the range of int: the numbers of the report are read +// with it only after this test, and a longer one (99999999999SM) threw std::out_of_range out of the parsing. the report comes from +// a memory cell, the weather panel or the scenery bool all_digits(std::string_view Text) { - return !Text.empty() && std::all_of(Text.begin(), Text.end(), [](char c) { return std::isdigit(static_cast(c)) != 0; }); + return !Text.empty() && (Text.size() <= 9) && std::ranges::all_of(Text, [](char c) { return std::isdigit(static_cast(c)) != 0; }); } // a number in the C locale, the whole token diff --git a/gl/glsl_common.cpp b/gl/glsl_common.cpp index f6f3df06d..bfe1a4716 100644 --- a/gl/glsl_common.cpp +++ b/gl/glsl_common.cpp @@ -53,8 +53,13 @@ void gl::glsl_common_setup() "#define WATER_MAP " + std::to_string(WATER_MAP) + "\n" + "#define WATER_GROUP_SIZE " + std::to_string(WATER_GROUP_SIZE) + "\n" + "#define WATER_SSBO_BINDING " + std::to_string(WATER_SSBO_BINDING) + "\n" + + "#define RAIN_CELLS_SSBO_BINDING " + std::to_string(RAIN_CELLS_SSBO_BINDING) + "\n" + "#define WATER_UBO_BINDING " + std::to_string(WATER_UBO_BINDING) + "\n" + "#define WATER_MASK_TEX " + std::to_string(WATER_MASK_TEX) + "\n" + + "#define WATER_LAYER_TEXELS " + std::to_string(WATER_LAYER_TEXELS) + "\n" + + "#define WATER_LAYER_BANDS " + std::to_string(WATER_LAYER_BANDS) + "\n" + + "#define WATER_SNOW_ATLAS_TEX " + std::to_string(WATER_SNOW_ATLAS_TEX) + "\n" + + "#define WATER_SNOW_NORMAL_TEX " + std::to_string(WATER_SNOW_NORMAL_TEX) + "\n" + "#define INSTANCE_COUNTER_HEADER " + std::to_string(INSTANCE_COUNTER_HEADER) + "\n" + "#define INSTANCE_JOB_SLEEPERS " + std::to_string(INSTANCE_JOB_SLEEPERS) + "U\n" + "#define LIGHT_SSBO_BINDING " + std::to_string(LIGHT_SSBO_BINDING) + "\n" + @@ -94,6 +99,7 @@ void gl::glsl_common_setup() "#define HEADLIGHT_SHADOW_TEX " + std::to_string(HEADLIGHT_SHADOW_TEX) + "\n" + "#define MAX_HEADLIGHT_SHADOWS " + std::to_string(MAX_HEADLIGHT_SHADOWS) + "U\n" + "#define MAX_CAB_PROBE_LAMPS " + std::to_string(MAX_CAB_PROBE_LAMPS) + "U\n" + + "#define WIPER_PASS_BUCKETS " + std::to_string(WIPER_PASS_BUCKETS) + "\n" + "#define FOG_VOLUME_TEX " + std::to_string(FOG_VOLUME_TEX) + "\n" + "#define CLOUD_SHADOW_TEX " + std::to_string(CLOUD_SHADOW_TEX) + "\n" + "#define CLOUD_TEX " + std::to_string(CLOUD_TEX) + "\n" + diff --git a/gl/streambuffer.cpp b/gl/streambuffer.cpp index 070723aaa..4307027e1 100644 --- a/gl/streambuffer.cpp +++ b/gl/streambuffer.cpp @@ -3,13 +3,13 @@ #include #include -#include +#include #include "utilities/Logs.h" namespace { -// a single frame isn't given more than this; past it the frame waits for the gpu to finish everything and starts the buffer over +// a buffer of a frame doesn't grow past this; a frame which streams more goes on in further buffers of this size constexpr GLsizeiptr STREAM_SIZE_MAX = 256 * 1024 * 1024; constexpr GLbitfield STREAM_MAP_FLAGS = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT; @@ -159,25 +159,21 @@ GLintptr gl::frame_stream::reserve(GLsizeiptr Size) { auto const needed{m_start + align_up(Size, m_alignment)}; auto const size{needed > STREAM_SIZE_MAX ? needed : std::min(std::max(needed, 2 * current->size), STREAM_SIZE_MAX)}; - if (size > current->size) + if (size <= current->size) { - // a bigger buffer for the rest of the frame, starting after its header again. the fence of the slot (if any) was - // waited for when the frame took the slot over, the old buffer is only read by this frame, which may still bind it - // for what it wrote there (a recorded draw drawn later), so it's kept, mapped, until the slot is taken over again - m_retired[m_slot].push_back(current->buffer); - current->buffer = 0; - current->data = nullptr; - current->size = 0; - create(*current, size); - ++m_grows; - } - else - { - // the frame wrote as much as a buffer may hold: start it over once the gpu read all of it - ErrorLog("Bad buffer: a frame streamed more than " + std::to_string(STREAM_SIZE_MAX / (1024 * 1024)) + " MiB, waiting for the gpu"); - glFinish(); - ++m_waits; + // the frame wrote as much as a buffer may hold. what it wrote may still be bound by draws it makes later, so it isn't + // written over: the rest of the frame goes to another buffer of the same size + ErrorLog(std::format("Bad buffer: a frame streamed more than {} MiB, another buffer is made for it", STREAM_SIZE_MAX / (1024 * 1024))); } + // a new buffer for the rest of the frame, starting after its header again. the fence of the slot (if any) was waited for + // when the frame took the slot over, the old buffer is only read by this frame, which may still bind it for what it + // wrote there (a recorded draw drawn later), so it's kept, mapped, until the slot is taken over again + m_retired[m_slot].push_back(current->buffer); + current->buffer = 0; + current->data = nullptr; + current->size = 0; + create(*current, size); + ++m_grows; offset = m_start; } m_fill = offset + Size; diff --git a/gl/ubo.h b/gl/ubo.h index 321e1af61..6ee7d5d9a 100644 --- a/gl/ubo.h +++ b/gl/ubo.h @@ -4,6 +4,7 @@ #include "bindable.h" #include "buffer.h" #include +#include #include #include #include @@ -72,6 +73,9 @@ namespace gl const size_t MAX_HEADLIGHT_SHADOWS = 4; // lights of the occupied cab the probe of the cab is drawn with (gfx::cab_probe, gl::scene_ubs::cab_probe_lamp), at most const size_t MAX_CAB_PROBE_LAMPS = 16; + // the places along the sweep of a blade (dWiperPos 0 .. 1) the rain fallen when it last went over them is kept for + // (gl::scene_ubs::wiper_rain_pass) + const size_t WIPER_PASS_BUCKETS = 64; // weather (opengl46_weather): the fog of the main view (3d, apply_fog.glsl) and the shadows the clouds cast (2d), read by the // shading. bound directly, like the ones above const size_t FOG_VOLUME_TEX = MAX_TEXTURES + HELPER_TEXTURES + 4; @@ -153,7 +157,8 @@ namespace gl // as realistic (gfx.water.realistic, water_surface.glsl), 0 as before glm::vec4 env_params; // the water on the windscreens (mat_rain_windscreen): xyz the velocity of the air against the vehicle of the camera (the - // share of the wind the particles of the rain drift with, less the velocity of the vehicle), world space, m/s; w unused + // share of the wind the particles of the rain drift with, less the velocity of the vehicle), world space, m/s; w the insects + // the vehicle met so far (mat_bugs_windscreen): seconds of driving at 100 km/h, none below 20 km/h, more the faster glm::vec4 rain_wind; // the ambient occlusion in the light of the surfaces (gfx.postfx.ao.lighting), set only for the colour pass of the main view, // zero elsewhere: x 1 when SCENE_AO_TEX holds the occlusion of the depth in SCENE_DEPTH_TEX, y the power it's raised to @@ -196,9 +201,50 @@ namespace gl glm::vec4 cab_probe_sun_color; glm::vec4 cab_probe_sun_box; glm::vec4 cab_probe_sun_world; + // the insects the vehicle had met (rain_wind.w) when the blades were at the ends of their sweep, as wiper_timer_out and + // wiper_timer_return (mat_bugs_windscreen: what hit the glass since a blade went over it); -1 not known + glm::vec4 wiper_bugs_out; + glm::vec4 wiper_bugs_return; + // the place of the camera of the pass in the world, which the models are drawn relative to: xyz of camera_hi the place + // rounded down to whole 64 metres, of camera_lo the rest (both exact in floats), w unused. mat_vat.vert puts a model in the + // world with them, inv_view and its modelview (the moment of its animation from its place) + glm::vec4 camera_hi; + glm::vec4 camera_lo; + // the rain the glass meets (mat_rain_windscreen): x the rain fallen so far, in seconds of the heaviest rain standing still (more + // at speed: the glass runs into it); y how wet the glass is, 0 dry .. 1 as full of drops as it gets (it fills with the rain, + // dries when it stops); z how fast the glass fills: the share left to fill goes down as exp(-z x the rain fallen); w 1 when the + // cells of the rain (RAIN_CELLS_SSBO_BINDING) were worked out in this frame, 0 else: the glasses read them only then + glm::vec4 rain_state; + // the rain fallen (rain_state.x) when a blade last went over a place of its sweep: element b for the places b / 64 .. (b + 1) + // / 64 of dWiperPos (the value of the wiper mask of a pixel), x .. w the blades (as wiper_pos); -1 not known. the drops and the + // haze come back with the rain fallen since. (the moments the blades were at the ends of their sweep, which the pixel took + // the one of by the way the blade went, gave the rain of a whole sweep back to the place a blade had just wiped) + glm::vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; - static_assert(sizeof(scene_ubs) == 928 + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + static_assert(sizeof(scene_ubs) == 1008 + 16 * WIPER_PASS_BUCKETS + 80 * MAX_HEADLIGHT_SHADOWS + 96 * MAX_CAB_PROBE_LAMPS, "bad size of ubs"); + + // the bucket of scene_ubs::wiper_rain_pass a place of a blade (dWiperPos, 0 .. 1) falls in + inline std::size_t wiper_pass_bucket(double const Position) + { + return std::min(static_cast(std::max(Position, 0.0) * static_cast(WIPER_PASS_BUCKETS)), WIPER_PASS_BUCKETS - 1); + } + + // the places blade Wiper went over from From to To (dWiperPos) get the rain fallen Value (-1: not known) + inline void wiper_pass_mark(scene_ubs &Scene, glm::length_t const Wiper, double const From, double const To, float const Value) + { + auto const last{wiper_pass_bucket(std::max(From, To))}; + for (auto bucket{wiper_pass_bucket(std::min(From, To))}; bucket <= last; ++bucket) + Scene.wiper_rain_pass[bucket][Wiper] = Value; + } + + // the camera of a pass in the world for the scene block (scene_ubs::camera_hi, camera_lo) + inline void set_camera_place(scene_ubs &Ubs, glm::dvec3 const &Place) + { + auto const high{glm::floor(Place / 64.0) * 64.0}; + Ubs.camera_hi = glm::vec4{glm::vec3{high}, 0.f}; + Ubs.camera_lo = glm::vec4{glm::vec3{Place - high}, 0.f}; + } const size_t MAX_PARAMS = 3; @@ -687,13 +733,32 @@ namespace gl const GLuint WATER_CELL_DROPS = 32; const GLuint WATER_TRAIL = 1024; const GLuint WATER_MAP = 256; + // the snow of a glass laid together (water_snowlayer.comp): WATER_LAYER_TEXELS texels over the rectangle of its uv the glass + // takes (across and down as the glass is wide and high, ~1 mm a texel), a band of every WATER_LAYER_BANDS-th row laid anew in + // a step (and wherever a blade goes over it), read by mat_snow_windscreen.frag. one layer: the first glass of the snow of the + // cab has it (a cab has one glass of the snow as a rule), the others lay their snow at every pixel as they're drawn + const GLuint WATER_LAYER_TEXELS = 2 * 1024 * 1024; + const GLuint WATER_LAYER_BANDS = 8; const GLuint WATER_GROUP_SIZE = 64; // the binding points of the opengl renderer: the storage of the water (read by the glasses, written by the passes), the block // of the step of the simulation (water_ubs) and the texture unit of the mask of the wipers the map is baked from. the storage // point is used by nothing else, bound with the colour passes const GLuint WATER_SSBO_BINDING = 16; + // the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp, rain_cells.glsl): worked + // out once a frame for every cell, so a glass only reads them. RAIN_CELLS_COUNT uvec4, as rain_cells.glsl lays them out + const GLuint RAIN_CELLS_SSBO_BINDING = 18; + const size_t RAIN_DROP_CELLS = 512; + const size_t RAIN_RIV_CELLS = 128; + const size_t RAIN_RIV_LAYERS = 5; + // the cells (the first pass of rain_cells.comp), then the reach of the drops into the quarters of each drop cell (the second) + const size_t RAIN_MASK_BASE = RAIN_DROP_CELLS * RAIN_DROP_CELLS + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS; + const size_t RAIN_CELLS_COUNT = RAIN_MASK_BASE + RAIN_DROP_CELLS * RAIN_DROP_CELLS; + const size_t RAIN_CELLS_GROUP_SIZE = 64; const GLuint WATER_UBO_BINDING = 6; const size_t WATER_MASK_TEX = MAX_TEXTURES + HELPER_TEXTURES + 13; + // the atlas and the normal map of the snow of a glass, for the laying of its snow (water_snowlayer.comp) + const size_t WATER_SNOW_ATLAS_TEX = MAX_TEXTURES + HELPER_TEXTURES + 20; + const size_t WATER_SNOW_NORMAL_TEX = MAX_TEXTURES + HELPER_TEXTURES + 21; // the parts of the storage of the water (std430, GLSL water_ssbo), offsets in bytes: the header of every glass (vec4), the // counts of every glass (uvec4), the drops (two vec4 each), the axes of the map (two vec4 a texel), the blades of the map (vec4 // a texel), the state of the drops (uint), the drops they flow into (uint), what they gather (four int), what they keep @@ -712,10 +777,24 @@ namespace gl const size_t WATER_CELLS_OFFSET = WATER_EXTRA_OFFSET + 16 * WATER_SLOT_DROPS; const size_t WATER_CELLS_SIZE = 4 * static_cast(WATER_SLOTS) * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS); const size_t WATER_TRAIL_OFFSET = WATER_CELLS_OFFSET + WATER_CELLS_SIZE; - const size_t WATER_STORAGE_SIZE = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; + // the snow on the glasses (water_snow.comp, mat_snow_windscreen.frag): two maps of every glass, WATER_MAP x WATER_MAP texels of + // two uint each (four halves: the snow, mm; the water, mm; how packed the snow is, 0 .. 1; random 0 .. 1, the shape of its + // flakes), a step reads one and writes the other (the header of the glass says which one is the latest) + const size_t WATER_SNOW_OFFSET = WATER_TRAIL_OFFSET + 4 * static_cast(WATER_SLOTS) * WATER_TRAIL * WATER_TRAIL; + const size_t WATER_SNOW_SIZE = 8 * static_cast(WATER_MAP) * WATER_MAP; + // the snow of the glass of the snow laid together (water_snowlayer.comp): first eight uint of every glass (the rectangle of its + // uv the layer takes, four floats; the texels of the layer across and down, 0 when the glass has no layer), then the layer, + // WATER_LAYER_TEXELS texels of four uint each (the sprites of the snow coming within the texel, see water.glsl and + // snow_sprites.glsl) + const size_t WATER_LAYER_INFO_OFFSET = WATER_SNOW_OFFSET + 2 * WATER_SNOW_SIZE * WATER_SLOTS; + const size_t WATER_LAYER_INFO_SIZE = 32; + const size_t WATER_LAYER_OFFSET = WATER_LAYER_INFO_OFFSET + WATER_LAYER_INFO_SIZE * WATER_SLOTS; + const size_t WATER_LAYER_SIZE = 16 * static_cast(WATER_LAYER_TEXELS); + const size_t WATER_STORAGE_SIZE = WATER_LAYER_OFFSET + WATER_LAYER_SIZE; // the parts of a glass in the storage: its drops and what the passes keep of them, its map (the axes the second part), its - // cells and its paths, its header and its counts, (offset, size) in bytes - inline std::array, 11> water_slot_parts(size_t const Slot) + // cells and its paths, its header and its counts, its two maps of the snow, the layer of the snow (the one of the cab, laid + // anew whichever glass it goes to), (offset, size) in bytes + inline std::array, 14> water_slot_parts(size_t const Slot) { auto const drops{static_cast(WATER_DROPS)}; auto const texels{static_cast(WATER_MAP) * WATER_MAP}; @@ -731,7 +810,10 @@ namespace gl {WATER_CELLS_OFFSET + cells * Slot, cells}, {WATER_TRAIL_OFFSET + trail * Slot, trail}, {WATER_HEADER_OFFSET + 16 * Slot, 16}, - {WATER_COUNTS_OFFSET + 16 * Slot, 16}}}; + {WATER_COUNTS_OFFSET + 16 * Slot, 16}, + {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * Slot, WATER_SNOW_SIZE}, + {WATER_SNOW_OFFSET + WATER_SNOW_SIZE * (WATER_SLOTS + Slot), WATER_SNOW_SIZE}, + {WATER_LAYER_OFFSET, WATER_LAYER_SIZE}}}; } // layout std140: the step of the simulation of the water on the windscreens (GLSL water_ubo), every vector in the space of the @@ -754,14 +836,21 @@ namespace gl // glass), y: 1 / the mean of the diameters above it, 1 / mm (they go as Marshall-Palmer), zw: unused glm::vec4 rain; // x: random seed of the step, y: the most landings tried on a glass in the step, z: the glass the passes for a single glass - // work on (the baking of the mask of the wipers) + // work on (the baking of the mask of the wipers, the laying of the snow), w: the step (the band of rows the laying of the + // snow lays anew) glm::uvec4 counts; // every glass: x the landings tried in the step, y 1 / the most metres squared of the glass a unit of its uv holds (the // landings tried at the densest place are all taken), z 1 when it's simulated, w the size of its drops (the param // rain_scale of its material) glm::vec4 slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the + // air the glass is (the cab heats it), degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + glm::vec4 snow; + // every glass: 1 when its snow is simulated + glm::vec4 snow_slots; }; - static_assert(sizeof(water_ubs) == 112 + 16 * WATER_SLOTS, "bad size of water_ubs"); + static_assert(WATER_SLOTS == 4, "snow_slots holds a glass in a component"); + static_assert(sizeof(water_ubs) == 144 + 16 * WATER_SLOTS, "bad size of water_ubs"); // layout std430: a bucket of a scene cell queued in the pass (GLSL: instance_cull_job) struct instance_cull_job diff --git a/input/command.cpp b/input/command.cpp index 0c81b82ec..5ca2dfe83 100644 --- a/input/command.cpp +++ b/input/command.cpp @@ -423,6 +423,42 @@ commanddescription_sequence Commands_descriptions = { {"linebreakeropenc", command_target::vehicle, command_mode::oneoff}, {"linebreakerclosec", command_target::vehicle, command_mode::oneoff}, {"repaircoupler", command_target::simulation, command_mode::oneoff}, + {"genericset0", command_target::vehicle, command_mode::oneoff}, + {"genericset1", command_target::vehicle, command_mode::oneoff}, + {"genericset2", command_target::vehicle, command_mode::oneoff}, + {"genericset3", command_target::vehicle, command_mode::oneoff}, + {"genericset4", command_target::vehicle, command_mode::oneoff}, + {"genericset5", command_target::vehicle, command_mode::oneoff}, + {"genericset6", command_target::vehicle, command_mode::oneoff}, + {"genericset7", command_target::vehicle, command_mode::oneoff}, + {"genericset8", command_target::vehicle, command_mode::oneoff}, + {"genericset9", command_target::vehicle, command_mode::oneoff}, + {"genericset10", command_target::vehicle, command_mode::oneoff}, + {"genericset11", command_target::vehicle, command_mode::oneoff}, + {"genericset12", command_target::vehicle, command_mode::oneoff}, + {"genericset13", command_target::vehicle, command_mode::oneoff}, + {"genericset14", command_target::vehicle, command_mode::oneoff}, + {"genericset15", command_target::vehicle, command_mode::oneoff}, + {"genericset16", command_target::vehicle, command_mode::oneoff}, + {"genericset17", command_target::vehicle, command_mode::oneoff}, + {"genericset18", command_target::vehicle, command_mode::oneoff}, + {"genericset19", command_target::vehicle, command_mode::oneoff}, + {"genericset20", command_target::vehicle, command_mode::oneoff}, + {"genericset21", command_target::vehicle, command_mode::oneoff}, + {"genericset22", command_target::vehicle, command_mode::oneoff}, + {"genericset23", command_target::vehicle, command_mode::oneoff}, + {"genericset24", command_target::vehicle, command_mode::oneoff}, + {"genericset25", command_target::vehicle, command_mode::oneoff}, + {"genericset26", command_target::vehicle, command_mode::oneoff}, + {"genericset27", command_target::vehicle, command_mode::oneoff}, + {"genericset28", command_target::vehicle, command_mode::oneoff}, + {"genericset29", command_target::vehicle, command_mode::oneoff}, + {"tractionmodetoggle", command_target::vehicle, command_mode::oneoff}, + {"tractionmodecatenary", command_target::vehicle, command_mode::oneoff}, + {"tractionmodegenset", command_target::vehicle, command_mode::oneoff}, + {"gensettoggle", command_target::vehicle, command_mode::oneoff}, + {"gensetenable", command_target::vehicle, command_mode::oneoff}, + {"gensetdisable", command_target::vehicle, command_mode::oneoff}, {"flashlighttoggle", command_target::simulation, command_mode::oneoff}, }; @@ -826,6 +862,42 @@ std::unordered_map const commandMap = { {"linebreakeropenc", user_command::linebreakeropenc}, {"linebreakerclosec", user_command::linebreakerclosec}, {"repaircoupler", user_command::repaircoupler}, + {"genericset0", user_command::genericset0}, + {"genericset1", user_command::genericset1}, + {"genericset2", user_command::genericset2}, + {"genericset3", user_command::genericset3}, + {"genericset4", user_command::genericset4}, + {"genericset5", user_command::genericset5}, + {"genericset6", user_command::genericset6}, + {"genericset7", user_command::genericset7}, + {"genericset8", user_command::genericset8}, + {"genericset9", user_command::genericset9}, + {"genericset10", user_command::genericset10}, + {"genericset11", user_command::genericset11}, + {"genericset12", user_command::genericset12}, + {"genericset13", user_command::genericset13}, + {"genericset14", user_command::genericset14}, + {"genericset15", user_command::genericset15}, + {"genericset16", user_command::genericset16}, + {"genericset17", user_command::genericset17}, + {"genericset18", user_command::genericset18}, + {"genericset19", user_command::genericset19}, + {"genericset20", user_command::genericset20}, + {"genericset21", user_command::genericset21}, + {"genericset22", user_command::genericset22}, + {"genericset23", user_command::genericset23}, + {"genericset24", user_command::genericset24}, + {"genericset25", user_command::genericset25}, + {"genericset26", user_command::genericset26}, + {"genericset27", user_command::genericset27}, + {"genericset28", user_command::genericset28}, + {"genericset29", user_command::genericset29}, + {"tractionmodetoggle", user_command::tractionmodetoggle}, + {"tractionmodecatenary", user_command::tractionmodecatenary}, + {"tractionmodegenset", user_command::tractionmodegenset}, + {"gensettoggle", user_command::gensettoggle}, + {"gensetenable", user_command::gensetenable}, + {"gensetdisable", user_command::gensetdisable}, {"flashlighttoggle", user_command::flashlighttoggle}, {"none", user_command::none}}; diff --git a/input/command.h b/input/command.h index 3b2955d15..f6dc95409 100644 --- a/input/command.h +++ b/input/command.h @@ -421,6 +421,44 @@ enum class user_command linebreakeropenc, linebreakerclosec, repaircoupler, // the broken coupler of the vehicle (payload) at the end (param1) + // sets universal control N to the position given in param1, 0-1 (MaSzyna-EU07/maszyna#62) + genericset0, + genericset1, + genericset2, + genericset3, + genericset4, + genericset5, + genericset6, + genericset7, + genericset8, + genericset9, + genericset10, + genericset11, + genericset12, + genericset13, + genericset14, + genericset15, + genericset16, + genericset17, + genericset18, + genericset19, + genericset20, + genericset21, + genericset22, + genericset23, + genericset24, + genericset25, + genericset26, + genericset27, + genericset28, + genericset29, + // the traction selector and the genset of a dual-mode vehicle (eu07/maszyna#536) + tractionmodetoggle, + tractionmodecatenary, + tractionmodegenset, + gensettoggle, + gensetenable, + gensetdisable, // the flashlight of the player (Global.flashlight), at the end so the numbers of the commands before it stay as they were flashlighttoggle, none = -1 diff --git a/input/driverkeyboardinput.cpp b/input/driverkeyboardinput.cpp index fd70b2f70..b0cb7a65c 100644 --- a/input/driverkeyboardinput.cpp +++ b/input/driverkeyboardinput.cpp @@ -103,6 +103,12 @@ driverkeyboard_input::default_bindings() { { fuelpumptoggle, {GLFW_KEY_F, ""} }, // fuelpumpenable, // fuelpumpdisable, + { tractionmodetoggle, {GLFW_KEY_G | keymodifier::shift, ""} }, + // tractionmodecatenary, + // tractionmodegenset, + { gensettoggle, {GLFW_KEY_G | keymodifier::control, ""} }, + // gensetenable, + // gensetdisable, { oilpumptoggle, {GLFW_KEY_F | keymodifier::shift, ""} }, // oilpumpenable, // oilpumpdisable, diff --git a/input/drivermouseinput.cpp b/input/drivermouseinput.cpp index 9749024ac..bc13495b0 100644 --- a/input/drivermouseinput.cpp +++ b/input/drivermouseinput.cpp @@ -21,6 +21,8 @@ http://mozilla.org/MPL/2.0/. #include "application/uilayer.h" #include "utilities/Logs.h" #include "utilities/utilities.h" +#include "physics/vehicle.h" +#include "vehicle/DynObj.h" auto const EU07_CONTROLLER_MOUSESLIDERSIZE{ 0.6 }; @@ -28,9 +30,11 @@ void mouse_slider::bind( user_command const &Command ) { m_command = Command; + m_universal.reset(); + m_universaldrag.reset(); auto const *train { simulation::Train }; - TMoverParameters const *vehicle { nullptr }; + physics::Vehicle const *vehicle { nullptr }; switch( m_command ) { using enum user_command; case jointcontrollerset: @@ -59,7 +63,7 @@ mouse_slider::bind( user_command const &Command ) { auto const powerrange { static_cast( vehicle->CoupledCtrl ? - vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo : + vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo() : vehicle->MainCtrlPosNo ) }; // for simplicity upper half of the range controls power, lower controls brakes @@ -67,37 +71,37 @@ mouse_slider::bind( user_command const &Command ) { m_value = 0.5 + 0.5 * ( vehicle->CoupledCtrl ? - vehicle->MainCtrlPos + vehicle->ScndCtrlPos : - vehicle->MainCtrlPos ) / powerrange - - 0.5 * occupied->LocalBrakePosA; + vehicle->MainCtrlPos() + vehicle->ScndCtrlPos() : + vehicle->MainCtrlPos() ) / powerrange + - 0.5 * occupied->brakes.IndependentPosition(); m_analogue = true; m_invertrange = false; break; } case user_command::mastercontrollerset: { - m_valuerange = vehicle->CoupledCtrl ? vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo : vehicle->MainCtrlPosNo; - m_value = vehicle->CoupledCtrl ? vehicle->MainCtrlPos + vehicle->ScndCtrlPos : vehicle->MainCtrlPos; + m_valuerange = vehicle->CoupledCtrl ? vehicle->MainCtrlPosNo + vehicle->ScndCtrlPosNo() : vehicle->MainCtrlPosNo; + m_value = vehicle->CoupledCtrl ? vehicle->MainCtrlPos() + vehicle->ScndCtrlPos() : vehicle->MainCtrlPos(); m_analogue = false; m_invertrange = false; break; } case user_command::secondcontrollerset: { - m_valuerange = vehicle->ScndCtrlPosNo; - m_value = vehicle->ScndCtrlPos; + m_valuerange = vehicle->ScndCtrlPosNo(); + m_value = vehicle->ScndCtrlPos(); m_analogue = false; m_invertrange = true; break; } case user_command::trainbrakeset: { m_valuerange = 1.0; - m_value = ( vehicle->fBrakeCtrlPos - vehicle->Handle->GetPos( bh_MIN ) ) / ( vehicle->Handle->GetPos( bh_MAX ) - vehicle->Handle->GetPos( bh_MIN ) ); + m_value = ( vehicle->brakes.HandlePositionSmooth() - vehicle->brakes.driverValve->GetPos( bh_MIN ) ) / ( vehicle->brakes.driverValve->GetPos( bh_MAX ) - vehicle->brakes.driverValve->GetPos( bh_MIN ) ); m_analogue = true; m_invertrange = true; break; } case user_command::independentbrakeset: { m_valuerange = 1.0; - m_value = vehicle->LocalBrakePosA; + m_value = vehicle->brakes.IndependentPosition(); m_analogue = true; m_invertrange = true; break; @@ -124,18 +128,47 @@ mouse_slider::bind( user_command const &Command ) { m_analogue ? controledge - m_value * controlsize : controledge - m_value * stepsize - 0.5 * stepsize ); } +void +mouse_slider::bind_universal( int const Index, universal_drag::direction const Drag, float const Position ) { + + m_command = static_cast( static_cast( user_command::genericset0 ) + Index ); + m_universal = Index; + m_universaldrag.emplace( Drag, Position ); + m_value = m_universaldrag->position(); + m_valuerange = 1.0; + m_analogue = true; + m_invertrange = false; + // the cursor is hidden for the drag and put back where it was when the drag ends; the drag follows its moves + // from wherever it is, so it isn't placed anywhere + m_cursorposition = glm::dvec2( Global.cursor_pos ); + Application.set_cursor( GLFW_CURSOR_DISABLED ); +} + void mouse_slider::release() { m_command = user_command::none; + m_universal.reset(); + m_universaldrag.reset(); Application.set_cursor_pos( m_cursorposition.x, m_cursorposition.y ); Application.set_cursor( GLFW_CURSOR_NORMAL ); } -void -mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { +bool +mouse_slider::on_move( double const Mousex, double const Mousey ) { auto const controlsize { Global.window_size.y * EU07_CONTROLLER_MOUSESLIDERSIZE }; + + if( m_universaldrag ) { + // a universal control, dragged the same way as the controllers: the move of the cursor over the size of the + // slider takes it from one end to the other + if( false == m_universaldrag->move( Mousex, Mousey, controlsize ) ) { + return false; + } + m_value = m_universaldrag->position(); + return true; + } + auto const controledge { Global.window_size.y * 0.5 + controlsize * 0.5 }; auto const stepsize { controlsize / m_valuerange }; @@ -143,6 +176,7 @@ mouse_slider::on_move( double const /*Mousex*/, double const Mousey ) { m_value = m_analogue ? (controledge - mousey) / controlsize : std::floor((controledge - mousey) / stepsize); if( m_invertrange ) { m_value = ( m_analogue ? 1.0 : m_valuerange ) - m_value; } + return true; } @@ -246,8 +280,8 @@ drivermouse_input::move( double Mousex, double Mousey ) { } else { // control picking mode - if( m_slider.command() != user_command::none ) { - m_slider.on_move( Mousex, Mousey ); + if( m_slider.command() != user_command::none + && true == m_slider.on_move( Mousex, Mousey ) ) { m_relay.post( m_slider.command(), m_slider.value(), @@ -341,7 +375,14 @@ drivermouse_input::button( int const Button, int const Action ) { else { m_pickwaiting = false; if (Button == GLFW_MOUSE_BUTTON_LEFT && m_slider.command() != user_command::none) { - m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + if( auto const universal { m_slider.universal() }; + universal && m_slider.is_click() ) { + // a universal control clicked rather than dragged goes to its end, as a click on any universal does + toggle_universal( *universal ); + } + else { + m_relay.post( m_slider.command(), 0, 0, Action, 0 ); + } m_slider.release(); } // if it's the right mouse button that got released and we had no command active, we were potentially in view panning mode; stop it @@ -392,6 +433,25 @@ drivermouse_input::button( int const Button, int const Action ) { default: { break; } } } + // a universal control with drag: in its definition is dragged to any position between its ends, + // and a click without dragging toggles it as before (MaSzyna-EU07/maszyna#62) + if( Button == GLFW_MOUSE_BUTTON_LEFT ) { + auto const universal { universal_index( mousecommand ) }; + auto const drag { + universal ? + simulation::Train->universal_drag_direction( *universal ) : + universal_drag::direction::none }; + if( drag != universal_drag::direction::none ) { + mousecommand = none; + if( false == pickwaiting ) { + // the button was let go before the control was found under the cursor: a click + toggle_universal( *universal ); + return; + } + m_slider.bind_universal( *universal, drag, simulation::Train->universal_position( *universal ) ); + return; + } + } switch( mousecommand ) { case mastercontrollerincrease: @@ -558,6 +618,9 @@ drivermouse_input::default_bindings() { { "maxcurrent_sw:", { motoroverloadrelaythresholdtoggle, none } }, + { "autorelay_sw:", { + notchingrelaytoggle, + none } }, { "waterpumpbreaker_sw:", { waterpumpbreakertoggle, none } }, @@ -579,6 +642,12 @@ drivermouse_input::default_bindings() { { "oilfuelpump_sw:", { oilfuelpumptoggle, none } }, + { "tractionmode_sw:", { + tractionmodetoggle, + none } }, + { "genset_sw:", { + gensettoggle, + none } }, { "motorblowersfront_sw:", { motorblowerstogglefront, none } }, @@ -1171,4 +1240,23 @@ drivermouse_input::adjust_command( user_command Command ) const { return Command; } +std::optional +drivermouse_input::universal_index( user_command const Command ) { + + auto const index { static_cast( Command ) - static_cast( user_command::generictoggle0 ) }; + if( index < 0 + || index > static_cast( user_command::generictoggle29 ) - static_cast( user_command::generictoggle0 ) ) { + return std::nullopt; + } + return index; +} + +void +drivermouse_input::toggle_universal( int const Index ) const { + + auto const toggle { static_cast( static_cast( user_command::generictoggle0 ) + Index ) }; + m_relay.post( toggle, 0, 0, GLFW_PRESS, 0 ); + m_relay.post( toggle, 0, 0, GLFW_RELEASE, 0 ); +} + //--------------------------------------------------------------------------- diff --git a/input/drivermouseinput.h b/input/drivermouseinput.h index 180e0335c..aa2ac0ca3 100644 --- a/input/drivermouseinput.h +++ b/input/drivermouseinput.h @@ -9,8 +9,10 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include "input/command.h" +#include "vehicle/universaldrag.h" // virtual slider; value determined by position of the mouse class mouse_slider { @@ -21,9 +23,14 @@ public: // methods void bind( user_command const &Command ); + // binds the slider to universal control Index, which the mouse drags in the Drag direction from its Position + // to any position between its ends (MaSzyna-EU07/maszyna#62) + void + bind_universal( int const Index, universal_drag::direction const Drag, float const Position ); void release(); - void + // returns whether the value changed + bool on_move( double const Mousex, double const Mousey ); inline user_command @@ -32,10 +39,19 @@ public: double value() const { return m_value; } + // the universal control the slider drags, if any, and whether letting it go now is a click rather than a drag + std::optional + universal() const { + return m_universal; } + bool + is_click() const { + return m_universaldrag && m_universaldrag->is_click(); } private: // members user_command m_command { user_command::none }; + std::optional m_universal; // the universal control dragged, if any + std::optional m_universaldrag; double m_value { 0.0 }; double m_valuerange { 0.0 }; bool m_analogue { false }; @@ -92,6 +108,12 @@ private: // potentially replaces supplied command with a more relevant one user_command adjust_command( user_command Command ) const; + // the universal control a command toggles, if it toggles one + static std::optional + universal_index( user_command const Command ); + // toggles universal control Index, as a click on it does + void + toggle_universal( int const Index ) const; // members command_relay m_relay; diff --git a/input/messaging.cpp b/input/messaging.cpp index 66a39e7d5..72ef70058 100644 --- a/input/messaging.cpp +++ b/input/messaging.cpp @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Driver.h" #include "world/mtable.h" #include "utilities/Logs.h" +#include "physics/vehicle.h" #ifdef _WIN32 extern "C" @@ -187,7 +188,7 @@ OnCommandGet(multiplayer::DaneRozkaz const *pRozkaz) d->Damage( pRozkaz->cString[ 0 ] ); d = d->Prev(); // w drugą stronę też } - WyslijUszkodzenia( lookup->asName, static_cast(lookup->MoverParameters->EngDmgFlag) ); // zwrot informacji o pojeździe + WyslijUszkodzenia( lookup->asName, static_cast(lookup->physics->equipmentFaults.Bits()) ); // zwrot informacji o pojeździe } break; default: @@ -272,40 +273,40 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) size_t j = Vehicle->asName.length(); r.iPar[0] = i; // ilość danych liczbowych r.fPar[1] = Global.fTimeAngleDeg / 360.0; // aktualny czas (1.0=doba) - r.fPar[2] = Vehicle->MoverParameters->Loc.X; // pozycja X - r.fPar[3] = Vehicle->MoverParameters->Loc.Y; // pozycja Y - r.fPar[4] = Vehicle->MoverParameters->Loc.Z; // pozycja Z - r.fPar[5] = Vehicle->MoverParameters->V; // prędkość ruchu X - r.fPar[6] = Vehicle->MoverParameters->nrot * M_PI * - Vehicle->MoverParameters->WheelDiameter; // prędkość obrotowa kóŁ + r.fPar[2] = Vehicle->physics->Loc().X; // pozycja X + r.fPar[3] = Vehicle->physics->Loc().Y; // pozycja Y + r.fPar[4] = Vehicle->physics->Loc().Z; // pozycja Z + r.fPar[5] = Vehicle->physics->V(); // prędkość ruchu X + r.fPar[6] = Vehicle->physics->nrot() * M_PI * + Vehicle->physics->WheelDiameter(); // prędkość obrotowa kóŁ r.fPar[7] = 0; // prędkość ruchu Z - r.fPar[8] = Vehicle->MoverParameters->AccS; // przyspieszenie X - r.fPar[9] = Vehicle->MoverParameters->AccN; // przyspieszenie Y //na razie nie - r.fPar[10] = Vehicle->MoverParameters->AccVert; // przyspieszenie Z - r.fPar[11] = Vehicle->MoverParameters->DistCounter; // przejechana odległość w km - r.fPar[12] = Vehicle->MoverParameters->PipePress; // ciśnienie w PG - r.fPar[13] = Vehicle->MoverParameters->ScndPipePress; // ciśnienie w PZ - r.fPar[14] = Vehicle->MoverParameters->BrakePress; // ciśnienie w CH - r.fPar[15] = Vehicle->MoverParameters->Compressor; // ciśnienie w ZG - r.fPar[16] = Vehicle->MoverParameters->Itot; // Prąd całkowity - r.iPar[17] = Vehicle->MoverParameters->MainCtrlPos; // Pozycja NJ - r.iPar[18] = Vehicle->MoverParameters->ScndCtrlPos; // Pozycja NB - r.iPar[19] = Vehicle->MoverParameters->MainCtrlActualPos; // Pozycja jezdna - r.iPar[20] = Vehicle->MoverParameters->ScndCtrlActualPos; // Pozycja bocznikowania - r.iPar[21] = Vehicle->MoverParameters->ScndCtrlActualPos; // Pozycja bocznikowania - r.iPar[22] = Vehicle->MoverParameters->ResistorsFlag * 1 - + Vehicle->MoverParameters->ConverterFlag * 2 - + Vehicle->MoverParameters->CompressorFlag * 4 - + Vehicle->MoverParameters->Mains * 8 + r.fPar[8] = Vehicle->physics->AccS(); // przyspieszenie X + r.fPar[9] = Vehicle->physics->AccN(); // przyspieszenie Y //na razie nie + r.fPar[10] = Vehicle->physics->AccVert(); // przyspieszenie Z + r.fPar[11] = Vehicle->physics->DistCounter(); // przejechana odległość w km + r.fPar[12] = Vehicle->physics->brakePipe.Pressure(); // ciśnienie w PG + r.fPar[13] = Vehicle->physics->mainPipe.Pressure(); // ciśnienie w PZ + r.fPar[14] = Vehicle->physics->brakes.cylinderPressure; // ciśnienie w CH + r.fPar[15] = Vehicle->physics->air.MainReservoirPressure(); // ciśnienie w ZG + r.fPar[16] = Vehicle->physics->Itot; // Prąd całkowity + r.iPar[17] = Vehicle->physics->MainCtrlPos(); // Pozycja NJ + r.iPar[18] = Vehicle->physics->ScndCtrlPos(); // Pozycja NB + r.iPar[19] = Vehicle->physics->MainCtrlActualPos; // Pozycja jezdna + r.iPar[20] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania + r.iPar[21] = Vehicle->physics->ScndCtrlActualPos; // Pozycja bocznikowania + r.iPar[22] = Vehicle->physics->ResistorsFlag * 1 + + Vehicle->physics->converter.IsRunning() * 2 + + Vehicle->physics->air.compressor.IsRunning() * 4 + + Vehicle->physics->lineBreaker.IsClosed() * 8 #ifdef EU07_USEOLDDOORCODE - + Vehicle->MoverParameters->DoorLeftOpened * 16 - + Vehicle->MoverParameters->DoorRightOpened * 32 + + Vehicle->physics->DoorLeftOpened * 16 + + Vehicle->physics->DoorRightOpened * 32 #else - + ( false == Vehicle->MoverParameters->Doors.instances[side::left].is_closed ) * 16 - + ( false == Vehicle->MoverParameters->Doors.instances[side::right].is_closed ) * 32 + + ( false == Vehicle->physics->Doors.instances[VehicleSide::left].is_closed ) * 16 + + ( false == Vehicle->physics->Doors.instances[VehicleSide::right].is_closed ) * 32 #endif - + Vehicle->MoverParameters->FuseFlag * 64 - + Vehicle->MoverParameters->DepartureSignal * 128; + + Vehicle->physics->FuseFlag * 64 + + Vehicle->physics->DepartureSignal() * 128; // WriteLog("Zapisalem stare"); // WriteLog("Mam patykow "+IntToStr(t->DynamicObject->iAnimType[ANIM_PANTS])); for (int p = 0; p < 4; p++) @@ -325,10 +326,10 @@ WyslijNamiary([[maybe_unused]] TDynamicObject const *Vehicle) // WriteLog("Zapisalem pantografy"); for (int p = 0; p < 3; p++) r.fPar[27 + p] = - Vehicle->MoverParameters->ShowCurrent(p + 1); // amperomierze kolejnych grup + Vehicle->physics->ShowCurrent(p + 1); // amperomierze kolejnych grup // WriteLog("zapisalem prady"); - r.iPar[30] = Vehicle->MoverParameters->WarningSignal; // trabienie - r.fPar[31] = Vehicle->MoverParameters->PantographVoltage; // napiecie WN + r.iPar[30] = Vehicle->physics->WarningSignal(); // trabienie + r.fPar[31] = Vehicle->physics->pantographCircuit.SupplyVoltage(); // napiecie WN // WriteLog("Parametry gotowe"); i <<= 2; // ilość bajtów r.cString[i] = char(j); // na końcu nazwa, żeby jakoś zidentyfikować diff --git a/lang/editor_pl.po b/lang/editor_pl.po index e7332801e..2abe0652d 100644 --- a/lang/editor_pl.po +++ b/lang/editor_pl.po @@ -8123,6 +8123,18 @@ msgstr "Pas rozwidla się najwyżej na trzy: na pasy dodane ponad dwa nie da si msgid "Lane width [m]" msgstr "Szerokość pasa (m)" +msgid "paved" +msgstr "utwardzona" + +msgid "dirt" +msgstr "gruntowa" + +msgid "Road type" +msgstr "Rodzaj drogi" + +msgid "Paved: asphalt, concrete or setts, with the bends and the junction angles of a built road.\nDirt: a track between fields or through a forest. It bends tighter (3 m radius instead of 6 m), can be shorter (1 m instead of 2 m),\nleaves other roads at sharper angles (15 degrees instead of 30) and can turn back in a hairpin.\nMade dirt, a road with the default asphalt gets the field road texture and loses the white lines" +msgstr "Utwardzona: asfalt, beton albo kostka, z łukami i kątami skrzyżowań jak na drodze budowanej.\nGruntowa: droga polna albo leśna. Skręca ciaśniej (promień 3 m zamiast 6 m), może być krótsza (1 m zamiast 2 m),\nodchodzi od innych dróg pod ostrzejszym kątem (15 stopni zamiast 30) i może zawrócić serpentyną.\nDroga z domyślnym asfaltem zmieniona na gruntową dostaje teksturę drogi polnej i traci białe linie" + msgid "Left side" msgstr "Lewa strona" @@ -14301,12 +14313,46 @@ msgstr "Kursor rysowany w obrazie (stream)" msgid "The pointer drawn by the editor into the frame instead of the one of the system: seen by those watching a stream\nor a recording of the window (Discord, OBS, the capture of the system), which leave the system pointer out" msgstr "Wskaźnik rysowany przez edytor w klatce zamiast systemowego: widać go w streamie\ni w nagraniu okna (Discord, OBS, przechwytywanie systemowe), które pomijają wskaźnik systemu" +msgid "Track names outside of ASCII..." +msgstr "Nazwy torów spoza ASCII..." + +msgid "The tracks whose names have Polish letters or other characters outside of ASCII, and what an ASCII name would collide with; nothing is changed" +msgstr "Tory, których nazwy mają polskie litery lub inne znaki spoza ASCII, i z czym zderzyłaby się nazwa w ASCII; nic nie jest zmieniane" + +msgid "%zu track names have characters outside of ASCII; they work as they are, the list is in Tools" +msgstr "%zu nazw torów ma znaki spoza ASCII; działają tak jak są, lista jest w menu Narzędzia" + +msgid "Track names outside of ASCII" +msgstr "Nazwy torów spoza ASCII" + +msgid "These names work as they are and nothing here changes them. New names given in the editor are ASCII only. To give one of these tracks an ASCII name, rename it in the track properties: the memory cells and the includes which name it go along, the events named after it are listed there. A track named by a parameter of an include (From an include: yes) can't be renamed there: change that parameter in the line of the scenery which puts the include." +msgstr "Te nazwy działają tak jak są i nic tutaj ich nie zmienia. Nowe nazwy nadawane w edytorze mogą mieć tylko znaki ASCII. Żeby dać któremuś z tych torów nazwę w ASCII, zmień ją we właściwościach toru: komórki pamięci i include'y, które go nazywają, zmienią się razem z nią, a eventy nazwane od niego są tam wypisane. Toru nazwanego parametrem include'a (Z include'a: tak) nie da się tam przemianować: zmień ten parametr w linii scenerii, która wstawia include." + +msgid "Check again" +msgstr "Sprawdź ponownie" + +msgid "Tracks: %zu" +msgstr "Torów: %zu" + +msgid "In ASCII" +msgstr "W ASCII" + +msgid "Taken" +msgstr "Zajęta" + +msgid "From an include" +msgstr "Z include'a" + +msgid "In a file the editor writes" +msgstr "W pliku zapisywanym przez edytor" + +msgid "The name can hold ASCII only: no Polish letters or other characters outside of it" +msgstr "Nazwa może mieć tylko znaki ASCII: bez polskich liter i innych znaków spoza niego" + msgid "Draws the imagery as part of the scene, so tracks, models and terrain in front of it hide it.\nIt is lit like the scene. Fully opaque, mouse placement lands on it as on any surface;\ntranslucent, it doesn't catch the mouse." msgstr "Rysuje zdjęcia jako część sceny, więc tory, modele i teren przed nimi je zasłaniają.\nJest oświetlone jak scena. W pełni kryjące łapie mysz przy wstawianiu jak każda powierzchnia;\nprzezroczyste nie łapie myszy." -msgid "Poles and gantries" -msgstr "Słupy i bramki" msgid "No pole: the catalogue (data/traction_cantilevers.txt, data/traction_supports.txt) isn't loaded or has no poles" msgstr "Brak słupa: katalog (data/traction_cantilevers.txt, data/traction_supports.txt) nie jest wczytany albo nie ma w nim słupów" @@ -14448,8 +14494,6 @@ msgstr "4 - sieć jednodrutowa, ramiona ciężkie, hk 1,30" msgid "5 - one contact wire, light arms, hk 1.70" msgstr "5 - sieć jednodrutowa, ramiona lekkie, hk 1,70" -msgid "Angle the textures of the chosen material are turned by, on every chunk painted with it.\nCtrl+click to type it. To have the material turned in one place only, fill it there with an angle of its own." -msgstr "Kąt obrotu tekstur wybranego materiału na każdym kaflu nim malowanym.\nCtrl+klik, żeby wpisać. Żeby obrócić materiał tylko w jednym miejscu, wypełnij je materiałem z własnym kątem." msgid "Poles with cantilevers by the track, the card chosen from the catalogue by the distance of the pole; the spans checked against the catalogue" msgstr "Słupy z wysięgnikami przy torze, karta z katalogu dobierana z odległości słupa; przęsła sprawdzane z tablicami katalogu" @@ -14495,11 +14539,6 @@ msgstr "Łańcuch %s: słupy %zu, przęsła %zu; zmiany od razu na całym łańc msgid "Network type" msgstr "Typ sieci" -msgid "Grade lines: %zu fitted, %zu track left" -msgid_plural "Grade lines: %zu fitted, %zu tracks left" -msgstr[0] "Niwelety: dopasowano %zu, został %zu tor" -msgstr[1] "Niwelety: dopasowano %zu, zostały %zu tory" -msgstr[2] "Niwelety: dopasowano %zu, zostało %zu torów" msgid "Wires" msgstr "Druty" @@ -14749,8 +14788,6 @@ msgstr "wczytany" msgid "changed, not saved" msgstr "zmieniony, niezapisany" -msgid "Pick a memory cell from the list to set what's in it" -msgstr "Wybierz komórkę pamięci z listy, aby ustawić jej zawartość" msgid "worn" msgstr "przejściowe" @@ -15867,6 +15904,11 @@ msgstr "Nie udało się zapisać sieci trakcyjnej: jej plik \"%s\" jest plikiem msgid "it's a part of the catenary, which is changed with the Catenary tool (F6)" msgstr "to część sieci trakcyjnej, którą zmienia się narzędziem Sieć trakcyjna (F6)" +# scenery editor: moths at the lamps, made by the game + +msgid "it's made by the game while it runs (the moths at a lamp), not a part of the scenery" +msgstr "to robi sama gra podczas jazdy (ćmy przy lampie), nie jest częścią scenerii" + msgid "A part of the catenary: it's changed with the Catenary tool (F6)" msgstr "Część sieci trakcyjnej: zmienia się ją narzędziem Sieć trakcyjna (F6)" @@ -16285,3 +16327,15 @@ msgstr "Ortofoto: %zu kafli widoku pobieranych w pierwszej kolejności (Ctrl+~)" msgid "Orthophoto: the view is all shown already (Ctrl+~)" msgstr "Ortofoto: cały widok jest już pokazany (Ctrl+~)" + +msgid "Preparing the graphics (takes longer at the first start of a new version)" +msgstr "Przygotowanie grafiki (przy pierwszym uruchomieniu nowej wersji trwa dłużej)" + +msgid "The name of the catenary file can't have spaces, ';', quotes, ':' or \"..\" in it, nor start with a slash: the directive including it couldn't read it" +msgstr "Nazwa pliku sieci trakcyjnej nie może zawierać spacji, ';', cudzysłowów, ':' ani \"..\" ani zaczynać się ukośnikiem: dyrektywa dołączająca plik nie odczytałaby jej" + +msgid "The terrain couldn't be saved: %s. The catenary files are written already, the scenery files aren't: save again once it's fixed" +msgstr "Nie udało się zapisać terenu: %s. Pliki sieci trakcyjnej są już zapisane, pliki scenerii nie: zapisz ponownie po usunięciu przyczyny" + +msgid "Files of the terrain or of the catenary may be written already, the scenery files aren't: save again once it's fixed" +msgstr "Pliki terenu lub sieci trakcyjnej mogą być już zapisane, pliki scenerii nie: zapisz ponownie po usunięciu przyczyny" diff --git a/launcher/scenery_wizard.cpp b/launcher/scenery_wizard.cpp index 250ff508d..d7bfd7f5d 100644 --- a/launcher/scenery_wizard.cpp +++ b/launcher/scenery_wizard.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/translation.h" #include "rendering/renderer.h" +#include "utilities/utilities.h" #include #include @@ -26,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include namespace @@ -400,8 +402,8 @@ bool ui::scenerywizard_panel::create_scenery() return false; } auto const now{std::time(nullptr)}; - char date[32]; - std::strftime(date, sizeof(date), "%Y-%m-%d", std::localtime(&now)); + std::tm const local{local_tm(now)}; + auto const date{std::format("{:04}-{:02}-{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday)}; char reference[96]; std::snprintf(reference, sizeof(reference), "//$g PUWG1992 %.3f %.3f", m_map.point().x / 1000.0, m_map.point().y / 1000.0); auto const area{range()}; diff --git a/launcher/textures_scanner.cpp b/launcher/textures_scanner.cpp index 741f978ca..480bd5671 100644 --- a/launcher/textures_scanner.cpp +++ b/launcher/textures_scanner.cpp @@ -9,8 +9,18 @@ void ui::vehicles_bank::scan_textures() if (f->path().filename() != "textures.txt") continue; + auto const folder{std::filesystem::relative(f->path().parent_path(), "dynamic/", error)}; + try { + // the vehicles are kept by narrow names. on Windows a folder named with a character the code page lacks + // can't be given one and would throw at the first vehicle; the game couldn't load it by that name anyway + [[maybe_unused]] auto const name{folder.generic_string()}; + } + catch (std::system_error const &) { + continue; + } + ctx_path = folder; + std::fstream stream(f->path(), std::ios_base::binary | std::ios_base::in); - ctx_path = std::filesystem::relative(f->path().parent_path(), "dynamic/", error); std::string line; while (std::getline(stream, line)) diff --git a/model/AnimModel.cpp b/model/AnimModel.cpp index 8553d63e5..42fea67cf 100644 --- a/model/AnimModel.cpp +++ b/model/AnimModel.cpp @@ -24,6 +24,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "rendering/renderer.h" +#include "vehicle/DynObj.h" std::list> TAnimModel::acAnimList; @@ -570,6 +571,15 @@ void TAnimModel::update_instanceable_flag() { ++s_instanceable_total; } +void TAnimModel::draw_alone() { + + if( m_instanceable ) { + ++s_instanceable_revoked; + m_instanceable = false; + ++scene::node_state_version; + } +} + std::shared_ptr TAnimModel::AddContainer(std::string const &Name) { // dodanie sterowania submodelem dla egzemplarza if (!pModel) diff --git a/model/AnimModel.h b/model/AnimModel.h index a66def742..d4e971615 100644 --- a/model/AnimModel.h +++ b/model/AnimModel.h @@ -17,7 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "utilities/Float3d.h" #include "model/Model3d.h" -#include "vehicle/DynObj.h" +#include "model/materialdata.h" +#include "utilities/Names.h" #include "scene/scenenode.h" const int iMaxNumLights = 8; @@ -125,6 +126,9 @@ public: // Angles, Scale: content of the optional blocks of the definition, nullptr for a block which isn't there void Load( std::string const &Name, std::string const &Texture, TAnimModel const *Twin, glm::vec3 const *Angles, glm::vec3 const *Scale, bool const Transition ); std::shared_ptr AddContainer(std::string const &Name); + // the instance drawn on its own from now on, not with the others of its model: one the game moves (the deer at the tracks), + // whose place the renderer takes anew in every frame + void draw_alone(); std::shared_ptr GetContainer(std::string const &Name = ""); void LightSet( int const n, float const v ); void SkinSet( int const Index, material_handle const Material ); diff --git a/model/Model3d.cpp b/model/Model3d.cpp index 4fa3e0d5c..f3ddbc4a5 100644 --- a/model/Model3d.cpp +++ b/model/Model3d.cpp @@ -24,6 +24,7 @@ Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others #include "simulation/simulationtime.h" #include "world/mtable.h" #include "scene/sn_utils.h" +#include "utilities/wholefile.h" #include @@ -1835,8 +1836,9 @@ void assign_lod_ranges(TSubModel *Root, std::string const &Filename) } auto const nearlimit{limits[std::min(phase.index, limitcount - 1)]}; auto farlimit{phase.index + 1 < limitcount ? limits[phase.index + 1] : farthest}; + // the last phase starting at 400 m or farther (_LOD5 and on) of a small part would have an empty range: it's seen 100 m on if (last) - farlimit = vanish; + farlimit = std::max(vanish, nearlimit + 100.f); phase.submodel->fSquareMinDist = nearlimit * nearlimit; phase.submodel->fSquareMaxDist = farlimit * farlimit; } @@ -2837,20 +2839,8 @@ void TModel3d::LoadFromBinFile(std::string const &FileName, bool dynamic) WriteLog("Loading binary format 3d model data from \"" + FileName + "\"...", logtype::model); // the file is read whole in one go and parsed from memory - std::unique_ptr filedata; - std::size_t filesize{0}; - { - std::ifstream input(FileName, std::ios::binary | std::ios::ate); - auto const length{input.tellg()}; - if (length > 0) - { - filedata.reset(new char[static_cast(length)]); - input.seekg(0); - input.read(filedata.get(), length); - filesize = static_cast(input.gcount()); - } - } - e3d_memorybuffer buffer(filedata.get(), filedata.get() + filesize); + auto const filedata{read_whole_file(FileName)}; + e3d_memorybuffer buffer(filedata.data.get(), filedata.data.get() + filedata.size); std::istream file(&buffer); uint32_t type = sn_utils::ld_uint32(file); diff --git a/model/Model3d.h b/model/Model3d.h index 9be9a4f0f..f7a09dc03 100644 --- a/model/Model3d.h +++ b/model/Model3d.h @@ -13,7 +13,6 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Float3d.h" #include "rendering/geometrybank.h" #include "model/material.h" -#include "gl/query.h" #include @@ -265,7 +264,6 @@ public: void ReplaceMaterial(const std::string &name); float MaxY( float4x4 const &m ); std::shared_ptr> screen_touch_list; // for python screen touching - std::optional occlusion_query; glm::mat4 future_transform; void deserialize(std::istream&); diff --git a/model/Texture.cpp b/model/Texture.cpp index efd9e711b..d058ca9b2 100644 --- a/model/Texture.cpp +++ b/model/Texture.cpp @@ -1258,7 +1258,8 @@ texture_source::load_TGA() { } downsize( GL_BGRA ); - if( data_width > Global.CurrentMaxTextureSize || data_height > Global.CurrentMaxTextureSize ) { + if( ( false == contains( traits, 'r' ) ) + && ( data_width > Global.CurrentMaxTextureSize || data_height > Global.CurrentMaxTextureSize ) ) { // for non-square textures there's currently possibility the scaling routine will have to abort // before it gets all work done data_state = resource_state::failed; @@ -1430,7 +1431,7 @@ opengl_texture::create( bool const Static ) { // uncompressed texture data. have the gfx card do the compression as it sees fit ::glTexImage2D( target, 0, - Global.compress_tex ? compressed_format : internal_format, + ( Global.compress_tex && ( false == contains( traits, 'r' ) ) ) ? compressed_format : internal_format, data_width, data_height, 0, data_format, data_type, (GLubyte *)&data[ 0 ] ); } @@ -1683,6 +1684,10 @@ opengl_texture::set_filtering() const void texture_source::downsize( GLuint const Format ) { + if( contains( traits, 'r' ) ) { + // raw data (trait r: the frames of the animations baked into textures, mat_vat): never scaled down + return; + } while( data_width > Global.CurrentMaxTextureSize || data_height > Global.CurrentMaxTextureSize ) { // scale down the base texture, if it's larger than allowed maximum // NOTE: scaling is uniform along both axes, meaning non-square textures can drop below the maximum diff --git a/model/material.cpp b/model/material.cpp index f1bc8d8ee..4c94d1f7e 100644 --- a/model/material.cpp +++ b/model/material.cpp @@ -86,11 +86,11 @@ int opengl_material::texture_slot( std::string const &Key ) // named binding, the slot it fills is up to the shader key.erase( 0, 1 ); key.pop_back(); - if( shader && ( shader->texture_conf.find( key ) != shader->texture_conf.end() ) ) { + if( shader && shader->texture_conf.contains( key ) ) { return static_cast( shader->texture_conf[ key ].id ); } - auto const lookup { texture_bindings.find( key ) }; - if( ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { + if( auto const lookup { texture_bindings.find( key ) }; + ( shader == nullptr ) && ( lookup != texture_bindings.end() ) ) { return lookup->second; } // ignore unrecognized texture bindings in legacy render mode, it's most likely data for more advanced shaders @@ -106,6 +106,35 @@ int opengl_material::texture_slot( std::string const &Key ) return -1; } +namespace { + +// the texture of a single texel which a unit of a material shows when its shader can do without the texture and the material +// gives none (the fourth argument of #pragma texture). made once for each colour, shared by all the materials +texture_handle +default_texture( gfx::shader_texture_default const Default ) { + + struct texel_source { + char const *name; + std::array texel; + }; + using enum gfx::shader_texture_default; + texel_source source { "internal_src:material/default_black", { 0, 0, 0, 255 } }; + if( Default == white ) { source = { "internal_src:material/default_white", { 255, 255, 255, 255 } }; } + else if( Default == red ) { source = { "internal_src:material/default_red", { 255, 0, 0, 255 } }; } + else if( Default == yellow ) { source = { "internal_src:material/default_yellow", { 255, 255, 0, 255 } }; } + + auto const handle { GfxRenderer->Fetch_Texture( source.name, true ) }; + if( handle == null_handle ) { return null_handle; } + // a texture just made is the stub of the generated textures, larger than the texel it gets here + if( auto &texture { GfxRenderer->Texture( handle ) }; + ( texture.get_width() != 1 ) || ( texture.get_height() != 1 ) ) { + texture.update_from_memory( 1, 1, source.texel.data() ); + } + return handle; +} + +} // namespace + void opengl_material::build_texture_variants( std::vector const &Bindings, bool const Loadnow ) { if( true == Bindings.empty() ) { return; } @@ -266,6 +295,17 @@ void opengl_material::finalize(bool Loadnow) for (auto it : shader->texture_conf) { gfx::shader_texture_entry &entry = it.second; + if( ( textures[ entry.id ] == null_handle ) && ( entry.fallback != gfx::shader_texture_default::none ) ) { + // a texture the shader can do without: its unit shows a single texel, in the sets of the variants too + auto const fallback { default_texture( entry.fallback ) }; + if( fallback != null_handle ) { + textures[ entry.id ] = fallback; + for( auto &variant : texture_variants ) { + if( variant[ entry.id ] == null_handle ) { variant[ entry.id ] = fallback; } + } + continue; + } + } texture_handle handle = textures[entry.id]; // NOTE: texture validation at this stage relies on forced texture load behaviour during its create() call // TODO: move texture id validation to later stage if/when deferred texture loading is implemented @@ -318,7 +358,7 @@ std::unordered_set seasons = { bool is_season( std::string const &String ) { - return seasons.find(String) != seasons.end(); + return seasons.contains(String); } std::unordered_set weather = { @@ -326,7 +366,7 @@ std::unordered_set weather = { bool is_weather( std::string const &String ) { - return weather.find(String) != weather.end(); + return weather.contains(String); } // imports member data pair from the config file @@ -362,7 +402,7 @@ void opengl_material::deserialize_texture_mapping( cParser &Input, std::string c value = variants.front(); } - auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, parse_info_s::tex_def{ value, Priority, variants } ) }; + auto const [ it, inserted ] { parse_info->tex_mapping.try_emplace( key, value, Priority, variants ) }; if( ( false == inserted ) && ( Priority > it->second.priority ) ) { it->second = parse_info_s::tex_def{ value, Priority, variants }; } @@ -389,7 +429,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 2, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } else if( key == Global.Season ) { @@ -397,7 +437,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // skip the opening bracket auto const value { Input.getToken( true, "\n\r\t ;" ) }; while( true == deserialize_mapping( Input, Priority + 1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } @@ -477,7 +517,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // unrecognized or ignored token, but comes with attribute block and potential further nesting // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } @@ -489,7 +529,7 @@ opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool c // ignored tokens can come with their own blocks, ignore these recursively // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { - ; // all work is done in the header + // all work is done in the header } } } diff --git a/model/materialdata.cpp b/model/materialdata.cpp new file mode 100644 index 000000000..8d026d71a --- /dev/null +++ b/model/materialdata.cpp @@ -0,0 +1,94 @@ +/* +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 "model/materialdata.h" + +#include "model/Texture.h" +#include "rendering/renderer.h" +#include "utilities/parser.h" +#include "utilities/utilities.h" +#include "utilities/Globals.h" + +// Ra 2015-01: sprawdzenie dostępności tekstury o podanej nazwie +std::string +TextureTest( std::string const &Name ) { + + auto const lookup { + FileExists( + { Global.asCurrentTexturePath + Name, Name, paths::textures + Name }, + { ".mat", ".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; + + return lookup.first + lookup.second; +} + +// assigns specified texture or a group of textures to replacable texture slots +void +material_data::assign( std::string const &Replacableskin ) { + + // a template puts its parameter after a folder ("tabl/(p6)"): a texture made by a script given there keeps its scheme + if( auto const scheme { Replacableskin.find( "/make:" ) }; + scheme != std::string::npos + && false == contains( Replacableskin, '|' ) ) { + assign( Replacableskin.substr( scheme + 1 ) ); + return; + } + // check for the pipe method first + if( contains( Replacableskin, '|' ) ) { + cParser nameparser( Replacableskin ); + nameparser.getTokens( 4, false, "|" ); + int skinindex = 0; + std::string texturename; nameparser >> texturename; + while( texturename != "" && skinindex < 4 ) { + replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( texturename ); + ++skinindex; + texturename = ""; nameparser >> texturename; + } + multi_textures = skinindex; + } + else { + // otherwise try the basic approach + int skinindex = 0; + do { + // test quietly for file existence so we don't generate tons of false errors in the log + // NOTE: this means actual missing files won't get reported which is hardly ideal, but still somewhat better + auto const material { TextureTest( ToLower( Replacableskin + "," + std::to_string( skinindex + 1 ) ) ) }; + if( true == material.empty() ) { break; } + + replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( material ); + ++skinindex; + } while( skinindex < 4 ); + multi_textures = skinindex; + if( multi_textures == 0 ) { + // zestaw nie zadziałał, próbujemy normanie + replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); + } + } + if( replacable_skins[ 1 ] == null_handle ) { + // last ditch attempt, check for single replacable skin texture + replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); + } + + // BUGS! it's not entierly designed whether opacity is property of material or submodel, + // and code does confusing things with this in various places + textures_alpha = GfxRenderer->Material(replacable_skins[1])->is_translucent() ? 0x31310031 : // tekstura -1 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + 0x30300030; // wszystkie tekstury nieprzezroczyste - nie renderować w cyklu przezroczystych + if( GfxRenderer->Material( replacable_skins[ 2 ] )->is_translucent() ) { + // tekstura -2 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + textures_alpha |= 0x02020002; + } + if( GfxRenderer->Material( replacable_skins[ 3 ] )->is_translucent() ) { + // tekstura -3 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + textures_alpha |= 0x04040004; + } + if( GfxRenderer->Material( replacable_skins[ 4 ] )->is_translucent() ) { + // tekstura -4 z kanałem alfa - nie renderować w cyklu nieprzezroczystych + textures_alpha |= 0x08080008; + } +} diff --git a/model/materialdata.h b/model/materialdata.h new file mode 100644 index 000000000..e149e9e5e --- /dev/null +++ b/model/materialdata.h @@ -0,0 +1,30 @@ +/* +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 replaceable skins of a model: the textures a vehicle or a scenery model puts in place of the replaceable ones + +#pragma once + +#include + +#include "interfaces/IMaterial.h" +#include "utilities/Classes.h" + +struct material_data { + + int textures_alpha{ 0x30300030 }; // maska przezroczystości tekstur. default: tekstury wymienne nie mają przezroczystości + material_handle replacable_skins[ 5 ] = { null_handle, null_handle, null_handle, null_handle, null_handle }; // McZapkie:zmienialne nadwozie + int multi_textures{ 0 }; //<0 tekstury wskazane wpisem, >0 tekstury z przecinkami, =0 jedna + + // assigns specified texture or a group of textures to replacable texture slots + void assign( std::string const &Replacableskin ); +}; + +// the file of the texture or the material of the given name, looked up as the models do; empty when there is none +std::string TextureTest( std::string const &Name ); diff --git a/network/network.cpp b/network/network.cpp index b5eeced42..1bd02267d 100644 --- a/network/network.cpp +++ b/network/network.cpp @@ -244,6 +244,7 @@ void network::client::handle_message(std::shared_ptr Connection, con if (!Global.ready_to_load) { Global.random_seed = cmd.seed; + Global.random_seed_given = true; Global.random_engine.seed(Global.random_seed); Global.starting_timestamp = cmd.timestamp; // TODO: configure simulation settings according to received cmd.config diff --git a/nodebank_previews_standalone.cpp b/nodebank_previews_standalone.cpp index effceedc0..cff04b6c5 100644 --- a/nodebank_previews_standalone.cpp +++ b/nodebank_previews_standalone.cpp @@ -76,19 +76,21 @@ bool parse_arguments(int const Argc, char *Argv[], preview_settings &Settings) } else if (token == "-resolution") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.resolution)) || (Settings.resolution < 16)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.resolution)) || (Settings.resolution < 16)) { report("-resolution needs a number of pixels, 16 or more", true); return false; } + ++i; } else if (token == "-margin") { - if ((i + 1 >= Argc) || (false == parse_number(Argv[++i], Settings.margin)) || (Settings.margin < 0)) + if ((i + 1 >= Argc) || (false == parse_number(Argv[i + 1], Settings.margin)) || (Settings.margin < 0)) { report("-margin needs a number of pixels, 0 or more", true); return false; } + ++i; } else if (token == "-no-shadows") { @@ -290,6 +292,8 @@ int generate_nodebank_previews(int Argc, char *Argv[]) { Global.LoadIniFile("eu07.ini"); } + // the settings are read, so the log service writes as it goes instead of holding everything until it stops + OpenLogFiles(); // the progress goes to the console, the log keeps the details Global.iWriteLogEnabled &= ~2; std::thread logservice(LogService); diff --git a/McZapkie/hamulce.cpp b/physics/brakes.cpp similarity index 95% rename from McZapkie/hamulce.cpp rename to physics/brakes.cpp index b30372e5e..7cd66b1d5 100644 --- a/McZapkie/hamulce.cpp +++ b/physics/brakes.cpp @@ -13,9 +13,9 @@ Copyright (C) 2007-2014 Maciej Cierniak */ #include "stdafx.h" -#include "hamulce.h" +#include "physics/brakes.h" #include -#include "MOVER.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" //---FUNKCJE OGOLNE--- @@ -855,25 +855,7 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -908,6 +890,29 @@ void TESt::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TESt::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the dimensionless opening factor of the ZS-filling slide valve /// (control reservoir <-> brake pipe) for the current pre-chamber/auxiliary @@ -1164,33 +1169,7 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) // odluzniacz CheckReleaser(dt); - // sprawdzanie stanu - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP - 0.12) - BrakeStatus |= b_on; // hamowanie stopniowe; - else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.12) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - } - else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania - { - // if ((BrakeStatus & 1) == 0) - //{ - // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 - // // SoundFlag:=SoundFlag or sf_Acc; - // // ValveRes.Act; - //} - BrakeStatus |= b_on | b_hld; - } - else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie - BrakeStatus |= b_hld; - - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } + UpdateStatusEP2(BCP, VVP, CVP); // przeplyw ZS <-> PG if (BVP < CVP - 0.2 || BrakeStatus != b_off || BCP > 0.25) @@ -1258,6 +1237,38 @@ double TEStEP2::GetPF(double const PP, double const dt, double const Vel) return result; } +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TEStEP2::UpdateStatusEP2(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP - 0.12) + BrakeStatus |= b_on; // hamowanie stopniowe; + else if (VVP - 0.003 + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.12) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + } + else if (VVP + 0.10 < CVP - 0.12 && BCP < 0.25) // poczatek hamowania + { + // if ((BrakeStatus & 1) == 0) + //{ + // // ValveRes.CreatePress(0.5*VVP); //110115 - konsultacje warszawa1 + // // SoundFlag:=SoundFlag or sf_Acc; + // // ValveRes.Act; + //} + BrakeStatus |= b_on | b_hld; + } + else if (VVP + BCP / BVM < CVP - 0.12 && BCP > 0.25) // zatrzymanie luzowanie + BrakeStatus |= b_hld; + + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + /// /// Recomputes the load-weighing coefficient LoadC for the current vehicle /// mass (linear between TareBP/MaxBP for TareM..LoadM, capped at 1.0). @@ -1672,58 +1683,8 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) double dV{0.0}; double dV1{0.0}; - // sprawdzanie stanu - // NOTE: partial copypaste from checkstate() of base class - // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste - if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) - { - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe - BrakeStatus |= b_on; - } - else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) - { - // luzowanie - BrakeStatus &= ~(b_on | b_hld); - } - else if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania - BrakeStatus &= ~b_on; - } - } - else if (VVP + 0.10 < CVP && BCP < 0.25) - { - // poczatek hamowania - if ((BrakeStatus & b_hld) == b_off) - { - SoundFlag |= sf_Acc; - } - BrakeStatus |= b_on | b_hld; - } - else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) - { - // zatrzymanie luzowanie - BrakeStatus |= b_hld; - } - if ((BrakeStatus & b_hld) == 0) - { - SoundFlag |= sf_CylU; - } - // equivalent of checkreleaser() in the base class? - if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) - { - if (CVP < 0.0) - { - BrakeStatus &= ~b_rls; - } - else - { // 008 - dV = PF1(CVP, BCP, 0.024) * dt; - CntrlRes->Flow(dV); - } - } + UpdateStatusLSt(BCP, VVP, CVP); + ReleaserLSt(BCP, CVP, dt); // przeplyw ZS <-> PG double temp; @@ -1770,6 +1731,87 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) // if Vel>55 then temp:=0.72 else // temp:=1;{R} // cisnienie PP + CylinderFlowLSt(BCP, BVP, CVP, dt, Vel); + + ImplsRes->Act(); + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + // LBP:=ValveRes->P(); + // ValveRes.CreatePress(ImplsRes->P()); + return result; +} + +// the state of the valve: braking in steps, holding or releasing, the start of braking +void TLSt::UpdateStatusLSt(double const BCP, double const VVP, double const CVP) +{ + // sprawdzanie stanu + // NOTE: partial copypaste from checkstate() of base class + // TODO: clean inheritance for checkstate() and checkreleaser() and reuse these instead of manual copypaste + if ((BrakeStatus & b_hld) == b_hld && BCP > 0.25) + { + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe + BrakeStatus |= b_on; + } + else if (VVP - 0.003 + (BCP - 0.1) / BVM > CVP) + { + // luzowanie + BrakeStatus &= ~(b_on | b_hld); + } + else if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania + BrakeStatus &= ~b_on; + } + } + else if (VVP + 0.10 < CVP && BCP < 0.25) + { + // poczatek hamowania + if ((BrakeStatus & b_hld) == b_off) + { + SoundFlag |= sf_Acc; + } + BrakeStatus |= b_on | b_hld; + } + else if (VVP + (BCP - 0.1) / BVM < CVP && (CVP - VVP) * BVM > 0.25 && BCP > 0.25) + { + // zatrzymanie luzowanie + BrakeStatus |= b_hld; + } + if ((BrakeStatus & b_hld) == 0) + { + SoundFlag |= sf_CylU; + } +} + +// the releaser, or the universal button set to release, letting the control reservoir out into the impulse chamber +void TLSt::ReleaserLSt(double const BCP, double const CVP, double const dt) +{ + double dV; + // equivalent of checkreleaser() in the base class? + if (bool is_releasing = BrakeStatus & b_rls || UniversalFlag & TUniversalBrake::ub_Release; is_releasing) + { + if (CVP < 0.0) + { + BrakeStatus &= ~b_rls; + } + else + { // 008 + dV = PF1(CVP, BCP, 0.024) * dt; + CntrlRes->Flow(dV); + } + } +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure the relay is set to: by the pilot +// pressure, the anti-slip brake and the rapid setting, at least the local brake's +void TLSt::CylinderFlowLSt(double const BCP, double const BVP, double const CVP, double const dt, double const Vel) +{ + double dV; + double temp; RapidTemp = RapidTemp + (RM * int(Vel > 55 && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; temp = 1 - RapidTemp; if (EDFlag > 0.2) @@ -1795,15 +1837,6 @@ double TLSt::GetPF(double const PP, double const dt, double const Vel) dV = 0; BrakeRes->Flow(dV); BrakeCyl->Flow(-dV); - - ImplsRes->Act(); - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - // LBP:=ValveRes->P(); - // ValveRes.CreatePress(ImplsRes->P()); - return result; } /// @@ -1916,33 +1949,7 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) nastG = BrakeDelayFlag & bdelay_G; - // sprawdzanie stanu - if (BCP < 0.25 && VVP + 0.08 > CVP) - Przys_blok = false; - - // sprawdzanie stanu - if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) - BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; - else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) - BrakeStatus &= ~(b_on | b_hld); // luzowanie; - else if (VVP + BCP / BVM > CVP - 0.05) - BrakeStatus &= ~b_on; // zatrzymanie napelaniania; - else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania - BrakeStatus |= b_hld; - - // poczatek hamowania - if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) - { - ValveRes->CreatePress(0.75 * VVP); - SoundFlag |= sf_Acc; - ValveRes->Act(); - Przys_blok = true; - } - - if (BCP > 0.5) - Zamykajacy = true; - else if (VVP - 0.6 < MPP) - Zamykajacy = false; + UpdateStatus(BCP, VVP, CVP, MPP); if ((BrakeStatus & b_rls) == b_rls) { @@ -1963,60 +1970,9 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) ImplsRes->Flow(-dv); BrakeRes->Flow(dv); - // przeplyw testowy miedzypojemnosci - if (MPP < CVP - 0.3) - temp = Nozzles[4]; - else if (BCP < 0.5) - if (Zamykajacy) - temp = Nozzles[8]; // 1.25; - else - temp = Nozzles[7]; - else - temp = 0; - dv = PF(MPP, VVP, temp); + Miedzypoj->Flow(IntermediateFlow(BCP, VVP, CVP, MPP, BVP, nastG) * dt * 0.15); - if (MPP < CVP - 0.17) - temp = 0; - else if (MPP > CVP - 0.08) - temp = Nozzles[5]; - else - temp = Nozzles[6]; - dv = dv + PF(MPP, CVP, temp); - - if (MPP - 0.05 > BVP) - dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); - if (MPP > VVP) - dv = dv + PF(MPP, VVP, 0.02); - Miedzypoj->Flow(dv * dt * 0.15); - - RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; - temp = std::max(1 - RapidTemp, 0.001); - // if EDFlag then temp:=1000; - // temp:=temp/(1-); - - // powtarzacz — podwojny zawor zwrotny - temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); - - if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) - temp = std::max(temp, ASBP); - - double speed = 1; - if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) - { - temp = 0; - speed = 3; - } - - if (BrakeCyl->P() > temp) - dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; - else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) - dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; - else - dv = 0; - - BrakeCyl->Flow(dv); - if (dv > 0) - BrakeRes->Flow(-dv); + CylinderFlow(BCP, BVP, dt, Vel); // przeplyw ZS <-> PG if (MPP < CVP - 0.17) @@ -2051,6 +2007,107 @@ double TEStED::GetPF(double const PP, double const dt, double const Vel) return dv - dV1; } +// the state of the valve: braking in steps, holding or releasing, the accelerator at the start of braking, and the +// closing valve +void TEStED::UpdateStatus(double const BCP, double const VVP, double const CVP, double const MPP) +{ + // sprawdzanie stanu + if (BCP < 0.25 && VVP + 0.08 > CVP) + Przys_blok = false; + + // sprawdzanie stanu + if (VVP + 0.002 + BCP / BVM < CVP - 0.05 && Przys_blok) + BrakeStatus |= b_on | b_hld; // hamowanie stopniowe; + else if (VVP - 0.002 + (BCP - 0.1) / BVM > CVP - 0.05) + BrakeStatus &= ~(b_on | b_hld); // luzowanie; + else if (VVP + BCP / BVM > CVP - 0.05) + BrakeStatus &= ~b_on; // zatrzymanie napelaniania; + else if (VVP + (BCP - 0.1) / BVM < CVP - 0.05 && BCP > 0.25) // zatrzymanie luzowania + BrakeStatus |= b_hld; + + // poczatek hamowania + if (VVP + 0.10 < CVP && BCP < 0.25 && !Przys_blok) + { + ValveRes->CreatePress(0.75 * VVP); + SoundFlag |= sf_Acc; + ValveRes->Act(); + Przys_blok = true; + } + + if (BCP > 0.5) + Zamykajacy = true; + else if (VVP - 0.6 < MPP) + Zamykajacy = false; +} + +// the flow into the intermediate reservoir from the pipe and the control reservoir, less the flow filling the auxiliary one +double TEStED::IntermediateFlow(double const BCP, double const VVP, double const CVP, double const MPP, double const BVP, double const nastG) const +{ + double dv; + double temp; + // przeplyw testowy miedzypojemnosci + if (MPP < CVP - 0.3) + temp = Nozzles[4]; + else if (BCP < 0.5) + if (Zamykajacy) + temp = Nozzles[8]; // 1.25; + else + temp = Nozzles[7]; + else + temp = 0; + dv = PF(MPP, VVP, temp); + + if (MPP < CVP - 0.17) + temp = 0; + else if (MPP > CVP - 0.08) + temp = Nozzles[5]; + else + temp = Nozzles[6]; + dv = dv + PF(MPP, CVP, temp); + + if (MPP - 0.05 > BVP) + dv = dv + PF(MPP - 0.05, BVP, Nozzles[10] * nastG + (1 - nastG) * Nozzles[9]); + if (MPP > VVP) + dv = dv + PF(MPP, VVP, 0.02); + return dv; +} + +// the cylinders filled or let out to the pressure the relay is set to: by the pilot pressure and the load, at least the +// local brake's, the anti-slip brake's, faster at the rapid setting +void TEStED::CylinderFlow(double const BCP, double const BVP, double const dt, double const Vel) +{ + double dv; + double temp; + RapidTemp = RapidTemp + (RM * int(Vel > RV && (BrakeDelayFlag & bdelay_R) == bdelay_R) - RapidTemp) * dt / 2; + temp = std::max(1 - RapidTemp, 0.001); + // if EDFlag then temp:=1000; + // temp:=temp/(1-); + + // powtarzacz — podwojny zawor zwrotny + temp = std::max(LoadC * BCP / temp * std::clamp(1 - EDFlag, 0., 1.), LBP); + + if ((UniversalFlag & TUniversalBrake::ub_AntiSlipBrake) > 0) + temp = std::max(temp, ASBP); + + double speed = 1; + if (ASBP < 0.1 && (BrakeStatus & b_asb_unbrake) == b_asb_unbrake) + { + temp = 0; + speed = 3; + } + + if (BrakeCyl->P() > temp) + dv = -PFVd(BrakeCyl->P(), 0, 0.05 * SizeBC * speed, temp) * dt; + else if (BrakeCyl->P() < temp && (BrakeStatus & b_asb) == 0) + dv = PFVa(BVP, BrakeCyl->P(), 0.05 * SizeBC, temp) * dt; + else + dv = 0; + + BrakeCyl->Flow(dv); + if (dv > 0) + BrakeRes->Flow(-dv); +} + /// /// Initialises the EStED: chains TLSt::Init, sizes Miedzypoj (5 l), pre-charges /// pressures, computes BVM with a 0.05 bar offset on HPP, configures the @@ -2509,25 +2566,7 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) if ((BrakeStatus & b_hld) == b_hld) { - - if (VVP + 0.003 + BCP / BVM < CVP) - { - // hamowanie stopniowe; - BrakeStatus |= b_on; - } - else - { - if (VVP + BCP / BVM > CVP) - { - // zatrzymanie napelaniania; - BrakeStatus &= ~b_on; - } - if (VVP - 0.003 + BCP / BVM > CVP) - { - // luzowanie; - BrakeStatus &= ~(b_on | b_hld); - } - } + CheckStateHeld(BCP, VVP, CVP); } else { @@ -2562,6 +2601,29 @@ void TKE::CheckState(double const BCP, double & /*dV1*/) } } +// the state of a valve holding: braking on in steps, the filling stopped, or released +void TKE::CheckStateHeld(double const BCP, double const VVP, double const CVP) +{ + if (VVP + 0.003 + BCP / BVM < CVP) + { + // hamowanie stopniowe; + BrakeStatus |= b_on; + } + else + { + if (VVP + BCP / BVM > CVP) + { + // zatrzymanie napelaniania; + BrakeStatus &= ~b_on; + } + if (VVP - 0.003 + BCP / BVM > CVP) + { + // luzowanie; + BrakeStatus &= ~(b_on | b_hld); + } + } +} + /// /// Returns the KE ZS-filling slide valve opening factor: closed once /// any pneumatic braking is requested, slightly attenuated when the @@ -2681,6 +2743,36 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) BrakeRes->Flow(dv); ImplsRes->Flow(-dv); + IMP = CylinderFlowKE(IMP, BCP, BVP, Vel, dt); + + // przeplyw ZP <-> rozdzielacz + temp = BVs(IMP); + // if(BrakeStatus and b_hld)=b_off then + if (IMP < 0.25 || VVP + 0.05 > BVP) + dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; + else + dv = 0; + BrakeRes->Flow(dv); + dV1 = dV1 + dv * 0.96; + ValveRes->Flow(-0.04 * dv); + // przeplyw PG <-> rozdzielacz + dv = PF(PP, VVP, 0.01) * dt; + ValveRes->Flow(-dv); + + ValveRes->Act(); + BrakeCyl->Act(); + BrakeRes->Act(); + CntrlRes->Act(); + ImplsRes->Act(); + return dv - dV1; +} + +// the cylinders filled from the auxiliary reservoir or let out to the pressure of the impulse chamber IMP, by the load +// and the rapid setting, at least the local brake's and the anti-slip brake's; returns that pressure +double TKE::CylinderFlowKE(double IMP, double const BCP, double const BVP, double const Vel, double const dt) +{ + double dv; + double temp; // rapid auto const &frictionmaterial{*FM}; if (auto const &frictionmaterialtype{typeid(frictionmaterial)}; !(frictionmaterialtype == typeid(TDisk1) || frictionmaterialtype == typeid(TDisk2))) // jesli zeliwo to schodz @@ -2715,27 +2807,7 @@ double TKE::GetPF(double const PP, double const dt, double const Vel) dv = 0; BrakeRes->Flow(-dv); BrakeCyl->Flow(+dv); - - // przeplyw ZP <-> rozdzielacz - temp = BVs(IMP); - // if(BrakeStatus and b_hld)=b_off then - if (IMP < 0.25 || VVP + 0.05 > BVP) - dv = PF(BVP, VVP, 0.02 * SizeBR * temp / 1.87) * dt; - else - dv = 0; - BrakeRes->Flow(dv); - dV1 = dV1 + dv * 0.96; - ValveRes->Flow(-0.04 * dv); - // przeplyw PG <-> rozdzielacz - dv = PF(PP, VVP, 0.01) * dt; - ValveRes->Flow(-dv); - - ValveRes->Act(); - BrakeCyl->Act(); - BrakeRes->Act(); - CntrlRes->Act(); - ImplsRes->Act(); - return dv - dV1; + return IMP; } /// @@ -3034,32 +3106,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) // na wszelki wypadek, zeby nie wyszlo poza zakres i_bcp = std::clamp(i_bcp, -1.999, 5.999); - double DP{0.0}; - if (TP > 0.0) - { - // jesli czasowy jest niepusty - DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) - TP -= DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - //.08 - TP = 0.0; - } - - if (XP > 0) - { - // jesli komora pod niepusta jest niepusty - DP = 2.5; - Sounds[s_fv4a_x] = DP * XP; - XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) - } - else - { - // jak pusty, to pusty - XP = 0.0; - } + DischargeChambers(dt); double pom; if (EQ(i_bcp, -1.0)) @@ -3071,21 +3118,7 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) pom = std::min(CP, HP); } - if (pom > RP + 0.25) - { - Fala = true; - } - if (Fala) - { - if (pom > RP + 0.3) - { - XP = XP - 20.0 * PR(pom, XP) * dt; - } - else - { - Fala = false; - } - } + UpdateWave(pom, dt); double LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie @@ -3127,28 +3160,12 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) } ep = dpPipe; - if (EQ(i_bcp, 0) || RP > ep) - { - // powolne wzrastanie, ale szybsze na jezdzie; - RP += PF(RP, ep, 0.0007) * dt; - } - else - { - // powolne wzrastanie i to bardzo - RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; - } - // jednak trzeba wydluzyc, bo obecnie zle dziala - if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) - { - // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) - // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG - RP += PF(RP, CP, 0.005) * dt; - } + UpdateReductor(i_bcp, ep, dt); if (EQ(i_bcp, i_bcpno) || EQ(i_bcp, -2)) { - DP = PF(0.0, PP, ActFlowSpeed / LBDelay); + auto const DP{PF(0.0, PP, ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0.0; @@ -3171,6 +3188,80 @@ double TFV4aM::GetPF(double i_bcp, double PP, double HP, double dt, double ep) return dpMainValve * dt; } +// the time reservoir and the reductor's air chamber let out, and their sounds +void TFV4aM::DischargeChambers(double const dt) +{ + double DP{0.0}; + if (TP > 0.0) + { + // jesli czasowy jest niepusty + DP = 0.045; // 2.5 w 55 sekund (5,35->5,15 w PG) + TP -= DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + //.08 + TP = 0.0; + } + + if (XP > 0) + { + // jesli komora pod niepusta jest niepusty + DP = 2.5; + Sounds[s_fv4a_x] = DP * XP; + XP -= dt * DP * 2.0; // od cisnienia 5 do 0 w 10 sekund ((5-0)*dt/10) + } + else + { + // jak pusty, to pusty + XP = 0.0; + } +} + +// the release pressure wave: on while the supply is well over the reductor's pressure, its chamber filled meanwhile +void TFV4aM::UpdateWave(double const pom, double const dt) +{ + if (pom > RP + 0.25) + { + Fala = true; + } + if (Fala) + { + if (pom > RP + 0.3) + { + XP = XP - 20.0 * PR(pom, XP) * dt; + } + else + { + Fala = false; + } + } +} + +// the reductor reservoir following the pressure ep the pipe is driven to, slowly, faster at running, and filled from +// the control reservoir under the lowest pressure of the handle +void TFV4aM::UpdateReductor(double const i_bcp, double const ep, double const dt) +{ + if (EQ(i_bcp, 0) || RP > ep) + { + // powolne wzrastanie, ale szybsze na jezdzie; + RP += PF(RP, ep, 0.0007) * dt; + } + else + { + // powolne wzrastanie i to bardzo + RP += PF(RP, ep, 0.000093 / 2 * 2) * dt; + } + // jednak trzeba wydluzyc, bo obecnie zle dziala + if (RP < ep && RP < BPT[std::lround(i_bcpno) + 2][1]) + { + // jesli jestesmy ponizej cisnienia w sterujacym (2.9 bar) + // przypisz cisnienie w PG - wydluzanie napelniania o czas potrzebny do napelnienia PG + RP += PF(RP, CP, 0.005) * dt; + } +} + /// Initialises CP and RP to the supplied pressure. /// Initial pressure [bar]. void TFV4aM::Init(double Press) @@ -3259,7 +3350,6 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep double dpPipe; double dpMainValve; double ActFlowSpeed; - double DP; double pom; for (auto &soundvalue : Sounds) @@ -3270,30 +3360,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep i_bcp = std::clamp(i_bcp, -0.999, 9.999); // na wszelki wypadek, zeby nie wyszlo poza zakres - if (TP > 0 && CP > 4.9) - { - DP = OverloadPressureDecrease; - if (EQ(i_bcp, 0)) - TP = TP - DP * dt; - Sounds[s_fv4a_t] = DP; - } - else - { - TP = 0; - } + DischargeTimedReservoir(i_bcp, dt); LimPP = std::min(LPP_RP(i_bcp) + TP * 0.08 + RedAdj, HP); // pozycja + czasowy lub zasilanie ActFlowSpeed = 4; - double uop = UnbrakeOverPressure; // unbrake over pressure in actual state - ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed - if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists - uop = 0; - - if (EQ(i_bcp, -1) && uop > 0) - pom = std::min(HP, 5.4 + RedAdj + uop); - else - pom = std::min(CP, HP); + pom = SupplyPressure(i_bcp, HP); if (LimPP > CP) // podwyzszanie szybkie CP = CP + 60 * std::min(abs(LimPP - CP), 0.05) * PR(CP, LimPP) * dt; // zbiornik sterujacy; @@ -3313,15 +3385,12 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep if ((EQ(i_bcp, -1) && AutoOvrld) || (i_bcp < 0.5 && UniversalFlag & TUniversalBrake::ub_Overload)) { - if (TP < 5) - TP = TP + dt; // 5/10 - if (TP < OverloadMaxPressure) - TP = TP - 0.5 * dt; // 5/10 + ChargeTimedReservoir(dt); } if (EQ(i_bcp, 10) || EQ(i_bcp, -2)) { - DP = PF(0, PP, 2 * ActFlowSpeed / LBDelay); + auto const DP{PF(0, PP, 2 * ActFlowSpeed / LBDelay)}; dpMainValve = DP; Sounds[s_fv4a_e] = DP; Sounds[s_fv4a_u] = 0; @@ -3344,6 +3413,45 @@ double TMHZ_EN57::GetPF(double i_bcp, double PP, double HP, double dt, double ep return dpMainValve * dt; } +// the time reservoir let out of the overload, at the running position, while the control reservoir is charged +void TMHZ_EN57::DischargeTimedReservoir(double const i_bcp, double const dt) +{ + if (TP > 0 && CP > 4.9) + { + auto const DP{OverloadPressureDecrease}; + if (EQ(i_bcp, 0)) + TP = TP - DP * dt; + Sounds[s_fv4a_t] = DP; + } + else + { + TP = 0; + } +} + +// the time reservoir charged by the overload, up to its highest pressure +void TMHZ_EN57::ChargeTimedReservoir(double const dt) +{ + if (TP < 5) + TP = TP + dt; // 5/10 + if (TP < OverloadMaxPressure) + TP = TP - 0.5 * dt; // 5/10 +} + +// the pressure the handle feeds the pipe from: the supply's over the running pressure at the filling stroke, where the +// handle has the overpressure (with its button pressed, for a button worked one), the control reservoir's otherwise +double TMHZ_EN57::SupplyPressure(double const i_bcp, double const HP) +{ + double uop = UnbrakeOverPressure; // unbrake over pressure in actual state + ManualOvrldActive = UniversalFlag & TUniversalBrake::ub_HighPressure; // button is pressed + if (ManualOvrld && !ManualOvrldActive) // no overpressure for not pressed button if it does not exists + uop = 0; + + if (EQ(i_bcp, -1) && uop > 0) + return std::min(HP, 5.4 + RedAdj + uop); + return std::min(CP, HP); +} + /// Initialises CP to the supplied pressure. /// Initial pressure [bar]. void TMHZ_EN57::Init(double Press) diff --git a/McZapkie/hamulce.h b/physics/brakes.h similarity index 98% rename from McZapkie/hamulce.h rename to physics/brakes.h index 2539250a5..4fb4b7f9f 100644 --- a/McZapkie/hamulce.h +++ b/physics/brakes.h @@ -25,7 +25,7 @@ ESt3, ESt3AL2, ESt4R, LSt, FV4a, FD1, EP2, prosty westinghouse duzo wersji żeliwa KE Tarcze od 152A -Magnetyki (implementacja w mover.pas) +Magnetyki (implementacja w physics.pas) Matrosow 394 H14K1 (zasadniczy), H1405 (pomocniczy), St113 (ep) Knorr/West EP - żeby był @@ -33,7 +33,7 @@ Knorr/West EP - żeby był #pragma once -#include "friction.h" // Pascal unit +#include "physics/friction.h" // Pascal unit /// Number of positions of the local (auxiliary/manual) brake handle. static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca recznego lub pomocniczego*/ @@ -249,6 +249,8 @@ class TReservoir /// /// Pressure in bar (atm). void CreatePress(double Press); + /// Returns reservoir capacity in liters. + double GetCap() const { return Cap; } /// /// Returns absolute (atmospheric) pressure inside the reservoir. /// @@ -273,6 +275,13 @@ class TReservoir return std::max(0.0, Vol + dVol) / Cap; } /// + /// Pressure the reservoir has now, without the flow accumulated for the step (Vol / Cap), in bar: P() of a const reservoir. + /// + double P_applied() const + { + return Vol / Cap; + } + /// /// Applies the accumulated flow (dVol) to the volume and resets dVol. /// Volume is clamped to be non-negative. /// @@ -611,6 +620,8 @@ class TESt : public TBrake /// Brake cylinder (or impulse) pressure. /// In/out accumulator for the brake pipe flow correction. void CheckState(double BCP, double &dV1); // glowny przyrzad rozrzadczy + /// The state of a valve holding: braking on in steps, the filling stopped, or released. + void CheckStateHeld(double BCP, double VVP, double CVP); /// Drives the releaser logic — bleeds the control reservoir while the releaser is engaged. /// Time step [s]. void CheckReleaser(double dt); // odluzniacz @@ -769,6 +780,12 @@ class TLSt : public TESt4R /// Constructs the LSt distributor. using TESt4R::TESt4R; + + private: + // the parts of GetPF() + void UpdateStatusLSt(double BCP, double VVP, double CVP); + void ReleaserLSt(double BCP, double CVP, double dt); + void CylinderFlowLSt(double BCP, double BVP, double CVP, double dt, double Vel); }; /// @@ -809,6 +826,13 @@ class TEStED : public TLSt /// Stores the load-weighing parameters. void SetLP(double const TM, double const LM, double const TBP) override; // parametry przystawki wazacej + private: + // the parts of GetPF() + void UpdateStatus(double BCP, double VVP, double CVP, double MPP); + double IntermediateFlow(double BCP, double VVP, double CVP, double MPP, double BVP, double nastG) const; + void CylinderFlow(double BCP, double BVP, double dt, double Vel); + + public: /// Constructs the distributor and creates the intermediate reservoir. inline TEStED(double i_mbp, double i_bcr, double i_bcd, double i_brc, int i_bcn, int i_BD, int i_mat, int i_ba, int i_nbpa) : TLSt(i_mbp, i_bcr, i_bcd, i_brc, i_bcn, i_BD, i_mat, i_ba, i_nbpa) { @@ -835,6 +859,10 @@ class TEStEP2 : public TLSt /// EP intensity (-1..1). double EPS = 0.0; + private: + // the part of GetPF() + void UpdateStatusEP2(double BCP, double VVP, double CVP); + public: /// Initialises the EP2-equipped distributor (impulse chamber, P delay). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; // inicjalizacja @@ -992,6 +1020,10 @@ class TKE : public TBrake /// Auxiliary (local) brake pressure feeding the DCV. double LBP = 0.0; // cisnienie hamulca pomocniczego + // the parts of GetPF() and CheckState() + double CylinderFlowKE(double IMP, double BCP, double BVP, double Vel, double dt); + void CheckStateHeld(double BCP, double VVP, double CVP); + public: /// Initialises the KE distributor (control / impulse / auxiliary reservoirs and BVM). void Init(double const PP, double const HPP, double const LPP, double const BP, int const BDF) override; @@ -1170,6 +1202,10 @@ class TFV4aM : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos (detent comparison). bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeChambers(double dt); + void UpdateWave(double pom, double dt); + void UpdateReductor(double i_bcp, double ep, double dt); public: /// Computes brake pipe flow for the FV4a/M handle (interpolated BPT, wave modelling, accelerator). @@ -1220,6 +1256,10 @@ class TMHZ_EN57 : public TDriverHandle double LPP_RP(double pos) const; /// Returns true if pos is within ±0.5 of i_pos. bool EQ(double pos, double i_pos) const; + // the parts of GetPF() + void DischargeTimedReservoir(double i_bcp, double dt); + void ChargeTimedReservoir(double dt); + double SupplyPressure(double i_bcp, double HP); public: /// Computes brake pipe flow for MHZ_EN57 (covers handle positions -1..10 with EP/pneumatic mix). @@ -1464,8 +1504,6 @@ class TSt113 : public TH14K1 static double const BEP_K[/*?*/ /*-1..5*/ 5 - -1 + 1]; /// Lookup of bh_* function codes to handle position values. static double const pos_table[11]; // = {-1, 5, -1, 0, 2, 3, 4, 5, 0, 0, 1}; - /// Local control pressure (mirrors PP). - double CP = 0; public: /// Computes brake pipe flow for the St113 handle (with EP). diff --git a/physics/collision.cpp b/physics/collision.cpp new file mode 100644 index 000000000..2dd3af62c --- /dev/null +++ b/physics/collision.cpp @@ -0,0 +1,401 @@ +/* +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 "physics/collision.h" + +#include +#include +#include + +#include "physics/derailment.h" + +namespace collision { + +namespace { + +// the hit is integrated in slices of this length at most, and in no more than so many of them [s] +constexpr double slice{0.0005}; +constexpr double slices_max{200.0}; + +// the force of a curve over a range of crush within one of its parts, the force linear in it there [J] +double linear_work(double const ForceFrom, double const ForceTo, double const Length) { + return 0.5 * (ForceFrom + ForceTo) * std::max(Length, 0.0); +} + +} // namespace + +double crush_curve::force(double const Crush) const { + if (Crush >= limit) { + return std::numeric_limits::infinity(); + } + if (Crush < onset) { + return peak; + } + if (Crush < densify) { + return plateau; + } + return plateau * (1.0 + hardening * (Crush - densify)); +} + +double crush_curve::energy(double const From, double const To) const { + auto const from{std::max(From, 0.0)}; + auto const to{std::min(To, limit)}; + if (to <= from) { + return 0.0; + } + auto work{0.0}; + // the peak + work += peak * std::max(0.0, std::min(to, onset) - from); + // the plateau + auto const plateaufrom{std::max(from, onset)}; + auto const plateauto{std::min(to, std::max(densify, onset))}; + work += plateau * std::max(0.0, plateauto - plateaufrom); + // packing down + auto const densefrom{std::max(from, std::max(densify, onset))}; + if (to > densefrom) { + work += linear_work(force(densefrom), plateau * (1.0 + hardening * (to - densify)), to - densefrom); + } + return work; +} + +crush_curve default_crush(vehicle_kind const Kind) { + switch (Kind) { + case vehicle_kind::locomotive: + return {4.0e6, 3.0e6, 0.05, 0.6, 2.0, 1.2}; + case vehicle_kind::crash_zone: + return {2.0e6, 2.0e6, 0.0, 0.8, 2.5, 1.2}; + case vehicle_kind::wagon: + case vehicle_kind::coach: + default: + return {3.0e6, 2.0e6, 0.05, 0.8, 2.0, 1.5}; + } +} + +vehicle_kind kind_of(bool const Powered, bool const Passenger, bool const CrashZone) { + if (CrashZone) { + return vehicle_kind::crash_zone; + } + if (Passenger) { + return vehicle_kind::coach; + } + return Powered ? vehicle_kind::locomotive : vehicle_kind::wagon; +} + +crush_curve crush_of(end_definition const &Definition, vehicle_kind const Kind) { + auto curve{default_crush(Definition.crash_zone.value_or(false) ? vehicle_kind::crash_zone : Kind)}; + curve.peak = std::max(Definition.peak.value_or(curve.peak), 1.0); + curve.plateau = std::max(Definition.plateau.value_or(curve.plateau), 1.0); + curve.onset = std::max(Definition.onset.value_or(curve.onset), 0.0); + curve.densify = std::max(Definition.densify.value_or(curve.densify), curve.onset); + curve.hardening = std::max(Definition.hardening.value_or(curve.hardening), 0.0); + curve.limit = std::max(Definition.limit.value_or(curve.limit), curve.onset); + return curve; +} + +bool anticlimber_of(end_definition const &Definition, vehicle_kind const Kind) { + return Definition.anticlimber.value_or(Definition.crash_zone.value_or(Kind == vehicle_kind::crash_zone)); +} + +double buffer_height(end_definition const &Definition, vehicle_kind const Kind, double const LoadShare) { + auto const wagon{Kind == vehicle_kind::wagon}; + auto const empty{Definition.buffer_height.value_or(wagon ? 1.065 : 1.040)}; + // the springs of a wagon give 125 mm under its full load + return wagon ? empty - 0.125 * std::clamp(LoadShare, 0.0, 1.0) : empty; +} + +buffer_rating rating(buffer_category const Category) { + switch (Category) { + case buffer_category::B: + return {0.105, 50.0e3}; + case buffer_category::C: + return {0.105, 70.0e3}; + case buffer_category::L: + return {0.150, 70.0e3}; + case buffer_category::passenger: + return {0.110, 30.0e3}; + case buffer_category::A: + default: + return {0.105, 30.0e3}; + } +} + +coupler_physics::spring_curve buffer_curve(buffer_category const Category, double const Progression) { + auto const buffer{rating(Category)}; + auto const progression{std::clamp(Progression, 0.0, 0.9)}; + // the energy of the curve to the end of the stroke is F_end * stroke * ((1 - p) / 2 + p / 4), of two buffers + auto const endforce{2.0 * buffer.energy / (buffer.stroke * ((1.0 - progression) / 2.0 + progression / 4.0))}; + return {endforce / buffer.stroke, buffer.stroke, progression}; +} + +std::optional buffer_category_of(char const Name) { + switch (Name) { + case 'A': + case 'a': + return buffer_category::A; + case 'B': + case 'b': + return buffer_category::B; + case 'C': + case 'c': + return buffer_category::C; + case 'L': + case 'l': + return buffer_category::L; + case 'P': + case 'p': + return buffer_category::passenger; + default: + return std::nullopt; + } +} + +buffer_category default_buffers(vehicle_kind const Kind) { + return Kind == vehicle_kind::coach ? buffer_category::passenger : buffer_category::A; +} + +double buffer_capacity(end_definition const &Definition, vehicle_kind const Kind) { + // two buffers side by side + return 2.0 * rating(Definition.buffers.value_or(default_buffers(Kind))).energy; +} + +void contact_energy::update(bool const Pressed, bool const Solid, double const Closing, double const Force, double const Compression, double const Dt) { + if (false == Pressed) { + // the buffers apart, the contact is over + reset(); + return; + } + if (Solid || m_inside) { + // pressed all the way, the buffers take in nothing more; nor do those of vehicles inside each other + return; + } + auto const force{std::max(Force, 0.0)}; + if (Closing > 0.0) { + m_absorbed += force * Closing * std::max(Dt, 0.0); + } + else if (Closing < 0.0) { + // springing back, they hold no more than their springs pressed in so far + m_absorbed = std::min(m_absorbed, 0.5 * force * std::max(Compression, 0.0)); + } +} + +void contact_energy::inside() { + m_absorbed = 0.0; + m_inside = true; +} + +void contact_energy::crushed(double const Work) { + m_crushed += std::max(Work, 0.0); +} + +double contact_energy::budget(double const Mass, double const Closing, double const Capacity) const { + auto const closing{std::max(Closing, 0.0)}; + // what the buffers of EN 15551 would still take in: the springs of the .fiz taking in more leave no more energy past + // the buffers than the hit has + return 0.5 * std::max(Mass, 0.0) * closing * closing - std::max(0.0, Capacity - m_absorbed); +} + +void contact_energy::reset() { + m_absorbed = 0.0; + m_crushed = 0.0; + m_inside = false; +} + +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input) { + hit_result result; + if (Input.velocity <= 0.0 || Input.mass1 <= 0.0 || Input.mass2 <= 0.0 || Input.dt <= 0.0) { + return result; + } + auto const mass{Input.mass1 * Input.mass2 / (Input.mass1 + Input.mass2)}; + auto const restitution{std::clamp(Input.restitution, 0.0, 0.95)}; + // the elastic hit on the steel at the closing velocity adds root * velocity to the force of the springs + auto const root{std::sqrt(std::max(Input.stiffness, 1.0) * mass)}; + auto const springs{std::max(Input.springs, 0.0)}; + // the closing velocity the step started with: the springs slow the pair over the step as well, the hit adds what + // they don't carry of the force the end gives at + auto velocity{Input.start_velocity > 0.0 ? std::max(Input.start_velocity, Input.velocity) : Input.velocity + springs * Input.dt / mass}; + // where the forces of the step alone would take the pair + auto const unhit{velocity - springs * Input.dt / mass}; + + auto crush1{First.crush}; + auto crush2{Second.crush}; + auto const elastic_limit = [&](double const Force) { return std::max(0.0, Force - springs) / root; }; + { + auto const force{std::min(First.curve.force(crush1), Second.curve.force(crush2))}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force) || false == (Input.budget > 0.0)) { + // the steel takes it all: the legacy elastic exchange + return result; + } + } + result.crushing = true; + + auto const slices{std::clamp(std::ceil(Input.dt / slice), 1.0, slices_max)}; + auto const length{Input.dt / slices}; + auto time{0.0}; + auto rebound{false}; + auto crushtime{0.0}; + auto work{0.0}; + auto cap{0.0}; // the force the crush went at last + while (Input.dt - time > 1e-12) { + auto const force1{First.curve.force(crush1)}; + auto const force2{Second.curve.force(crush2)}; + auto const force{std::min(force1, force2)}; + if (false == std::isfinite(force) || velocity <= elastic_limit(force)) { + // both ends crushed all the way, or the pair slowed down to what the steel takes back + rebound = true; + break; + } + auto const limit{elastic_limit(force)}; + auto step{std::min(length, Input.dt - time)}; + auto change{force * step / mass}; + if (velocity - change < limit) { + step = (velocity - limit) * mass / force; + change = velocity - limit; + } + auto crush{(velocity - 0.5 * change) * step}; + auto spent{false}; + if (work + force * crush > Input.budget) { + // the energy of the hit past the buffers runs out in the slice: the crush goes as far as it takes, the + // buffers of EN 15551 would take in the rest + auto const share{std::clamp((Input.budget - work) / std::max(force * crush, 1e-12), 0.0, 1.0)}; + step *= share; + change *= share; + crush *= share; + spent = true; + } + work += force * crush; + cap = force; + // the weaker end gives, both alike when they're alike + if (std::abs(force1 - force2) <= 1e-9 * force) { + crush1 += 0.5 * crush; + crush2 += 0.5 * crush; + } + else if (force1 < force2) { + crush1 += crush; + } + else { + crush2 += crush; + } + velocity -= change; + time += step; + crushtime += step; + result.force = std::max(result.force, force); + if (spent) { + result.spent = true; + rebound = true; + break; + } + } + + auto after{velocity}; + auto duration{crushtime}; + if (rebound) { + // the steel springs back with the restitution, the springs push the pair apart over the rest of the step + // under the force the weaker end gives at, as the slices stopped there. a crush stopped at the budget: the + // buffers of EN 15551 would have taken in the rest, its force no more than what crushes the end + result.force = std::max(result.force, result.spent ? std::min(springs + velocity * root, cap) : springs + velocity * root); + if (velocity > 0.0) { + duration += (1.0 + restitution) * velocity * mass / std::max(velocity * root, 1.0); + } + after = -restitution * velocity - springs * (Input.dt - time) / mass; + } + result.velocity = after; + result.impulse = mass * (unhit - after); + result.duration = std::min(duration, Input.dt); + result.crush1 = crush1 - First.crush; + result.crush2 = crush2 - Second.crush; + result.work = work; + return result; +} + +override_result override_of(override_input const &Input) { + override_result result; + if (Input.anticlimbers) { + // interlocked, they keep the ends level until the crush zone of one of them is used up + auto const spent1{Input.zone1 <= 0.0 || Input.crush1 >= Input.zone1}; + auto const spent2{Input.zone2 <= 0.0 || Input.crush2 >= Input.zone2}; + if (false == spent1 && false == spent2) { + return result; + } + } + auto const crush{Input.crush1 + Input.crush2}; + if (crush > override_both) { + result.first = true; + result.second = true; + return result; + } + if (crush <= override_crush) { + return result; + } + if (Input.mass1 * override_mass_ratio < Input.mass2) { + result.first = true; + } + else if (Input.mass2 * override_mass_ratio < Input.mass1) { + result.second = true; + } + else if (false == Input.anticlimbers && std::abs(Input.height1 - Input.height2) >= override_height - 1e-9) { + // the higher one rides up + result.first = Input.height1 > Input.height2; + result.second = false == result.first; + } + return result; +} + +double pushed_wheel::ratio() const { + if (q > 0.0) { + return y / q; + } + return y > 0.0 ? 1e9 : 0.0; +} + +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + return pushed_forces(Vehicle, End, Radius).ratio(); +} + +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double const Radius) { + pushed_wheel result; + if (Vehicle.mass <= 0.0 || End.force <= 0.0) { + return result; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + // the axles of the half of the vehicle at the end: its bogie, or its axle + auto const half{std::max(axles / 2.0, 1.0)}; + auto const wheelload{Vehicle.mass * gravity / (2.0 * axles)}; + auto const halflength{std::max(0.5 * Vehicle.length, 1.0)}; + auto const angle{straight_angle + derailment::coupling_angle(Vehicle.length, End.other_length, Radius) + crush_angle * std::max(End.crush, 0.0) / halflength}; + // in a curve the leading axle meets the rail at an angle, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (std::abs(Radius) > 1e-3) { + auto const attack{Vehicle.axle_base / (2.0 * std::abs(Radius))}; + guiding = derailment::tread_friction * wheelload * std::min(1.0, attack / derailment::saturated_attack); + } + auto const lateral{End.force * angle / half + guiding}; + // the force off the height it's carried at pitches the vehicle: the bogie at the end pressed in takes the load off + auto const pivots{Vehicle.pivots > 0.0 ? Vehicle.pivots : halflength}; + result.y = lateral; + result.q = wheelload - End.force * eccentricity / (2.0 * half * pivots); + return result; +} + +bool pushed_monitor::update(bool const Climbs, double const Distance, bool const Lifted, double const Duration) { + auto const climbed{m_climbing.update(Climbs, Distance, climb_distance)}; + if (false == Lifted) { + m_lifted = 0.0; + return climbed; + } + m_lifted += std::max(Duration, 0.0); + return climbed || m_lifted >= lift_time - 1e-9; +} + +void pushed_monitor::reset() { + m_climbing.reset(); + m_lifted = 0.0; +} + +} // namespace collision diff --git a/physics/collision.h b/physics/collision.h new file mode 100644 index 000000000..9b9258169 --- /dev/null +++ b/physics/collision.h @@ -0,0 +1,297 @@ +/* +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 + +#include +#include + +#include "physics/couplerphysics.h" +#include "physics/derailment.h" + +// what a collision of two vehicles does to them past their buffers (physics.collisions new in eu07.ini, see +// physics::Vehicle::CollisionDetect()), as plain functions of the vehicles and the hit: +// +// crush: once the buffers of the pair are pressed all the way, the underframes carry the rest of the hit, up to the +// force the weaker end gives at. only the energy the hit brings past what the buffers of EN 15551 of both ends take +// in can crush them (contact_energy): a hit the buffers would take, or the push of a train at a stand, never does. past it the end crushes for good: a short peak of force, then a lower plateau as +// the structure folds, then it packs down and stiffens (the force-crush curves of the full scale tests of the FRA: +// Tyrell et al., IMECE2002-33247). the hit is an impulse limited to that force over the step, so the force never +// goes past it and the depth of the crush is the same with any step; the depth stays with the end +// override: an end crushed deep enough no longer holds the other one down: the lighter of the two vehicles, or the +// one with its buffers higher (40 mm, the vertical offset of the design collision of EN 15227), climbs onto the +// other one and leaves the rails; past a deeper crush both do. interlocked anticlimbers hold them until the crush +// zone of an end is used up +// pushed off the track: the force pressing a vehicle's end acts at an angle to it, the more in a curve and the +// deeper the end is crushed, which gives a lateral force on its wheels; acting off the height of the centre of the +// vehicle it lifts its leading wheels. Y / Q over Nadal's limit while the wheels roll on over the window of +// EN 14363 and the flange climbs the rail (the light wagon between heavy ones goes first, in a curve sooner than +// on a straight track: EN 15566 takes 250 kN of the pair of buffers in a curve of 150 m as the safe push). a wheel +// which doesn't roll doesn't climb: Nadal's limit is that of a wheel rolling under its angle of attack, the creep of +// the flange contact turning the friction upwards; standing, the friction holds the flange down, and with a flange +// of 70 degrees and a friction over 1 / tan 70 = 0.36 no lateral force gets it up. so a train pushing at a stand, +// or the short peak of the springs of a hit, never pushes a wheel off. a push that takes the whole load off the +// leading wheels lifts them off the rail, rolling or not: that holding for a short time is enough +namespace collision { + +inline constexpr double gravity{9.81}; // [m/s2] + +// ---- the crush of an end + +// force-crush characteristic of the underframe at one end of a vehicle +struct crush_curve { + double peak{3.0e6}; // the force the crushing starts at [N] + double plateau{2.0e6}; // of the crushing past the onset [N] + double onset{0.05}; // the crush past which the peak drops to the plateau [m] + double densify{0.8}; // the crush past which the crushed structure packs down and stiffens [m] + double hardening{2.0}; // the growth of the force past it, to the plateau for each metre [1/m] + double limit{1.5}; // the end can't be crushed past it, it's rigid from there [m] + + // the force the end gives at with the crush [N]; past the limit there's no force it gives at + double force(double Crush) const; + // the work it takes to crush the end from the one depth to the other one [J] + double energy(double From, double To) const; +}; + +// what the vehicle is, for its defaults +enum class vehicle_kind { + wagon, // a freight wagon + coach, // a passenger coach, or a car of a unit + locomotive, + crash_zone // a vehicle built to EN 15227, with the energy absorbers and the anticlimbers at its ends +}; +// the defaults of the kind: a wagon or a coach gives at 1.5 times the force of the proof test of EN 12663 at the +// height of the buffers (2 MN), a locomotive at 4 MN; the plateau is the 2 MN of the crush of the cab car of the FRA +// test. the absorbers of a crash zone give a steady 2 MN over 0.8 m, as the deformation tubes and the crash buffers +// do (2 MN of the crash buffers in service) +crush_curve default_crush(vehicle_kind Kind); + +// the buffers of EN 15551, by their category +enum class buffer_category { + A, // 105 mm, 30 kJ + B, // 105 mm, 50 kJ + C, // 105 mm, 70 kJ + L, // the long stroke, 150 mm + passenger // 110 mm, of the coaches +}; + +// the optional keys of the .fiz for an end (BuffCoupl): what's not given comes from the kind of the vehicle +struct end_definition { + std::optional peak; // FcrushPeak [N] + std::optional plateau; // FcrushPlateau [N] + std::optional onset; // CrushOnset [m] + std::optional densify; // CrushDensify [m] + std::optional hardening; // CrushHardening [1/m] + std::optional limit; // CrushLimit [m] + std::optional crash_zone; // CrashZone: built to EN 15227 + std::optional anticlimber; // AntiClimber + std::optional buffer_height; // BufferHeight, of the empty vehicle above the rail [m] + std::optional buffers; // BufferCategory +}; +vehicle_kind kind_of(bool Powered, bool Passenger, bool CrashZone); +crush_curve crush_of(end_definition const &Definition, vehicle_kind Kind); +bool anticlimber_of(end_definition const &Definition, vehicle_kind Kind); +// height of the buffers above the rail [m]: UIC 940 to 1065 mm. without a given one, a wagon has them at the top of +// the range empty and lower by 125 mm fully loaded on its springs, a locomotive or a coach at 1040 mm +double buffer_height(end_definition const &Definition, vehicle_kind Kind, double LoadShare); + +// ---- the buffers, EN 15551 + +struct buffer_rating { + double stroke{0.105}; // [m] + double energy{30.0e3}; // dynamic energy of one buffer [J] +}; +buffer_rating rating(buffer_category Category); +// the spring curve of the two buffers of an end side by side, of the progression given, which takes in their energy +// over the stroke +coupler_physics::spring_curve buffer_curve(buffer_category Category, double Progression); +std::optional buffer_category_of(char Name); +// the buffers of an end without the category given: of category A, those of a coach of its own category (EN 15551, +// 30 kJ a buffer either way) +buffer_category default_buffers(vehicle_kind Kind); +// the energy the two buffers of an end take in over their stroke, of the category given or the default of the kind [J] +double buffer_capacity(end_definition const &Definition, vehicle_kind Kind); + +// vehicles pressed onto each other past the stop of their buffers and the crush of their ends by more than this, more +// than a hit could have taken them in a step, are inside each other: a scenery put them down overlapping. no hit the +// crush could tell anything of, the legacy collision handles them [m] +inline constexpr double inside_margin{0.5}; + +// ---- the energy of a hit, for the crush + +// the energy budget of the crush in a contact of two ends. what a hit brings to the stop of the buffers is the kinetic +// energy of the relative motion of the pair there, and what its buffers took in on the way (the springs of the .fiz, +// which may take less than the buffers of EN 15551 would). the buffers of EN 15551 of both ends take in their +// capacity of it first, the crush may take only the rest: +// budget = 1/2 mu v^2 - max(0, capacity - absorbed) +// over the steps of a crush the crush done already is in neither term, so the crush of the whole hit never takes more +// than the hit brought past the buffers. the train behind the pair pushing it on through the crush brings in more: +// it's in the velocity the pair closes in with in the next step. the buffers take in in the stroke under way: the +// buffers pressed and the pair closing in. springing back they keep what they still hold, so a train pushing at a +// stand never builds up what it feeds into their damping. the buffers pressed all the way from the start of the +// contact took in nothing: vehicles put down inside each other, or knocked onto each other by a hit elsewhere, bring +// in only the kinetic energy they close in with. nor do the buffers of vehicles found inside each other in the +// contact (inside_margin) take in anything until they part: their springs pressed past the stop and back throw the +// pair about, which is no hit +class contact_energy { +public: + // the step of the pair: whether its buffers press, and all the way; the closing velocity [m/s] and the force + // pressing the buffers [N] at the start of the step; how far they're pressed in [m]; the length of the step [s] + void update(bool Pressed, bool Solid, double Closing, double Force, double Compression, double Dt); + // the vehicles of the pair are inside each other: what the buffers took in is gone, and they take in nothing more + // until the contact is over + void inside(); + // the crush of the hit took the energy [J] + void crushed(double Work); + // the energy the crush may take now, closing in at the velocity [m/s] with the reduced mass [kg], the buffers of + // both ends taking in the capacity [J]; zero or less, the hit stays elastic + double budget(double Mass, double Closing, double Capacity) const; + // what the buffers took in in the stroke under way [J], and the crush in the contact + double absorbed() const { return m_absorbed; } + double crush_work() const { return m_crushed; } + void reset(); + +private: + double m_absorbed{0.0}; + double m_crushed{0.0}; + bool m_inside{false}; +}; + +// ---- the hit past the buffers + +// an end of the pair, as the hit sees it +struct end_state { + crush_curve curve; + double crush{0.0}; // the depth it's crushed to already [m] +}; + +struct hit_input { + double velocity{0.0}; // the pair closes in on the stop at [m/s] + double mass1{0.0}; // [kg] + double mass2{0.0}; + double restitution{0.2}; // coefficient of restitution of the elastic rest of the hit + double stiffness{1.0e8}; // of the steel parts of both ends in series, past the springs [N/m] + double springs{0.0}; // the force the springs of the pair carry at the stop over the step [N] + double dt{0.01}; // the length of the step [s] + // the closing velocity the pair started the step with, before the forces of the step [m/s]; without it (0), the + // velocity with what the springs took off it over the step + double start_velocity{0.0}; + // the energy the crush may take at most [J] (contact_energy::budget()); none left, the hit stays elastic, and the + // crush stops once it took it, the rest springs back as the buffers would have taken it + double budget{std::numeric_limits::infinity()}; +}; + +struct hit_result { + bool crushing{false}; // false: the hit stays elastic, it's the legacy exchange of momentum + double impulse{0.0}; // the hit adds to the forces of the step, pushing the vehicles apart [N s] + double velocity{0.0}; // the closing velocity after the step [m/s], negative as they part + double force{0.0}; // the peak force between the ends, with the springs [N] + double duration{0.0}; // how long that force acted over the step [s] + double crush1{0.0}; // added to the end of the first vehicle [m] + double crush2{0.0}; // of the second one + double work{0.0}; // the crush took [J] + bool spent{false}; // the crush stopped at the budget +}; + +// the hit of the step: the steel takes the hit elastically up to the force the weaker end gives at, past that the end +// crushes at that force until the pair closes in no faster than the steel takes back. the motion over the step is +// integrated in short slices, with the springs slowing the pair as well, so the crush doesn't depend on the step +hit_result hit(end_state const &First, end_state const &Second, hit_input const &Input); + +// a crush of an end deeper than this is a damage worth the log [m] +inline constexpr double crush_mark{0.05}; +// the draw gear sits behind the headstock: crushed this deep, the coupling of the end is torn off [m] +inline constexpr double draw_gear_crush{0.15}; + +// ---- override + +// the crush of the contact of both ends past which the lighter (or the higher) vehicle climbs onto the other one, +// and past which both leave the rails [m] +inline constexpr double override_crush{0.35}; +inline constexpr double override_both{0.6}; +// the masses differ enough for the lighter one to climb +inline constexpr double override_mass_ratio{1.3}; +// the buffers differ in height enough for the higher one to climb: the vertical offset of the design collision of +// EN 15227 [m] +inline constexpr double override_height{0.04}; + +struct override_input { + double crush1{0.0}; // of the end of the first vehicle [m] + double crush2{0.0}; + double mass1{0.0}; // [kg] + double mass2{0.0}; + double height1{1.0}; // of its buffers [m] + double height2{1.0}; + bool anticlimbers{false}; // both ends have them, interlocked + double zone1{0.0}; // the crush zone of the end with the anticlimber, its densify [m] + double zone2{0.0}; +}; +struct override_result { + bool first{false}; // the first vehicle left the rails + bool second{false}; +}; +override_result override_of(override_input const &Input); + +// ---- pushed off the track + +// the angle of the force at the end of a vehicle to it on a straight track: the play of the wheelsets and of the +// bogies, the buffer heads off the middle [rad] +inline constexpr double straight_angle{0.006}; +// the crushed end no longer keeps the ends in line: the angle grows by this share of the crush to the half length +inline constexpr double crush_angle{0.1}; +// the height the force acts at off the height it's carried at, the buffers of the pair not at the same height [m] +inline constexpr double eccentricity{0.10}; +// the distance the wheels have to roll with Y / Q over the limit for the flange to climb the rail: the window of the +// criteria of derailment [m] +inline constexpr double climb_distance{derailment::window}; +// the time the push has to hold the leading wheels off the rail, without any load on them, to lift them over the +// rail [s] +inline constexpr double lift_time{0.05}; + +struct pushed_vehicle { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double pivots{0.0}; // the distance of the bogie pivots, of the axles without bogies [m] + double axle_base{0.0}; // the wheelbase of a bogie, of the vehicle without bogies [m] +}; +struct pushed_end { + double force{0.0}; // pressing the end in [N] + double other_length{0.0}; // of the vehicle at that end [m] + double crush{0.0}; // of the end [m] +}; +// the forces of the leading wheel at the end pressed in by the force, in a curve of the radius [m] (0 straight): its +// lateral force, and its vertical one, none or less when the push lifts it off the rail +struct pushed_wheel { + double y{0.0}; // [N] + double q{0.0}; // [N] + double ratio() const; + bool lifted() const { return q <= 0.0 && y > 0.0; } +}; +pushed_wheel pushed_forces(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); +// Y / Q of that wheel +double pushed_ratio(pushed_vehicle const &Vehicle, pushed_end const &End, double Radius); + +// the push off the track step by step: how far the wheels rolled with Y / Q over the limit without a break, and how +// long the push held the leading wheels lifted off the rail +class pushed_monitor { +public: + // true once the flange climbed the rail, given whether Y / Q held over the limit in the step and the distance the + // wheels rolled while it held [m], and whether the push lifted the wheels and for how long in the step [s] + bool update(bool Climbs, double Distance, bool Lifted, double Duration); + void reset(); + double distance() const { return m_climbing.distance(); } + double time() const { return m_lifted; } + +private: + derailment::stretch m_climbing; + double m_lifted{0.0}; +}; + +} // namespace collision diff --git a/physics/components/airsupply.h b/physics/components/airsupply.h new file mode 100644 index 000000000..b5a04460b --- /dev/null +++ b/physics/components/airsupply.h @@ -0,0 +1,326 @@ +/* +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 supply of compressed air of a vehicle: the compressor and the main reservoir, held by physics::Vehicle as air; and +// the pipes along the train, held by it as brakePipe and mainPipe. as the parts of the main circuit (maincircuit.h): the +// definition in `config`, the state behind queries and operations + +#pragma once + +#include +#include +#include + +#include "physics/vehicletypes.h" + +class TReservoir; + +namespace physics +{ + +// a pipe along the train, coupled by the hoses between the vehicles: the brake pipe, the main reservoir pipe +class TrainPipe +{ + public: + std::shared_ptr reservoir; + + // the pressure in the pipe [bar], as it was last taken from its reservoir + double const &Pressure() const { return pressure; } + // the pressure taken from the reservoir of the pipe, after the flows of a step + void SetPressure(double const Value) { pressure = Value; } + + // the pipe stepped, its exchange of air through the hoses is yet to come (UpdatePipeCouplers()) + bool CouplersPending() const { return couplersPending; } + void SetCouplersPending(bool const State) { couplersPending = State; } + + private: + double pressure{0.0}; + bool couplersPending{false}; +}; + +// where the compressor gets its power from (CompressorPower of the .fiz), in the order of the numbers it had before +enum class CompressorSupply +{ + mainCircuit, // Main + converterManual, // the default: from the converter, switched by hand + converter, // Converter: from the converter, always + engine, // Engine: driven by the diesel engine + frontUnitConverter, // Coupler1: from the converter of the unit in front (a motor car of an EMU) + rearUnitConverter, // Coupler2: from the converter of the unit behind +}; + +// what the compressor needs to know in the step +struct CompressorInputs +{ + bool converterAllowed{false}; // the converter of the vehicle may run + bool mainCircuitPowered{false}; // the main circuit has its power + bool lowVoltage110v{false}; // the 110 V circuit has its power + bool coupledGovernorLock{false}; // a vehicle coupled permanently has its compressor stopped by the governor + bool switchingDelayPassed{false}; // the vehicle may switch something on again (LastSwitchingTime > CtrlDelay) + double engineRpmRatio{0.0}; // the revolutions of the engine against the most at its position, for a compressor it drives +}; + +// what the step of the compressor did, for the vehicle to follow it up +struct CompressorStep +{ + bool switched{false}; // it started or stopped + bool vented{false}; // the reservoir let air out over the top pressure +}; + +// the compressor of the main reservoir +class AirCompressor +{ + public: + struct Config + { + // the definition (the Brake section of the .fiz). where the pressures follow the occupied cab (cabDependent) the + // compressor sets minPressure and maxPressure to those of the cab in each step + double minPressure{0.0}; // MinCP: it starts below this pressure of the main reservoir + double maxPressure{0.0}; // MaxCP: it stops above this pressure + double minPressureCabA{0.0}; // the pressures of each cab, where they differ (MinCP_B, MaxCP_B given) + double maxPressureCabA{0.0}; + double minPressureCabB{0.0}; // MinCP_B + double maxPressureCabB{0.0}; // MaxCP_B + bool cabDependent{false}; // the pressures follow the occupied cab + double speed{0.0}; // CompressorSpeed: how fast it fills the main reservoir + CompressorSupply supply{CompressorSupply::converterManual}; // CompressorPower + double startDelay{0.0}; // CompressorStartDelay: how long it waits after getting its power before it can start, after the engine starts say [s] + bool tankValve{false}; // CompressorTankValve: the pressure over the top is let out of its tank at once + start_t start{start_t::manual}; // CompressorStart: whether it is started by hand, or another way + // the programmer of the compressors of a unit (the CompressorList section), indexed by the cl_* rows + std::array, 4> list{}; + int listPositions{0}; // Size: the positions of its switch + int listDefaultPosition{1}; // Default + bool listWraps{false}; // Wrap + }; + Config config; + + // a compressor of no output doesn't count + bool IsFitted() const { return config.speed != 0.0; } + bool IsRunning() const { return running; } + void Stop() { running = false; } + + // it may start, as its switch (or what drives it) has it + bool IsAllowed() const { return allow; } + void Allow(bool const State) { allow = State; } + // the switch of the vehicle itself; most have none, so it allows + bool LocalSwitchOn() const { return allowLocal; } + void SetLocalSwitch(bool const State) { allowLocal = State; } + // the governor switched it off at the cut-out pressure + bool IsGovernorLocked() const { return governorLock; } + + // the position of the switch of the programmer + int ListPosition() const { return listPosition; } + void SetListPosition(int const Position) { listPosition = std::min(std::max(Position, 0), config.listPositions); } + // the programmer at its default position, as the vehicle is placed + void ResetListPosition() + { + if (config.listPositions > 0) + { + listPosition = config.listDefaultPosition; + } + } + + // the pressures of the occupied cab, where they follow it + void SelectCab(int const Cab) + { + if (false == config.cabDependent) + { + return; + } + if (Cab > 0) + { + config.minPressure = config.minPressureCabA; + config.maxPressure = config.maxPressureCabA; + } + if (Cab < 0) + { + config.minPressure = config.minPressureCabB; + config.maxPressure = config.maxPressureCabB; + } + } + + // the fault the scenery can set (the damage events): its pressures moved out of reach, so it never starts; and back + void SetFault(bool const State) + { + constexpr double faultoffset{100000001}; + if (State) + { + if (config.minPressure > 0) + config.minPressure -= faultoffset; + if (config.maxPressure > 0) + config.maxPressure -= faultoffset; + } + else + { + if (config.minPressure < 0) + config.minPressure += faultoffset; + if (config.maxPressure < 0) + config.maxPressure += faultoffset; + } + } + + // the step of the compressor, which works the reservoir of the given volume of compressed air at the given pressure + CompressorStep Update(CompressorInputs const &Inputs, double &CompressedVolume, double const ReservoirPressure, double const dt) + { + CompressorStep step; + // assorted operational logic + auto const maxpressure{config.list[cl_MaxFactor][listPosition] * config.maxPressure}; + auto const minpressure{config.list[cl_MinFactor][listPosition] * config.minPressure}; + auto const speed{config.list[cl_SpeedFactor][listPosition] * config.speed}; + // checking the impact on the compressor allowance + if (auto const allowfactor{config.list[cl_Allow][listPosition]}; allowfactor > 0.5) + { + allow = allowfactor > 1.5; + } + switch (config.supply) + { + case CompressorSupply::converter: + allow = Inputs.converterAllowed; + break; + case CompressorSupply::engine: + // HACK: make sure compressor coupled with diesel engine is always ready for work + config.start = start_t::automatic; + break; + default: + break; + } + + // the main circuit, also for a compressor driven by the engine, otherwise the low voltage + auto const power{config.supply == CompressorSupply::mainCircuit || config.supply == CompressorSupply::engine ? Inputs.mainCircuitPowered : Inputs.lowVoltage110v}; + powerTime = power ? powerTime + dt : 0.0; + auto const ready{power && powerTime >= config.startDelay}; + // TBD: split CompressorAllow into separate enable/disable flags, inherit compressor from basic_device + auto const enable{allowLocal && (config.start == start_t::automatic || allow)}; + + auto const pressuretoolow{ReservoirPressure < minpressure}; + auto const pressuretoohigh{ReservoirPressure > maxpressure}; + + // TBD, TODO: break the lock with no low voltage power? + auto const governorlockpresent{maxpressure - minpressure > 0.0001}; + governorLock = governorlockpresent && false == pressuretoolow // unlock if pressure drops below minimal threshold + && (pressuretoohigh || governorLock); // lock if pressure goes above maximum threshold + // for these multi-unit engines compressors turn off whenever any of them was affected by the governor + // NOTE: this is crude implementation, limited only to adjacent vehicles + // TODO: re-implement when a more elegant/flexible system is in place + auto const locked{governorLock || Inputs.coupledGovernorLock}; + + auto const wasrunning{running}; + running = ready && enable && (false == locked || config.supply == CompressorSupply::engine) && (running || (enable && Inputs.switchingDelayPassed)); + step.switched = running != wasrunning; + + if (false == running) + { + return step; + } + + // working compressor adds air to the air reservoir + if (config.supply == CompressorSupply::engine) + { + // the compressor is coupled with the diesel engine, engine revolutions affect the output + CompressedVolume += speed * (2.0 * maxpressure - ReservoirPressure) / maxpressure * Inputs.engineRpmRatio * dt * (governorLock ? 0.0 : 1.0); // with the lock active air is vented out + } + else + { + // the compressor is a stand-alone device, working at steady pace + CompressedVolume += speed * (2.0 * maxpressure - ReservoirPressure) / maxpressure * dt; + } + + if (pressuretoohigh && (false == governorlockpresent || config.supply == CompressorSupply::engine)) + { + // vent some air out if there's no governor lock to stop the compressor from exceeding acceptable pressure level + step.vented = true; + auto ventedfraction{0.999}; // HACK: drop a tiny bit so the sound doesn't trigger repeatedly + if (false == governorlockpresent) + { + ventedfraction = 0.80; // arbitrary amount + } + else if (config.tankValve) + { + ventedfraction = minpressure / maxpressure; // drop to mincompressor level + } + CompressedVolume *= ventedfraction; + if (false == governorlockpresent || config.tankValve) + { + governorLock = false; + } + } + return step; + } + + private: + bool running{false}; + bool allow{false}; + bool allowLocal{true}; + bool governorLock{false}; + double powerTime{0.0}; // how long it has had its power [s] + int listPosition{0}; +}; + +// the supply of compressed air +class AirSupply +{ + public: + struct Config + { + double mainReservoirVolume{0.0}; // Vv: the volume of the main reservoir + double leakRate{0.01}; // AirLeakRate: the base rate of the air leaking from the components of the brakes (0.001 = 1 l/s) + }; + Config config; + + AirCompressor compressor; + + // the pressure in the main reservoir [bar], as the last step found it + double const &MainReservoirPressure() const { return mainReservoirPressure; } + // the pressure taken from the air in the reservoir; an empty one of no volume has none, and stops the compressor + void UpdatePressure() + { + if (config.mainReservoirVolume > 0) + { + mainReservoirPressure = compressedVolume / config.mainReservoirVolume; + } + else + { + mainReservoirPressure = 0; + compressor.Stop(); + } + } + + // the compressed air in the supply + double CompressedVolume() const { return compressedVolume; } + // air let into the reservoir, or out of it with a negative volume + void AddAir(double const Volume) { compressedVolume += Volume; } + // the reservoir filled with the given volume of compressed air, as the vehicle is placed + void Fill(double const Volume) { compressedVolume = Volume; } + // no air below nothing + void ClampEmpty() + { + if (compressedVolume < 0.0) + { + compressedVolume = 0.0; + } + } + + // the step of the reservoir and its compressor: the leaks, then the compressor, which fills it + CompressorStep Update(CompressorInputs const &Inputs, double const dt) + { + compressedVolume = std::max(0.0, compressedVolume - dt * config.leakRate * 0.1); // nieszczelności: 0.001=1l/s + mainReservoirPressure = compressedVolume / config.mainReservoirVolume; + return compressor.Update(Inputs, compressedVolume, mainReservoirPressure, dt); + } + + // for the tests: the pressure in the reservoir as given, whatever its air + void SetPressureForTest(double const Value) { mainReservoirPressure = Value; } + + private: + double mainReservoirPressure{0.0}; + double compressedVolume{0.0}; +}; + +} // namespace physics diff --git a/physics/components/body.cpp b/physics/components/body.cpp new file mode 100644 index 000000000..a65ff1178 --- /dev/null +++ b/physics/components/body.cpp @@ -0,0 +1,1354 @@ +/* +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 vehicle as a body: construction, the forces on it, its movement along the track, adhesion and sand + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" +#include "physics/components/drive.h" + + +int DirPatch(VehicleEnd const Coupler1, VehicleEnd const Coupler2) +{ // poprawka dla liczenia sil przy ustawieniu przeciwnym obiektow + return Coupler1 != Coupler2 ? 1 : -1; +} +namespace +{ + + +// physics.collisions new: a rail vehicle derailed the legacy way keeps the deceleration of the legacy model, g, as the +// friction of its weight, and the forces of the vehicles coupled to it act on it as on any other: the train behind it +// pushes it on, and it holds the train back. alone it stops as the legacy model has it. the legacy model stops it +// whatever pushes it, and the train behind it stopped at once against it, in a hit no train had +bool legacy_derailed_slides(physics::Vehicle const &Vehicle) +{ + return Global.collisions == global_settings::collision_model::physical && TestFlag(Vehicle.CategoryFlag, 1) && Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && + Vehicle.Derailed() == derailment::outcome::none; +} + +} // namespace + +int DirF(VehicleEnd CouplerN) +{ + switch (CouplerN) + { + case VehicleEnd::front: + return -1; + case VehicleEnd::rear: + return 1; + default: + return 0; + } +} + +// ************************************************************************************************* +// główny konstruktor +// ************************************************************************************************* +physics::Vehicle::Vehicle(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab) : TypeName(TypeNameInit), Name(NameInit), cabOccupied(Cab) +{ + WriteLog("------------------------------------------------------"); + WriteLog("init default physic values for " + NameInit + ", [" + TypeNameInit + "]"); + + // BrakeLevelSet(-2); //Pascal ustawia na 0, przestawimy na odcięcie (CHK jest jeszcze nie wczytane!) + litLights[0] = 0; + litLights[1] = 0; // światła zgaszone + + // inicjalizacja stalych + for (auto &scheme : RList) + { + scheme = TScheme(); + } + RlistSize = 0; + for (auto &motorparam : MotorParam) + { + motorparam = TMotorParameters(); + } + + for (auto &cablights : Lights) + for (int k = 0; k < 17; ++k) + cablights[k] = 0; + + for (auto &compressorrow : air.compressor.config.list) + for (int k = 1; k < 9; ++k) + compressorrow[k] = 0; + air.compressor.config.list[0][0] = 0.0; + air.compressor.config.list[1][0] = 1.0; + air.compressor.config.list[2][0] = 1.0; + air.compressor.config.list[3][0] = 1.0; + + for (int b = -1; b <= MainBrakeMaxPos; ++b) + { + brakes.config.pressureTable[b].PipePressureVal = 0.0; + brakes.config.pressureTable[b].BrakePressureVal = 0.0; + brakes.config.pressureTable[b].FlowSpeedVal = 0.0; + } + // with BrakePressureTable[-2] do {pozycja odciecia} + { + brakes.config.pressureTable[-2].PipePressureVal = -1.0; + brakes.config.pressureTable[-2].BrakePressureVal = -1.0; + brakes.config.pressureTable[-2].FlowSpeedVal = 0.0; + } + for (auto &delay : brakes.config.delays) + { + delay = 0.0; + } + + for (int b = 0; b < 2; ++b) // Ra: kto tu zrobił "for b:=1 to 2 do" ??? + { + Couplers[b].CouplerType = TCouplerType::NoCoupler; + Couplers[b].SpringKB = 1.0; + Couplers[b].SpringKC = 1.0; + Couplers[b].DmaxB = 0.1; + Couplers[b].FmaxB = 1000.0; + Couplers[b].DmaxC = 0.1; + Couplers[b].FmaxC = 1000.0; + } + for (auto &cylindermult : brakes.config.cylinders.leverRatio) + { + cylindermult = 0.0; + } + + for (auto &couplerentry : Couplers) + { + couplerentry.AllowedFlag = Coupling::coupler | Coupling::brakeHose; // domyślnie hak i hamulec, inne trzeba włączyć jawnie w FIZ + couplerentry.CouplingFlag = {}; + couplerentry.Connected = nullptr; + couplerentry.ConnectedNr = 0; // Ra: to nie ma znaczenia jak nie podłączony + couplerentry.Render = false; + couplerentry.CForce = 0.0; + couplerentry.Dist = 0.0; + couplerentry.CheckCollision = false; + } + + for (auto &brakepress : brakes.config.maxCylinderPressure) + { + brakepress = 0.0; + } + + Vel = abs(VelInitial); + travelSpeed = VelInitial / 3.6; + + RunningShape.Len = 1.0; + + RunningTrack.CategoryFlag = CategoryFlag; + RunningTrack.Width = TrackW; + RunningTrack.friction = Steel2Steel_friction; + RunningTrack.QualityFlag = 20; + RunningTrack.DamageFlag = 0; + RunningTrack.Velmax = 100.0; // dla uzytku maszynisty w ai_driver} + + RunningTraction.TractionVoltage = 0.0; + RunningTraction.TractionFreq = 0.0; + RunningTraction.TractionMaxCurrent = 0.0; + RunningTraction.TractionResistivity = 1.0; +}; + +void physics::Vehicle::change_train_velocity(double const Change) +{ + // the vehicles coupled to this one in a line, each with the direction of its axis to the axis of this one + std::vector> train{{this, 1}}; + for (std::size_t i = 0; i < train.size(); ++i) + { + auto const [vehicle, direction] = train[i]; + for (auto const end : VehicleEnds) + { + auto const &coupler{vehicle->Couplers[end]}; + auto *other{coupler.Connected}; + if (other == nullptr || coupler.CouplingFlag == Coupling::none || std::any_of(train.begin(), train.end(), [other](auto const &Entry) { return Entry.first == other; })) + { + continue; + } + auto const otherdirection{direction * DirPatch(end, coupler.ConnectedEnd())}; + other->travelSpeed += Change * otherdirection; + train.emplace_back(other, otherdirection); + } + } +} + +// ************************************************************************************************* +// Oblicza przemieszczenie taboru +// ************************************************************************************************* +double physics::Vehicle::ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, TRotation const &NewRot) +{ + + if (!DamageFlag.HasAll(VehicleDamage::derailed)) + { // Ra: to przepisywanie tu jest bez sensu + RunningShape = Shape; + RunningTrack = Track; + RunningTraction = ElectricTraction; + + // if (!DynamicBrakeFlag) + // RunningTraction.TractionVoltage = ElectricTraction.TractionVoltage /*- + // abs(ElectricTraction.TractionResistivity * + // (Itot + HVCouplers[0][0] + HVCouplers[1][0]))*/; + // else + // RunningTraction.TractionVoltage = + // ElectricTraction.TractionVoltage /*- + // abs(ElectricTraction.TractionResistivity * Itot * + // 0)*/; // zasadniczo ED oporowe nie zmienia napięcia w sieci + } + else if (OffTrack.active()) + { + // off the track the grade is that of the ground under it, along its heading + RunningShape.dHtrack = Shape.dHtrack; + } + + if (CategoryFlag == 4) + offsetTrackV = totalMass / (Dim.L * Dim.W * 1000.0); + else if (TestFlag(CategoryFlag, 1) && TestFlag(RunningTrack.CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed)) + { + offsetTrackV = -0.2; + offsetTrackH = Sign(RunningShape.R) * 0.2; + } + + // TODO: investigate, seems supplied NewRot is always 0 although the code here suggests some actual values are expected + location = NewLoc; + Rot = NewRot; + + if (dL == 0) // oblicz przesuniecie} + { + auto const AccSprev{accS}; + // przyspieszenie styczne + accS = std::lerp(AccSprev, FTotal / totalMass, 0.5); + // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) + + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none && false == legacy_derailed_slides(*this)) + accS = -Sign(travelSpeed) * g * 1; // random(0.0, 0.1) + // stuck in the ballast: the friction holds a derailed vehicle once it stopped, until the forces on it are larger + auto const stuck{(derailOutcome != derailment::outcome::none || legacy_derailed_slides(*this)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + accS = 0.0; + + // przyspieszenie normalne + if (abs(Shape.R) > 0.01) + accN = square(travelSpeed) / Shape.R + g * Shape.dHrail / TrackW; // Q: zamieniam SQR() na sqr() + else + accN = g * Shape.dHrail / TrackW; + + // velocity change + auto const Vprev{travelSpeed}; + travelSpeed += (3.0 * accS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + travelSpeed = 0.0; + if (travelSpeed * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) + { + // tlumienie predkosci przy hamowaniu + // zahamowany + travelSpeed = 0; + } + + // tangential acceleration, from velocity change + accSVBased = std::lerp(accSVBased, (travelSpeed - Vprev) / dt, std::clamp(dt * 3.0, 0.0, 1.0)); + + // vertical acceleration + accVert = std::abs(accVert) < 0.01 ? 0.0 : accVert * 0.5; + // szarpanie + /* + #ifdef EU07_USE_FUZZYLOGIC + if( FuzzyLogic( ( 10.0 + Track.DamageFlag ) * emptyMass * Vel / vmax, 500000.0, p_accn ) ) { + // Ra: czemu tu masa bez ładunku? + AccV /= ( 2.0 * 0.95 + 2.0 * Random() * 0.1 ); // 95-105% of base modifier (2.0) + } + else + #endif + AccV = AccV / 2.0; + + if (AccV > 1.0) + accN += (7.0 - Random(5)) * (100.0 + Track.DamageFlag / 2.0) * AccV / 2000.0; + */ + // wykolejanie na luku oraz z braku szyn + if (TestFlag(CategoryFlag, 1)) + { + if (TestFlag(Track.DamageFlag, dtrack_norail)) + Derail(END_OF_TRACK); + // too fast in a curve: the legacy draw in every step (physics.derailment old), or the physical criteria + // once the step's distance is known, below + if ((Global.derailment == global_settings::derailment_model::old || Global.derailment == global_settings::derailment_model::monitor) && FuzzyLogic(accN / g * (1.0 + 0.1 * (Track.DamageFlag & dtrack_freerail)), TrackW / Dim.H, 1)) + Derail(TOO_HIGH_SPEED); + // wykolejanie na poszerzeniu toru + if (FuzzyLogic(abs(Track.Width - TrackW), TrackW / 10.0, 1)) + Derail(GAUGE_MISMATCH); + } + // wykolejanie wkutek niezgodnosci kategorii toru i pojazdu + if (!TestFlag(RunningTrack.CategoryFlag, CategoryFlag)) + Derail(WRONG_TRACK_TYPE); + + // dL:=(V+AccS*dt/2)*dt; + // przyrost dlugosci czyli przesuniecie + dL = (3.0 * travelSpeed - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha} + if (Global.derailment == global_settings::derailment_model::physical || Global.derailment == global_settings::derailment_model::monitor) + { + // over the distance of this step and of the simpler ones of the frame before it + check_derailment(Shape, Track, derailmentDistance + std::abs(dL)); + } + derailmentDistance = 0.0; + // ale jesli jest kolizja (zas. zach. pedu) to...} + for (auto const b : VehicleEnds) + if (Couplers[b].CheckCollision) + CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt, std::abs(dL)); + + } // liczone dL, predkosc i przyspieszenie + + auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu + dL)}; + + distCounter += fabs(dL) / 1000.0; + Odometer.run(dL); + dL = 0; + + // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze + compute_movement_(dt); + + // security system + SecuritySystemCheck(dt1); + + return d; +}; + +// ************************************************************************************************* +// Oblicza przemieszczenie taboru - uproszczona wersja +// ************************************************************************************************* + +double physics::Vehicle::FastComputeMovement(double dt, const TTrackShape & /*Shape*/, TTrackParam & /*Track*/, TLocation const &NewLoc, TRotation const &NewRot) +{ + // physics::Vehicle::FastComputeMovement(dt, Shape, Track, NewLoc, NewRot); + + location = NewLoc; + Rot = NewRot; + + if (dL == 0) // oblicz przesuniecie + { + auto const AccSprev{accS}; + // przyspieszenie styczne + accS = std::lerp(AccSprev, FTotal / totalMass, 0.5); + // std::clamp( dt * 3.0, 0.0, 1.0 ) ); // prawo Newtona ale z wygladzaniem (średnia z poprzednim) + + if (DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none && false == legacy_derailed_slides(*this)) + accS = -Sign(travelSpeed) * g * 1; // * random(0.0, 0.1) + auto const stuck{(derailOutcome != derailment::outcome::none || legacy_derailed_slides(*this)) && travelSpeed == 0.0 && std::abs(FTrain) <= std::abs(FStand)}; + if (stuck) + accS = 0.0; + + // simple mode skips calculation of normal acceleration + + // velocity change + auto const Vprev{travelSpeed}; + travelSpeed += (3.0 * accS - AccSprev) * dt / 2.0; // przyrost predkosci + if (stuck) + travelSpeed = 0.0; + if (travelSpeed * Vprev <= 0 && std::abs(FStand) > std::abs(FTrain)) + { + // tlumienie predkosci przy hamowaniu + // zahamowany + travelSpeed = 0; + } + + // simple mode skips calculation of tangential acceleration + + // simple mode skips calculation of vertical acceleration + accVert = 0.0; + + // a vehicle derailed by the physical criteria slides on with the friction of ComputeTotalForce(), and so does one + // derailed the legacy way with physics.collisions new + if (true == DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none && false == legacy_derailed_slides(*this) && Vel < 1.0) + { + travelSpeed = 0.0; + accS = 0.0; + } + + dL = (3.0 * travelSpeed - Vprev) * dt / 2.0; // metoda Adamsa-Bashfortha + // the criteria of derailment go by the distance, checked in the full step which ends the frame + derailmentDistance += std::abs(dL); + // ale jesli jest kolizja (zas. zach. pedu) to... + for (auto const b : VehicleEnds) + if (Couplers[b].CheckCollision) + CollisionDetect(b, dt); // zmienia niejawnie AccS, V !!! + check_pushed_off(dt, std::abs(dL)); + } // liczone dL, predkosc i przyspieszenie + + auto const d{(EngineType == TEngineType::WheelsDriven ? dL * CabActive : // na chwile dla testu + dL)}; + + distCounter += fabs(dL) / 1000.0; + Odometer.run(dL); + dL = 0; + + // koniec procedury, tu nastepuja dodatkowe procedury pomocnicze + compute_movement_(dt); + + return d; +}; + +// updates shared between 'fast' and regular movement computation methods +void physics::Vehicle::compute_movement_(double const Deltatime) +{ + + // sprawdzanie i ewentualnie wykonywanie->kasowanie poleceń + if (loadStatus > 0) // czas doliczamy tylko jeśli trwa (roz)ładowanie + LastLoadChangeTime += Deltatime; // czas (roz)ładunku + + RunInternalCommand(); + + // relay settings + // adjust motor overload relay threshold + if (EngineType == TEngineType::ElectricSeriesMotor && imaxHi > imaxLo) + { + if (motorOverloadRelayHighThreshold) + { // set high threshold + if (trainType != train_type::et42 ? RList[mainCtrlPos].Bn < 2 : mainCtrlPos == 0) + { + Imax = imaxHi; + } + } + else + { // set low threshold + if (trainType != train_type::et42 || mainCtrlPos == 0) + { + Imax = imaxLo; + } + } + } + + // Uproszczona symulacja wentylatorow rezystora hamowania + + // Prad oddawany na rezystor + + // Wlacz wentylator jesli prad rekuperacji przekroczy maksymalny dla pasywnego chlodzenia rezystora + if (double Irh = abs(inductionMotor.state.electricalPower) - abs(inductionMotor.state.lineCurrent); Irh > brakes.electrodynamic.resistorPassiveMaxCurrent && inductionMotor.state.lineCurrent < 0) + { + brakes.electrodynamic.resistorFansTimer = 0; + brakes.electrodynamic.resistorFansRunning = true; + } + else + { + brakes.electrodynamic.resistorFansTimer += Deltatime; + if (brakes.electrodynamic.resistorFansTimer > brakes.electrodynamic.resistorFansSustain) + brakes.electrodynamic.resistorFansRunning = false; + } + + // the master controller set directly, not through IncMainCtrl()/DecMainCtrl() (AI, consist): the locked shunt follows it as well + ScndCtrlResistiveLockCheck(); + // automatyczny rozruch, silnik spalinowy + if (Drive().UpdateEngine(*this, Deltatime)) + { + SetFlag(soundFlag, sound::relay); + } + + // TODO: gather and move current calculations to dedicated method + TotalCurrent = 0; + + // low voltage power sources + LowVoltagePowerCheck(Deltatime); + // power sources + PantographsCheck(Deltatime); + GensetCheck(Deltatime); + // main circuit + MainsCheck(Deltatime); + // traction motors + MotorBlowersCheck(Deltatime); + // uklady hamulcowe: + ConverterCheck(Deltatime); + air.UpdatePressure(); + if (air.config.mainReservoirVolume > 0.0) + { + // sprężarka musi mieć jakąś niezerową wydajność żeby rozważać jej załączenie i pracę + CompressorCheck(Deltatime); + } + if (Power > 1.0) + { + // w rozrządczym nie (jest błąd w FIZ!) - Ra 2014-07: teraz we wszystkich + UpdatePantVolume(Deltatime); // Ra 2014-07: obsługa zbiornika rozrządu oraz pantografów + } + // heating + HeatingCheck(Deltatime); + // lighting + LightsCheck(Deltatime); + + UpdateBrakePressure(Deltatime); + UpdatePipePressure(Deltatime); + UpdateBatteryVoltage(Deltatime); + UpdateScndPipePressure(Deltatime); // druga rurka, youBy + + if ((brakes.emuDynamic.checkedCoupler & 1) != 0 && Couplers[VehicleEnd::front].CouplingFlag.HasAny(Coupling::control)) + { + brakes.electrodynamic.emuWorking &= Couplers[VehicleEnd::front].Connected->brakes.electrodynamic.emuWorking; + } + if ((brakes.emuDynamic.checkedCoupler & 2) != 0 && Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)) + { + brakes.electrodynamic.emuWorking &= Couplers[VehicleEnd::rear].Connected->brakes.electrodynamic.emuWorking; + } + + if (brakes.antiSlipTimer > 0.8 && brakes.config.antiSlipType != 128) + { // ASBSpeed=0.8 + // hamulec antypoślizgowy - wyłączanie + brakes.distributor->ASB(0); + } + brakes.antiSlipTimer += Deltatime; + // automatic doors + update_doors(Deltatime); + + m_plc.update(Deltatime); + + PowerCouplersCheck(Deltatime, Coupling::highVoltage); + PowerCouplersCheck(Deltatime, Coupling::power110v); + PowerCouplersCheck(Deltatime, Coupling::power24v); + + lowVoltage.SetSupply(std::max(PowerCircuits[0].first, GetTrainsetVoltage(Coupling::power24v)), PowerCircuits[1].first > 0 || GetTrainsetVoltage(Coupling::power110v) > 0); +} + +// ************************************************************************************************* +// Q: 20160710 +// Siła napędzająca drezynę po naciśnięciu wajhy +// ************************************************************************************************* +bool physics::Vehicle::AddPulseForce(int Multipler) +{ + bool APF; + if (EngineType == TEngineType::WheelsDriven && EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + { + DirActive = CabActive; + DirAbsolute = DirActive * CabActive; + if (Vel > 0) + PulseForce = std::min(1000.0 * Power / (abs(travelSpeed) + 0.1), Ftmax); + else + PulseForce = Ftmax; + if (PulseForceCount > 1000.0) + PulseForce = 0; + else + PulseForce = PulseForce * Multipler; + PulseForceCount = PulseForceCount + abs(Multipler); + APF = PulseForce > 0; + } + else + APF = false; + return APF; +} + +// ************************************************************************************************* +// yB: 20190909 +// sypanie piasku reczne +// ************************************************************************************************* +bool physics::Vehicle::SandboxManual(bool const State, range_t const Notify) +{ + bool result{false}; + + if (SandDoseManual != State) + { + if (SandDoseManual == false) + { + // switch on + if (Sand > 0) + { + SandDoseManual = true; + result = true; + } + } + else + { + // switch off + SandDoseManual = false; + result = true; + } + } + + Sandbox(SandDoseManual || SandDoseAuto, Notify); + + return result; +} + +// ************************************************************************************************* +// yB: 20190909 +// sypanie piasku automatyczne +// ************************************************************************************************* +bool physics::Vehicle::SandboxAuto(bool const State, range_t const Notify) +{ + bool result{false}; + if (bool NewState = State && SandDoseAutoAllow; SandDoseAuto != NewState) + { + if (SandDoseAuto == false) + { + // switch on + if (Sand > 0) + { + SandDoseAuto = true; + result = true; + } + } + else + { + // switch off + SandDoseAuto = false; + result = true; + } + } + + Sandbox(SandDoseManual || SandDoseAuto, Notify); + + return result; +} + +// ************************************************************************************************* +// Q: 20160713 +// sypanie piasku +// ************************************************************************************************* +bool physics::Vehicle::Sandbox(bool const State, range_t const Notify) +{ + bool result{false}; + + if (sandDose != State) + { + if (sandDose == false) + { + // switch on + if (Sand > 0 && DirActive != 0) + { + sandDose = true; + result = true; + } + } + else + { + // switch off + sandDose = false; + result = true; + } + } + + if (Notify != range_t::local) + { + // if requested pass the command on + auto const couplingtype = Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control; + + if (State == true) + { + // switch on + SendCtrlToNext(VehicleCommand::sandbox, 1, CabActive, couplingtype); + } + else + { + // switch off + SendCtrlToNext(VehicleCommand::sandbox, 0, CabActive, couplingtype); + } + } + + return result; +} + +// ************************************************************************************************* +// yB: 20190909 +// włączenie / wyłączenie automatycznej piasecznicy +// ************************************************************************************************* +bool physics::Vehicle::SandboxAutoAllow(bool State) +{ + // SendCtrlToNext(VehicleCommand::sandboxAutoAllow, int(State), CabActive, Coupling::control); + + if (SandDoseAutoAllow != State) + { + SandDoseAutoAllow = State; + return true; + } + else + return false; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczenie stałych potrzebnych do dalszych obliczeń +// ************************************************************************************************* +void physics::Vehicle::ComputeConstans(void) +{ + double BearingF; + double RollF; + double HideModifier; + double Curvature; // Ra 2014-07: odwrotność promienia + + TotalMassxg = totalMass * g; // TotalMass*g + BearingF = DamageFlag.HasAny(VehicleDamage::bearing) ? 2.0 : 0; + + HideModifier = 0; // int(Couplers[0].CouplingFlag>0)+int(Couplers[1].CouplingFlag>0); + + if (BearingType == 0) + RollF = 0.05; // slizgowe + else + RollF = 0.015; // toczne + RollF += BearingF / 200.0; + + // if (NPoweredAxles > 0) + // RollF = RollF * 1.5; //dodatkowe lozyska silnikow + + if (nPoweredAxles > 0) // drobna optymalka + { + RollF += 0.025; + // if (Ft * Ft < 1) + // HideModifier = HideModifier - 3; + } + Ff = TotalMassxg * (BearingF + RollF * travelSpeed * travelSpeed / 10.0) / 1000.0; + // dorobic liczenie temperatury lozyska! + FrictConst1 = TotalMassxg * RollF / 10000.0; + // drag calculation + { + // NOTE: draft effect of previous vehicle is simplified and doesn't have much to do with reality + auto const *previousvehicle{Couplers[travelSpeed >= 0.0 ? VehicleEnd::front : VehicleEnd::rear].Connected}; + auto dragarea{Dim.W * Dim.H}; + if (previousvehicle) + { + dragarea = std::max(0.0, dragarea - 0.85 * previousvehicle->Dim.W * previousvehicle->Dim.H); + } + FrictConst1 += Cx * dragarea; + } + + if (CategoryFlag & 1) + { + Curvature = RunningShape.R == 0.0 ? // zero oznacza nieskończony promień + 0.0 : + 1.0 / std::abs(RunningShape.R); + } + else + { + // vehicles other than trains don't experience friction against the rail on curves + Curvature = 0.0; + } + // opór składu na łuku (youBy): +(500*TrackW/R)*TotalMassxg*0.001 do FrictConst2s/d + FrictConst2s = TotalMassxg * (500.0 * TrackW * Curvature + 2.5 - HideModifier + 2 * BearingF / 4.0) * 0.001; + FrictConst2d = TotalMassxg * (500.0 * TrackW * Curvature + 2.0 - HideModifier + BearingF / 4.0) * 0.001; +} + +// ************************************************************************************************* +// Q: 20160713 +// Oblicza masę ładunku +// ************************************************************************************************* +void physics::Vehicle::ComputeMass() +{ + // Ra: na razie tak, ale nie wszędzie masy wirujące się wliczają + totalMass = emptyMass + mred; + + if (loadAmount == 0) + { + return; + } + + // include weight of carried load + auto loadtypeunitweight{0.f}; + + if (ToLower(LoadQuantity) == "tonns") + { + loadtypeunitweight = 1000; + } + else + { + auto const lookup{simulation::Weights.find(LoadType.name)}; + loadtypeunitweight = lookup != simulation::Weights.end() ? lookup->second : 1000.f; // legacy default unit weight value + } + + totalMass += loadAmount * loadtypeunitweight; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczanie wypadkowej siły z wszystkich działających sił +// ************************************************************************************************* +// TBD, TODO: move some of the calculations out of the method, they're relevant to more than just force calculations +void physics::Vehicle::ComputeTotalForce(double dt) +{ + + Vel = std::abs(travelSpeed) * 3.6; // prędkość w km/h + + // McZapkie-031103: sprawdzanie czy warto liczyc fizyke i inne updaty + // ABu 300105: cos tu mieszalem , dziala teraz troche lepiej, wiec zostawiam + { + // asleep, the brake force is the one of the step it fell asleep in: a vehicle whose brakes have changed since, released + // or applied, wakes for the 5 s of LastSwitchingTime, which take the new force into FStand, and sleeps again if it's + // still held. none of the causes of the test below, so as "other" + if (brakes_changed_asleep()) + switch_physics(true, wake_cause::other); + + auto const vehicleisactive{CabActive != 0 || Vel > 0.0001 || accelerating() || LastSwitchingTime < 5 || is_multiple_unit()}; + + auto const movingvehicleahead{Neighbours[VehicleEnd::front].vehicle != nullptr && + (Neighbours[VehicleEnd::front].vehicle->physics->Vel > 0.0001 || Neighbours[VehicleEnd::front].vehicle->physics->accelerating())}; + + auto const movingvehiclebehind{Neighbours[VehicleEnd::rear].vehicle != nullptr && + (Neighbours[VehicleEnd::rear].vehicle->physics->Vel > 0.0001 || Neighbours[VehicleEnd::rear].vehicle->physics->accelerating())}; + + auto const calculatephysics{vehicleisactive || movingvehicleahead || movingvehiclebehind}; + + switch_physics(calculatephysics, Vel > 0.0001 ? wake_cause::speed : + accelerating() ? wake_cause::acceleration : + vehicleisactive ? wake_cause::rest : + wake_cause::neighbour); + } + + if (false == physicActivation) + { + return; + } + + // juz zoptymalizowane: + FStand = FrictionForce(); // siła oporów ruchu + if (true == DamageFlag.HasAll(VehicleDamage::derailed)) + { + if (derailOutcome != derailment::outcome::none) + { + // off the rails by the physical criteria: the vehicle slides on the sleepers and the ballast, or on its side; + // off the track on the ground, as far as it tipped over (physics.derailment new) + auto const friction{OffTrack.active() ? OffTrack.friction() : derailment::sliding_friction(derailOutcome)}; + FStand = friction * (totalMass - mred) * g; + } + else if (legacy_derailed_slides(*this)) + { + // derailed the legacy way with physics.collisions new: the deceleration of g of the legacy model, as a friction + FStand = totalMass * g; + } + else + { + // HACK: crude way to reduce speed after derailment + // TBD, TODO: more accurate approach? + FStand *= 1e20; + } + } + double old_nrot = abs(nrotValue); + nrotValue = v2n(); // przeliczenie prędkości liniowej na obrotową + + if (true == TestFlag(brakes.config.method, bp_MHS) && brakePipe.Pressure() < 3.0 // ustawione na sztywno na 3 bar + && Vel > 45 && true == TestFlag(brakes.delaySetting, bdelay_M)) + { + // doliczenie hamowania hamulcem szynowym + FStand += brakes.config.trackBrakeForce; + } + // w charakterystykach jest wartość siły hamowania zamiast nacisku + + LastSwitchingTime += dt; + Drive().UpdateEngineVoltage(*this, dt); + + FTrain = Power > 0 ? TractionForce(dt) : 0; + double FT_factor = 1.0; + if (EngineType == TEngineType::ElectricInductionMotor && inductionMotor.inverterRatio > 0.0) + { + FT_factor = 1.0 / inductionMotor.inverterRatio; + FTrain *= FT_factor; + } + + brakingForce = BrakeForce(RunningTrack); + // poslizg + auto Fwheels{FTrain - brakingForce * Sign(travelSpeed)}; + if (Vel > 0.1 // crude trap, to prevent braked stationary vehicles from passing fb > mass * adhesive test + && std::abs(Fwheels) > TotalMassxg * Adhesive(RunningTrack.friction)) + { + slippingWheels = true; + } + if (true == slippingWheels && Vel < 0.1 // the same crude trap: (nearly) stopped vehicle... + && std::abs(nrotValue * M_PI * wheelDiameter - travelSpeed) < 0.1 / 3.6) // ...with wheels turning at its speed, i.e. locked wheels at the end of a skid + { + // locked wheels never pass the rotation speed test below once the vehicle stops, and a skidding vehicle + // keeps its braking force capped by the sliding adhesion, so the rest of the consist could push it around + slippingWheels = false; + nrotValue = travelSpeed / M_PI / wheelDiameter; + } + double temp_nrot = nrotValue; + if (true == slippingWheels) + { + + temp_nrot = ComputeRotatingWheel(Fwheels - Sign(nrotValue * M_PI * wheelDiameter - travelSpeed) * Adhesive(RunningTrack.friction) * TotalMassxg, dt, nrotValue); + if (Sign(nrotValue * M_PI * wheelDiameter - travelSpeed) * Sign(temp_nrot * M_PI * wheelDiameter - travelSpeed) < 0) + { + slippingWheels = false; + temp_nrot = travelSpeed / M_PI / wheelDiameter; + } + } + if (true == slippingWheels) + { + Fwheels = Sign(temp_nrot * M_PI * wheelDiameter - travelSpeed) * TotalMassxg * Adhesive(RunningTrack.friction); + if (Fwheels * Sign(travelSpeed) > 0) + { + FTrain = Fwheels + brakingForce * Sign(travelSpeed); + } + else if (FTrain * Sign(travelSpeed) > 0) + { + brakingForce = FTrain * Sign(travelSpeed) - Fwheels * Sign(travelSpeed); + } + else + { + double factor = FTrain - brakingForce * Sign(travelSpeed) != 0 ? Fwheels / (FTrain - brakingForce * Sign(travelSpeed)) : 1.0; + brakingForce *= factor; + FTrain *= factor; + } + if (std::abs(nrotValue) < 0.1) + { + wheelFlat = sqrt(square(wheelFlat) + abs(Fwheels) / nAxles * Vel * 0.000002); + } + + nrotValue = temp_nrot; + } + nrot_eps = (abs(nrotValue) - old_nrot) / dt; + // doliczenie sił z innych pojazdów + for (auto const end : VehicleEnds) + { + // a new step: the hit of the pair not taken by either vehicle yet + Couplers[end].hit_handled = false; + Couplers[end].hit_force = 0.0; + Couplers[end].hit_duration = 0.0; + Couplers[end].closing = 0.0; + if (Neighbours[end].vehicle != nullptr) + { + // the velocities before the step, the forces of all the vehicles come before their movement + Couplers[end].closing = -CouplerVelocityDifference(end, *Neighbours[end].vehicle->physics, Neighbours[end].FacingEnd()) * DirF(end); + Couplers[end].CForce = CouplerForce(end, dt); + // off the track (physics.derailment new) the vehicles are apart in another direction than along the axis of + // this one: of the force between them, along it the share the gap goes by, which for ends gone past each + // other is the other way. the force as a whole stays in CForce, for the motion off the track + FTrain += Couplers[end].CForce * (Neighbours[end].off_track ? coupler_gap_change(end, 1.0, 0.0) * DirF(end) : 1.0); + // what the buffers of the pair take in, for the budget of the crush (physics.collisions new and monitor) + auto &coupler{Couplers[end]}; + coupler.contact.update(coupler.Dist < 0.0, coupler.CheckCollision, coupler.closing, compression_at(coupler, end), std::max(0.0, -coupler.Dist), dt); + } + else + { + Couplers[end].CForce = 0; + Couplers[end].contact.reset(); + } + } + + FStand += brakingForce; + // doliczenie składowej stycznej grawitacji + FTrain /= FT_factor; + FTrain += TotalMassxg * RunningShape.dHtrack; + //! niejawne przypisanie zmiennej! + FTotal = FTrain - Sign(travelSpeed) * FStand; +} + +double physics::Vehicle::BrakeForceR(double ratio, double velocity) const +{ + double press = 0; + ratio = brakes.distributor->GetBrakeRatio(ratio); + if (brakes.config.maxPressureMass > 2) + { + press = brakes.config.maxCylinderPressure[1] + (brakes.config.maxCylinderPressure[3] - brakes.config.maxCylinderPressure[1]) * std::min(1.0, (totalMass - emptyMass) / (brakes.config.maxPressureMass - emptyMass)); + } + else + { + if (brakes.config.maxCylinderPressure[1] > 0.1) + { + press = brakes.config.maxCylinderPressure[brakes.loadSetting]; + } + else + { + press = brakes.config.maxCylinderPressure[3]; + if (brakes.electrodynamic.type == dbrake_automatic) + ratio = ratio + (1.5 - ratio) * std::min(1.0, Vel * 0.02); + if (brakes.delaySetting & bdelay_R && brakes.config.method % 128 != bp_Cosid && brakes.config.method % 128 != bp_D1 && brakes.config.method % 128 != bp_D2 && Power < 1) + ratio *= brakes.distributor->GetRapidRatio(velocity); + if (trainType == train_type::dmu && velocity < 30.0) + { + ratio -= 0.3; + } + } + } + return BrakeForceP(press * ratio, velocity); +} + +double physics::Vehicle::BrakeForceP(double press, double velocity) const +{ + double BFP = 0; + double K = ((press * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce) * brakes.config.cylinders.riggingEfficiency; + K *= static_cast(brakes.config.cylinders.count) / (nAxles * std::max(1, brakes.config.blocksPerAxle)); + BFP = brakes.distributor->GetFC(velocity, K) * K * (nAxles * std::max(1, brakes.config.blocksPerAxle)) * 1000; + return BFP; +} + +// ************************************************************************************************* +// Q: 20160713 +// oblicza siłę na styku koła i szyny +// ************************************************************************************************* +double physics::Vehicle::BrakeForce(TTrackParam const & /*Track*/) +{ + + double K{0}; + double brakeforce{0}; + + switch (brakes.config.localKind) + { + case TLocalBrake::ManualBrake: + { + K = brakes.config.maxForce * ManualBrakeRatio(); + break; + } + case TLocalBrake::HydraulicBrake: + { + K = brakes.config.maxForce * LocalBrakeRatio(); + break; + } + default: + { + break; + } + } + + if (brakes.config.hasHandBrake == true) + { + K = brakes.config.maxForce * ManualBrakeRatio(); + } + + // the spring brake of a vehicle prepared for hauling (PulleeMode) is released by hand: no force, whatever its cylinder has + if (brakes.spring.isReady && false == pulleeMode) + K += std::max(0.0, brakes.spring.minForcePressure - brakes.spring.cylinder->P()) * brakes.spring.maxForce; + + u = (brakes.cylinderPressure * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce; + if (u * brakes.config.cylinders.riggingEfficiency > Ntotal) // histereza na nacisku klockow + Ntotal = u * brakes.config.cylinders.riggingEfficiency; + else + { + u = (brakes.cylinderPressure * brakes.config.pressureToForce - brakes.config.cylinders.springForce) * brakes.config.cylinders.leverRatio[0] - brakes.config.cylinders.slackAdjusterForce; + if (u * (2.0 - brakes.config.cylinders.riggingEfficiency) < Ntotal) // histereza na nacisku klockow + Ntotal = u * (2.0 - brakes.config.cylinders.riggingEfficiency); + } + + auto const NBrakeAxles{nAxles}; + + if (NBrakeAxles * brakes.config.blocksPerAxle > 0) + { + if (Ntotal > 0) // nie luz + K += Ntotal; // w kN + K *= static_cast(brakes.config.cylinders.count) / (NBrakeAxles * static_cast(brakes.config.blocksPerAxle)); // w kN na os + } + if (brakes.config.kind == TBrakeSystem::Pneumatic || brakes.config.kind == TBrakeSystem::ElectroPneumatic) + { + u = brakes.distributor->GetFC(Vel, K); + brakes.unitForce = u * K * 1000.0; // sila na jeden klocek w N + } + else + brakes.unitForce = K * 1000.0; + // if (LocalBrake=ManualBrake)or(MBrake=true)) and (BrakePress<0.3) then + // Fb:=UnitBrakeForce*NBpA {ham. reczny dziala na jedna os} + // else //yB: to nie do konca ma sens, ponieważ ręczny w wagonie działa na jeden cylinder + // hamulcowy/wózek, dlatego potrzebne są oddzielnie liczone osie + brakeforce = brakes.unitForce * NBrakeAxles * std::max(1, brakes.config.blocksPerAxle); + + // u:=((BrakePress*P2FTrans)-BrakeCylSpring*BrakeCylMult[BCMFlag]/BrakeCylNo-0.83*BrakeSlckAdj/(BrakeCylNo))*BrakeCylNo; + // { end; } + return brakeforce; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczanie siły tarcia +// ************************************************************************************************* +double physics::Vehicle::FrictionForce() const +{ + double FF = 0; + // ABu 240205: chyba juz ekstremalnie zoptymalizowana funkcja liczaca sily tarcia + if (abs(travelSpeed) > 0.01) + FF = FrictConst1 * travelSpeed * travelSpeed + FrictConst2d; + else + FF = FrictConst1 * travelSpeed * travelSpeed + FrictConst2s; + return FF; +} + +// ************************************************************************************************* +// Q: 20160713 +// Oblicza przyczepność +// ************************************************************************************************* +double physics::Vehicle::Adhesive(double staticfriction) const +{ + double adhesion = 0.0; + const double adh_factor = 0.25; // współczynnik określający, jak bardzo spada tarcie przy poślizgu + const double slipfactor = 0.33; // współczynnik określający, jak szybko spada tarcie przy poślizgu + const double sandfactor = 1.25; // współczynnik określający, jak mocno pomaga piasek + /* + // ABu: male przerobki, tylko czy to da jakikolwiek skutek w FPS? + // w kazdym razie zaciemni kod na pewno :) + if (slippingWheels == false) + { + if (sandDose) + adhesion = (std::max(staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 11.0), 0.048)) * + (11.0 - 2.0 * Random(0.0, 1.0)); + else + adhesion = (staticfriction * (100.0 + Vel) / ((50.0 + Vel) * 10.0)) * + (11.0 - 2.0 * Random(0.0, 1.0)); + } + else + { + if (sandDose) + adhesion = (0.048) * (11.0 - 2.0 * Random(0.0, 1.0)); + else + adhesion = (staticfriction * 0.02) * (11.0 - 2.0 * Random(0.0, 1.0)); + } + // WriteLog(FloatToStr(adhesive)); // tutaj jest na poziomie 0.2 - 0.3 + return adhesion; + + //wersja druga + if( true == slippingWheels ) { + + if( true == sandDose ) { adhesion = 0.48; } + else { adhesion = staticfriction * 0.2; } + } + else { + + if( true == sandDose ) { adhesion = std::max( staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ) * 1.1, 0.48 ); } + else { adhesion = staticfriction * ( 100.0 + Vel ) / ( 50.0 + Vel ); } + } + // adhesion *= ( 0.9 + 0.2 * Random() ); + */ + // wersja3 by youBy - uwzględnia naturalne mikropoślizgi i wpływ piasecznicy, usuwa losowość z pojazdu + double Vwheels = nrotValue * M_PI * wheelDiameter; // predkosc liniowa koła wynikająca z obrotowej + double deltaV = travelSpeed - Vwheels; // poślizg - różnica prędkości w punkcie styku koła i szyny + deltaV = std::max(0.0, std::abs(deltaV) - 0.25); // mikropoślizgi do ok. 0,25 m/s nie zrywają przyczepności + Vwheels = std::abs(Vwheels); + adhesion = staticfriction * (28 + Vwheels) / (14 + Vwheels) * ((sandDose ? sandfactor : 1) - (1 - adh_factor) * (deltaV / (deltaV + slipfactor))); + + return adhesion; +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczenie predkości obrotowej kół??? +// ************************************************************************************************* +double physics::Vehicle::ComputeRotatingWheel(double WForce, double dt, double n) const +{ + double newn = 0; + double eps = 0; + if (n == 0 && WForce * Sign(travelSpeed) < 0) + newn = 0; + else + { + eps = WForce * wheelDiameter / (2.0 * AxleInertialMoment); + newn = n + eps * dt; + if (newn * n <= 0 && eps * n < 0) + newn = 0; + } + return newn; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przesuwa pojazd o podaną wartość w bok względem toru (dla samochodów) +// ************************************************************************************************* +bool physics::Vehicle::ChangeOffsetH(double DeltaOffset) +{ + bool COH = false; + if (TestFlag(CategoryFlag, 2) && TestFlag(RunningTrack.CategoryFlag, 2)) + { + offsetTrackH = offsetTrackH + DeltaOffset; + // if (abs(OffsetTrackH) > (RunningTrack.Width / 1.95 - TrackW / 2.0)) + if (abs(offsetTrackH) > 0.5 * (RunningTrack.Width - Dim.W) - 0.05) // Ra: może pół pojazdu od brzegu? + COH = false; // kola na granicy drogi + else + COH = true; + } + else + COH = false; + + return COH; +} + +// ************************************************************************************************* +// Q: 20160713 +// Testuje zmienną (narazie tylko 0) i na podstawie uszkodzenia zwraca informację tekstową +// ************************************************************************************************* +std::string physics::Vehicle::EngineDescription(int what) const +{ + std::string outstr{"OK"}; + if (what == 0) + { + if (DamageFlag == DamageSet::FromBits(255)) // every damage but the pantograph + { + outstr = "WRECKED"; + } + else + { + if (DamageFlag.HasAll(VehicleDamage::thinWheel)) + { + if (Power > 0.1) + outstr = "Thin wheel"; + else + outstr = "Load shifted"; + } + if (wheelFlat > 5.0 || DamageFlag.HasAll(VehicleDamage::wheelWear)) + { + outstr = "Wheel wear"; + } + if (DamageFlag.HasAll(VehicleDamage::bearing)) + { + outstr = "Bearing damaged"; + } + if (DamageFlag.HasAll(VehicleDamage::coupling)) + { + outstr = "Coupler broken"; + } + if (DamageFlag.HasAll(VehicleDamage::loadDamage)) + { + if (Power > 0.1) + outstr = "Ventilator damaged"; + else + outstr = "Load damaged"; + } + if (DamageFlag.HasAll(VehicleDamage::loadDestroyed)) + { + if (Power > 0.1) + outstr = "Engine damaged"; + else + outstr = "LOAD DESTROYED"; + } + if (DamageFlag.HasAll(VehicleDamage::axle)) + { + outstr = "Axle broken"; + } + if (DamageFlag.HasAll(VehicleDamage::derailed)) + { + outstr = "DERAILED"; + } + } + } + else + { + outstr = "Invalid qualifier"; + } + return outstr; +} + +// ************************************************************************************************* +// whether the vehicle accelerates, for the test which turns the physics off in vehicles standing still +// ************************************************************************************************* +bool physics::Vehicle::accelerating() const +{ + if (std::abs(accS) <= 0.0001) + return false; + // standing still and held by the brakes and the resistance, against the slope and the couplers: the test ComputeMovement() + // sets the speed to zero by. the forces are of the last ComputeTotalForce(), the ones the movement went by. a vehicle whose + // brake cylinders still fill or release isn't held yet: asleep, it would keep the brake force (and the pressure the AI waits on + // to set off) it had when it fell asleep. 0.05 bar/s is less than a distributor moves the cylinder when it applies or releases, and + // more than the leaks take + auto const held{Global.physics_sleepheld && Vel <= 0.0001 && std::abs(FStand) > std::abs(FTrain) && brakes.cylinderPressureRate <= 0.05}; + return false == held; +} + +void physics::Vehicle::wake_for_brake() +{ + if (Global.physics_sleepheld) + { + switch_physics(true, wake_cause::command); + } +} + +// ************************************************************************************************* +// whether the brakes of a vehicle whose physics sleeps have changed since it fell asleep: the pressure in the brake cylinders +// or in the one of the spring brake by more than 0.05 bar, the hand brake by a notch, or the local brake by 1 percent. the brake system +// itself steps on while asleep in the vehicle the user is in (TDynamicObject::Update(), MechInside); the settings change by +// hand or by a command in any vehicle. 0.05 bar is less than what a distributor applying or releasing moves the cylinder by in +// a second, and much less than the pressure the cylinder's return spring takes (BrakeCylSpring, some tenths of a bar), below +// which the cylinder gives no force: a release ends with the vehicle asleep and no force left. a cylinder holding its +// pressure, or settling within that, leaves the vehicle asleep +// ************************************************************************************************* +bool physics::Vehicle::brakes_changed_asleep() const +{ + if (physicActivation) + return false; + constexpr double pressure_change{0.05}; // [bar] + return std::abs(brakes.cylinderPressure - sleep_brakes.cylinder) > pressure_change || std::abs(brakes.spring.pressure - sleep_brakes.spring) > pressure_change || + brakes.HandBrakePosition() != sleep_brakes.manual || std::abs(brakes.IndependentPosition() - sleep_brakes.local) > 0.01; +} + +// ************************************************************************************************* +// Kasowanie zmiennych pracy fizyki +// ************************************************************************************************* +bool physics::Vehicle::switch_physics(bool const State, wake_cause const Cause) // DO PRZETLUMACZENIA NA KONCU +{ + if (physicActivation == State) + { + return false; + } + + physicActivation = State; + if (true == State) + { + LastSwitchingTime = 0; + Timer::subsystem.switching.note(static_cast(Timer::switching_counter::wake + static_cast(Cause)), this, &TypeName, &Name); + } + else + { + // what the brake force of the last step came from, which it keeps while asleep (brakes_changed_asleep()) + sleep_brakes = {brakes.cylinderPressure, brakes.spring.pressure, brakes.HandBrakePosition(), brakes.IndependentPosition()}; + } + + return true; +} + +namespace simulation +{ + +weights_table Weights; + +} // namespace simulation + +void physics::Vehicle::SetEquipmentFaults(EquipmentFaultSet const Faults) +{ + if (Faults.HasAll(EquipmentFault::differentialRelay)) // różnicówka nie robi nic + { + MainSwitch(false); + FuseOff(); + } + // the faults of the control and of the camshaft hold the start, or the steps of the controller, by delays that never + // pass: the delays of the definition moved out of reach, and back when the fault clears + constexpr double faultoffset{100000001}; + constexpr double faultthreshold{100000000}; + if (Faults.HasAll(EquipmentFault::control)) // usterka sterowania + { + lineContactors.Open(); + if (initialCtrlDelay < faultthreshold) + initialCtrlDelay += faultoffset; + } + else if (initialCtrlDelay > faultthreshold) + { + initialCtrlDelay -= faultoffset; + } + if (Faults.HasAll(EquipmentFault::converter) && converter.config.start != start_t::disabled) // blokada przetwornicy + { + converter.Overload(); + } + air.compressor.SetFault(Faults.HasAll(EquipmentFault::compressor)); // blokada sprezarki + if (Faults.HasAll(EquipmentFault::camshaft)) // blokada wału + { + if (CtrlDelay < faultthreshold) + CtrlDelay += faultoffset; + if (CtrlDownDelay < faultthreshold) + CtrlDownDelay += faultoffset; + } + else + { + if (CtrlDelay > faultthreshold) + CtrlDelay -= faultoffset; + if (CtrlDownDelay > faultthreshold) + CtrlDownDelay -= faultoffset; + } + // hamowanie nagłe (emergencyBrake): nothing yet + equipmentFaults = Faults; +} + +void physics::Vehicle::ClearAIFlag(int const Flag) +{ + ClearFlag(aiFlag, Flag); +} diff --git a/physics/components/braking.h b/physics/components/braking.h new file mode 100644 index 000000000..a767be94f --- /dev/null +++ b/physics/components/braking.h @@ -0,0 +1,267 @@ +/* +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 braking of a vehicle: its brake valves and cylinders, the handles of the driver, the blending of the brakes of a +// unit, the holding brake, the spring brake. Held by physics::Vehicle as brakes + +#pragma once + +#include +#include +#include + +#include "physics/vehicletypes.h" + +class TReservoir; +class TBrake; +class TDriverHandle; + +namespace physics +{ + +// the blending of the electro-pneumatic and the electrodynamic brake of a unit (MED, the Blending section of the .fiz) +struct BrakeBlending +{ + double maxSpeed = 0; // MED_Vmax: the top speed the momentary force of the EP brake is computed for [km/h] + double minSpeed = 0; // MED_Vmin: the lowest speed the momentary force of the EP brake is computed for [km/h] + double referenceSpeed = 0; // MED_Vref: the speed the available force of the EP brake is computed for [km/h] + double maxDeceleration{9.81}; // MED_amax: the most deceleration of the service braking [m/s2] + bool epCorrection = false; // MED_EPVC: the force of the EP brake corrected while the ED brake is unavailable + double epCorrectionTime = 7; // MED_EPVC_Time: how long that correction lasts [s] + bool loadCorrection = false; // MED_Ncor: the braking force corrected by the load on the axles + double minEdDemand = 0; // MED_MinBrakeReqED: below this demand only the EP brake brakes, the ED brake stays off + double edForceFactor = 1; // MED_FrEDFactor: the factor of the force of the ED brake, to correct the blending + double edFirstDelay = 0; // MED_FirstDelayED: the delay of the ED brake coming in, the first time [s] + double edNextDelay = 0; // MED_ScndDelayED: the delay of the ED brake growing, the times after [s] + // the state + double epCorrectionTimer = 0; // how long the force of the EP brake has been corrected [s] + double edDelayTimer = 0; // the count of the delay of the ED brake [s] +}; + +// the electrodynamic brake of a DC unit and the EP brake beside it (the DCEMUED section of the .fiz) +struct EmuDynamicBrake +{ + int checkedCoupler{0}; // CouplerCheck: the coupler the ED brake of the unit is checked on + double epMaxSpeed{0.0}; // EP_max_Vel: the top speed the EP brake works at with the ED brake of the unit on (trailers) + double epMinCurrent{0.0}; // EP_min_Im: the current the EP brake stops working at with the ED brake of the car on (motor cars) + double epDelay{0.0}; // EP_delay: the delay of the EP brake coming in while the ED brake brakes +}; + +// the holding brake of a unit with the MED: it holds the unit standing, and lets go once power is demanded +struct HoldingBrake +{ + double deceleration = 0.0; // SBD: the deceleration it holds the unit with [m/s2] + // SBDReleaseDelay: it lets go only once power has been demanded for this long [s]; 0 lets it go at the first demand + double releaseDelay = 0.0; + double releaseTimer = 0.0; // how long power has been demanded without a break [s] +}; + +// the spring brake: the spring of its cylinder brakes when the air leaves it (the SpringBrake section of the .fiz) +struct SpringBrake +{ + std::shared_ptr cylinder; + // the inputs + bool activate{false}; // switched on or off in service: the main valve or switch + bool shutOff{true}; // shut off for a fault: the valve in the pneumatic container + bool release{false}; // the emergency release rod + // the outputs + bool isReady{false}; // ready to brake: the cylinder armed, the spring tensioned + bool isActive{false}; // braking + double pressure{0.0}; // the pressure in the cylinder + // the configuration + bool pneumaticConnection{false}; // connected to the cylinders of the air brake + double maxSetPressure{0.0}; // MaxSP: the most pressure for the brake switched off + double resetPressure{0.0}; // ResetP: the pressure that arms the cylinder + double minForcePressure{0.1}; // MinFP: the least pressure of no force + double maxForce{0.0}; // MBF: the most force of the spring on the brake shoes or pads + double pressureOn{-2.0}; // PressOn: the pressure the brake turns on at + double pressureOff{-1.0}; // PressOff: the pressure the brake turns off at + double valveOffArea{0.0}; // the area of the filling valve (read from the key ValveOnArea) + double valveOnArea{0.0}; // the area of the dumping valve (read from the key ValveOffArea) + double valvePneumaticArea{0.0}; // ValvePNBArea: the area of the bypass to the cylinders of the air brake + int controlCouplings{127}; // MTC: the couplings the command needs to pass on, the number of the couplings of the .fiz + // of the vehicle with it + bool releasesParking{false}; // ReleaseParkingBySpringBrake + bool releasesParkingWithDoorOpen{false}; // ReleaseParkingBySpringBrakeWhenDoorIsOpen + bool cutsOffDrive{true}; // SpringBrakeCutsOffDrive + double driveEmergencySpeed{-1}; // SpringBrakeDriveEmergencyVel +}; + +// the braking of a vehicle beside its air brake valves +// the electrodynamic brake of the traction motors and its resistors +struct ElectrodynamicBrake +{ + int type = 0; // dbrake_* + int ammeters = 2; // the ammeters it shows on + bool splitFromPneumatic = false; // its controller is apart from the one of the independent air brake + int controllerPositions = 10; // DBPN: the positions of its controller + double controllerPosition = 0.0; // the position of its controller, 0..1, with splitFromPneumatic only + double resistance = 5.8; // of the braking resistors + double resistance1 = 5.8; // of the first mode + double resistance2 = 5.8; // of the second mode + bool on = false; // braking + bool emuWorking = true; // it works, in a multiple unit + bool resistorFansRunning = false; // the fans of the braking resistor + int resistorFansSustain = 0; // how long the fans still cool the resistor after it stops [s] + double resistorFansTimer = 0; // the timer of that + int resistorPassiveMaxCurrent = 0; // the most current of the resistor cooled passively +}; + +// the settings of the driver's brake valve (the Handle_* keys of the .fiz) +struct DriverValveSettings +{ + bool automaticOverload = false; // the overcharge is let in automatically at the filling position + bool manualOverload = false; // the overcharge is let in by a button + double genericParameter1 = 0.0; + double genericParameter2 = 0.0; + double overloadMaxPressure = 1.0; // the most the overcharge raises the pressure + double overloadPressureDecrease = 0.002; // how fast the pressure of the overcharge falls +}; + +// the brake cylinders of a vehicle and their rigging +struct BrakeCylinders +{ + int count = 0; + double radius = 0.0; + double stroke = 0.0; + std::array leverRatio{}; // the ratio of the brake rigging, by the load setting + double springForce = 0.0; // the sum of the forces of the return springs [kN] + double slackAdjusterForce = 0.0; // the resistance of the slack adjuster [kN] + double riggingEfficiency = 0.0; // the efficiency of the lever rigging +}; + +// the emergency valve, which lets the air out of the main reservoir above its pressure +struct EmergencyValve +{ + double onPressure = 0.0; // MaxEVP: it opens above this pressure of the main reservoir + double offPressure = 0.0; // MinEVP: it closes again below this one + bool open = false; + double area = 0.0; // EVArea + double flow = 0.0; // the air through it in the last step +}; + +// the lock of the brake pipe in an emergency application +struct PipeLock +{ + double onPressure = -1.0; // LPOn + double offPressure = -1.0; // LPOff + double unlockHandlePosition = -3.0; // HandlePipeUnlockPos: the position of the driver's valve that unlocks it + bool locked = false; + bool unlockPressed = false; // the button that unlocks it pressed +}; + +// the braking of a vehicle +struct Braking +{ + // the valves + std::shared_ptr distributor; // the brake valve of the vehicle with its reservoirs and cylinders + std::shared_ptr driverValve; // the driver's brake valve of the train brake + std::shared_ptr independentValve; // the driver's valve of the independent brake + + // the definition, what the .fiz gives: set as the vehicle loads, not changed after + struct Config + { + TBrakeSystem kind = TBrakeSystem::Individual; // the kind of the train brake + TBrakeSubSystem subsystem = TBrakeSubSystem::ss_None; + TBrakeValve distributorType = TBrakeValve::NoValve; + int distributorSize = 0; + std::string distributorParameters; + TBrakeHandle driverValveType = TBrakeHandle::NoHandle; + TBrakeHandle independentValveType = TBrakeHandle::NoHandle; + bool independentTraxx = false; // the independent brake of the Traxx kind + DriverValveSettings driverValveSettings; + TLocalBrake localKind = TLocalBrake::NoBrake; // the kind of the individual brake + TBrakePressureTable pressureTable; // the pressures in the pipe of the positions of the driver's valve + int antiSlipType = 0; // 0: no anti-slip brake, 1: by hand, 2: automatic + std::array universalButtonActions{}; // what the universal brake buttons do + double maxForce = 0.0; // the most force of the brake + std::array maxCylinderPressure{}; // by the load setting: auxiliary, empty, medium, loaded, anti-slip + double pressureToForce = 0.0; // P2FTrans + double trackBrakeForce = 0.0; // the force of the track brake + int method = 0; // the friction material and its flags (bp_*) + int blocksPerAxle = 0; // NBpA: 0, 1, 2 or 4 + double maxPressureMass = 1.0; // MBPM: the mass of the highest pressure + double pipeHighPressure = 0.0; // the highest working pressure of the brake pipe + double pipeLowPressure = 0.0; // the lowest one + double pipePressureRange = 0.0; // the difference between them + double cylinderVolume = 0.0; // the volume of the brake cylinders + double valveVolume = 0.0; // BVV + BrakeCylinders cylinders; + double rapidRatio = 1.0; // the ratio of the rapid brake + double rapidSpeed = 55.0; // the speed the rapid brake switches at + double pipeSection = 0.0; // Spg: the cross-section of the brake pipe + bool emergencyCutsOffDriverValve = false; // EmergencyCutsOffHandle + TBrakeDelayTable delays; // the delays of applying and releasing + int handlePositions = 0; // the positions of the driver's valve + bool hasHandBrake = false; + int availableDelays = 0; // the delays it can be set to + int availableOperatingModes = 0; + }; + Config config; + + // the state + TBrakePressure actualPressure; // their values weighted for the present position of the valve + std::array universalButtonPressed{}; // the universal brake buttons pressed + int loadSetting = 0; // the index of maxCylinderPressure the brake takes + double controlReservoirPressure = 0.0; // the pressure in the control reservoir + EmergencyValve emergencyValve; + PipeLock pipeLock; + double cylinderPressure = 0.0; // the pressure in the brake cylinders + double cylinderPressureRate = 0.0; // how fast it changes, averaged over about a second [bar/s], see accelerating() + double independentCylinderPressure = 0.0; // the pressure in the cylinders from the independent brake + double pipeCylinderPressure = 0.0; // the pressure in the cylinders from the brake pipe + double equivalentPipePressure = 0.0; // the pressure of the brake pipe of the consist + double pipeLimiterPressure = 0.0; // the pressure the stabiliser holds + double reservoirAir = 0.0; // the compressed air in the brake reservoir + double brakeFlow = 0.0; // the air of the step: into the cylinders, + double pipeFlow = 0.0; // of the brake pipe, + double driverValveFlow = 0.0; // through the driver's valve, + double independentValveFlow = 0.0; // through the valve of the independent brake + int const &HandlePosition() const { return handlePosition; } // the position of the driver's valve + void SetHandlePosition(int const Value) { handlePosition = Value; } + double const &HandlePositionReal() const { return handlePositionReal; } // the same, continuous, of the FV4a + void SetHandlePositionReal(double const Value) { handlePositionReal = Value; } + double const &HandleCapPosition() const { return handleCapPosition; } // the cap of the FV4a + void SetHandleCapPosition(double const Value) { handleCapPosition = Value; } + double const &HandlePositionSmooth() const { return handlePositionSmooth; } // the continuous position of the driver's valve + void SetHandlePositionSmooth(double const Value) { handlePositionSmooth = Value; } + double const &IndependentPosition() const { return independentPosition; } // the position of the independent brake + void SetIndependentPosition(double const Value) { independentPosition = Value; } + double const &IndependentPositionEim() const { return independentPositionEim; } // the position of the EP independent brake of the asynchronous EMUs + void SetIndependentPositionEim(double const Value) { independentPositionEim = Value; } + int const &HandBrakePosition() const { return handBrakePosition; } + void SetHandBrakePosition(int const Value) { handBrakePosition = Value; } + int status = 0; // the bits b_* (b_off 0, b_on, b_dmg, b_rls, b_asb, b_ep ...) + bool alarmChain = false; // the manual emergency brake + int delaySetting = 0; // the delay set (bdelay_*) + // the AI wagon inspector cut the brake out (b_dmg) and puts it back when the train no longer needs it cut out + // (brake_setting::apply). Anyone else cutting it out or putting it back takes it over + bool cutOutByInspector = false; + int operatingMode = 0; // the mode set (bom_*: PS/PN/EP/MED 1/2/4/8) + double unitForce = 0.0; // the braking force of one braked element + double antiSlipTimer = 0.0; // to switch the anti-slip brake off + + ElectrodynamicBrake electrodynamic; + BrakeBlending blending; + EmuDynamicBrake emuDynamic; + HoldingBrake holding; + SpringBrake spring; + + private: + // the positions of the handles: the driver, the cab and the AI move them through the operations above + int handlePosition = -2; + double handlePositionReal = 0.0; + double handleCapPosition = 0.0; + double handlePositionSmooth = -2.0; + double independentPosition = 0.0; + double independentPositionEim = 0.0; + int handBrakePosition = 0; +}; + +} // namespace physics diff --git a/physics/components/cab.cpp b/physics/components/cab.cpp new file mode 100644 index 000000000..b17bd8624 --- /dev/null +++ b/physics/components/cab.cpp @@ -0,0 +1,250 @@ +/* +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 cab: activation, the direction, the horns, the pullee mode + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +bool physics::Vehicle::DirectionForward() +{ + if (false == EIMDirectionChangeAllow()) + { + return false; + } + + if (MainCtrlPosNo > 0 && DirActive < 1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) + { + ++DirActive; + DirAbsolute = DirActive * CabActive; + SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); + return true; + } + else if (DirActive == 1 && IsMainCtrlNoPowerPos() && trainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor) + return MinCurrentSwitch(true); //"wysoki rozruch" EN57 + return false; +}; + +bool physics::Vehicle::ChangeCab(int direction) +{ // zmiana kabiny i resetowanie ustawien + if (std::abs(cabOccupied + direction) < 2) + { + cabOccupied = cabOccupied + direction; + if (brakes.config.handlePositions > 0 && (brakes.config.kind == TBrakeSystem::Pneumatic || brakes.config.kind == TBrakeSystem::ElectroPneumatic)) + { + BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); + brakes.pipeLimiterPressure = brakePipe.Pressure(); + actFlowSpeed = 0; + } + else + BrakeLevelSet(brakes.driverValve->GetPos(bh_NP)); + mainCtrlPos = MainCtrlNoPowerPos(); + scndCtrlPos = 0; + return true; + } + return false; +}; + +int physics::Vehicle::SoundingHorns(int const Signal) const +{ + auto const supplied{[this](horn_supply const Supply) { + if (Supply == horn_supply::electric) + { + return lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable(); + } + if (air.config.mainReservoirVolume > 0.0) + { + return air.MainReservoirPressure() >= HornMinPressure; + } + // a vehicle without a main reservoir of its own takes the air from the main pipe, a vehicle without either + // (a road vehicle, say) has no air to check + auto const mainpipe{(Couplers[VehicleEnd::front].AllowedFlag | Couplers[VehicleEnd::rear].AllowedFlag).HasAny(Coupling::mainHose)}; + return false == mainpipe || mainPipe.Pressure() >= HornMinPressure; + }}; + auto horns{0}; + if (supplied(hornSupply)) + { + horns |= Signal & (1 | 2); + } + if (supplied(Horn3Supply)) + { + horns |= Signal & 4; + } + return horns; +} + +// ************************************************************************************************* +// Q: 20160710 +// załączenie rozrządu +// ************************************************************************************************* +bool physics::Vehicle::CabActivisation(bool const Enforce) +{ + bool OK = false; + + OK = Enforce || CabActive == 0; // numer kabiny, z której jest sterowanie + if (pulleeMode) + { + // nobody drives from a vehicle prepared for hauling + OK = false; + } + if (OK) + { + CabActive = cabOccupied; // sterowanie jest z kabiny z obsadą + DirAbsolute = DirActive * CabActive; + cabMaster = true; + SecuritySystem.set_enabled(true); // activate the alerter TODO: make it part of control based cab selection + SendCtrlToNext(VehicleCommand::cabActivation, 1, CabActive); + SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); + if (InactiveCabFlag & activation::springbrakeoff) + { + SpringBrakeActivate(false); + } + } + return OK; +} + +bool physics::Vehicle::CabActivisationAuto(bool const Enforce) +{ + bool OK = AutomaticCabActivation ? CabActivisation(Enforce) : false; + return OK; +} + +// ************************************************************************************************* +// Q: 20160710 +// wyłączenie rozrządu +// ************************************************************************************************* +bool physics::Vehicle::CabDeactivisation(bool const Enforce) +{ + bool OK = false; + + OK = Enforce || IsCabMaster(); // o ile obsada jest w kabinie ze sterowaniem + if (OK) + { + if (InactiveCabFlag & activation::springbrakeon) + { + SpringBrakeActivate(true); + } + if (InactiveCabFlag & activation::pantographsup) + { + inactiveCabPantsCheck = true; + } + if (InactiveCabFlag & activation::doorpermition) + { + PermitDoors(VehicleSide::right, true, range_t::consist); + PermitDoors(VehicleSide::left, true, range_t::consist); + } + if (InactiveCabFlag & activation::neutraldirection) + { + DirActive = 0; + SendCtrlToNext(VehicleCommand::direction, 0, CabActive); + } + + CabActive = 0; + DirAbsolute = DirActive * CabActive; + cabMaster = false; + departureSignalOn = false; // nie buczeć z nieaktywnej kabiny + SecuritySystem.set_enabled(false); // deactivate alerter TODO: make it part of control based cab selection + + SendCtrlToNext(VehicleCommand::cabActivation, 0, cabOccupied); // CabActive==0! + } + return OK; +} + +bool physics::Vehicle::CabDeactivisationAuto(bool const Enforce) +{ + bool OK = AutomaticCabActivation ? CabDeactivisation(Enforce) : false; + return OK; +} + +// ************************************************************************************************* +// pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): prepares the vehicle for being hauled dead in a +// train, or puts it back in service. while in the mode the vehicle: +// - vents the brake pipe for nothing of its own (inactive cab, vigilance, radio-stop, spring brake), only when +// the train parts (UpdatePipePressure()), +// - gets no force from its spring brake, whatever air its cylinder has (BrakeForce()), +// - has its driver's valve cut out and its local brake released, whatever the handles show; the distributor +// stays on the brake pipe, so it brakes and releases with the train, +// - keeps its battery off and takes no cab (BatterySwitch(), CabActivisation() and their commands). +// entering it also lets go of the hand brake and of the spring brake switch. +// returns whether the mode changed; a vehicle driven from can't enter it +// ************************************************************************************************* +bool physics::Vehicle::PulleeModeSwitch(bool const State) +{ + if (pulleeMode == State || (State && CabActive != 0)) + { + return false; + } + pulleeMode = State; + if (pulleeMode) + { + DecManualBrakeLevel(ManualBrakePosNo); + brakes.spring.activate = false; + SecuritySystem.set_enabled(false); + lowVoltage.DisconnectBattery(); + } + return true; +} + +// ************************************************************************************************* +// Q: 20160710 +// kierunek do tyłu +// ************************************************************************************************* +bool physics::Vehicle::DirectionBackward(void) +{ + if (false == EIMDirectionChangeAllow()) + { + return false; + } + + if (DirActive == 1 && mainCtrlPos == 0 && trainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor && MinCurrentSwitch(false)) + { + return true; + } + if (MainCtrlPosNo > 0 && DirActive > -1 && (CabActive != 0 || (InactiveCabFlag & activation::neutraldirection) == 0)) + { + if (EngineType == TEngineType::WheelsDriven) + --CabActive; + // else + --DirActive; + DirAbsolute = DirActive * CabActive; + SendCtrlToNext(VehicleCommand::direction, DirActive, CabActive); + return true; + } + + return false; +} + +bool physics::Vehicle::EIMDirectionChangeAllow(void) const +{ + bool OK = false; + /* + // NOTE: disabled while eimic variables aren't immediately synced with master controller changes inside ai module + OK = (EngineType != TEngineType::ElectricInductionMotor || ((eimic <= 0) && (eimicReal <= 0) && (Vel < 0.1))); + */ + OK = mainCtrlPos <= mainCtrlMaxDirChangePos; + return OK; +} diff --git a/physics/components/collisions.cpp b/physics/components/collisions.cpp new file mode 100644 index 000000000..6e1e511c9 --- /dev/null +++ b/physics/components/collisions.cpp @@ -0,0 +1,877 @@ +/* +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/. +*/ + +// collisions of the ends, their crush and repair, derailment and putting back on the rails + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +double ComputeCollision(double &v1, double &v2, double m1, double m2, double beta, bool vc) +{ // oblicza zmiane predkosci i przyrost pedu wskutek kolizji + assert(beta < 1.0); + + if (v1 < v2 && vc == true) + return 0; + else + { + double sum = m1 + m2; + double w1 = (m2 * v2 * 2.0 + v1 * (m1 - m2)) / sum; + double w2 = (m1 * v1 * 2.0 + v2 * (m2 - m1)) / sum; + // the collision changes the velocities directly: the bounce loses energy in the velocities relative to the + // centre of mass only, the pair keeps its momentum. scaling the velocities themselves braked the vehicles + // down with every step their couplers spent stretched or pressed in all the way (eu07/maszyna#553) + auto const centre{(m1 * v1 + m2 * v2) / sum}; + auto const restitution{std::sqrt(1.0 - beta)}; + v1 = std::lerp(centre, w1, restitution); + v2 = std::lerp(centre, w2, restitution); + return m1 * (w2 - w1) * (1 - beta); + } +} +namespace +{ + +// a derailed vehicle tears its brake hoses: the brake pipe vents and the rest of the train brakes in emergency +void tear_brake_hoses(physics::Vehicle &Vehicle) +{ + if (std::any_of(std::begin(Vehicle.Couplers), std::end(Vehicle.Couplers), [](auto const &Coupler) { return Coupler.CouplingFlag.HasAll(Coupling::brakeHose); })) + { + Vehicle.brakes.alarmChain = true; + } +} + +} // namespace + +// ************************************************************************************************* +// Q: 20160716 +// Wykrywanie kolizji +// ************************************************************************************************* +void physics::Vehicle::CollisionDetect(VehicleEnd const End, double const dt) +{ + if (Neighbours[End].vehicle == nullptr) + { + return; + } // shouldn't normally happen but, eh + + auto const &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->physics}; + auto const otherend{Neighbours[End].FacingEnd()}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; + + auto const physical{coupler_physics_at(End)}; + // physics.collisions new: past the buffers the ends of rail vehicles crush (collision.h); a hit the steel takes stays + // the legacy one, and so do the collisions of the road vehicles (the traffic of a scenery), with the legacy rule + auto const rails{TestFlag(CategoryFlag, 1) && TestFlag(othervehicle->CategoryFlag, 1)}; + auto const crushing{Global.collisions == global_settings::collision_model::physical && rails}; + if (crushing && (thiscoupler.hit_handled || crush_hit(End, dt))) + { + return; + } + // physics.collisions monitor: the legacy collision follows, the log tells what the crush would be + if (Global.collisions == global_settings::collision_model::monitor && rails) + { + crush_hit(End, dt); + } + if (physical && false == coupler_stop_hit(End, *othervehicle, otherend)) + { + return; + } + // the share of the energy of the relative motion the hit takes: in the physical model the springs gone solid give + // for good, rather than spring back as the legacy model has it + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + // the velocities along this vehicle's axis: the other vehicle's one is turned around when the vehicles face each + // other (touch with the same ends), as in CouplerForce() + auto const otherdirection{DirPatch(End, otherend)}; + auto velocity{travelSpeed}; + auto othervehiclevelocity{othervehicle->travelSpeed * otherdirection}; + // calculate collision force and new velocities for involved vehicles + auto const VirtualCoupling{(thiscoupler.CouplingFlag == Coupling::none)}; + auto CCF{0.0}; + + switch (End) + { + case VehicleEnd::front: + { + CCF = ComputeCollision(velocity, othervehiclevelocity, totalMass, othervehicle->totalMass, loss, VirtualCoupling) / dt; + break; // yB: ej ej ej, a po + } + case VehicleEnd::rear: + { + CCF = ComputeCollision(othervehiclevelocity, velocity, othervehicle->totalMass, totalMass, loss, VirtualCoupling) / dt; + break; + } + default: + { + break; + } + } + + // the new model crushes the ends and derails the vehicles by the crush, see crush_hit() + if (Global.crash_damage && false == crushing) + { + // the physical model breaks the coupling and crushes the buffers by the force of the hit (coupler_stop_hit()) + if (false == physical && -thiscoupler.Dist >= thiscoupler.DmaxB && FuzzyLogic(std::abs(CCF), 5.0 * (thiscoupler.FmaxC + 1.0), p_coupldmg)) + { + // small chance to smash the coupler if it's hit with excessive force + damage_coupler(End); + } + + // HACK: limit excessive speed derailment checks to vehicles which aren't part of the same consist + auto const outsideconsist{thiscoupler.CouplingFlag == Coupling::none || true == othervehicle->DamageFlag.HasAll(VehicleDamage::derailed)}; + auto const velocitydifference{outsideconsist ? CollisionVelocity(End, *othervehicle, otherend) : 0.0}; + + if (velocitydifference > SafeCollisionVelocity) + { + // HACK: crude estimation for potential derail, will take place with velocity difference > 15 km/h adjusted for vehicle mass ratio + if (false == DamageFlag.HasAll(VehicleDamage::derailed) || false == othervehicle->DamageFlag.HasAll(VehicleDamage::derailed)) + { + WriteLog("Bad driving: " + Name + " and " + othervehicle->Name + " collided with velocity " + to_string(velocitydifference, 0) + " km/h"); + } + + if (velocitydifference > SafeCollisionVelocity * (totalMass / othervehicle->totalMass)) + { + Derail(COLLISION); + } + if (velocitydifference > SafeCollisionVelocity * (othervehicle->totalMass / totalMass)) + { + othervehicle->Derail(COLLISION); + } + } + } + + // adjust velocity and acceleration of affected vehicles. the physical model changes the velocities alone: the + // integration of the next step (ComputeMovement()) would carry a quarter of an acceleration spike over into the + // velocity once more, and the vehicles would bounce off the stop faster than they hit it + auto const accelerationspike{physical ? 0.0 : 1.0}; + // derailed the legacy way a vehicle is a wall, off the rails by the new criteria it slides on and takes the hit. with + // the crush, the vehicles coupled to the wall push it on (crush_hit()) + auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; + auto const wall = [crushing, coupled](physics::Vehicle const &Vehicle) { + return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed) && (false == crushing || (Vehicle.derailOutcome == derailment::outcome::none && false == coupled)); + }; + if (false == wall(*this)) + { + auto const accelerationchange{(velocity - travelSpeed) / dt}; + accS += accelerationchange * accelerationspike; + travelSpeed = velocity; + } + if (false == wall(*othervehicle)) + { + auto const othervehiclenewvelocity{othervehiclevelocity * otherdirection}; // back along the other vehicle's axis + auto const othervehicleaccelerationchange{(othervehiclenewvelocity - othervehicle->travelSpeed) / dt}; + othervehicle->accS += othervehicleaccelerationchange * accelerationspike; + othervehicle->travelSpeed = othervehiclenewvelocity; + } +} + +void physics::Vehicle::damage_coupler(VehicleEnd const End) +{ + + auto &thiscoupler{Couplers[End]}; + + if (thiscoupler.type() == TCouplerType::Articulated) + { + return; + } // HACK: don't break articulated couplings no matter what + + if (DamageFlag.Set(VehicleDamage::coupling)) + eventFlag = true; + + auto const hosetorn{thiscoupler.CouplingFlag.HasAll(Coupling::brakeHose)}; + if (hosetorn) + { + // hamowanie nagle - zerwanie przewodow hamulcowych + brakes.alarmChain = true; + } + + thiscoupler.CouplingFlag = {}; + thiscoupler.broken = true; + + if (thiscoupler.Connected != nullptr) + { + // break connection with other vehicle, if there's any: on the end it's coupled with, which is the front one too + // for vehicles facing each other + auto &othercoupler{thiscoupler.Connected->Couplers[thiscoupler.ConnectedNr]}; + othercoupler.CouplingFlag = Coupling::none; + // the coupling broke between the two, either end can be repaired + othercoupler.broken = true; + if (hosetorn && coupler_physics_at(End)) + { + // the brake pipe of the other part of the train vents through the torn hose as well + thiscoupler.Connected->brakes.alarmChain = true; + } + } + + WriteLog("Bad driving: " + Name + " broke a coupler"); +} + +// ************************************************************************************************* +// physics.collisions new: the collisions past the buffers, see collision.h +// ************************************************************************************************* +collision::vehicle_kind physics::Vehicle::collision_kind() const +{ + auto const powered{EngineType != TEngineType::None && EngineType != TEngineType::Dumb}; + auto const unit{is_multiple_unit()}; + auto const passengers{std::any_of(LoadAttributes.begin(), LoadAttributes.end(), [](auto const &Load) { return ToLower(Load.name).starts_with("passenger"); })}; + // a coach heats its compartments; the crash zone is a matter of each end (crush_of()) + return collision::kind_of(powered, unit || passengers || (false == powered && trainHeating.config.power > 0.0), false); +} + +collision::crush_curve physics::Vehicle::crush_curve_at(VehicleEnd const End) const +{ + return collision::crush_of(Couplers[End].collision, collision_kind()); +} + +double physics::Vehicle::buffer_height_at(VehicleEnd const End) const +{ + auto const loadshare{maxLoad > 0.f ? loadAmount / maxLoad : 0.0}; + return collision::buffer_height(Couplers[End].collision, collision_kind(), loadshare); +} + +void physics::Vehicle::derail_in_collision(DerailReason const Reason, std::string const &Why) +{ + if (false == DamageFlag.Set(VehicleDamage::derailed)) + { + return; + } + // upright, it slides on the sleepers and keeps passing the forces on + derailOutcome = derailment::outcome::off_rails; + derailCause = derail_motion::cause::collision; + derailAcceleration = 0.0; + derailSide = 0; + collisionDerail = Reason; + eventFlag = true; + MainSwitch(false, range_t::local); + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrotValue = 0.0; + slippingWheels = false; + } + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + tear_brake_hoses(*this); + derailment_monitor.reset(); + pushed_off_monitor.reset(); + ErrorLog(std::format("Bad driving: {} derailed in a collision, {}: {}", Name, Reason == COLLISION_OVERRIDE ? "overriding" : "pushed off the track", Why)); +} +namespace +{ + + +char const *end_name(VehicleEnd const End) +{ + return End == VehicleEnd::front ? "front" : "rear"; +} + +char const *kind_name(collision::vehicle_kind const Kind) +{ + switch (Kind) + { + case collision::vehicle_kind::locomotive: + return "locomotive"; + case collision::vehicle_kind::coach: + return "coach"; + case collision::vehicle_kind::crash_zone: + return "crash zone"; + case collision::vehicle_kind::wagon: + default: + return "wagon"; + } +} + +} // namespace +namespace +{ + +// the steel parts of both ends in series [N/m] +double steel_stiffness(TCoupling const &First, TCoupling const &Second) +{ + auto const first{std::max(First.physics.link_stiffness, 1.0)}; + auto const second{std::max(Second.physics.link_stiffness, 1.0)}; + return first * second / (first + second); +} + +// the hit of the pair in the step, for the push off the track: the peak force and how long it acted +void record_hit(TCoupling &Coupler, double const Force, double const Duration) +{ + Coupler.hit_force = std::max(Coupler.hit_force, Force); + Coupler.hit_duration = std::max(Coupler.hit_duration, Duration); +} + +} // namespace + +bool physics::Vehicle::crush_hit(VehicleEnd const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->physics}; + auto const otherend{Neighbours[End].FacingEnd()}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + + auto const physical{coupler_physics_at(End)}; + // the buffers pressed all the way, not the draw gear pulled all the way, and the pair still closing in + auto const buffers{physical ? thiscoupler.physics_state.stop < 0 : thiscoupler.Dist < 0.0}; + auto const closing{-CouplerVelocityDifference(End, *othervehicle, otherend) * DirF(End)}; + if (false == Global.crash_damage || false == buffers || closing <= 0.0) + { + // the hit is over, the next one is another one for the monitor + thiscoupler.crush_monitored = false; + othercoupler.crush_monitored = false; + return false; + } + auto const monitor{Global.collisions == global_settings::collision_model::monitor}; + // put down by the scenery inside each other: pressed past the stop of the buffers and the crush of the ends by more + // than a hit takes them in a step. the legacy collision pushes them apart; their springs, the stops at both ends + // and the neighbours found at either end there make up any closing velocity, not a hit + auto const stop{std::max(thiscoupler.DmaxB + othercoupler.DmaxB, thiscoupler.physics.buffers.travel + othercoupler.physics.buffers.travel) + thiscoupler.crush + othercoupler.crush}; + auto const overlap{-static_cast(Neighbours[End].distance)}; + if (overlap > stop + collision::inside_margin + closing * dt) + { + // nor is what their springs took in pressed past the stop and back a hit, for as long as the buffers touch + thiscoupler.contact.inside(); + othercoupler.contact.inside(); + if (false == thiscoupler.inside_reported) + { + thiscoupler.inside_reported = true; + othercoupler.inside_reported = true; + WriteLog(std::format("Bad scenery: {} and {} are inside each other, their buffers pressed {:.2f} m past their stop, no crush", Name, othervehicle->Name, overlap - stop)); + } + return false; + } + // parting at the start of the step: what closes the pair in now is the knock of a hit of either vehicle in the step, + // or of the vehicles inside each other next to it, not a hit of this pair. the legacy collision takes it; a pair + // still closing in at the start of the next step is a hit + if (thiscoupler.closing < 0.0) + { + return false; + } + // a vehicle derailed the legacy way (the end of the track, say) stays where it is, whatever hits it from outside its + // train. the vehicles coupled to it push it on, as the train behind a derailed vehicle does: a wall to them, it + // stopped the whole train at once, and the vehicles behind it crushed by the energy of the train + auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; + auto const wall{false == coupled && DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome == derailment::outcome::none}; + auto const otherwall{false == coupled && othervehicle->DamageFlag.HasAll(VehicleDamage::derailed) && othervehicle->derailOutcome == derailment::outcome::none}; + if (wall && otherwall) + { + return false; + } + constexpr double immovable{1e12}; + auto const mass{wall ? immovable : totalMass}; + auto const othermass{otherwall ? immovable : othervehicle->totalMass}; + auto const loss{physical ? coupler_physics::solid_hit_loss(thiscoupler.physics, othercoupler.physics) : (thiscoupler.beta + othercoupler.beta) / 2.0}; + + auto const firstcurve{crush_curve_at(End)}; + auto const secondcurve{othervehicle->crush_curve_at(otherend)}; + auto const stiffness{steel_stiffness(thiscoupler, othercoupler)}; + auto const springs{compression_at(thiscoupler, End)}; + collision::hit_input input; + input.velocity = closing; + input.mass1 = mass; + input.mass2 = othermass; + input.restitution = std::sqrt(std::max(0.0, 1.0 - loss)); + input.stiffness = stiffness; + input.springs = springs; + // the monitor takes the whole hit at once, over a second, longer than the crush of any hit lasts + input.dt = monitor ? 1.0 : dt; + input.start_velocity = thiscoupler.closing; + // the crush takes only what the hit brings past what the buffers of EN 15551 of both ends take in. an automatic + // coupler (or its adapter) has no buffers at the side: its draft gear takes in what its springs of the .fiz do + auto const reduced{mass * othermass / (mass + othermass)}; + auto const central{thiscoupler.type() == TCouplerType::Automatic || othercoupler.type() == TCouplerType::Automatic || thiscoupler.has_adapter() || othercoupler.has_adapter()}; + auto const capacity{central ? 0.0 : collision::buffer_capacity(thiscoupler.collision, collision_kind()) + collision::buffer_capacity(othercoupler.collision, othervehicle->collision_kind())}; + auto const hitvelocity{std::max(closing, thiscoupler.closing)}; + input.budget = thiscoupler.contact.budget(reduced, hitvelocity, capacity); + auto const hit{collision::hit({firstcurve, thiscoupler.crush}, {secondcurve, othercoupler.crush}, input)}; + // the override, by the crush of both ends + auto const climbing_of = [&](double const Crush1, double const Crush2) { + collision::override_input climbing; + climbing.crush1 = Crush1; + climbing.crush2 = Crush2; + climbing.mass1 = totalMass - mred; + climbing.mass2 = othervehicle->totalMass - othervehicle->mred; + climbing.height1 = buffer_height_at(End); + climbing.height2 = othervehicle->buffer_height_at(otherend); + climbing.anticlimbers = collision::anticlimber_of(thiscoupler.collision, collision_kind()) && collision::anticlimber_of(othercoupler.collision, othervehicle->collision_kind()); + climbing.zone1 = firstcurve.densify; + climbing.zone2 = secondcurve.densify; + return climbing; + }; + if (monitor) + { + if (hit.crushing && false == thiscoupler.crush_monitored) + { + thiscoupler.crush_monitored = true; + othercoupler.crush_monitored = true; + ++crushreportsValue; + auto const crush1{thiscoupler.crush + hit.crush1}; + auto const crush2{othercoupler.crush + hit.crush2}; + auto const climbed{collision::override_of(climbing_of(crush1, crush2))}; + auto const torn{std::max(crush1, crush2) >= collision::draw_gear_crush}; + std::string const outcome{climbed.first && climbed.second ? std::string{"both would leave the rails"} + : climbed.first ? Name + " would ride up onto " + othervehicle->Name + : climbed.second ? othervehicle->Name + " would ride up onto " + Name + : std::string{"both would stay on the rails"}}; + WriteLog(std::format("collision monitor: {} and {} collided at {:.0f} km/h: the {} end of {} ({:.1f} t {}) would crush by {:.2f} m, the {} end of {} ({:.1f} t {}) by {:.2f} m, " + "at {:.0f} kN; draw gear {}; {}", + Name, othervehicle->Name, closing * 3.6, end_name(End), Name, totalMass / 1000.0, kind_name(collision_kind()), crush1, end_name(otherend), othervehicle->Name, + othervehicle->totalMass / 1000.0, kind_name(othervehicle->collision_kind()), crush2, hit.force / 1000.0, torn ? "torn off" : "holds", outcome)); + } + return false; + } + if (false == hit.crushing) + { + // the steel takes it, the legacy collision follows; its peak, under the force an end gives at, for the push + // off the track + auto const weaker{std::min(firstcurve.force(thiscoupler.crush), secondcurve.force(othercoupler.crush))}; + auto const peak{std::min(springs + coupler_physics::impact_force(closing, stiffness, mass, othermass), weaker)}; + auto const duration{std::min(dt, (1.0 + input.restitution) * std::sqrt(reduced / stiffness))}; + record_hit(thiscoupler, peak, duration); + record_hit(othercoupler, peak, duration); + return false; + } + // the other vehicle doesn't take it again in this step + thiscoupler.hit_handled = true; + othercoupler.hit_handled = true; + + // the hit at the force the weaker end gives at pushes the vehicles apart: the velocities alone change, along this + // vehicle's axis as in CollisionDetect() + auto const otherdirection{DirPatch(End, otherend)}; + auto const apart{End == VehicleEnd::front ? -1.0 : 1.0}; + if (false == wall) + { + travelSpeed += apart * hit.impulse / mass; + } + if (false == otherwall) + { + othervehicle->travelSpeed -= apart * hit.impulse / othermass * otherdirection; + } + record_hit(thiscoupler, hit.force, hit.duration); + record_hit(othercoupler, hit.force, hit.duration); + + // the energy the crush took, for both vehicles' count of the contact + thiscoupler.contact.crushed(hit.work); + othercoupler.contact.crushed(hit.work); + // what the log tells of the pair, for the analysis of a crush + auto const kinetic{0.5 * reduced * hitvelocity * hitvelocity}; + auto const pair = [&]() { + return std::format("{} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; {} {:.1f} t {}, {} end crushed {:.2f} m, gives at {:.0f} kN; force {:.0f} kN, springs {:.0f} kN, " + "closing at {:.1f} km/h at the start of the step; energy {:.0f} kJ of the motion and {:.0f} kJ in the buffers, past the {:.0f} kJ they take in, " + "{:.0f} kJ crushed in the contact", + Name, totalMass / 1000.0, kind_name(collision_kind()), end_name(End), thiscoupler.crush, firstcurve.force(thiscoupler.crush) / 1000.0, othervehicle->Name, + othervehicle->totalMass / 1000.0, kind_name(othervehicle->collision_kind()), end_name(otherend), othercoupler.crush, + secondcurve.force(othercoupler.crush) / 1000.0, hit.force / 1000.0, springs / 1000.0, input.start_velocity * 3.6, kinetic / 1000.0, + thiscoupler.contact.absorbed() / 1000.0, capacity / 1000.0, thiscoupler.contact.crush_work() / 1000.0); + }; + auto const crushed = [&](physics::Vehicle const &Vehicle, VehicleEnd const crushedEnd, double const Before, double const After) { + if (Before < collision::crush_mark && After >= collision::crush_mark) + { + ErrorLog(std::format("Bad driving: {} and {} collided at {:.0f} km/h, the {} end of {} crushed ({})", Name, othervehicle->Name, closing * 3.6, end_name(crushedEnd), Vehicle.Name, pair())); + } + }; + auto const before{thiscoupler.crush}; + auto const otherbefore{othercoupler.crush}; + thiscoupler.crush += hit.crush1; + othercoupler.crush += hit.crush2; + crushed(*this, End, before, thiscoupler.crush); + crushed(*othervehicle, otherend, otherbefore, othercoupler.crush); + + // the crushed headstock tears off the draw gear, with the brake hose: both parts of the train brake in emergency. + // the coupler of an end not coupled is gone as well, it doesn't couple any more + if (thiscoupler.CouplingFlag != Coupling::none && std::max(thiscoupler.crush, othercoupler.crush) >= collision::draw_gear_crush) + { + auto const hose{thiscoupler.CouplingFlag.HasAll(Coupling::brakeHose)}; + damage_coupler(End); + if (hose) + { + othervehicle->brakes.alarmChain = true; + } + } + else if (thiscoupler.CouplingFlag == Coupling::none) + { + if (thiscoupler.crush >= collision::draw_gear_crush && false == thiscoupler.broken) + { + damage_coupler(End); + } + if (othercoupler.crush >= collision::draw_gear_crush && false == othercoupler.broken) + { + othervehicle->damage_coupler(otherend); + } + } + + // the end crushed deep enough lets one vehicle climb onto the other one + auto const climbing{climbing_of(thiscoupler.crush, othercoupler.crush)}; + auto const climbed{collision::override_of(climbing)}; + auto const why = [&](physics::Vehicle const &Climber, physics::Vehicle const &Other) { + return std::format("{} rode up onto {} at {:.0f} km/h, the ends crushed by {:.2f} m, buffers at {:.0f} / {:.0f} mm, anticlimbers {} ({})", Climber.Name, Other.Name, closing * 3.6, + thiscoupler.crush + othercoupler.crush, climbing.height1 * 1000.0, climbing.height2 * 1000.0, climbing.anticlimbers ? "yes" : "no", pair()); + }; + if (climbed.first) + { + derail_in_collision(COLLISION_OVERRIDE, why(*this, *othervehicle)); + } + if (climbed.second) + { + othervehicle->derail_in_collision(COLLISION_OVERRIDE, why(*othervehicle, *this)); + } + return true; +} + +void physics::Vehicle::check_pushed_off(double const dt, double const Distance) +{ + if (Global.collisions != global_settings::collision_model::physical || false == Global.crash_damage || DamageFlag.HasAll(VehicleDamage::derailed) || false == TestFlag(CategoryFlag, 1) || + DebugModeFlag) + { + pushed_off_monitor.reset(); + return; + } + collision::pushed_vehicle vehicle; + vehicle.mass = totalMass - mred; + vehicle.axles = nAxles > 0 ? nAxles : 4; + vehicle.length = Dim.L; + vehicle.pivots = bDist; + vehicle.axle_base = aDist > 0.0 ? aDist : bDist; + + auto climbs{false}; + auto distance{0.0}; + auto lifted{false}; + auto duration{0.0}; + auto worst{0.0}; + auto worstforce{0.0}; + auto worstend{VehicleEnd::front}; + for (auto const end : VehicleEnds) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + auto const &coupler{Couplers[end]}; + collision::pushed_end pushed; + pushed.other_length = other->physics->Dim.L; + pushed.crush = coupler.crush; + // the steady push of the springs over the step, or the peak of a hit for as long as it lasted: the flange climbs + // over the distance the wheels rolled meanwhile, a wheel lifted off the rail goes in a short time, rolling or not + for (auto const &[force, time] : {std::pair{compression_at(coupler, end), dt}, std::pair{coupler.hit_force, coupler.hit_duration}}) + { + pushed.force = force; + auto const wheel{collision::pushed_forces(vehicle, pushed, RunningShape.R)}; + auto const ratio{wheel.ratio()}; + if (ratio < derailment::climbing_limit) + { + continue; + } + climbs = true; + distance = std::max(distance, Distance * std::clamp(time / std::max(dt, 1e-9), 0.0, 1.0)); + if (wheel.lifted()) + { + lifted = true; + duration = std::max(duration, time); + } + if (ratio > worst) + { + worst = ratio; + worstforce = force; + worstend = end; + } + } + } + if (pushed_off_monitor.update(climbs, distance, lifted, duration)) + { + derail_in_collision(COLLISION_PUSHED_OFF, std::format("{:.0f} kN pressing its {} end in, {}, at {:.0f} km/h, curve radius {:.0f} m: Y/Q {:.2f} ({:.1f} t {}, {} axles, " + "springs {:.0f} / {:.0f} kN, hits {:.0f} / {:.0f} kN, crushed {:.2f} / {:.2f} m)", + worstforce / 1000.0, end_name(worstend), + lifted ? std::format("its wheels lifted off the rail for {:.3f} s", pushed_off_monitor.time()) + : std::format("the flange climbing over {:.2f} m", pushed_off_monitor.distance()), + Vel, std::abs(RunningShape.R), std::min(worst, 99.0), + vehicle.mass / 1000.0, kind_name(collision_kind()), vehicle.axles, compression_at(Couplers[VehicleEnd::front], VehicleEnd::front) / 1000.0, + compression_at(Couplers[VehicleEnd::rear], VehicleEnd::rear) / 1000.0, Couplers[VehicleEnd::front].hit_force / 1000.0, Couplers[VehicleEnd::rear].hit_force / 1000.0, + Couplers[VehicleEnd::front].crush, Couplers[VehicleEnd::rear].crush)); + } +} +namespace +{ + + +// the end as it was built (physics.collisions new): not crushed, and nothing of a contact or a hit kept +void restore_end(TCoupling &Coupler) +{ + Coupler.crush = 0.0; + Coupler.contact.reset(); + Coupler.hit_handled = false; + Coupler.hit_force = 0.0; + Coupler.hit_duration = 0.0; + Coupler.crush_monitored = false; + Coupler.inside_reported = false; +} + +// the coupler as good as new, its end with it (the crush that tore the draw gear off), the vehicle without the coupler +// damage (and the emergency braking of the torn brake hose) once neither of its couplers is broken +void repair(physics::Vehicle &Vehicle, TCoupling &Coupler) +{ + Coupler.broken = false; + Coupler.stretch_duration = 0.f; + Coupler.physics_state.couple(); + restore_end(Coupler); + if (Vehicle.Couplers[VehicleEnd::front].broken || Vehicle.Couplers[VehicleEnd::rear].broken) + { + return; + } + Vehicle.DamageFlag.Clear(VehicleDamage::coupling); + // either vehicle of the pair may have been braking through the torn hose + Vehicle.brakes.alarmChain = false; +} + +} // namespace + +bool physics::Vehicle::repair_coupler(VehicleEnd const End) +{ + auto &thiscoupler{Couplers[End]}; + if (false == thiscoupler.broken) + { + return false; + } + repair(*this, thiscoupler); + // the other half of the coupling, which may be the vehicle flagged with the damage + if (auto *other{thiscoupler.Connected}; other != nullptr && other->Couplers[thiscoupler.ConnectedNr].broken) + { + repair(*other, other->Couplers[thiscoupler.ConnectedNr]); + } + WriteLog(std::format("Coupler of {} repaired, at its {} end", Name, End == VehicleEnd::front ? "front" : "rear")); + return true; +} + +static_assert(derailment::track_damage::railwear == dtrack_railwear && derailment::track_damage::freerail == dtrack_freerail && derailment::track_damage::thinrail == dtrack_thinrail && + derailment::track_damage::railbend == dtrack_railbend); + +double physics::Vehicle::centre_of_gravity() const +{ + auto const kind{EngineType == TEngineType::None ? derailment::vehicle_class::unpowered : derailment::vehicle_class::powered}; + auto const empty{CentreOfGravity > 0.0 ? CentreOfGravity : derailment::default_centre_of_gravity(Dim.H, kind)}; + auto const loadmass{totalMass - emptyMass - mred}; + auto const loadshare{maxLoad > 0.f ? loadAmount / maxLoad : 1.0}; + return derailment::loaded_centre_of_gravity(empty, emptyMass, loadmass, loadshare, Floor, Dim.H); +} + +void physics::Vehicle::check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double const Distance) +{ + if (DamageFlag.HasAll(VehicleDamage::derailed) || false == TestFlag(CategoryFlag, 1) || DebugModeFlag) + { + derailment_monitor.reset(); + return; + } + derailment::vehicle_state vehicle; + vehicle.mass = totalMass - mred; + vehicle.axles = nAxles > 0 ? nAxles : 4; + vehicle.length = Dim.L; + vehicle.axle_base = aDist > 0.0 ? aDist : bDist; + vehicle.centre_of_gravity = centre_of_gravity(); + for (auto const end : VehicleEnds) + { + auto const *other{Neighbours[end].vehicle}; + if (other == nullptr) + { + continue; + } + // the force of the coupling, or of the buffers touching, along this vehicle: forwards at the front pulls + vehicle.ends[NumberOf(end)].compression = (end == VehicleEnd::front ? -1.0 : 1.0) * Couplers[end].CForce; + vehicle.ends[NumberOf(end)].other_length = other->physics->Dim.L; + } + derailment::track_state track; + track.radius = Shape.R; + track.cant = Shape.dHrail; + track.gauge = TrackW; + track.uneven_curvature = Shape.uneven_curvature; + track.uneven_cross = Shape.uneven_cross; + track.buckle_curvature = Shape.buckle_curvature; + track.damage = Track.DamageFlag; + + auto const verdict{derailment_monitor.update(vehicle, track, travelSpeed, Distance)}; + if (verdict.result == derailment::outcome::none) + { + return; + } + auto const physical{Global.derailment == global_settings::derailment_model::physical}; + // physics.derailment.trustlimits: under the trusted speed of the limit of the track the curve alone derails nothing, + // the limit is a defect of the scenery (derailment.h) + auto const trusted{physical && Global.derailment_trust_limits && + derailment::limited_verdict(verdict, derailment::from_track_alone(verdict, vehicle, track, travelSpeed), travelSpeed, Track.Velmax).result == derailment::outcome::none}; + if (physical && false == trusted) + { + derail(verdict, vehicle, track, Track.Name); + return; + } + // physics.derailment monitor: the legacy draw decides, the log tells what the criteria would do; or the verdict held + // back. once on a track + if (derailment_reported.has_value() && *derailment_reported == Track.Name) + { + return; + } + derailment_reported = Track.Name; + ++derailmentreportsValue; + auto const trackname{Track.Name != nullptr ? *Track.Name : std::string{}}; + WriteLog(trusted ? "derailment monitor: data: " + Name + " " + derailment::held_back_report(verdict, vehicle, track, travelSpeed, Track.Velmax, trackname) + : "derailment monitor: " + Name + " " + derailment::report(verdict, vehicle, track, travelSpeed, trackname)); +} + +void physics::Vehicle::derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName) +{ + if (false == DamageFlag.Set(VehicleDamage::derailed)) + { + return; + } + derailOutcome = Verdict.result; + derailCause = Verdict.result == derailment::outcome::overturned ? derail_motion::cause::overturned : derail_motion::cause::off_rails; + // out of the curve; a buckle bending the line against the curve more than the curve does throws it into the curve + derailAcceleration = std::abs(Track.radius) > 1e-3 && derailment::line_curvature(Track) < 0.0 ? -Verdict.acceleration : Verdict.acceleration; + derailSide = 0; + eventFlag = true; + MainSwitch(false, range_t::local); + // the brake hoses tear: the brake pipe vents and the rest of the train brakes in emergency + tear_brake_hoses(*this); + ErrorLog("Bad driving: " + Name + " " + derailment::report(Verdict, Vehicle, Track, travelSpeed, TrackName != nullptr ? *TrackName : std::string{})); + if (Track.buckle_curvature != 0.0) + { + ErrorLog(std::format("Bad driving: {} derailed on buckled track, the buckle bending the line by 1/{:.0f} m {} the curve", Name, 1.0 / std::abs(Track.buckle_curvature), + Track.buckle_curvature > 0.0 ? "with" : "against")); + } +} + +void physics::Vehicle::rerail() +{ + DamageFlag.Clear(VehicleDamage::derailed); + derailOutcome = derailment::outcome::none; + // and back on the track; what derailed it before has no say in how it leaves the track the next time + OffTrack.reset(); + derailCause = derail_motion::cause::off_rails; + derailAcceleration = 0.0; + derailSide = 0; + derailment_monitor.reset(); + derailmentDistance = 0.0; + derailment_reported.reset(); + // nor derailed in a collision + collisionDerail = NONE; + pushed_off_monitor.reset(); + // back on the axis of the track, which the derailment shifted the vehicle off aside and down (a road vehicle keeps + // its place on the road) + if (TestFlag(CategoryFlag, 1)) + { + offsetTrackH = 0.0; + offsetTrackV = 0.0; + } + // a derailed vehicle which stopped sleeps (Global.physics_sleepheld) with the friction of the derailment in FStand and + // where the derailment put it, until something wakes it: the physics on, for the friction of the rails and its place on + // them. it is put back by a command (resetconsist, SetDamage) or by the road spawner, which sets it going anyway + switch_physics(true, wake_cause::command); +} + +void physics::Vehicle::repair_damage() +{ + DamageFlag = {}; + equipmentFaults = {}; + wheelFlat = 0.0; + brakes.alarmChain = false; + // the crushed ends rebuilt + for (auto &coupler : Couplers) + { + restore_end(coupler); + } + rerail(); +} + +void physics::Vehicle::Derail(DerailReason const Reason) +{ + if (DamageFlag.Set(VehicleDamage::derailed)) + { + eventFlag = true; + MainSwitch(false, range_t::local); + + auto const velocity{travelSpeed}; + accS *= 0.65; + travelSpeed *= 0.65; + // physics.collisions new: the vehicles coupled to it lose the speed with it. the cut in a step stands for the + // train coming to a stop with the vehicle; the coupled ones keeping their speed would run into it at a third of + // the speed of the train, and crush their ends and ride up onto it for a hit no train had + if (Global.collisions == global_settings::collision_model::physical && TestFlag(CategoryFlag, 1)) + { + change_train_velocity(travelSpeed - velocity); + } + RunningShape.R = 0; + if (Vel < 5.0) + { + // HACK: prevent permanent axle spin in static vehicle after a collision + nrotValue = 0.0; + slippingWheels = false; + } + // physics.derailment new: off the end of the track the vehicle runs on straight on its wheels, sliding on the + // ground as the vehicles the criteria derail do, and its brake hoses tear + if (Reason == END_OF_TRACK && Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1)) + { + derailOutcome = derailment::outcome::off_rails; + derailCause = derail_motion::cause::end_of_track; + derailAcceleration = 0.0; + derailSide = 0; + tear_brake_hoses(*this); + } + + // Print a message in the log. + if (Reason == END_OF_TRACK) + ErrorLog("Bad driving: " + Name + " derailed due to end of track"); + else if (Reason == TOO_HIGH_SPEED) + ErrorLog("Bad driving: " + Name + " derailed due to too high speed"); + else if (Reason == GAUGE_MISMATCH) + ErrorLog("Bad dynamic: " + Name + " derailed due to track width"); // błąd w scenerii + else if (Reason == WRONG_TRACK_TYPE) + ErrorLog("Bad dynamic: " + Name + " derailed due to wrong track type"); // błąd w scenerii + else if (Reason == COLLISION) + WriteLog("Bad driving: " + Name + " derailed"); // This reason also generates its own message in `physics::Vehicle::CollisionDetect()` + else if (Reason == TRAILED_SWITCH) + ErrorLog("Bad driving: " + Name + " derailed trailing through a switch with a movable nose set the other way"); + } +} + +bool physics::Vehicle::leaves_track() const +{ + return Global.derailment == global_settings::derailment_model::physical && TestFlag(CategoryFlag, 1) && DamageFlag.HasAll(VehicleDamage::derailed) && derailOutcome != derailment::outcome::none && + false == OffTrack.active(); +} + +void physics::Vehicle::pull_off(int const Side, double const Acceleration, std::string const &Why) +{ + if (Global.derailment != global_settings::derailment_model::physical || false == DamageFlag.Set(VehicleDamage::derailed)) + { + return; + } + // upright, its flange climbs the rail the coupling pulls it over + derailOutcome = derailment::outcome::off_rails; + derailCause = derail_motion::cause::pulled_off; + derailAcceleration = Acceleration; + derailSide = Side; + eventFlag = true; + MainSwitch(false, range_t::local); + tear_brake_hoses(*this); + derailment_monitor.reset(); + ErrorLog(std::format("Bad driving: {} pulled off the track by the vehicle coupled to it, {}", Name, Why)); +} diff --git a/physics/components/commands.cpp b/physics/components/commands.cpp new file mode 100644 index 000000000..5aed38a8a --- /dev/null +++ b/physics/components/commands.cpp @@ -0,0 +1,819 @@ +/* +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 commands passed between the vehicles of a train + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +// ************************************************************************************************* +// Q: 20160714 +// Wstawia komendę z parametrem, od sprzęgu i w lokalizacji do pojazdu +// ************************************************************************************************* +void physics::Vehicle::PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation) +{ + auto const parsed{ParseVehicleCommand(NewCommand)}; + CommandIn.Command = parsed.command; + CommandIn.Text = NewCommand; + CommandIn.Argument = parsed.argument; + CommandIn.Value1 = NewValue1; + CommandIn.Value2 = NewValue2; + CommandIn.Location = NewLocation; + // czy uruchomic tu RunInternalCommand? nie wiem +} + +// ************************************************************************************************* +// Q: 20160714 +// Ustawienie komendy wraz z parametrami +// ************************************************************************************************* +bool physics::Vehicle::SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, CouplingSet const Couplertype) +{ + bool SIC; + if (CommandIn.Command == NewCommand && CommandIn.Argument.empty() && CommandIn.Value1 == NewValue1 && CommandIn.Value2 == NewValue2 && CommandIn.couplings == Couplertype) + SIC = false; + else + { + CommandIn.Command = NewCommand; + CommandIn.Text = VehicleCommandName(NewCommand); + CommandIn.Argument.clear(); + CommandIn.Value1 = NewValue1; + CommandIn.Value2 = NewValue2; + CommandIn.couplings = Couplertype; + SIC = true; + LastLoadChangeTime = 0; // zerowanie czasu (roz)ładowania + } + + return SIC; +} + +// ************************************************************************************************* +// Q: 20160714 +// wysyłanie komendy w kierunku dir (1=przód, -1=tył) do kolejnego pojazdu (jednego) +// ************************************************************************************************* +bool physics::Vehicle::SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, CouplingSet const Couplertype) +{ + bool OK; + int d; // numer sprzęgu w kierunku którego wysyłamy + + // Ra: był problem z propagacją, jeśli w składzie jest pojazd wstawiony odwrotnie + // Ra: problem jest również, jeśli AI będzie na końcu składu + OK = true; // ( dir != 0 ); // experimentally disabled + d = (1 + static_cast(Sign(dir))) / 2; // dir=-1=>d=0, dir=1=>d=1 - wysyłanie tylko w tył + // musi być wybrana niezerowa kabina + if (OK && Couplers[d].Connected != nullptr && Couplers[d].CouplingFlag.HasAll(Couplertype)) + { + + if (Couplers[d].ConnectedNr != d) + { + // jeśli ten nastpęny jest zgodny z aktualnym + if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, dir, Couplertype)) + OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja + } + else + { + // jeśli następny jest ustawiony przeciwnie, zmieniamy kierunek + if (Couplers[d].Connected->SetInternalCommand(CtrlCommand, ctrlvalue, -dir, Couplertype)) + OK = Couplers[d].Connected->RunInternalCommand() && OK; // tu jest rekurencja + } + } + return OK; +} + +// ************************************************************************************************* +// Q: 20160723 +// ************************************************************************************************* +// wysłanie komendy otrzymanej z kierunku CValue2 (względem sprzęgów: 1=przod,-1=tył) +// Ra: Jest tu problem z rekurencją. Trzeba by oddzielić wykonywanie komend od mechanizmu +// ich propagacji w składzie. Osobnym problemem może być propagacja tylko w jedną stronę. +// Jeśli jakiś człon jest wstawiony odwrotnie, to również odwrotnie musi wykonywać +// komendy związane z kierunkami (PantFront, PantRear, DoorLeft, DoorRight). +// Komenda musi być zdefiniowana tutaj, a jeśli się wywołuje funkcję, to ona nie może +// sama przesyłać do kolejnych pojazdów. Należy też się zastanowić, czy dla uzyskania +// jakiejś zmiany (np. IncMainCtrl) lepiej wywołać funkcję, czy od razu wysłać komendę. +bool physics::Vehicle::RunCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, std::string_view const Argument) +{ + // the group of the command sets OK; a command none of them knows isn't done + if (bool OK{false}; RunControllerCommand(Command, CValue1, CValue2, Couplertype, OK) || RunRelaysCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunCabCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBrakeEquipmentCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunAuxiliariesCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPumpsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunBlowersCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunPowerCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunDoorsCommand(Command, CValue1, CValue2, Couplertype, OK) || + RunLoadCommand(Command, CValue1, CValue2, Argument, OK)) + { + return OK; // dla true komenda będzie usunięta, dla false wykonana ponownie + } + return false; +} + +// RunCommand() for the controllers; returns whether the command is one of them +bool physics::Vehicle::RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::mainController) + { + // sent as MainCtrlPosForCoupled(), passed on unchanged + if (auto const position{MainCtrlPosFromCoupled(static_cast(floor(CValue1)))}; MainCtrlPosNo >= position) + { + mainCtrlPos = position; + if (delayCtrlFlag) + { + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay && mainCtrlPos == 1) + lineContactors.RestartSwitchTimer(); + } + else if (lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::secondaryController) + { + if (scndCtrlPosNo >= floor(CValue1)) + { + scndCtrlPos = static_cast(floor(CValue1)); + if (lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + /* else if command='BrakeCtrl' then + begin + if BrakeCtrlPosNo>=Trunc(CValue1) then + begin + BrakeCtrlPos:=Trunc(CValue1); + OK:=SendCtrlToNext(command,CValue1,CValue2); + end; + end */ + else if (Command == VehicleCommand::integratedController) // ElectricInductionMotor Integrated Control - propulsion and brakes in relative values + { + eimicReal = CValue1; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the direction, the automatic start and the current relays; returns whether the command is one of them +bool physics::Vehicle::RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::direction) + { + DirActive = static_cast(floor(CValue1)); + DirAbsolute = DirActive * CabActive; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::autoRelaySwitch) + { + if (CValue1 == 1 && autoRelayType == 2) + autoRelayFlag = true; + else + autoRelayFlag = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::maxCurrentSwitch) + { + MaxCurrentSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::minCurrentSwitch) + { + OK = MinCurrentSwitch(CValue1 == 1); + } + /*test komend oddzialywujacych na tabor*/ + else + { + return false; + } + return true; +} + +// RunCommand() for the cab and the speed control; returns whether the command is one of them +bool physics::Vehicle::RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::cabActivation) + { + // OK:=Power>0.01; + switch (static_cast(CValue1 * CValue2)) + { // CValue2 ma zmieniany znak przy niezgodności sprzęgów + case 1: + { + CabActive = 1; + break; + } + case -1: + { + CabActive = -1; + break; + } + default: + { + CabActive = 0; // gdy CValue1==0 + break; + } + } + if (pulleeMode) + { + // a vehicle prepared for hauling takes no cab, the command only passes through it + CabActive = 0; + } + DirAbsolute = DirActive * CabActive; + cabMaster = false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::speedControl) + { + if (EngineType == TEngineType::ElectricInductionMotor || speedCtrl) + SpeedCtrlValue = static_cast(round(CValue1)); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::speedControlParking) + { + SpeedCtrlUnit.Parking = static_cast(CValue1); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the train brake, the releaser and the emergency brake; returns whether the command is one of them +bool physics::Vehicle::RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::brake) // youBy - jak sie EP hamuje, to trza sygnal wyslac... + { + if (CValue1 < 0.001) + brakes.electrodynamic.emuWorking = true; + double temp1 = CValue1; + if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && brakes.electrodynamic.emuWorking) + temp1 = 0; + if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && brakes.electrodynamic.emuWorking) + temp1 = 0; + brakes.distributor->SetEPS(temp1); + TUHEX_StageActual = static_cast(CValue1); + TUHEX_Active = TUHEX_StageActual > 0; + if (CValue1 < 0.001) + brakes.electrodynamic.emuWorking = true; + // fBrakeCtrlPos:=BrakeCtrlPos; //to powinnno być w jednym miejscu, aktualnie w C++!!! + brakes.actualPressure = brakes.config.pressureTable[brakes.HandlePosition()]; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } // youby - odluzniacz hamulcow, przyda sie + else if (Command == VehicleCommand::brakeReleaser) + { + OK = BrakeReleaser(static_cast(Round(CValue1))); // samo się przesyła dalej + // OK:=SendCtrlToNext(command,CValue1,CValue2); //to robiło kaskadę 2^n + } + else if (Command == VehicleCommand::emergencyBrake) + { + if (RadiostopSwitch(floor(CValue1) == 1)) // YB: czy to jest potrzebne? + OK = true; + else + OK = false; + } + else + { + return false; + } + return true; +} + +// RunCommand() for the brake delays, the spring brake, the sand and the cab signalling; returns whether the command is one of them +bool physics::Vehicle::RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::brakeDelay) + { + if (auto const brakesetting = static_cast(std::floor(CValue1)); true == brakes.distributor->SetBDF(brakesetting)) + { + brakes.delaySetting = brakesetting; + OK = true; + } + else + { + OK = false; + } + SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::springBrakeActivate) + { + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) + { + brakes.spring.activate = CValue1 > 0; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + OK = true; + } + + else if (Command == VehicleCommand::sandbox) + { + OK = Sandbox(CValue1 == 1, range_t::local); + } + else if (Command == VehicleCommand::cabSignal) /*SHP,Indusi*/ + { // Ra: to powinno działać tylko w członie obsadzonym + SecuritySystem.set_cabsignal(); + // else OK:=false; + OK = true; // true, gdy można usunąć komendę + } + /*naladunek/rozladunek*/ + // TODO: have these commands leverage load exchange system instead + // TODO: CValue1 defines amount to load/unload + else + { + return false; + } + return true; +} + +// RunCommand() for the heating, the converter, the battery and the compressor; returns whether the command is one of them +bool physics::Vehicle::RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::heatingSwitch) + { + HeatingSwitch_(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::converterSwitch) /*NBMX*/ + { + converter.Switch(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::batterySwitch) /*NBMX*/ + { + // the battery of a vehicle prepared for hauling (PulleeMode) stays off + if (false == pulleeMode || CValue1 <= 0.0) + { + lowVoltage.SwitchBattery(CValue1 > 0.0); + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + // else if command='EpFuseSwitch' then {NBMX} + // begin + // if (CValue1=1) then EpFuse:=true + // else if (CValue1=0) then EpFuse:=false; + // OK:=SendCtrlToNext(command,CValue1,CValue2); + // end + else if (Command == VehicleCommand::compressorSwitch) /*NBMX*/ + { + CompressorSwitch(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::compressorPreset) + { + air.compressor.SetListPosition(static_cast(CValue1)); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the water, fuel and oil pumps and the water heater; returns whether the command is one of them +bool physics::Vehicle::RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::waterPumpBreakerSwitch) + { + /* + if( FuelPump.start_type != start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + */ + WaterPump.breaker = CValue1 == 1; + /* + } + */ + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::waterPumpSwitch) + { + + if (WaterPump.start_type != start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + WaterPump.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::waterPumpSwitchOff) + { + + if (WaterPump.start_type != start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + WaterPump.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::waterHeaterBreakerSwitch) + { + /* + if( FuelPump.start_type != start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + */ + WaterHeater.breaker = CValue1 == 1; + /* + } + */ + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::waterHeaterSwitch) + { + /* + if( FuelPump.start_type != start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + */ + WaterHeater.is_enabled = CValue1 == 1; + /* + } + */ + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::waterCircuitsLinkSwitch) + { + if (true == diesel.heat.auxiliary_water_circuit) + { + // can only link circuits if the vehicle has more than one of them + waterCircuitsLink = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::fuelPumpSwitch) + { + if (FuelPump.start_type != start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + FuelPump.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::fuelPumpSwitchOff) + { + if (FuelPump.start_type != start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + FuelPump.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::oilPumpSwitch) + { + if (OilPump.start_type != start_t::automatic) + { + // automatic pump ignores 'manual' state commands + OilPump.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::oilPumpSwitchOff) + { + if (OilPump.start_type != start_t::automatic) + { + // automatic pump ignores 'manual' state commands + OilPump.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the motor blowers and the compartment lights; returns whether the command is one of them +bool physics::Vehicle::RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::motorBlowersFrontSwitch) + { + if (MotorBlowers[VehicleEnd::front].start_type != start_t::manual && MotorBlowers[VehicleEnd::front].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[VehicleEnd::front].is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::motorBlowersFrontSwitchOff) + { + if (MotorBlowers[VehicleEnd::front].start_type != start_t::manual && MotorBlowers[VehicleEnd::front].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[VehicleEnd::front].is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::motorBlowersRearSwitch) + { + if (MotorBlowers[VehicleEnd::rear].start_type != start_t::manual && MotorBlowers[VehicleEnd::rear].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[VehicleEnd::rear].is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::motorBlowersRearSwitchOff) + { + if (MotorBlowers[VehicleEnd::rear].start_type != start_t::manual && MotorBlowers[VehicleEnd::rear].start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + MotorBlowers[VehicleEnd::rear].is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::compartmentLightsSwitch) + { + + if (CompartmentLights.start_type != start_t::automatic) + { + // automatic lights ignore 'manual' state commands + CompartmentLights.is_enabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::compartmentLightsSwitchOff) + { + + if (CompartmentLights.start_type != start_t::automatic) + { + // automatic lights ignore 'manual' state commands + CompartmentLights.is_disabled = CValue1 == 1; + } + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the line breaker, the relays and the pantographs; returns whether the command is one of them +bool physics::Vehicle::RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::mainSwitch) + { + MainSwitch_(CValue1 > 0.0); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::relayReset) + { + RelayReset(static_cast(CValue1), range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::pantographValve) // Winger 160204 + { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów + auto const inputend{(static_cast(CValue1) & 0x80) != 0 ? 1 : 0}; + auto const inputcab{(static_cast(CValue1) & 0x40) != 0 ? 1 : 0}; + auto const inputoperation{static_cast(CValue1) & ~(0x80 | 0x40)}; + auto const noswap{trainType == train_type::emu || trainType == train_type::et41}; + auto swap{false == noswap && Couplers[CValue2 == -1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)}; + if (auto const reversed{inputcab != (CabActive != -1 ? 1 : 0)}; reversed) + { + swap = !swap; + } // TODO: check whether this part has RL equivalent + OperatePantographValve(static_cast(swap ? 1 - inputend : inputend), static_cast(inputoperation), range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::pantographsValve) + { + OperatePantographsValve(static_cast(static_cast(CValue1)), range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::pantographsAllDown) + { + DropAllPantographs(CValue1 == 1, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::tractionMode) + { + TractionModeSwitch(CValue1 > 0.5 ? traction_mode::genset : traction_mode::catenary, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::gensetSwitch) + { + GensetSwitch(CValue1 > 0.5, range_t::local); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// RunCommand() for the doors and the departure signal; returns whether the command is one of them +bool physics::Vehicle::RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype, bool &OK) +{ + if (Command == VehicleCommand::doorPermit) + { + DoorPermitCommand(CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::doorOpen || Command == VehicleCommand::doorClose) /*NBMX*/ + { // Ra: uwzględnić trzeba jeszcze zgodność sprzęgów + DoorRemoteCommand(Command == VehicleCommand::doorOpen, CValue1, CValue2); + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::doorLock) + { + Doors.lock_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::doorStep) + { + Doors.step_enabled = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::doorMode) + { + Doors.remote_only = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else if (Command == VehicleCommand::departureSignal) + { + departureSignalOn = CValue1 == 1 ? true : false; + OK = SendCtrlToNext(Command, CValue1, CValue2, Couplertype); + } + else + { + return false; + } + return true; +} + +// the doors' permits, on the sides the command names: CValue1 the sides, negative to take the permit back, CValue2 the +// direction the command comes from +void physics::Vehicle::DoorPermitCommand(double const CValue1, double const CValue2) +{ + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; std::abs(static_cast(CValue1)) & rightside) + { + PermitDoors_(VehicleSide::right, CValue1 > 0); + } + if (std::abs(static_cast(CValue1)) & leftside) + { + PermitDoors_(VehicleSide::left, CValue1 > 0); + } +} + +// the doors opened or closed from afar on the sides the command names, unless they're only worked locally +void physics::Vehicle::DoorRemoteCommand(bool const Open, double const CValue1, double const CValue2) +{ + using enum control_t; + if (auto const doorcontrol{Open ? Doors.open_control : Doors.close_control}; + (doorcontrol != conductor && doorcontrol != driver && doorcontrol != mixed) || (false == lowVoltage.Is24vAvailable() && false == lowVoltage.Is110vAvailable())) + { + return; + } + auto const leftside{CValue2 > 0 ? 1 : 2}; + if (auto const rightside{3 - leftside}; static_cast(CValue1) & rightside) + { + Doors.instances[VehicleSide::right].remote_open = Open; + Doors.instances[VehicleSide::right].remote_close = false == Open; + } + if (static_cast(CValue1) & leftside) + { + Doors.instances[VehicleSide::left].remote_open = Open; + Doors.instances[VehicleSide::left].remote_close = false == Open; + } +} + +namespace +{ + +// the number of SetDamage on the set of the damage, as SetFlag() did on the number: a positive one adds its values, a +// negative one takes them away where all of them are there; returns whether it changed the set +bool setOrClear(DamageSet &damage, int const number) +{ + if (number > 0) + { + return damage.Set(DamageSet::FromBits(number)); + } + if (number < 0) + { + return damage.Clear(DamageSet::FromBits(-number)); + } + return false; +} + +} // namespace + +// RunCommand() for the load and the damage; returns whether the command is one of them +bool physics::Vehicle::RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view const Argument, bool &OK) +{ + if (Command == VehicleCommand::load) + { + OK = false; // będzie powtarzane aż się załaduje + if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist + && maxLoad > 0 && loadAmount < maxLoad * (1.0 + OverLoadFactor) && Distance(location, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) + { // ten peron/rampa + + auto const loadname{ToLower(std::string{Argument})}; + if (loadAmount == 0.f) + { + AssignLoad(loadname); + } + OK = LoadingDone(LoadSpeed, + loadname); // zmienia loadStatus + } + else + { + // no loading can be done if conditions aren't met + LastLoadChangeTime = 0.0; + } + } + else if (Command == VehicleCommand::unload) + { + OK = false; // będzie powtarzane aż się rozładuje + if (Vel < 0.1 // tolerance margin for small vehicle movements in the consist + && loadAmount > 0 // czy jest co rozladowac? + && Distance(location, CommandIn.Location, Dim, Dim) < (CValue2 > 1.0 ? CValue2 : 10.0)) + { // ten peron + /*mozna to rozladowac*/ + OK = LoadingDone(-1.f * LoadSpeed, ToLower(std::string{Argument})); + } + else + { + // no loading can be done if conditions aren't met + LastLoadChangeTime = 0.0; + } + } + else if (Command == VehicleCommand::setDamage) + { + if (CValue2 == 1) + OK = setOrClear(DamageFlag, static_cast(floor(CValue1))); + if (CValue2 == -1) + { + auto const derailed{DamageFlag.HasAll(VehicleDamage::derailed)}; + OK = setOrClear(DamageFlag, static_cast(-floor(CValue1))); + // taking the derailment off puts the vehicle back on the rails, with what the criteria of derailment held + if (derailed && false == DamageFlag.HasAll(VehicleDamage::derailed)) + rerail(); + } + } + else + { + return false; + } + return true; +} + +// ************************************************************************************************* +// Q: 20160714 +// Uruchamia funkcję RunCommand aż do skutku. Jeśli będzie pozytywny to kasuje komendę. +// ************************************************************************************************* +bool physics::Vehicle::RunInternalCommand() +{ + bool OK; + + if (CommandIn.Command != VehicleCommand::none) + { + OK = RunCommand(CommandIn.Command, CommandIn.Value1, CommandIn.Value2, CommandIn.couplings, CommandIn.Argument); + if (OK) + { + + CommandIn.Command = VehicleCommand::none; // kasowanie bo rozkaz wykonany + CommandIn.Text.clear(); + CommandIn.Argument.clear(); + CommandIn.Value1 = 0; + CommandIn.Value2 = 0; + CommandIn.couplings = {}; + CommandIn.Location.X = 0; + CommandIn.Location.Y = 0; + CommandIn.Location.Z = 0; + switch_physics(true, wake_cause::command); + } + } + else + OK = false; + return OK; +} diff --git a/physics/components/controllers.cpp b/physics/components/controllers.cpp new file mode 100644 index 000000000..364feb8be --- /dev/null +++ b/physics/components/controllers.cpp @@ -0,0 +1,1428 @@ +/* +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 master and the secondary controllers, the automatic relay and the camshaft, the integrated controller, the speed control + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" +#include "physics/components/drive.h" + + +// ************************************************************************************************* +// queuedEU +// ************************************************************************************************* + +// ************************************************************************************************* +// Q: 20160710 +// zwiększenie nastawinika +// ************************************************************************************************* + +bool physics::Vehicle::IncMainCtrl(int CtrlSpeed) +{ + // basic fail conditions: + if (MainCtrlPosNo <= 0 || CabActive == 0) + { + // nie ma sterowania + return false; + } + if (trainType == train_type::et22 && scndCtrlPos != 0) + { + // w ET22 nie da się kręcić nastawnikiem przy włączonym boczniku + return false; + } + if (trainType == train_type::emu && DirActive == 0) + { + // w EZT nie da się załączyć pozycji bez ustawienia kierunku + return false; + } + + bool OK = false; + if (mainCtrlPos < MainCtrlPosNo) + { + OK = IncMainCtrlByEngine(CtrlSpeed); + } + else + { // mainCtrlPos>=MainCtrlPosNo + if (true == CoupledCtrl) + { + // wspólny wał nastawnika jazdy i bocznikowania + if (scndCtrlPos < scndCtrlPosNo) + { // 3<3 -> false + ++scndCtrlPos; + OK = true; + } + else + { + OK = false; + } + } + } + + if (true == OK) + { + ScndCtrlResistiveLockCheck(); // e.g. from the last series position on to the resistive parallel ones + SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? + SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); + } + + // hunter-101012: poprawka + // poprzedni warunek byl niezbyt dobry, bo przez to przy trzymaniu + + // styczniki tkwily na tej samej pozycji (LastRelayTime byl caly czas 0 i rosl + // po puszczeniu plusa) + + if (OK) + { + if (delayCtrlFlag) + { + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay && mainCtrlPos == 1) + lineContactors.RestartSwitchTimer(); + } + else if (lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); + } + return OK; +} + +// a notch up, as the kind of the engine takes it; returns whether the controller moved +bool physics::Vehicle::IncMainCtrlByEngine(int const CtrlSpeed) +{ + return Drive().IncreaseMainController(*this, CtrlSpeed); +} + +// a notch up of the series motors' controller: CtrlSpeed over 1 runs it to the first position without resistors; +// returns whether it moved as asked +bool physics::Vehicle::IncMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (DirActive == 0) + { + return false; + } + + if (CtrlSpeed > 1) + { + // szybkie przejœcie na bezoporow¹ + if (trainType == train_type::et40) + { + return false; // this means ET40 won't react at all to fast acceleration command. should it issue just IncMainCtrl(1) instead? + } + while (RList[mainCtrlPos].R > 0.0 && IncMainCtrl(1)) + { + // all work is done in the loop header + } + OK = false; // shouldn't this be part of the loop above? + // if (TrainType=train_type::et40) then + // while Abs (Im)>IminHi do + // dec(mainCtrlPos); + // OK:=false ; + } + else + { // CtrlSpeed == 1 + ++mainCtrlPos; + OK = true; + if (Imax == imaxHi && RList[mainCtrlPos].Bn > 1) + { + /* NOTE: disabled, relay configuration was moved to compute_movement_ + if( true == MaxCurrentSwitch( false )) { + // wylaczanie wysokiego rozruchu + SetFlag( soundFlag, sound::relay ); + } + */ + if (trainType == train_type::et42) + { + --mainCtrlPos; + OK = false; + } + } + // + // if (TrainType == "et40") + // if (Abs(Im) > IminHi) + // { + // mainCtrlPos--; //Blokada nastawnika po przekroczeniu minimalnego pradu + // OK = false; + // } + //} + } + + if (trainType == train_type::et42 && true == brakes.electrodynamic.on && mainCtrlPos > 20) + { + mainCtrlPos = 20; + OK = false; + } + return OK; +} + +// ***************************************************************************** +// Q: 20160710 +// zmniejszenie nastawnika +// ***************************************************************************** +bool physics::Vehicle::DecMainCtrl(int CtrlSpeed) +{ + bool OK = false; + // basic fail conditions: + if (MainCtrlPosNo <= 0 || CabActive == 0) + { + // nie ma sterowania + OK = false; + } + else if (CtrlSpeed == 0) + { + return false; + } + else + { + // TBD, TODO: replace with mainctrlpowerpos() check? + if (mainCtrlPos > 0) + { + if (trainType != train_type::et22 || scndCtrlPos == 0) // Ra: ET22 blokuje nastawnik przy boczniku + { + if (CoupledCtrl && scndCtrlPos > 0) + { + scndCtrlPos--; // wspolny wal + OK = true; + } + else + OK = DecMainCtrlByEngine(CtrlSpeed); + } + } + else if (EngineType == TEngineType::WheelsDriven) + OK = AddPulseForce(-CtrlSpeed); + else + OK = false; + + if (OK) + { + ScndCtrlResistiveLockCheck(); // the shunt drops when the master controller leaves a resistance-free position + /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); // hmmmm...???!!! + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); + } + } + // if OK then LastRelayTime:=0; + // hunter-101012: poprawka + if (OK) + { + if (delayCtrlFlag) + { + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay) + lineContactors.RestartSwitchTimer(); + } + else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) + lineContactors.RestartSwitchTimer(); + } + return OK; +} + +// a notch down, as the kind of the engine takes it; returns whether the controller moved +bool physics::Vehicle::DecMainCtrlByEngine(int const CtrlSpeed) +{ + return Drive().DecreaseMainController(*this, CtrlSpeed); +} + +// a notch down of the series motors' controller: CtrlSpeed over 1 runs it down to the first position without resistors +bool physics::Vehicle::DecMainCtrlSeriesMotor(int const CtrlSpeed) +{ + bool OK = false; + if (CtrlSpeed == 1) /*and (scndCtrlPos=0)*/ + { + mainCtrlPos--; + // if (mainCtrlPos=0) and (scndCtrlPos=0) and + // (TrainType<>train_type::et40)and(TrainType<>train_type::ep05) then + // StLinFlag:=false; + // if (mainCtrlPos=0) and (TrainType<>train_type::et40) and + // (TrainType<>train_type::ep05) then + // MainCtrlActualPos:=0; //yBARC: co to tutaj robi? ;) + OK = true; + } + else if (CtrlSpeed > 1) /*and (scndCtrlPos=0)*/ + { + OK = true; + if (RList[mainCtrlPos].R == 0) // Q: tu zrobilem = ;] + DecMainCtrl(1); + while (RList[mainCtrlPos].R > 0 && DecMainCtrl(1)) + ; // takie chamskie, potem poprawie} + } + return OK; +} + +bool physics::Vehicle::IsMainCtrlActualNoPowerPos() const +{ + // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems + return MainCtrlActualPos <= MainCtrlNoPowerPos(); +} + +bool physics::Vehicle::IsMainCtrlNoPowerPos() const +{ + // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems + return mainCtrlPos <= MainCtrlNoPowerPos(); +} + +bool physics::Vehicle::IsMainCtrlMaxPowerPos() const +{ + // TODO: wrap controller pieces into a class for potential specializations, similar to brake subsystems + return mainCtrlPos == MainCtrlPosNo; +} + +int physics::Vehicle::MainCtrlNoPowerPos() const +{ + + switch (EIMCtrlType) + { + case 1: + { + return 3; + } + case 2: + { + return 3 + EIMCtrlEmergencyPositions(); + } + case 3: + { + return UniCtrlNoPowerPos; + } + default: + { + return 0; + } + } +} + +int physics::Vehicle::MainCtrlActualPowerPos() const +{ + + return MainCtrlActualPos - MainCtrlNoPowerPos(); +} + +int physics::Vehicle::MainCtrlPowerPos() const +{ + + return mainCtrlPos - MainCtrlNoPowerPos(); +} + +int physics::Vehicle::EIMCtrlEmergencyPositions() const +{ + return (EIMCtrlType == 2 && eimCtrlMainEmergency) ? 1 : 0; +} + +bool physics::Vehicle::IsMainCtrlEmergencyPos() const +{ + return mainCtrlPos < EIMCtrlEmergencyPositions(); +} + +int physics::Vehicle::MainCtrlPosForCoupled() const +{ + // the emergency brake itself reaches the train through the brake pipe, vented by the vehicle driven from + return std::max(0, mainCtrlPos - EIMCtrlEmergencyPositions()); +} + +int physics::Vehicle::MainCtrlPosFromCoupled(int const Position) const +{ + return Position + EIMCtrlEmergencyPositions(); +} + +// ************************************************************************************************* +// Q: 20160710 +// zwiększenie bocznika +// ************************************************************************************************* +bool physics::Vehicle::IncScndCtrl(int CtrlSpeed) +{ + bool OK = false; + + if (brakes.electrodynamic.on && trainType == train_type::et42 && CabActive != 0 && IsMainCtrlNoPowerPos() && scndCtrlPos == 0) + { + OK = DynamicBrakeSwitch(false); + } + else if (scndCtrlPosNo > 0 && CabActive != 0 && !(trainType == train_type::et42 && (Imax == imaxHi || (brakes.electrodynamic.on && MainCtrlPowerPos() > 0)))) + { + // if (RList[mainCtrlPos].R=0) and (mainCtrlPos>0) and (scndCtrlPos 1) + { + scndCtrlPos = scndCtrlPosNo; // takie chamskie, potem poprawie + } + OK = true; + } + } + else // nie mozna zmienic + OK = false; + if (OK) + { + /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); + } + } + else // nie ma sterowania + OK = false; + // if OK then LastRelayTime:=0; + // hunter-101012: poprawka + if (OK && lineContactors.TimeSinceSwitch() > CtrlDelay) + lineContactors.RestartSwitchTimer(); + + if (OK && EngineType == TEngineType::ElectricInductionMotor && scndCtrlPosNo == 1 && mainCtrlPos > 0) + { + SpeedCtrlValue = Vel; + if (EIMCtrlType == 0 && (SpeedCtrlAutoTurnOffFlag & 1) == 1) + { + MainCtrlActualPos = mainCtrlPos; + } + SpeedCtrlUnit.IsActive = true; + } + + if (OK && speedCtrl && scndCtrlPos == 1 && EngineType == TEngineType::DieselEngine) + { + // NOTE: round() already adds 0.5, are the ones added here as well correct? + SpeedCtrlValue = static_cast(Round(Vel)); + SpeedCtrlUnit.IsActive = true; + } + + return OK; +} + +// ************************************************************************************************* +// Q: 20160710 +// zmniejszenie bocznika +// ************************************************************************************************* +bool physics::Vehicle::DecScndCtrl(int CtrlSpeed) +{ + bool OK = false; + + if (IsMainCtrlNoPowerPos() && CabActive != 0 && trainType == train_type::et42 && scndCtrlPos == 0 && !brakes.electrodynamic.on && CtrlSpeed == 1) + { + // Ra: AI wywołuje z CtrlSpeed=2 albo gdy scndCtrlPos>0 + OK = DynamicBrakeSwitch(true); + } + else if (scndCtrlPosNo > 0 && CabActive != 0) + { + if (scndCtrlPos > 0 && !CoupledCtrl && (EngineType != TEngineType::DieselElectric || !autoRelayFlag) && !IsScndCtrlLockedByMainCtrl()) + { + if (CtrlSpeed == 1) + { + scndCtrlPos--; + } + else if (CtrlSpeed > 1) + { + scndCtrlPos = 0; // takie chamskie, potem poprawie + } + OK = true; + } + else + OK = false; + if (OK) + { + /*OK:=*/SendCtrlToNext(VehicleCommand::mainController, MainCtrlPosForCoupled(), CabActive); //??? + /*OK:=*/SendCtrlToNext(VehicleCommand::secondaryController, scndCtrlPos, CabActive); + } + } + else + OK = false; + // if OK then LastRelayTime:=0; + // hunter-101012: poprawka + if (OK && lineContactors.TimeSinceSwitch() > CtrlDownDelay) + lineContactors.RestartSwitchTimer(); + + if (OK && EngineType == TEngineType::ElectricInductionMotor && scndCtrlPosNo == 1) + { + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + } + + if (OK && speedCtrl && scndCtrlPos == 0 && EngineType == TEngineType::DieselEngine) + { + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + } + + return OK; +} + +bool physics::Vehicle::IsScndCtrlLockedByMainCtrl() const +{ + // ET21, ET22, EP09: the field shunting engages only on the resistance-free positions of the master controller (eu07/maszyna#402) + return ScndCtrlResistiveLock && (IsMainCtrlNoPowerPos() || RList[mainCtrlPos].R >= 0.01); +} + +void physics::Vehicle::ScndCtrlResistiveLockCheck() +{ + // the shunt controller, locked in both directions on zero and the resistive positions, would otherwise stay engaged there once the + // master controller is taken back (or set from elsewhere, e.g. by the AI or another vehicle of the consist) with the shunt on + if (scndCtrlPos > 0 && !CoupledCtrl && IsScndCtrlLockedByMainCtrl()) + { + scndCtrlPos = 0; + } +} + +int physics::Vehicle::GetVirtualScndPos() const +{ + if (trainType == train_type::et42 && brakes.electrodynamic.on && !scndCtrlPos) + return -1; + return scndCtrlPos; +} + +bool physics::Vehicle::IsScndCtrlNoPowerPos() const +{ + // TODO: refine the check on account of potential electric series vehicles with speed control + return scndCtrlPos == 0 || true == speedCtrl; +} + +bool physics::Vehicle::IsScndCtrlMaxPowerPos() const +{ + // TODO: refine the check on account of potential electric series vehicles with speed control + return scndCtrlPos == scndCtrlPosNo || true == speedCtrl; +} + +// ************************************************************************************************* +// Q: 20160713 +// Włączenie / wyłączenie automatycznego rozruchu +// ************************************************************************************************* +bool physics::Vehicle::AutoRelaySwitch(bool State) +{ + bool ARS; + if (autoRelayType == 2 && autoRelayFlag != State) + { + autoRelayFlag = State; + ARS = true; + SendCtrlToNext(VehicleCommand::autoRelaySwitch, int(State), CabActive); + } + else + ARS = false; + + return ARS; +} + +// ************************************************************************************************* +// Q: 20160724 +// Sprawdzenie warunków pracy automatycznego rozruchu +// ************************************************************************************************* + +bool physics::Vehicle::AutoRelayCheck(void) +{ + bool OK = false; // b:int; + + auto const motorconnectorsoff{false == MotorConnectorsCheck()}; + + // Ra 2014-06: dla SN61 nie działa prawidłowo + // yBARC - rozlaczenie stycznikow liniowych + if (motorconnectorsoff || (HasCamshaft ? IsMainCtrlActualNoPowerPos() : IsMainCtrlNoPowerPos())) + { + lineContactors.Open(); + if (false == brakes.electrodynamic.on) + { + Im = 0; + Itot = 0; + ResistorsFlag = false; + } + } + + // sprawdzenie wszystkich warunkow (AutoRelayFlag, AutoSwitch, Im 0 || scndCtrlPos > 0) && (!CoupledCtrl || RList[MainCtrlActualPos].Relay == mainCtrlPos)) + { // zmieniaj scndctrlactualpos + OK = AutoRelayShuntStep(ARFASI2); + } + else + { // zmieniaj mainctrlactualpos + OK = AutoRelayMainStep(ARFASI); + } + } + else // not StLinFlag + { + OK = AutoRelayLineContactorsStep(motorconnectorsoff); + } + if (OK) + lineContactors.RestartSwitchTimer(); + + return OK; + } +} + +// a step of the shunt field on a position without resistors, up or down to the second controller +bool physics::Vehicle::AutoRelayShuntStep(bool const ARFASI2) +{ + bool OK = false; + // scnd bez samoczynnego rozruchu + if (ScndCtrlActualPos < scndCtrlPos) + { + if (lineContactors.TimeSinceSwitch() > CtrlDelay && ARFASI2) + { + ++ScndCtrlActualPos; + SetFlag(soundFlag, sound::shuntfield); + OK = true; + } + } + else if (ScndCtrlActualPos > scndCtrlPos) + { + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay && trainType != train_type::emu) + { + --ScndCtrlActualPos; + SetFlag(soundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main controller's relays, up or down to its position, or the shunt field off on the resistors +bool physics::Vehicle::AutoRelayMainStep(bool const ARFASI) +{ + bool OK = false; + // running backwards, the motors don't get joined in more branches than allowed (the series connection + // alone, usually); the camshaft still goes back down from there (eu07/maszyna#393: it stayed where it + // was, the line contactors closed, whatever the driver did with the master controller) + auto const backwardslimit{DirActive < 0 && trainType != train_type::pseudodiesel && RList[MainCtrlActualPos + 1].Bn > BackwardsBranchesAllowed}; + // main bez samoczynnego rozruchu + if (false == backwardslimit && MainCtrlActualPos < std::size(RList) - 1 // crude guard against running out of current fixed table + && (RList[MainCtrlActualPos].Relay < mainCtrlPos || (RList[MainCtrlActualPos + 1].Relay == mainCtrlPos && MainCtrlActualPos < RlistSize) || + (trainType == train_type::et22 && delayCtrlFlag))) + { + OK = AutoRelayMainUp(ARFASI); + } + else if (RList[MainCtrlActualPos].Relay > mainCtrlPos) + { + OK = AutoRelayMainDown(); + } + else if (RList[MainCtrlActualPos].R > 0 && ScndCtrlActualPos > 0) + { + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) + { + --ScndCtrlActualPos; // boczniki nie dzialaja na poz. oporowych + SetFlag(soundFlag, sound::shuntfield); + OK = true; + } + } + else + OK = false; + return OK; +} + +// a step of the main relays up to the controller's position, at once to the parallel position without resistors +// on a fast serial circuit (303E); returns whether the relays moved, never into parallel with the overload relay high +bool physics::Vehicle::AutoRelayMainUp(bool const ARFASI) +{ + bool OK = false; + // prevent switch to parallel mode if motor overload relay is set to high threshold mode + if (IsMotorOverloadRelayHighThresholdOn() && RList[MainCtrlActualPos + 1].Bn > 1) + { + return false; + } + + if (RList[mainCtrlPos].R == 0 && mainCtrlPos > 0 && mainCtrlPos != MainCtrlPosNo && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=mainCtrlPos; //hunter-111012: + ++MainCtrlActualPos; + if (mainCtrlPos - MainCtrlActualPos == 1) + { + // HACK: ensure we play only single sound of basic relays for entire trasition; return false + // for all but last step despite configuration change, to prevent playback of the basic relay sound + // TBD, TODO: move the basic sound event here and enable it with call parameter + OK = true; + } + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(soundFlag, sound::parallel | sound::loud); + OK = true; + } + } + else if (lineContactors.TimeSinceSwitch() > CtrlDelay && ARFASI) + { + OK = AutoRelayMainNotchUp(); + } + return OK; +} + +// a notch up of the main relays after their delay, through the group switch of the ET22, and the sounds of the +// parallel positions; returns whether they moved +bool physics::Vehicle::AutoRelayMainNotchUp() +{ + bool OK = false; + // WriteLog("LRT = " + FloatToStr(LastRelayTime) + ", " + + // FloatToStr(CtrlDelay)); + if (trainType == train_type::et22 && mainCtrlPos > 1 && (RList[MainCtrlActualPos].Bn < RList[MainCtrlActualPos + 1].Bn || delayCtrlFlag)) + { + // et22 z walem grupowym + if (!delayCtrlFlag) // najpierw przejscie + { + ++MainCtrlActualPos; + delayCtrlFlag = true; // tryb przejscia + OK = true; + } + else if (lineContactors.TimeSinceSwitch() > 4 * CtrlDelay) // przejscie + { + + delayCtrlFlag = false; + OK = true; + } + /* + else + ; + */ + } + else // nie ET22 z wałem grupowym + { + ++MainCtrlActualPos; + OK = true; + } + //--------- + // hunter-111211: poprawki + if (MainCtrlActualPos > 0) + { + if (RList[MainCtrlActualPos].R == 0 && MainCtrlActualPos != MainCtrlPosNo) + { + // wejscie na bezoporowa + SetFlag(soundFlag, sound::parallel | sound::loud); + } + else if (RList[MainCtrlActualPos].R > 0 && RList[MainCtrlActualPos - 1].R == 0) + { + // wejscie na drugi uklad + SetFlag(soundFlag, sound::parallel); + } + } + return OK; +} + +// a step of the main relays down to the controller's position; returns whether they moved +bool physics::Vehicle::AutoRelayMainDown() +{ + bool OK = false; + if (RList[mainCtrlPos].R == 0 && mainCtrlPos > 0 && !(mainCtrlPos == MainCtrlPosNo) && FastSerialCircuit == 1) + { + // szybkie wchodzenie na bezoporowa (303E) + // MainCtrlActualPos:=mainCtrlPos; //hunter-111012: + --MainCtrlActualPos; + OK = true; + if (RList[MainCtrlActualPos].R == 0) + { + SetFlag(soundFlag, sound::parallel); + } + } + else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) + { + if (trainType != train_type::emu) // tutaj powinien być tryb sterowania wałem + { + --MainCtrlActualPos; + OK = true; + } + // hunter-111211: poprawki + if (MainCtrlActualPos > 0 && RList[MainCtrlActualPos].R == 0) + { + // dzwieki schodzenia z bezoporowej} + SetFlag(soundFlag, sound::parallel); + } + } + return OK; +} + +// the line contactors closed at the first position, or, open, the camshaft run back to zero +bool physics::Vehicle::AutoRelayLineContactorsStep(bool const motorconnectorsoff) +{ + bool OK = false; + // ybARC - zalaczenie stycznikow liniowych + if (false == motorconnectorsoff && MainCtrlActualPos == 0 && (trainType == train_type::emu || HasCamshaft ? MainCtrlPowerPos() > 0 : MainCtrlPowerPos() == 1)) + { + + delayCtrlFlag = true; + if (lineContactors.TimeSinceSwitch() >= initialCtrlDelay) + { + lineContactors.Close(); + MainCtrlActualPos = 1; + delayCtrlFlag = false; + SetFlag(soundFlag, sound::relay | sound::loud); + OK = true; + } + } + else + { + delayCtrlFlag = false; + } + + if (false == lineContactors.IsClosed() && (MainCtrlActualPos > 0 || ScndCtrlActualPos > 0)) + { + OK |= CamshaftRunDown(); + } + return OK; +} + +// the camshaft, the line contactors open, run back to its zero position a step at a time, or at once without one; +// returns whether it moved +bool physics::Vehicle::CamshaftRunDown() +{ + bool OK = false; + + if (CoupledCtrl) + { + + if (trainType == train_type::emu) + { + OK = CamshaftRunDownEMU(); + } + else if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) // wal kulakowy dwukierunkowy + { + if (ScndCtrlActualPos > 0) + { + --ScndCtrlActualPos; + SetFlag(soundFlag, sound::shuntfield); + } + else + { + --MainCtrlActualPos; + } + OK = true; + } + } + else if (HasCamshaft) + { + // wal kulakowy dwukierunkowy + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) + { + if (MainCtrlActualPos > 0) + { + --MainCtrlActualPos; + } + ScndCtrlActualPos = 0; + OK = true; + } + } + else + { + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + OK = true; + } + return OK; +} + +// the one way camshaft of the EN57 run on to its end and round to zero; returns whether it moved +bool physics::Vehicle::CamshaftRunDownEMU() +{ + bool OK = false; + // EN57 wal jednokierunkowy calosciowy + if (MainCtrlActualPos == 1) + { + + MainCtrlActualPos = 0; + OK = true; + } + else + { + + if (lineContactors.TimeSinceSwitch() > CtrlDownDelay) + { + + if (MainCtrlActualPos < RlistSize) + { + // dojdz do konca + ++MainCtrlActualPos; + } + else if (ScndCtrlActualPos < scndCtrlPosNo) + { + // potem boki + ++ScndCtrlActualPos; + SetFlag(soundFlag, sound::shuntfield); + } + else + { + // i sie przewroc na koniec + MainCtrlActualPos = 0; + ScndCtrlActualPos = 0; + } + OK = true; + } + } + return OK; +} + +bool physics::Vehicle::MotorConnectorsCheck() +{ + + // hunter-111211: wylacznik cisnieniowy + // (on some vehicles it watches the brake pipe alone) + protection.UpdatePressureSwitch(brakes.cylinderPressure, brakePipe.Pressure()); + + if (true == protection.PressureSwitchTripped()) + { + return false; + } + + // a line breaker closed ahead of the pantographs holds without voltage; what cuts the motors off there is its + // undervoltage relay, which elsewhere opens the line breaker + auto const undervoltage{lineBreaker.config.pantographsRequireIt && false == protection.UndervoltageHolds()}; + + auto const connectorsoff{false == lineBreaker.IsClosed() || undervoltage || true == FuseFlag || true == lineContactors.IsForcedOpen() || DirActive == 0}; + + return false == connectorsoff && LineContactorsInterlockReleased(); +} + +bool physics::Vehicle::LineContactorsInterlockReleased() const +{ + switch (lineContactors.config.interlock) + { + case line_contactors_interlock::converter: + // the converter of this very vehicle, not the 110 V of the trainset: a section with its fans off doesn't start + return converter.IsRunning(); + case line_contactors_interlock::motor_blowers: + return std::ranges::all_of(MotorBlowers, [this](auto const &Blower) { + if (Blower.min_start_velocity < 0) + { + return Blower.is_active; + } + // a blower which starts with the speed and the motor current (MotorBlowersStartVelocity) can't run before + // the contactors close, nor after a stop longer than it keeps running for: it's enough that it's + // switched on and has power, so it starts once the vehicle moves + return MotorBlowerPowerIsAvailable(Blower) && false == Blower.is_disabled && (Blower.start_type == start_t::manual ? Blower.is_enabled : true); + }); + default: + return true; + } +} +namespace +{ + +// the setting of the universal controller one UniCtrlValStep further from Value towards Limit, never past it +double next_uc_step(double const Value, double const Limit, double const Step) +{ + constexpr double epsilon{1e-6}; + if (Limit > Value) + { + return std::min((std::floor(Value / Step + epsilon) + 1.0) * Step, Limit); + } + return std::max((std::ceil(Value / Step - epsilon) - 1.0) * Step, Limit); +} + +// the universal controller with UniCtrlValStep: the setting the continuous ramp got to (Ramped) turned into whole steps. +// a move of the controller onto a position which changes the setting makes one step at once, the ramp then one step each +// time it covers a step's length; the steps stop at the position's set value (or its bound, past which the ramp doesn't go) +double stepped_uc_value(double const Current, double const Ramped, TUniversalCtrl const &Position, double const Step, bool const Moved, double &Progress) +{ + if (Moved) + { + Progress = 0.0; + } + double const delta{Ramped - Current}; + if (std::abs(delta) < 1e-9) + { + Progress = 0.0; + return Ramped; + } + double limit{0.0}; + if (delta > 0.0) + { + limit = Position.SetCtrlVal > Current ? Position.SetCtrlVal : Position.MaxCtrlVal; + } + else + { + limit = Position.SetCtrlVal < Current ? Position.SetCtrlVal : Position.MinCtrlVal; + } + Progress = Moved ? Step : Progress + std::abs(delta); + double value{Current}; + bool reached{std::abs(value - limit) < 1e-9}; + while (!reached && Progress >= Step - 1e-9) + { + value = next_uc_step(value, limit, Step); + Progress -= Step; + reached = std::abs(value - limit) < 1e-9; + } + if (reached) + { + Progress = 0.0; + } + // added after the move to std::clamp: bounds given the other way round are put in order, as master did it + auto const [lowest, highest] = std::minmax(Position.MinCtrlVal, Position.MaxCtrlVal); + return std::clamp(value, lowest, highest); +} + +} // namespace + +void physics::Vehicle::CheckEIMIC(double dt) +{ + double offset = EIMCtrlAdditionalZeros ? 1.0 : 0.0; + double multiplier = (eimCtrlEmergency ? 1.0 : 0.0) + offset; + // gdy SplitEDPneumaticBrake jest wlaczone, sterowanie ujemne (hamowanie ED) bierzemy + // z osobnego nastawnika DynamicBrakeCtrl, a nie z hamulca pomocniczego (LocalBrake). + // Dodatkowo zapotrzebowanie ED jest ograniczone przez strefe Vh0..Vh1: powyzej Vh1 - pelny ED, + // pomiedzy Vh1 a Vh0 - liniowe zanikanie, ponizej Vh0 - zerowe (brak hamowania pneumatycznego + // jako uzupelnienia, poniewaz LocalBrake jest oddzielny i operuje wylacznie pneumatyka). + double brakeDemand = brakes.electrodynamic.splitFromPneumatic ? DynamicBrakeRatio() : LocalBrakeRatio(); + if (brakes.electrodynamic.splitFromPneumatic) + { + double const vh0 = inductionMotor.braking.offSpeed; + double const vh1 = inductionMotor.braking.fullSpeed; + if (vh1 > vh0 + 0.001) + { + double const vhRamp = std::clamp((Vel - vh0) / (vh1 - vh0), 0.0, 1.0); + brakeDemand *= vhRamp; + } + } + switch (EIMCtrlType) + { + case 0: + EIMICFromController(brakeDemand, offset, multiplier); + break; + case 1: + EIMICFromSteps(dt); + break; + case 2: + EIMICFromFourPositions(dt); + break; + case 3: + EIMICFromUniversalController(dt, brakeDemand); + break; + } + if (brakes.config.independentTraxx) + { + EIMICTraxxLocalBrake(dt); + } + + EIMICLimit(); +} + +// the controller (EIMCtrlType 0): the position of the main controller, or the analog one, or the brake asked +void physics::Vehicle::EIMICFromController(double const brakeDemand, double const offset, double const multiplier) +{ + eimic = brakeDemand > 0.01 ? -brakeDemand : eimicAnalog > 0.01 ? eimicAnalog : (double)mainCtrlPos / (double)MainCtrlPosNo; + if (EIMCtrlAdditionalZeros || eimCtrlEmergency) + { + if (eimic > 0.001) + eimic = std::max(0.002, eimic * (double)MainCtrlPosNo / ((double)MainCtrlPosNo - offset) - offset / ((double)MainCtrlPosNo - offset)); + if (eimic < -0.001 && brakes.config.driverValveType != TBrakeHandle::MHZ_EN57) + eimic = std::min(-0.002, eimic * (double)LocalBrakePosNo / ((double)LocalBrakePosNo - multiplier) + offset / ((double)LocalBrakePosNo - multiplier)); + } + if (eimic > 0.001 && SpeedCtrlUnit.IsActive) + eimic = std::max(eimic, SpeedCtrlUnit.MinPower); +} + +// EIMCtrlType 1: the positions B+ to TMax move the value at a steady pace +void physics::Vehicle::EIMICFromSteps(double dt) +{ + switch (mainCtrlPos) + { + case 0: // B+ + eimic -= std::clamp(1.0 + eimic, 0.0, dt * 0.14); // odejmuj do -1 + break; + case 1: // B + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + break; + case 2: // B- + case 3: // 0 + case 4: // T- + eimic -= std::clamp(0.0 + eimic, 0.0, dt * 0.14); // odejmuj do 0 + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 5: // T + eimic += std::clamp(0.0 - eimic, 0.0, dt * 0.14); // dodawaj do 0 + break; + case 6: // T+ + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1 + break; + case 7: // TMax + eimic += std::clamp(1.0 - eimic, 0.0, dt * 0.14); // dodawaj do 1, max + break; + default: + break; + } + if (mainCtrlPos >= 3 && eimic < 0) + eimic = 0; + if (mainCtrlPos <= 3 && eimic > 0) + eimic = 0; +} + +// EIMCtrlType 2: the positions 0 to 4 move the value towards -1, 0 or 1, from the controller's delay on; the +// emergency brake position below them, where the controller has one, brakes in full at once +void physics::Vehicle::EIMICFromFourPositions(double dt) +{ + if (IsMainCtrlEmergencyPos()) + { + // hamowanie nagle: pelne hamowanie od razu, przewod glowny oproznia UpdatePipePressure() + eimic = -1.0; + } + else if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > initialCtrlDelay) + { + double delta = MainCtrlActualPos == mainCtrlPos ? dt * CtrlDelay : 0.01; + // the positions below are those of the controller without the emergency brake position + switch (mainCtrlPos - EIMCtrlEmergencyPositions()) + { + case 0: + case 1: + eimic -= safe_clamp(1.0 + eimic, 0.0, delta); // odejmuj do -1 + if (eimic > 0) + eimic = 0; + break; + case 2: + eimic -= safe_clamp(0.0 + eimic, 0.0, delta); // odejmuj do 0 + break; + case 3: + eimic += safe_clamp(0.0 - eimic, 0.0, delta); // dodawaj do 0 + break; + case 4: + eimic += safe_clamp(1.0 - eimic, 0.0, delta); // dodawaj do 1 + if (eimic < 0) + eimic = 0; + break; + default: + break; + } + } + if (MainCtrlActualPos == mainCtrlPos) + lineContactors.AdvanceSwitchTimer(dt); + else + { + lineContactors.RestartSwitchTimer(); + MainCtrlActualPos = mainCtrlPos; + } +} + +// EIMCtrlType 3: the universal controller of UniCtrlList, with the train brake built in or not +void physics::Vehicle::EIMICFromUniversalController(double dt, double const brakeDemand) +{ + if (UniCtrlIntegratedBrakePNCtrl) + { + UniversalControllerTrainBrake(); + } + + if (MainCtrlActualPos != mainCtrlPos || lineContactors.TimeSinceSwitch() > initialCtrlDelay) + { + auto const &position{UniCtrlList[mainCtrlPos]}; + double ramped{eimic}; + ramped -= safe_clamp(-position.SetCtrlVal + ramped, 0.0, + MainCtrlActualPos == mainCtrlPos ? dt * position.SpeedDown : sign(position.SpeedDown) * 0.01); // odejmuj do X + ramped += safe_clamp(position.SetCtrlVal - ramped, 0.0, + MainCtrlActualPos == mainCtrlPos ? dt * position.SpeedUp : sign(position.SpeedUp) * 0.01); // dodawaj do X + ramped = safe_clamp(ramped, position.MinCtrlVal, position.MaxCtrlVal); + eimic = uniCtrlValStep > 0.0 ? stepped_uc_value(eimic, ramped, position, uniCtrlValStep, MainCtrlActualPos != mainCtrlPos, eimic_step_progress) : ramped; + } + if (MainCtrlActualPos == mainCtrlPos) + lineContactors.AdvanceSwitchTimer(dt); + else + { + lineContactors.RestartSwitchTimer(); + MainCtrlActualPos = mainCtrlPos; + } + if (brakes.distributor->GetEDBCP() > 0.3 && eimic < 0 && !uniCtrlIntegratedLocalBrakeCtrl) // when braking with pneumatic brake + eimic = 0; // shut off retarder + if (UniCtrlIntegratedBrakeCtrl == false && uniCtrlIntegratedLocalBrakeCtrl == false) + { + // w trybie SplitEDPneumaticBrake hamowanie ED przychodzi z osobnego nastawnika, + // LocalBrake operuje wylacznie pneumatycznym hamulcem lokomotywy + eimic = brakeDemand > 0.01 ? -brakeDemand : eimic; + } +} + +// the train brake built into the universal controller: the handle set to the controller's position, or the +// controller, at a brake handle moved alone, to the nearest position of the handle's +void physics::Vehicle::UniversalControllerTrainBrake() +{ + if (UniCtrlList[mainCtrlPos].mode != brakes.HandlePosition() && MainCtrlActualPos == mainCtrlPos) // there was no move of controller, but brake only + { + if (brakes.HandlePosition() < UniCtrlList[MainCtrlPosNo].mode) + BrakeLevelSet(UniCtrlList[MainCtrlPosNo].mode); // bottom clamping + if (brakes.HandlePosition() > UniCtrlList[0].mode) + BrakeLevelSet(UniCtrlList[0].mode); // top clamping + if (IsCabMaster()) + { + while (brakes.HandlePosition() > UniCtrlList[mainCtrlPos].mode) + DecMainCtrl(1); // find nearest position + while (brakes.HandlePosition() < UniCtrlList[mainCtrlPos].mode) + IncMainCtrl(1); // find nearest position + } + } + else // controller was moved + BrakeLevelSet(UniCtrlList[mainCtrlPos].mode); +} + +// the local brake of the TRAXX locomotives, by time: released, held or applied, which cuts the drive off +void physics::Vehicle::EIMICTraxxLocalBrake(double dt) +{ + if (LocalBrakeRatio() < 0.4) // pozycja 0, odhamowywanie + { + eim_localbrake -= dt * 0.17; + } + + if (LocalBrakeRatio() > 0.6) // pozycja 2, zahamowywanie + { + eim_localbrake += dt * 0.17; + eim_localbrake = std::max(eim_localbrake, brakes.cylinderPressure / brakes.config.maxCylinderPressure[0]); + } + else // pozycja 1, utrzymanie cisnienia + { + if (eim_localbrake < brakes.distributor->GetEDBCP() / brakes.config.maxCylinderPressure[0]) + eim_localbrake = 0; + } + eim_localbrake = std::clamp(eim_localbrake, 0.0, 1.0); + if (eim_localbrake > 0.04 && eimic > 0) + eimic = 0; +} + +// the value limited by the power, the spring brake, the pipe lock, the direction and the doors' permits +void physics::Vehicle::EIMICLimit() +{ + auto const eimicpowerenabled{(MainCircuitPowered() || Power == 0.0) && (!brakes.spring.isActive || !brakes.spring.cutsOffDrive) && !brakes.pipeLock.locked && DirAbsolute != 0}; + auto const eimicdoorenabled{(brakes.spring.isActive && brakes.spring.releasesParkingWithDoorOpen)}; + double eimic_max = 0.0; + if (Doors.instances[VehicleSide::left].open_permit == false && Doors.instances[VehicleSide::right].open_permit == false) + { + if (eimicpowerenabled) + { + eimic_max = 1.0; + } + else + { + eimic_max = 0.001; + } + } + else + { + if (eimicdoorenabled) + { + eimic_max = 0.001; + } + } + eimic = safe_clamp(eimic, -1.0, eimicpowerenabled ? eimic_max : 0.0); +} + +void physics::Vehicle::CheckSpeedCtrl(double dt) +{ + if (EIMCtrlType == 0) + { + SpeedCtrlUnit.DesiredPower = std::max(eimic, 0.0); + } + double accfactor = SpeedCtrlUnit.DesiredPower; + if (EIMCtrlType >= 2) + { + if (mainCtrlPos < MainCtrlPosNo - 2) + { + SpeedCtrlUnit.Standby = true; + } + if (mainCtrlPos > MainCtrlPosNo - 1) + { + SpeedCtrlUnit.Standby = false; + } + if (!SpeedCtrlUnit.BrakeIntervention && (brakes.distributor->GetEDBCP() > 0.4 || brakePipe.Pressure() < brakes.config.pipeHighPressure - 0.2)) + SpeedCtrlUnit.Standby = true; + if (EIMCtrlType >= 3 && UniCtrlList[mainCtrlPos].SpeedUp <= 0) + { + accfactor = 0.0; + eimicSpeedCtrlValue = 0; + } + } + if (SpeedCtrlUnit.IsActive) + { // speed control + if (true) + { + if (!SpeedCtrlUnit.Standby) + { + SpeedCtrlRegulator(dt, accfactor); + } + else + { + eimicSpeedCtrlValue = 0; + eimicSpeedCtrlIntegral = 0; + } + SpeedCtrlUnit.Parking = Vel == 0.0 && eimic <= 0 && EngineType != TEngineType::ElectricInductionMotor; + SendCtrlToNext(VehicleCommand::speedControlParking, SpeedCtrlUnit.Parking, CabActive); + } + else + { + if (vmax < 250) + eimicSpeedCtrlValue = std::clamp(0.5 * (SpeedCtrlValue - Vel), -1.0, 1.0); + else + eimicSpeedCtrlValue = std::clamp(0.5 * (SpeedCtrlValue * 2 - Vel), -1.0, 1.0); + } + if ((SpeedCtrlAutoTurnOffFlag & 2) == 2 && brakes.distributor->GetEDBCP() > 0.25) + { + SpeedCtrlSwitch(false); + SpeedCtrlUnit.IsActive = false; + } + } + else + { + eimicSpeedCtrlValue = 1; + eimicSpeedCtrlIntegral = 0; + SpeedCtrlUnit.Parking = false; + SendCtrlToNext(VehicleCommand::speedControlParking, SpeedCtrlUnit.Parking, CabActive); + } +} + +// the PI regulator of the speed control: the power asked of the drive, or its brake intervention, from the error of +// the speed; accfactor, the most power it may ask +void physics::Vehicle::SpeedCtrlRegulator(double dt, double const accfactor) +{ + if (SpeedCtrlUnit.ManualStateOverride && eimic > 0.0009) + eimic = 1.0; + double error = std::max(SpeedCtrlValue + SpeedCtrlUnit.Offset, 0.0) - Vel; + double factorP = error > 0 ? SpeedCtrlUnit.FactorPpos : SpeedCtrlUnit.FactorPneg; + double eSCP = std::clamp(factorP * error, -1.2, 1.0); // P module + bool retarder_not_work = EngineType != TEngineType::DieselEngine || Vel < SpeedCtrlUnit.BrakeInterventionVel; + if (eSCP < -1.0) + { + SpeedCtrlUnit.BrakeInterventionBraking = eSCP < -1.1 && retarder_not_work && eimicSpeedCtrlValue < -0.99 * SpeedCtrlUnit.DesiredPower; + eSCP = -1.0; + } + SpeedCtrlUnit.BrakeInterventionUnbraking = eSCP > 0.0 || Vel == 0.0; + if (abs(eSCP) < 0.999) + { + // TODO: check how to disable integral part when braking in smart way + // double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + double factorI = eimicSpeedCtrlIntegral >= 0 ? SpeedCtrlUnit.FactorIpos : SpeedCtrlUnit.FactorIneg; + eimicSpeedCtrlIntegral = safe_clamp(eimicSpeedCtrlIntegral + factorI * eSCP * dt, -1.0 + eSCP, 1.0 - eSCP); + } + else + { + eimicSpeedCtrlIntegral = 0; + } + auto const DesiredeimicSpeedCtrl{safe_clamp(eimicSpeedCtrlIntegral + eSCP, -SpeedCtrlUnit.DesiredPower, accfactor)}; + eimicSpeedCtrlValue = safe_clamp(DesiredeimicSpeedCtrl, eimicSpeedCtrlValue - SpeedCtrlUnit.PowerDownSpeed * dt, eimicSpeedCtrlValue + SpeedCtrlUnit.PowerUpSpeed * dt); + if (Vel < SpeedCtrlUnit.FullPowerVelocity) + { + eimicSpeedCtrlValue = std::min(eimicSpeedCtrlValue, SpeedCtrlUnit.InitialPower); + } + if (Vel < SpeedCtrlUnit.StartVelocity && mainCtrlPos < MainCtrlPosNo) + { + eimicSpeedCtrlValue = 0; + eimic = 0; + } +} + +bool physics::Vehicle::IsSpeedCtrlSeparate() const +{ + // no secondary controller, or one of these engines', which shunts the field of the traction motors (eu07/maszyna#69) + return speedCtrl && (scndCtrlPosNo == 0 || EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric); +} + +bool physics::Vehicle::IsSpeedCtrlEngaged() const +{ + return IsSpeedCtrlSeparate() ? SpeedCtrlUnit.IsActive : scndCtrlPos > 0; +} + +bool physics::Vehicle::SpeedCtrlSwitch(bool const State) +{ + if (false == IsSpeedCtrlSeparate()) + { + return State ? IncScndCtrl(1) : DecScndCtrl(2); + } + // its own switch, the secondary controller left to the field shunting + if (State) + { + if (CabActive == 0 || SpeedCtrlUnit.IsActive) + { + return false; + } + SpeedCtrlValue = static_cast(Round(Vel)); + SpeedCtrlUnit.IsActive = true; + return true; + } + auto const wasactive{SpeedCtrlUnit.IsActive}; + SpeedCtrlValue = 0; + SpeedCtrlUnit.IsActive = false; + if (wasactive && SpeedCtrlUnit.ManualStateOverride) + { + eimic = 0.0; + } + return wasactive; +} + +void physics::Vehicle::SpeedCtrlButton(int button) +{ + if (speedCtrl && IsSpeedCtrlEngaged()) + { + SpeedCtrlValue = SpeedCtrlButtons[button]; + } +} + +void physics::Vehicle::SpeedCtrlInc() +{ + if (speedCtrl && IsSpeedCtrlEngaged()) + { + double x = floor(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) + 1.0; + SpeedCtrlValue = std::min(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MaxVelocity); + } +} + +void physics::Vehicle::SpeedCtrlDec() +{ + if (speedCtrl && IsSpeedCtrlEngaged()) + { + double x = ceil(SpeedCtrlValue / SpeedCtrlUnit.VelocityStep) - 1.0; + SpeedCtrlValue = std::max(x * SpeedCtrlUnit.VelocityStep, SpeedCtrlUnit.MinVelocity); + } +} + +bool physics::Vehicle::SpeedCtrlPowerInc() +{ + if (!(speedCtrl && IsSpeedCtrlEngaged())) + return false; + + if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MaxPower) + return false; + + SpeedCtrlUnit.DesiredPower = std::min(SpeedCtrlUnit.DesiredPower + SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MaxPower); + return true; +} + +bool physics::Vehicle::SpeedCtrlPowerDec() +{ + if (!(speedCtrl && IsSpeedCtrlEngaged())) + return false; + + if (SpeedCtrlUnit.DesiredPower == SpeedCtrlUnit.MinPower) + return false; + + SpeedCtrlUnit.DesiredPower = std::max(SpeedCtrlUnit.DesiredPower - SpeedCtrlUnit.PowerStep, SpeedCtrlUnit.MinPower); + return true; +} diff --git a/physics/components/couplers.cpp b/physics/components/couplers.cpp new file mode 100644 index 000000000..1633375a6 --- /dev/null +++ b/physics/components/couplers.cpp @@ -0,0 +1,592 @@ +/* +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/. +*/ + +// attaching and detaching, the forces in the couplers and the automatic coupling + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + +// Ra: tu należy przenosić funcje z physics.pas, które nie są z niego wywoływane. +// Jeśli jakieś zmienne nie są używane w physics.pas, też można je przenosić. +// Przeniesienie wszystkiego na raz zrobiło by zbyt wielki chaos do ogarnięcia. + +const double dEpsilon = 0.01; // 1cm (zależy od typu sprzęgu...) + +double physics::Vehicle::Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2) +{ // zwraca odległość pomiędzy pojazdami (Loc1) i (Loc2) z uwzględnieneim ich długości (kule!) + return hypot(Loc2.X - Loc1.X, Loc1.Y - Loc2.Y) - 0.5 * (Dim2.L + Dim1.L); +}; + +double physics::Vehicle::CouplerDist(physics::Vehicle const *Left, physics::Vehicle const *Right) +{ // obliczenie odległości pomiędzy sprzęgami (kula!) + return Distance(Left->location, Right->location, Left->Dim, Right->Dim); // odległość pomiędzy sprzęgami (kula!) +}; + +bool physics::Vehicle::Attach(int ConnectNo, int ConnectToNr, physics::Vehicle *ConnectTo, CouplingSet CouplingType, bool Enforce, bool Audible) +{ // łączenie do swojego sprzęgu (ConnectNo) pojazdu (ConnectTo) stroną (ConnectToNr) + // Ra: zwykle wykonywane dwukrotnie, dla każdego pojazdu oddzielnie + // Ra: trzeba by odróżnić wymóg dociśnięcia od uszkodzenia sprzęgu przy podczepianiu AI do składu + + if (ConnectTo == nullptr || CouplingType == Coupling::none) + { + return false; + } + + auto &thiscoupler{Couplers[ConnectNo]}; + auto const otherend{ConnectToNr != 2 ? ConnectToNr : thiscoupler.ConnectedNr}; + auto &othercoupler = ConnectTo->Couplers[otherend]; + auto const distance{CouplerDist(this, ConnectTo) - (thiscoupler.adapter_length + othercoupler.adapter_length)}; + + + if (auto const couplercheck{Enforce || (distance <= dEpsilon && thiscoupler.type() != TCouplerType::NoCoupler && thiscoupler.type() == othercoupler.type())}; false == couplercheck) + { + return false; + } + + // no multiple-unit control between an electric and a diesel locomotive, whoever asks for it: the scenario, the AI + // or the player (eu07/maszyna#520) + if (auto const compatible{CompatibleCoupling(static_cast(ConnectNo), *ConnectTo, static_cast(otherend), CouplingType)}; compatible != CouplingType) + { + WriteLog(std::format("Vehicles \"{}\" and \"{}\" can't share their control, coupled without the control connection", Name, ConnectTo->Name)); + CouplingType = compatible; + if (CouplingType == Coupling::none) + { + return false; + } + } + + // stykaja sie zderzaki i kompatybilne typy sprzegow, chyba że łączenie na starcie + if (thiscoupler.CouplingFlag == Coupling::none) + { + // a new coupling: the play of the coupling as set up anew, without the stretch of the one before + thiscoupler.physics_state.couple(); + othercoupler.physics_state.couple(); + // jeśli wcześniej nie było połączone, ustalenie z której strony rysować sprzęg + thiscoupler.Render = true; // tego rysować + othercoupler.Render = false; // a tego nie + } + auto const couplingchange{CouplingType ^ thiscoupler.CouplingFlag}; + thiscoupler.Connected = ConnectTo; + thiscoupler.CouplingFlag = CouplingType; // ustawienie typu sprzęgu + if (ConnectToNr != 2) + { + thiscoupler.ConnectedNr = ConnectToNr; // 2=nic nie podłączone + } + othercoupler.Connected = this; + othercoupler.CouplingFlag = CouplingType; + othercoupler.ConnectedNr = ConnectNo; + + if (true == Audible && false == couplingchange.Empty()) + { + // set sound event flag + int soundflag{sound::none}; + std::vector> const soundmappings = {{Coupling::coupler, sound::attachcoupler}, {Coupling::brakeHose, sound::attachbrakehose}, + {Coupling::mainHose, sound::attachmainhose}, {Coupling::control, sound::attachcontrol}, + {Coupling::gangway, sound::attachgangway}, {Coupling::heating, sound::attachheating}}; + for (auto const &[mappingcoupling, mappingsound] : soundmappings) + { + if (couplingchange.HasAny(mappingcoupling)) + { + soundflag |= mappingsound; + } + } + SetFlag(thiscoupler.sounds, soundflag); + } + + return true; +} + +int physics::Vehicle::DettachStatus(int ConnectNo) +{ // Ra: sprawdzenie, czy odległość jest dobra do rozłączania + // powinny być 3 informacje: =0 sprzęg już rozłączony, <0 da się rozłączyć. >0 nie da się rozłączyć + if (!Couplers[ConnectNo].Connected) + return 0; // nie ma nic, to rozłączanie jest OK + if (false == Couplers[ConnectNo].CouplingFlag.HasAny(Coupling::coupler)) + return -Couplers[ConnectNo].CouplingFlag.Bits(); // hak nie połączony - rozłączanie jest OK + if (DamageFlag.HasAll(VehicleDamage::coupling)) + return -Couplers[ConnectNo].CouplingFlag.Bits(); // hak urwany - rozłączanie jest OK + // CouplerDist(ConnectNo); + if (Couplers[ConnectNo].type() != TCouplerType::Screw || Neighbours[ConnectNo].distance < 0.01) + return -Couplers[ConnectNo].CouplingFlag.Bits(); // można rozłączać, jeśli dociśnięty + return Neighbours[ConnectNo].distance > 0.2 ? -Couplers[ConnectNo].CouplingFlag.Bits() : Couplers[ConnectNo].CouplingFlag.Bits(); +}; + +bool physics::Vehicle::Dettach(int ConnectNo) +{ // rozlaczanie + + auto &thiscoupler{Couplers[ConnectNo]}; + auto &othervehicle{thiscoupler.Connected}; + auto &othercoupler{othervehicle->Couplers[thiscoupler.ConnectedNr]}; + + if (othervehicle == nullptr) + { + return true; + } // nie ma nic, to odczepiono + + auto couplingchange{thiscoupler.CouplingFlag}; // presume we'll uncouple all active flags + auto const couplingstate{DettachStatus(ConnectNo)}; // stan sprzęgu + if (couplingstate < 0) + { + // gdy scisniete zderzaki, chyba ze zerwany sprzeg (wirtualnego nie odpinamy z drugiej strony) + std::tie(othercoupler.Connected, othercoupler.ConnectedNr, othercoupler.CouplingFlag) = std::make_tuple(nullptr, -1, Coupling::none); + std::tie(thiscoupler.Connected, thiscoupler.ConnectedNr, thiscoupler.CouplingFlag) = std::make_tuple(nullptr, -1, Coupling::none); + } + else if (couplingstate > 0) + { // odłączamy węże i resztę, pozostaje sprzęg fizyczny, który wymaga dociśnięcia (z wirtualnym nic) + thiscoupler.CouplingFlag &= Coupling::coupler; + othercoupler.CouplingFlag &= Coupling::coupler; + } + // set sound event flag + couplingchange ^= thiscoupler.CouplingFlag; // remaining bits were removed from coupling + if (false == couplingchange.Empty()) + { + int soundflag{sound::detach}; // HACK: use detach flag to indicate removal of listed coupling + std::vector> const soundmappings = {{Coupling::coupler, sound::attachcoupler}, {Coupling::brakeHose, sound::attachbrakehose}, + {Coupling::mainHose, sound::attachmainhose}, {Coupling::control, sound::attachcontrol}, + {Coupling::gangway, sound::attachgangway}, {Coupling::heating, sound::attachheating}}; + for (auto const &[mappingcoupling, mappingsound] : soundmappings) + { + if (couplingchange.HasAny(mappingcoupling)) + { + soundflag |= mappingsound; + } + } + SetFlag(thiscoupler.sounds, soundflag); + } + + return couplingstate < 0; +}; + +// ************************************************************************************************* +// prędkość zbliżania się stykających się końców pojazdów przy zderzeniu, w km/h +// ************************************************************************************************* +double physics::Vehicle::CollisionVelocity(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const +{ + auto const velocitydifference{CouplerVelocityDifference(End, Other, OtherEnd)}; + // the front end closes in on the other vehicle when this one moves forward faster, the rear end when it's slower + return (End == VehicleEnd::front ? velocitydifference : -velocitydifference) * 3.6; // m/s -> km/h +} + +double physics::Vehicle::CouplerVelocityDifference(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const +{ + // V runs along the vehicle's own axis, towards its front; the other vehicle's velocity is turned around when the + // vehicles face each other (touch with the same ends) + return travelSpeed - Other.travelSpeed * DirPatch(End, OtherEnd); +} + +bool physics::Vehicle::AutomaticCouplingSafe(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const +{ + return false == Global.crash_damage || CollisionVelocity(End, Other, OtherEnd) <= SafeCollisionVelocity; +} +namespace +{ + + +// the kind of traction a vehicle's engine stands for, as far as its multiple-unit control goes +enum class traction_kind +{ + none, + electric, + diesel +}; + +traction_kind traction_of(TEngineType const Engine) +{ + switch (Engine) + { + case TEngineType::ElectricSeriesMotor: + case TEngineType::ElectricInductionMotor: + return traction_kind::electric; + case TEngineType::DieselEngine: + case TEngineType::DieselElectric: + return traction_kind::diesel; + default: + return traction_kind::none; + } +} + +} // namespace + +bool physics::Vehicle::ControlCouplingAllowed(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const +{ + if (false == Global.control_coupling_engine_check) + { + return true; + } + // the same control system named on both couplers is the vehicle authors' word that they work together + if (auto const &controltype{Couplers[End].control_type}; false == controltype.empty() && controltype == Other.Couplers[OtherEnd].control_type) + { + return true; + } + auto const traction{traction_of(EngineType)}; + auto const othertraction{traction_of(Other.EngineType)}; + return traction == traction_kind::none || othertraction == traction_kind::none || traction == othertraction; +} + +CouplingSet physics::Vehicle::CompatibleCoupling(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const +{ + if (false == CouplingType.HasAny(Coupling::control) || CouplingType.HasAny(Coupling::permanent) || ControlCouplingAllowed(End, Other, OtherEnd)) + { + return CouplingType; + } + return CouplingType.Without(Coupling::control); +} + +// ************************************************************************************************* +// Q: 20160713 +// Obliczanie sił dzialających na sprzęgach +// ************************************************************************************************* +double physics::Vehicle::CouplerForce(VehicleEnd const End, double dt) +{ + if (coupler_physics_at(End)) + { + return coupler_force_physical(End, dt); + } + + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->physics}; + auto const otherend{Neighbours[End].FacingEnd()}; + auto const &othercoupler{othervehicle->Couplers[otherend]}; + + auto const othervehiclemove{(othervehicle->moveLength * DirPatch(End, otherend))}; + auto const initialdistance{Neighbours[End].distance}; // odległość od sprzęgu sąsiada + auto const distancedelta{(End == VehicleEnd::front ? othervehiclemove - moveLength : moveLength - othervehiclemove)}; + + // the ends crushed for good (physics.collisions new, see collision.h) let the buffers meet that much closer + auto const crushed{thiscoupler.crush + othercoupler.crush}; + auto const rawdistance{initialdistance + 10.0 * distancedelta}; + auto const newdistance{rawdistance < 0.0 ? std::min(0.0, rawdistance + crushed) : rawdistance}; + + auto const dV{CouplerVelocityDifference(End, *othervehicle, otherend)}; + auto const absdV{std::abs(dV)}; + + // potentially generate sounds on clash or stretch + if (newdistance < 0.0 && thiscoupler.Dist > newdistance && dV < -0.1 && false == thiscoupler.has_adapter()) + { // HACK: with adapter present we presume buffers won't clash + // 090503: dzwieki pracy zderzakow + SetFlag(thiscoupler.sounds, absdV > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash); + } + else if (thiscoupler.CouplingFlag != Coupling::none && newdistance > 0.001 && thiscoupler.Dist <= 0.001 && absdV > 0.005 && Vel > 1.0) + { + // 090503: dzwieki pracy sprzegu + SetFlag(thiscoupler.sounds, absdV > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch); + } + + thiscoupler.CheckCollision = false; + thiscoupler.Dist = 0.0; + + double CF{0.0}; + + if (thiscoupler.CouplingFlag == Coupling::none && initialdistance > 0.05) + { // arbitrary distance + // potentially reset auto coupling lock + thiscoupler.AutomaticCouplingAllowed = true; + } + + if (thiscoupler.CouplingFlag != Coupling::none || initialdistance < 0) + { + + thiscoupler.Dist = safe_clamp(newdistance, thiscoupler.has_adapter() ? 0 : -thiscoupler.DmaxB, thiscoupler.DmaxC); + + double BetaAvg = 0; + double Fmax = 0; + + if (thiscoupler.CouplingFlag == Coupling::none) + { + + BetaAvg = thiscoupler.beta; + Fmax = (thiscoupler.FmaxC + thiscoupler.FmaxB) * CouplerTune; + } + else + { + // usrednij bo wspolny sprzeg + BetaAvg = 0.5 * (thiscoupler.beta + othercoupler.beta); + Fmax = 0.5 * (thiscoupler.FmaxC + thiscoupler.FmaxB + othercoupler.FmaxC + othercoupler.FmaxB) * CouplerTune; + } + auto const distDelta{std::abs(newdistance) - std::abs(thiscoupler.Dist)}; // McZapkie-191103: poprawka na histereze + + if (newdistance > 0) + { + + if (distDelta > 0) + { + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + } + else + { + CF = -(thiscoupler.SpringKC + othercoupler.SpringKC) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + } + // liczenie sily ze sprezystosci sprzegu + if (newdistance > thiscoupler.DmaxC + othercoupler.DmaxC) + { + // zderzenie + thiscoupler.CheckCollision = true; + } + CouplerStretchCheck(End, CF, dt); + } + if (newdistance < 0) + { + + if (distDelta > 0) + { + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) - Fmax * dV * BetaAvg; + } + else + { + CF = -(thiscoupler.SpringKB + othercoupler.SpringKB) * thiscoupler.Dist / 2.0 * DirF(End) * BetaAvg - Fmax * dV * BetaAvg; + } + // liczenie sily ze sprezystosci zderzaka + auto const collisiondistance{(thiscoupler.has_adapter() || othercoupler.has_adapter() ? + std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : // HACK: only take into account buffering ability of automatic coupler + thiscoupler.DmaxB + othercoupler.DmaxB)}; + if (-newdistance > collisiondistance) + { + // zderzenie + thiscoupler.CheckCollision = true; + } + if (-newdistance >= std::min(collisiondistance, dEpsilon)) + { + automatic_coupling(End, *othervehicle, otherend); + } + } + } + + if (thiscoupler.CouplingFlag != Coupling::none) + { + // uzgadnianie prawa Newtona, on the coupler of the other vehicle this one is coupled with, along that vehicle's + // axis: turned around once more when the vehicles face each other + othervehicle->Couplers[otherend].CForce = -CF * DirPatch(End, otherend); + } + + return CF; +} + +// a coupler stretched with more than its strength for over a second breaks, the more likely the longer, with crash damage on +void physics::Vehicle::CouplerStretchCheck(VehicleEnd const End, double const CF, double dt) +{ + auto &thiscoupler{Couplers[End]}; + if (std::abs(CF) > thiscoupler.FmaxC) + { + // coupler is stretched with excessive force, may break + thiscoupler.stretch_duration += static_cast(dt); + // give coupler 1 sec of leeway to account for simulation glitches, before checking whether it breaks + // (arbitrary) chance to break grows from 10-100% over 10 sec period + if (Global.crash_damage && thiscoupler.stretch_duration > 1.f && Random() < thiscoupler.stretch_duration * 0.1f * dt) + { + damage_coupler(End); + } + } + else + { + thiscoupler.stretch_duration = 0.f; + } +} + +bool physics::Vehicle::coupler_physics_at(VehicleEnd const End) const +{ + if (false == Global.coupler_physics) + { + return false; + } + if (Global.coupler_physics_all || couplerPhysics) + { + return true; + } + // either vehicle of the pair covered takes the pair in, so both of them compute it the same way + auto const *other{Neighbours[End].vehicle}; + return other != nullptr && other->physics->couplerPhysics; +} + +void physics::Vehicle::automatic_coupling(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + + if (thiscoupler.type() != TCouplerType::Automatic || thiscoupler.type() != othercoupler.type() || thiscoupler.CouplingFlag != Coupling::none || false == thiscoupler.AutomaticCouplingAllowed || + false == othercoupler.AutomaticCouplingAllowed) + { + return; + } + // a coupler torn off by the crush of its end (physics.collisions new) doesn't catch + if (Global.collisions == global_settings::collision_model::physical && (thiscoupler.broken || othercoupler.broken)) + { + return; + } + // sprzeganie wagonow z samoczynnymi sprzegami + auto couplingtype{thiscoupler.AutomaticCouplingFlag & othercoupler.AutomaticCouplingFlag}; + // potentially exclude incompatible control coupling + if (thiscoupler.control_type != othercoupler.control_type) + { + couplingtype = couplingtype.Without(Coupling::control); + } + couplingtype = CompatibleCoupling(End, Other, OtherEnd, couplingtype); + + // too fast for the couplers to catch, the vehicles collide instead (and may derail, see CollisionDetect()) + auto const safe{AutomaticCouplingSafe(End, Other, OtherEnd)}; + auto const caught{safe && Attach(End, OtherEnd, &Other, couplingtype)}; + // HACK: we're reusing sound enum to mark whether vehicle was connected to another + aiFlag |= (caught ? sound::attachcoupler : 0); + // coupled, or locked until the vehicles part, so they don't couple as soon as the collision slows them down + thiscoupler.AutomaticCouplingAllowed = safe && false == caught; + othercoupler.AutomaticCouplingAllowed = safe && false == caught; +} +namespace +{ + + +// the gap between the ends of a coupled pair, taking up the play of the coupling, opens up enough to jerk the train +constexpr double coupler_stretch_threshold{0.001}; + +// the sounds of the buffers hitting each other, and of the coupling taking up its play +struct coupler_sound_input +{ + double gap{0.0}; // between the ends [m] + double previous_gap{0.0}; + double gap_rate{0.0}; // [m/s] + double draw_gear{0.0}; // deflection [m] + double previous_draw_gear{0.0}; + bool coupled{false}; + bool adapter{false}; + bool moving{false}; +}; + +int coupler_sounds(coupler_sound_input const &Input) +{ + if (Input.gap < 0.0 && Input.gap < Input.previous_gap && Input.gap_rate < -0.1 && false == Input.adapter) + { + // 090503: dzwieki pracy zderzakow + return std::abs(Input.gap_rate) > 5.0 ? sound::bufferclash | sound::loud : sound::bufferclash; + } + if (Input.coupled && Input.moving && Input.draw_gear > coupler_stretch_threshold && Input.previous_draw_gear <= coupler_stretch_threshold && std::abs(Input.gap_rate) > 0.005) + { + // 090503: dzwieki pracy sprzegu + return std::abs(Input.gap_rate) > 0.035 ? sound::couplerstretch | sound::loud : sound::couplerstretch; + } + return sound::none; +} + +} // namespace + +double physics::Vehicle::coupler_gap_change(VehicleEnd const End, double const Own, double const Other) const +{ + auto const &neighbour{Neighbours[End]}; + if (neighbour.off_track) + { + return neighbour.own_share * Own + neighbour.other_share * Other; + } + // the gap opens up when the front end falls behind the vehicle ahead of it, or the rear end runs ahead of the one + // behind; the other vehicle's move turned around when the vehicles face each other + auto const other{Other * DirPatch(End, neighbour.FacingEnd())}; + return End == VehicleEnd::front ? other - Own : Own - other; +} + +double physics::Vehicle::coupler_force_physical(VehicleEnd const End, double const dt) +{ + auto &thiscoupler{Couplers[End]}; + auto *othervehicle{Neighbours[End].vehicle->physics}; + auto const otherend{Neighbours[End].FacingEnd()}; + auto &othercoupler{othervehicle->Couplers[otherend]}; + auto &state{thiscoupler.physics_state}; + + // the gap as it is now: the distance found at the start of the frame, and the movement of both vehicles since. + // off the track the ends of a pair may have gone past each other, where a move along the track that would close + // them on it opens the gap; taken as along the track, the draw gear unloaded while the gap grew far past its travel, + // and the coupling neither held nor broke + auto const gap{Neighbours[End].distance + coupler_gap_change(End, moveLength, othervehicle->moveLength)}; + auto const gaprate{coupler_gap_change(End, travelSpeed, othervehicle->travelSpeed)}; + auto const coupled{thiscoupler.CouplingFlag != Coupling::none}; + auto const adapter{thiscoupler.has_adapter() || othercoupler.has_adapter()}; + + if (false == coupled && Neighbours[End].distance > 0.05) + { // arbitrary distance + // potentially reset auto coupling lock + thiscoupler.AutomaticCouplingAllowed = true; + } + + auto const previousgap{state.gap}; + auto const previousdrawgear{state.draw_gear.deflection}; + auto const result{coupler_physics::update_pair(thiscoupler.physics, othercoupler.physics, state, {gap, gaprate, coupled, adapter, Global.crash_damage, thiscoupler.crush + othercoupler.crush})}; + + SetFlag(thiscoupler.sounds, coupler_sounds({gap, previousgap, gaprate, state.draw_gear.deflection, previousdrawgear, coupled, adapter, Vel > 1.0})); + + thiscoupler.CheckCollision = state.stop != 0; + // for the buffers drawn pressed in, see TDynamicObject: twice the deflection of the buffers of this end + thiscoupler.Dist = result.compression > 0.0 ? -2.0 * result.buffers_deflection : std::max(gap, 0.0); + // the link pulled past its yield force, which the AI drivers ease off on + thiscoupler.stretch_duration = result.overloaded ? thiscoupler.stretch_duration + static_cast(dt) : 0.f; + + if (result.broken) + { + damage_coupler(End); + } + if (false == coupled && gap < 0.0) + { + auto const collisiondistance{adapter ? std::min(thiscoupler.DmaxB, othercoupler.DmaxB) : thiscoupler.DmaxB + othercoupler.DmaxB}; + if (-gap >= std::min(collisiondistance, dEpsilon)) + { + automatic_coupling(End, *othervehicle, otherend); + } + } + + // tension pulls this vehicle towards the other one + auto const force{result.force * -DirF(End)}; + if (thiscoupler.CouplingFlag != Coupling::none) + { + // uzgadnianie prawa Newtona, as in CouplerForce() + othercoupler.CForce = -force * DirPatch(End, otherend); + } + return force; +} + +bool physics::Vehicle::coupler_stop_hit(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd) +{ + auto &thiscoupler{Couplers[End]}; + auto &othercoupler{Other.Couplers[OtherEnd]}; + auto &state{thiscoupler.physics_state}; + + // the draw gear went solid with the gap opening up, the buffers with it closing + auto const gaprate{coupler_gap_change(End, travelSpeed, Other.travelSpeed)}; + auto const closing{state.stop > 0 ? gaprate : -gaprate}; + if (state.stop == 0 || closing <= 0.0) + { + // parting from the stop already, after the hit on the other vehicle's end + return false; + } + if (false == Global.crash_damage) + { + return true; + } + auto const hit{coupler_physics::impact(thiscoupler.physics, othercoupler.physics, state, closing, totalMass, Other.totalMass)}; + // the other vehicle keeps the state of the pair alike + othercoupler.physics_state.elongation = state.elongation; + // with physics.collisions new the crush of the ends past the buffers is crush_hit()'s + if (hit.broken || (hit.crushed && Global.collisions != global_settings::collision_model::physical)) + { + damage_coupler(End); + } + // a broken coupling lets the vehicles part + return false == hit.broken; +} diff --git a/physics/components/devices.h b/physics/components/devices.h new file mode 100644 index 000000000..1b76e2971 --- /dev/null +++ b/physics/components/devices.h @@ -0,0 +1,243 @@ +/* +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 devices of a vehicle: pumps, fans, valves, pantographs, doors, the genset (nested in physics::Vehicle before) + +#pragma once + +#include +#include + +#include "physics/vehicletypes.h" + +namespace physics +{ + +/* TODO: implement + // communication cable, exchanging control signals with adjacent vehicle + struct jumper_cable { + // types + using flag_pair = std::pair; + // members + // booleans + // std::array flags {}; + // boolean pairs, exchanged data is swapped when connected to a matching end (front to front or back to back) + // TBD, TODO: convert to regular bool array for efficiency once it's working? + std::array flag_pairs {}; + // integers + // std::array values {}; + }; +*/ +// basic approximation of a generic device +// TBD: inheritance or composition? +struct basic_device +{ + // config + start_t start_type{start_t::manual}; + // ld inputs + bool is_enabled{false}; // device is allowed/requested to operate + bool is_disabled{false}; // device is requested to stop + // TODO: add remaining inputs; start conditions and potential breakers + // ld outputs + bool is_active{false}; // device is working +}; + +struct basic_light : public basic_device +{ + // config + float dimming{1.0f}; // light strength multiplier + // ld outputs + float intensity{0.0f}; // current light strength +}; + +struct cooling_fan : public basic_device +{ + // config + float speed{0.f}; // cooling fan rpm; either fraction of parent rpm, or absolute value if negative + float sustain_time{0.f}; // time of sustaining work of cooling fans after stop + float min_start_velocity{-1.f}; // minimal velocity of vehicle, when cooling fans activate + // ld outputs + float revolutions{0.f}; // current fan rpm + float stop_timer{0.f}; // current time, when shut off condition is active +}; + +// basic approximation of a fuel pump +struct fuel_pump : public basic_device +{ + // TODO: fuel consumption, optional automatic engine start after activation +}; + +// basic approximation of an oil pump +struct oil_pump : public basic_device +{ + // config + float pressure_minimum{0.f}; // lowest acceptable working pressure + float pressure_maximum{0.65f}; // oil pressure at maximum engine revolutions + // ld inputs + float resource_amount{1.f}; // amount of affected resource, compared to nominal value + // internal data + float pressure_target{0.f}; + // ld outputs + float pressure{0.f}; // current pressure +}; + +// the diesel generator set of a dual-mode vehicle: a second source of the traction circuit, next to the +// pantographs (eu07/maszyna#536). none unless the .fiz gives GensetPower +struct genset_device : public basic_device +{ + // config (Power: Genset*), revolutions in rev/s, the .fiz gives rpm + double power{0.0}; // GensetPower, electric output at full revolutions [kW]; 0 = no genset + double voltage_nominal{0.0}; // GensetVoltage, regulated DC voltage from the idle revolutions up [V] + double revolutions_idle{0.0}; // GensetIdleRPM + double revolutions_max{0.0}; // GensetMaxRPM + double start_time{8.0}; // GensetStartTime, from the start request to running at idle [s] + double spinup_time{3.0}; // GensetSpinUpTime, time constant of the revolutions [s] + double traction_share{1.0}; // GensetPmaxRatio, part of the power the traction may take + // state + double timer{0.0}; // of the start [s] + bool is_cranking{false}; + // ld outputs + double revolutions{0.0}; // [rev/s] + double voltage{0.0}; // [V] + bool fitted() const { return power > 0.0; } + // the power the genset gives at its present revolutions [kW] + double available_power() const { return revolutions_max > 0.0 ? power * std::clamp(revolutions / revolutions_max, 0.0, 1.0) : 0.0; } +}; +// basic approximation of a water pump +struct water_pump : public basic_device +{ + // ld inputs + // TODO: move to breaker list in the basic device once implemented + bool breaker{false}; // device is allowed to operate +}; + +// basic approximation of a solenoid valve +struct basic_valve : basic_device +{ + // config + bool solenoid{true}; // requires electric power to operate + bool spring{true}; // spring return or double acting actuator +}; + +// basic approximation of a pantograph +struct basic_pantograph +{ + // ld inputs + basic_valve valve; // associated pneumatic valve + // ld outputs + bool is_active{false}; // device is working + double voltage{0.0}; +}; + +// basic approximation of doors +struct basic_door +{ + // config + // ld inputs + bool open_permit{false}; // door can be opened + bool local_open{false}; // local attempt to open the door + bool local_close{false}; // local attempt to close the door + bool remote_open{false}; // received remote signal to open the door + bool remote_close{false}; // received remote signal to close the door + // internal data + float auto_timer{-1.f}; // delay between activation of open state and closing state for automatic doors + float close_delay{0.f}; // delay between activation of closing state and actual closing + float open_delay{0.f}; // delay between activation of opening state and actual opening + float position{0.f}; // current shift of the door from the closed position + float step_position{0.f}; // current shift of the movable step from the retracted position + // ld outputs + bool is_closed{true}; // the door is fully closed + bool is_door_closed{true}; // the door is fully closed, step doesn't matter + bool is_closing{false}; // the door is currently closing + bool is_opening{false}; // the door is currently opening + bool is_open{false}; // the door is fully open + bool step_folding{false}; // the doorstep is currently closing + bool step_unfolding{false}; // the doorstep is currently opening +}; + +struct door_data +{ + // config + control_t open_control{control_t::passenger}; + float open_rate{1.f}; + float open_delay{0.f}; + control_t close_control{control_t::passenger}; + float close_rate{1.f}; + float close_delay{0.f}; + int type{2}; + float range{0.f}; // extent of primary move/rotation + float range_out{0.f}; // extent of shift outward, applicable for plug doors + int step_type{2}; + float step_rate{0.5f}; + float step_range{0.f}; + bool has_lock{false}; + bool has_warning{false}; + bool has_autowarning{false}; + float auto_duration{-1.f}; // automatic door closure delay period + float auto_velocity{-1.f}; // automatic door closure velocity threshold + bool auto_include_remote{false}; // automatic door closure applies also to remote control + bool permit_needed{false}; + bool closure_signal{false}; // the door closure lamp (SOD) of the cab signals the doors of the whole consist in three states + std::vector permit_presets; // permit presets selectable with preset switch + float voltage{0.f}; // power type required for door movement + // ld inputs + bool lock_enabled{true}; + bool step_enabled{true}; + bool remote_only{false}; // door ignores local control signals + // internal data + int permit_preset{-1}; // curent position of preset selection switch + // vehicle parts + BySide instances; // door on the right and left side of the vehicle + // ld outputs + bool is_locked{false}; + double doorLockSpeed = 10.0; // predkosc przy ktorej wyzwalana jest blokada drzwi + + // what the doors need to know of the vehicle in the step + struct StepInputs + { + double velocity{0.0}; // [km/h] + bool powered{false}; // the doors have the voltage they work on + bool multipleUnit{false}; // the steps fold only once the door has closed + bool exchangingLoad{false}; // the passengers get in or out: the doors that close after a while stay open + }; + // the step of the doors: the lock, the requests, the movement of the doors and their steps, the timers + // (physics/components/doors.cpp) + void Update(StepInputs const &Inputs, double Deltatime); + // the state of the door closure signalling (SOD) of the vehicle + door_closure_t Closure() const; + + private: + // the permit, the state and the requests of a door, and whether it and its step open or close + void UpdateRequests(basic_door &door, StepInputs const &Inputs, bool localopencontrol, bool remoteopencontrol, bool localclosecontrol, bool remoteclosecontrol); + bool OpenRequest(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + bool CloseRequest(basic_door const &door, StepInputs const &Inputs, bool localclosecontrol, bool remoteclosecontrol) const; + bool StepFolding(basic_door const &door) const; + float OpenDuration(basic_door const &door, bool localopencontrol, bool remoteopencontrol) const; + void Move(basic_door &door, StepInputs const &Inputs, double Deltatime); + void UpdateTimers(StepInputs const &Inputs, double Deltatime); +}; + +struct water_heater +{ + // config + struct heater_config_t + { + float temp_min{-1}; // lowest accepted temperature + float temp_max{-1}; // highest accepted temperature + }; + heater_config_t config; + // ld inputs + bool breaker{false}; // device is allowed to operate + bool is_enabled{false}; // device is requested to operate + // ld outputs + bool is_active{false}; // device is working + bool is_damaged{false}; // device is damaged +}; + +} // namespace physics diff --git a/physics/components/diesel.cpp b/physics/components/diesel.cpp new file mode 100644 index 000000000..8d0909ce5 --- /dev/null +++ b/physics/components/diesel.cpp @@ -0,0 +1,1487 @@ +/* +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 diesel engine: its revolutions, the gearbox, the clutch, the hydraulic transmission, its heat and pumps + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" +#include "physics/components/drive.h" + + +double physics::Vehicle::EngineRPMRatio() const +{ + return Drive().EngineRpmRatio(*this); +} + +double physics::Vehicle::EngineIdleRPM() const +{ + return Drive().EngineIdleRpm(*this); +} + +double physics::Vehicle::EngineMaxRPM() const +{ + return Drive().EngineMaxRpm(*this); +} + +// water pump status check +void physics::Vehicle::WaterPumpCheck(double const /*Timestep*/) +{ + // NOTE: breaker override with start type is sm42 specific hack, replace with ability to define the presence of the breaker + WaterPump.is_active = true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && true == WaterPump.breaker && false == WaterPump.is_disabled && + (true == WaterPump.is_active || true == WaterPump.is_enabled || WaterPump.start_type == start_t::battery); +} + +// water heater status check +void physics::Vehicle::WaterHeaterCheck(double const /*Timestep*/) +{ + + WaterHeater.is_active = false == WaterHeater.is_damaged && true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && true == WaterHeater.is_enabled && true == WaterHeater.breaker && + (WaterHeater.is_active || WaterHeater.config.temp_min < 0 || diesel.heat.temperatura1 < WaterHeater.config.temp_min); + + WaterHeater.is_damaged = true == WaterHeater.is_damaged || (true == WaterHeater.is_active && false == WaterPump.is_active); + + if (WaterHeater.config.temp_max > 0 && diesel.heat.temperatura1 > WaterHeater.config.temp_max) + { + WaterHeater.is_active = false; + } +} + +// fuel pump status update +void physics::Vehicle::FuelPumpCheck(double const /*Timestep*/) +{ + using enum start_t; + + FuelPump.is_active = true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && false == FuelPump.is_disabled && + (FuelPump.is_active || (FuelPump.start_type == manual ? FuelPump.is_enabled : + FuelPump.start_type == automatic ? diesel.startupRequested || lineBreaker.IsClosed() : + FuelPump.start_type == manualwithautofallback ? FuelPump.is_enabled || diesel.startupRequested || lineBreaker.IsClosed() : + false)); // shouldn't ever get this far but, eh +} + +// oil pump status update +void physics::Vehicle::OilPumpCheck(double const Timestep) +{ + + OilPump.is_active = true == (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) && false == lineBreaker.IsClosed() && false == OilPump.is_disabled && + (OilPump.is_active || (OilPump.start_type == start_t::manual ? OilPump.is_enabled : + OilPump.start_type == start_t::automatic ? diesel.startupRequested : + OilPump.start_type == start_t::manualwithautofallback ? OilPump.is_enabled || diesel.startupRequested : + false)); // shouldn't ever get this far but, eh + + auto const minpressure{OilPump.pressure_minimum > 0.f ? OilPump.pressure_minimum : 0.15f}; // arbitrary fallback value + + OilPump.pressure_target = enrot > 0.1 ? std::lerp( minpressure, OilPump.pressure_maximum, static_cast( EngineRPMRatio() ) ) * OilPump.resource_amount : + true == OilPump.is_active ? std::min( minpressure + 0.1f, OilPump.pressure_maximum ) : // slight pressure margin to give time to switch off the pump and start the engine + 0.f; + + if (OilPump.pressure < OilPump.pressure_target) + { + // TODO: scale change rate from 0.01-0.05 with oil/engine temperature/idle time + OilPump.pressure = std::min(OilPump.pressure_target, static_cast(OilPump.pressure + (enrot > 5.0 ? 0.05 : 0.035) * Timestep)); + } + if (OilPump.pressure > OilPump.pressure_target) + { + OilPump.pressure = std::max(OilPump.pressure_target, static_cast(OilPump.pressure - (enrot > 5.0 ? 0.05 : 0.035) * 0.5 * Timestep)); + } + OilPump.pressure = std::clamp(OilPump.pressure, 0.f, 1.5f); +} + +// water pump breaker state toggle +bool physics::Vehicle::WaterPumpBreakerSwitch(bool State, range_t const Notify) +{ + /* + if( FuelPump.start_type == start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + return false; + } + */ + bool const initialstate{WaterPump.breaker}; + + WaterPump.breaker = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::waterPumpBreakerSwitch, WaterPump.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return WaterPump.breaker != initialstate; +} + +// water pump state toggle +bool physics::Vehicle::WaterPumpSwitch(bool State, range_t const Notify) +{ + + if (WaterPump.start_type == start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{WaterPump.is_enabled}; + + WaterPump.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::waterPumpSwitch, WaterPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return WaterPump.is_enabled != initialstate; +} + +// water pump state toggle +bool physics::Vehicle::WaterPumpSwitchOff(bool State, range_t const Notify) +{ + + if (WaterPump.start_type == start_t::battery) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{WaterPump.is_disabled}; + + WaterPump.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::waterPumpSwitchOff, WaterPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return WaterPump.is_disabled != initialstate; +} + +// water heater breaker state toggle +bool physics::Vehicle::WaterHeaterBreakerSwitch(bool State, range_t const Notify) +{ + /* + if( FuelPump.start_type == start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + return false; + } + */ + bool const initialstate{WaterHeater.breaker}; + + WaterHeater.breaker = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::waterHeaterBreakerSwitch, WaterHeater.breaker ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return WaterHeater.breaker != initialstate; +} + +// water heater state toggle +bool physics::Vehicle::WaterHeaterSwitch(bool State, range_t const Notify) +{ + /* + if( FuelPump.start_type == start::automatic ) { + // automatic fuel pump ignores 'manual' state commands + return false; + } + */ + bool const initialstate{WaterHeater.is_enabled}; + + WaterHeater.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::waterHeaterSwitch, WaterHeater.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return WaterHeater.is_enabled != initialstate; +} + +// water circuits link state toggle +bool physics::Vehicle::WaterCircuitsLinkSwitch(bool State, range_t const Notify) +{ + + if (false == diesel.heat.auxiliary_water_circuit) + { + // can't link the circuits if the vehicle only has one + return false; + } + + bool const initialstate{waterCircuitsLink}; + + waterCircuitsLink = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::waterCircuitsLinkSwitch, waterCircuitsLink ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return waterCircuitsLink != initialstate; +} + +// fuel pump state toggle +bool physics::Vehicle::FuelPumpSwitch(bool State, range_t const Notify) +{ + + if (FuelPump.start_type == start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{FuelPump.is_enabled}; + + FuelPump.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::fuelPumpSwitch, FuelPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return FuelPump.is_enabled != initialstate; +} + +bool physics::Vehicle::FuelPumpSwitchOff(bool State, range_t const Notify) +{ + + if (FuelPump.start_type == start_t::automatic) + { + // automatic fuel pump ignores 'manual' state commands + return false; + } + + bool const initialstate{FuelPump.is_disabled}; + + FuelPump.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::fuelPumpSwitchOff, FuelPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return FuelPump.is_disabled != initialstate; +} + +// oil pump state toggle +bool physics::Vehicle::OilPumpSwitch(bool State, range_t const Notify) +{ + + if (OilPump.start_type == start_t::automatic) + { + // automatic pump ignores 'manual' state commands + return false; + } + + bool const initialstate{OilPump.is_enabled}; + + OilPump.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::oilPumpSwitch, OilPump.is_enabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return OilPump.is_enabled != initialstate; +} + +bool physics::Vehicle::OilPumpSwitchOff(bool State, range_t const Notify) +{ + + if (OilPump.start_type == start_t::automatic) + { + // automatic pump ignores 'manual' state commands + return false; + } + + bool const initialstate{OilPump.is_disabled}; + + OilPump.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::oilPumpSwitchOff, OilPump.is_disabled ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return OilPump.is_disabled != initialstate; +} + +// the revolutions of the engine; returns those a diesel-electric engine aims at [1/s], 0 for the others. +// for a diesel engine, the ratio of the transmission and the engine's moment +double physics::Vehicle::UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment) +{ + return Drive().UpdateEngineRevolutions(*this, dt, dtrans, dmoment); +} + +// the revolutions a diesel-electric's engine aims at [1/s], by the controller and the heating; the fill shown by the smoke +double physics::Vehicle::DieselElectricTargetRevolutions() +{ + double tmp; + + if (EIMCtrlType > 0) // sterowanie cyfrowe + tmp = (DElist[0].RPM + (DElist[MainCtrlPosNo].RPM - DElist[0].RPM) * std::max(0.0, eimicReal)) / 60.0; + else + tmp = DElist[protection.PressureSwitchTripped() ? MainCtrlNoPowerPos() : mainCtrlPos].RPM / 60.0; + + if (true == trainHeating.IsAllowed() && trainHeating.config.power > 0 && trainHeating.config.engineRpm > 0) + { + // bump engine revolutions up if needed, when heating is on + tmp = std::max(tmp, std::min(EngineMaxRPM(), trainHeating.config.engineRpm) / 60.0); + } + // NOTE: fake diesel.fill calculation for the sake of smoke emitter which uses this parameter to determine smoke opacity + diesel.fill = std::clamp(0.2 + 0.35 * (tmp - enrot) + 0.5 * (std::abs(Im) / DElist[MainCtrlPosNo].Imax), 0.05, 1.0); + return tmp; +} + +void physics::Vehicle::DieselEngineTractionForce(double dt, double const dmoment, double const dtrans) +{ + Mw = dmoment * dtrans * Transmision.Efficiency; // dmoment i dtrans policzone przy okazji enginerotation + if (retarder.present && retarder.placement == 0) + Mw -= dizel_MomentumRetarder(nrotValue * Transmision.Ratio, dt) * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / wheelDiameter / nPoweredAxles; + ft = Fw * nPoweredAxles; // sila trakcyjna + ft = ft * DirAbsolute; // DirActive*CabActive; +} + +// tmp: the revolutions the engine aims at [1/s], see UpdateEngineRevolutions() +void physics::Vehicle::DieselElectricTractionForce(double tmp) +{ + double PosRatio; + // tmpV:=V*CabActive*DirActive; + auto const tmpV{nrotValue * Pirazy2 * 0.5 * wheelDiameter * DirAbsolute}; //*CabActive*DirActive; + auto tempUmax = 0.0; + auto tempImax = 0.0; + // jazda manewrowa + if (EIMCtrlType > 0) // sterowanie cyfrowe + { + tmp = DieselElectricDigitalForce(tmpV, tempUmax, tempImax); + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + else if (true == ShuntMode) + { + DieselElectricShuntForce(tmpV, tmp); + PosRatio = 1; + } + else // jazda ciapongowa + { + auto power = Power; + tempImax = DElist[mainCtrlPos].Imax; + tempUmax = DElist[mainCtrlPos].Umax; + if (true == trainHeating.IsOn()) + { + power -= trainHeating.config.power; + } + power = std::max(power, 0.0); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + auto const currentgenpower{(DElist[mainCtrlPos].RPM > 0 ? DElist[mainCtrlPos].GenPower * (60.0 * enrot / DElist[mainCtrlPos].RPM) : 0.0)}; + + tmp = std::min(power, currentgenpower); + + PosRatio = currentgenpower / DElist[MainCtrlPosNo].GenPower; + // stosunek mocy teraz do mocy max + // NOTE: Mains in this context is working diesel engine + if (true == lineContactors.IsClosed()) + ft = DieselElectricForce(tmpV, power, PosRatio, tmp); + else + ft = 0; // jak nastawnik na zero, to sila tez zero + + PosRatio = tmp / DElist[MainCtrlPosNo].GenPower; + } + + if (FuseFlag) + ft = 0; + else + ft = ft * DirAbsolute; // DirActive * CabActive; //zwrot sily i jej wartosc + Fw = ft / nPoweredAxles; // sila na obwodzie kola + Mw = Fw * wheelDiameter / 2.0; // moment na osi kola + motorMoment = Mw / Transmision.Ratio; // moment silnika trakcyjnego + + Im = dieselelectric_motor_current(motorMoment); + + if (ShuntMode) + { + DieselElectricShuntPower(tmp); + } + else + { + DieselElectricGenerator(tmp, tempUmax, tempImax); + } + + if (Imax > 1 && Im > Imax) + FuseOff(); + if (FuseFlag) + EngineVoltage = 0; + + // przekazniki bocznikowania, kazdy inny dla kazdej pozycji + if (auto const fieldshuntingcontrol{fieldshunting::diesel_electric(autoRelayType, fieldShuntSwitch, autoRelayFlag)}; + false == lineContactors.IsClosed() || ShuntMode || fieldshuntingcontrol == fieldshunting::control::off) + { + scndCtrlPos = 0; + } + else if (autoRelayFlag) + { + // the shunting relays set the field shunting (fieldshunting::control::automatic) + ShuntFieldRelaysCheck(tmpV, PosRatio, tmp); + } +} + +// the tractive force of a diesel-electric shunting, by the generator's table SST and the shunting controller anPos; +// tmp, the power the generator gives +void physics::Vehicle::DieselElectricShuntForce(double const tmpV, double &tmp) +{ + if (true == lineContactors.IsClosed()) + { + EngineVoltage = SST[mainCtrlPos].Umax * anPos + SST[mainCtrlPos].Umin * (1.0 - anPos); + // NOTE: very crude way to approximate power generated at current rpm instead of instant top output + // NOTE, TODO: doesn't take into account potentially increased revolutions if heating is on, fix it + tmp = EngineRPMRatio() * (SST[mainCtrlPos].Pmax * anPos) + SST[mainCtrlPos].Pmin * (1.0 - anPos); + ft = tmp * 1000.0 / (abs(tmpV) + 1.6); + } + else + { + EngineVoltage = 0; + ft = 0; + } +} + +// the tractive force of a diesel-electric set by the integrated controller, at the speed tmpV; the generator's +// voltage and current limits too. returns the power the generator gives +double physics::Vehicle::DieselElectricDigitalForce(double const tmpV, double &tempUmax, double &tempImax) +{ + auto eimic_positive = std::max(0.0, eimicReal); + auto const rpmratio{EngineRPMRatio()}; + tempImax = DElist[MainCtrlPosNo].Imax * eimic_positive; + tempUmax = DElist[MainCtrlPosNo].Umax * std::min(eimic_positive, rpmratio); + auto const tempPmax = DElist[MainCtrlPosNo].GenPower * std::min(eimic_positive, rpmratio); + if (true == lineContactors.IsClosed()) + ft = DieselElectricForce(tmpV, tempPmax, eimic_positive, tempPmax); + else + ft = 0; // jak nastawnik na zero, to sila tez zero + return tempPmax; +} + +// the tractive force of a diesel-electric at the speed tmpV: on the straight part of its characteristic under the speed +// Vhyp gives at the power LinePower, at the share Ratio of it, on the hyperbola of the power HyperbolaPower over it +double physics::Vehicle::DieselElectricForce(double const tmpV, double const LinePower, double const Ratio, double const HyperbolaPower) const +{ + if (tmpV < Vhyp * LinePower / DElist[MainCtrlPosNo].GenPower) + { + // czy na czesci prostej, czy na hiperboli + return (Ftmax - (Ftmax - 1000.0 * DElist[MainCtrlPosNo].GenPower / (Vhyp + Vadd)) * (tmpV / Vhyp) / PowerCorRatio) * Ratio; // posratio - bo sila jakos tam sie rozklada + } + // na hiperboli + // 1.107 - wspolczynnik sredniej nadwyzki Ft w symku nad charakterystyka + return 1000.0 * HyperbolaPower / (tmpV + Vadd) / PowerCorRatio; // tu jest zawarty stosunek mocy +} + +// in the shunting mode, the generator's power limited to tmp, the power the engine gives +void physics::Vehicle::DieselElectricShuntPower(double const tmp) +{ + EnginePower = EngineVoltage * Im / 1000.0; + if (EnginePower > tmp) + { + EnginePower = tmp; + EngineVoltage = EnginePower * 1000.0 / Im; + } + if (EnginePower < tmp) + { + ft *= EnginePower / tmp; + } +} + +// the generator's current limited to tempImax and its voltage by its characteristic, under tempUmax and the power tmp +void physics::Vehicle::DieselElectricGenerator(double const tmp, double const tempUmax, double const tempImax) +{ + if (abs(Im) > tempImax) + { // nie ma nadmiarowego, tylko Imax i zwarcie na pradnicy + ft = ft / Im * tempImax; + Im = tempImax; + } + + if (Im > 0) + { + // jak pod obciazeniem + if (true == Flat) + { + // ograniczenie napiecia w pradnicy - plaszczak u gory + EngineVoltage = 1000.0 * tmp / std::abs(Im); + } + else + { + auto tempMCP = EIMCtrlType > 0 ? 1 + 99 * std::max(1.0, eimicReal) : mainCtrlPos; + auto tempMCPN = EIMCtrlType > 0 ? 100 : MainCtrlPosNo; + // charakterystyka pradnicy obcowzbudnej (elipsa) - twierdzenie Pitagorasa + EngineVoltage = std::sqrt(std::abs(square(tempUmax) - square(tempUmax * Im / tempImax))) * (tempMCP - 1) + (1.0 - Im / tempImax) * tempUmax * (tempMCPN - tempMCP); + EngineVoltage /= tempMCPN - 1; + EngineVoltage = safe_clamp(EngineVoltage, Im * 0.05, 1000.0 * tmp / std::abs(Im)); + } + } + + if (EngineVoltage > tempUmax || Im == 0) + { + // gdy wychodzi za duze napiecie albo przy biegu jalowym (jest cos takiego?) + EngineVoltage = tempUmax * (converter.IsRunning() ? 1 : 0); + } + + EnginePower = EngineVoltage * Im / 1000.0; + /* + // power curve drop + // NOTE: disabled for the time being due to side-effects + if( ( tmpV > 1 ) && ( EnginePower < tmp ) ) { + ft = std::lerp( + ft, EnginePower / tmp, + std::clamp( tmpV - 1.0, 0.0, 1.0 ) ); + } + */ +} + +// the current of a diesel-electric vehicle's traction motors giving the moment [N m] of one motor +double physics::Vehicle::dieselelectric_motor_current(double const Moment) const +{ + // with MotorParam[scndCtrlPos] do + if (abs(Moment) > motor_param(scndCtrlPos).fi) + return nPoweredAxles * abs(abs(Moment) / motor_param(scndCtrlPos).mfi + motor_param(scndCtrlPos).mIsat); + else + return nPoweredAxles * sqrt(abs(Moment * motor_param(scndCtrlPos).Isat)); +} + +// the effort of a diesel-electric vehicle's dynamic brake the driver asks for, 0..1 +double physics::Vehicle::dieselelectric_dynamic_brake_demand() const +{ + switch (DEDynamicBrake.source) + { + case diesel_electric_dynamic_brake::control::controller: + return std::clamp(-eimicReal, 0.0, 1.0); + case diesel_electric_dynamic_brake::control::lever: + return DynamicBrakeRatio(); + default: + return 0.0; + } +} + +// the force [N] of a diesel-electric vehicle's dynamic brake at full effort at the speed: the most the motors take +// (the current), above the speed where the resistors' power takes over, the power; under EDBrakeV1 it fades, down to +// nothing at EDBrakeV0. a brake of direct current motors, whose force grows with the speed (the voltage they generate +// into the resistors), fades from 0 to the speed of its whole force; an inverter's only at the stop +double physics::Vehicle::dieselelectric_dynamic_brake_limit() const +{ + auto const &brake{DEDynamicBrake}; + auto limit{brake.max_force}; + if (brake.max_power > 0.0 && std::abs(travelSpeed) > 0.0) + { + limit = std::min(limit, brake.max_power / std::abs(travelSpeed)); + } + if (brake.fade_high > brake.fade_low) + { + limit *= std::clamp((Vel - brake.fade_low) / (brake.fade_high - brake.fade_low), 0.0, 1.0); + } + else if (Vel < brake.fade_low) + { + limit = 0.0; + } + return limit; +} + +// the dynamic brake of a diesel-electric vehicle, before the drive's force: the effort follows the demand, the force +// is the share of the most at the speed. the motors brake while the engine runs (it excites them, or keeps the +// control of the inverters going), with the direction set, the overload relay closed, no power asked for and the +// wheels rolling; otherwise there's no brake at once +void physics::Vehicle::update_dieselelectric_dynamic_brake(double const dt) +{ + auto &brake{DEDynamicBrake}; + auto const nopower{brake.source == diesel_electric_dynamic_brake::control::controller ? eimicReal <= 0.0 : IsMainCtrlNoPowerPos()}; + if (lineBreaker.IsClosed() && DirActive != 0 && false == FuseFlag && false == slippingWheels && nopower) + { + brake.level += std::clamp(dieselelectric_dynamic_brake_demand() - brake.level, -brake.rate * dt, brake.rate * dt); + } + else + { + brake.level = 0.0; + } + brake.force = brake.level * dieselelectric_dynamic_brake_limit(); + brakes.electrodynamic.on = brake.force > 0.0; + if (brake.blending) + { + // the train brake of the locomotive lets off by the share of the dynamic brake's force (LSt, EStED) + brakes.distributor->SetED(brake.max_force > 0.0 ? brake.force / brake.max_force : 0.0); + } +} + +// the force of a diesel-electric vehicle's dynamic brake, against the motion, in place of the drive's one: the motors +// work as generators into the resistors, the ammeter shows their current, the main generator gives nothing. near the +// stop no more than what stops the vehicle within the step dt: with no fade (EDBrakeV0 = EDBrakeV1 = 0) the whole force +// would turn round each time the speed crosses zero, and in FTrain it never lets the stop of ComputeMovement() catch it +void physics::Vehicle::apply_dieselelectric_dynamic_brake(double const dt) +{ + auto const force{dt > 0.0 ? std::min(DEDynamicBrake.force, totalMass * std::abs(travelSpeed) / dt) : DEDynamicBrake.force}; + ft = travelSpeed > 0.0 ? -force : travelSpeed < 0.0 ? force : 0.0; + Fw = ft / nPoweredAxles; + Mw = Fw * wheelDiameter / 2.0; + motorMoment = Mw / Transmision.Ratio; + Im = dieselelectric_motor_current(motorMoment); + EngineVoltage = 0.0; + EnginePower = 0.0; +} + +// ************************************************************************************************* +// Q: 20160715 +// Zmienia parametr do którego dąży sprzęgło +// ************************************************************************************************* +bool physics::Vehicle::dizel_EngageSwitch(double state) +{ + if (EngineType == TEngineType::DieselEngine && state <= 1 && state >= 0 && state != diesel.clutchState) + { + diesel.clutchState = state; + return true; + } + else + return false; +} + +// ************************************************************************************************* +// Q: 20160715 +// Zmienia parametr do którego dąży sprzęgło +// ************************************************************************************************* +bool physics::Vehicle::dizel_EngageChange(double dt) +{ + double engagespeed = 0; // OK:boolean; + bool DEC; + + DEC = false; + if (diesel.clutchPressure - diesel.clutchState > 0) + engagespeed = engagedownspeed; + else + engagespeed = engageupspeed; + if (dt > 0.2) + dt = 0.1; + if (abs(diesel.clutchPressure - diesel.clutchState) < 0.11) + { + if (diesel.clutchPressure != diesel.clutchState) + { + DEC = true; + diesel.clutchPressure = diesel.clutchState; + } + // else OK:=false; //już jest false + } + else + { + diesel.clutchPressure = diesel.clutchPressure + engagespeed * dt * (diesel.clutchState - diesel.clutchPressure); + // OK:=false; + } + // dizel_EngageChange:=OK; + return DEC; +} + +// ************************************************************************************************* +// Q: 20160715 +// Automatyczna zmiana biegów gdy prędkość przekroczy widełki +// ************************************************************************************************* +bool physics::Vehicle::dizel_AutoGearCheck(void) +{ + auto OK{false}; + + auto const VelUp{(motor_param(ScndCtrlActualPos).mfi0 != 0.0 ? + motor_param(ScndCtrlActualPos).mfi0 + (motor_param(ScndCtrlActualPos).mfi - motor_param(ScndCtrlActualPos).mfi0) * std::max(0.0, eimicReal) : + motor_param(ScndCtrlActualPos).mfi)}; + + auto const VelDown{(motor_param(ScndCtrlActualPos).fi0 != 0.0 && eimicReal <= 0.0 ? motor_param(ScndCtrlActualPos).fi0 : motor_param(ScndCtrlActualPos).fi)}; + + if (motor_param(ScndCtrlActualPos).AutoSwitch && lineBreaker.IsClosed()) + { + OK = dizel_GearShiftCheck(VelUp, VelDown); + } + + if (lineBreaker.IsClosed()) + { + dizel_ClutchCheck(); + } + return OK; +} + +// the automatic gearbox: a gear up over VelUp, down under VelDown, changed once the clutch is out; returns whether it acted +bool physics::Vehicle::dizel_GearShiftCheck(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (RList[mainCtrlPos].Mn == 0 && !torqueConverter.present) + { + if (diesel.clutchState > 0) + dizel_EngageSwitch(0); + if (IsMainCtrlNoPowerPos() && ScndCtrlActualPos > 0) + diesel.automaticGearShift = -1; + } + else + { + OK = dizel_GearShiftRequest(VelUp, VelDown); + } + if (diesel.clutchPressure < 0.1 && diesel.automaticGearShift != 0) + { + if (diesel.automaticGearShift == 1) + ScndCtrlActualPos++; + else + ScndCtrlActualPos--; + diesel.automaticGearShift = 0; + dizel_EngageSwitch(1.0); + OK = true; + } + return OK; +} + +// a gear up asked over VelUp, down under VelDown, where the gearbox shifts by itself; returns whether one is +bool physics::Vehicle::dizel_GearShiftRequest(double const VelUp, double const VelDown) +{ + auto OK{false}; + if (motor_param(ScndCtrlActualPos).AutoSwitch && diesel.automaticGearShift == 0) // sprawdz czy zmienic biegi + { + if (Vel > VelUp) + { + // shift up + if (ScndCtrlActualPos < scndCtrlPosNo) + { + diesel.automaticGearShift = 1; + OK = true; + } + } + else if (Vel < VelDown) + { + // shift down + if (ScndCtrlActualPos > 0) + { + diesel.automaticGearShift = -1; + OK = true; + } + } + } + return OK; +} + +// the pressure in the clutch's cylinder, by the controller's position or the integrated controller +void physics::Vehicle::dizel_ClutchCheck() +{ + if (EIMCtrlType > 0) // sterowanie komputerowe + { + dizel_ClutchByIntegratedController(); + } + else if (diesel.automaticGearShift == 0) // ustaw cisnienie w silowniku sprzegla} + dizel_ClutchByController(); + else + dizel_EngageSwitch(0.0); + if (!(motor_param(ScndCtrlActualPos).mIsat > 0)) + dizel_EngageSwitch(0.0); // wylacz sprzeglo na pozycjach neutralnych + if (!autoRelayFlag) + ScndCtrlActualPos = scndCtrlPos; +} + +// the clutch by the controller's position: half or fully in, fully over the speed of the full engagement +void physics::Vehicle::dizel_ClutchByController() +{ + switch (RList[mainCtrlPos].Mn) + { + case 1: + dizel_EngageSwitch(0.5); + break; + case 2: + dizel_EngageSwitch(1.0); + break; + case 3: + if (Vel > diesel.fullEngageMinVelocity) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.5); + break; + case 4: + if (Vel > diesel.fullEngageMinVelocity) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.66); + break; + case 5: + if (Vel > diesel.fullEngageMinVelocity) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.35 * (1 + RList[mainCtrlPos].R) * RList[mainCtrlPos].R); + break; + default: + if (torqueConverter.present && torqueConverter.fill > 0.01) + dizel_EngageSwitch(1.0); + else + dizel_EngageSwitch(0.0); + } +} + +// the clutch of the integrated controller: in with the converter filled or the power asked, half in for the retarder +void physics::Vehicle::dizel_ClutchByIntegratedController() +{ + if (diesel.automaticGearShift == 0) + { + if ((torqueConverter.present && torqueConverter.fill > 0.01) || eimicReal > 0.005) + dizel_EngageSwitch(1.0); + else if (Vel > retarder.engageVelocity && retarder.present && retarder.fill > 0.01) + dizel_EngageSwitch(0.5); + else + dizel_EngageSwitch(0.0); + } + else + dizel_EngageSwitch(0.0); +} + +// performs diesel engine startup procedure; potentially clears startup switch; returns: true if the engine can be started, false otherwise +bool physics::Vehicle::dizel_StartupCheck() +{ + + auto engineisready{true}; // make inital optimistic presumption, then watch the reality crush it + + // test the fuel pump + // TODO: add fuel pressure check + if (false == FuelPump.is_active || (EngineType == TEngineType::DieselEngine && RList[mainCtrlPos].R == 0.0)) + { + engineisready = false; + // if( FuelPump.start_type == start_t::manual ) { + // with manual pump control startup procedure is done only once per starter switch press + diesel.startupRequested = false; + // } + } + // test the oil pump + if (false == OilPump.is_active || OilPump.pressure < OilPump.pressure_minimum) + { + engineisready = false; + if (OilPump.start_type == start_t::manual) + { + // with manual pump control startup procedure is done only once per starter switch press + diesel.startupRequested = false; + } + } + // test the water circuits and water temperature + if (true == diesel.heat.PA) + { + engineisready = false; + // TBD, TODO: reset startup procedure depending on pump and heater control mode + diesel.startupRequested = false; + } + + return engineisready; +} + +// ************************************************************************************************* +// Q: 20160715 +// Aktualizacja stanu silnika +// ************************************************************************************************* +bool physics::Vehicle::dizel_Update(double dt) +{ + + WaterPumpCheck(dt); + WaterHeaterCheck(dt); + OilPumpCheck(dt); + FuelPumpCheck(dt); + // the engine being started fires once the starter has turned it a while; one stopped meanwhile starts over + diesel.firingCountdown = (lineBreaker.IsClosed() ? std::max(0.0, diesel.firingCountdown - dt) : 0.0); + + if (true == diesel.startupRequested && true == dizel_StartupCheck()) + { + diesel.ignitionRequested = true; + } + + if (true == diesel.ignitionRequested && LastSwitchingTime >= initialCtrlDelay) + { + + diesel.startupRequested = false; + diesel.ignitionRequested = false; + // TODO: split engine and main circuit state indicator in two separate flags + LastSwitchingTime = 0; + Timer::subsystem.switching.note(Timer::switching_counter::diesel, this, &TypeName, &Name); + lineBreaker.Close(); + diesel.spinningUp = true; + diesel.firingCountdown = diesel.smokeDelay; + enrot = std::max(enrot, + 0.35 * ( // TODO: dac zaleznie od temperatury i baterii + EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0)); + } + + diesel.spinningUp = diesel.spinningUp && lineBreaker.IsClosed() && enrot < 0.95 * (EngineType == TEngineType::DieselEngine ? diesel.minRevolutions : DElist[0].RPM / 60.0); + + if (true == lineBreaker.IsClosed() && false == FuelPump.is_active) + { + // knock out the engine if the fuel pump isn't feeding it + // TBD, TODO: grace period before the engine is starved for fuel and knocked out + // an engine started on its own stops on its own + MainSwitch(false, MainSwitchRange()); + } + + bool DU{false}; + + if (EngineType == TEngineType::DieselEngine) + { + dizel_EngageChange(dt); + DU = dizel_AutoGearCheck(); + double const fillspeed{2}; + diesel.fill = diesel.fill + fillspeed * dt * (dizel_fillcheck(mainCtrlPos, dt) - diesel.fill); + } + + dizel_Heat(dt); + + return DU; +} + +// ************************************************************************************************* +// Q: 20160715 +// oblicza napelnienie, uzwglednia regulator obrotow +// ************************************************************************************************* +double physics::Vehicle::dizel_fillcheck(int mcp, double dt) +{ + auto realfill{0.0}; + + if (true == lineBreaker.IsClosed() && MainCtrlPosNo > 0 && true == FuelPump.is_active) + { + + if (true == diesel.ignitionRequested && LastSwitchingTime >= 0.9 * initialCtrlDelay) + { + // wzbogacenie przy rozruchu + // NOTE: ignition flag is reset before this code is executed + // TODO: sort this out + realfill = 1; + } + else + { + // napelnienie zalezne od mainCtrlPos + if (EIMCtrlType > 0) + { + realfill = dizel_DigitalFill(dt); + } + else + { + diesel.governorMaxRevolutions = diesel.maxRevolutions; + realfill = RList[mcp].R; + } + } + if (diesel.cutoffRevolutions > 0) + { + realfill = dizel_GovernorFill(mcp, realfill); + } + } + + return std::clamp(realfill, 0.0, 1.0); +} + +// the fill set by the integrated controller, and the idle and top revolutions the governor keeps to +double physics::Vehicle::dizel_DigitalFill(double dt) +{ + double realfill; + realfill = std::max(0.0, std::min(eimicReal, 1 - motor_param(ScndCtrlActualPos).Isat)); + if (eimicReal > 0.005 && !torqueConverter.lockedUp) + { + diesel.governorMinRevolutions = std::min(diesel.governorMinRevolutions + 2.5 * dt, diesel.hydraulicMinRevolutions + eimicReal * diesel.hydraulicMinRevolutionsFactor); + } + else + { + if (Vel < retarder.engageVelocity && retarder.present && retarder.fill > 0.01) + diesel.governorMinRevolutions = std::min(diesel.governorMinRevolutions + 5.0 * dt, diesel.retarderRevolutions); + else + diesel.governorMinRevolutions = diesel.minRevolutions; + } + if (!diesel.speedMaxRevolutionsTable.empty() && !torqueConverter.lockedUp) + { + diesel.governorMaxRevolutions = std::min(std::min(diesel.governorMaxRevolutions, enrot) + diesel.governorAcceleration * dt, TableInterpolation(diesel.speedMaxRevolutionsTable, Vel)); + } + else + { + diesel.governorMaxRevolutions = diesel.maxRevolutions; + } + return realfill; +} + +// the fill cut off over the revolutions the governor allows at the controller's position, or full under the idle ones +double physics::Vehicle::dizel_GovernorFill(int const mcp, double realfill) const +{ + auto nreg{0.0}; + if (EIMCtrlType > 0) + nreg = eimicReal > 0.005 ? diesel.governorMaxRevolutions : diesel.minRevolutions; + else + nreg = dizel_GovernorRevolutions(mcp, realfill); + if (enrot > nreg) // nad predkoscia regulatora zeruj dawke + realfill = 0; + if (enrot < diesel.governorMinRevolutions && RList[mcp].R > 0.001) // jesli ponizej biegu jalowego i niezerowa dawka, to dawaj pelna + realfill = 1; + return realfill; +} + +// the revolutions the governor allows at the controller's position, the gearbox and the speed; the fill cut off at +// a position the governor doesn't know +double physics::Vehicle::dizel_GovernorRevolutions(int const mcp, double &realfill) const +{ + auto nreg{0.0}; + switch (RList[mainCtrlPos].Mn) + { + case 0: + case 1: + nreg = diesel.minRevolutions; + break; + case 2: + if (diesel.automaticGearShift == 0 && true /*(!torqueConverter.present) || (diesel.clutchPressure>diesel.fill)*/) + nreg = diesel.governorMaxRevolutions; + else + nreg = diesel.minRevolutions; + break; + case 3: + if (diesel.automaticGearShift == 0 && Vel > diesel.fullEngageMinVelocity) + nreg = diesel.governorMaxRevolutions; + else + nreg = diesel.minRevolutions; + break; + case 4: + if (diesel.automaticGearShift == 0 && Vel > diesel.fullEngageMinVelocity) + nreg = diesel.maxRevolutions; + else + nreg = diesel.minRevolutions * 0.75 + diesel.governorMaxRevolutions * 0.25; + break; + case 5: + if (Vel > diesel.fullEngageMinVelocity) + nreg = diesel.governorMaxRevolutions; + else + nreg = diesel.minRevolutions + 0.8 * (diesel.governorMaxRevolutions - diesel.minRevolutions) * RList[mcp].R; + break; + default: + realfill = 0; // sluczaj + break; + } + return nreg; +} + +// ************************************************************************************************* +// Q: 20160715 +// Oblicza moment siły wytwarzany przez silnik spalinowy +// ************************************************************************************************* +double physics::Vehicle::dizel_Momentum(double Fill, double n, double dt) +{ // liczy moment sily wytwarzany przez silnik spalinowy} + double Moment = 0; + double enMoment = 0; + double gearMoment = 0; + double eps = 0; + double newn = 0; + double friction = 0; + double TorqueH = 0; + double TorqueL = 0; + double TorqueC = 0; + n = n * CabActive; + if (motor_param(ScndCtrlActualPos).mIsat < 0.001 || DirActive == 0) + n = enrot; + friction = diesel.clutchFriction; + torqueConverter.revolutionsIn = enrot; // wal wejsciowy przetwornika momentu + torqueConverter.revolutionsOut = diesel.previousRevolutions; // wal wyjsciowy przetwornika momentu + + if (enrot > 0) + { + if (diesel.momentTable.size() > 1) + { + Moment = TableInterpolation(diesel.momentTable, enrot) * Fill - diesel.standingMoment; + } + else + { + Moment = (diesel.maxMoment - (diesel.maxMoment - diesel.maxRevolutionsMoment) * square((enrot - diesel.maxMomentRevolutions) / (diesel.maxMomentRevolutions - diesel.maxRevolutions))) * Fill - diesel.standingMoment; + } + motorMoment = Moment; + diesel.fuelConsumptionActual = diesel.fuelConsumption * enrot * Fill; + diesel.fuelConsumedTotal += diesel.fuelConsumptionActual * dt / 3600.0; + if (retarder.present && retarder.placement == 2) + Moment -= dizel_MomentumRetarder(enrot, dt); + } + else + { + Moment = -diesel.standingMoment; + } + if (enrot < diesel.minRevolutions / 10.0 && eAngleValue < M_PI_2) + { + // wstrzymywanie przy malych obrotach + Moment -= diesel.standingMoment; + } + if (true == diesel.spinningUp) + Moment += diesel.standingMoment / (0.3 + std::max(0.0, enrot / diesel.minRevolutions)); // rozrusznik + + diesel.torque = Moment; + + hydro_TCFillCheck(dt); + + // obliczanie momentow poszczegolnych sprzegiel + // sprzeglo glowne (skrzynia biegow) + TorqueC = diesel.clutchMaxForce * diesel.clutchPressure * diesel.clutchDiameter * friction; + + if (torqueConverter.present) // jesli hydro + { + hydro_TCTorque(); + TorqueH = torqueConverter.torqueOut; + TorqueL = torqueConverter.lockupTorque * torqueConverter.lockupRate; + } + else + { + TorqueH = 0; // brak przetwornika oznacza brak momentu + TorqueL = 1 + TorqueC * 2; // zabezpieczenie, polaczenie trwale + } + + // sprawdzanie dociskow poszczegolnych sprzegiel + if (abs(Moment) > std::min(TorqueC, TorqueL + abs(torqueConverter.torqueIn)) || abs(diesel.previousRevolutions - enrot) > 0.1) // slizga sie z powodu roznic predkosci albo przekroczenia momentu + { + diesel.clutchSlip = enrot - diesel.previousRevolutions; + + if (TorqueC > TorqueL) + { + if (TorqueC > TorqueL + abs(TorqueH)) + { + torqueConverter.revolutionsOut = n; + gearMoment = TorqueL + abs(TorqueH) * sign(diesel.clutchSlip); + enMoment = Moment - (TorqueL + abs(torqueConverter.torqueIn)) * sign(diesel.clutchSlip); + } + else + { + torqueConverter.revolutionsOut = enrot - (n - enrot) * (TorqueC - TorqueL) / TorqueH; // slizganie proporcjonalne, zeby przetwornik nadrabial + gearMoment = TorqueC * sign(diesel.clutchSlip); + enMoment = Moment - gearMoment; + } + } + else + { + torqueConverter.revolutionsOut = enrot; + gearMoment = TorqueC*sign(diesel.clutchSlip); + enMoment = Moment - gearMoment; + } + eps = enMoment / diesel.shaftInertia; + newn = enrot + eps * dt; + if ((newn - n) * (enrot - diesel.previousRevolutions) < 0 && TorqueC > 0.1) // przejscie przez zero - slizgalo sie i przestało + newn = n; + if (newn * enrot <= 0 && eps * enrot < 0) // przejscie przez zero obrotow + newn = 0; + enrot = newn; + } + else // nie slizga sie (jeszcze) + { + diesel.clutchSlip = 0; + gearMoment = Moment; + double enrot_min = enrot - (std::min(TorqueC, TorqueL + abs(torqueConverter.torqueIn)) - Moment) / diesel.shaftInertia * dt; + double enrot_max = enrot + (std::min(TorqueC, TorqueL + abs(torqueConverter.torqueIn)) + Moment) / diesel.shaftInertia * dt; + enrot = safe_clamp(n, enrot_min, enrot_max); + } + if (retarder.present && retarder.placement == 1) + gearMoment -= dizel_MomentumRetarder(torqueConverter.revolutionsOut, dt); + + if (enrot <= 0 && false == diesel.spinningUp) + { + // an engine stalling stops those started together with it, once. one already stopped, from its own switch or + // another vehicle's, or not started at all, has nothing to stop: it stays quiet, rather than stop every frame + // the engines started on their own or from the separate switches (eu07/maszyna#80) + if (true == lineBreaker.IsClosed()) + { + MainSwitch(false, MainSwitchRange()); + } + enrot = 0; + } + + diesel.previousRevolutions = n; // obecna predkosc katowa na potrzeby kolejnej klatki + + return gearMoment; +} + +// the torque converter filled and emptied, and its lockup clutch engaged and released, by the power and the speed +void physics::Vehicle::hydro_TCFillCheck(double dt) +{ + if (torqueConverter.present) // jesli przetwornik momentu + { + // napelnianie przetwornika + bool IsPower = EIMCtrlType > 0 ? eimicReal > 0.005 : MainCtrlPowerPos() > 0; + if (IsPower && lineBreaker.IsClosed() && enrot > diesel.minRevolutions * 0.9) + torqueConverter.fill += torqueConverter.fillRateIncrease * dt; + // oproznianie przetwornika + if ((!IsPower && Vel < diesel.converterReleaseVelocity) || !lineBreaker.IsClosed() || enrot < diesel.minRevolutions * 0.8) + torqueConverter.fill -= torqueConverter.fillRateDecrease * dt; + // obcinanie zakresu + torqueConverter.fill = std::clamp(torqueConverter.fill, 0.0, 1.0); + + // blokowanie sprzegla blokującego + if (Vel > torqueConverter.lockupSpeed && lineBreaker.IsClosed() && enrot > 0.9 * diesel.minRevolutions && IsPower) + { + torqueConverter.lockedUp = true; + torqueConverter.lockupRate += torqueConverter.fillRateIncrease * dt; + } + // luzowanie sprzegla blokujacego + if (Vel < (IsPower ? torqueConverter.lockupSpeed : torqueConverter.unlockSpeed) || !lineBreaker.IsClosed() || enrot < 0.8 * diesel.minRevolutions) + { + torqueConverter.lockedUp = false; + torqueConverter.lockupRate -= torqueConverter.fillRateDecrease * dt; + } + // obcinanie zakresu + torqueConverter.lockupRate = std::clamp(torqueConverter.lockupRate, 0.0, 1.0); + } + else + { + torqueConverter.fill = 0.0; + torqueConverter.lockupRate = 0.0; + } +} + +// the torque converter's moments on its input and output shafts, by their revolutions and its fill +void physics::Vehicle::hydro_TCTorque() +{ + double HydroTorque = 0; + HydroTorque += torqueConverter.revolutionsIn * torqueConverter.revolutionsIn * torqueConverter.torqueInIn; + HydroTorque += (torqueConverter.revolutionsIn - torqueConverter.revolutionsOut) * torqueConverter.torqueInOut; + HydroTorque += torqueConverter.revolutionsOut * torqueConverter.revolutionsOut * torqueConverter.torqueOutOut; + double nOut2In = torqueConverter.revolutionsOut / std::max(0.01, torqueConverter.revolutionsIn); + if (torqueConverter.table.size() > 1) + { + torqueConverter.torqueRatio = TableInterpolation(torqueConverter.table, nOut2In); + torqueConverter.torqueOut = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; + torqueConverter.torqueIn = HydroTorque * torqueConverter.fill * std::min(1.0, torqueConverter.torqueRatio); + } + else + { + if (nOut2In < torqueConverter.couplingPoint) + { + torqueConverter.torqueRatio = 1 + (torqueConverter.maxTorqueRatio - 1) * square(1 - nOut2In / torqueConverter.couplingPoint); + torqueConverter.torqueIn = HydroTorque * torqueConverter.fill; + torqueConverter.torqueOut = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; + } + else + { + torqueConverter.torqueRatio = (1 - nOut2In) / (1 - torqueConverter.couplingPoint); + torqueConverter.torqueIn = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; + torqueConverter.torqueOut = HydroTorque * torqueConverter.fill * torqueConverter.torqueRatio; + } + } +} + +double physics::Vehicle::dizel_MomentumRetarder(double n, double dt) +{ + double RetarderRequest = lineBreaker.IsClosed() ? std::max(0.0, -eimicReal) : 0; + if (retarder.withIndividual) + RetarderRequest = LocalBrakeRatio(); + if (Vel < retarder.minVelocity) + RetarderRequest = 0; + if (retarder.placement == 2 && enrot < diesel.minRevolutions) + { + RetarderRequest = 0; + } + + retarder.clutchActive = !retarder.hasClutch || RetarderRequest > 0; + if (!retarder.hasClutch || (retarder.clutchActive && retarder.clutchSpeed == 0)) + { + retarder.revolutions = n * 60; + } + else if (retarder.clutchActive) + { + retarder.revolutions = sign(n) * std::min(std::abs(retarder.revolutions + retarder.clutchSpeed * dt), std::abs(n * 60)); + } + else + { + retarder.revolutions = 0; + } + n = retarder.revolutions / 60.f; + + if (retarder.fill < RetarderRequest) // gdy zadane hamowanie + { + retarder.fill = std::min(retarder.fill + retarder.fillRateIncrease * dt, RetarderRequest); + } + else + { + retarder.fill = std::max(retarder.fill - retarder.fillRateDecrease * dt, RetarderRequest); + } + + double Moment = retarder.maxTorque; + if (double pwr = Moment * std::abs(n) * M_PI * 2 * 0.001; pwr > retarder.maxPower) + Moment = Moment * retarder.maxPower / pwr; + double moment_in = n * n * retarder.torqueInIn; + Moment = std::min(moment_in, Moment * retarder.fill); + + retarder.torque = Moment; + + return Moment; +} + +// sets component temperatures to specified value +void physics::Vehicle::dizel_HeatSet(float const Value) +{ + + // TODO: don't include ambient temperature, pull it from environment data instead + diesel.heat.Te = Value; + diesel.heat.Ts = Value; + diesel.heat.To = Value; + diesel.heat.Tsr = Value; + diesel.heat.Twy = Value; + diesel.heat.Tsr2 = Value; + diesel.heat.Twy2 = Value; + diesel.heat.temperatura1 = Value; + diesel.heat.temperatura2 = Value; +} + +// calculates diesel engine temperature and heat transfers +// adapted from scripts written by adamst +// NOTE: originally executed twice per second +void physics::Vehicle::dizel_Heat(double const dt) +{ + + auto const qs{44700.0}; + auto const Cs{11000.0}; + auto const Cw{4.189}; + auto const Co{1.885}; + auto const gwmin{400.0}; + auto const gwmax{4000.0}; + auto const gwmin2{400.0}; + auto const gwmax2{4000.0}; + + diesel.heat.Te = Global.AirTemperature; + + auto const engineon{(lineBreaker.IsClosed() ? 1 : 0)}; + auto const engineoff{(lineBreaker.IsClosed() ? 0 : 1)}; + auto const rpm{enrot * 60}; + // TODO: calculate this once and cache for further use, instead of doing it repeatedly all over the place + auto const revolutionsfactor{EngineRPMRatio()}; + auto const waterpump{WaterPump.is_active ? 1 : 0}; + + auto const gw = engineon * std::lerp(gwmin, gwmax, revolutionsfactor) + waterpump * 1000 + engineoff * 200; + auto const gw2 = engineon * std::lerp(gwmin2, gwmax2, revolutionsfactor) + waterpump * 1000 + engineoff * 200; + auto const gwO = std::lerp(gwmin, gwmax, revolutionsfactor); + + diesel.heat.water.is_cold = diesel.heat.water.config.temp_min > 0 && diesel.heat.temperatura1 < diesel.heat.water.config.temp_min - (lineBreaker.IsClosed() ? 5 : 0); + diesel.heat.water.is_hot = diesel.heat.water.config.temp_max > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_max - (diesel.heat.water.is_hot ? 8 : 0); + diesel.heat.water_aux.is_cold = diesel.heat.water_aux.config.temp_min > 0 && diesel.heat.temperatura2 < diesel.heat.water_aux.config.temp_min - (lineBreaker.IsClosed() ? 5 : 0); + diesel.heat.water_aux.is_hot = diesel.heat.water_aux.config.temp_max > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_max - (diesel.heat.water_aux.is_hot ? 8 : 0); + diesel.heat.oil.is_cold = diesel.heat.oil.config.temp_min > 0 && diesel.heat.To < diesel.heat.oil.config.temp_min - (lineBreaker.IsClosed() ? 5 : 0); + diesel.heat.oil.is_hot = diesel.heat.oil.config.temp_max > 0 && diesel.heat.To > diesel.heat.oil.config.temp_max - (diesel.heat.oil.is_hot ? 8 : 0); + // engine overheat check + diesel.heat.engine_is_hot = diesel.heat.engine_max_temp > 0 && diesel.heat.Ts > diesel.heat.engine_max_temp - (diesel.heat.engine_is_hot ? 8 : 0); + + auto const PT = false == diesel.heat.water.is_cold && false == diesel.heat.water.is_hot && false == diesel.heat.water_aux.is_cold && false == diesel.heat.water_aux.is_hot && + false == diesel.heat.oil.is_cold && false == diesel.heat.oil.is_hot && false == diesel.heat.engine.is_hot /* && ( false == awaria_termostatow ) */ + /* || PTp */; + auto const PPT = false == PT /* && ( false == PPTp ) */; + diesel.heat.PA = /* ( ( !zamkniecie or niedomkniecie ) and !WBD ) || */ PPT /* || nurnik || ( woda < 7 ) */; + + // engine heat transfers + auto const Ge{engineon * (0.21 * diesel.heat.powerfactor * EnginePower + 12) / 3600}; + // TODO: replace fixed heating power cost with more accurate calculation + auto const obciazenie{engineon * (diesel.heat.powerfactor * EnginePower / 950 + (trainHeating.IsOn() ? trainHeating.config.power : 0) + 70)}; + auto const Qd{qs * Ge - obciazenie}; + // silnik oddaje czesc ciepla do wody chlodzacej, a takze pewna niewielka czesc do otoczenia, modyfikowane przez okienko + auto const Qs{(Qd - diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) - diesel.heat.kfe * /* ( 0.3 + 0.7 * ( diesel.heat.okienko ? 1 : 0 ) ) * */ (diesel.heat.Ts - diesel.heat.Te))}; + auto const dTss{Qs / Cs}; + diesel.heat.Ts += static_cast(dTss * dt); + + // oil heat transfers + // olej oddaje cieplo do wody gdy krazy przez wymiennik ciepla == wlaczona pompka lub silnik + auto const dTo{(diesel.heat.auxiliary_water_circuit ? (diesel.heat.kfo * (diesel.heat.Ts - diesel.heat.To) - diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr2)) / (gwO * Co) : + (diesel.heat.kfo * (diesel.heat.Ts - diesel.heat.To) - diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr)) / (gwO * Co))}; + diesel.heat.To += static_cast(dTo * dt); + + // heater + /* + if( typ == "SP45" ) + Qp = (float)( podgrzewacz and ( true == WaterPump.is_active ) and ( Twy < 55 ) and ( Twy2 < 55 ) ) * 1000; + else + */ + auto const Qp = (true == WaterHeater.is_active && true == WaterPump.is_active && diesel.heat.Twy < 60 && diesel.heat.Twy2 < 60 ? 1 : 0) * 1000; + + auto const kurek07{1}; // unknown/unimplemented device TBD, TODO: identify and implement? + + if (true == diesel.heat.auxiliary_water_circuit) + { + // auxiliary water circuit setup + diesel.heat.water_aux.is_warm = true == diesel.heat.cooling || + (true == lineBreaker.IsClosed() && lowVoltage.BatteryVoltage() > 0.75 * lowVoltage.config.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + && diesel.heat.water_aux.config.temp_cooling > 0 && diesel.heat.temperatura2 > diesel.heat.water_aux.config.temp_cooling - (diesel.heat.water_aux.is_warm ? 8 : 0)); + auto const PTC2{(diesel.heat.water_aux.is_warm /*or PTC2p*/ ? 1 : 0)}; + diesel.heat.rpmwz2 = static_cast(PTC2 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); + diesel.heat.zaluzje2 = diesel.heat.water_aux.config.shutters ? PTC2 == 1 : true; // no shutters is an equivalent to having them open + auto const zaluzje2{(diesel.heat.zaluzje2 ? 1 : 0)}; + // auxiliary water circuit heat transfer values + auto const kf2{kurek07 * (diesel.heat.kw * (0.3 + 0.7 * zaluzje2) * diesel.heat.rpmw2 + diesel.heat.kv * (0.3 + 0.7 * zaluzje2) * Vel / 3.6) + 2}; + auto const dTs2{diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr2) / (gw2 * Cw)}; + // przy otwartym kurku B ma³y obieg jest dogrzewany przez du¿y - stosujemy przy korzystaniu z podgrzewacza oraz w zimie + auto const Qch2{-kf2 * (diesel.heat.Tsr2 - diesel.heat.Te) + 80 * (true == waterCircuitsLink ? 1 : 0) * (diesel.heat.Twy - diesel.heat.Tsr2)}; + auto const dTch2{Qch2 / (gw2 * Cw)}; + // auxiliary water circuit heat transfers finalization + // NOTE: since primary circuit doesn't read data from the auxiliary one, we can pretty safely finalize auxiliary updates before touching the primary circuit + auto const Twe2{diesel.heat.Twy2 + dTch2 * dt}; + diesel.heat.Twy2 = static_cast(Twe2 + dTs2 * dt); + diesel.heat.Tsr2 = static_cast(0.5 * (diesel.heat.Twy2 + Twe2)); + diesel.heat.temperatura2 = diesel.heat.Twy2; + } + // primary water circuit setup + diesel.heat.water.is_flowing = diesel.heat.water.config.temp_flow < 0 || diesel.heat.temperatura1 > diesel.heat.water.config.temp_flow - (diesel.heat.water.is_flowing ? 5 : 0); + auto const obieg{(diesel.heat.water.is_flowing ? 1 : 0)}; + diesel.heat.water.is_warm = + true == diesel.heat.cooling || (true == lineBreaker.IsClosed() && lowVoltage.BatteryVoltage() > 0.75 * lowVoltage.config.nominalBatteryVoltage /* && !bezpompy && !awaria_chlodzenia && !WS10 */ + && diesel.heat.water.config.temp_cooling > 0 && diesel.heat.temperatura1 > diesel.heat.water.config.temp_cooling - (diesel.heat.water.is_warm ? 8 : 0)); + auto const PTC1{(diesel.heat.water.is_warm /*or PTC1p*/ ? 1 : 0)}; + diesel.heat.rpmwz = static_cast(PTC1 * (diesel.heat.fan_speed >= 0 ? rpm * diesel.heat.fan_speed : diesel.heat.fan_speed * -1)); + diesel.heat.zaluzje1 = diesel.heat.water.config.shutters ? PTC1 == 1 : true; // no shutters is an equivalent to having them open + auto const zaluzje1{(diesel.heat.zaluzje1 ? 1 : 0)}; + // primary water circuit heat transfer values + auto const kf{obieg * kurek07 * (diesel.heat.kw * (0.3 + 0.7 * zaluzje1) * diesel.heat.rpmw + diesel.heat.kv * (0.3 + 0.7 * zaluzje1) * Vel / 3.6 + 3) + 2}; + auto const dTs{(diesel.heat.auxiliary_water_circuit ? diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) / (gw * Cw) : + (diesel.heat.kfs * (diesel.heat.Ts - diesel.heat.Tsr) + diesel.heat.kfo2 * (diesel.heat.To - diesel.heat.Tsr)) / (gw * Cw))}; + auto const Qch{-kf * (diesel.heat.Tsr - diesel.heat.Te) + Qp}; + auto const dTch{Qch / (gw * Cw)}; + // primary water circuit heat transfers finalization + auto const Twe{diesel.heat.Twy + dTch * dt}; + diesel.heat.Twy = static_cast(Twe + dTs * dt); + diesel.heat.Tsr = static_cast(0.5 * (diesel.heat.Twy + Twe)); + diesel.heat.temperatura1 = diesel.heat.Twy; + /* + fuelConsumed = fuelConsumed + ( Ge * 0.5 ); + + while( fuelConsumed >= 0.83 ) { + fuelConsumed = fuelConsumed - 0.83; + fuelQueue.DestroyProductMatching( null, 1 ); + }//if + + if( engineon ) + temp_turbo = temp_turbo + 0.3 * ( t_pozycja ); + if( t_pozycja == 0 and cisnienie > 0.04 ) + temp_turbo = temp_turbo - 1; + + if( temp_turbo > 400 ) + temp_turbo = 400; + if( temp_turbo < 0 ) + temp_turbo = 0; + + if( temp_turbo > 50 and cisnienie < 0.05 ) + timer_turbo = timer_turbo + 1; + + if( temp_turbo == 0 ) + timer_turbo = 0; + + if( timer_turbo > 360 ) { + awaria_turbo = true; + timer_turbo = 400; + } + + if( Ts < 50 ) + p_odpal = 3; + if( Ts > 49 and Ts < 76 ) + p_odpal = 4; + if( Ts > 75 ) + p_odpal = 7; + + stukanie = stukanie or awaria_oleju; + + if( awaria_oleju == true and ilosc_oleju > 0 ) { + ilosc_oleju = ilosc_oleju - ( 0.002 * rpm / 1500 ); + } + if( awaria_oleju == true and cisnienie < 0.06 ) + damage = 1; + */ +} diff --git a/physics/components/dieselengine.h b/physics/components/dieselengine.h new file mode 100644 index 000000000..07937ffcb --- /dev/null +++ b/physics/components/dieselengine.h @@ -0,0 +1,185 @@ +/* +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 diesel engine of a vehicle and its hydraulic transmission: their definition from the .fiz and their state. +// a vehicle has them whatever its drive; the drives of a diesel engine (DieselEngine, DieselElectric) use them + +#pragma once + +#include + +// the heat of a diesel engine: its cooling circuits, their fans and shutters, the temperatures +struct EngineHeat +{ + // input, state of relevant devices + bool cooling{false}; // TODO: user controlled device, implement + // bool okienko { true }; // window in the engine compartment + // system configuration + bool auxiliary_water_circuit{false}; // cooling system has an extra water circuit + double fan_speed{0.075}; // cooling fan rpm; either fraction of engine rpm, or absolute value if negative + // heat exchange factors + double kw{0.35}; + double kv{0.6}; + double kfe{1.0}; + double kfs{80.0}; + double kfo{25.0}; + double kfo2{25.0}; + // system parts + struct fluid_circuit_t + { + + struct circuit_config_t + { + float temp_min{-1}; // lowest accepted temperature + float temp_max{-1}; // highest accepted temperature + float temp_cooling{-1}; // active cooling activation point + float temp_flow{-1}; // fluid flow activation point + bool shutters{false}; // the radiator has shutters to assist the cooling + }; + circuit_config_t config; + bool is_cold{false}; // fluid is too cold + bool is_warm{false}; // fluid is too hot + bool is_hot{false}; // fluid temperature crossed cooling threshold + bool is_flowing{false}; // fluid is being pushed through the circuit + }; + fluid_circuit_t water; + fluid_circuit_t water_aux; + fluid_circuit_t oil; + fluid_circuit_t engine; + // output, state of affected devices + bool PA{false}; // malfunction flag + float rpmw{0.0}; // current main circuit fan revolutions + float rpmwz{0.0}; // desired main circuit fan revolutions + bool zaluzje1{false}; + float rpmw2{0.0}; // current auxiliary circuit fan revolutions + float rpmwz2{0.0}; // desired auxiliary circuit fan revolutions + bool zaluzje2{false}; + // output, temperatures + float Te{15.0}; // ambient temperature TODO: get it from environment data + // NOTE: by default the engine is initialized in warm, startup-ready state + float Ts{50.0}; // engine temperature + float To{45.0}; // oil temperature + float Tsr{50.0}; // main circuit radiator temperature (?) + float Twy{50.0}; // main circuit water temperature + float Tsr2{40.0}; // secondary circuit radiator temperature (?) + float Twy2{40.0}; // secondary circuit water temperature + float temperatura1{50.0}; + float temperatura2{40.0}; + float powerfactor{1.0}; // coefficient of heat generation for engines other than su45 + // engine overheat threshold + float engine_max_temp{-1}; // maximum acceptable engine temperature, triggers overheat lamp when exceeded + bool engine_is_hot{false}; // engine temperature crossed cooling threshold +}; + +// the diesel engine, its governor, its clutch and its fuel (the dizel_ values before) +struct DieselEngine +{ + // the definition (the Engine section of the .fiz) + double maxMoment = 1.0; // Mmax + double maxMomentRevolutions = 1.0; // nMmax + double maxRevolutionsMoment = 2.0; // Mnmax + double maxRevolutions = 2.0; // nmax + double nominalFill = 0.0; + std::map momentTable; + std::map speedMaxRevolutionsTable; // vel2nmax + /*parametry aproksymacji silnika spalinowego*/ + double standingMoment = 0.0; /*moment oporow ruchu silnika dla enrot=0*/ + double cutoffRevolutions = 0.0; /*predkosc obrotowa zadzialania ogranicznika predkosci*/ + double minRevolutions = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa*/ + double hydraulicMinRevolutions = 0.0; /*najmniejsza dopuszczalna predkosc obrotowa w czasie jazdy na hydro */ + double hydraulicMinRevolutionsFactor = 0.0; /*wspolczynnik wzrostu obrotow minimalnych hydro zaleznosci od zadanego procentu*/ + double retarderRevolutions = 0.0; /*obroty pracy podczas hamowania retarderem*/ + double governorAcceleration = 999.0; /*tempo zwiększania prędkości przez regulator dizla */ + double fullEngageMinVelocity = 0.0; /*najmniejsza predkosc przy jezdzie ze sprzeglem bez poslizgu*/ + double converterReleaseVelocity = 3.0; /*predkosc progowa rozlaczenia przetwornika momentu*/ + double shaftInertia = 1.0; /*moment bezwladnosci walu itp*/ + double revolutionsDecreaseRate{2.0}; + double nominalFuelConsumptionRate = 250.0; /*jednostkowe zużycie paliwa przy mocy nominalnej, wczytywane z fiz, g/kWh*/ + double fuelConsumption = 0.0; /*współczynnik zużycia paliwa przeliczony do jednostek maszynowych, l/obrót*/ + double clutchDiameter = 0.5; + double clutchMaxForce = 6000.0; + double clutchFriction = 0.5; /*parametry sprzegla*/ + // the starter turns the engine a while before it fires: smoke comes out only after SmokeDelay (the Engine section of the vehicle's + // .fiz, seconds from the start of the spin up) has passed. 0, the default, lets it out as soon as the starter turns, as before eu07/maszyna#523 + double smokeDelay{0.0}; + + // the state + double fill = 0.0; /*napelnienie*/ + double clutchState = 0.0; /*sprzeglo skrzyni biegow: 0 - luz, 1 - wlaczone, 0.5 - wlaczone 50% (z poslizgiem)*/ + double clutchPressure = 0.0; /*sprzeglo skrzyni biegow: aktualny docisk*/ + double automaticGearShift = 0.0; /*0 - bez zmiany, -1 zmiana na nizszy +1 zmiana na wyzszy*/ + bool startupRequested{false}; // engine startup procedure request indicator + bool ignitionRequested{false}; // engine ignition request indicator + bool spinningUp{false}; // engine spin up to idle speed flag + double firingCountdown{0.0}; // seconds left until the engine being started fires, 0 once it runs on its own + double clutchSlip = 0.0; /*roznica predkosci katowych tarcz sprzegla*/ + double previousRevolutions = 0.0; /*poredkosc na potrzeby obliczen sprzegiel*/ + double torque = 0.0; /*aktualny moment obrotowy silnika spalinowego*/ + double power = 0.0; /*aktualna moc silnika spalinowego*/ + double governorMinRevolutions = 0.0; /*predkosc regulatora minimalna, zmienna w hydro*/ + double governorMaxRevolutions = 0.0; /*predkosc regulatora maksymalna, zmienna w hydro*/ + double fuelConsumptionActual = 0.0; /*chwilowe spalanie paliwa w l/h*/ + double fuelConsumedTotal = 0.0; /*ilość paliwa zużyta od początku symulacji, l*/ + EngineHeat heat; +}; + +// the hydraulic torque converter (the hydro_TC values before) +struct TorqueConverter +{ + // the definition + bool present = false; /*obecnosc hydraulicznego przetwornika momentu*/ + double maxTorqueRatio = 2.0; /*maksymalne wzmocnienie momentu*/ + double couplingPoint = 0.85; /*wzgledna predkosc zasprzeglenia*/ + double lockupTorque = 3000.0; /*moment graniczny sprzegla blokujacego*/ + double lockupRate = 1.0; /*szybkosc zalaczania sprzegla blokujacego*/ + double unlockRate = 1.0; /*szybkosc rozlaczania sprzegla blokujacego*/ + double fillRateIncrease = 1.0; /*szybkosc napelniania sprzegla*/ + double fillRateDecrease = 1.0; /*szybkosc oprozniania sprzegla*/ + double torqueInIn = 4.5; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ + double torqueInOut = 0.0; /*stala momentu proporcjonalnego do roznica obrotow wejsciowych i wyjsciowych*/ + double torqueOutOut = 0.0; /*stala momentu proporcjonalnego do kwadratu obrotow wyjsciowych*/ + double lockupSpeed = 1.0; /*prog predkosci zalaczania sprzegla blokujacego*/ + double unlockSpeed = 1.0; /*prog predkosci rozlaczania sprzegla blokujacego*/ + std::map table; /*tablica przetwornika momentu*/ + + // the state + double fill = 0.0; /*napelnienie*/ + bool lockedUp = false; /*zapiecie sprzegla*/ + double torqueIn = 0.0; /*moment*/ + double torqueOut = 0.0; /*moment*/ + double torqueRatio = 1.0; /*aktualne przelozenie momentu*/ + double request = 0.0; /*zadanie sily*/ + double revolutionsIn = 0.0; /*predkosc obrotowa walu wejsciowego*/ + double revolutionsOut = 0.0; /*predkosc obrotowa walu wyjsciowego*/ +}; + +// the hydraulic retarder (the hydro_R values before) +struct Retarder +{ + // the definition + bool present = false; /*obecnosc retardera*/ + int placement = 0; /*umiejscowienie retardera: 0 - za skrzynia biegow, 1 - miedzy przetwornikiem a biegami, 2 - przed skrzynia biegow */ + double torqueInIn = 1.0; /*stala momentu proporcjonalnego do kwadratu obrotow wejsciowych*/ + double maxTorque = 1.0; /*maksymalny moment retardera*/ + double maxPower = 1.0; /*maksymalna moc retardera - ogranicza moment*/ + double fillRateIncrease = 1.0; /*szybkosc napelniania sprzegla*/ + double fillRateDecrease = 1.0; /*szybkosc oprozniania sprzegla*/ + double minVelocity = 1.0; /*minimalna predkosc, przy ktorej retarder dziala*/ + double engageVelocity = 1.0; /*minimalna predkosc hamowania, przy ktorej sprzeglo jest wciaz wlaczone*/ + bool hasClutch = false; /*czy retarder ma rozłączalne sprzęgło*/ + double clutchSpeed = 10.0; /*szybkość narastania obrotów po włączeniu sprzęgła retardera*/ + bool withIndividual = false; /*czy dla autobusów jest to łączone*/ + + // the state + double fill = 0.0; /*napelnienie*/ + double torque = 0.0; /*moment*/ + double request = 0.0; /*zadanie sily hamowania*/ + double revolutions = 0.0; /*predkosc obrotowa retardera*/ + bool clutchActive = false; /*czy retarder jest napędzany*/ +}; diff --git a/physics/components/doors.cpp b/physics/components/doors.cpp new file mode 100644 index 000000000..d3b796886 --- /dev/null +++ b/physics/components/doors.cpp @@ -0,0 +1,624 @@ +/* +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 doors and the exchange of the load + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +bool physics::Vehicle::AssignLoad(std::string const &Loadname, float const Amount) +{ + + if (Loadname == "pantstate") + { + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + { + // wartość niby "pantstate" - nazwa dla formalności, ważna jest ilość + auto const pantographsetup{static_cast(Amount)}; + if (pantographsetup & 1 << 2) + { + DoubleTr = -1; + } + if (pantographsetup & 1 << 0) + { + if (DoubleTr == 1) + { + OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + } + else + { + OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); + } + } + if (pantographsetup & 1 << 1) + { + if (DoubleTr == 1) + { + OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); + } + else + { + OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + } + } + return true; + } + else + { + return false; + } + } + + if (Loadname.empty()) + { + // empty the vehicle if requested + loadTypeChange = LoadType.name != Loadname; + LoadType = load_attributes(); + loadAmount = 0.f; + return true; + } + // can't mix load types, at least for the time being + if (loadAmount > 0 && LoadType.name != Loadname) + { + return false; + } + + auto const loadattributes = std::ranges::find_if(LoadAttributes, [&](auto const &attributes) { return attributes.name == Loadname; }); + if (loadattributes == std::end(LoadAttributes)) + { + // didn't find matching load configuration, this type is unsupported + return false; + } + loadTypeChange = LoadType.name != Loadname; + LoadType = *loadattributes; + loadAmount = safe_clamp(Amount, 0.f, maxLoad); + ComputeMass(); + return true; +} + +// a step of the exchange of the load: so much taken out, the mass with it +void physics::Vehicle::UnloadStep(float const Amount) +{ + loadStatus = 1; + loadAmount = std::max(0.f, loadAmount - Amount); + ComputeMass(); +} + +// a step of the exchange of the load: so much put in, up to the capacity, the mass with it +void physics::Vehicle::LoadStep(float const Amount) +{ + loadStatus = 2; + loadAmount = std::min(maxLoad, loadAmount + Amount); // std::max not strictly needed but, eh + ComputeMass(); +} + +// ************************************************************************************************* +// Q: 20160713 +// Test zakończenia załadunku / rozładunku +// ************************************************************************************************* +bool physics::Vehicle::LoadingDone(double const LSpeed, std::string_view Loadname) +{ + + if (LSpeed == 0.0) + { + // zerowa prędkość zmiany, to koniec + loadStatus = 4; + return true; + } + + if (Loadname.empty()) + { + return loadStatus >= 4; + } + if (Loadname != LoadType.name) + { + return loadStatus >= 4; + } + + // test zakończenia załadunku/rozładunku + // load exchange speed is reduced if the wagon is overloaded + auto const loadchange{static_cast(std::abs(LSpeed * LastLoadChangeTime) * (loadAmount > maxLoad ? 0.5 : 1.0))}; + + if (LSpeed < 0) + { + // gdy rozładunek + loadStatus = 2; // trwa rozładunek (włączenie naliczania czasu) + if (loadchange > 0) // jeśli coś przeładowano + { + LastLoadChangeTime = 0; // naliczony czas został zużyty + loadAmount -= loadchange; // zmniejszenie ilości ładunku + CommandIn.Value1 -= loadchange; // zmniejszenie ilości do rozładowania + if (loadAmount <= 0 || CommandIn.Value1 <= 0) + { + // pusto lub rozładowano żądaną ilość + loadStatus = 4; // skończony rozładunek + loadAmount = safe_clamp(loadAmount, 0.f, maxLoad); // ładunek nie może być ujemny + } + if (loadAmount == 0.f) + { + AssignLoad(""); // jak nic nie ma, to nie ma też nazwy + } + ComputeMass(); + } + } + else if (LSpeed > 0) + { + // gdy załadunek + loadStatus = 1; // trwa załadunek (włączenie naliczania czasu) + if (loadchange > 0) // jeśli coś przeładowano + { + LastLoadChangeTime = 0; // naliczony czas został zużyty + loadAmount += loadchange; // zwiększenie ładunku + CommandIn.Value1 -= loadchange; + if (loadAmount >= maxLoad * (1.0 + OverLoadFactor) || CommandIn.Value1 <= 0) + { + loadStatus = 4; // skończony załadunek + loadAmount = std::min(static_cast(maxLoad * (1.0 + OverLoadFactor)), loadAmount); + } + ComputeMass(); + } + } + + return loadStatus >= 4; +} + +bool physics::Vehicle::ChangeDoorPermitPreset(int const Change, range_t const Notify) +{ + + auto const initialstate{Doors.permit_preset}; + + if (false == Doors.permit_presets.empty()) + { + + Doors.permit_preset = safe_clamp(Doors.permit_preset + Change, 0, static_cast(Doors.permit_presets.size() - 1)); + auto const doors{Doors.permit_presets[Doors.permit_preset]}; + auto const permitleft{((doors & 1) != 0)}; + auto const permitright{((doors & 2) != 0)}; + + PermitDoors(CabActive > 0 ? VehicleSide::left : VehicleSide::right, permitleft, Notify); + PermitDoors(CabActive > 0 ? VehicleSide::right : VehicleSide::left, permitright, Notify); + } + + return Doors.permit_preset != initialstate; +} + +bool physics::Vehicle::PermitDoorStep(bool const State, range_t const Notify) +{ + + auto const initialstate{Doors.step_enabled}; + + Doors.step_enabled = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext(VehicleCommand::doorStep, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return Doors.step_enabled != initialstate; +} + +bool physics::Vehicle::PermitDoors(VehicleSide const Door, bool const State, range_t const Notify) +{ + + bool const initialstate{Doors.instances[Door].open_permit}; + + PermitDoors_(Door, State); + + if (Notify != range_t::local) + { + + SendCtrlToNext(VehicleCommand::doorPermit, + (State ? 1 : -1) // positive: grant, negative: revoke + * (Door == (CabActive > 0 ? VehicleSide::left : VehicleSide::right) ? // 1=lewe, 2=prawe (swap if reversed) + 1 : + 2), + CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return Doors.instances[Door].open_permit != initialstate; +} + +void physics::Vehicle::PermitDoors_(VehicleSide const Door, bool const State) +{ + + if (State && State != Doors.instances[Door].open_permit) + { + SetFlag(soundFlag, sound::doorpermit); + } + Doors.instances[Door].open_permit = State; +} + +bool physics::Vehicle::ChangeDoorControlMode(bool const State, range_t const Notify) +{ + + auto const initialstate{Doors.remote_only}; + + Doors.remote_only = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext(VehicleCommand::doorMode, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + if (true == State) + { + // when door are put in remote control mode they're automatically open + // TBD, TODO: make it dependant on config switch? + OperateDoors(VehicleSide::left, true); + OperateDoors(VehicleSide::right, true); + } + + return Doors.remote_only != initialstate; +} + +bool physics::Vehicle::OperateDoors(VehicleSide const Door, bool const State, range_t const Notify) +{ + + auto &door{Doors.instances[Door]}; + /* + if( ( State == true ? door.is_open : door.is_closed ) ) { + // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? + // (for the time being no, methods are often invoked blindly which would lead to commands spam) + return false; + } + */ + bool result{false}; + + if (Notify == range_t::local) + { + door.local_open = State; + door.local_close = false == State; + result = true; + } + else + { + // remote door operation signals require power to propagate + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) + { + door.remote_open = State; + door.remote_close = false == State; + result = true; + } + } + + if (Notify != range_t::local) + { + + SendCtrlToNext(State == true ? VehicleCommand::doorOpen : VehicleCommand::doorClose, + Door == (CabActive > 0 ? VehicleSide::left : VehicleSide::right) ? // 1=lewe, 2=prawe (swap if reversed) + 1 : + 2, + CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return result; +} + +// toggle door lock +bool physics::Vehicle::LockDoors(bool const State, range_t const Notify) +{ + + auto const initialstate{Doors.lock_enabled}; + + Doors.lock_enabled = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext(VehicleCommand::doorLock, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return Doors.lock_enabled != initialstate; +} + +// toggles departure warning +bool physics::Vehicle::signal_departure(bool const State, range_t const Notify) +{ + + if (departureSignalOn == State) + { + // TBD: should the command be passed to other vehicles regardless of whether it affected the primary target? + return false; + } + + departureSignalOn = State; + if (Notify != range_t::local) + { + // wysłanie wyłączenia do pozostałych? + SendCtrlToNext(VehicleCommand::departureSignal, State == true ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return true; +} + +// state of the door closure signalling (SOD) of this vehicle: open while a door isn't fully closed, released while +// the closed doors can be opened (a permit given, or, for doors that need none, no lock engaged), locked otherwise. +// doors the crew doesn't close (autonomous) aren't signalled, the same as for the door lights of the consist +door_closure_t physics::door_data::Closure() const +{ + if (range == 0.f || close_control == control_t::autonomous) + { + return door_closure_t::none; + } + if (std::ranges::any_of(instances, [](basic_door const &Door) { return false == Door.is_closed; })) + { + return door_closure_t::open; + } + if (is_locked) + { + return door_closure_t::locked; + } + if (permit_needed && std::ranges::none_of(instances, [](basic_door const &Door) { return Door.open_permit; })) + { + return door_closure_t::locked; + } + return door_closure_t::released; +} + +door_closure_t physics::Vehicle::door_closure() const +{ + return Doors.Closure(); +} + +bool physics::Vehicle::door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const +{ + return Doors.closure_signal ? door_closure_lamp(Consist, BlinkLit) : Doors.is_locked; +} + +bool door_closure_lamp(door_closure_t const State, bool const BlinkLit) +{ + switch (State) + { + case door_closure_t::locked: + return true; + case door_closure_t::released: + return BlinkLit; + default: + return false; + } +} + +// automatic door controller update +void physics::Vehicle::update_doors(double const Deltatime) +{ + door_data::StepInputs inputs; + inputs.velocity = Vel; + inputs.powered = doors_powered(); + inputs.multipleUnit = is_multiple_unit(); + inputs.exchangingLoad = (loadStatus & (2 | 1)) != 0; + Doors.Update(inputs, Deltatime); +} + +// whether the doors have the voltage they work on +bool physics::Vehicle::doors_powered() const +{ + if (Doors.voltage == 0) + { + return true; + } + if (Doors.voltage == 24) + { + return lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable(); + } + return Doors.voltage == 110 && lowVoltage.Is110vAvailable(); +} + +// the step of the doors: the lock, the requests, the movement of the doors and their steps, the timers +void physics::door_data::Update(StepInputs const &Inputs, double const Deltatime) +{ + + if (range == 0.f) + { + return; + } // HACK: crude way to distinguish vehicles with actual doors + + // NBMX Obsluga drzwi, MC: zuniwersalnione + auto const localopencontrol{false == remote_only && (open_control == control_t::passenger || open_control == control_t::mixed)}; + auto const remoteopencontrol{open_control == control_t::driver || open_control == control_t::conductor || open_control == control_t::mixed}; + auto const localclosecontrol{false == remote_only && (close_control == control_t::passenger || close_control == control_t::mixed)}; + auto const remoteclosecontrol{close_control == control_t::driver || close_control == control_t::conductor || close_control == control_t::mixed}; + + is_locked = true == has_lock && true == lock_enabled && Inputs.velocity >= doorLockSpeed; + + for (auto &door : instances) + { + UpdateRequests(door, Inputs, localopencontrol, remoteopencontrol, localclosecontrol, remoteclosecontrol); + Move(door, Inputs, Deltatime); + } + + if (false == instances[VehicleSide::right].is_open && false == instances[VehicleSide::left].is_open) + { + return; + } + + if (auto_duration > 0.f) + { + UpdateTimers(Inputs, Deltatime); + } + /* + // the door are closed if their timer goes below 0, or if the vehicle is moving faster than defined threshold + std::array const doorids { VehicleSide::right, VehicleSide::left }; + for( auto const doorid : doorids ) { + auto const &door { instances[ doorid ] }; + if( true == door.is_open ) { + if( ( ( auto_velocity != -1.f ) && ( Inputs.velocity > auto_velocity ) ) + || ( ( door.auto_timer != -1.f ) && ( door.auto_timer <= 0.f ) ) ) { + // close the door and set the timer to expired state (closing may happen sooner if vehicle starts moving) + OperateDoors( doorid, false, range_t::local ); + } + } + } + */ +} + +// the permit, the state and the requests of a door, and whether it and its step open or close +void physics::door_data::UpdateRequests(basic_door &door, StepInputs const &Inputs, bool const localopencontrol, bool const remoteopencontrol, bool const localclosecontrol, bool const remoteclosecontrol) +{ + // revoke permit if... + door.open_permit = true == door.open_permit // ...we already have one... + && (false == permit_presets.empty() // ...there's no preset switch controlling permit state... + || (false == is_locked // ...and the door lock is engaged... + && false == door.remote_close)); // ...or the door is about to be closed + + door.is_open = door.position >= range && (false == step_enabled || door.step_position >= (step_range != 0.f ? 1.f : 0.f)); + door.is_closed = door.position <= 0.f && door.step_position <= 0.f; + door.is_door_closed = door.position <= 0.f; + + door.local_open = door.local_open && false == door.is_open && (false == permit_needed || door.open_permit); + door.remote_open = (door.remote_open || remote_only) && false == door.is_open && (false == permit_needed || door.open_permit); + door.local_close = door.local_close && false == door.is_closed && (false == remoteopencontrol || false == door.remote_open); + door.remote_close = door.remote_close && false == door.is_closed && (false == localopencontrol || false == door.local_open); + + auto const openrequest{OpenRequest(door, localopencontrol, remoteopencontrol)}; + auto const closerequest{CloseRequest(door, Inputs, localclosecontrol, remoteclosecontrol)}; + auto const ispowered{Inputs.powered}; + + door.is_opening = false == door.is_open && true == ispowered && false == closerequest && (true == door.is_opening || (true == openrequest && false == is_locked)); + door.is_closing = false == door.is_closed && true == ispowered && false == openrequest && (door.is_closing || closerequest); + door.step_unfolding = step_range != 0.f && step_enabled && false == is_locked && door.step_position < 1.f && door.is_opening; + door.step_folding = StepFolding(door); + + if (true == door.is_opening) + { + door.auto_timer = OpenDuration(door, localopencontrol, remoteopencontrol); + } +} + +// whether the door is asked to open, by the passengers, from afar or by itself +bool physics::door_data::OpenRequest(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + auto const autoopenrequest{open_control == control_t::autonomous && (false == permit_needed || door.open_permit)}; + return (localopencontrol && door.local_open) || (remoteopencontrol && door.remote_open) || (autoopenrequest && false == door.is_open); +} + +// whether the door is asked to close, by the passengers, from afar, or by itself: over the speed, after its time or +// with its permit taken back +bool physics::door_data::CloseRequest(basic_door const &door, StepInputs const &Inputs, bool const localclosecontrol, bool const remoteclosecontrol) const +{ + auto const autocloserequest{(auto_velocity != -1.f && Inputs.velocity > auto_velocity) || (door.auto_timer != -1.f && door.auto_timer <= 0.f) || + (permit_needed && false == door.open_permit)}; + return (door.remote_close && remoteclosecontrol) || (door.local_close && localclosecontrol) || (autocloserequest && door.is_open); +} + +// whether the unfolded step folds: without the permission to stay out, or with the door closing, once it's about to +// close or closed +bool physics::door_data::StepFolding(basic_door const &door) const +{ + auto const unfolded{door.step_position > 0.f}; + auto const mayfold{false == step_enabled || (permit_needed ? false == door.open_permit : door.is_closing)}; + return unfolded && mayfold && (door.close_delay > close_delay || door.position <= 0.f); +} + +// how long the opening door stays open: the time of the doors, for the passengers' opening and, if it counts, the +// opening from afar; none otherwise +float physics::door_data::OpenDuration(basic_door const &door, bool const localopencontrol, bool const remoteopencontrol) const +{ + if (localopencontrol && door.local_open) + { + return auto_duration; + } + if (remoteopencontrol && door.remote_open && auto_include_remote) + { + return auto_duration; + } + return -1.f; +} + +// a door and its step moved as they open or close +void physics::door_data::Move(basic_door &door, StepInputs const &Inputs, double const Deltatime) +{ + // doors + if (true == door.is_opening) + { + // open door + if (false == door.step_unfolding // no wait if no doorstep + || step_type == 2) + { // no wait for rotating doorstep + door.open_delay += static_cast(Deltatime); + if (door.open_delay > open_delay) + { + door.position = std::min(range, static_cast(door.position + open_rate * Deltatime)); + } + } + door.close_delay = 0.f; + } + if (true == door.is_closing) + { + // close door + door.close_delay += static_cast(Deltatime); + if (door.close_delay > close_delay) + { + door.position = std::max(0.f, static_cast(door.position - close_rate * Deltatime)); + } + door.open_delay = 0.f; + } + // doorsteps + if (door.step_unfolding) + { + // unfold left doorstep + door.step_position = std::min(1.f, static_cast(door.step_position + step_rate * Deltatime)); + } + if (door.step_folding) + { + // fold left doorstep + if (Inputs.multipleUnit) + { + // multi-unit vehicles typically fold the doorstep only after closing the door + if (door.position <= 0.f) + { + door.step_position = std::max(0.f, static_cast(door.step_position - step_rate * Deltatime)); + } + } + else + { + door.step_position = std::max(0.f, static_cast(door.step_position - step_rate * Deltatime)); + } + } +} + +// the timers of the open doors which close after a while, kept running while the load is exchanged +void physics::door_data::UpdateTimers(StepInputs const &Inputs, double const Deltatime) +{ + // update door timers if the door close after defined time + for (auto &door : instances) + { + + if (false == door.is_open) + { + continue; + } + + if (door.auto_timer > 0.f) + { + door.auto_timer -= static_cast(Deltatime); + } + // if there's load exchange in progress, reset the timer(s) for already open doors + if (door.auto_timer != -1.f && Inputs.exchangingLoad) + { + door.auto_timer = auto_duration; + } + } +} diff --git a/physics/components/drive.cpp b/physics/components/drive.cpp new file mode 100644 index 000000000..4380c908d --- /dev/null +++ b/physics/components/drive.cpp @@ -0,0 +1,588 @@ +/* +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 drives of the vehicles, one class for each kind of engine + +#include "stdafx.h" +#include "physics/components/drive.h" + +#include +#include +#include + +#include "physics/vehicle.h" +#include "utilities/utilities.h" + +// the defaults: a drive with no engine model and no engine of revolutions does nothing in the steps + +double TractionDrive::UpdateEnginePower(physics::Vehicle & /*vehicle*/) const +{ + return 0.0; +} + +void TractionDrive::BeforeTractionForce(physics::Vehicle & /*vehicle*/, double /*dt*/) const +{ + // nothing before the force +} + +void TractionDrive::UpdateTractionForce(physics::Vehicle & /*vehicle*/, DriveStep const & /*step*/) const +{ + // no force +} + +void TractionDrive::AfterTractionForce(physics::Vehicle & /*vehicle*/) const +{ + // nothing after the force +} + +void TractionDrive::UpdateVentilators(physics::Vehicle & /*vehicle*/, double /*dt*/) const +{ + // no ventilators +} + +double TractionDrive::ShowCurrent(physics::Vehicle const &vehicle, int const ammeter) const +{ + return vehicle.ShowCurrentP(ammeter); +} + +double TractionDrive::EngineRpmRatio(physics::Vehicle const & /*vehicle*/) const +{ + return 1.0; +} + +double TractionDrive::EngineIdleRpm(physics::Vehicle const & /*vehicle*/) const +{ + return std::numeric_limits::max(); +} + +double TractionDrive::EngineMaxRpm(physics::Vehicle const & /*vehicle*/) const +{ + return std::numeric_limits::max(); +} + +double TractionDrive::UpdateEngineRevolutions(physics::Vehicle &vehicle, double /*dt*/, double & /*transmission*/, double & /*moment*/) const +{ + vehicle.enrot = vehicle.Transmision.Ratio * vehicle.nrot(); + return 0.0; +} + +bool TractionDrive::IncreaseMainController(physics::Vehicle & /*vehicle*/, int /*speed*/) const +{ + return false; +} + +bool TractionDrive::DecreaseMainController(physics::Vehicle & /*vehicle*/, int /*speed*/) const +{ + return false; +} + +bool TractionDrive::MainsPowerAvailable(physics::Vehicle const & /*vehicle*/) const +{ + return true; +} + +void TractionDrive::CheckVoltageRelays(physics::Vehicle & /*vehicle*/) const +{ + // no voltage relays +} + +bool TractionDrive::UpdateEngine(physics::Vehicle & /*vehicle*/, double /*dt*/) const +{ + return false; +} + +void TractionDrive::UpdateEngineVoltage(physics::Vehicle &vehicle, double /*dt*/) const +{ + vehicle.EngineVoltage = vehicle.Power > 1.0 ? vehicle.TractionSupplyVoltage() : 0.0; +} + +namespace +{ + +// the radiator fans of a diesel engine follow their demanded revolutions while the engine runs, and run down without it +void updateRadiatorFans(physics::Vehicle &vehicle, double const dt) +{ + auto &heat{vehicle.diesel.heat}; + if (true == vehicle.lineBreaker.IsClosed()) + { + heat.rpmw += static_cast(std::clamp(heat.rpmwz - heat.rpmw, -100.f, 50.f) * dt); + heat.rpmw2 += static_cast(std::clamp(heat.rpmwz2 - heat.rpmw2, -100.f, 50.f) * dt); + } + else + { + heat.rpmw *= static_cast(std::max(0.0, 1.0 - heat.rpmw * dt)); + heat.rpmw2 *= static_cast(std::max(0.0, 1.0 - heat.rpmw2 * dt)); + } +} + +// the line breaker of the drives fed from the line: closed ahead of the pantographs it runs on the low voltage circuits, +// else it needs the voltage of the source +bool linePowerAvailable(physics::Vehicle const &vehicle) +{ + return vehicle.lineBreaker.config.pantographsRequireIt ? vehicle.lowVoltage.Is24vAvailable() || vehicle.lowVoltage.Is110vAvailable() : vehicle.EnginePowerSourceVoltage() > 0.5 * vehicle.EnginePowerSource.MaxVoltage; +} + +// a notch of the master controller of the drives without steps of their own (no engine, Dumb, diesel-electric, +// induction): one position at a time, the speed control let go when the position leaves the one it holds +bool increaseNotch(physics::Vehicle &vehicle, int const speed) +{ + if (speed > 1) + { + return vehicle.IncMainCtrl(1) && vehicle.IncMainCtrl(speed - 1); // a fail will propagate up the recursion chain. should this be || instead? + } + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() + 1); + if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos()) + { + vehicle.SpeedCtrlSwitch(false); + vehicle.SpeedCtrlUnit.IsActive = false; + } + return true; +} + +bool decreaseNotch(physics::Vehicle &vehicle, int const speed) +{ + if (speed == 1) + { + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() - 1); + if (vehicle.EIMCtrlType == 0 && (vehicle.SpeedCtrlAutoTurnOffFlag & 1) == 1 && vehicle.MainCtrlActualPos != vehicle.MainCtrlPos()) + { + vehicle.SpeedCtrlSwitch(false); + vehicle.SpeedCtrlUnit.IsActive = false; + } + return true; + } + if (speed > 1) + { + return vehicle.DecMainCtrl(1) && vehicle.DecMainCtrl(speed - 1); + } + return false; +} + +// a vehicle without an engine (a wagon, a control car): its controller still steps, for the vehicles it controls +class NoEngineDrive final : public TractionDrive +{ +public: + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } +}; + +// an engine with no model at all (steam, Main): nothing happens in the steps +class UnmodelledDrive final : public TractionDrive +{ +}; + +// an engine with no model: the power follows the share of the controller positions +class DumbDrive final : public TractionDrive +{ +public: + double UpdateEnginePower(physics::Vehicle &vehicle) const override + { + auto const posRatio{(vehicle.MainCtrlPos() + vehicle.ScndCtrlPos()) / (vehicle.MainCtrlPosNo + vehicle.ScndCtrlPosNo() + 0.01)}; + vehicle.EnginePower = /*1000.0 **/ vehicle.Power * posRatio; + return posRatio; + } + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override + { + vehicle.DumbTractionForce(step.posRatio); + } + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override + { + return vehicle.lowVoltage.Is24vAvailable(); + } + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } +}; + +// a draisine and the like, the wheels driven by hand +class WheelsDrivenDrive final : public TractionDrive +{ +public: + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override + { + vehicle.WheelsDrivenTractionForce(step.dt); + } + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return vehicle.AddPulseForce(speed); + } +}; + +// series wound direct current motors, started through resistors +class SeriesMotorDrive final : public TractionDrive +{ +public: + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override + { + vehicle.SeriesMotorTractionForce(step.dt); + } + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return vehicle.IncMainCtrlSeriesMotor(speed); + } + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return vehicle.DecMainCtrlSeriesMotor(speed); + } + void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override + { + if (vehicle.MainCircuitPowered()) + { + vehicle.UpdateResistorBlowers(dt); + } // mains + else + { + vehicle.RventRot *= std::max(0.0, 1.0 - vehicle.RVentSpeed * dt); + } + } + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override + { + return linePowerAvailable(vehicle); + } + void CheckVoltageRelays(physics::Vehicle &vehicle) const override + { + // update the state of voltage relays + auto const voltage{std::max(vehicle.GetTrainsetHighVoltage(), vehicle.pantographCircuit.SupplyVoltage())}; + // where the line breaker holds without voltage (closed ahead of the pantographs) the undervoltage relay opens the + // line contactors instead, see MotorConnectorsCheck(). it picks up again only with the master controller back + // where a start begins, as the line breaker it stands in for wouldn't close on a running position either: at + // zero, or at the first position, which is the first resistance step, where the line contactors close on any + // start, and where the AI waits for them rather than going back to zero + auto const novoltrelaypicksup{false == vehicle.lineBreaker.config.pantographsRequireIt || vehicle.protection.UndervoltageHolds() || vehicle.MainCtrlPowerPos() <= 1}; + auto const &source{vehicle.EnginePowerSource}; + vehicle.protection.SetVoltageRelays( + source.SourceType != TPowerSource::CurrentCollector || (voltage >= source.CollectorParameters.MinV && novoltrelaypicksup), + source.SourceType != TPowerSource::CurrentCollector || voltage <= source.CollectorParameters.MaxV || false == source.CollectorParameters.OVP); + // wywalanie szybkiego z powodu niewłaściwego napięcia + // (a line breaker closed ahead of the pantographs holds without voltage) + if (true == vehicle.lineBreaker.IsClosed() && ((false == vehicle.protection.UndervoltageHolds() && false == vehicle.lineBreaker.config.pantographsRequireIt) || false == vehicle.protection.OvervoltageHolds()) && + vehicle.MainSwitch(false, vehicle.TrainType() == train_type::emu ? range_t::unit : range_t::local)) // TODO: check whether we need to send this EMU-wide + { + vehicle.RaiseEventFlag(); + } + } + bool UpdateEngine(physics::Vehicle &vehicle, double /*dt*/) const override + { + // automatyczny rozruch + return vehicle.AutoRelayCheck(); + } + void UpdateEngineVoltage(physics::Vehicle &vehicle, double const dt) const override + { + vehicle.lineContactors.AdvanceSwitchTimer(dt); + // potem ulepszyc! pantogtrafy! + // Ra 2014-03: uwzględnienie kierunku jazdy w napięciu na silnikach, a powinien być zdefiniowany nawrotnik + vehicle.EngineVoltage = vehicle.lineBreaker.IsClosed() ? vehicle.EnginePowerSourceVoltage() : 0.0; + if (vehicle.CabActive == 0) + { + vehicle.EngineVoltage *= vehicle.DirActive; + } + else + { + vehicle.EngineVoltage *= vehicle.DirAbsolute; // the reverser of the active cab, relative to the couplers + } + } +}; + +// asynchronous motors fed by inverters +class InductionMotorDrive final : public TractionDrive +{ +public: + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override + { + vehicle.InductionMotorTractionForce(step.dt); + } + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } + double ShowCurrent(physics::Vehicle const &vehicle, int const ammeter) const override + { + switch (ammeter) + { // do asynchronicznych + case 1: + return vehicle.WindingRes() * vehicle.Mm() / vehicle.Vadd; + case 2: + return vehicle.inductionMotor.forceShare * vehicle.WindingRes(); + default: + return vehicle.ShowCurrentP(ammeter); + } + } + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override + { + return linePowerAvailable(vehicle); + } + void CheckVoltageRelays(physics::Vehicle &vehicle) const override + { + // TODO: check if we can use instead the code for electricseriesmotor + // nie wchodzić w funkcję bez potrzeby + // (a line breaker closed ahead of the pantographs holds without voltage) + // (the source by the traction selector of a dual-mode vehicle: the pantographs or the genset) + if (vehicle.lineBreaker.IsClosed() && ((vehicle.TractionSupplyVoltage() < vehicle.TractionSupplyMinVoltage() && false == vehicle.lineBreaker.config.pantographsRequireIt) || + vehicle.TractionSupplyVoltage() > vehicle.EnginePowerSource.CollectorParameters.MaxV + 200)) + { + vehicle.MainSwitch(false, vehicle.TrainType() == train_type::emu ? range_t::unit : range_t::local); // TODO: check whether we need to send this EMU-wide + } + } +}; + +// a diesel engine driving the wheels through a mechanical or hydraulic transmission +class DieselMechanicalDrive final : public TractionDrive +{ +public: + double UpdateEnginePower(physics::Vehicle &vehicle) const override + { + vehicle.diesel.power = vehicle.Mm() * vehicle.enrot * (2.0 * M_PI / 1000.0); + vehicle.EnginePower = (vehicle.diesel.standingMoment + vehicle.Mm()) * vehicle.enrot * (2.0 * M_PI / 1000.0); + if (vehicle.MainCtrlPowerPos() > 1) + { + // dodatkowe opory z powodu sprezarki} + // dmoment -= diesel.standingMoment * ( 0.2 * enrot / diesel.maxRevolutions ); //yB: skąd to w ogóle się bierze?! + } + return 0.0; + } + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override + { + vehicle.DieselEngineTractionForce(step.dt, step.moment, step.transmission); + } + double UpdateEngineRevolutions(physics::Vehicle &vehicle, double const dt, double &transmission, double &moment) const override + { + if (vehicle.ShuntMode) // dodatkowa przekładnia np. dla 2Ls150 + transmission = vehicle.AnPos() * vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; + else + transmission = vehicle.Transmision.Ratio * vehicle.motor_param(vehicle.ScndCtrlActualPos).mIsat; + + moment = vehicle.dizel_Momentum(vehicle.diesel.fill, transmission * vehicle.nrot() * vehicle.DirActive, dt); // oblicza tez enrot + return 0.0; + } + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + if (speed > 1) + { + while (vehicle.MainCtrlPos() < vehicle.MainCtrlPosNo && vehicle.IncMainCtrl(1)) + { + // all work is done in the loop header + } + } + else + { + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() + 1); + } + vehicle.air.compressor.Allow(vehicle.MainCtrlPowerPos() > 0); + return true; + } + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + if (speed == 1) + { + vehicle.SetMainCtrlPos(vehicle.MainCtrlPos() - 1); + return true; + } + if (speed > 1) + { + while (vehicle.MainCtrlPos() > 0 || vehicle.RList[vehicle.MainCtrlPos()].Mn > 0) + vehicle.DecMainCtrl(1); + return true; + } + return false; + } + void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override + { + // NOTE: we update only radiator fans, as vehicles with diesel engine don't have other ventilators + updateRadiatorFans(vehicle, dt); + } + double EngineRpmRatio(physics::Vehicle const &vehicle) const override + { + return std::clamp(std::abs(vehicle.enrot) / vehicle.nmax, 0.0, 1.0); + } + double EngineIdleRpm(physics::Vehicle const &vehicle) const override + { + return vehicle.diesel.minRevolutions * 60; + } + double EngineMaxRpm(physics::Vehicle const &vehicle) const override + { + return vehicle.diesel.maxRevolutions * 60; + } + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override + { + return vehicle.lowVoltage.Is24vAvailable(); + } + bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override + { + return vehicle.dizel_Update(dt); + } +}; + +// a diesel engine driving a generator which feeds the traction motors +class DieselElectricDrive final : public TractionDrive +{ +public: + double UpdateEnginePower(physics::Vehicle &vehicle) const override + { + vehicle.EnginePower = 0; // the actual calculation is done in two steps later in the method + return 0.0; + } + void BeforeTractionForce(physics::Vehicle &vehicle, double const dt) const override + { + if (vehicle.DEDynamicBrake.source != physics::Vehicle::diesel_electric_dynamic_brake::control::none) + { + vehicle.update_dieselelectric_dynamic_brake(dt); + } + } + void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const override + { + vehicle.DieselElectricTractionForce(step.revolutions); + if (vehicle.DEDynamicBrake.level > 0.0) + { + // braking: no power asked for, so the drive above gave no force + vehicle.apply_dieselelectric_dynamic_brake(step.dt); + } + } + double UpdateEngineRevolutions(physics::Vehicle &vehicle, double const dt, double & /*transmission*/, double & /*moment*/) const override + { + double target{0.0}; + if (true == vehicle.lineBreaker.IsClosed() && true == vehicle.FuelPump.is_active) + { + target = vehicle.DieselElectricTargetRevolutions(); + } + else + { + target = 0.0; + vehicle.diesel.fill = 0.0; + } + + if (vehicle.enrot != target) + { + vehicle.enrot = safe_clamp(vehicle.enrot + dt / vehicle.diesel.shaftInertia * (vehicle.enrot < target ? 1.0 : -1.0 * vehicle.diesel.revolutionsDecreaseRate), // NOTE: revolutions typically drop faster than they rise + 0.0, std::max(target, vehicle.enrot)); + if (std::abs(target - vehicle.enrot) < 0.001) + { + vehicle.enrot = target; + } + } + return target; + } + bool IncreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return increaseNotch(vehicle, speed); + } + bool DecreaseMainController(physics::Vehicle &vehicle, int const speed) const override + { + return decreaseNotch(vehicle, speed); + } + void AfterTractionForce(physics::Vehicle &vehicle) const override + { + // rough approximation of extra effort to overcome friction etc + vehicle.EnginePower += EngineRpmRatio(vehicle) * 0.15 * vehicle.DElist[vehicle.MainCtrlPosNo].GenPower; + } + void UpdateVentilators(physics::Vehicle &vehicle, double const dt) const override + { + // NOTE: for this type RventRot is the speed of motor blowers; we also update radiator fans while at it + if (true == vehicle.lineBreaker.IsClosed()) + { + // TBD, TODO: currently ignores RVentType, fix this? + vehicle.RventRot += std::clamp(vehicle.enrot - vehicle.RventRot, -100.0, 50.0) * dt; + } + else + { + vehicle.RventRot *= std::max(0.0, 1.0 - vehicle.RVentSpeed * dt); + } + updateRadiatorFans(vehicle, dt); + } + double ShowCurrent(physics::Vehicle const &vehicle, int const /*ammeter*/) const override + { + return std::fabs(vehicle.Im); + } + double EngineRpmRatio(physics::Vehicle const &vehicle) const override + { + return std::clamp(60.0 * std::abs(vehicle.enrot) / vehicle.DElist[vehicle.MainCtrlPosNo].RPM, 0.0, 1.0); + } + double EngineIdleRpm(physics::Vehicle const &vehicle) const override + { + return vehicle.DElist[vehicle.MainCtrlNoPowerPos()].RPM; + } + double EngineMaxRpm(physics::Vehicle const &vehicle) const override + { + return vehicle.DElist[vehicle.MainCtrlPosNo].RPM; + } + bool MainsPowerAvailable(physics::Vehicle const &vehicle) const override + { + return vehicle.lowVoltage.Is24vAvailable(); + } + void CheckVoltageRelays(physics::Vehicle &vehicle) const override + { + // TODO: move this to the auto relay check when the electric engine code paths are unified + if (vehicle.lineBreaker.IsClosed() && false == vehicle.lineContactors.IsClosed() && vehicle.MainCtrlPowerPos() == 1) + { + vehicle.lineContactors.Close(); + } + if (false == vehicle.MotorConnectorsCheck()) + { + vehicle.lineContactors.Open(); + } + if (false == (vehicle.MainCtrlPowerPos() > 0)) + { + vehicle.lineContactors.Open(); + } + } + bool UpdateEngine(physics::Vehicle &vehicle, double const dt) const override + { + return vehicle.dizel_Update(dt); + } +}; + +NoEngineDrive const noEngineDrive{}; +UnmodelledDrive const unmodelledDrive{}; +DumbDrive const dumbDrive{}; +WheelsDrivenDrive const wheelsDrivenDrive{}; +SeriesMotorDrive const seriesMotorDrive{}; +InductionMotorDrive const inductionMotorDrive{}; +DieselMechanicalDrive const dieselMechanicalDrive{}; +DieselElectricDrive const dieselElectricDrive{}; + +} // namespace + +TractionDrive const &DriveOf(TEngineType const type) +{ + switch (type) + { + case TEngineType::Dumb: + return dumbDrive; + case TEngineType::WheelsDriven: + return wheelsDrivenDrive; + case TEngineType::ElectricSeriesMotor: + return seriesMotorDrive; + case TEngineType::ElectricInductionMotor: + return inductionMotorDrive; + case TEngineType::DieselEngine: + return dieselMechanicalDrive; + case TEngineType::DieselElectric: + return dieselElectricDrive; + case TEngineType::None: + return noEngineDrive; + case TEngineType::SteamEngine: + case TEngineType::Main: + return unmodelledDrive; + } + return unmodelledDrive; +} diff --git a/physics/components/drive.h b/physics/components/drive.h new file mode 100644 index 000000000..ac8dc9c70 --- /dev/null +++ b/physics/components/drive.h @@ -0,0 +1,71 @@ +/* +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 drive of a vehicle, by the kind of its engine (EngineType, the Engine section of the .fiz): what each kind of +// drive does in the step of the vehicle, in place of a switch on the engine type in each of those places. the drives +// hold no state of their own yet (it is in physics::Vehicle): there is one of each kind, shared by the vehicles + +#pragma once + +#include "physics/vehicletypes.h" + +namespace physics { class Vehicle; } + +// what the step of the traction gives the drive +struct DriveStep +{ + double dt{0.0}; // the length of the step [s] + double posRatio{0.0}; // the share of the controller positions, of the drive of no engine model (Dumb) + double revolutions{0.0}; // the revolutions of the engine + double moment{0.0}; // the moment of the diesel engine + double transmission{0.0}; // the ratio of the transmission of the diesel engine +}; + +class TractionDrive +{ +public: + virtual ~TractionDrive() = default; + + // the power of the engine for the controller positions; returns the share of the positions (Dumb), 0 for the others + virtual double UpdateEnginePower(physics::Vehicle &vehicle) const; + // before the traction force, whether the reverser is set or not + virtual void BeforeTractionForce(physics::Vehicle &vehicle, double dt) const; + // the traction force of the step (Ft), the reverser set + virtual void UpdateTractionForce(physics::Vehicle &vehicle, DriveStep const &step) const; + // after the traction force, whether the reverser is set or not + virtual void AfterTractionForce(physics::Vehicle &vehicle) const; + // the blowers of the starting resistors and the fans of the radiators + virtual void UpdateVentilators(physics::Vehicle &vehicle, double dt) const; + // the current the given ammeter of the cab shows + virtual double ShowCurrent(physics::Vehicle const &vehicle, int ammeter) const; + // the revolutions of the engine against the most it gives at the present controller position, 0..1; 1 with no + // engine of revolutions + virtual double EngineRpmRatio(physics::Vehicle const &vehicle) const; + // the revolutions of the engine idling and at most [rpm]; the largest double with no engine of revolutions + virtual double EngineIdleRpm(physics::Vehicle const &vehicle) const; + virtual double EngineMaxRpm(physics::Vehicle const &vehicle) const; + // the revolutions of the engine in the step (enrot); returns the revolutions a diesel-electric engine aims for, 0 for + // the others. a diesel engine with a mechanical transmission gives its ratio and its moment through the references + virtual double UpdateEngineRevolutions(physics::Vehicle &vehicle, double dt, double &transmission, double &moment) const; + // a notch up and down of the master controller, as the kind of the engine takes it; return whether it moved + virtual bool IncreaseMainController(physics::Vehicle &vehicle, int speed) const; + virtual bool DecreaseMainController(physics::Vehicle &vehicle, int speed) const; + // whether the line breaker has the power it needs to close, before the genset of a dual-mode vehicle has its say + virtual bool MainsPowerAvailable(physics::Vehicle const &vehicle) const; + // the relays that open the line breaker at a voltage out of range, or the line contactors + virtual void CheckVoltageRelays(physics::Vehicle &vehicle) const; + // the engine in the step of the vehicle: the automatic start of the series motors, the diesel engine; returns + // whether a relay clicked + virtual bool UpdateEngine(physics::Vehicle &vehicle, double dt) const; + // the voltage of the traction motors in the step (EngineVoltage) + virtual void UpdateEngineVoltage(physics::Vehicle &vehicle, double dt) const; +}; + +// the drive of the given kind of engine +TractionDrive const &DriveOf(TEngineType type); diff --git a/physics/components/electrics.cpp b/physics/components/electrics.cpp new file mode 100644 index 000000000..97d17fab5 --- /dev/null +++ b/physics/components/electrics.cpp @@ -0,0 +1,1237 @@ +/* +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 +#include +#include +#include +#include +#include +#include +#include +#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(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::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(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(0x80 * (End == VehicleEnd::front ? 0 : 1) + 0x40 * (CabActive != -1 ? 1 : 0) + static_cast(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 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(dimPositions.size()) - 1); +} + +physics::Vehicle::dimPosition physics::Vehicle::currentDimPosition() const +{ + if (modernDimmerPosition < 0 || modernDimmerPosition >= static_cast(dimPositions.size())) + { + return {}; + } + return dimPositions[modernDimmerPosition]; +} + +bool physics::Vehicle::stepDimmerPosition(int const Step) +{ + if (dimPositions.empty()) + { + return false; + } + auto const last{static_cast(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 physics::Vehicle::LightsPresetCabLight(int const Position) const +{ + if (Position < 1 || Position > static_cast(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}; +} diff --git a/physics/components/fizparser.cpp b/physics/components/fizparser.cpp new file mode 100644 index 000000000..ece8c004c --- /dev/null +++ b/physics/components/fizparser.cpp @@ -0,0 +1,1344 @@ +/* +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/. +*/ + +// reading the vehicle definition (.fiz): the parser and its tables + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +int ConversionError = 0; + +// ************************************************************************************************* +// FUNKCJE PARSERA WCZYTYWANIA PLIKU FIZYKI POJAZDU +// ************************************************************************************************* +bool startBPT; +bool startMPT; +bool startMPT0; +bool startRLIST; +bool startUCLIST; +bool startDIZELMOMENTUMLIST; +bool startDIZELV2NMAXLIST; +bool startHYDROTCLIST; +bool startPMAXLIST; +bool startDLIST; +bool startFFLIST; +bool startWWLIST; +bool startWiperList; +bool startDimmerList; +bool startFFEDLIST; +bool startLIGHTSLIST; +bool startCOMPRESSORLIST; +int LISTLINE; + +bool issection(std::string_view Name, std::string_view Input) +{ + + return Input.compare(0, Name.size(), Name) == 0; +} + +// ************************************************************************************************* +// Q: 20160717 +// ************************************************************************************************* +// parsowanie Motor Param Table +// checks a motor parameter table position read from the .fiz file against the table size +static bool is_valid_mpt_index(int const Index) +{ + if (Index >= 0 && Index <= MotorParametersArraySize) + { + return true; + } + WriteLog("Read MPT: position " + std::to_string(Index) + " out of range 0-" + std::to_string(MotorParametersArraySize) + " in line " + std::to_string(LISTLINE)); + return false; +} + +bool physics::Vehicle::readMPT0(std::string const &line) +{ + + // TBD, TODO: split into separate functions similar to readMPT if more varied schemes appear? + cParser parser(line); + if (false == parser.getTokens(7, false)) + { + WriteLog("Read MPT0: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + if (EngineType == TEngineType::DieselEngine) + { + parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi0 >> MotorParam[idx].fi >> MotorParam[idx].mfi0 >> MotorParam[idx].mfi >> MotorParam[idx].Isat; + } + else + { + parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].mfi0 >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MotorParam[idx].fi0; + } + if (true == parser.getTokens(1, false)) + { + int autoswitch{0}; + parser >> autoswitch; + MotorParam[idx].AutoSwitch = autoswitch == 1; + } + else + { + MotorParam[idx].AutoSwitch = false; + } + return true; +} + +bool physics::Vehicle::readMPT(std::string const &line) +{ + + ++LISTLINE; + + switch (EngineType) + { + + case TEngineType::ElectricSeriesMotor: + { + return readMPTElectricSeries(line); + } + case TEngineType::DieselElectric: + { + return readMPTDieselElectric(line); + } + case TEngineType::DieselEngine: + { + return readMPTDieselEngine(line); + } + default: + { + return false; + } + } +} + +bool physics::Vehicle::readMPTElectricSeries(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(5, false)) + { + WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat; + if (true == parser.getTokens(1, false)) + { + int autoswitch{0}; + parser >> autoswitch; + MotorParam[idx].AutoSwitch = autoswitch == 1; + } + else + { + MotorParam[idx].AutoSwitch = false; + } + return true; +} + +bool physics::Vehicle::readMPTDieselElectric(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(7, false)) + { + WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + parser >> MotorParam[idx].mfi >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].Isat >> MPTRelay[idx].Iup >> MPTRelay[idx].Idown; + + return true; +} + +bool physics::Vehicle::readMPTDieselEngine(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read MPT: arguments missing in line " + std::to_string(LISTLINE)); + return false; + } + int idx = 0; // numer pozycji + parser >> idx; + if (false == is_valid_mpt_index(idx)) + { + return false; + } + parser >> MotorParam[idx].mIsat >> MotorParam[idx].fi >> MotorParam[idx].mfi; + if (true == parser.getTokens(1, false)) + { + int autoswitch{0}; + parser >> autoswitch; + MotorParam[idx].AutoSwitch = autoswitch == 1; + } + else + { + MotorParam[idx].AutoSwitch = false; + } + return true; +} + +bool physics::Vehicle::readBPT(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(5, false)) + { + + WriteLog("Read BPT: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + std::string braketype; + int idx = 0; + parser >> idx; + parser >> brakes.config.pressureTable[idx].PipePressureVal >> brakes.config.pressureTable[idx].BrakePressureVal >> brakes.config.pressureTable[idx].FlowSpeedVal >> braketype; + if (braketype == "Pneumatic") + { + brakes.config.pressureTable[idx].BrakeType = TBrakeSystem::Pneumatic; + } + else if (braketype == "ElectroPneumatic") + { + brakes.config.pressureTable[idx].BrakeType = TBrakeSystem::ElectroPneumatic; + } + else + { + brakes.config.pressureTable[idx].BrakeType = TBrakeSystem::Individual; + } + + return true; +} + +bool physics::Vehicle::readRList(std::string const &Input) +{ + + cParser parser(Input); + if (false == parser.getTokens(5, false)) + { + + WriteLog("Read RList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + auto idx = LISTLINE++; + if (idx >= std::size(RList)) + { + WriteLog("Read RList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Bn >> RList[idx].Mn >> RList[idx].AutoSwitch; + + if (true == parser.getTokens(1, false)) + { + parser >> RList[idx].ScndAct; + } + else + { + RList[idx].ScndAct = 0; + } + + return true; +} + +bool physics::Vehicle::readUCList(std::string const &line) +{ + + cParser parser(line); + parser.getTokens(10, false); + auto idx = LISTLINE++; + if (idx >= std::size(UniCtrlList)) + { + WriteLog("Read UCList: number of entries exceeded capacity of the data table"); + return false; + } + int i = 0; + parser >> i >> UniCtrlList[idx].mode >> UniCtrlList[idx].MinCtrlVal >> UniCtrlList[idx].MaxCtrlVal >> UniCtrlList[idx].SetCtrlVal >> UniCtrlList[idx].SpeedUp >> UniCtrlList[idx].SpeedDown >> + UniCtrlList[idx].ReturnPosition >> UniCtrlList[idx].NextPosFastInc >> UniCtrlList[idx].PrevPosFastDec; + + return true; +} + +bool physics::Vehicle::readDList(std::string const &line) +{ + + cParser parser(line); + parser.getTokens(3, false); + auto idx = LISTLINE++; + if (idx >= std::size(RList)) + { + WriteLog("Read DList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> RList[idx].Relay >> RList[idx].R >> RList[idx].Mn; + + return true; +} + +bool physics::Vehicle::readDMList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read DMList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + diesel.momentTable.emplace(x / 60.0, y); + + return true; +} + +bool physics::Vehicle::readV2NMAXList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read V2nmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + diesel.speedMaxRevolutionsTable.emplace(x, y / 60.0); + + return true; +} + +bool physics::Vehicle::readHTCList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read HTCList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + torqueConverter.table.emplace(x, y); + + return true; +} + +bool physics::Vehicle::readPmaxList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + + WriteLog("Read PmaxList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + double x = 0.0; + double y = 0.0; + parser >> x >> y; + + inductionMotor.maxPowerTable.emplace(x, y); + + return true; +} + +bool physics::Vehicle::readFFList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(FFlist)) + { + WriteLog("Read FList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> FFlist[idx].v >> FFlist[idx].freq; + + return true; +} + +bool physics::Vehicle::readFFEDList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(2, false)) + { + WriteLog("Read FList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(FFEDlist)) + { + WriteLog("Read FList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> FFEDlist[idx].v >> FFEDlist[idx].freq; + + return true; +} + +// parsowanie wiperList +bool physics::Vehicle::readWiperList(std::string const &line) +{ + cParser parser(line); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read WiperList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(WiperList)) + { + WriteLog("Read WiperList: number of entries exceeded capacity of the data table"); + return false; + } + // the mask of the wipers is a number: read into an int and clamped, as the parser would take only its first character for a uint8_t + int bytesum{0}; + parser >> bytesum >> WiperList[idx].WiperSpeed >> WiperList[idx].interval >> WiperList[idx].outBackDelay; + WiperList[idx].byteSum = static_cast(std::clamp(bytesum, 0, 255)); + return true; +} + +bool physics::Vehicle::readDimmerList(std::string const &line) +{ + cParser parser(line); + if (false == parser.getTokens(3, false)) + { + WriteLog("Read DimmerList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + ++LISTLINE; + + dimPosition dps; + parser >> dps.isHighBeam >> dps.isDimmed >> dps.isOff; + dimPositions.push_back(dps); + return true; +} + +// parsowanie WWList +bool physics::Vehicle::readWWList(std::string const &line) +{ + + cParser parser(line); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read WWList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx >= std::size(DElist)) + { + WriteLog("Read WWList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> DElist[idx].RPM >> DElist[idx].GenPower >> DElist[idx].Umax >> DElist[idx].Imax; + + if (true == parser.getTokens(3, false)) + { + // optional parameters for shunt mode + parser >> SST[idx].Umin >> SST[idx].Umax >> SST[idx].Pmax; + + SST[idx].Pmin = std::sqrt(std::pow(SST[idx].Umin, 2) / 47.6); + SST[idx].Pmax = std::min(SST[idx].Pmax, std::pow(SST[idx].Umax, 2) / 47.6); + } + return true; +} + +bool physics::Vehicle::readLightsList(std::string const &Input) +{ + + cParser parser(Input); + if (false == parser.getTokens(2, false)) + { + WriteLog("Read LightsList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx > 16) + { + WriteLog("Read LightsList: number of entries exceeded capacity of the data table"); + return false; + } + parser >> Lights[0][idx] >> Lights[1][idx]; + // optional third column: the cab interior light the preset sets (eu07/maszyna#529). anything but a whole number + // (some rows carry stray notes after the two columns) leaves the cab light to its own switch + LightsCabLight[idx] = -1; + if (true == parser.getTokens(1, false)) + { + std::string cablight; + parser >> cablight; + int flags{-1}; + auto const [end, error]{std::from_chars(cablight.data(), cablight.data() + cablight.size(), flags)}; + if (error == std::errc{} && end == cablight.data() + cablight.size() && flags >= 0) + { + LightsCabLight[idx] = flags; + } + } + + return true; +} + +bool physics::Vehicle::readCompressorList(std::string const &Input) +{ + + cParser parser(Input); + if (false == parser.getTokens(4, false)) + { + WriteLog("Read CompressorList: arguments missing in line " + std::to_string(LISTLINE + 1)); + return false; + } + int idx = LISTLINE++; + if (idx > 8 - 1) + { + WriteLog("Read CompressorList: number of entries exceeded capacity of the data table"); + return false; + } + // NOTE: content of slot [x][0] is hardcoded elsewhere + parser >> air.compressor.config.list[0][idx + 1] >> air.compressor.config.list[1][idx + 1] >> air.compressor.config.list[2][idx + 1] >> air.compressor.config.list[3][idx + 1]; + + return true; +} + +// ************************************************************************************************* +// Q: 20160719 +// ************************************************************************************************* +void physics::Vehicle::BrakeValveDecode(std::string const &Valve) +{ + using enum TBrakeValve; + + std::map> valvetypes{{"W", W}, + {"W_Lu_L", W_Lu_L}, + {"W_Lu_XR", W_Lu_XR}, + {"W_Lu_VI", W_Lu_VI}, + {"K", K}, + {"Kg", Kg}, + {"Kp", Kp}, + {"Kss", Kss}, + {"Kkg", Kkg}, + {"Kkp", Kkp}, + {"Kks", Kks}, + {"Hikp1", Hikp1}, + {"Hikss", Hikss}, + {"Hikg1", Hikg1}, + {"KE", KE}, + {"SW", SW}, + {"EStED", EStED}, + {"NESt3", NESt3}, + {"ESt3", ESt3}, + {"LSt", LSt}, + {"ESt4", ESt4}, + {"ESt3AL2", ESt3AL2}, + {"EP1", EP1}, + {"EP2", EP2}, + {"M483", M483}, + {"CV1_L_TR", CV1_L_TR}, + {"CV1", CV1}, + {"CV1_R", CV1_R}}; + auto lookup = valvetypes.find(Valve); + brakes.config.distributorType = lookup != valvetypes.end() ? lookup->second : Other; + + if (brakes.config.distributorType == Other && contains(Valve, "ESt")) + { + + brakes.config.distributorType = ESt3; + } +} + +// ************************************************************************************************* +// Q: 20160719 +// ************************************************************************************************* +void physics::Vehicle::BrakeSubsystemDecode() +{ + using enum TBrakeSubSystem; + brakes.config.subsystem = ss_None; + switch (brakes.config.distributorType) + { + using enum TBrakeValve; + case W: + case W_Lu_L: + case W_Lu_VI: + case W_Lu_XR: + brakes.config.subsystem = ss_W; + break; + case ESt3: + case ESt3AL2: + case ESt4: + case EP2: + case EP1: + brakes.config.subsystem = ss_ESt; + break; + case KE: + brakes.config.subsystem = ss_KE; + break; + case CV1: + case CV1_L_TR: + brakes.config.subsystem = ss_Dako; + break; + case LSt: + case EStED: + brakes.config.subsystem = ss_LSt; + break; + default: + break; + } +} + +// ************************************************************************************************* +// Q: 20160717 +// Funkcja pelniaca role pierwotnej LoadChkFile wywolywana w dynobj.cpp w double +// TDynamicObject::Init() +// Po niej wykonywana jest CreateBrakeSys(), ktora jest odpowiednikiem CheckLocomotiveParameters() +// ************************************************************************************************* +bool physics::Vehicle::LoadFIZ(std::string const &chkpath) +{ + chkPath = chkpath; // assign class path for reloading + + ConversionError = 666; + std::string file = TypeName + ".fiz"; + + WriteLog("LOAD FIZ FROM " + file); + /* + std::ifstream in(file); + if (!in.is_open()) + { + WriteLog("E8 - FIZ FILE NOT EXIST."); + return false; + } + */ + cParser fizparser(file, cParser::buffer_FILE, chkpath); + if (false == fizparser.ok()) + { + WriteLog("E8 - FIZ FILE NOT EXIST."); + return false; + } + + return LoadFIZ_Parse(fizparser); +} + +// reads the vehicle definition from text in the .fiz format, e.g. one made up by a unit test +bool physics::Vehicle::LoadFIZ_Text(std::string const &Text) +{ + ConversionError = 666; + cParser fizparser(Text, cParser::buffer_TEXT); + return LoadFIZ_Parse(fizparser); +} + +bool physics::Vehicle::LoadFIZ_Parse(cParser &fizparser) +{ + LISTLINE = 0; + startBPT = false; + startMPT = false; + startMPT0 = false; + startRLIST = false; + startUCLIST = false; + startDLIST = false; + startDIZELMOMENTUMLIST = false; + startDIZELV2NMAXLIST = false; + startHYDROTCLIST = false; + startPMAXLIST = false; + startFFLIST = false; + startFFEDLIST = false; + startWWLIST = false; + startWiperList = false; + startDimmerList = false; + startLIGHTSLIST = false; + startCOMPRESSORLIST = false; + + ConversionError = 0; + + // Zbieranie danych zawartych w pliku FIZ + // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + std::map> fizlines; + std::string inputline; + /* + while (std::getline(in, inputline)) + */ + while (fizparser.ok()) + { + + inputline = fizparser.getToken(false, "\n\r"); + + if (inputline.starts_with("//") || contains(inputline, '#')) + { + // skip commented lines + continue; + } + + if (!inputline.empty() && inputline.front() == ' ') + { + // guard against malformed config files with leading spaces + inputline.erase(0, inputline.find_first_not_of(' ')); + } + + // trim CR at end (mainly for linux) + if (!inputline.empty() && inputline.back() == '\r') + inputline.pop_back(); + + if (inputline.length() == 0) + { + startBPT = false; + continue; + } + + if (LoadFIZ_TableEnd(inputline) || LoadFIZ_Section(inputline, fizlines) || LoadFIZ_TableSection(inputline, fizlines)) + { + continue; + } + LoadFIZ_TableRow(inputline); + } // while line + /* + in.close(); + */ + // Operacje na zebranych parametrach - przypisywanie do wlasciwych zmiennych i ustawianie + // zaleznosci + + bool result; + if (ConversionError == 0) + result = true; + else + result = false; + + // ustawiamy domyslna pozycje dimmera + // the DefaultPos of a short or an empty DimmerList would put the dimmer outside of it + modernDimmerDefaultPosition = clampDimmerPosition(modernDimmerDefaultPosition); + modernDimmerPosition = clampDimmerPosition(modernDimmerPosition); + if (!enableModernDimmerValue) + { + modernDimmerPosition = modernDimmerDefaultPosition; + } + + WriteLog("CERROR: " + std::to_string(ConversionError) + ", SUCCES: " + std::to_string(result)); + return result; +} + +// the end of the table being read; returns whether the line is one +bool physics::Vehicle::LoadFIZ_TableEnd(std::string const &inputline) const +{ + // checking if table parsing should be switched off goes first... + if (issection("END-MPT", inputline)) + { + startBPT = false; + startMPT = false; + startMPT0 = false; + return true; + } + if (issection("END-RL", inputline)) + { + startBPT = false; + startRLIST = false; + return true; + } + if (issection("END-UCL", inputline)) + { + startBPT = false; + startUCLIST = false; + return true; + } + if (issection("END-DL", inputline)) + { + startBPT = false; + startDLIST = false; + return true; + } + if (issection("END-DML", inputline)) + { + startBPT = false; + startDIZELMOMENTUMLIST = false; + return true; + } + if (issection("END-V2NL", inputline)) + { + startBPT = false; + startDIZELV2NMAXLIST = false; + return true; + } + if (issection("END-HTCL", inputline)) + { + startBPT = false; + startHYDROTCLIST = false; + return true; + } + if (issection("END-PML", inputline)) + { + startBPT = false; + startPMAXLIST = false; + return true; + } + if (issection("endff", inputline)) + { + startBPT = false; + startFFLIST = false; + startFFEDLIST = false; + return true; + } + if (issection("endwl", inputline)) + { + // skonczylismy czytac liste konfiguracji wycieraczek + startBPT = false; + startWiperList = false; + return true; + } + if (issection("endDimmerList", inputline)) + { + // skonczylismy czytac liste konfiguracji pstryka od przyciemnienia + startBPT = false; + startDimmerList = false; + return true; + } + if (issection("END-WWL", inputline)) + { + startBPT = false; + startWWLIST = false; + return true; + } + if (issection("endL", inputline)) + { + startBPT = false; + startLIGHTSLIST = false; + return true; + } + if (issection("endCL", inputline)) + { + startBPT = false; + startCOMPRESSORLIST = false; + return true; + } + return false; +} + +// a section of the definition giving values, kept in fizlines by its name; returns whether the line is one +bool physics::Vehicle::LoadFIZ_Section(std::string const &inputline, std::map> &fizlines) +{ + // ...then all recognized sections... + if (issection("Param.", inputline)) + { + startBPT = false; + fizlines.try_emplace("Param", inputline); + LoadFIZ_Param(inputline); + return true; + } + + if (issection("Load:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Load", inputline); + LoadFIZ_Load(inputline); + return true; + } + + if (issection("Dimensions:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Dimensions", inputline); + LoadFIZ_Dimensions(inputline); + return true; + } + + if (issection("Wheels:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Wheels", inputline); + LoadFIZ_Wheels(inputline); + return true; + } + + if (issection("Brake:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Brake", inputline); + LoadFIZ_Brake(inputline); + return true; + } + + if (issection("Doors:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Doors", inputline); + LoadFIZ_Doors(inputline); + return true; + } + + if (issection("BuffCoupl.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl", inputline); + LoadFIZ_BuffCoupl(inputline, 0); + return true; + } + + else if (issection("BuffCoupl1.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl1", inputline); + LoadFIZ_BuffCoupl(inputline, 1); + return true; + } + + else if (issection("BuffCoupl2.", inputline)) + { + + startBPT = false; + fizlines.try_emplace("BuffCoupl2", inputline); + LoadFIZ_BuffCoupl(inputline, 2); + return true; + } + + if (issection("TurboPos:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("TurboPos", inputline); + LoadFIZ_TurboPos(inputline); + return true; + } + + if (issection("Cntrl.", inputline)) + { + + startBPT = true; + LISTLINE = 0; + fizlines.try_emplace("Cntrl", inputline); + LoadFIZ_Cntrl(inputline); + return true; + } + + if (issection("Headlights:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Headlights", inputline); + LoadFIZ_Headlights(inputline); + return true; + } + + if (issection("Blending:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("Blending", inputline); + LoadFIZ_Blending(inputline); + return true; + } + + if (issection("DCEMUED:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("DCEMUED", inputline); + LoadFIZ_DCEMUED(inputline); + return true; + } + + if (issection("SpringBrake:", inputline)) + { + + startBPT = false; + LISTLINE = 0; + fizlines.try_emplace("SpringBrake", inputline); + LoadFIZ_SpringBrake(inputline); + return true; + } + + if (issection("Light:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Light", inputline); + LoadFIZ_Light(inputline); + return true; + } + + if (issection("Security:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Security", inputline); + SecuritySystem.load(inputline, vmax); + extract_value(EmergencyBrakeWarningSignal, "EmergencyBrakeWarningSignal", inputline, ""); + return true; + } + + if (issection("Clima:", inputline)) + { + + startBPT = false; + fizlines.try_emplace("Clima", inputline); + LoadFIZ_Clima(inputline); + return true; + } + + if (issection("Power:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Power", inputline); + LoadFIZ_Power(inputline); + return true; + } + + if (issection("SpeedControl:", inputline)) + { + startBPT = false; + fizlines.try_emplace("SpeedControl", inputline); + LoadFIZ_SpeedControl(inputline); + return true; + } + + if (issection("Engine:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Engine", inputline); + LoadFIZ_Engine(inputline); + return true; + } + + if (issection("Switches:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Switches", inputline); + LoadFIZ_Switches(inputline); + return true; + } + + if (issection("Circuit:", inputline)) + { + startBPT = false; + fizlines.try_emplace("Circuit", inputline); + LoadFIZ_Circuit(inputline); + return true; + } + + if (issection("AI:", inputline)) + { + startBPT = false; + fizlines.try_emplace("AI", inputline); + LoadFIZ_AI(inputline); + return true; + } + + return false; +} + +// a section of the definition opening a table, kept in fizlines by its name; returns whether the line is one +bool physics::Vehicle::LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines) +{ + if (issection("MotorParamTable:", inputline)) + { + startBPT = false; + startMPT = true; + LISTLINE = 0; + fizlines.try_emplace("MotorParamTable", inputline); + LoadFIZ_MotorParamTable(inputline); + return true; + } + + if (issection("MotorParamTable0:", inputline)) + { + startBPT = false; + startMPT0 = true; + LISTLINE = 0; + return true; + } + + if (issection("RList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("RList", inputline); + startRLIST = true; + LISTLINE = 0; + LoadFIZ_RList(inputline); + return true; + } + + if (issection("UCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("UCList", inputline); + startUCLIST = true; + LISTLINE = 0; + LoadFIZ_UCList(inputline); + return true; + } + + if (issection("DList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DList", inputline); + startDLIST = true; + LISTLINE = 0; + LoadFIZ_DList(inputline); + return true; + } + + if (issection("DMList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("DMList", inputline); + startDIZELMOMENTUMLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("HTCList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("HTCList", inputline); + startHYDROTCLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("PmaxList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("PmaxList", inputline); + startPMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("V2NList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("V2NList", inputline); + startDIZELV2NMAXLIST = true; + LISTLINE = 0; + return true; + } + + if (issection("ffList:", inputline)) + { + startBPT = false; + startFFLIST = true; + LISTLINE = 0; + LoadFIZ_FFList(inputline); + return true; + } + + if (issection("ffBrakeList:", inputline)) + { + startBPT = false; + startFFEDLIST = true; + LISTLINE = 0; + LoadFIZ_FFEDList(inputline); + return true; + } + + if (issection("WWList:", inputline)) + { + startBPT = false; + startWWLIST = true; + LISTLINE = 0; + + return true; + } + + if (issection("WiperList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("WiperList", inputline); + startWiperList = true; + LISTLINE = 0; + LoadFIZ_WiperList(inputline); + + return true; + } + + if (issection("DimmerList:", inputline)) + { + dimPositions.clear(); // uzywamy customowej listy + startBPT = false; + startDimmerList = true; + fizlines.try_emplace("DimmerList", inputline); + LoadFIZ_DimmerList(inputline); + return true; + } + + if (issection("LightsList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("LightsList", inputline); + startLIGHTSLIST = true; + LISTLINE = 0; + LoadFIZ_LightsList(inputline); + return true; + } + + if (issection("CompressorList:", inputline)) + { + startBPT = false; + fizlines.try_emplace("CompressorList", inputline); + startCOMPRESSORLIST = true; + LISTLINE = 0; + LoadFIZ_CompressorList(inputline); + return true; + } + return false; +} + +// a row of the table being read +void physics::Vehicle::LoadFIZ_TableRow(std::string const &inputline) +{ + // ...and finally, table parsers. + // NOTE: once table parsing is enabled it lasts until switched off, when another section is recognized + if (true == startBPT) + { + readBPT(inputline); + return; + } + if (true == startMPT) + { + readMPT(inputline); + return; + } + if (true == startMPT0) + { + readMPT0(inputline); + return; + } + if (true == startRLIST) + { + readRList(inputline); + return; + } + if (true == startUCLIST) + { + readUCList(inputline); + return; + } + if (true == startDLIST) + { + readDList(inputline); + return; + } + if (true == startDIZELMOMENTUMLIST) + { + readDMList(inputline); + return; + } + if (true == startDIZELV2NMAXLIST) + { + readV2NMAXList(inputline); + return; + } + if (true == startHYDROTCLIST) + { + readHTCList(inputline); + return; + } + if (true == startPMAXLIST) + { + readPmaxList(inputline); + return; + } + if (true == startFFLIST) + { + readFFList(inputline); + return; + } + if (true == startFFEDLIST) + { + readFFEDList(inputline); + return; + } + if (true == startWWLIST) + { + readWWList(inputline); + return; + } + if (true == startWiperList) + { + readWiperList(inputline); + return; + } + if (true == startDimmerList) + { + readDimmerList(inputline); + } + if (true == startLIGHTSLIST) + { + readLightsList(inputline); + return; + } + if (true == startCOMPRESSORLIST) + { + readCompressorList(inputline); + return; + } +} + +bool physics::Vehicle::reload_FIZ() +{ + WriteLog("[DEV] Reloading FIZ for " + Name); + // pause simulation + Global.iPause |= 0b1000; + if (bool result = LoadFIZ(chkPath); result == true) + { + // jesli sie udalo przeladowac FIZ + Global.iPause &= 0b0111; + WriteLog("[DEV] FIZ reloaded for " + Name); + } + else + { + // failed to reload - exit simulator + ErrorLog("[DEV] Failed to reload fiz for vehicle " + Name); + } + return true; +} diff --git a/physics/components/fizsections.cpp b/physics/components/fizsections.cpp new file mode 100644 index 000000000..08643375c --- /dev/null +++ b/physics/components/fizsections.cpp @@ -0,0 +1,1835 @@ +/* +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/. +*/ + +// reading the vehicle definition (.fiz): the sections and their keywords + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +int s2NPW(std::string s) +{ // wylicza ilosc osi napednych z opisu ukladu osi + const char A = 64; + int NPW = 0; + for (char const chentry : s) + { + if (chentry >= (char)65 && chentry <= (char)90) + NPW += chentry - A; + } + return NPW; +} + +int s2NNW(std::string s) +{ // wylicza ilosc osi nienapedzanych z opisu ukladu osi + const char Zero = 48; + int NNW = 0; + for (char const ch : s) + { + if (ch >= (char)49 && ch <= (char)57) + NNW += ch - Zero; + } + return NNW; +} + +void physics::Vehicle::LoadFIZ_Param(std::string const &line) +{ + + extract_value(emptyMass, "M", line, "0"); + extract_value(mred, "Mred", line, "0"); + extract_value(vmax, "Vmax", line, "0"); + extract_value(Power, "PWR", line, "0"); + extract_value(SandCapacity, "SandCap", line, "0"); + extract_value(trainHeating.config.power, "HeatingP", line, "0"); + extract_value(LightPower, "LightP", line, "0"); + + { + std::map> categories{{"train", 1}, {"road", 2}, {"unimog", 3}, {"ship", 4}, {"airplane,", 8}}; + std::string category; + extract_value(category, "Category", line, "none"); + auto lookup = categories.find(category); + CategoryFlag = lookup != categories.end() ? lookup->second : 0; + if (CategoryFlag == 0) + { + ErrorLog("Unknown vehicle category: \"" + category + "\"."); + } + } + + { + std::map> types{ + {"pseudodiesel", train_type::pseudodiesel}, + {"ezt", train_type::emu}, + {"dmu", train_type::dmu}, + {"sn61", train_type::sn61}, + {"et22", train_type::et22}, + {"et40", train_type::et40}, + {"et41", train_type::et41}, + {"et42", train_type::et42}, + {"ep05", train_type::ep05}, + {"181", train_type::skoda181}, + {"182", train_type::skoda181} // na razie tak + }; + std::string type; + extract_value(type, "Type", line, "none"); + auto lookup = types.find(ToLower(type)); + trainType = lookup != types.end() ? lookup->second : train_type::generic; + } + + if (trainType == train_type::emu) + { + + IminLo = 1; + IminHi = 2; + imin = 1; + } +} + +void physics::Vehicle::LoadFIZ_Load(std::string const &line) +{ + + auto const acceptedloads{Split(extract_value("LoadAccepted", line), ',')}; + + if (acceptedloads.empty()) + { + return; + } + + auto const minoffsets{Split(extract_value("LoadMinOffset", line), ',')}; + auto minoffset{0.f}; + auto minoffsetsiterator{std::begin(minoffsets)}; + // NOTE: last (if any) offset parameter retrieved from the list applies to the remainder of the list + // TBD, TODO: include other load parameters in this system + for (auto &load : acceptedloads) + { + if (minoffsetsiterator != std::end(minoffsets)) + { + minoffset = std::stof(*minoffsetsiterator); + ++minoffsetsiterator; + } + LoadAttributes.emplace_back(ToLower(load), minoffset); + } + + extract_value(maxLoad, "MaxLoad", line, ""); + extract_value(LoadQuantity, "LoadQ", line, ""); + extract_value(OverLoadFactor, "OverLoadFactor", line, ""); + extract_value(LoadSpeed, "LoadSpeed", line, ""); + extract_value(UnLoadSpeed, "UnLoadSpeed", line, ""); +} + +void physics::Vehicle::LoadFIZ_Headlights(std::string const &line) +{ + extract_value(refR, "LampRed", line, ""); + extract_value(refG, "LampGreen", line, ""); + extract_value(refB, "LampBlue", line, ""); + + extract_value(dimMultiplier, "DimmedMultiplier", line, ""); + extract_value(normMultiplier, "NormalMultiplier", line, ""); + extract_value(highDimMultiplier, "HighbeamDimmedMultiplier", line, ""); + extract_value(highMultiplier, "HighBeamMultiplier", line, ""); +} + +void physics::Vehicle::LoadFIZ_Dimensions(std::string const &line) +{ + + extract_value(Dim.L, "L", line, ""); + extract_value(Dim.H, "H", line, ""); + extract_value(Dim.W, "W", line, ""); + // height of the centre of gravity of the empty vehicle [m], for the criteria of derailment + extract_value(CentreOfGravity, "CoGH", line, ""); + + extract_value(Cx, "Cx", line, "0.3"); + if (Dim.H <= 2.0) + { + // gdyby nie było parametru, lepsze to niż zero + Floor = static_cast(Dim.H); + } + else + { + // zgodność wsteczna + Floor = 0.0; + } + extract_value(Floor, "Floor", line, ""); +} + +void physics::Vehicle::LoadFIZ_Wheels(std::string const &line) +{ + + extract_value(wheelDiameter, "D", line, ""); + WheelDiameterL = wheelDiameter; // gdyby nie było parametru, lepsze to niż zero + extract_value(WheelDiameterL, "Dl", line, ""); + WheelDiameterT = wheelDiameter; // gdyby nie było parametru, lepsze to niż zero + extract_value(WheelDiameterT, "Dt", line, ""); + + extract_value(TrackW, "Tw", line, ""); + extract_value(AxleInertialMoment, "AIM", line, ""); + + extract_value(AxleArangement, "Axle", line, ""); + nPoweredAxles = s2NPW(AxleArangement); + nAxles = nPoweredAxles + s2NNW(AxleArangement); + + BearingType = extract_value("BearingType", line) == "Roll" ? 1 : 0; + + extract_value(aDist, "Ad", line, ""); + extract_value(bDist, "Bd", line, ""); + + if (AxleInertialMoment <= 0.0) + { + /* + AxleInertialMoment = 1.0; + */ + // approximation formula by youby + auto const k = 472.0; // arbitrary constant + AxleInertialMoment = k / 4.0 * std::pow(wheelDiameter, 4.0) * nAxles; + mred = k * std::pow(wheelDiameter, 2.0) * nAxles; + } +} + +void physics::Vehicle::LoadFIZ_Brake(std::string const &line) +{ + + extract_value(brakes.config.distributorParameters, "BrakeValve", line, ""); + BrakeValveDecode(brakes.config.distributorParameters); + BrakeSubsystemDecode(); + + extract_value(brakes.config.blocksPerAxle, "NBpA", line, ""); + extract_value(brakes.config.maxForce, "MBF", line, ""); + extract_value(brakes.config.distributorSize, "Size", line, ""); + extract_value(brakes.config.trackBrakeForce, "TBF", line, ""); + brakes.config.trackBrakeForce *= 1000.0; + + extract_value(brakes.config.maxCylinderPressure[3], "MaxBP", line, ""); + if (brakes.config.maxCylinderPressure[3] > 0.0) + { + + extract_value(brakes.config.cylinders.count, "BCN", line, ""); + if (brakes.config.cylinders.count > 0) + { + + extract_value(brakes.config.maxCylinderPressure[0], "MaxLBP", line, ""); + if (brakes.config.maxCylinderPressure[0] < 0.01) + { + brakes.config.maxCylinderPressure[0] = brakes.config.maxCylinderPressure[3]; + } + extract_value(brakes.config.maxCylinderPressure[1], "TareMaxBP", line, ""); + extract_value(brakes.config.maxCylinderPressure[2], "MedMaxBP", line, ""); + extract_value(brakes.config.maxCylinderPressure[4], "MaxASBP", line, ""); + if (brakes.config.maxCylinderPressure[4] < 0.01) + { + brakes.config.maxCylinderPressure[4] = 0.0; + } + + extract_value(brakes.config.cylinders.radius, "BCR", line, ""); + extract_value(brakes.config.cylinders.stroke, "BCD", line, ""); + extract_value(brakes.config.cylinders.springForce, "BCS", line, ""); + extract_value(brakes.config.cylinders.slackAdjusterForce, "BSA", line, ""); + extract_value(brakes.config.cylinders.riggingEfficiency, "BRE", line, "1"); + + extract_value(brakes.config.cylinders.leverRatio[0], "BCM", line, ""); + extract_value(brakes.config.cylinders.leverRatio[1], "BCMlo", line, ""); + extract_value(brakes.config.cylinders.leverRatio[2], "BCMHi", line, ""); + + brakes.config.pressureToForce = 100 * M_PI * std::pow(brakes.config.cylinders.radius, 2); // w kN/bar + + if (brakes.config.cylinders.leverRatio[1] > 0.0 || brakes.config.maxCylinderPressure[1] > 0.0) + { + brakes.loadSetting = 1; + } + else + { + brakes.loadSetting = 0; + } + + brakes.config.cylinderVolume = M_PI * std::pow(brakes.config.cylinders.radius, 2) * brakes.config.cylinders.stroke * brakes.config.cylinders.count; + extract_value(brakes.config.valveVolume, "BVV", line, ""); + + { + std::map> brakemethods{{"P10-Bg", bp_P10Bg}, {"P10-Bgu", bp_P10Bgu}, {"FR513", bp_FR513}, {"FR510", bp_FR510}, {"Cosid", bp_Cosid}, + {"P10yBg", bp_P10yBg}, {"P10yBgu", bp_P10yBgu}, {"Disk1", bp_D1}, {"Disk1+Mg", bp_D1 + bp_MHS}, {"Disk2", bp_D2}}; + auto lookup = brakemethods.find(extract_value("BM", line)); + brakes.config.method = lookup != brakemethods.end() ? lookup->second : 0; + } + + extract_value(brakes.config.rapidRatio, "RM", line, "1"); + extract_value(brakes.config.rapidSpeed, "RV", line, "55"); + } + } + else + { + // maxbrakepress[3] == 0 or less + brakes.config.pressureToForce = 0; + } + + // Ra 2014-07: trochę niedokładności + // the draws are sequenced: the order of the operands of '-' is unspecified, and GCC and MSVC draw them the other way round + auto const firstdraw{Random(10)}; + brakes.controlReservoirPressure = 5 + 0.001 * (Random(10) - firstdraw); + extract_value(brakes.controlReservoirPressure, "HiPP", line, ""); + brakes.config.pipeHighPressure = brakes.controlReservoirPressure; + brakes.config.pipeLowPressure = std::min(brakes.config.pipeHighPressure, 3.5); + extract_value(brakes.config.pipeLowPressure, "LoPP", line, ""); + brakes.config.pipePressureRange = brakes.config.pipeHighPressure - brakes.config.pipeLowPressure; + + extract_value(air.config.mainReservoirVolume, "Vv", line, ""); + /* + if( VeselVolume == 0.0 ) { VeselVolume = 0.01; } + */ + extract_value(air.compressor.config.minPressure, "MinCP", line, ""); + extract_value(air.compressor.config.maxPressure, "MaxCP", line, ""); + extract_value(air.compressor.config.minPressureCabB, "MinCP_B", line, ""); + extract_value(air.compressor.config.maxPressureCabB, "MaxCP_B", line, ""); + extract_value(air.compressor.config.tankValve, "CompressorTankValve", line, ""); + extract_value(air.compressor.config.speed, "CompressorSpeed", line, ""); + extract_value(brakes.emergencyValve.offPressure, "MinEVP", line, ""); + extract_value(brakes.emergencyValve.onPressure, "MaxEVP", line, ""); + extract_value(brakes.emergencyValve.area, "EVArea", line, ""); + extract_value(brakes.config.universalButtonActions[0], "UBB1", line, ""); + extract_value(brakes.config.universalButtonActions[1], "UBB2", line, ""); + extract_value(brakes.config.universalButtonActions[2], "UBB3", line, ""); + extract_value(brakes.pipeLock.onPressure, "LPOn", line, "-1"); + extract_value(brakes.pipeLock.offPressure, "LPOff", line, "-1"); + extract_value(brakes.pipeLock.unlockHandlePosition, "HandlePipeUnlockPos", line, "-3"); + extract_value(brakes.config.emergencyCutsOffDriverValve, "EmergencyCutsOffHandle", line, ""); + { + using enum CompressorSupply; + std::map> compressorpowers{ + {"Main", mainCircuit}, + // the default: powered by the converter, switched by hand + {"Converter", converter}, + {"Engine", engine}, // equivalent of Main, TODO: separate 'main' and 'engine' in the code + {"Coupler1", frontUnitConverter}, // włączana w silnikowym EZT z przodu + {"Coupler2", rearUnitConverter} // włączana w silnikowym EZT z tyłu + }; + auto lookup = compressorpowers.find(extract_value("CompressorPower", line)); + air.compressor.config.supply = lookup != compressorpowers.end() ? lookup->second : converterManual; + } + extract_value(air.compressor.config.startDelay, "CompressorStartDelay", line, ""); + + if (true == extract_value(air.config.leakRate, "AirLeakRate", line, "")) + { + // the parameter is provided in form of a multiplier, where 1.0 means the default rate of 0.01 + air.config.leakRate *= 0.01; + } + + extract_value(ReleaserEnabledOnlyAtNoPowerPos, "ReleaserPowerPosLock", line, EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric ? "yes" : "no"); + + if (air.compressor.config.minPressureCabB > 0.0) + { + air.compressor.config.minPressureCabA = air.compressor.config.minPressure; + air.compressor.config.cabDependent = true; + } + else + { + air.compressor.config.minPressureCabB = air.compressor.config.minPressure; + } + if (air.compressor.config.maxPressureCabB > 0.0) + { + air.compressor.config.maxPressureCabA = air.compressor.config.maxPressure; + air.compressor.config.cabDependent = true; + } + else + { + air.compressor.config.maxPressureCabB = air.compressor.config.maxPressure; + } +} + +void physics::Vehicle::LoadFIZ_Doors(std::string const &line) +{ + + std::map> doorcontrols{ + {"Passenger", control_t::passenger}, {"AutomaticCtrl", control_t::autonomous}, {"DriverCtrl", control_t::driver}, {"Conductor", control_t::conductor}, {"Mixed", control_t::mixed}}; + // opening method + { + auto lookup = doorcontrols.find(extract_value("OpenCtrl", line)); + Doors.open_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; + } + // closing method + { + auto lookup = doorcontrols.find(extract_value("CloseCtrl", line)); + Doors.close_control = lookup != doorcontrols.end() ? lookup->second : control_t::passenger; + } + // automatic closing conditions + extract_value(Doors.auto_duration, "DoorStayOpen", line, ""); + extract_value(Doors.auto_velocity, "DoorAutoCloseVel", line, ""); + extract_value(Doors.auto_include_remote, "DoorAutoCloseRemote", line, ""); + // operation permit + extract_value(Doors.permit_needed, "DoorNeedPermit", line, ""); + // the door closure lamp (SOD) of the cab signals the doors of the whole consist + extract_value(Doors.closure_signal, "DoorClosureSignal", line, ""); + { + auto permitpresets = Split(extract_value("DoorPermitList", line), '|'); + for (auto const &permit : permitpresets) + { + Doors.permit_presets.emplace_back(std::stoi(permit)); + } + if (false == Doors.permit_presets.empty()) + { + // HACK: legacy position indices start from 1, so we deduct 1 to arrive at proper index into the array + extract_value(Doors.permit_preset, "DoorPermitListDefault", line, "1"); + Doors.permit_preset = std::min(static_cast(Doors.permit_presets.size()), Doors.permit_preset) - 1; + } + } + + extract_value(Doors.open_rate, "OpenSpeed", line, ""); + extract_value(Doors.open_delay, "DoorOpenDelay", line, ""); + extract_value(Doors.close_rate, "CloseSpeed", line, ""); + extract_value(Doors.close_delay, "DoorCloseDelay", line, ""); + extract_value(Doors.range, "DoorMaxShiftL", line, ""); + extract_value(Doors.range, "DoorMaxShiftR", line, ""); + extract_value(Doors.range_out, "DoorMaxShiftPlug", line, ""); + + std::map> doortypes{ + {"Shift", 1}, + {"Rotate", 2}, + {"Fold", 3}, + {"Plug", 4}, + }; + // opening method + { + auto lookup = doortypes.find(extract_value("DoorOpenMethod", line)); + Doors.type = lookup != doortypes.end() ? lookup->second : 2; // default type is plain, rotating door + } + + extract_value(Doors.has_warning, "DoorClosureWarning", line, ""); + extract_value(Doors.has_autowarning, "DoorClosureWarningAuto", line, ""); + extract_value(Doors.has_lock, "DoorBlocked", line, ""); + extract_value(Doors.doorLockSpeed, "DoorLockSpeed", line, ""); + { + auto const remotedoorcontrol{Doors.open_control == control_t::driver || Doors.open_control == control_t::conductor || Doors.open_control == control_t::mixed}; + + extract_value(Doors.voltage, "DoorVoltage", line, remotedoorcontrol ? "24" : "0"); + } + + extract_value(Doors.step_rate, "PlatformSpeed", line, ""); + extract_value(Doors.step_range, "PlatformMaxShift", line, ""); + + std::string platformopenmethod; + extract_value(platformopenmethod, "PlatformOpenMethod", line, ""); + if (platformopenmethod == "Shift") + { + Doors.step_type = 1; + } // przesuw + + extract_value(MirrorMaxShift, "MirrorMaxShift", line, ""); + extract_value(MirrorVelClose, "MirrorVelClose", line, ""); + + extract_value(DoorsOpenWithPermitAfter, "DoorOpenWithPermit", line, ""); + extract_value(doorsPermitLightBlinking, "DoorsPermitLightBlinking", line, ""); +} +namespace +{ + + +// the value of an optional key of the line, or the default without it +double optional_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{Default}; + extract_value(value, Key, Line, ""); + return value; +} + +// the value of an optional key of the line given in kilo-units, in units; or the default (in units) without it +double optional_kilo_value(std::string const &Line, std::string const &Key, double const Default) +{ + auto value{0.0}; + return extract_value(value, Key, Line, "") && value > 0.0 ? value * 1000.0 : Default; +} + +// the play of a coupling as made, for each kind: a screw coupling is tightened so that the buffers touch, the knuckles of +// an automatic coupler have about a centimetre between them, a chain hangs loose +double default_slack(TCouplerType const Type) +{ + switch (Type) + { + case TCouplerType::Automatic: + return 0.005; + case TCouplerType::Chain: + return 0.05; + default: + return 0.0; + } +} + +// the parameters of the physical model of the coupling (couplerphysics in eu07.ini, see couplerphysics.h), taken from +// those of the legacy model, and the optional keys of the .fiz for what the legacy model doesn't have: +// Slack [m] the play of the coupling of this end, negative for a screw coupling tightened to press the buffers in +// ProgB, ProgC [-] progression of the buffers and of the draw gear, 0 linear, up to 0.9 +// UnloadB, UnloadC [-] force of the unloading curve of the buffers and of the draw gear to that of the loading one +// FyieldC [kN] the force past which the link stretches for good; DbreakC [m] the elongation at which it breaks +// kL [kN/m] stiffness of the steel parts past the travel of the springs; FcrushB [kN] the buffers give under it +// RestitutionSolid [-] coefficient of restitution of a hit on the springs gone solid +coupler_physics::end_parameters coupler_physics_parameters(TCoupling const &Coupler, std::string const &Line) +{ + coupler_physics::end_parameters parameters; + parameters.buffers = {Coupler.SpringKB, Coupler.DmaxB, std::clamp(optional_value(Line, "ProgB", 0.5), 0.0, 0.9)}; + parameters.draw_gear = {Coupler.SpringKC, Coupler.DmaxC, std::clamp(optional_value(Line, "ProgC", 0.3), 0.0, 0.9)}; + // only a screw coupling can be tightened to press the buffers in, and not past their travel + auto const tightest{Coupler.CouplerType == TCouplerType::Screw ? -Coupler.DmaxB : 0.0}; + parameters.slack = std::max(optional_value(Line, "Slack", default_slack(Coupler.CouplerType)), tightest); + // the legacy model sprang back at beta of the force it was loaded with + auto const unloading{Coupler.beta > 0.0 && Coupler.beta < 1.0 ? Coupler.beta : 0.5}; + parameters.buffers_unloading = std::clamp(optional_value(Line, "UnloadB", unloading), 0.05, 1.0); + parameters.draw_gear_unloading = std::clamp(optional_value(Line, "UnloadC", unloading), 0.05, 1.0); + // as much as the legacy model had + parameters.damping = CouplerTune * (Coupler.FmaxC + Coupler.FmaxB) * std::max(Coupler.beta, 0.0); + + // FmaxC is the rated breaking force of the coupling + auto const ultimate{std::max(Coupler.FmaxC, 1.0)}; + auto const yield{std::min(optional_kilo_value(Line, "FyieldC", 0.8 * ultimate), ultimate)}; + auto const elongation{std::max(optional_value(Line, "DbreakC", 0.02), 0.001)}; + parameters.link = {yield, ultimate, std::max((ultimate - yield) / elongation, 1.0), Coupler.CouplerType != TCouplerType::Articulated}; + // the steel parts give a few millimetres under the rated force + parameters.link_stiffness = optional_kilo_value(Line, "kL", ultimate / 0.003); + parameters.crush_force = optional_kilo_value(Line, "FcrushB", 2.5 * std::max(Coupler.FmaxB, Coupler.FmaxC)); + parameters.solid_restitution = std::clamp(optional_value(Line, "RestitutionSolid", parameters.solid_restitution), 0.05, 0.95); + return parameters; +} + +void scale_strength(coupler_physics::link_strength &Link, double const Factor) +{ + Link.yield *= Factor; + Link.ultimate *= Factor; +} + +// the optional keys of the collisions past the buffers (physics.collisions new, see collision.h), what's not given +// comes from the kind of the vehicle: +// FcrushPeak, FcrushPlateau [kN] the force the end starts to crush at, and keeps crushing at +// CrushOnset, CrushDensify, CrushLimit [m] the crush the peak drops at, it packs down past, it can't go past +// CrushHardening [1/m] the growth of the force past CrushDensify, to the plateau for each metre +// CrashZone [yes/no] built to EN 15227: energy absorbers and anticlimbers; AntiClimber [yes/no] on its own +// BufferHeight [m] of the empty vehicle above the rail +// BufferCategory [A/B/C/L/P] the buffers of EN 15551 (P those of the coaches) in place of kB and DmaxB +collision::end_definition collision_definition(std::string const &Line) +{ + collision::end_definition definition; + auto const number = [&Line](std::string const &Key, double const Scale) -> std::optional { + auto value{0.0}; + if (extract_value(value, Key, Line, "") && value >= 0.0) + { + return value * Scale; + } + return std::nullopt; + }; + auto const flag = [&Line](std::string const &Key) -> std::optional { + auto value{false}; + if (extract_value(value, Key, Line, "")) + { + return value; + } + return std::nullopt; + }; + definition.peak = number("FcrushPeak", 1000.0); + definition.plateau = number("FcrushPlateau", 1000.0); + definition.onset = number("CrushOnset", 1.0); + definition.densify = number("CrushDensify", 1.0); + definition.hardening = number("CrushHardening", 1.0); + definition.limit = number("CrushLimit", 1.0); + definition.crash_zone = flag("CrashZone"); + definition.anticlimber = flag("AntiClimber"); + definition.buffer_height = number("BufferHeight", 1.0); + return definition; +} + +} // namespace + +void physics::Vehicle::LoadFIZ_BuffCoupl(std::string const &line, int const Index) +{ + + TCoupling *thiscoupler; + if (Index == 2) + { + thiscoupler = &Couplers[1]; + } + else + { + thiscoupler = &Couplers[0]; + } + + std::map> couplertypes{ + {"Automatic", TCouplerType::Automatic}, {"Screw", TCouplerType::Screw}, {"Chain", TCouplerType::Chain}, {"Bare", TCouplerType::Bare}, {"Articulated", TCouplerType::Articulated}, + }; + auto lookup = couplertypes.find(extract_value("CType", line)); + thiscoupler->CouplerType = lookup != couplertypes.end() ? lookup->second : TCouplerType::NoCoupler; + + extract_value(thiscoupler->SpringKC, "kC", line, ""); + extract_value(thiscoupler->DmaxC, "DmaxC", line, ""); + extract_value(thiscoupler->FmaxC, "FmaxC", line, ""); + extract_value(thiscoupler->SpringKB, "kB", line, ""); + extract_value(thiscoupler->DmaxB, "DmaxB", line, ""); + extract_value(thiscoupler->FmaxB, "FmaxB", line, ""); + extract_value(thiscoupler->beta, "beta", line, ""); + // the sets are numbers in the definition, the sums of the numbers of the kinds of coupling + auto automaticflag{thiscoupler->AutomaticCouplingFlag.Bits()}; + extract_value(automaticflag, "AutomaticFlag", line, ""); + thiscoupler->AutomaticCouplingFlag = CouplingSet::FromBits(automaticflag); + auto allowedflag{thiscoupler->AllowedFlag.Bits()}; + extract_value(allowedflag, "AllowedFlag", line, ""); + // negative: the coupling is permanent besides + thiscoupler->AllowedFlag = allowedflag < 0 ? CouplingSet::FromBits(-allowedflag) | Coupling::permanent : CouplingSet::FromBits(allowedflag); + auto powercoupling{thiscoupler->PowerCoupling.Bits()}; + extract_value(powercoupling, "PowerCoupling", line, ""); + thiscoupler->PowerCoupling = CouplingSet::FromBits(powercoupling); + auto powerflag{thiscoupler->PowerFlag.Bits()}; + extract_value(powerflag, "PowerFlag", line, ""); + thiscoupler->PowerFlag = CouplingSet::FromBits(powerflag); + extract_value(thiscoupler->control_type, "ControlType", line, ""); + + if (thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated) + { + + thiscoupler->SpringKC *= 1000; + thiscoupler->FmaxC *= 1000; + thiscoupler->SpringKB *= 1000; + thiscoupler->FmaxB *= 1000; + } + else if (thiscoupler->CouplerType == TCouplerType::Bare) + { + + thiscoupler->SpringKC = 50.0 * emptyMass + Ftmax / 0.05; + thiscoupler->DmaxC = 0.05; + thiscoupler->FmaxC = 100.0 * emptyMass + 2 * Ftmax; + thiscoupler->SpringKB = 60.0 * emptyMass + Ftmax / 0.05; + thiscoupler->DmaxB = 0.05; + thiscoupler->FmaxB = 50.0 * emptyMass + 2.0 * Ftmax; + thiscoupler->beta = 0.3; + } + else if (thiscoupler->CouplerType == TCouplerType::Articulated) + { + /* + coupler->SpringKC = 60.0 * emptyMass + 1000; + coupler->DmaxC = 0.05; + coupler->FmaxC = 20000000.0 + 2.0 * Ftmax; + coupler->SpringKB = 70.0 * emptyMass + 1000; + coupler->DmaxB = 0.05; + coupler->FmaxB = 4000000.0 + 2.0 * Ftmax; + coupler->beta = 0.55; + */ + thiscoupler->SpringKC = 4500 * 1000; + thiscoupler->FmaxC = 850 * 1000; + thiscoupler->SpringKB = 9200 * 1000; + thiscoupler->FmaxB = 320 * 1000; + thiscoupler->beta = 0.55; + // the spring force is taken up to Dmax only, past it the vehicles collide (CollisionDetect()); so the joint + // carries the full FmaxC either way before it gives. with 0.05 m it carried 225 kN, short of what a loaded + // articulated wagon in a freight train takes, which then collided at every step (eu07/maszyna#553) + thiscoupler->DmaxC = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKC); + thiscoupler->DmaxB = std::max(0.05, thiscoupler->FmaxC / thiscoupler->SpringKB); + } + + // the buffers of a category of EN 15551 in place of the springs given + auto const categoryname{extract_value("BufferCategory", line)}; + auto const category{categoryname.empty() ? std::nullopt : collision::buffer_category_of(categoryname.front())}; + auto const buffered{thiscoupler->CouplerType != TCouplerType::NoCoupler && thiscoupler->CouplerType != TCouplerType::Bare && thiscoupler->CouplerType != TCouplerType::Articulated}; + if (category && buffered) + { + auto const linear{collision::buffer_curve(*category, 0.0)}; + thiscoupler->SpringKB = linear.stiffness; + thiscoupler->DmaxB = linear.travel; + } + thiscoupler->physics = coupler_physics_parameters(*thiscoupler, line); + if (category && buffered) + { + thiscoupler->physics.buffers = collision::buffer_curve(*category, thiscoupler->physics.buffers.progression); + } + thiscoupler->collision = collision_definition(line); + thiscoupler->collision.buffers = category; + + if (Index == 0) + { + // 0 indicates single entry for both couplers + Couplers[1] = Couplers[0]; + } + // each coupling as made is a little stronger than its rated force, a different one at each end + for (auto const end : VehicleEnds) + { + if (Index == 0 || end == (Index == 2 ? VehicleEnd::rear : VehicleEnd::front)) + { + scale_strength(Couplers[end].physics.link, coupler_physics::strength_scatter(Name, NumberOf(end))); + } + } +} + +void physics::Vehicle::LoadFIZ_TurboPos(std::string const &Input) +{ + + extract_value(TurboTest, "TurboPos", Input, ""); +} + +void physics::Vehicle::LoadFIZ_Cntrl(std::string const &line) +{ + + LoadFIZ_CntrlBrakes(line); + LoadFIZ_CntrlControllers(line); + LoadFIZ_CntrlStarts(line); +} + +// Cntrl.: the brake system, the handles, the brake delays and the local and manual brakes +void physics::Vehicle::LoadFIZ_CntrlBrakes(std::string const &line) +{ + { + using enum TBrakeSystem; + std::map> brakesystems{{"Pneumatic", Pneumatic}, {"ElectroPneumatic", ElectroPneumatic}}; + auto lookup = brakesystems.find(extract_value("BrakeSystem", line)); + brakes.config.kind = lookup != brakesystems.end() ? lookup->second : Individual; + } + if (brakes.config.kind != TBrakeSystem::Individual) + { + LoadFIZ_CntrlTrainBrake(line); + } // brakesystem != individual + + // localbrake + { + using enum TLocalBrake; + std::map> localbrakes{{"ManualBrake", ManualBrake}, {"PneumaticBrake", PneumaticBrake}, {"HydraulicBrake", HydraulicBrake}}; + auto lookup = localbrakes.find(extract_value("LocalBrake", line)); + brakes.config.localKind = lookup != localbrakes.end() ? lookup->second : NoBrake; + } + // mbrake + extract_value(brakes.config.hasHandBrake, "ManualBrake", line, ""); +} + +// Cntrl.: of a vehicle with a train brake, its positions, delays, modes, handles, load weighing and anti-slip brake +void physics::Vehicle::LoadFIZ_CntrlTrainBrake(std::string const &line) +{ + using enum TBrakeHandle; + + extract_value(brakes.config.handlePositions, "BCPN", line, ""); + for (int idx = 0; idx < 4; ++idx) + { + + extract_value(brakes.config.delays[idx], std::format("BDelay{}", idx + 1), line, ""); + } + // brakedelays, brakedelayflag + { + std::map> brakedelays{{"GPR", bdelay_G + bdelay_P + bdelay_R}, + {"PR", bdelay_P + bdelay_R}, + {"GP", bdelay_G + bdelay_P}, + {"R", bdelay_R}, + {"P", bdelay_P}, + {"G", bdelay_G}, + {"GPR+Mg", bdelay_G + bdelay_P + bdelay_R + bdelay_M}, + {"PR+Mg", bdelay_P + bdelay_R + bdelay_M}}; + std::map> brakedelayflags{{"R", bdelay_R}, {"P", bdelay_P}, {"G", bdelay_G}}; + std::string brakedelay; + extract_value(brakedelay, "BrakeDelays", line, ""); + auto lookup = brakedelays.find(brakedelay); + brakes.config.availableDelays = lookup != brakedelays.end() ? lookup->second : 0; + lookup = brakedelayflags.find(brakedelay); + brakes.delaySetting = lookup != brakedelayflags.end() ? lookup->second : 0; + } + // brakeopmode + { + std::map> brakeopmodes{{"PN", bom_PS + bom_PN}, {"PNEP", bom_PS + bom_PN + bom_EP}, {"PNEPMED", bom_PS + bom_PN + bom_EP + bom_MED}}; + auto lookup = brakeopmodes.find(extract_value("BrakeOpModes", line)); + brakes.config.availableOperatingModes = lookup != brakeopmodes.end() ? lookup->second : 0; + } + // brakehandle + { + std::map> brakehandles{ + {"FV4a", FV4a}, {"test", testH}, {"D2", D2}, {"MHZ_EN57", MHZ_EN57}, {"MHZ_K5P", MHZ_K5P}, + {"MHZ_K8P", MHZ_K8P}, {"MHZ_6P", MHZ_6P}, {"M394", M394}, {"Knorr", Knorr}, {"Westinghouse", West}, + {"FVel6", FVel6}, {"FVE408", FVE408}, {"St113", St113}}; + auto lookup = brakehandles.find(extract_value("BrakeHandle", line)); + brakes.config.driverValveType = lookup != brakehandles.end() ? lookup->second : NoHandle; + } + extract_value(brakes.config.driverValveSettings.automaticOverload, "HAO", line, ""); + extract_value(brakes.config.driverValveSettings.manualOverload, "HMO", line, ""); + extract_value(brakes.config.driverValveSettings.genericParameter1, "HGDP1", line, ""); + extract_value(brakes.config.driverValveSettings.genericParameter2, "HGDP2", line, ""); + extract_value(brakes.config.driverValveSettings.overloadMaxPressure, "OMP", line, ""); + extract_value(brakes.config.driverValveSettings.overloadPressureDecrease, "OPD", line, ""); + // brakelochandle + { + std::map> locbrakehandles{{"FD1", FD1}, {"Knorr", Knorr}, {"Westinghouse", West}}; + auto lookup = locbrakehandles.find(extract_value("LocBrakeHandle", line)); + brakes.config.independentValveType = lookup != locbrakehandles.end() ? lookup->second : NoHandle; + } + + // mbpm + if (true == extract_value(brakes.config.maxPressureMass, "MaxBPMass", line, "")) + { + // NOTE: only convert the value from tons to kilograms if the entry is present in the config file + brakes.config.maxPressureMass *= 1000.0; + } + + // asbtype + LoadFIZ_CntrlAntiSlipBrake(ToLower(extract_value("ASB", line))); +} + +// Cntrl.: the kind of the anti-slip brake, by hand or automatic only for a vehicle with a brake handle +void physics::Vehicle::LoadFIZ_CntrlAntiSlipBrake(std::string_view const asb) +{ + if (asb == "yes") + { + brakes.config.antiSlipType = 128; + } + else if (brakes.config.handlePositions > 0 && asb == "manual") + { + brakes.config.antiSlipType = 1; + } + else if (brakes.config.handlePositions > 0 && asb == "automatic") + { + brakes.config.antiSlipType = 2; + } +} + +// Cntrl.: the controllers, their delays, the cab and the switches of the driver's desk +void physics::Vehicle::LoadFIZ_CntrlControllers(std::string const &line) +{ + // maksymalna predkosc dostepna na tarczce predkosciomierza + extract_value(maxTachoSpeed, "MaxTachoSpeed", line, ""); + + // horns + { + using enum horn_supply; + std::map> const hornsupplies{{"Pneumatic", air}, {"Electric", electric}}; + auto lookup = hornsupplies.find(extract_value("HornType", line)); + hornSupply = lookup != hornsupplies.end() ? lookup->second : air; + lookup = hornsupplies.find(extract_value("Horn3Type", line)); + Horn3Supply = lookup != hornsupplies.end() ? lookup->second : hornSupply; + } + + // dynamicbrake + { + std::map> dynamicbrakes{{"Passive", dbrake_passive}, {"Switch", dbrake_switch}, {"Reversal", dbrake_reversal}, {"Automatic", dbrake_automatic}}; + auto lookup = dynamicbrakes.find(extract_value("DynamicBrake", line)); + brakes.electrodynamic.type = lookup != dynamicbrakes.end() ? lookup->second : dbrake_none; + extract_value(brakes.electrodynamic.ammeters, "DBAM", line, ""); + } + + // split ED/pneumatic brake control: when true the local brake operates only on the + // pneumatic locomotive cylinder while electrodynamic braking is commanded by a + // separate "dynamicbrakectrl" lever (or the negative range of jointctrl). + extract_value(brakes.electrodynamic.splitFromPneumatic, "SplitEDPneumaticBrake", line, ""); + // number of stepped positions for the dedicated ED brake controller (default 10) + brakes.electrodynamic.controllerPositions = 10; + extract_value(brakes.electrodynamic.controllerPositions, "DBPN", line, ""); + if (brakes.electrodynamic.controllerPositions < 1) + { + brakes.electrodynamic.controllerPositions = 10; + } + + extract_value(MainCtrlPosNo, "MCPN", line, ""); + extract_value(scndCtrlPosNo, "SCPN", line, ""); + extract_value(ScndInMain, "SCIM", line, ""); + extract_value(mainCtrlMaxDirChangePos, "DirChangeMaxPos", line, ""); + + if (auto const autorelay{ToLower(extract_value("AutoRelay", line))}; autorelay == "optional") + { + autoRelayType = 2; + } + else if (autorelay == "yes") + { + autoRelayType = 1; + } + else + { + autoRelayType = 0; + } + // a key of its own rather than a new AutoRelay value: an exe that doesn't know it reads the line as before, and the value + // stays Optional, which every check of the switch looks for + extract_value(fieldShuntSwitch, "FieldShuntSwitch", line, ""); + + extract_value(CoupledCtrl, "CoupledCtrl", line, ""); + extract_value(HasCamshaft, "Camshaft", line, ""); + extract_value(EIMCtrlType, "EIMCtrlType", line, ""); + EIMCtrlType = std::clamp(EIMCtrlType, 0, 3); + extract_value(brakes.config.independentTraxx, "LocalBrakeTraxx", line, ""); + extract_value(EIMCtrlAdditionalZeros, "EIMCtrlAddZeros", line, ""); + extract_value(eimCtrlEmergency, "EIMCtrlEmergency", line, ""); + // Elf (EIMCtrlType 2): an emergency brake position below the controller's position 0, which shifts the other positions up by one + extract_value(eimCtrlMainEmergency, "EIMCtrlMainEmergency", line, ""); + if (auto const elfpositions{4 + EIMCtrlEmergencyPositions()}; EIMCtrlEmergencyPositions() > 0 && MainCtrlPosNo < elfpositions) + { + // the old positions in the file: without the fix-up the controller would have no power position, and the + // reverser would stop working at neutral (DirChangeMaxPos read before, in the old positions) + mainCtrlMaxDirChangePos += EIMCtrlEmergencyPositions(); + ErrorLog(std::format("Bad fiz: EIMCtrlMainEmergency needs MCPN={} in {}, DirChangeMaxPos taken as {}", elfpositions, TypeName, mainCtrlMaxDirChangePos)); + MainCtrlPosNo = elfpositions; + } + + extract_value(ScndS, "ScndS", line, ""); // brak pozycji rownoleglej przy niskiej nastawie PSR + extract_value(ScndCtrlResistiveLock, "ScndCtrlResistiveLock", line, ""); // bocznikowanie tylko na pozycjach bezoporowych + + extract_value(initialCtrlDelay, "IniCDelay", line, ""); + extract_value(CtrlDelay, "SCDelay", line, ""); + CtrlDownDelay = CtrlDelay; // hunter-101012: jesli nie ma SCDDelay; + extract_value(CtrlDownDelay, "SCDDelay", line, ""); + + // hunter-111012: dla siodemek 303E + FastSerialCircuit = ToLower(extract_value("FSCircuit", line)) == "yes" ? 1 : 0; + extract_value(BackwardsBranchesAllowed, "BackwardsBranchesAllowed", line, ""); + + extract_value(AutomaticCabActivation, "AutomaticCabActivation", line, ""); + extract_value(InactiveCabFlag, "InactiveCabFlag", line, ""); + + extract_value(brakes.holding.deceleration, "SBD", line, ""); + extract_value(brakes.holding.releaseDelay, "SBDReleaseDelay", line, ""); // the holding brake waits for the power demand this long, s + extract_value(brakes.spring.releasesParking, "ReleaseParkingBySpringBrake", line, ""); + extract_value(brakes.spring.releasesParkingWithDoorOpen, "ReleaseParkingBySpringBrakeWhenDoorIsOpen", line, ""); + extract_value(brakes.spring.cutsOffDrive, "SpringBrakeCutsOffDrive", line, ""); + extract_value(brakes.spring.driveEmergencySpeed, "SpringBrakeDriveEmergencyVel", line, ""); + + extract_value(HideDirStatusWhenMoving, "HideDirStatusWhenMoving", line, ""); + extract_value(HideDirStatusSpeed, "HideDirStatusSpeed", line, ""); + extract_value(isDoubleClickForMeasureNeeded, "DCMB", line, ""); + extract_value(DistanceCounterDoublePressPeriod, "DCDPP", line, ""); + + extract_value(lowVoltage.config.batteryButtonImpulse, "IBTB", line, ""); + extract_value(lowVoltage.config.batteryButtonHeld, "SBBBH", line, ""); + extract_value(lowVoltage.config.batteryButtonHoldTime, "BBHT", line, ""); +} + +// Cntrl.: how the devices start (MainStart, BatteryStart, ...) and their relays +void physics::Vehicle::LoadFIZ_CntrlStarts(std::string const &line) +{ + using enum start_t; + std::map> starts{{"Disabled", disabled}, {"Manual", manual}, {"Automatic", automatic}, {"Mixed", manualwithautofallback}, + {"Battery", battery}, {"Converter", converter}, {"Direction", direction}}; + + // main circuit + extract_value(lineBreaker.config.initTime, "MainInitTime", line, ""); + { + auto lookup = starts.find(extract_value("MainStart", line)); + lineBreaker.config.start = lookup != starts.end() ? lookup->second : manual; + } + extract_value(lineBreaker.config.pantographsRequireIt, "PantRequiresMain", line, ""); + // the brake pipe pressure of an emergency brake application, which opens the line breaker under power + extract_value(lineBreaker.config.emergencyOffPressure, "EmergencyBrakeMainOff", line, ""); + lineBreaker.config.emergencyOffPressure = std::max(0.0, lineBreaker.config.emergencyOffPressure); + // battery + { + auto lookup = starts.find(extract_value("BatteryStart", line)); + lowVoltage.config.batteryStart = lookup != starts.end() ? lookup->second : manual; + } + // converter + { + auto lookup = starts.find(extract_value("ConverterStart", line)); + this->converter.config.start = lookup != starts.end() ? lookup->second : manual; + } + extract_value(this->converter.config.startDelay, "ConverterStartDelay", line, ""); + extract_value(this->converter.config.overloadRelayOffWithLineBreaker, "ConverterOverloadWhenMainIsOff", line, trainType == train_type::emu ? "yes" : "no"); + // compressor + { + auto lookup = starts.find(extract_value("CompressorStart", line)); + air.compressor.config.start = lookup != starts.end() ? lookup->second : manual; + } + // pantograph compressor + { + auto lookup = starts.find(extract_value("PantCompressorStart", line)); + pantographAir.config.compressorStart = lookup != starts.end() ? lookup->second : manual; + } + // pantograph compressor valve + pantographAir.config.autoValve = trainType == train_type::emu; // legacy code behaviour, automatic valve was initially installed in all EMUs + extract_value(pantographAir.config.autoValve, "PantAutoValve", line, ""); + // pantographs valve + { + auto lookup = starts.find(extract_value("PantEPValveStart", line)); + pantographAir.valve.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy code behaviour, there was no pantographs valve + extract_value(pantographAir.valve.spring, "PantEPValveSpring", line, ""); + } + // pantograph valve configuration + { + auto lookup = starts.find(extract_value("PantValveStart", line)); + auto valvestarttype = lookup != starts.end() ? lookup->second : manual; + auto valvespring{true}; + extract_value(valvespring, "PantValveSpring", line, ""); + auto valvesolenoid{true}; + extract_value(valvesolenoid, "PantValveSolenoid", line, ""); + for (auto &pantograph : pantographs) + { + pantograph.valve.spring = valvespring; + pantograph.valve.solenoid = valvesolenoid; + pantograph.valve.start_type = valvestarttype; + } + } + // fuel pump + { + auto lookup = starts.find(extract_value("FuelStart", line)); + FuelPump.start_type = lookup != starts.end() ? lookup->second : manual; + } + // oil pump + { + auto lookup = starts.find(extract_value("OilStart", line)); + OilPump.start_type = lookup != starts.end() ? lookup->second : manual; + } + // genset of a dual-mode vehicle: Manual (the default) needs GensetSwitch, Automatic runs whenever the selector is on it + { + auto lookup = starts.find(extract_value("GensetStart", line)); + Genset.start_type = lookup != starts.end() ? lookup->second : manual; + } + // water pump + { + auto lookup = starts.find(extract_value("WaterStart", line)); + WaterPump.start_type = lookup != starts.end() ? lookup->second : manual; + } + // traction motor fans + { + auto lookup = starts.find(extract_value("MotorBlowersStart", line)); + MotorBlowers[VehicleEnd::rear].start_type = lookup != starts.end() ? lookup->second : manual; + MotorBlowers[VehicleEnd::front].start_type = MotorBlowers[VehicleEnd::rear].start_type; + } + // what else the line contactors need to close + { + std::map> const interlocks{{"Converter", line_contactors_interlock::converter}, + {"MotorBlowers", line_contactors_interlock::motor_blowers}}; + auto lookup = interlocks.find(extract_value("LineContactorsInterlock", line)); + lineContactors.config.interlock = lookup != interlocks.end() ? lookup->second : line_contactors_interlock::none; + } + extract_value(LouvresOpenPressure, "LouvresOpenPressure", line, ""); + // compartment lights + { + auto lookup = starts.find(extract_value("CompartmentLightsStart", line)); + CompartmentLights.start_type = lookup != starts.end() ? lookup->second : automatic; // legacy behaviour + } + // ground relay + { + auto lookup = starts.find(extract_value("GroundRelayStart", line)); + auto const defaultstart{trainType == train_type::emu ? automatic : manual}; + protection.config.groundStart = lookup != starts.end() ? lookup->second : defaultstart; + } + // converter overload relay + { + auto lookup = starts.find(extract_value("ConverterOverloadRelayStart", line)); + // the relay of a multiple unit activates when the converter is switched off + auto const defaultstart{trainType == train_type::emu ? converter : manual}; + this->converter.config.overloadRelayStart = lookup != starts.end() ? lookup->second : defaultstart; + } +} + +void physics::Vehicle::LoadFIZ_Blending(std::string const &line) +{ + + extract_value(brakes.blending.maxSpeed, "MED_Vmax", line, std::to_string(vmax)); + extract_value(brakes.blending.minSpeed, "MED_Vmin", line, "0"); + extract_value(brakes.blending.referenceSpeed, "MED_Vref", line, std::to_string(vmax)); + extract_value(brakes.blending.maxDeceleration, "MED_amax", line, "9.81"); + extract_value(brakes.blending.epCorrection, "MED_EPVC", line, ""); + extract_value(brakes.blending.loadCorrection, "MED_Ncor", line, ""); + extract_value(brakes.blending.minEdDemand, "MED_MinBrakeReqED", line, ""); + extract_value(brakes.blending.edForceFactor, "MED_FrEDFactor", line, ""); + extract_value(brakes.blending.edFirstDelay, "MED_FirstDelayED", line, ""); + extract_value(brakes.blending.edNextDelay, "MED_ScndDelayED", line, ""); +} + +void physics::Vehicle::LoadFIZ_DCEMUED(std::string const &line) +{ + + extract_value(brakes.emuDynamic.checkedCoupler, "CouplerCheck", line, "0"); + extract_value(brakes.emuDynamic.epMaxSpeed, "EP_max_Vel", line, "0"); + extract_value(brakes.emuDynamic.epMinCurrent, "EP_min_Im", line, "0"); + extract_value(brakes.emuDynamic.epDelay, "EP_delay", line, "0"); +} + +void physics::Vehicle::LoadFIZ_SpringBrake(std::string const &line) +{ + + double vol{1.0}; + extract_value(vol, "Volume", line, "1"); + if (!brakes.spring.cylinder) + brakes.spring.cylinder = std::make_shared(); + brakes.spring.cylinder->CreateCap(vol); + extract_value(brakes.spring.maxForce, "MBF", line, ""); + extract_value(brakes.spring.maxSetPressure, "MaxSP", line, ""); + extract_value(brakes.spring.resetPressure, "ResetP", line, ""); + extract_value(brakes.spring.minForcePressure, "MinFP", line, ""); + extract_value(brakes.spring.pressureOff, "PressOff", line, ""); + extract_value(brakes.spring.pressureOn, "PressOn", line, ""); + extract_value(brakes.spring.valveOffArea, "ValveOnArea", line, ""); + extract_value(brakes.spring.valveOnArea, "ValveOffArea", line, ""); + extract_value(brakes.spring.valvePneumaticArea, "ValvePNBArea", line, ""); + brakes.spring.pneumaticConnection = brakes.spring.valvePneumaticArea > 0; + extract_value(brakes.spring.controlCouplings, "MTC", line, ""); + brakes.spring.shutOff = false; + brakes.spring.activate = false; + brakes.spring.isReady = true; +} + +void physics::Vehicle::LoadFIZ_Light(std::string const &line) +{ + + LightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Light", line)); + LoadFIZ_PowerParamsDecode(LightPowerSource, "L", line); + + AlterLightPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterLight", line)); + LoadFIZ_PowerParamsDecode(AlterLightPowerSource, "AlterL", line); + + extract_value(NominalVoltage, "Volt", line, ""); + auto batteryvoltage{lowVoltage.BatteryVoltage()}; + extract_value(batteryvoltage, "LMaxVoltage", line, ""); + lowVoltage.SetBattery(batteryvoltage); +} + +void physics::Vehicle::LoadFIZ_Clima(std::string const &line) +{ + + HeatingPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("Heating", line)); + LoadFIZ_PowerParamsDecode(HeatingPowerSource, "H", line); + AlterHeatPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("AlterHeating", line)); + LoadFIZ_PowerParamsDecode(AlterHeatPowerSource, "AlterH", line); +} + +void physics::Vehicle::LoadFIZ_Power(std::string const &Line) +{ + + EnginePowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("EnginePower", Line)); + LoadFIZ_PowerParamsDecode(EnginePowerSource, "", Line); + /* + if( ( EnginePowerSource.SourceType == TPowerSource::Generator ) + && ( EnginePowerSource.GeneratorEngine == TEngineType::WheelsDriven ) ) { + // perpetuum mobile? + ConversionError = 666; + } + */ + if (Power == 0.0) + { + // jeśli nie ma mocy, np. rozrządcze EZT + EnginePowerSource.SourceType = TPowerSource::NotDefined; + } + else + { + LoadFIZ_Genset(Line); + } + + SystemPowerSource.SourceType = LoadFIZ_SourceDecode(extract_value("SystemPower", Line)); + LoadFIZ_PowerParamsDecode(SystemPowerSource, "", Line); +} + +// the genset of a dual-mode vehicle (eu07/maszyna#536), on the Power: line; all optional, no genset without GensetPower +void physics::Vehicle::LoadFIZ_Genset(std::string const &Line) +{ + extract_value(Genset.power, "GensetPower", Line, ""); + if (false == Genset.fitted()) + { + return; + } + extract_value(Genset.voltage_nominal, "GensetVoltage", Line, ""); + if (Genset.voltage_nominal <= 0.0) + { + Genset.voltage_nominal = EnginePowerSource.MaxVoltage > 0.0 ? 0.65 * EnginePowerSource.MaxVoltage : 3000.0; + } + extract_value(Genset.revolutions_idle, "GensetIdleRPM", Line, "600"); + extract_value(Genset.revolutions_max, "GensetMaxRPM", Line, "1800"); + Genset.revolutions_max = std::max(Genset.revolutions_max, 1.0) / 60.0; + Genset.revolutions_idle = std::clamp(Genset.revolutions_idle / 60.0, 1.0 / 60.0, Genset.revolutions_max); + extract_value(Genset.start_time, "GensetStartTime", Line, "8"); + extract_value(Genset.spinup_time, "GensetSpinUpTime", Line, "3"); + extract_value(Genset.traction_share, "GensetPmaxRatio", Line, "1"); + Genset.start_time = std::max(Genset.start_time, 0.0); + Genset.spinup_time = std::max(Genset.spinup_time, 0.01); + Genset.traction_share = std::clamp(Genset.traction_share, 0.0, 1.0); +} + +void physics::Vehicle::LoadFIZ_SpeedControl(std::string const &Line) +{ + // speed control + extract_value(speedCtrl, "SpeedCtrl", Line, ""); + if (!speedCtrl && EngineType == TEngineType::ElectricInductionMotor && scndCtrlPosNo > 0) // backward compatibility + speedCtrl = true; + extract_value(SpeedCtrlDelay, "SpeedCtrlDelay", Line, ""); + speedCtrlTypeTime = extract_value("SpeedCtrlType", Line) == "Time" ? true : false; + extract_value(SpeedCtrlAutoTurnOffFlag, "SpeedCtrlATOF", Line, ""); + + auto speedpresets = Split(extract_value("SpeedButtons", Line), '|'); + int speed_no = 0; + for (auto const &speed : speedpresets) + { + SpeedCtrlButtons[speed_no++] = std::stod(speed); + if (speed_no > 9) + break; + } + extract_value(SpeedCtrlUnit.ManualStateOverride, "OverrideManual", Line, ""); + extract_value(SpeedCtrlUnit.BrakeIntervention, "BrakeIntervention", Line, ""); + extract_value(SpeedCtrlUnit.InitialPower, "InitPwr", Line, ""); + extract_value(SpeedCtrlUnit.FullPowerVelocity, "MaxPwrVel", Line, ""); + extract_value(SpeedCtrlUnit.StartVelocity, "StartVel", Line, ""); + extract_value(SpeedCtrlUnit.VelocityStep, "VelStep", Line, ""); + extract_value(SpeedCtrlUnit.PowerStep, "PwrStep", Line, ""); + extract_value(SpeedCtrlUnit.MinPower, "MinPwr", Line, ""); + extract_value(SpeedCtrlUnit.MaxPower, "MaxPwr", Line, ""); + extract_value(SpeedCtrlUnit.MinVelocity, "MinVel", Line, ""); + extract_value(SpeedCtrlUnit.MaxVelocity, "MaxVel", Line, ""); + extract_value(SpeedCtrlUnit.Offset, "Offset", Line, ""); + extract_value(SpeedCtrlUnit.FactorPpos, "kPpos", Line, ""); + extract_value(SpeedCtrlUnit.FactorPneg, "kPneg", Line, ""); + extract_value(SpeedCtrlUnit.FactorIpos, "kIpos", Line, ""); + extract_value(SpeedCtrlUnit.FactorIneg, "kIneg", Line, ""); + extract_value(SpeedCtrlUnit.BrakeInterventionVel, "BrakeIntMaxVel", Line, ""); + extract_value(SpeedCtrlUnit.PowerUpSpeed, "PowerUpSpeed", Line, ""); + extract_value(SpeedCtrlUnit.PowerDownSpeed, "PowerDownSpeed", Line, ""); +} + +void physics::Vehicle::LoadFIZ_Engine(std::string const &Input) +{ + + EngineType = LoadFIZ_EngineDecode(extract_value("EngineType", Input)); + extract_value(lineBreaker.config.jointStart, "JointEngineStart", Input, ""); + + if (std::string transmission = extract_value("Trans", Input); false == transmission.empty()) + { + // transmission type. moved here because more than one engine type has this entry + auto ratios = Split(transmission, ':'); // e.g. 18:79 + + if (ratios.size() != 2) + { + ErrorLog("Wrong transmition definition: " + transmission); + } + + Transmision.NToothM = std::atoi(ratios[0].c_str()); // ToothM to pierwszy czyli 18 + Transmision.NToothW = std::atoi(ratios[1].c_str()); // ToothW to drugi parametr czyli 79 + + if (Transmision.NToothM > 0) + Transmision.Ratio = static_cast(Transmision.NToothW) / Transmision.NToothM; + else + Transmision.Ratio = 1.0; + extract_value(Transmision.Efficiency, "TransEff", Input, ""); + } + + switch (EngineType) + { + + case TEngineType::ElectricSeriesMotor: + { + + extract_value(NominalVoltage, "Volt", Input, ""); + extract_value(windingRes, "WindingRes", Input, ""); + if (windingRes == 0.0) + { + + windingRes = 0.01; + } + extract_value(nmax, "nmax", Input, ""); + nmax /= 60.0; + break; + } + case TEngineType::WheelsDriven: + case TEngineType::Dumb: + { + + extract_value(Ftmax, "Ftmax", Input, ""); + break; + } + case TEngineType::DieselEngine: + { + LoadFIZ_EngineDiesel(Input); + break; + } + case TEngineType::DieselElectric: + { // youBy + LoadFIZ_EngineDieselElectric(Input); + break; + } + case TEngineType::ElectricInductionMotor: + { + LoadFIZ_EngineInductionMotor(Input); + break; + } + default: + { + // nothing here + } + } // engine type + + // NOTE: elements shared by both diesel engine variants; crude but, eh + if (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) + { + LoadFIZ_EngineDieselShared(Input); + } + + // traction motors + extract_value(MotorBlowers[VehicleEnd::front].speed, "MotorBlowersSpeed", Input, ""); + extract_value(MotorBlowers[VehicleEnd::front].sustain_time, "MotorBlowersSustainTime", Input, ""); + extract_value(MotorBlowers[VehicleEnd::front].min_start_velocity, "MotorBlowersStartVelocity", Input, ""); + MotorBlowers[VehicleEnd::rear] = MotorBlowers[VehicleEnd::front]; + // pressure switch + extract_value(protection.config.hasPressureSwitch, "PressureSwitch", Input, trainType != train_type::emu ? "yes" : "no"); + // its brake cylinder half; the brake pipe one stays + extract_value(protection.config.pressureSwitchWatchesCylinders, "PressureSwitchBrakeCylinder", Input, ""); +} + +// Engine: of a diesel engine, its revolutions, gears, hydraulic transmission and retarder +void physics::Vehicle::LoadFIZ_EngineDiesel(std::string const &Input) +{ + + extract_value(diesel.minRevolutions, "nmin", Input, ""); + diesel.minRevolutions /= 60.0; + diesel.governorMinRevolutions = diesel.minRevolutions * 0.98; + extract_value(diesel.hydraulicMinRevolutions, "nmin_hdrive", Input, ""); + diesel.hydraulicMinRevolutions /= 60.0; + if (diesel.hydraulicMinRevolutions == 0.0) + { + diesel.hydraulicMinRevolutions = diesel.minRevolutions; + } + extract_value(diesel.hydraulicMinRevolutionsFactor, "nmin_hdrive_factor", Input, ""); + diesel.hydraulicMinRevolutionsFactor /= 60.0; + extract_value(diesel.retarderRevolutions, "nmin_retarder", Input, ""); + diesel.retarderRevolutions /= 60.0; + if (diesel.retarderRevolutions == 0.0) + { + diesel.retarderRevolutions = diesel.minRevolutions; + } + // TODO: unify naming scheme and sort out which diesel engine params are used where and how + extract_value(nmax, "nmax", Input, ""); + nmax /= 60.0; + extract_value(diesel.cutoffRevolutions, "nmax_cutoff", Input, "0.0"); + diesel.cutoffRevolutions /= 60.0; + extract_value(diesel.governorAcceleration, "nreg_acc", Input, ""); + diesel.governorAcceleration /= 60.0; + extract_value(diesel.shaftInertia, "AIM", Input, "1.0"); + extract_value(diesel.revolutionsDecreaseRate, "RPMDecRate", Input, ""); + + extract_value(engageupspeed, "EUS", Input, "0.5"); + extract_value(engagedownspeed, "EDS", Input, "0.9"); + + if (true == extract_value(anPos, "ShuntMode", Input, "")) + { + // dodatkowa przekładnia dla SM03 (2Ls150) + ShuntModeAllow = true; + ShuntMode = false; + if (anPos < 1.0) + { + //"rozruch wysoki" ma dawać większą siłę + anPos = 1.0 / anPos; // im większa liczba, tym wolniej jedzie + } + } + extract_value(torqueConverter.present, "IsTC", Input, ""); + if (true == torqueConverter.present) + { + extract_value(torqueConverter.maxTorqueRatio, "TC_TMMax", Input, ""); + extract_value(torqueConverter.couplingPoint, "TC_CP", Input, ""); + extract_value(torqueConverter.lockupTorque, "TC_LT", Input, ""); + extract_value(torqueConverter.lockupRate, "TC_LR", Input, ""); + extract_value(torqueConverter.unlockRate, "TC_ULR", Input, ""); + extract_value(torqueConverter.fillRateIncrease, "TC_FRI", Input, ""); + extract_value(torqueConverter.fillRateDecrease, "TC_FRD", Input, ""); + extract_value(torqueConverter.torqueInIn, "TC_TII", Input, ""); + extract_value(torqueConverter.torqueInOut, "TC_TIO", Input, ""); + extract_value(torqueConverter.torqueOutOut, "TC_TOO", Input, ""); + extract_value(torqueConverter.lockupSpeed, "TC_LS", Input, ""); + extract_value(torqueConverter.unlockSpeed, "TC_ULS", Input, ""); + extract_value(diesel.converterReleaseVelocity, "MaxVelANS", Input, ""); + + extract_value(retarder.present, "IsRetarder", Input, ""); + if (true == retarder.present) + { + extract_value(retarder.placement, "R_Place", Input, ""); + extract_value(retarder.torqueInIn, "R_TII", Input, ""); + extract_value(retarder.maxTorque, "R_MT", Input, ""); + extract_value(retarder.maxPower, "R_MP", Input, ""); + extract_value(retarder.fillRateIncrease, "R_FRI", Input, ""); + extract_value(retarder.fillRateDecrease, "R_FRD", Input, ""); + extract_value(retarder.minVelocity, "R_MinVel", Input, ""); + extract_value(retarder.engageVelocity, "R_EngageVel", Input, ""); + extract_value(retarder.hasClutch, "R_IsClutch", Input, ""); + extract_value(retarder.clutchSpeed, "R_ClutchSpeed", Input, ""); + extract_value(retarder.withIndividual, "R_WithIndividual", Input, ""); + } + } +} + +// Engine: of a diesel-electric +void physics::Vehicle::LoadFIZ_EngineDieselElectric(std::string const &Input) +{ + + extract_value(Ftmax, "Ftmax", Input, ""); + Flat = extract_value("Flat", Input) == "1"; + extract_value(Vhyp, "Vhyp", Input, ""); + Vhyp /= 3.6; + extract_value(Vadd, "Vadd", Input, ""); + Vadd /= 3.6; + extract_value(PowerCorRatio, "Cr", Input, ""); + extract_value(RelayType, "RelayType", Input, ""); + if (extract_value("ShuntMode", Input) == "1") + { + + ShuntModeAllow = true; + ShuntMode = false; + anPos = 0.0; + imaxHi = 2; + imaxLo = 1; + } + extract_value(trainHeating.config.engineRpm, "HeatingRPM", Input, ""); + extract_value(diesel.shaftInertia, "AIM", Input, "1.25"); + extract_value(diesel.revolutionsDecreaseRate, "RPMDecRate", Input, ""); + LoadFIZ_DieselElectricDynamicBrake(Input); +} + +// Engine: of an induction motor drive +void physics::Vehicle::LoadFIZ_EngineInductionMotor(std::string const &Input) +{ + + RVentnmax = 1.0; + extract_value(NominalVoltage, "Volt", Input, ""); + + extract_value(inductionMotor.motor.currentPerSlip, "dfic", Input, ""); + extract_value(inductionMotor.motor.maxSlipFrequency, "dfmax", Input, ""); + extract_value(inductionMotor.motor.polePairs, "p", Input, ""); + extract_value(inductionMotor.motor.voltsPerHertz, "cfu", Input, ""); + extract_value(inductionMotor.motor.torquePerCurrent, "cim", Input, ""); + extract_value(inductionMotor.motor.fieldCurrentRatio, "icif", Input, ""); + extract_value(inductionMotor.converter.maxLinkVoltage, "Uzmax", Input, ""); + extract_value(inductionMotor.converter.brakingLinkVoltage, "Uzh", Input, ""); + extract_value(inductionMotor.converter.voltageDrop, "DU", Input, ""); + extract_value(inductionMotor.converter.noLoadCurrent, "I0", Input, ""); + extract_value(inductionMotor.converter.voltsPerHertz, "fcfu", Input, ""); + if (false == extract_value(inductionMotor.converter.brakingVoltsPerHertz, "fcfuH", Input, "")) + { + // without its own figure the dynamic brake takes the one of the traction + inductionMotor.converter.brakingVoltsPerHertz = inductionMotor.converter.voltsPerHertz; + } + extract_value(inductionMotor.traction.startingForce, "F0", Input, ""); + extract_value(inductionMotor.traction.forceDropPerSpeed, "a1", Input, ""); + extract_value(inductionMotor.traction.maxPower, "Pmax", Input, ""); + extract_value(inductionMotor.braking.maxForce, "Fh", Input, ""); + extract_value(inductionMotor.braking.maxPower, "Ph", Input, ""); + extract_value(inductionMotor.braking.offSpeed, "Vh0", Input, ""); + extract_value(inductionMotor.braking.fullSpeed, "Vh1", Input, ""); + extract_value(inductionMotor.traction.maxCurrent, "Imax", Input, ""); + extract_value(inductionMotor.braking.cylinderPressureGain, "abed", Input, ""); + extract_value(inductionMotor.braking.maxEpDeceleration, "edep", Input, ""); + extract_value(inductionMotor.logForce, "eimclf", Input, ""); + extract_value(inductionMotor.inverterCount, "InvNo", Input, ""); + extract_value(inductionMotor.inverterControlCouplings, "InvCtrCplFlag", Input, ""); + extract_value(brakes.electrodynamic.resistorPassiveMaxCurrent, "Imaxrpc", Input, ""); + extract_value(brakes.electrodynamic.resistorFansSustain, "BRVto", Input, ""); + extract_value(Flat, "Flat", Input, ""); + + if (inductionMotor.traction.maxPower > 0 && Power > 0 && inductionMotor.inverterCount == 0) + { + inductionMotor.inverterCount = 1; + } + inductionMotor.inverters.resize(inductionMotor.inverterCount); + /*for (int i = 0; i > inductionMotor.inverterCount; i++) + { + Inverter x; + inductionMotor.inverters.emplace_back(x); + }*/ +} + +// Engine: what both kinds of diesels have, their heat among it +void physics::Vehicle::LoadFIZ_EngineDieselShared(std::string const &Input) +{ + // oil pump + extract_value(OilPump.pressure_minimum, "OilMinPressure", Input, ""); + extract_value(OilPump.pressure_maximum, "OilMaxPressure", Input, ""); + // the time the starter turns the engine before it fires and smokes (eu07/maszyna#523) + extract_value(diesel.smokeDelay, "SmokeDelay", Input, "0"); + diesel.smokeDelay = std::max(0.0, diesel.smokeDelay); + // engine cooling factore + extract_value(diesel.heat.kw, "HeatKW", Input, ""); + extract_value(diesel.heat.kv, "HeatKV", Input, ""); + extract_value(diesel.heat.kfe, "HeatKFE", Input, ""); + extract_value(diesel.heat.kfs, "HeatKFS", Input, ""); + extract_value(diesel.heat.kfo, "HeatKFO", Input, ""); + extract_value(diesel.heat.kfo2, "HeatKFO2", Input, ""); + // engine cooling systems + extract_value(diesel.heat.water.config.temp_min, "WaterMinTemperature", Input, ""); + extract_value(diesel.heat.water.config.temp_max, "WaterMaxTemperature", Input, ""); + extract_value(diesel.heat.water.config.temp_flow, "WaterFlowTemperature", Input, ""); + extract_value(diesel.heat.water.config.temp_cooling, "WaterCoolingTemperature", Input, ""); + extract_value(diesel.heat.water.config.shutters, "WaterShutters", Input, ""); + extract_value(diesel.heat.auxiliary_water_circuit, "WaterAuxCircuit", Input, ""); + extract_value(diesel.heat.water_aux.config.temp_min, "WaterAuxMinTemperature", Input, ""); + extract_value(diesel.heat.water_aux.config.temp_max, "WaterAuxMaxTemperature", Input, ""); + extract_value(diesel.heat.water_aux.config.temp_cooling, "WaterAuxCoolingTemperature", Input, ""); + extract_value(diesel.heat.water_aux.config.shutters, "WaterAuxShutters", Input, ""); + extract_value(diesel.heat.oil.config.temp_min, "OilMinTemperature", Input, ""); + extract_value(diesel.heat.oil.config.temp_max, "OilMaxTemperature", Input, ""); + extract_value(diesel.heat.engine_max_temp, "EngineMaxTemperature", Input, ""); + extract_value(diesel.heat.fan_speed, "WaterCoolingFanSpeed", Input, ""); + // water heater + extract_value(WaterHeater.config.temp_min, "HeaterMinTemperature", Input, ""); + extract_value(WaterHeater.config.temp_max, "HeaterMaxTemperature", Input, ""); + float pf{1235.f}; + extract_value(pf, "NominalCoolingPower", Input, "1235"); + diesel.heat.powerfactor = 1235 / pf; +} + +void physics::Vehicle::LoadFIZ_Switches(std::string const &Input) +{ + + extract_value(pantographCircuit.config.switchType, "Pantograph", Input, ""); + extract_value(converter.config.switchType, "Converter", Input, ""); + extract_value(lineContactors.config.switchType, "MotorConnectors", Input, ""); + trainHeating.config.switchImpulse = ToLower(extract_value("TrainHeating", Input)) == "impulse"; + // because people can't make up their minds whether it's "impulse" or "Impulse"... + pantographCircuit.config.switchType = ToLower(pantographCircuit.config.switchType); + converter.config.switchType = ToLower(converter.config.switchType); + lineContactors.config.switchType = ToLower(lineContactors.config.switchType); + // universal reset buttons assignments + extract_value(UniversalResetButtonFlag[0], "RelayResetButton1", Input, ""); + extract_value(UniversalResetButtonFlag[1], "RelayResetButton2", Input, ""); + extract_value(UniversalResetButtonFlag[2], "RelayResetButton3", Input, ""); + extract_value(enableModernDimmerValue, "ModernDimmer", Input, ""); + // pantograph presets + { + auto &presets{pantographCircuit.presets.first}; + extract_value(presets, "PantographPresets", Input, "0|1|3|2"); + std::erase(presets, '|'); + } +} + +void physics::Vehicle::LoadFIZ_MotorParamTable(std::string const &Input) +{ + + switch (EngineType) + { + + case TEngineType::DieselEngine: + { + + extract_value(diesel.fullEngageMinVelocity, "minVelfullengage", Input, ""); + extract_value(diesel.clutchDiameter, "engageDia", Input, ""); + extract_value(diesel.clutchMaxForce, "engageMaxForce", Input, ""); + extract_value(diesel.clutchFriction, "engagefriction", Input, ""); + break; + } + default: + { + // nothing here + } + } +} + +void physics::Vehicle::LoadFIZ_Circuit(std::string const &Input) +{ + + extract_value(CircuitRes, "CircuitRes", Input, ""); + extract_value(IminLo, "IminLo", Input, ""); + extract_value(IminHi, "IminHi", Input, ""); + extract_value(imaxLo, "ImaxLo", Input, ""); + extract_value(imaxHi, "ImaxHi", Input, ""); + imin = IminLo; + Imax = imaxLo; + extract_value(TUHEX_Sum, "TUHEX_Sum", Input, ""); + extract_value(TUHEX_Diff, "TUHEX_Diff", Input, ""); + extract_value(TUHEX_MaxIw, "TUHEX_MaxIw", Input, ""); + extract_value(TUHEX_MinIw, "TUHEX_MinIw", Input, ""); + extract_value(TUHEX_Sum1, "TUHEX_Sum1", Input, ""); + extract_value(TUHEX_Sum2, "TUHEX_Sum2", Input, ""); + extract_value(TUHEX_Sum3, "TUHEX_Sum3", Input, ""); + extract_value(TUHEX_Stages, "TUHEX_Stages", Input, "0"); +} + +void physics::Vehicle::LoadFIZ_AI(std::string const &Input) +{ + + extract_value(aiHintPantstate, "Pantstate", Input, ""); + extract_value(aiHintShuntPantstate, "ShuntPantstate", Input, ""); + extract_value(AIHintPantUpIfIdle, "IdlePantUp", Input, ""); + extract_value(aiHintLocalBrakeAccFactor, "LocalBrakeAccFactor", Input, ""); +} + +void physics::Vehicle::LoadFIZ_RList(std::string const &Input) +{ + + extract_value(RlistSize, "Size", Input, ""); + + if (auto const venttype{ToLower(extract_value("RVent", Input))}; venttype == "automatic") + { + + RVentType = 2; + } + else + { + + RVentType = venttype == "yes" ? 1 : 0; + } + + if (RVentType > 0) + { + + extract_value(RVentnmax, "RVentnmax", Input, ""); + RVentnmax /= 60.0; + extract_value(RVentCutOff, "RVentCutOff", Input, ""); + } + extract_value(RVentMinI, "RVentMinI", Input, ""); + extract_value(RVentSpeed, "RVentSpeed", Input, ""); + extract_value(brakes.electrodynamic.resistance, "DynBrakeRes", Input, ""); + extract_value(brakes.electrodynamic.resistance1, "DynBrakeRes1", Input, ""); + extract_value(brakes.electrodynamic.resistance2, "DynBrakeRes2", Input, ""); +} + +// the dynamic brake of a diesel-electric vehicle, from its Engine section: none without EDBrake +void physics::Vehicle::LoadFIZ_DieselElectricDynamicBrake(std::string const &Input) +{ + using enum diesel_electric_dynamic_brake::control; + std::map> const sources{{"Controller", controller}, {"Lever", lever}}; + auto const lookup{sources.find(extract_value("EDBrake", Input))}; + if (lookup == sources.end()) + { + return; + } + auto &brake{DEDynamicBrake}; + brake.source = lookup->second; + auto force{0.0}; // [kN] + auto power{0.0}; // [kW] + extract_value(force, "EDBrakeFmax", Input, ""); + extract_value(power, "EDBrakePmax", Input, ""); + brake.max_force = force * 1000.0; + brake.max_power = power * 1000.0; + extract_value(brake.fade_low, "EDBrakeV0", Input, ""); + extract_value(brake.fade_high, "EDBrakeV1", Input, ""); + extract_value(brake.rate, "EDBrakeRate", Input, ""); + extract_value(brake.blending, "EDBrakeBlending", Input, ""); + if (brake.source == lever) + { + // the lever of its own, which the commands of the dynamic brake controller move + brakes.electrodynamic.splitFromPneumatic = true; + } +} + +void physics::Vehicle::LoadFIZ_UCList(std::string const &Input) +{ + + extract_value(UniCtrlListSize, "Size", Input, ""); + extract_value(UniCtrlIntegratedBrakeCtrl, "IntegratedBrake", Input, ""); + extract_value(uniCtrlIntegratedLocalBrakeCtrl, "IntegratedLocBrake", Input, ""); + extract_value(UniCtrlIntegratedBrakePNCtrl, "IntegratedBrakePN", Input, ""); + extract_value(uniCtrlValStep, "CtrlValStep", Input, ""); + uniCtrlValStep = std::max(uniCtrlValStep, 0.0); +} + +void physics::Vehicle::LoadFIZ_DList(std::string const &Input) +{ + + extract_value(diesel.maxMoment, "Mmax", Input, ""); + extract_value(diesel.maxMomentRevolutions, "nMmax", Input, ""); + extract_value(diesel.maxRevolutionsMoment, "Mnmax", Input, ""); + extract_value(diesel.maxRevolutions, "nmax", Input, ""); + extract_value(diesel.nominalFill, "nominalfill", Input, ""); + extract_value(diesel.standingMoment, "Mstand", Input, ""); + extract_value(diesel.nominalFuelConsumptionRate, "NomFuelConsRate", Input, ""); + + if (diesel.maxMomentRevolutions == diesel.maxRevolutions) + { + // HACK: guard against cases where nMmax == nmax, leading to division by 0 in momentum calculation + diesel.maxMomentRevolutions = diesel.maxRevolutions - 1.0 / 60.0; + } + + // Calculation of fuel consumption coefficient for futher calculation + double dizel_max_power = diesel.maxRevolutions * (diesel.maxRevolutionsMoment - diesel.standingMoment) * M_PI * 2 * 0.001; // power in kW + double dizel_max_energy = dizel_max_power; // energy per one hour in kWh is equal to power in kW times 1 h + double fuel_density = 850; // g/l + diesel.fuelConsumption = diesel.nominalFuelConsumptionRate * dizel_max_energy / fuel_density / diesel.maxRevolutions; +} + +void physics::Vehicle::LoadFIZ_FFList(std::string const &Input) +{ + extract_value(FFListSize, "Size", Input, ""); +} + +void physics::Vehicle::LoadFIZ_FFEDList(std::string const &Input) +{ + extract_value(FFEDListSize, "Size", Input, ""); +} + +void physics::Vehicle::LoadFIZ_WiperList(std::string const &Input) +{ + extract_value(WiperListSize, "Size", Input, ""); + extract_value(WiperAngle, "Angle", Input, ""); + extract_value(WiperDefaultPos, "Default", Input, ""); +} + +void physics::Vehicle::LoadFIZ_DimmerList(std::string const &Input) +{ + // extract_value(modernWpierListSize, "Size", Input, ""); + extract_value(modernDimmerCanCycle, "Cycle", Input, ""); + extract_value(modernDimmerDefaultPosition, "DefaultPos", Input, ""); +} +void physics::Vehicle::LoadFIZ_LightsList(std::string const &Input) +{ + + extract_value(LightsPosNo, "Size", Input, ""); + extract_value(LightsWrap, "Wrap", Input, ""); + extract_value(LightsDefPos, "Default", Input, ""); +} + +void physics::Vehicle::LoadFIZ_CompressorList(std::string const &Input) +{ + + extract_value(air.compressor.config.listPositions, "Size", Input, ""); + extract_value(air.compressor.config.listWraps, "Wrap", Input, ""); + extract_value(air.compressor.config.listDefaultPosition, "Default", Input, ""); +} + +void physics::Vehicle::LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Line) +{ + + switch (Powerparameters.SourceType) + { + + case TPowerSource::NotDefined: + case TPowerSource::InternalSource: + { + + Powerparameters.PowerType = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerType", Line)); + break; + } + case TPowerSource::Transducer: + { + + extract_value(Powerparameters.Transducer.InputVoltage, Prefix + "TransducerInputV", Line, ""); + break; + } + case TPowerSource::Generator: + { + // prime mover for the generator + auto &generatorparameters{Powerparameters.EngineGenerator}; + + if (auto const enginetype{LoadFIZ_EngineDecode(extract_value(Prefix + "GeneratorEngine", Line))}; enginetype == TEngineType::Main) + { + generatorparameters.engine_revolutions = &enrot; + } + else + { + // TODO: for engine types other than Main create requested engine object and link to its revolutions + generatorparameters.engine_revolutions = nullptr; + generatorparameters.revolutions = 0; + generatorparameters.voltage = 0; + } + // config + extract_value(generatorparameters.voltage_min, Prefix + "GeneratorMinVoltage", Line, "0"); + extract_value(generatorparameters.voltage_max, Prefix + "GeneratorMaxVoltage", Line, "0"); + // NOTE: for consistency the fiz file specifies revolutions per minute + extract_value(generatorparameters.revolutions_min, Prefix + "GeneratorMinRPM", Line, "0"); + extract_value(generatorparameters.revolutions_max, Prefix + "GeneratorMaxRPM", Line, "0"); + generatorparameters.revolutions_min /= 60; + generatorparameters.revolutions_max /= 60; + break; + } + case TPowerSource::Accumulator: + { + + extract_value(Powerparameters.RAccumulator.MaxCapacity, Prefix + "Cap", Line, ""); + Powerparameters.RAccumulator.RechargeSource = LoadFIZ_SourceDecode(extract_value(Prefix + "RS", Line)); + break; + } + case TPowerSource::CurrentCollector: + { + + auto &collectorparameters = Powerparameters.CollectorParameters; + + collectorparameters = TCurrentCollector{0, 0, 0, 0, 0, 0, false, 0, 0, 0, false, 0}; + + std::string PantType = ""; + extract_value(PantType, "PantType", Line, ""); + if (PantType == "AKP_4E") + collectorparameters.PantographType = TPantType::AKP_4E; + if (PantType.size() >= 3 && PantType.compare(0, 3, "DSA") == 0) + collectorparameters.PantographType = TPantType::DSAx; + if (PantType == "EC160" || PantType == "EC200") + collectorparameters.PantographType = TPantType::EC160_200; + if (PantType == "WBL85") + collectorparameters.PantographType = TPantType::WBL85; + + extract_value(collectorparameters.CollectorsNo, "CollectorsNo", Line, ""); + extract_value(collectorparameters.MinH, "MinH", Line, ""); + extract_value(collectorparameters.MaxH, "MaxH", Line, ""); + extract_value(collectorparameters.CSW, "CSW", Line, ""); // szerokość części roboczej + extract_value(collectorparameters.MaxV, "MaxVoltage", Line, ""); + extract_value(collectorparameters.OVP, "OverVoltProt", Line, ""); // przekaźnik nadnapięciowy + // napięcie rozłączające WS + collectorparameters.MinV = 0.5 * collectorparameters.MaxV; // gdyby parametr nie podany + extract_value(collectorparameters.MinV, "MinV", Line, ""); + // napięcie wymagane do załączenia WS + collectorparameters.InsetV = 0.6 * collectorparameters.MaxV; // gdyby parametr nie podany + extract_value(collectorparameters.InsetV, "InsetV", Line, ""); + // ciśnienie rozłączające WS + extract_value(collectorparameters.MinPress, "MinPress", Line, "3.5"); // domyślnie 2 bary do załączenia WS + // maksymalne ciśnienie za reduktorem + // collectorparameters.MaxPress = 5.0 + 0.001 * ( Random( 50 ) - Random( 50 ) ); + extract_value(collectorparameters.MaxPress, "MaxPress", Line, "5.0"); + extract_value(collectorparameters.FakePower, "FakePower", Line, ""); + if (extract_value(collectorparameters.PhysicalLayout, "PhysicalLayout", Line, "3")) + collectorparameters.CollectorsNo = std::min(collectorparameters.PhysicalLayout, 2); + break; + } + case TPowerSource::PowerCable: + { + + Powerparameters.RPowerCable.PowerTrans = LoadFIZ_PowerDecode(extract_value(Prefix + "PowerTrans", Line)); + if (Powerparameters.RPowerCable.PowerTrans == TPowerType::SteamPower) + { + + extract_value(Powerparameters.RPowerCable.SteamPressure, Prefix + "SteamPress", Line, ""); + } + break; + } + case TPowerSource::Heater: + { + // jeszcze nie skonczone! + break; + } + default:; // nothing here + } + + if (Powerparameters.SourceType != TPowerSource::Heater && Powerparameters.SourceType != TPowerSource::InternalSource) + { + + extract_value(Powerparameters.MaxVoltage, Prefix + "MaxVoltage", Line, ""); + extract_value(Powerparameters.MaxCurrent, Prefix + "MaxCurrent", Line, ""); + extract_value(Powerparameters.IntR, Prefix + "IntR", Line, ""); + } +} + +TPowerType physics::Vehicle::LoadFIZ_PowerDecode(std::string const &Powertype) const +{ + using enum TPowerType; + + std::map> powertypes{ + {"BioPower", BioPower}, {"MechPower", MechPower}, {"ElectricPower", ElectricPower}, {"SteamPower", SteamPower}}; + auto lookup = powertypes.find(Powertype); + return lookup != powertypes.end() ? lookup->second : NoPower; +} + +TPowerSource physics::Vehicle::LoadFIZ_SourceDecode(std::string const &Source) const +{ + using enum TPowerSource; + + std::map> powersources{{"Transducer", Transducer}, {"Generator", Generator}, + {"Accu", Accumulator}, // legacy compatibility leftover. TODO: check if we can get rid of it + {"Accumulator", Accumulator}, {"CurrentCollector", CurrentCollector}, + {"PowerCable", PowerCable}, {"Heater", Heater}, + {"Internal", InternalSource}, {"Main", Main}}; + auto lookup = powersources.find(Source); + return lookup != powersources.end() ? lookup->second : NotDefined; +} + +TEngineType physics::Vehicle::LoadFIZ_EngineDecode(std::string const &Engine) const +{ + using enum TEngineType; + + std::map> enginetypes{{"ElectricSeriesMotor", ElectricSeriesMotor}, + {"DieselEngine", DieselEngine}, + {"SteamEngine", SteamEngine}, + {"WheelsDriven", WheelsDriven}, + {"Dumb", Dumb}, + {"DieselElectric", DieselElectric}, + {"DumbDE", DieselElectric}, + {"ElectricInductionMotor", ElectricInductionMotor}, + {"Main", Main}}; + auto lookup = enginetypes.find(Engine); + return lookup != enginetypes.end() ? lookup->second : None; +} diff --git a/physics/components/inductionmotor.h b/physics/components/inductionmotor.h new file mode 100644 index 000000000..45fc35b12 --- /dev/null +++ b/physics/components/inductionmotor.h @@ -0,0 +1,174 @@ +/* +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 drive of asynchronous motors fed by inverters (ElectricInductionMotor): its definition from the .fiz and its state + +#pragma once + +#include +#include +#include +#include +#include + +// an inverter of the drive +struct Inverter +{ + double Freal = 0.0; + double Request = 0.0; + bool IsActive = true; + bool Activate = true; + bool Error = false; + bool Failure_Drive = false; + bool Failure_Const = false; +}; + +// the motor itself (the s_ entries of eimc before) +struct InductionMotorWinding +{ + double currentPerSlip = 0.0; // dfic: the torque current per hertz of slip, at full flux + double maxSlipFrequency = 0.0; // dfmax: the most slip the drive allows [Hz] + double polePairs = 0.0; // p: the pairs of poles + double voltsPerHertz = 0.0; // cfu: the voltage per hertz of full flux + double torquePerCurrent = 0.0; // cim: the torque per unit of flux and torque current + double fieldCurrentRatio = 0.0; // icif: the field current per unit of torque current +}; + +// the inverter feeding the motors (the f_ entries of eimc before) +struct InductionMotorConverter +{ + double maxLinkVoltage = 0.0; // Uzmax: the most voltage the inverter gives the motors in traction [V] + double brakingLinkVoltage = 0.0; // Uzh: the same in electrodynamic braking [V] + double voltageDrop = 0.0; // DU: the voltage lost in the inverter [V] + double noLoadCurrent = 0.0; // I0: the current the drive draws with no load [A] + double voltsPerHertz = 0.0; // fcfu: the voltage per hertz the inverter gives in traction + double brakingVoltsPerHertz = 0.0; // fcfuH: the same in electrodynamic braking, fcfu without it +}; + +// what the drive gives in traction (the p_ entries of eimc before) +struct InductionMotorTraction +{ + double startingForce = 0.0; // F0: the force at a standstill [kN] + double forceDropPerSpeed = 0.0; // a1: how much of the starting force each km/h takes away [kN/(km/h)] + double maxPower = 0.0; // Pmax: the most power [kW]; follows the table of the most power by the speed, where there is one + double maxCurrent = 0.0; // Imax: the most current of the motors [A] +}; + +// the electrodynamic brake of the drive (the p_ entries of eimc before) +struct InductionMotorBraking +{ + double maxForce = 0.0; // Fh: the most braking force [kN] + double maxPower = 0.0; // Ph: the most braking power [kW] + double offSpeed = 0.0; // Vh0: below this speed the electrodynamic brake gives nothing [km/h] + double fullSpeed = 0.0; // Vh1: above this speed the electrodynamic brake gives all it can; between the two it fades [km/h] + double cylinderPressureGain = 0.0; // abed: the share of the brake cylinder pressure the electrodynamic brake takes; 0: the air brake cuts it off + double maxEpDeceleration = 1.5; // edep: the most the electro-pneumatic brake of a vehicle decelerates its mass before the force goes elsewhere [m/s2] +}; + +// the values of the model of the drive in the step (eimv before) +struct InductionMotorState +{ + // the forces [kN] + double absoluteMaxForce = 0.0; // FMAXMAX: the most force the motors can give at the present speed and voltage + double maxForce = 0.0; // Fmax: the force at the present setting + double fullForce = 0.0; // Fful: the force at a full setting + double force = 0.0; // Fr: the force the motors give + double forceDemand = 0.0; // Fzad: the share of the force asked of the drive, negative in braking + // the frequencies + double slipShare = 0.0; // ks: the force against the most there is, the share of the most slip + double slipFrequency = 0.0; // df [Hz] + double supplyFrequency = 0.0; // fp: the frequency the inverter gives the motors [Hz] + double criticalFrequency = 0.0; // fkr: above this frequency the flux weakens [Hz] + // the motors + double linkVoltage = 0.0; // Uzsmax: the most voltage the inverter can give now [V] + double voltage = 0.0; // U: the voltage of the motors [V] + double flux = 0.0; // pole: the flux against the full one + double torqueCurrent = 0.0; // Ic + double fieldCurrent = 0.0; // If + double torque = 0.0; // M: of a motor + double lineCurrent = 0.0; // Ipoj: the current of the vehicle from the line [A] + double currentLimit = 0.0; // Imax: never set; shown in the debug panel + // the powers [kW] + double powerLimit = 0.0; // Pmax: the most power now, of traction or of braking + double mechanicalPower = 0.0; // Pm + double electricalPower = 0.0; // Pe + double efficiency = 0.0; // eta +}; + +struct InductionMotor +{ + using Listing = std::array, 21>; + + // the definition + InductionMotorWinding motor; + InductionMotorConverter converter; + InductionMotorTraction traction; + InductionMotorBraking braking; + std::map maxPowerTable; /*tablica mocy maksymalnej od predkosci*/ + int inverterCount = 0; // number of inverters + double inverterRatio = 0.0; + int inverterControlCouplings = 4; // the couplings needed to control the inverters, the number of InvCtrCplFlag of the .fiz + bool logForce = false; // EIMCLogForce + + // the state + InductionMotorState state; + double forceShare = 0; /*realizowany procent dostepnej sily rozruchu/hamowania*/ + double inverterFrequency{0.0}; // current frequency of power inverters + std::vector inverters; // all inverters + + // the definition and the state with their labels, for the debug panel + Listing ConfigListing() const + { + return {{{"dfic: ", motor.currentPerSlip}, + {"dfmax:", motor.maxSlipFrequency}, + {"p: ", motor.polePairs}, + {"scfu: ", motor.voltsPerHertz}, + {"cim: ", motor.torquePerCurrent}, + {"icif: ", motor.fieldCurrentRatio}, + {"Uzmax:", converter.maxLinkVoltage}, + {"Uzh: ", converter.brakingLinkVoltage}, + {"DU: ", converter.voltageDrop}, + {"I0: ", converter.noLoadCurrent}, + {"fcfu: ", converter.voltsPerHertz}, + {"F0: ", traction.startingForce}, + {"a1: ", traction.forceDropPerSpeed}, + {"Pmax: ", traction.maxPower}, + {"Fh: ", braking.maxForce}, + {"Ph: ", braking.maxPower}, + {"Vh0: ", braking.offSpeed}, + {"Vh1: ", braking.fullSpeed}, + {"Imax: ", traction.maxCurrent}, + {"abed: ", braking.cylinderPressureGain}, + {"eped: ", braking.maxEpDeceleration}}}; + } + Listing StateListing() const + { + return {{{"Fkrt:", state.absoluteMaxForce}, + {"Fmax:", state.maxForce}, + {"ks: ", state.slipShare}, + {"df: ", state.slipFrequency}, + {"fp: ", state.supplyFrequency}, + {"Us: ", state.voltage}, + {"pole:", state.flux}, + {"Ic: ", state.torqueCurrent}, + {"If: ", state.fieldCurrent}, + {"M: ", state.torque}, + {"Fr: ", state.force}, + {"Ipoj:", state.lineCurrent}, + {"Pm: ", state.mechanicalPower}, + {"Pe: ", state.electricalPower}, + {"eta: ", state.efficiency}, + {"fkr: ", state.criticalFrequency}, + {"Uzsm:", state.linkVoltage}, + {"Pmax:", state.powerLimit}, + {"Fzad:", state.forceDemand}, + {"Imax:", state.currentLimit}, + {"Fful:", state.fullForce}}}; + } +}; diff --git a/physics/components/internal.h b/physics/components/internal.h new file mode 100644 index 000000000..b469abbc5 --- /dev/null +++ b/physics/components/internal.h @@ -0,0 +1,39 @@ +/* +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 helpers the files of physics/components/ share: only they include this header + +#pragma once + +#include + +#include "physics/vehicle.h" + +const double CouplerTune = 0.1; // skalowanie tlumiennosci + + +inline double square(double val) // SQR() zle liczylo w current() ... +{ + return val * val; +} + +int DirPatch(VehicleEnd Coupler1, VehicleEnd Coupler2); + +int DirF(VehicleEnd CouplerN); + +double TableInterpolation(std::map &Map, double Parameter); + +// the force pressing the end in, of the coupling or of the buffers touching [N]: forwards at the front pulls +inline double compression_at(TCoupling const &Coupler, VehicleEnd const End) +{ + return std::max(0.0, (End == VehicleEnd::front ? -1.0 : 1.0) * Coupler.CForce); +} + +bool issection(std::string_view Name, std::string_view Input); + diff --git a/physics/components/lowvoltage.h b/physics/components/lowvoltage.h new file mode 100644 index 000000000..a3c4b1332 --- /dev/null +++ b/physics/components/lowvoltage.h @@ -0,0 +1,129 @@ +/* +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 low voltage supply and the train heating of a vehicle, held by physics::Vehicle as lowVoltage and trainHeating. +// as the parts of the main circuit (maincircuit.h): the definition in `config`, the state behind queries and operations + +#pragma once + +#include "physics/vehicletypes.h" + +namespace physics +{ + +// the battery and the low voltage circuits +class LowVoltageSupply +{ + public: + struct Config + { + float nominalBatteryVoltage{0.f}; + start_t batteryStart{start_t::manual}; + // the battery switch of the cab + bool batteryButtonImpulse{false}; // the switch works as a single button + bool batteryButtonHeld{false}; // the button has to be held to switch the battery on or off + float batteryButtonHoldTime{1.f}; // how long it has to be held [s] + }; + Config config; + + // the battery of the definition (LMaxVoltage), charged + void SetBattery(double const Value) + { + batteryVoltage = Value; + config.nominalBatteryVoltage = static_cast(Value); + } + + bool IsBatteryOn() const { return batteryOn; } + // the battery switch, where the battery is switched by hand; returns whether that changed it + bool SwitchBattery(bool const State) + { + auto const initialstate{batteryOn}; + if (config.batteryStart == start_t::manual) + { + batteryOn = State; + } + return batteryOn != initialstate; + } + // the battery cut off whatever its switch, as for a vehicle prepared for hauling + void DisconnectBattery() { batteryOn = false; } + // the battery as the vehicle is placed: on, unless the vehicle has none + void ResetBattery() { batteryOn = config.batteryStart != start_t::disabled; } + // for the tests: the battery on or off, whatever its switch + void SetBatteryOnForTest(bool const State) { batteryOn = State; } + + double BatteryVoltage() const { return batteryVoltage; } + // the battery drained by the given amount [V]; returns whether its voltage fell too low for the line breaker to hold. + // it neither charges above its nominal voltage nor drops to nothing + bool DrainBattery(double const Drain) + { + batteryVoltage -= Drain; + auto const toolow{config.nominalBatteryVoltage / batteryVoltage > 1.57}; + if (batteryVoltage > config.nominalBatteryVoltage) + { + batteryVoltage = config.nominalBatteryVoltage; // wstrzymanie ładowania pow. 110V + } + if (batteryVoltage < 0.01) + { + batteryVoltage = 0.01; + } + return toolow; + } + // the battery kept at its nominal voltage, where its drain isn't modelled + void KeepBatteryCharged() { batteryVoltage = config.nominalBatteryVoltage; } + + // the low voltage circuits, as the last step found them + bool const &Is24vAvailable() const { return power24vAvailable; } + bool const &Is110vAvailable() const { return power110vAvailable; } + // either of them + bool IsAvailable() const { return power24vAvailable || power110vAvailable; } + // the voltage of the battery circuit + double Voltage24v() const { return power24vVoltage; } + // the circuits in the step: the 24 V one from its voltage, the 110 V one as given + void SetSupply(double const Volts24, bool const Available110v) + { + power24vVoltage = Volts24; + power24vAvailable = power24vVoltage > 0; + power110vAvailable = Available110v; + } + // for the tests of the parts the circuits feed: the power of a circuit as given, whatever the voltage + void Set24vAvailableForTest(bool const State) { power24vAvailable = State; } + void Set110vAvailableForTest(bool const State) { power110vAvailable = State; } + + private: + bool batteryOn{false}; + double batteryVoltage{0.0}; + bool power110vAvailable{false}; + bool power24vAvailable{false}; + double power24vVoltage{0.0}; +}; + +// the heating of the train fed by the vehicle +class TrainHeating +{ + public: + struct Config + { + bool switchImpulse{false}; // the switch springs back to its middle position + double power{0.0}; + double engineRpm{0.0}; // the revolutions of the engine guaranteed with the heating on + }; + Config config; + + bool IsOn() const { return on; } + void SetOn(bool const State) { on = State; } + // the heating switch. TODO: wrap the heating in a basic device + bool IsAllowed() const { return allow; } + void Allow(bool const State) { allow = State; } + + private: + bool on{false}; + bool allow{false}; +}; + +} // namespace physics diff --git a/physics/components/maincircuit.h b/physics/components/maincircuit.h new file mode 100644 index 000000000..39f083687 --- /dev/null +++ b/physics/components/maincircuit.h @@ -0,0 +1,289 @@ +/* +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 main circuit of a vehicle: the line breaker, the line contactors, the protective relays, the converter. Held by +// physics::Vehicle as lineBreaker, lineContactors, protection and converter. +// +// each part holds its definition in `config`, filled from the .fiz and not changed after, and keeps its state to itself: +// the rest of the vehicle reads the state through the queries and changes it through the operations. what decides when +// they act (the interlocks of the cab, the controller positions, the voltages) stays with the vehicle, which hands the +// parts what they need as plain values + +#pragma once + +#include + +#include "physics/vehicletypes.h" + +namespace physics +{ + +// the line breaker (the main switch) of the vehicle +class LineBreaker +{ + public: + struct Config + { + double initTime{0.0}; // how long the main circuit initialises after it gets its power, before the breaker can close [s] + start_t start{start_t::manual}; + // Engine:JointEngineStart: the line breaker / engine start switch of the cab works the vehicles in multiple too; when it + // doesn't, the cab has separate switches for them (mainb_*, mainc_*) + bool jointStart{true}; + // Cntrl.PantRequiresMain: the line breaker closes without traction voltage and holds without it, and the pantographs + // rise and stay up only while it's closed (EU05, EP05, ČD 181 family); off, the pantographs come first and the line + // breaker needs their voltage. what the main circuit feeds still needs the voltage (MainCircuitPowered()), and without + // it the undervoltage relay opens the line contactors (protection.UndervoltageHolds()) + bool pantographsRequireIt{false}; + bool closesOnlyAtNoPower{false}; // it closes only with the master controller at a position of no power + // Cntrl.EmergencyBrakeMainOff: the brake pipe pressure [bar] taken for an emergency brake application: below it, with + // the master controller on a power position, the line breaker opens and doesn't close again. where the pantographs + // stay up only through the closed line breaker (pantographsRequireIt) they drop with it (EP05). 0: an emergency + // application leaves the line breaker alone + double emergencyOffPressure{0.0}; + }; + Config config; + + bool IsClosed() const { return closed; } + void Close() { closed = true; } + void Open() { closed = false; } + + // how long the main circuit still initialises [s]; below zero once it's done + double RemainingInitTime() const { return initCountdown; } + // the main circuit is done initialising, the breaker may close + bool IsInitialised() const { return initCountdown <= 0.0; } + // the step of the supply of the main circuit: with it the initialisation counts down, without it it starts over. + // returns whether the circuit has its supply and was done initialising before this step, when it may start on its own + bool UpdateInitialisation(bool const supplied, double const dt) + { + if (false == supplied) + { + initCountdown = config.initTime; + return false; + } + // NOTE: readiness means a countdown below zero, which rules out at once the vehicles of no initialisation time + if (initCountdown >= 0.0) + { + initCountdown -= dt; + return false; + } + return true; + } + + private: + bool closed{false}; + double initCountdown{0.0}; // how long it still initialises [s] +}; + +// the line contactors of the traction motors +class LineContactors +{ + public: + struct Config + { + std::string switchType; // StLinSwitchType: the kind of the switch of the cab + line_contactors_interlock interlock{line_contactors_interlock::none}; // what else they need to close + }; + Config config; + + bool IsClosed() const { return closed; } + void Close() { closed = true; } + void Open() { closed = false; } + + // the button of the cab that forces them open + bool IsForcedOpen() const { return forcedOpen; } + void ForceOpen(bool const State) { forcedOpen = State; } + + // the time since the master controller or the relays of the start last switched [s] + double TimeSinceSwitch() const { return lastSwitchTime; } + void RestartSwitchTimer() { lastSwitchTime = 0.0; } + void AdvanceSwitchTimer(double const dt) { lastSwitchTime += dt; } + + private: + bool closed{false}; + bool forcedOpen{false}; + double lastSwitchTime{0.0}; +}; + +// the protective relays and the pressure switch of the main circuit. the relays hold (true) while all is well and drop +// (false) when they protect the circuit +class ProtectionRelays +{ + public: + struct Config + { + start_t groundStart{start_t::manual}; // how the ground relay is reset + bool hasPressureSwitch{true}; + // Engine:PressureSwitchBrakeCylinder: the pressure switch watches the brake cylinders (it cuts the start off above 2 bar + // there) as well as the brake pipe (below 3.6 bar). off, it's left with the brake pipe alone, and the vehicle takes + // current whatever the pressure in its brake cylinders (EP05) + bool pressureSwitchWatchesCylinders{true}; + }; + Config config; + + // the undervoltage relay: it drops if the voltage falls below its threshold, which opens the line breaker; with + // lineBreaker.config.pantographsRequireIt it opens the line contactors instead, and picks up again only with the master + // controller at zero or the first position + bool UndervoltageHolds() const { return noVoltage; } + // the overvoltage relay, which drops above the voltage it's set to + bool OvervoltageHolds() const { return overvoltage; } + // the voltage relays as the drive of the vehicle judges them from the voltage of its supply + void SetVoltageRelays(bool const undervoltageHolds, bool const overvoltageHolds) + { + noVoltage = undervoltageHolds; + overvoltage = overvoltageHolds; + } + + // the ground relay, which drops to protect against damage from earths + bool GroundHolds() const { return ground; } + // the ground relay of a series motor vehicle in the step: it drops without the low voltage, and one that isn't reset + // by hand picks up again with it + void UpdateGround(bool const lowVoltagePower) + { + ground &= lowVoltagePower; + if (config.groundStart != start_t::manual) + { + // NOTE: we're ignoring intricaties of battery and converter types as they're unlikely to be used + // TODO: generic check method which takes these into account + ground |= lowVoltagePower; + } + } + // the reset of the ground relay, which needs the low voltage; returns whether it picked up + bool ResetGround(bool const lowVoltagePower) + { + auto const reset{false == ground && lowVoltagePower}; + ground |= lowVoltagePower; + return reset; + } + + // tripped while the brake pipe and/or the brake cylinders aren't at their working pressures + bool PressureSwitchTripped() const { return pressureSwitch; } + // the pressure switch in the step, from the pressures [bar] + void UpdatePressureSwitch(double const cylinderPressure, double const pipePressure) + { + pressureSwitch = config.hasPressureSwitch && ((config.pressureSwitchWatchesCylinders && cylinderPressure > 2.0) || pipePressure < 3.6); + } + + private: + bool noVoltage{true}; + bool overvoltage{true}; + bool ground{true}; + bool pressureSwitch{false}; +}; + +// what the converter of the vehicle needs to know in the step +struct ConverterSupply +{ + bool lineBreakerClosed{false}; + bool lowVoltage24v{false}; // the 24 V circuits have their power + bool directionActive{false}; // the reverser is set + bool pantographPressureLock{false}; // the pressure lock of the pantographs is on + bool highVoltage{false}; // the main circuit, or for a vehicle of no power of its own the train line, has its voltage + bool damaged{false}; // the converter is damaged +}; + +// the converter of the vehicle +class PowerConverter +{ + public: + struct Config + { + start_t start{start_t::manual}; // whether it is started by hand, or another way + float startDelay{0.0f}; // the delay before it starts, once its conditions are met [s] + start_t overloadRelayStart{start_t::manual}; // whether its overload relay is reset by a button of its own + bool overloadRelayOffWithLineBreaker{false}; // ConverterOverloadRelayOffWhenMainIsOff + std::string switchType; // ConvSwitchType: the kind of the switch of the cab. TODO: the kinds of the switches belong to the cab definition + }; + Config config; + + bool IsRunning() const { return running; } + // it may run, as its switch (or its start) has it + bool IsAllowed() const { return allow; } + // the switch of the converter, where it is worked by hand; returns whether that changed it + bool Switch(bool const State) + { + auto const initialstate{allow}; + if (config.start == start_t::manual) + { + allow = State; + } + return allow != initialstate; + } + // the switch of the vehicle itself; most have none, so it allows + bool LocalSwitchOn() const { return allowLocal; } + void SetLocalSwitch(bool const State) { allowLocal = State; } + + // the overload relay of the converter and the heating + bool IsOverloaded() const { return overloaded; } + void Overload() { overloaded = true; } + // the reset of the overload relay, which needs the low voltage; returns whether it was tripped + bool ResetOverloadRelay(bool const lowVoltagePower) + { + auto const reset{overloaded && lowVoltagePower}; + overloaded &= false == lowVoltagePower; + return reset; + } + + // the converter in the step + void Update(ConverterSupply const &supply, double const dt) + { + if (config.start != start_t::disabled && config.overloadRelayOffWithLineBreaker) + { + overloaded |= false == supply.lineBreakerClosed && supply.lowVoltage24v; + } + switch (config.start) + { + case start_t::disabled: + allow = false; + // NOTE: if there's no converter in vehicle we can end the check here + return; + case start_t::automatic: + allow = supply.lineBreakerClosed; + break; + case start_t::direction: + allow = supply.directionActive; + break; + default: + break; + } + if (allow && allowLocal && false == overloaded && false == supply.pantographPressureLock && supply.highVoltage) + { + // delay timer can be optionally configured, and is set anew whenever converter goes off + if (startDelayTimer <= 0.0) + { + running = true; + } + else + { + startDelayTimer -= dt; + } + } + else + { + running = false; + startDelayTimer = static_cast(config.startDelay); + } + if (config.overloadRelayStart == start_t::converter && false == (allow && allowLocal) && false == supply.damaged) + { + // reset converter overload relay if the converter was switched off, unless it's damaged + overloaded = false; + } + } + + // for the tests of the parts it feeds: the converter running, or not, whatever its conditions + void SetRunningForTest(bool const State) { running = State; } + + private: + bool allow{false}; + bool allowLocal{true}; + bool running{false}; + bool overloaded{false}; + double startDelayTimer{0.0}; // how long its conditions have been met +}; + +} // namespace physics diff --git a/physics/components/pantographs.h b/physics/components/pantographs.h new file mode 100644 index 000000000..be7ab5688 --- /dev/null +++ b/physics/components/pantographs.h @@ -0,0 +1,213 @@ +/* +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 circuit and the air of the pantographs of a vehicle, held by physics::Vehicle as pantographCircuit and +// pantographAir beside its pantographs. as the parts of the main circuit (maincircuit.h): the definition in `config`, the +// state behind queries and operations + +#pragma once + +#include +#include +#include + +#include "physics/components/devices.h" + +namespace physics +{ + +// the circuit of the pantographs: their voltages, the kind of their switches, the presets of the cabs +class PantographCircuit +{ + public: + struct Config + { + std::string switchType; // PantSwitchType: the kind of the switches of the cab + }; + Config config; + + // the voltage at the pantograph of the given end, from the overhead line it touches + double Voltage(VehicleEnd const End) const { return End == VehicleEnd::front ? frontVoltage : rearVoltage; } + double FrontVoltage() const { return frontVoltage; } + double RearVoltage() const { return rearVoltage; } + void SetFrontVoltage(double const Value) { frontVoltage = Value; } + void SetRearVoltage(double const Value) { rearVoltage = Value; } + // the voltage supplied to the pantographs, from the overhead line the vehicle is under + double SupplyVoltage() const { return supplyVoltage; } + void SetSupplyVoltage(double const Value) { supplyVoltage = Value; } + + // the switch that lowers all of them + bool AllDown() const { return allDown; } + void SetAllDown(bool const State) { allDown = State; } + + // the presets of the pantographs: the setups they can be switched to as chars, and the one selected in each cab + std::pair> presets{"0132", {0, 0}}; + + private: + double frontVoltage{0.0}; + double rearVoltage{0.0}; + double supplyVoltage{0.0}; + bool allDown{false}; +}; + +// what the air of the pantographs needs to know in the step +struct PantographAirSupply +{ + bool anyPantographActive{false}; // a pantograph of the vehicle is up or rising + bool lowVoltage{false}; // the low voltage circuits have their power + bool collectors{false}; // the vehicle takes its power through pantographs: they have air of their own + bool multipleUnit{false}; // an electric multiple unit: its small compressor fills slower, its pressure switch locks + double mainReservoirPressure{0.0}; // [bar] + double controlReservoirPressure{0.0}; // [bar], what the gauge shows on a vehicle of no pantographs + double maxPressure{0.0}; // of the pantographs [bar], CollectorParameters.MaxPress + double minPressure{0.0}; // below which the pressure switch trips [bar], CollectorParameters.MinPress +}; + +// the air of the pantographs: their reservoir, the small compressor that fills it, the valves +class PantographAir +{ + public: + struct Config + { + start_t compressorStart{start_t::manual}; // PantCompressorStart + int compressorPower{0}; // SmallCompressorPower + bool autoValve{false}; // the kind of the valve of the small compressor fitted + }; + Config config; + + basic_valve valve; + + // in the reservoirs of the pantographs [bar] + double const &Pressure() const { return pressure; } + // the air in them, in the units of the model of their reservoir + double Volume() const { return volume; } + // the reservoirs of a vehicle placed with its pantographs down and empty + void Empty() + { + volume = 0.1; + pressure = 0.0; + } + + // the small compressor + bool IsCompressorRunning() const { return compressorRunning; } + void SwitchCompressor(bool const State) { compressorRunning = State; } + // the three-way cock: to the main reservoir, or to the small compressor + bool IsConnectedToMainReservoir() const { return connectedToMainReservoir; } + void ConnectToMainReservoir(bool const State) { connectedToMainReservoir = State; } + + // the pressure switch, primed at the pressure set in the air of the pantographs + bool IsPressureSwitchPrimed() const { return pressureSwitchActive; } + // the lock of the converter and the heating of a multiple unit, set when the pressure switch trips + bool IsPressureLockActive() const { return pressureLockActive; } + + // the step of the air of the pantographs. returns whether the pressure switch tripped in it, by the pressure falling + // below its level: the switch is spent then, and the lock of a multiple unit set; what else follows is up to the vehicle + bool Update(PantographAirSupply const &Supply, double const dt) + { + // automatic start if the pressure is too low + compressorRunning |= pressure < 4.2 && Supply.anyPantographActive && (config.compressorStart == start_t::automatic || config.compressorStart == start_t::manualwithautofallback); + compressorRunning &= Supply.lowVoltage; + + if (false == Supply.collectors) + { + // a tu coś dla SM42 i SM31, aby pokazywać na manometrze + pressure = Supply.controlReservoirPressure; + return false; + } + // Ra 2014-07: zasadniczo, to istnieje zbiornik rozrządu i zbiornik pantografów - na razie mamy razem + // Ra 2014-07: kurek trójdrogowy łączy spr.pom. z pantografami i wyłącznikiem ciśnieniowym WS + // Ra 2014-07: zbiornika rozrządu nie pompuje się tu, tylko pantografy; potem można zamknąć + // WS i odpalić resztę + if (config.autoValve ? pressure < Supply.mainReservoirPressure : connectedToMainReservoir) // kurek zamyka połączenie z ZG + { + // zbiornik pantografu połączony ze zbiornikiem głównym - małą sprężarką się tego nie napompuje + // Ra 2013-12: Niebugocław mówi, że w EZT nie ma potrzeby odcinać kurkiem + // ograniczenie ciśnienia do MaxPress (tylko w pantografach!) + // (the bounds as the .fiz gives them, which may cross) + pressure = std::min(std::max(Supply.mainReservoirPressure, 0.0), Supply.maxPressure); + volume = (pressure + 1.0) * 0.1; // objętość, na wypadek odcięcia kurkiem + } + else + { + // zbiornik główny odcięty, można pompować pantografy + if (compressorRunning) + { + // włączona mała sprężarka + volume += dt + // Ra 2013-12: Niebugocław mówi, że w EZT nabija 1.5 raz wolniej niż jak było 0.005 + * (Supply.multipleUnit ? 0.003 : 0.005) / std::max(1.0, pressure) * (0.45 - (0.1 / volume / 10 - 0.1)) / 0.45; + } + pressure = std::min(std::max(10.0 * volume - 1.0, 0.0), Supply.maxPressure); // tu by się przydała objętość zbiornika + } + if (false == compressorRunning && volume > 0.1) + { + volume -= dt * 0.0003 * std::max(1.0, pressure * 0.5); // nieszczelności: 0.0003=0.3l/s + } + return UpdatePressureSwitch(Supply); + } + + // the pressure switch: low, it trips once (see Update()); primed again over 4.6 bar, where the small compressor stops + // at 4.8. returns whether it tripped + bool UpdatePressureSwitch(PantographAirSupply const &Supply) + { + if (pressure < Supply.minPressure) + { + // 3.5 wg http://www.transportszynowy.pl/eu06-07pneumat.php + if (false == pressureSwitchActive) + { + return false; + } + // specialized variant for EMU -- pwr system disables converter and heating, + // and prevents their activation until pressure switch is set again + if (Supply.multipleUnit) + { + pressureLockActive = true; + } + // mark the pressure switch as spent + pressureSwitchActive = false; + return true; + } + if (pressure >= 4.6) + { + // NOTE: we require active low power source to prime the pressure switch + // this is a work-around for potential isssues caused by the switch activating on otherwise idle vehicles, but should check whether it's accurate + if (Supply.lowVoltage) + { + // prime the pressure switch + pressureSwitchActive = true; + // turn off the subsystems lock + pressureLockActive = false; + } + if (pressure >= 4.8) + { + // Winger - automatyczne wylaczanie malej sprezarki + // TODO: governor lock, disables usage until pressure drop below 3.8 (should really make compressor object we could reuse) + compressorRunning = false; + } + } + return false; + } + + // for the tests: the reservoirs at the given pressure, with the pressure switch primed or not + void SetForTest(double const Value, bool const PressureSwitchPrimed) + { + pressure = Value; + pressureSwitchActive = PressureSwitchPrimed; + } + + private: + double volume{0.48}; // so that the raised pantographs drop soon with the compressor off + double pressure{0.0}; + bool compressorRunning{false}; + bool connectedToMainReservoir{true}; + bool pressureSwitchActive{false}; + bool pressureLockActive{false}; +}; + +} // namespace physics diff --git a/physics/components/pneumatics.cpp b/physics/components/pneumatics.cpp new file mode 100644 index 000000000..335616420 --- /dev/null +++ b/physics/components/pneumatics.cpp @@ -0,0 +1,1521 @@ +/* +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 brakes and the air: the brake controls, the pipes, the valves, the compressor, the spring brake + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +// Nastawianie hamulców + +void physics::Vehicle::BrakeLevelSet(double b) +{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo + // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego + if (brakes.HandlePositionSmooth() == b) + return; // nie przeliczać, jak nie ma zmiany + brakes.SetHandlePositionSmooth(b); + if (brakes.HandlePositionSmooth() < brakes.driverValve->GetPos(bh_MIN)) + brakes.SetHandlePositionSmooth(brakes.driverValve->GetPos(bh_MIN)); // odcięcie + else if (brakes.HandlePositionSmooth() > brakes.driverValve->GetPos(bh_MAX)) + brakes.SetHandlePositionSmooth(brakes.driverValve->GetPos(bh_MAX)); + // TODO: verify whether BrakeCtrlPosR and fBrakeCtrlPos can be rolled into single variable + brakes.SetHandlePositionReal(brakes.HandlePositionSmooth()); + auto x = static_cast(std::floor(brakes.HandlePositionSmooth())); // jeśli odwołujemy się do BrakeCtrlPos w pośrednich, to musi być + // obcięte a nie zaokrągone + while (x > brakes.HandlePosition() && brakes.HandlePosition() < brakes.config.handlePositions) // jeśli zwiększyło się o 1 + if (!IncBrakeLevelOld()) // physics::Vehicle:: + break; // wyjście awaryjne + while (x < brakes.HandlePosition() && brakes.HandlePosition() >= -1) // jeśli zmniejszyło się o 1 + if (!DecBrakeLevelOld()) // physics::Vehicle:: + break; + brakes.actualPressure = brakes.config.pressureTable[brakes.HandlePosition()]; // skopiowanie pozycji + /* + //youBy: obawiam sie, ze tutaj to nie dziala :P + //Ra 2014-03: było tak zrobione, że działało - po każdej zmianie pozycji była wywoływana ta + funkcja + // if (BrakeSystem==Pneumatic?BrakeSubsystem==Oerlikon:false) //tylko Oerlikon akceptuje ułamki + if(false) + if (fBrakeCtrlPos>0.0) + {//wartości pośrednie wyliczamy tylko dla hamowania + double u=fBrakeCtrlPos-double(x); //ułamek ponad wartość całkowitą + if (u>0.0) + {//wyliczamy wartości ważone + BrakePressureActual.PipePressureVal+=-u*BrakePressureActual.PipePressureVal+u*BrakePressureTable[BrakeCtrlPos+1+2].PipePressureVal; + //BrakePressureActual.BrakePressureVal+=-u*BrakePressureActual.BrakePressureVal+u*BrakePressureTable[BrakeCtrlPos+1].BrakePressureVal; + //to chyba nie będzie tak działać, zwłaszcza w EN57 + BrakePressureActual.FlowSpeedVal+=-u*BrakePressureActual.FlowSpeedVal+u*BrakePressureTable[BrakeCtrlPos+1+2].FlowSpeedVal; + } + } + */ +}; + +bool physics::Vehicle::BrakeLevelAdd(double b) +{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) + // zwraca false, gdy po dodaniu było by poza zakresem + BrakeLevelSet(brakes.HandlePositionSmooth() + b); + return b > 0.0 ? brakes.HandlePositionSmooth() < brakes.config.handlePositions : brakes.HandlePosition() > -1.0; // true, jeśli można kontynuować +}; + +bool physics::Vehicle::IncBrakeLevel() +{ // nowa wersja na użytek AI, false gdy osiągnięto pozycję BrakeCtrlPosNo + return BrakeLevelAdd(1.0); +}; + +bool physics::Vehicle::DecBrakeLevel() +{ + return BrakeLevelAdd(-1.0); +}; // nowa wersja na użytek AI, false gdy osiągnięto pozycję -1 + +/* Ukrotnienie EN57: +1 //układ szeregowy +2 //układ równoległy +3 //bocznik 1 +4 //bocznik 2 +5 //bocznik 3 +6 //do przodu +7 //do tyłu +8 //1 przyspieszenie +9 //minus obw. 2 przyspieszenia +10 //jazda na oporach +11 //SHP +12A //podnoszenie pantografu przedniego +12B //podnoszenie pantografu tylnego +13A //opuszczanie pantografu przedniego +13B //opuszczanie wszystkich pantografów +14 //załączenie WS +15 //rozrząd (WS, PSR, wał kułakowy) +16 //odblok PN +18 //sygnalizacja przetwornicy głównej +19 //luzowanie EP +20 //hamowanie EP +21 //rezerwa** (1900+: zamykanie drzwi prawych) +22 //zał. przetwornicy głównej +23 //wył. przetwornicy głównej +24 //zał. przetw. oświetlenia +25 //wył. przetwornicy oświetlenia +26 //sygnalizacja WS +28 //sprężarka +29 //ogrzewanie +30 //rezerwa* (1900+: zamykanie drzwi lewych) +31 //otwieranie drzwi prawych +32H //zadziałanie PN siln. trakcyjnych +33 //sygnał odjazdu +34 //rezerwa (sygnalizacja poślizgu) +35 //otwieranie drzwi lewych +ZN //masa +*/ + +// ***************************************************************************** +// Q: 20160714 +// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca pomocnicznego +// ***************************************************************************** +double physics::Vehicle::LocalBrakeRatio(void) const +{ + double LBR; + if (brakes.config.driverValveType == TBrakeHandle::MHZ_EN57) + if (brakes.operatingMode >= bom_EP) + LBR = brakes.driverValve->GetEP(brakes.HandlePositionReal()); + else + LBR = 0; + else + { + if (LocalBrakePosNo > 0) + LBR = brakes.IndependentPosition(); + else + LBR = 0; + } + // if (TestFlag(BrakeStatus, b_antislip)) + // LBR = std::max(LBR, PipeRatio) + 0.4; + return LBR; +} + +// ***************************************************************************** +// Q: 20160714 +// Oblicza iloraz aktualnej pozycji do maksymalnej hamulca ręcznego +// ***************************************************************************** +double physics::Vehicle::ManualBrakeRatio(void) const +{ + double MBR; + + if (ManualBrakePosNo > 0) + MBR = (double)brakes.HandBrakePosition() / ManualBrakePosNo; + else + MBR = 0; + return MBR; +} + +// ***************************************************************************** +// Q: 20160713 +// Zwraca objętość +// ***************************************************************************** +double physics::Vehicle::BrakeVP(void) const +{ + if (brakes.config.valveVolume > 0) + return brakes.reservoirAir / (10.0 * brakes.config.valveVolume); + else + return 0; +} + +// ***************************************************************************** +// Q: 20160713 +// Zwraca iloraz różnicy między przewodem kontrolnym i głównym oraz DeltaPipePress +// ***************************************************************************** +double physics::Vehicle::RealPipeRatio(void) const +{ + double rpp; + + if (brakes.config.pipePressureRange > 0) + rpp = (brakes.controlReservoirPressure - brakePipe.Pressure()) / brakes.config.pipePressureRange; + else + rpp = 0; + return rpp; +} + +// ***************************************************************************** +// Q: 20160713 +// Zwraca iloraz ciśnienia w przewodzie do DeltaPipePress +// ***************************************************************************** +double physics::Vehicle::PipeRatio(void) const +{ + double pr; + + if (brakes.config.pipePressureRange > 0) + if (false) // SPKS!! no to jak nie wchodzimy to po co branch? + { + if (3.0 * brakePipe.Pressure() > brakes.config.pipeHighPressure + brakes.config.pipeLowPressure + brakes.config.pipeLowPressure) + pr = (brakes.config.pipeHighPressure - std::min(brakes.config.pipeHighPressure, brakePipe.Pressure())) / (brakes.config.pipePressureRange * 4.0 / 3.0); + else + pr = (brakes.config.pipeHighPressure - 1.0 / 3.0 * brakes.config.pipePressureRange - std::max(brakes.config.pipeLowPressure, brakePipe.Pressure())) / (brakes.config.pipePressureRange * 2.0 / 3.0); + // if (not TestFlag(BrakeStatus, b_Ractive)) + // and(BrakeMethod and 1 = 0) and TestFlag(BrakeDelays, bdelay_R) and (Power < 1) and + // (BrakeCtrlPos < 1) then pr : = std::min(0.5, pr); + // if (Compressor > 0.5) + // then pr : = pr * 1.333; // dziwny rapid wywalamy + } + else + pr = (brakes.config.pipeHighPressure - std::max(brakes.config.pipeLowPressure, std::min(brakes.config.pipeHighPressure, brakePipe.Pressure()))) / brakes.config.pipePressureRange; + else + pr = 0; + return pr; +} + +// ************************************************************************************************* +// Q: 20160710 +// włączenie / wyłączenie hamulca elektro-pneumatycznego +// ************************************************************************************************* +bool physics::Vehicle::EpFuseSwitch(bool State) +{ + if (epFuse != State) + { + epFuse = State; + return true; + } + else + return false; + // if (EpFuse == true) SendCtrlToNext(VehicleCommand::epFuseSwitch, 1, CabActive) + // else SendCtrlToNext(VehicleCommand::epFuseSwitch, 0, CabActive); +} + +// ************************************************************************************************* +// yB: 20190906 +// włączenie / wyłączenie hamulca sprezynowego +// ************************************************************************************************* +bool physics::Vehicle::SpringBrakeActivate(bool State) +{ + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) + { + SendCtrlToNext(VehicleCommand::springBrakeActivate, int(State), CabActive, CouplingSet::FromBits(brakes.spring.controlCouplings)); + + if (brakes.spring.activate != State) + { + brakes.spring.activate = State; + wake_for_brake(); + return true; + } + } + return false; +} + +// ************************************************************************************************* +// yB: 20190906 +// włączenie / wyłączenie odciecia hamulca sprezynowego +// ************************************************************************************************* +bool physics::Vehicle::SpringBrakeShutOff(bool State) +{ + if (brakes.spring.shutOff != State) + { + brakes.spring.shutOff = State; + return true; + } + else + return false; +} + +// ************************************************************************************************* +// yB: 20190906 +// wyluzowanie hamulca sprezynowego +// ************************************************************************************************* +bool physics::Vehicle::SpringBrakeRelease() +{ + if (brakes.spring.isReady && brakes.spring.cylinder->P() < brakes.spring.minForcePressure) + { + brakes.spring.isReady = false; + wake_for_brake(); + return true; + } + else + return false; +} + +// ************************************************************************************************* +// Q: 20160710 +// załączenie przycisku przeciwpoślizgowego +// ************************************************************************************************* +bool physics::Vehicle::AntiSlippingButton(void) +{ + // NOTE: disabled the sandbox part, it's already controlled by another part of the AI routine + return AntiSlippingBrake() /*|| Sandbox(true)*/; +} + +// ************************************************************************************************* +// Q: 20160713 +// włączenie / wyłączenie sprężarki +// ************************************************************************************************* +bool physics::Vehicle::CompressorSwitch(bool State, range_t const Notify) +{ + + if (air.compressor.config.start != start_t::manual) + { + // only pay attention if the compressor can be controlled manually + return false; + } + + auto const initialstate{air.compressor.IsAllowed()}; + + if (air.config.mainReservoirVolume > 0.0 && air.compressor.config.speed > 0.0) + { + air.compressor.Allow(State); + } + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::compressorSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return air.compressor.IsAllowed() != initialstate; +} + +bool physics::Vehicle::ChangeCompressorPreset(int const State, range_t const Notify) +{ + + auto const initialstate{air.compressor.ListPosition()}; + + air.compressor.SetListPosition(State); + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::compressorPreset, State, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return air.compressor.ListPosition() != initialstate; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie nastawy hamulca +// ************************************************************************************************* +bool physics::Vehicle::IncBrakeLevelOld(void) +{ + bool IBLO = false; + + if (brakes.config.handlePositions > 0) + { + if (brakes.HandlePosition() < brakes.config.handlePositions) + { + brakes.SetHandlePosition(brakes.HandlePosition() + 1); + // youBy: EP po nowemu + IBLO = true; + if (brakes.actualPressure.PipePressureVal < 0 && brakes.config.pressureTable[brakes.HandlePosition() - 1].PipePressureVal > 0) + brakes.pipeLimiterPressure = brakePipe.Pressure(); + } + else + { + IBLO = false; + } + } + + return IBLO; +} + +// ***************************************************************************** +// Q: 20160711 +// zmniejszenie nastawy hamulca +// ***************************************************************************** +bool physics::Vehicle::DecBrakeLevelOld(void) +{ + bool DBLO = false; + + if (brakes.config.handlePositions > 0) + { + if (brakes.HandlePosition() > (brakes.config.driverValveType == TBrakeHandle::FV4a ? -2 : -1)) + { + brakes.SetHandlePosition(brakes.HandlePosition() - 1); + // youBy: EP po nowemu + DBLO = true; + // if ((BrakePressureTable[BrakeCtrlPos].PipePressureVal<0.0) && + // (BrakePressureTable[BrakeCtrlPos+1].PipePressureVal > 0)) + // LimPipePress=PipePress; + } + else + DBLO = false; + } + + return DBLO; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie nastawy hamulca pomocnicznego +// ************************************************************************************************* +bool physics::Vehicle::IncLocalBrakeLevel(float const CtrlSpeed) +{ + bool IBL; + if (brakes.IndependentPosition() < 1.0 /*and (BrakeCtrlPos<1)*/) + { + brakes.SetIndependentPosition(std::min(1.0, brakes.IndependentPosition() + CtrlSpeed / LocalBrakePosNo)); + wake_for_brake(); + IBL = true; + } + else + IBL = false; + + return IBL; +} + +// ************************************************************************************************* +// Q: 20160711 +// zmniejszenie nastawy hamulca pomocniczego +// ************************************************************************************************* +bool physics::Vehicle::DecLocalBrakeLevel(float const CtrlSpeed) +{ + bool DBL; + if (brakes.IndependentPosition() > 0) + { + brakes.SetIndependentPosition(std::max(0.0, brakes.IndependentPosition() - CtrlSpeed / LocalBrakePosNo)); + wake_for_brake(); + DBL = true; + } + else + DBL = false; + + return DBL; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie nastawy hamulca ręcznego +// ************************************************************************************************* +bool physics::Vehicle::IncManualBrakeLevel(int CtrlSpeed) +{ + bool IMBL; + if (brakes.HandBrakePosition() < ManualBrakePosNo) /*and (BrakeCtrlPos<1)*/ + { + while (brakes.HandBrakePosition() < ManualBrakePosNo && CtrlSpeed > 0) + { + brakes.SetHandBrakePosition(brakes.HandBrakePosition() + 1); + CtrlSpeed--; + } + wake_for_brake(); + IMBL = true; + } + else + IMBL = false; + + return IMBL; +} + +// ************************************************************************************************* +// Q: 20160711 +// zmniejszenie nastawy hamulca ręcznego +// ************************************************************************************************* +bool physics::Vehicle::DecManualBrakeLevel(int CtrlSpeed) +{ + bool DMBL; + if (brakes.HandBrakePosition() > 0) + { + while (CtrlSpeed > 0 && brakes.HandBrakePosition() > 0) + { + brakes.SetHandBrakePosition(brakes.HandBrakePosition() - 1); + CtrlSpeed--; + } + wake_for_brake(); + DMBL = true; + } + else + DMBL = false; + return DMBL; +} + +bool physics::Vehicle::AlarmChainSwitch(bool const State) +{ + + if (brakes.alarmChain != State) + { + // simple routine for the time being + brakes.alarmChain = State; + return true; + } + return false; +} + +// ************************************************************************************************* +// Q: 20160710 +// hamowanie przeciwpoślizgowe +// ************************************************************************************************* +bool physics::Vehicle::AntiSlippingBrake(void) +{ + bool ASB = false; // Ra: przeniesione z końca + if (brakes.config.antiSlipType == 1) + { + ASB = true; // SPKS!! + brakes.distributor->ASB(1); + brakes.antiSlipTimer = 0; + } + return ASB; +} + +// ************************************************************************************************* +// Q: 20160711 +// włączenie / wyłączenie odluźniacza +// ************************************************************************************************* +bool physics::Vehicle::BrakeReleaser(int state) +{ + bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 + if (state != 0) + { + // additional limitations imposed by pressure switch + if (false == protection.PressureSwitchTripped() || false == ReleaserEnabledOnlyAtNoPowerPos || true == IsMainCtrlNoPowerPos()) + { + brakes.distributor->Releaser(state); + } + } + else + { + brakes.distributor->Releaser(state); + } + if (CabActive != 0) // rekurencyjne wysłanie do następnego + OK = SendCtrlToNext(VehicleCommand::brakeReleaser, state, CabActive); + return OK; +} + +// ************************************************************************************************* +// yB: 20160711 +// włączenie / wyłączenie uniwersalnego przycisku hamulcowego +// ************************************************************************************************* +bool physics::Vehicle::UniversalBrakeButton(int button, int state) +{ + bool OK = true; // false tylko jeśli nie uda się wysłać, GF 20161124 + brakes.universalButtonPressed[button] = state > 0; + int flag = 0; + if (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()) + { + for (int i = 0; i < 3; i++) + { + flag = flag | (brakes.universalButtonPressed[i] ? brakes.config.universalButtonActions[i] : 0); + } + } + + brakes.distributor->SetUniversalFlag(flag); + brakes.driverValve->SetUniversalFlag(flag); + brakes.independentValve->SetUniversalFlag(flag); + brakes.pipeLock.unlockPressed = (flag & TUniversalBrake::ub_UnlockPipe) > 0; + + // if the releaser can be activated by switch + if (TestFlag(brakes.config.universalButtonActions[0] & brakes.config.universalButtonActions[1] & brakes.config.universalButtonActions[2], TUniversalBrake::ub_Release)) + { + BrakeReleaser(TestFlag(flag, TUniversalBrake::ub_Release) ? 1 : 0); + } + return OK; +} + +// ************************************************************************************************* +// Q: 20160711 +// włączenie / wyłączenie hamulca elektro-pneumatycznego +// ************************************************************************************************* +bool physics::Vehicle::SwitchEPBrake(int state) +{ + bool OK; + + OK = false; + if (brakes.config.driverValveType == TBrakeHandle::St113 && cabOccupied != 0) + { + // the handle works the EP contactors pneumatically, their supply is cut as the Oerlikon handle's is + if (state > 0 && EPBrakeControlPowered()) + EpForce = brakes.driverValve->GetEP(); // TODO: przetlumaczyc + else + EpForce = 0; + brakes.distributor->SetEPS(EpForce); + SendCtrlToNext(VehicleCommand::brake, EpForce, CabActive); + } + // OK:=SetFlag(BrakeStatus,((2*State-1)*b_epused)); + // SendCtrlToNext('Brake',(state*(2*BrakeCtrlPos-1)),CabActive); + return OK; +} + +bool physics::Vehicle::EPBrakeControlPowered() const +{ + return lowVoltage.Is24vAvailable() && DirActive != 0 && epFuse; +} + +// ************************************************************************************************* +// Q: 20160711 +// zwiększenie ciśnienia hamowania +// ************************************************************************************************* +bool physics::Vehicle::IncBrakePress(double &brake, double PressLimit, double dp) +{ + bool IBP; + // if (DynamicBrakeType<>dbrake_switch) and (DynamicBrakeType<>dbrake_none) and + // ((BrakePress>2.0) or (PipePress<3.7{(LowPipePress+0.5)})) then + if (brakes.electrodynamic.type != dbrake_switch && brakes.electrodynamic.type != dbrake_none && brakes.cylinderPressure > 2.0 && trainType != train_type::emu) // yB radzi nie sprawdzać ciśnienia w przewodzie + // hunter-301211: dla EN57 silnikow nie odlaczamy + { + brakes.electrodynamic.on = true; // uruchamianie hamulca ED albo odlaczanie silnikow + if (brakes.electrodynamic.type == dbrake_automatic && abs(Im) > 60) // nie napelniaj wiecej, jak na EP09 + dp = 0.0; + } + if (brake + dp < PressLimit) + { + brake = brake + dp; + IBP = true; + } + else + { + IBP = false; + brake = PressLimit; + } + return IBP; +} + +// ************************************************************************************************* +// Q: 20160711 +// zmniejszenie ciśnienia hamowania +// ************************************************************************************************* +bool physics::Vehicle::DecBrakePress(double &brake, double PressLimit, double dp) +{ + bool DBP; + + if (brake - dp > PressLimit) + { + brake = brake - dp; + DBP = true; + } + else + { + DBP = false; + brake = PressLimit; + } + // if ((DynamicBrakeType != dbrake_switch) && ((BrakePress < 0.1) && (PipePress > 0.45 + // /*(LowPipePress+0.06)*/ ))) + if (brakes.electrodynamic.type != dbrake_switch && brakes.cylinderPressure < 0.1) // yB radzi nie sprawdzać ciśnienia w przewodzie + brakes.electrodynamic.on = false; // wylaczanie hamulca ED i/albo zalaczanie silnikow + + return DBP; +} + +// ************************************************************************************************* +// Q: 20160711 +// przełączenie nastawy hamulca O/P/T +// ************************************************************************************************* +bool physics::Vehicle::BrakeDelaySwitch(int BDS) +{ + bool rBDS; + if (brakes.distributor->SetBDF(BDS)) + { + brakes.delaySetting = BDS; + rBDS = true; + brakes.distributor->SetBrakeStatus(brakes.distributor->GetBrakeStatus() & ~64); + // kopowanie nastawy hamulca do kolejnego czlonu - do przemyślenia + if (CabActive != 0) + SendCtrlToNext(VehicleCommand::brakeDelay, brakes.delaySetting, CabActive); + } + else + rBDS = false; + + return rBDS; +} + +// ************************************************************************************************* +// Q: 20160712 +// zwiększenie przełożenia hamulca +// ************************************************************************************************* +bool physics::Vehicle::IncBrakeMult(void) +{ + bool IBM; + + if (brakes.loadSetting > 0 && brakes.config.maxPressureMass < 2 && brakes.loadSetting < 3) + { + if (brakes.config.maxCylinderPressure[2] > 0 && brakes.loadSetting == 1) + brakes.loadSetting = 2; + else + brakes.loadSetting = 3; + IBM = true; + if (brakes.config.cylinders.leverRatio[2] > 0) + brakes.config.cylinders.leverRatio[0] = brakes.config.cylinders.leverRatio[2]; + } + else + IBM = false; + + return IBM; +} + +// ************************************************************************************************* +// Q: 20160712 +// zmniejszenie przełożenia hamulca +// ************************************************************************************************* +bool physics::Vehicle::DecBrakeMult(void) +{ + bool DBM; + if (brakes.loadSetting > 1 && brakes.config.maxPressureMass < 2) + { + if (brakes.config.maxCylinderPressure[2] > 0 && brakes.loadSetting == 3) + brakes.loadSetting = 2; + else + brakes.loadSetting = 1; + DBM = true; + if (brakes.config.cylinders.leverRatio[1] > 0) + brakes.config.cylinders.leverRatio[0] = brakes.config.cylinders.leverRatio[1]; + } + else + DBM = false; + + return DBM; +} + +// ************************************************************************************************* +// Q: 20160712 +// zaktualizowanie ciśnienia w hamulcach +// ************************************************************************************************* +void physics::Vehicle::UpdateBrakePressure(double dt) +{ + // const double LBDelay = 5.0; // stala czasowa hamulca + // double Rate, Speed, dp, sm; + + brakes.independentValveFlow = 0; + brakes.brakeFlow = 0; + + brakes.distributor->ForceLeak(dt * air.config.leakRate * 0.25); // fake air leaks from brake system reservoirs + + auto const brakepress{brakes.cylinderPressure}; + brakes.cylinderPressure = brakes.distributor->GetBCP(); + if (dt > 0.0) + { + // averaged over about a second: the valves move the cylinder in pulses, quicker than that within a single step + auto const rate{std::abs(brakes.cylinderPressure - brakepress) / dt}; + brakes.cylinderPressureRate += (rate - brakes.cylinderPressureRate) * std::min(1.0, dt / 1.0); + } + // BrakePress:=(Hamulec as TEst4).ImplsRes.pa; + brakes.reservoirAir = brakes.distributor->GetBRP(); +} + +// ************************************************************************************************* +// Q: 20160712 +// Obliczanie pracy sprężarki +// ************************************************************************************************* +void physics::Vehicle::CompressorCheck(double dt) +{ + auto &compressor{air.compressor}; + if (false == compressor.IsFitted()) + { + compressor.Allow(false); + return; + } + compressor.SelectCab(CabActive); + + // EmergencyValve + brakes.emergencyValve.open = air.MainReservoirPressure() > (brakes.emergencyValve.open ? brakes.emergencyValve.offPressure : brakes.emergencyValve.onPressure); + if (brakes.emergencyValve.open) + { + auto dV = static_cast(PF(0, air.MainReservoirPressure(), brakes.emergencyValve.area) * dt); + air.AddAir(-dV); + } + + CompressorInputs inputs; + inputs.converterAllowed = converter.IsAllowed(); + inputs.mainCircuitPowered = MainCircuitPowered(); + inputs.lowVoltage110v = lowVoltage.Is110vAvailable(); + // for these multi-unit engines compressors turn off whenever any of them was affected by the governor + // NOTE: this is crude implementation, limited only to adjacent vehicles + auto const governorlocked = [this](VehicleEnd const End) { + auto const &coupler{Couplers[End]}; + return coupler.Connected != nullptr && coupler.CouplingFlag.HasAll(Coupling::permanent) && coupler.Connected->air.compressor.IsGovernorLocked(); + }; + inputs.coupledGovernorLock = governorlocked(VehicleEnd::rear) || governorlocked(VehicleEnd::front); + inputs.switchingDelayPassed = LastSwitchingTime > CtrlDelay; + inputs.engineRpmRatio = EngineRPMRatio(); + + auto const step{air.Update(inputs, dt)}; + if (step.switched) + { + if (compressor.IsRunning()) + { + // jeśli została załączona to trzeba ograniczyć ponowne włączenie + LastSwitchingTime = 0; + } + Timer::subsystem.switching.note(compressor.IsRunning() ? Timer::switching_counter::compressor_on : Timer::switching_counter::compressor_off, this, &TypeName, &Name); + } + if (step.vented) + { + SetFlag(soundFlag, sound::relay | sound::loud); + } + // a compressor not driven by the engine doesn't draw power (some 5 A) from the high- or low voltage circuit yet +} + +// ************************************************************************************************* +// Q: 20160712 +// aktualizacja ciśnienia w przewodzie głównym +// ************************************************************************************************* +void physics::Vehicle::UpdatePipePressure(double dt) +{ + if (brakePipe.Pressure() > 1.0) + { + brakePipe.reservoir->Flow(-brakePipe.Pressure()*air.config.leakRate * dt); + brakePipe.reservoir->Act(); + } + + // double dV; + // physics::Vehicle *c; // physics::Vehicle + double temp; + // int b; + + brakePipe.SetPressure(brakePipe.reservoir->P()); + // PPP:=PipePress; + + brakes.driverValveFlow = 0; + + if (brakes.config.handlePositions > 1) + { + + UpdateLocalBrakeValve(dt); + UpdateMainValve(dt); + } + + UpdateEmergencyValve(dt); + + // 0.2*Spg + brakePipe.reservoir->Flow(-brakes.driverValveFlow); + brakePipe.reservoir->Flow(-brakePipe.Pressure() * 0.001 * dt); + // if Heating then + // Pipe.Flow(PF(PipePress, 0, d2A(7)) * dt); + // if ConverterFlag then + // Pipe.Flow(PF(PipePress, 0, d2A(12)) * dt); + brakes.driverValveFlow = brakes.driverValveFlow / (Dim.L * brakes.config.pipeSection * 20); + + brakes.controlReservoirPressure = brakes.distributor->GetVRP(); // ciśnienie komory wstępnej rozdzielacza + + // if (Hamulec is typeid(TWest)) return 0; + + UpdateDistributorSettings(); + + if ((brakes.config.driverValveType == TBrakeHandle::FVel6 || brakes.config.driverValveType == TBrakeHandle::FVE408) && cabOccupied != 0) + { + UpdateEPBrake(); + } + else if (brakes.config.driverValveType == TBrakeHandle::St113 && cabOccupied != 0 && std::abs(EpForce) > 0.001 && !EPBrakeControlPowered()) + { + // the EP brake switched on with the button drops out with the control's supply + SwitchEPBrake(0); + } + + brakePipe.reservoir->Act(); + brakePipe.SetPressure(brakePipe.reservoir->P()); + if ((brakes.distributor->GetBrakeStatus() & b_dmg) == b_dmg) // jesli hamulec wyłączony + temp = 0.0; // odetnij + else + temp = 1.0; // połącz + brakePipe.reservoir->Flow(temp * brakes.distributor->GetPF(temp * brakePipe.Pressure(), dt, Vel)); + // the air the brake hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + brakePipe.SetCouplersPending(true); + + if (brakes.config.antiSlipType == 128) + brakes.distributor->ASB(int(slippingWheels && Vel > 1) * (1 + 2 * int(nrot_eps < -0.01))); + + brakes.pipeFlow = 0; + + // yB: jednokrokowe liczenie tego wszystkiego + brakePipe.reservoir->Act(); + brakePipe.SetPressure(brakePipe.reservoir->P()); + + brakes.driverValveFlow = brakes.driverValveFlow / (100.0 * dt); // normalizacja po czasie do syczenia; + + if (brakePipe.Pressure() < -1.0) + { + brakePipe.SetPressure(-1.0); + brakePipe.reservoir->CreatePress(-1.0); + brakePipe.reservoir->Act(); + } + + air.ClampEmpty(); +} + +// the flow of the local brake valve, by the handle, the TRAXX's timed one, the integrated controller or the parking +void physics::Vehicle::UpdateLocalBrakeValve(double dt) +{ + // the local brake of a vehicle prepared for hauling (PulleeMode) is held released, whatever asks for it + if (EngineType != TEngineType::ElectricInductionMotor) + { + double lbpa = brakes.config.independentTraxx ? eim_localbrake : brakes.IndependentPosition(); + if (EIMCtrlType > 0 && uniCtrlIntegratedLocalBrakeCtrl) + { + lbpa = std::max(0.0, -eimicReal); + } + if (SpeedCtrlUnit.Parking) + { + lbpa = std::max(lbpa, brakes.holding.deceleration); + } + brakes.independentValveFlow = brakes.independentValve->GetPF(pulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); + } + else + { + // in EIM stock the pneumatic local brake is normally driven only by the MED algorithm + // (LocalBrakePosAEIM). When SplitEDPneumaticBrake is active the dedicated LocalBrake + // lever should apply pneumatic pressure on the locomotive directly, bypassing MED. + // LocHandleTimeTraxx also bypasses MED, but has 3 positions (brake-hold-unbrake). + double lbpa; + if (brakes.config.independentTraxx) + { + lbpa = eim_localbrake; + } + else if (brakes.electrodynamic.splitFromPneumatic) // When LocHandleTimeTraxx and SplitEDPneumaticBrake are both active, lbpa is taken from LocHandleTimeTraxx, which is the desired behavior. + { + lbpa = brakes.IndependentPosition(); + } + else + { + lbpa = 0.0; + } + brakes.independentValveFlow = brakes.independentValve->GetPF(pulleeMode ? 0.0 : std::max(lbpa, brakes.IndependentPositionEim()), brakes.distributor->GetBCP(), mainPipe.Pressure(), dt, 0); + } +} + +// the lock of the brake pipe and the flow of the driver's handle, from the main reservoir or into the air +void physics::Vehicle::UpdateMainValve(double dt) +{ + auto const temp{MainValveSupply()}; + brakes.driverValve->SetReductor(brakes.HandleCapPosition()); + + if (pulleeMode) + { + // the driver's valve of a vehicle prepared for hauling is cut out, whatever its handle shows + brakes.driverValveFlow = 0; + } + else if ((brakes.config.availableOperatingModes & bom_PS) == 0 || (cabOccupied != 0 && brakes.operatingMode != bom_PS)) + { + + if (brakes.operatingMode < bom_EP || brakes.driverValve->GetPos(bh_EB) - 0.5 < brakes.HandlePositionReal() || (brakes.config.driverValveType != TBrakeHandle::MHZ_EN57 && brakes.config.driverValveType != TBrakeHandle::MHZ_K8P)) + { + brakes.driverValveFlow = brakes.driverValve->GetPF(MainValveHandlePosition(), brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); + } + else + { + brakes.driverValveFlow = brakes.driverValve->GetPF(0, brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); + } + } + else if (brakes.HandlePosition() == brakes.driverValve->GetPos(bh_EB)) + { + brakes.driverValveFlow = brakes.driverValve->GetPF(brakes.HandlePositionReal(), brakePipe.Pressure(), temp, dt, brakes.equivalentPipePressure); + } + + if (brakes.driverValveFlow < 0) // && (PipePressureVal > 0.01) //50 + { + if (air.MainReservoirPressure() > mainPipe.Pressure()) + { + air.AddAir(brakes.driverValveFlow / 1500.0); + mainPipe.reservoir->Flow(brakes.driverValveFlow / 3.0); + } + else + mainPipe.reservoir->Flow(brakes.driverValveFlow); + } +} + +// the pressure the driver's handle is fed from: the main pipe's, or the brake pipe's own with the pipe locked +double physics::Vehicle::MainValveSupply() +{ + brakes.pipeLock.locked = brakePipe.Pressure() < (brakes.pipeLock.locked ? brakes.pipeLock.offPressure : brakes.pipeLock.onPressure); + bool lock_new = (brakes.pipeLock.locked && !brakes.pipeLock.unlockPressed && brakes.HandlePositionReal() > brakes.pipeLock.unlockHandlePosition) || (brakes.config.emergencyCutsOffDriverValve && brakes.emergencyValve.flow > 0); // new simple codition based on .fiz + bool lock_old = brakes.config.driverValveType == TBrakeHandle::FV4a // old complex condition based on assumptions + && brakePipe.Pressure() < 2.75 && (brakes.distributor->GetStatus() & b_rls) == 0 && brakes.config.subsystem == TBrakeSubSystem::ss_LSt && trainType != train_type::emu && !brakes.pipeLock.unlockPressed; + + if (lock_old || lock_new) + { + return brakePipe.Pressure() + 0.00001; + } + return mainPipe.Pressure(); +} + +// the position the driver's handle works at: its own, or the one the speed control's brake intervention sets +double physics::Vehicle::MainValveHandlePosition() const +{ + double pos = brakes.HandlePositionReal(); + if (SpeedCtrlUnit.IsActive && SpeedCtrlUnit.BrakeIntervention && !SpeedCtrlUnit.Standby && brakes.HandlePosition() != brakes.driverValve->GetPos(bh_EB)) + { + pos = brakes.driverValve->GetPos(bh_NP); + if (SpeedCtrlUnit.BrakeInterventionBraking) + pos = brakes.driverValve->GetPos(bh_FB); + if (SpeedCtrlUnit.BrakeInterventionUnbraking) + pos = brakes.driverValve->GetPos(bh_RP); + } + return pos; +} + +void physics::Vehicle::UpdateEmergencyValve(double dt) +{ + // ulepszony hamulec bezp. + brakes.emergencyValve.flow = 0.0; + + + // EngDmgFlag 32 (load destroyed) used to trigger this too; dropped, it has nothing to do with + // the emergency brake (a broken coupler sets AlarmChainFlag instead). the Elf's emergency brake position + // vents the pipe only from the vehicle driven from, whatever the controllers of the others show. + // a vehicle prepared for hauling (PulleeMode) vents it for nothing of its own, only for the alarm chain, + // which a train parting sets too + auto const ownemergency{radioStopFlag || (eimCtrlEmergency && brakes.IndependentPosition() >= 1.0) || (IsMainCtrlEmergencyPos() && IsCabMaster()) || SecuritySystem.is_braking() || + (brakes.spring.driveEmergencySpeed >= 0 && Vel > brakes.spring.driveEmergencySpeed && brakes.spring.isActive) || + (0 == CabActive && (InactiveCabFlag & activation::emergencybrake) != 0)}; + if (brakes.alarmChain || (ownemergency && false == pulleeMode)) + { + brakes.emergencyValve.flow = PF(0, brakePipe.Pressure(), 0.15) * dt; + } + brakes.driverValveFlow += brakes.emergencyValve.flow; +} + +// what the distributor valve gets of the local brake and the load, by its kind +void physics::Vehicle::UpdateDistributorSettings() +{ + switch (brakes.config.distributorType) + { + + case TBrakeValve::K: + case TBrakeValve::W: + { + + if (brakes.config.independentValveType != TBrakeHandle::NoHandle) + { + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); + + //(Hamulec as TWest).SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); + } + if (brakes.config.maxPressureMass < 2) + //(Hamulec as TWest).PLC(MaxBrakePress[LoadFlag]) + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); + else + //(Hamulec as TWest).PLC(TotalMass); + brakes.distributor->PLC(totalMass - mred); + break; + } + + case TBrakeValve::LSt: + case TBrakeValve::EStED: + { + + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); + auto const et41or42 = [](train_type const Type) { return Type == train_type::et41 || Type == train_type::et42; }; + for (auto const &couplerentry : Couplers) + // nie podoba mi się to rozwiązanie, chyba trzeba + // dodać jakiś wpis do fizyki na to + if (et41or42(trainType) && couplerentry.Connected != nullptr && et41or42(couplerentry.Connected->trainType) && couplerentry.CouplingFlag.HasAll(Coupling::control | Coupling::mainHose)) + brakes.independentCylinderPressure = std::max(couplerentry.Connected->brakes.independentValve->GetCP(), brakes.independentCylinderPressure); + + // if ((DynamicBrakeFlag) && (EngineType == ElectricInductionMotor)) + //{ + // //if (Vel > 10) + // // LocBrakePress = 0; + // //else if (Vel > 5) + // // LocBrakePress = (10 - Vel) / 5 * LocBrakePress; + // } + + //(Hamulec as TLSt).SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); + if (brakes.config.distributorType == TBrakeValve::EStED) + { + if (brakes.config.maxPressureMass < 2) + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); + else + brakes.distributor->PLC(totalMass - mred); + } + break; + } + + case TBrakeValve::CV1_L_TR: + { + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); + //(Hamulec as TCV1L_TR).SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); + break; + } + + case TBrakeValve::EP2: + case TBrakeValve::EP1: + { + brakes.distributor->PLC(totalMass - mred); + break; + } + case TBrakeValve::ESt3AL2: + case TBrakeValve::NESt3: + case TBrakeValve::ESt4: + case TBrakeValve::ESt3: + { + if (brakes.config.maxPressureMass < 2) + //(Hamulec as TNESt3).PLC(MaxBrakePress[LoadFlag]) + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); + else + //(Hamulec as TNESt3).PLC(TotalMass); + brakes.distributor->PLC(totalMass - mred); + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); + //(Hamulec as TNESt3).SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); + break; + } + case TBrakeValve::KE: + { + brakes.independentCylinderPressure = brakes.independentValve->GetCP(); + //(Hamulec as TKE).SetLBP(LocBrakePress); + brakes.distributor->SetLBP(brakes.independentCylinderPressure); + if (brakes.config.maxPressureMass < 2) + //(Hamulec as TKE).PLC(MaxBrakePress[LoadFlag]) + brakes.distributor->PLC(brakes.config.maxCylinderPressure[brakes.loadSetting]); + else + //(Hamulec as TKE).PLC(TotalMass); + brakes.distributor->PLC(totalMass - mred); + break; + } + default: + { + // unsupported brake valve type, we should never land here + // ErrorLog( "Unsupported brake valve type (" + std::to_string( BrakeValve ) + ") in " + TypeName ); + // ::PostQuitMessage( 0 ); + break; + } + } // switch +} + +// the ep brake of the FVel6 and FVE408 handles, passed along the unit +void physics::Vehicle::UpdateEPBrake() +{ + if (EPBrakeControlPowered()) // tu powinien byc jeszcze bezpiecznik EP i baterie - + // temp = (Handle as TFVel6).GetCP + EpForce = brakes.driverValve->GetEP(); + else + EpForce = 0.0; + + brakes.electrodynamic.emuWorking = EpForce > 0.001 ? lowVoltage.Is110vAvailable() : true; + + double temp1 = EpForce; + if (brakes.emuDynamic.epMaxSpeed > 0.001 && Vel > brakes.emuDynamic.epMaxSpeed && brakes.electrodynamic.emuWorking) + temp1 = 0; + if (brakes.emuDynamic.epMinCurrent > 0.001 && abs(Im) > brakes.emuDynamic.epMinCurrent && brakes.electrodynamic.emuWorking) + temp1 = 0; + brakes.distributor->SetEPS(temp1); + TUHEX_StageActual = static_cast(EpForce); + TUHEX_Active = TUHEX_StageActual > 0; + // Ra 2014-11: na tym się wysypuje, ale nie wiem, w jakich warunkach + SendCtrlToNext(VehicleCommand::brake, EpForce, CabActive); +} + +// ************************************************************************************************* +// Q: 20160713 +// Aktualizacja ciśnienia w przewodzie zasilającym +// ************************************************************************************************* +void physics::Vehicle::UpdateScndPipePressure(double dt) +{ + if (mainPipe.Pressure() > 1.0) + { + mainPipe.reservoir->Flow(-mainPipe.Pressure()*air.config.leakRate * dt); + mainPipe.reservoir->Act(); + } + + const double Spz = 0.5067; + + UpdateSpringBrake(dt); + + mainPipe.reservoir->Flow(brakes.distributor->GetHPFlow(mainPipe.Pressure(), dt)); + // NOTE: condition disabled to allow the air flow from the main hose to the main tank as well + if (/* ( ( Compressor > ScndPipePress ) && ( */ air.config.mainReservoirVolume > 0.0 /* ) ) || ( trainType == train_type::emu ) || ( trainType == train_type::dmu ) */) + { + double const dV = PF(air.MainReservoirPressure(), mainPipe.Pressure(), Spz) * dt; + air.AddAir(dV / 1000.0); + mainPipe.reservoir->Flow(-dV); + } + // the air the main reservoir hoses carry to and from the neighbours comes once all vehicles have stepped, UpdatePipeCouplers() + mainPipe.SetCouplersPending(true); + mainPipe.reservoir->Act(); + mainPipe.SetPressure(mainPipe.reservoir->P()); + + if (mainPipe.Pressure() < -1) + { + mainPipe.SetPressure(-1); + mainPipe.reservoir->CreatePress(-1); + mainPipe.reservoir->Act(); + } +} + +// ************************************************************************************************* +// yB: 20190906 +// Aktualizacja ciśnienia w hamulcu sprezynowym +// ************************************************************************************************* +void physics::Vehicle::UpdateSpringBrake(double /*dt*/) +{ + double BP = brakes.spring.pneumaticConnection ? brakes.cylinderPressure : 0; + double MSP = brakes.spring.shutOff ? 0 : brakes.spring.maxSetPressure; + if (!brakes.spring.activate) + { + double desired_press = std::min(std::max(MSP, BP), mainPipe.reservoir->P()); + double dv = PF(desired_press, brakes.spring.pressure, brakes.spring.valveOffArea); + brakes.spring.cylinder->Flow(-dv); + mainPipe.reservoir->Flow(std::max(dv, 0.0)); + } + else + { + double dv = PF(BP, brakes.spring.pressure, brakes.spring.valveOnArea); + brakes.spring.cylinder->Flow(-dv); + } + if (brakes.spring.pressure > brakes.spring.resetPressure) + brakes.spring.isReady = true; + + brakes.spring.isActive = brakes.spring.pressure < (brakes.spring.isActive ? brakes.spring.pressureOff : brakes.spring.pressureOn); + + brakes.spring.release = false; + brakes.spring.cylinder->Act(); + brakes.spring.pressure = brakes.spring.cylinder->P(); +} +namespace +{ + +// whether the air flowing to a coupled vehicle along a pipe wakes its physics: any flow did, but a vehicle standing next to one +// whose physics is on gets a trickle of it all the time, as their pressures settle, and each wake kept it on for 5 s. with +// Global.physics_pipewake only a flow which leaves its pressure, with what has flown in while it slept, that much away from the +// pressure of the vehicle the air comes from, or which has changed it by that much since it fell asleep: a pressure followed in +// small steps would never reach the valves of a vehicle asleep otherwise +bool pipe_wakes(double const Flow, double const Pressure, TReservoir const &Reservoir) +{ + if (Flow * Flow <= 0.00000000000001) + return false; + return (Global.physics_pipewake <= 0.f) + || (std::abs(Pressure - Reservoir.P_pending()) > Global.physics_pipewake) + || (std::abs(Reservoir.P_pending() - Reservoir.P_applied()) > Global.physics_pipewake); +} + +// the pressure in the pipe of a coupled vehicle the flow to it goes by. the pressure the vehicle keeps is the one of its last step: +// with Global.physics_pipewake one asleep can take air for a long time without waking, and the flow, going by that pressure, would +// carry on past the pressure of the vehicle it comes from. so of one asleep, the pressure with what has flown in since +double neighbour_pipe_pressure(physics::Vehicle const &Neighbour, double const Pressure, TReservoir const &Reservoir) +{ + if ((Global.physics_pipewake <= 0.f) || Neighbour.PhysicActivation()) + return Pressure; + return Reservoir.P_pending(); +} + +} // namespace + +// ************************************************************************************************* +// Q: 20160715 +// oblicza i zwraca przepływ powietrza pomiędzy pojazdami +// ************************************************************************************************* +double physics::Vehicle::GetDVc(double dt) +{ + // physics::Vehicle *c; + physics::Vehicle *c; + double dv1; + double dv2; // , dV; + + dv1 = 0; + dv2 = 0; + // sprzeg 1 + if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) + { //*0.85 + c = Couplers[0].Connected; // skrot //0.08 //e/D * L/D = e/D^2 * L + dv1 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.config.pipeSection / (1.0 + 0.015 / brakes.config.pipeSection * Dim.L)); + c->brakePipe.reservoir->Flow(-dv1); + if (pipe_wakes(dv1, brakePipe.Pressure(), *c->brakePipe.reservoir)) + c->switch_physics(true, wake_cause::mainpipe); + } + // sprzeg 2 + if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(brakePipe.Pressure(), neighbour_pipe_pressure(*c, c->brakePipe.Pressure(), *c->brakePipe.reservoir), brakes.config.pipeSection / (1.0 + 0.015 / brakes.config.pipeSection * Dim.L)); + c->brakePipe.reservoir->Flow(-dv2); + if (pipe_wakes(dv2, brakePipe.Pressure(), *c->brakePipe.reservoir)) + c->switch_physics(true, wake_cause::mainpipe); + } + // if ((Couplers[1].Connected != NULL) && (Couplers[0].Connected != NULL)) + // if ((Couplers[0].CouplingFlag.HasAll(Coupling::brakeHose)) && + // (Couplers[1].CouplingFlag.HasAll(Coupling::brakeHose))) + // { + // dV = 0.05 * dt * PF(Couplers[0].Connected->PipePress, Couplers[1].Connected->PipePress, + // (Spg * 0.85) / (1 + 0.03 * Dim.L)) * + // 0; // ktoś mi powie jaki jest sens tego bloku jeśli przepływ mnożony przez zero? + // Couplers[0].Connected->Pipe->Flow(+dV); + // Couplers[1].Connected->Pipe->Flow(-dV); + // } + // suma + return dv2 + dv1; +} + +// ************************************************************************************************* +// the air the main reservoir hoses carry between the vehicle's pipe and the neighbours' in dt: the neighbours' +// share is sent to them, the vehicle's own returned +// ************************************************************************************************* +double physics::Vehicle::GetScndDVc(double dt) +{ + const double Spz = 0.5067; + physics::Vehicle *c; + double dv1 = 0; + double dv2 = 0; + + // sprzeg 1 + if (Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) + { + c = Couplers[0].Connected; // skrot + dv1 = 0.5 * dt * PF(mainPipe.Pressure(), neighbour_pipe_pressure(*c, c->mainPipe.Pressure(), *c->mainPipe.reservoir), Spz * 0.75); + c->mainPipe.reservoir->Flow(-dv1); + if (pipe_wakes(dv1, mainPipe.Pressure(), *c->mainPipe.reservoir)) + c->switch_physics(true, wake_cause::scndpipe); + } + // sprzeg 2 + if (Couplers[1].Connected != nullptr && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) + { + c = Couplers[1].Connected; // skrot + dv2 = 0.5 * dt * PF(mainPipe.Pressure(), neighbour_pipe_pressure(*c, c->mainPipe.Pressure(), *c->mainPipe.reservoir), Spz * 0.75); + c->mainPipe.reservoir->Flow(-dv2); + if (pipe_wakes(dv2, mainPipe.Pressure(), *c->mainPipe.reservoir)) + c->switch_physics(true, wake_cause::scndpipe); + } + if (Couplers[1].Connected != nullptr && Couplers[0].Connected != nullptr && Couplers[0].CouplingFlag.HasAll(Coupling::mainHose) && Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) + { + double const dV = 0.00025 * dt * PF(Couplers[0].Connected->mainPipe.Pressure(), Couplers[1].Connected->mainPipe.Pressure(), Spz * 0.25); + Couplers[0].Connected->mainPipe.reservoir->Flow(+dV); + Couplers[1].Connected->mainPipe.reservoir->Flow(-dV); + } + return dv1 + dv2; +} +namespace +{ + + +// a pipe along the train, whose air the hoses between the vehicles carry (physics::Vehicle::UpdatePipeCouplers()) +struct train_pipe +{ + physics::TrainPipe physics::Vehicle::*pipe; // the reservoir, the pressure and whether the exchange through the hoses is yet to come + CouplingSet hose; // the coupling of the pipe's hose + double (physics::Vehicle::*exchange)(double); // the air the hoses carry in a step, the neighbours' share sent to them + double (*area)(physics::Vehicle const &); // the cross-section of the hose, as the exchange takes it +}; + +// the brake pipe, GetDVc() +train_pipe const brake_pipe{&physics::Vehicle::brakePipe, + Coupling::brakeHose, + &physics::Vehicle::GetDVc, + [](physics::Vehicle const &Vehicle) { return Vehicle.brakes.config.pipeSection / (1.0 + 0.015 / Vehicle.brakes.config.pipeSection * Vehicle.Dim.L); }}; +// the main reservoir pipe, GetScndDVc() +train_pipe const main_reservoir_pipe{&physics::Vehicle::mainPipe, + Coupling::mainHose, + &physics::Vehicle::GetScndDVc, + [](physics::Vehicle const &) { return 0.5067 * 0.75; }}; + +// the number of sub-steps of dt the air exchange through the hoses of the vehicle's pipe needs: in one, the air a +// hose carries stays below what evens out the pipes on its ends +int hose_substeps(physics::Vehicle const &Vehicle, train_pipe const &trainPipe, double const dt) +{ + auto substeps{1}; + auto const area{trainPipe.area(Vehicle)}; + auto const capacity{(Vehicle.*trainPipe.pipe).reservoir->GetCap()}; + for (auto const &hose : Vehicle.Couplers) + { + if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(trainPipe.hose)) + { + continue; + } + auto const &other{*hose.Connected}; + auto const othercapacity{(other.*trainPipe.pipe).reservoir->GetCap()}; + // the flow per bar of the difference, at small differences, where it's the largest + auto const pressure{std::max((Vehicle.*trainPipe.pipe).Pressure(), (other.*trainPipe.pipe).Pressure())}; + auto const conductance{std::abs(PF(pressure, pressure - 0.01, area)) / 0.01}; + auto const equalising{capacity * othercapacity / (capacity + othercapacity)}; + substeps = std::max(substeps, static_cast(std::ceil(dt * conductance / equalising))); + } + return std::min(substeps, 10); +} + +// the vehicles of the list which stepped the pipe, each with the number of the train it is in: the ones joined by the hoses +// of the pipe, directly, numbered in the order of their first vehicle in the list. a vehicle which didn't step the pipe +// (its physics sleeps) takes the air sent to it without passing it on, so it ends a train +std::vector hose_trains(std::vector const &Vehicles, train_pipe const &trainPipe) +{ + auto constexpr none{std::numeric_limits::max()}; + std::vector trains(Vehicles.size(), none); + // the vehicles by their address, for finding the neighbours in the list + std::vector> byaddress; + byaddress.reserve(Vehicles.size()); + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + if ((Vehicles[index]->*trainPipe.pipe).CouplersPending()) + { + byaddress.emplace_back(Vehicles[index], index); + } + } + std::ranges::sort(byaddress); + auto const find = [&byaddress](physics::Vehicle const *Vehicle) { + auto const found{std::ranges::lower_bound(byaddress, Vehicle, std::less<>{}, &std::pair::first)}; + return (found != byaddress.end() && found->first == Vehicle) ? found->second : none; + }; + std::size_t count{0}; + std::vector stack; + for (std::size_t first = 0; first < Vehicles.size(); ++first) + { + if (false == (Vehicles[first]->*trainPipe.pipe).CouplersPending() || trains[first] != none) + { + continue; + } + trains[first] = count; + stack.assign(1, first); + while (false == stack.empty()) + { + auto const &vehicle{*Vehicles[stack.back()]}; + stack.pop_back(); + for (auto const &hose : vehicle.Couplers) + { + if (hose.Connected == nullptr || false == hose.CouplingFlag.HasAll(trainPipe.hose)) + { + continue; + } + if (auto const other{find(hose.Connected)}; other != none && trains[other] == none) + { + trains[other] = count; + stack.push_back(other); + } + } + } + ++count; + } + return trains; +} + +// the air exchange through the hoses of the pipe, for the vehicles which stepped it since the last call, in the order +// they stepped: each train in as many sub-steps of dt as its vehicle needing the most of them takes, each going through +// its vehicles one after another, as the step of the vehicles does. the air of a train stays in it, so a train comes out +// the same whichever other vehicles are exchanged in the same call: all of them, or the ones of a group of +// vehicle_table::update_steps_parallel() +void exchange_through_hoses(std::vector const &Vehicles, train_pipe const &trainPipe, double const dt) +{ + auto const trains{hose_trains(Vehicles, trainPipe)}; + std::vector substeps; + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending()) + { + continue; + } + if (substeps.size() <= trains[index]) + { + substeps.resize(trains[index] + 1, 1); + } + substeps[trains[index]] = std::max(substeps[trains[index]], hose_substeps(*Vehicles[index], trainPipe, dt)); + } + for (std::size_t train = 0; train < substeps.size(); ++train) + { + auto const substep{dt / substeps[train]}; + for (auto i = 0; i < substeps[train]; ++i) + { + for (std::size_t index = 0; index < Vehicles.size(); ++index) + { + if (false == (Vehicles[index]->*trainPipe.pipe).CouplersPending() || trains[index] != train) + { + continue; + } + auto *vehicle{Vehicles[index]}; + auto &pipe{*(vehicle->*trainPipe.pipe).reservoir}; + pipe.Act(); // what the neighbours have sent in the meantime + (vehicle->*trainPipe.pipe).SetPressure(pipe.P()); + pipe.Flow((vehicle->*trainPipe.exchange)(substep)); + pipe.Act(); + (vehicle->*trainPipe.pipe).SetPressure(pipe.P()); + } + } + } + for (auto *vehicle : Vehicles) + { + (vehicle->*trainPipe.pipe).SetCouplersPending(false); + } +} + +} // namespace + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the brake hoses of the vehicle needs. taken in a single +// step of 0.01 s, the hose between two 14 m freight wagons carries twice the air which evens out their pipes, the +// pipes overshoot each other in turns and the distributors see the pressure up to 0.28 bar off what's in the pipe +// (eu07/maszyna#368) +// ************************************************************************************************* +int physics::Vehicle::PipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, brake_pipe, dt); +} + +// ************************************************************************************************* +// the number of sub-steps of dt the air exchange through the main reservoir hoses of the vehicle needs. taken in a +// single step of 0.01 s, the hose carries about 1.5 times the air which evens out the pipes on its ends; along with +// the vehicles' own main reservoirs feeding the pipe in the same step, the pipes of the middle vehicles of a +// multiple unit or of locomotives in multiple traction kept jumping 0.8 bar to and fro between the steps +// ************************************************************************************************* +int physics::Vehicle::ScndPipeCouplersSubsteps(double const dt) const +{ + return hose_substeps(*this, main_reservoir_pipe, dt); +} + +// ************************************************************************************************* +// the air exchange through the brake and the main reservoir hoses of the vehicles which stepped their pipes +// (UpdatePipePressure(), UpdateScndPipePressure()) since the last call, each pipe in its own sub-steps +// ************************************************************************************************* +void physics::Vehicle::UpdatePipeCouplers(std::vector const &Vehicles, double const dt) +{ + exchange_through_hoses(Vehicles, brake_pipe, dt); + exchange_through_hoses(Vehicles, main_reservoir_pipe, dt); +} + +bool physics::Vehicle::UpdateStopBrakeRelease(double const Demand, double const Dt) +{ + if (Demand <= 0.0) + { + brakes.holding.releaseTimer = 0.0; + return false; + } + // the step the demand rises above 0 is time 0 of it, so without the delay the brake lets go at once, as it always did + auto const released{brakes.holding.releaseTimer >= brakes.holding.releaseDelay}; + brakes.holding.releaseTimer += Dt; + return released; +} diff --git a/physics/components/securitysystem.cpp b/physics/components/securitysystem.cpp new file mode 100644 index 000000000..3605d6810 --- /dev/null +++ b/physics/components/securitysystem.cpp @@ -0,0 +1,298 @@ +/* +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 security system (vigilance, cab signalling, radio-stop) + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +void TSecuritySystem::set_enabled(bool e) +{ + if (vigilance_enabled || cabsignal_enabled || radiostop_enabled) + enabled = e; + if (CabDependent) + cabactive = 0; +} + +void TSecuritySystem::acknowledge_press() +{ + pressed = true; + + if (vigilance_timer > AwareDelay) + { + alert_timer = 0.0; + vigilance_timer = 0.0; + return; + } + vigilance_timer = 0.0; + + if (!separate_acknowledge && cabsignal_active && !cabsignal_lock) + { + cabsignal_active = false; + alert_timer = 0.0; + } +} + +void TSecuritySystem::acknowledge_release() +{ + pressed = false; + + if (press_timer > MaxHoldTime) + alert_timer = 0.0; + press_timer = 0.0; +} + +void TSecuritySystem::cabsignal_reset() +{ + if (cabsignal_active && !cabsignal_lock) + { + cabsignal_active = false; + alert_timer = 0.0; + } +} + +void TSecuritySystem::update(double dt, double vel, bool pwr, int cab) +{ + if (!enabled || !pwr || DebugModeFlag) + { + power = pwr; + cabsignal_active = false; + vigilance_timer = 0.0; + alert_timer = 0.0; + press_timer = 0.0; + return; + } + + bool just_powered_on = !power && pwr; + bool just_activated = CabDependent && cabactive != cab; + + /* enabling battery */ + if (cabsignal_enabled && (just_powered_on || just_activated)) + { + cabsignal_active = true; + alert_timer = SoundSignalDelay; + } + + power = pwr; + velocity = vel; + cabactive = cab; + + if (vigilance_suspended) + { + // the vigilance device is switched off: no time counts towards a new alarm, of the alerter or of the button held + // too long. an alarm already on, with the emergency braking it leads to, stays until it's acknowledged as usual + if (vigilance_timer <= AwareDelay) + vigilance_timer = 0.0; + if (press_timer <= MaxHoldTime) + press_timer = 0.0; + } + else + { + if (vigilance_enabled && velocity > AwareMinSpeed) + vigilance_timer += dt; + + if (pressed && (!is_sifa || velocity > AwareMinSpeed)) + press_timer += dt; + } + + if (vigilance_timer > AwareDelay || press_timer > MaxHoldTime || cabsignal_active) + alert_timer += dt; +} + +void TSecuritySystem::set_cabsignal() +{ + if (cabsignal_enabled && power) + cabsignal_active = true; +} + +bool TSecuritySystem::has_separate_acknowledge() const +{ + return separate_acknowledge; +} + +bool TSecuritySystem::is_blinking() const +{ + if (!power) + return false; + + return alert_timer > 0.0; +} + +bool TSecuritySystem::is_vigilance_blinking() const +{ + if (!power) + return false; + + return press_timer > MaxHoldTime || vigilance_timer > AwareDelay; +} + +bool TSecuritySystem::is_cabsignal_blinking() const +{ + if (!power) + return false; + + return cabsignal_active; +} + +bool TSecuritySystem::is_beeping() const +{ + if (!power) + return false; + + return alert_timer > SoundSignalDelay && (!separate_acknowledge || is_vigilance_blinking()); +} + +bool TSecuritySystem::is_cabsignal_beeping() const +{ + if (!power) + return false; + + return alert_timer > SoundSignalDelay && is_cabsignal_blinking(); +} + +bool TSecuritySystem::is_braking() const +{ + if (!power && enabled) + return true; + + return alert_timer > SoundSignalDelay + EmergencyBrakeDelay; +} + +bool TSecuritySystem::radiostop_available() const +{ + return radiostop_enabled; +} + +void TSecuritySystem::set_cabsignal_lock(bool v) +{ + cabsignal_lock = v; +} + +void TSecuritySystem::set_shunt_mode(bool const State) +{ + vigilance_suspended = State && AwareOffInShuntMode; +} + +bool TSecuritySystem::is_engine_blocked() const +{ + if (!is_sifa) + return false; + + return velocity < AwareMinSpeed && pressed; +} + +void TSecuritySystem::load(std::string const &line, double vmax) +{ + std::string awaresystem = extract_value("AwareSystem", line); + if (awaresystem.find("Active") != std::string::npos) + vigilance_enabled = true; + if (awaresystem.find("CabSignal") != std::string::npos) + cabsignal_enabled = true; + if (awaresystem.find("Sifa") != std::string::npos) + is_sifa = true; + if (awaresystem.find("SeparateAcknowledge") != std::string::npos) + separate_acknowledge = true; + + extract_value(AwareDelay, "AwareDelay", line, ""); + AwareMinSpeed = 0.1 * vmax; // domyślnie 10% Vmax + extract_value(AwareMinSpeed, "AwareMinSpeed", line, ""); + extract_value(SoundSignalDelay, "SoundSignalDelay", line, ""); + extract_value(EmergencyBrakeDelay, "EmergencyBrakeDelay", line, ""); + extract_value(MaxHoldTime, "MaxHoldTime", line, ""); + extract_value(radiostop_enabled, "RadioStop", line, ""); + extract_value(MagnetLocation, "MagnetLocation", line, ""); + extract_value(CabDependent, "CabDependent", line, ""); + extract_value(AwareOffInShuntMode, "AwareOffInShuntMode", line, ""); +} + +// ***************************************************************************** +// Q: 20160710 +// zbicie czuwaka / SHP +// ***************************************************************************** +// hunter-091012: rozbicie alarmow, dodanie testu czuwaka +void physics::Vehicle::SecuritySystemReset(void) // zbijanie czuwaka/SHP +{ + // reset all, used by AI + SecuritySystem.acknowledge_press(); + SecuritySystem.acknowledge_release(); + SecuritySystem.cabsignal_reset(); +} + +// ************************************************************************************************* +// Q: 20160711 +// sprawdzanie stanu CA/SHP +// ************************************************************************************************* +void physics::Vehicle::SecuritySystemCheck(double dt) +{ + bool isPower = lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable(); + // the shunt mode of the SM42 switches its vigilance device (CA) off, on the vehicles with AwareOffInShuntMode=Yes (eu07/maszyna#457) + SecuritySystem.set_shunt_mode(ShuntMode); + SecuritySystem.update(dt, Vel, isPower, CabActive); + + if (!lowVoltage.IsBatteryOn() || !radio || !radioFuse) + { // wyłączenie baterii deaktywuje sprzęt + RadiostopSwitch(false); + } +} + +// ************************************************************************************************* +// Q: 20160711 +// włączenie / wyłączenie hamowania awaryjnego +// ************************************************************************************************* +bool physics::Vehicle::RadiostopSwitch(bool Switch) +{ + bool EBS; + if (brakes.config.kind != TBrakeSystem::Individual && brakes.config.handlePositions > 0) + { + + if (true == Switch && false == radioStopFlag) + { + radioStopFlag = Switch; + EBS = true; + } + else + { + if (Switch == false && std::abs(travelSpeed) < 0.1) + { + // odblokowanie hamulca bezpieczenistwa tylko po zatrzymaniu + radioStopFlag = Switch; + EBS = true; + } + else + { + EBS = false; + } + } + } + else + { + // nie ma hamulca bezpieczenstwa gdy nie ma hamulca zesp. + EBS = false; + } + + return EBS; +} diff --git a/physics/components/setup.cpp b/physics/components/setup.cpp new file mode 100644 index 000000000..b6c3383c3 --- /dev/null +++ b/physics/components/setup.cpp @@ -0,0 +1,470 @@ +/* +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/. +*/ + +// setting the vehicle up after reading its definition: the checks, the brake valves, the handles and the pipes + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" + + +// ************************************************************************************************* +// Q: 20160717 +// ************************************************************************************************* + +bool physics::Vehicle::CheckLocomotiveParameters(bool ReadyFlag, int /*Dir*/) +{ + WriteLog("check locomotive parameters..."); + bool OK = true; + + autoRelayFlag = autoRelayType == 1; + + if (lowVoltage.config.nominalBatteryVoltage == 0.0) + { + lowVoltage.config.batteryStart = start_t::disabled; + } + + Sand = SandCapacity; + + // NOTE: for diesel-powered vehicles we automatically convert legacy "main" power source to more accurate "engine" + if (air.compressor.config.supply == CompressorSupply::mainCircuit && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) + { + air.compressor.config.supply = CompressorSupply::engine; + } + + // for these engine types secondary controller positions index MotorParam table + if ((EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric) && + scndCtrlPosNo > MotorParametersArraySize) + { + WriteLog("SCPN=" + std::to_string(scndCtrlPosNo) + " exceeds motor parameter table size, limited to " + std::to_string(MotorParametersArraySize)); + scndCtrlPosNo = MotorParametersArraySize; + } + + // WriteLog("aa = " + AxleArangement + " " + std::string( Pos("o", AxleArangement)) ); + + if (contains(AxleArangement, "o") && EngineType == TEngineType::ElectricSeriesMotor) + { + // test poprawnosci ilosci osi indywidualnie napedzanych + OK = RList[1].Bn * RList[1].Mn == nPoweredAxles; + // WriteLogSS("aa ok", BoolToYN(OK)); + } + + if (brakes.config.kind == TBrakeSystem::Individual && brakes.config.subsystem != TBrakeSubSystem::ss_None) + OK = false; //! + + if (brakes.config.valveVolume == 0 && brakes.config.maxCylinderPressure[3] > 0 && brakes.config.kind != TBrakeSystem::Individual) + { + brakes.config.valveVolume = brakes.config.maxCylinderPressure[3] / (5.0 - brakes.config.maxCylinderPressure[3]) * (brakes.config.cylinders.radius * brakes.config.cylinders.radius * brakes.config.cylinders.stroke * brakes.config.cylinders.count * M_PI) * 1000; + } + if (brakes.config.valveVolume == 0.0) + { + brakes.config.valveVolume = 0.01; + } + // WriteLog("BVV = " + FloatToStr(BrakeVVolume)); + + CreateBrakeValve(); + + CreateBrakeHandles(); + + CreateBrakePipes(); + + if (LightsPosNo > 0) + lightsPos = LightsDefPos; + + // set default wiper switch position + wiperSwitchPos = WiperDefaultPos; + + air.compressor.ResetListPosition(); + + // the genset of a dual-mode vehicle is a second source of the traction circuit of an induction motor vehicle + if (Genset.fitted() && (EngineType != TEngineType::ElectricInductionMotor || EnginePowerSource.SourceType != TPowerSource::CurrentCollector)) + { + WriteLog("GensetPower ignored: a genset works only with EngineType=ElectricInductionMotor and EnginePower=CurrentCollector"); + Genset = genset_device{}; + } + + // NOTE: legacy compatibility behaviour for vehicles without defined heating power source + if (EnginePowerSource.SourceType == TPowerSource::CurrentCollector && HeatingPowerSource.SourceType == TPowerSource::NotDefined) + { + HeatingPowerSource.SourceType = TPowerSource::Main; + } + if (HeatingPowerSource.SourceType == TPowerSource::NotDefined && trainHeating.config.power > 0) + { + HeatingPowerSource.SourceType = TPowerSource::PowerCable; + HeatingPowerSource.PowerType = TPowerType::ElectricPower; + } + + // checking ready flag + // to dac potem do init + if (ReadyFlag) // gotowy do drogi + { + SetReadyToDepart(); + } + else + { // zahamowany} + SetBraked(); + } + + actFlowSpeed = 0.0; + brakes.SetHandlePositionReal(brakes.HandlePosition()); + + if (brakes.config.independentValveType == TBrakeHandle::Knorr) + brakes.SetIndependentPosition(0.5); + + brakePipe.reservoir->CreatePress(brakePipe.Pressure()); + mainPipe.reservoir->CreatePress(mainPipe.Pressure()); + brakePipe.reservoir->Act(); + mainPipe.reservoir->Act(); + + brakes.equivalentPipePressure = brakePipe.Pressure(); + + brakes.driverValve->Init(brakePipe.Pressure()); + + ComputeConstans(); + + if (brakes.loadSetting > 0) + { + + if (loadAmount < maxLoad * 0.45) + { + IncBrakeMult(); + IncBrakeMult(); + DecBrakeMult(); // TODO: przeinesiono do physics.cpp + if (loadAmount < maxLoad * 0.35) + DecBrakeMult(); + } + else + { + IncBrakeMult(); // TODO: przeinesiono do physics.cpp + if (loadAmount >= maxLoad * 0.55) + IncBrakeMult(); + } + } + + // taki mini automat - powinno byc ladnie dobrze :) + brakes.delaySetting = bdelay_P; + if (TestFlag(brakes.config.availableDelays, bdelay_G) && !TestFlag(brakes.config.availableDelays, bdelay_R)) + brakes.delaySetting = bdelay_G; + if (TestFlag(brakes.config.availableDelays, bdelay_R) && !TestFlag(brakes.config.availableDelays, bdelay_G)) + brakes.delaySetting = bdelay_R; + /* + // disabled, as test mode is used in specific situations and not really a default + if (BrakeOpModes & bom_PS) + BrakeOpModeFlag = bom_PS; + else + */ + brakes.operatingMode = bom_PN; + + // yB: jesli pojazdy nie maja zadeklarowanych czasow, to wsadz z przepisow +-16,(6)% + std::array const DefBrakeTable{15, 4, 25, 25, 13, 3, 12, 2}; + + for (int b = 1; b < 4; b++) + { + if (brakes.config.delays[b] == 0) + brakes.config.delays[b] = DefBrakeTable[b]; + brakes.config.delays[b] = brakes.config.delays[b] * (2.5 + Random(0.0, 0.2)) / 3.0; + } + + brakes.distributor->Init(brakePipe.Pressure(), brakes.config.pipeHighPressure, brakes.config.pipeLowPressure, brakes.cylinderPressure, brakes.delaySetting); + /* + ScndPipePress = Compressor; + */ + // WriteLogSS("OK=", BoolTo10(OK)); + // WriteLog(""); + + if (EIMCtrlType == 3) + { + for (auto idx = 0; idx < MainCtrlPosNo; ++idx) + { + if (UniCtrlList[idx].MaxCtrlVal > 0.0) + { + UniCtrlNoPowerPos = std::max(0, idx - 1); + break; + } + } + } + + // security system + // by default place the magnet in the vehicle centre + if (SecuritySystem.MagnetLocation == 0) + { + SecuritySystem.MagnetLocation = Dim.L / 2 - 0.5; + } + SecuritySystem.MagnetLocation = safe_clamp(SecuritySystem.MagnetLocation, 0.0, Dim.L); + + return OK; +} + +// the distributor valve of the vehicle's kind +void physics::Vehicle::CreateBrakeValve() +{ + switch (brakes.config.distributorType) + { + case TBrakeValve::W: + case TBrakeValve::K: + { + WriteLog("XBT W, K"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); + else + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + break; + } + case TBrakeValve::KE: + { + WriteLog("XBT WKE"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetRM(brakes.config.rapidRatio); + if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); + else + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + break; + } + case TBrakeValve::NESt3: + case TBrakeValve::ESt3: + case TBrakeValve::ESt3AL2: + case TBrakeValve::ESt4: + { + WriteLog("XBT NESt3, ESt3, ESt3AL2, ESt4"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + static_cast(brakes.distributor.get())->SetSize(brakes.config.distributorSize, brakes.config.distributorParameters); + if (brakes.config.maxPressureMass < 2) // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); + else + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + break; + } + case TBrakeValve::LSt: + { + WriteLog("XBT LSt"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetRM(brakes.config.rapidRatio); + break; + } + case TBrakeValve::EStED: + { + WriteLog("XBT EStED"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetRM(brakes.config.rapidRatio); + if (brakes.config.maxPressureMass < 2) + { + // jesli przystawka wazaca + brakes.distributor->SetLP(0, brakes.config.maxCylinderPressure[3], 0); + } + else + { + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + } + break; + } + case TBrakeValve::EP2: + { + WriteLog("XBT EP2"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + break; + } + case TBrakeValve::EP1: + { + WriteLog("XBT EP1"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + brakes.distributor->SetLP(emptyMass, brakes.config.maxPressureMass, brakes.config.maxCylinderPressure[1]); + brakes.distributor->SetRM(brakes.config.rapidRatio); + break; + } + case TBrakeValve::CV1: + { + WriteLog("XBT CV1"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + break; + } + case TBrakeValve::CV1_L_TR: + { + WriteLog("XBT CV1_L_T"); + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + break; + } + default: + brakes.distributor = std::make_shared(brakes.config.maxCylinderPressure[3], brakes.config.cylinders.radius, brakes.config.cylinders.stroke, brakes.config.valveVolume, brakes.config.cylinders.count, brakes.config.availableDelays, brakes.config.method, nAxles, brakes.config.blocksPerAxle); + } + + brakes.distributor->SetASBP(brakes.config.maxCylinderPressure[4]); + brakes.distributor->SetRV(brakes.config.rapidSpeed); +} + +// the driver's handle and the local brake handle of the vehicle's kinds +void physics::Vehicle::CreateBrakeHandles() +{ + switch (brakes.config.driverValveType) + { + using enum TBrakeHandle; + case FV4a: + brakes.driverValve = std::make_shared(); + break; + case MHZ_EN57: + case MHZ_K8P: + brakes.driverValve = std::make_shared(); + break; + case FVel6: + brakes.driverValve = std::make_shared(); + break; + case FVE408: + brakes.driverValve = std::make_shared(); + break; + case testH: + brakes.driverValve = std::make_shared(); + break; + case M394: + brakes.driverValve = std::make_shared(); + break; + case Knorr: + brakes.driverValve = std::make_shared(); + break; + case St113: + brakes.driverValve = std::make_shared(); + break; + case MHZ_K5P: + brakes.driverValve = std::make_shared(); + break; + case MHZ_6P: + brakes.driverValve = std::make_shared(); + break; + default: + brakes.driverValve = std::make_shared(); + } + brakes.driverValve->SetParams(brakes.config.driverValveSettings.automaticOverload, brakes.config.driverValveSettings.manualOverload, brakes.config.driverValveSettings.genericParameter1, brakes.config.driverValveSettings.genericParameter2, brakes.config.driverValveSettings.overloadMaxPressure, brakes.config.driverValveSettings.overloadPressureDecrease); + + switch (brakes.config.independentValveType) + { + case TBrakeHandle::FD1: + { + brakes.independentValve = std::make_shared(); + brakes.independentValve->Init(brakes.config.maxCylinderPressure[0]); + if (trainType == train_type::emu) + { + + dynamic_cast(brakes.independentValve.get())->SetSpeed(3.5); + } + break; + } + case TBrakeHandle::Knorr: + { + brakes.independentValve = std::make_shared(); + brakes.independentValve->Init(brakes.config.maxCylinderPressure[0]); + break; + } + default: + brakes.independentValve = std::make_shared(); + } +} + +// the brake pipe, the main pipe and the spring brake's cylinder +void physics::Vehicle::CreateBrakePipes() +{ + if (true == TestFlag(brakes.config.availableDelays, bdelay_G) && (false == TestFlag(brakes.config.availableDelays, bdelay_R) || Power > 1.0)) // ustalanie srednicy przewodu glownego (lokomotywa lub napędowy + brakes.config.pipeSection = 0.792; + else + brakes.config.pipeSection = 0.507; + // WriteLog("SPG = " + FloatToStr(Spg)); + + brakePipe.reservoir = std::make_shared(); + mainPipe.reservoir = std::make_shared(); // zabezpieczenie, bo sie PG wywala... :( + brakePipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.config.pipeSection * 1); // dlugosc x przekroj x odejscia i takie tam + mainPipe.reservoir->CreateCap((std::max(Dim.L, 14.0) + 0.5) * brakes.config.pipeSection * 1); + if (!brakes.spring.cylinder) + { + brakes.spring.cylinder = std::make_shared(); + brakes.spring.cylinder->CreateCap(1); + } +} + +// the pressure of the main pipe at the start: the main reservoir's, or HosePressure fed through a main hose, or none +double physics::Vehicle::InitialScndPipePress(double const HosePressure) const +{ + if (air.config.mainReservoirVolume > 0.0) + { + return air.CompressedVolume() / air.config.mainReservoirVolume; + } + if (Couplers[VehicleEnd::front].AllowedFlag.HasAny(Coupling::mainHose) || Couplers[VehicleEnd::rear].AllowedFlag.HasAny(Coupling::mainHose)) + { + return HosePressure; + } + return 0.0; +} + +// the air and the controls of a vehicle ready to depart +void physics::Vehicle::SetReadyToDepart() +{ + WriteLog("Ready to depart"); + air.Fill(air.config.mainReservoirVolume * air.compressor.config.minPressure * 9.8 / 10.0); + mainPipe.SetPressure(InitialScndPipePress(5.0)); + brakePipe.SetPressure(brakes.controlReservoirPressure); + brakes.cylinderPressure = 0.0; + brakes.SetIndependentPosition(0.0); + if (CabActive == 0) + brakes.SetHandlePosition(static_cast(brakes.driverValve->GetPos(bh_NP))); + else + brakes.SetHandlePosition(static_cast(brakes.driverValve->GetPos(bh_RP))); + /* + // NOTE: disabled and left up to the driver, if there's any + MainSwitch( false ); + PantFront( true ); + PantRear( true ); + MainSwitch( true ); + */ + DirActive = 0; // Dir; //nastawnik kierunkowy - musi być ustawiane osobno! + DirAbsolute = DirActive * CabActive; // kierunek jazdy względem sprzęgów + brakes.pipeLimiterPressure = brakes.controlReservoirPressure; + + lowVoltage.ResetBattery(); +} + +// the air and the brakes of a vehicle standing braked +void physics::Vehicle::SetBraked() +{ + WriteLog("Braked"); + brakes.reservoirAir = brakes.config.valveVolume * brakes.config.maxCylinderPressure[3]; + air.Fill(air.config.mainReservoirVolume * air.compressor.config.minPressure * 0.55); + /* + ScndPipePress = 5.1; + */ + mainPipe.SetPressure(InitialScndPipePress(5.1)); + brakePipe.SetPressure(brakes.config.pipeLowPressure); + brakes.pipeCylinderPressure = brakes.config.maxCylinderPressure[3] * 0.5; + brakes.cylinderPressure = brakes.config.maxCylinderPressure[3] * 0.5; + brakes.SetIndependentPosition(0.0); + brakes.SetHandlePosition(static_cast(brakes.driverValve->GetPos(bh_NP))); + brakes.pipeLimiterPressure = brakes.config.pipeLowPressure; + if (brakes.config.localKind == TLocalBrake::ManualBrake || brakes.config.hasHandBrake == true) + { + IncManualBrakeLevel(ManualBrakePosNo); + } + if (brakes.spring.maxForce > 0.0) + { + brakes.spring.activate = true; + } +} diff --git a/physics/components/traction.cpp b/physics/components/traction.cpp new file mode 100644 index 000000000..018539c09 --- /dev/null +++ b/physics/components/traction.cpp @@ -0,0 +1,1681 @@ +/* +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 traction motors and their forces for each kind of drive, the relays, the fuses, the dynamic brake + +#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 +#include +#include +#include +#include +#include +#include +#include +#include "physics/components/internal.h" +#include "physics/components/drive.h" + + +double TableInterpolation(std::map &Map, double Parameter) +{ + if (Map.empty()) + return 0.0; + if (Map.size() == 1) + return Map.begin()->second; + + auto lower = Map.lower_bound(Parameter); + auto upper = lower; + + if (lower != Map.begin()) + lower--; + else + upper++; + + if (upper == Map.end()) + { + lower--; + upper--; + } + double ratio = (upper->second - lower->second) / (upper->first - lower->first); + return lower->second + (Parameter - lower->first) * ratio; +} + +// ************************************************************************************************* +// Q: 20160716 +// Obliczanie natężenie prądu w silnikach +// ************************************************************************************************* +double physics::Vehicle::Current(double n, double U) +{ + // wazna funkcja - liczy prad plynacy przez silniki polaczone szeregowo lub rownolegle + // w zaleznosci od polozenia nastawnikow MainCtrl i ScndCtrl oraz predkosci obrotowej n + // a takze wywala bezpiecznik nadmiarowy gdy za duzy prad lub za male napiecie + // jest takze mozliwosc uszkodzenia silnika wskutek nietypowych parametrow + + double R; + double MotorCurrent; + double Mn; // przujmuje int, ale dla poprawnosci obliczeń + double Bn; + + UpdateSeriesMotorDynamicBrakeFlag(); + + ResistorsFlag = RList[MainCtrlActualPos].R > 0.01; // and (!DelayCtrlFlag) + ResistorsFlag = ResistorsFlag || (brakes.electrodynamic.on == true && brakes.electrodynamic.type == dbrake_automatic); + + if (trainType == train_type::et22 && delayCtrlFlag && MainCtrlActualPos > 1) + Bn = 1.0 - 1.0 / RList[MainCtrlActualPos].Bn; + else + Bn = 1; // to jest wykonywane dla EU07 + + R = RList[MainCtrlActualPos].R * Bn + CircuitRes; + + if (trainType != train_type::emu || imin != IminLo || false == ScndS) + { + // yBARC - boczniki na szeregu poprawnie + Mn = RList[MainCtrlActualPos].Mn; // to jest wykonywane dla EU07 + } + else + { + Mn = RList[MainCtrlActualPos].Mn * RList[MainCtrlActualPos].Bn; + if (RList[MainCtrlActualPos].Bn > 1) + { + R = CircuitRes; + } + } + + if (brakes.electrodynamic.on && !FuseFlag && brakes.electrodynamic.type == dbrake_automatic && lowVoltage.Is110vAvailable() && lineBreaker.IsClosed()) // hamowanie EP09 //TUHEX + { + // TODO: zrobic bardziej uniwersalne nie tylko dla EP09 + MotorCurrent = -std::max(motor_param(0).fi * (Vadd / (Vadd + motor_param(0).Isat) - motor_param(0).fi0), 0.) * n * 2.0 / brakes.electrodynamic.resistance; + } + else if (RList[MainCtrlActualPos].Bn == 0 || false == lineContactors.IsClosed()) + { + // wylaczone + MotorCurrent = 0; + } + else + { // wlaczone... + MotorCurrent = SeriesMotorCurrent(n, U, R, Mn); + } + // writepaslog("MotorCurrent ", FloatToStr(MotorCurrent)); + + if (brakes.electrodynamic.type == dbrake_switch && (brakes.cylinderPressure > 2.0 || brakePipe.Pressure() < 3.6)) + { + Im = 0; + // Im:=0; + Itot = 0; + } + else + Im = MotorCurrent; + + EnginePower = abs(Itot) * (1 + RList[MainCtrlActualPos].Mn) * abs(U) / 1000.0; + + MotorFailuresCheck(n); + + return Im; +} + +// the automatic dynamic brake of the series motors (EP09, the units) on or off, and the distributor told of it +void physics::Vehicle::UpdateSeriesMotorDynamicBrakeFlag() +{ + // i dzialanie hamulca ED w EP09 + if (brakes.electrodynamic.type == dbrake_automatic && trainType != train_type::emu) + { + if ((brakes.distributor->GetEDBCP() < 0.25 && Vadd < 1) || brakes.cylinderPressure > 2.1) + brakes.electrodynamic.on = false; + else if (brakes.cylinderPressure > 0.25 && brakes.distributor->GetEDBCP() > 0.25) + brakes.electrodynamic.on = true; + brakes.electrodynamic.on = brakes.electrodynamic.on && lowVoltage.Is110vAvailable(); + } + if (brakes.electrodynamic.type == dbrake_automatic && trainType == train_type::emu) + { + brakes.electrodynamic.on = lowVoltage.Is110vAvailable() && (TUHEX_Active || Vadd > TUHEX_MinIw) && brakes.electrodynamic.emuWorking; + } + + // wylacznik cisnieniowy yBARC - to jest chyba niepotrzebne tutaj Q: no to usuwam... + + // BrakeSubsystem = ss_LSt; + // if (BrakeSubsystem == ss_LSt) WriteLog("LSt"); + // if (BrakeSubsystem == ss_LSt) // zrobiona funkcja virtualna + if (brakes.electrodynamic.on) + { + brakes.distributor->SetED(abs(Im / 350)); // hamulec ED na EP09 dziala az do zatrzymania lokomotywy + //- WriteLog("A"); + } + else + { + brakes.distributor->SetED(0); + //- WriteLog("B"); + } +} + +// the current of the series motors connected, at the revolutions n and the voltage U, through the resistance R of +// Mn motors in series +double physics::Vehicle::SeriesMotorCurrent(double const n, double const U, double const R, double const Mn) const +{ + double MotorCurrent{0.0}; + double Rz; + int SP = ScndCtrlActualPos; + + if (ScndCtrlActualPos < 255) // tak smiesznie bede wylaczal + { + if (ScndInMain && RList[MainCtrlActualPos].ScndAct != 255) + { + SP = RList[MainCtrlActualPos].ScndAct; + } + + Rz = Mn * windingRes + R; + + if (brakes.electrodynamic.on) // hamowanie + { + // if DynamicBrakeType<>dbrake_automatic then + // MotorCurrent:=-fi*n/Rz {hamowanie silnikiem na oporach rozruchowych} + /* begin + U:=0; + Isf:=Isat; + Delta:=SQR(Isf*Rz+Mn*fi*n-U)+4*U*Isf*Rz; + MotorCurrent:=(U-Isf*Rz-Mn*fi*n+SQRT(Delta))/(2*Rz) + end*/ + // only the ET42's switched brake brakes on the starting resistors, otherwise the current is cut off (0) + if (brakes.electrodynamic.type == dbrake_switch && trainType == train_type::et42) + { // z Megapacka + Rz = windingRes + R; + MotorCurrent = -motor_param(SP).fi * n / Rz; //{hamowanie silnikiem na oporach rozruchowych} + } + } + else + { + MotorCurrent = SeriesMotorDrivingCurrent(n, U, Rz, Mn, SP); + } // else DBF + + } // 255 + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the current of the series motors driving, at the revolutions n, the voltage U and the resistance Rz of Mn motors in +// series, by the motor parameters of the shunt field SP +double physics::Vehicle::SeriesMotorDrivingCurrent(double const n, double const U, double const Rz, double const Mn, int const SP) const +{ + double MotorCurrent; + double Delta; + double Isf; + double U1; // napiecie z korekta + U1 = U + Mn * n * motor_param(SP).fi0 * motor_param(SP).fi; + // writepaslog("U1 ", FloatToStr(U1)); + // writepaslog("Isat ", FloatToStr(MotorParam[SP].Isat)); + // writepaslog("fi ", FloatToStr(MotorParam[SP].fi)); + Isf = Sign(U1) * motor_param(SP).Isat; + // writepaslog("Isf ", FloatToStr(Isf)); + Delta = square(Isf * Rz + Mn * motor_param(SP).fi * n - U1) + 4.0 * U1 * Isf * Rz; // 105 * 1.67 + Mn * 140.9 * 20.532 - U1 + // DeltaQ = Isf * Rz + Mn * MotorParam[SP].fi * n - U1 + 4 * U1 * Isf * Rz; + // writepaslog("Delta ", FloatToStr(Delta)); + // writepaslog("DeltaQ ", FloatToStr(DeltaQ)); + // writepaslog("U ", FloatToStr(U)); + if (MainCircuitPowered()) + { + if (U > 0) + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n + std::sqrt(Delta)) / (2.0 * Rz); + else + MotorCurrent = (U1 - Isf * Rz - Mn * motor_param(SP).fi * n - std::sqrt(Delta)) / (2.0 * Rz); + } + else + MotorCurrent = 0; + return MotorCurrent; +} + +// the line breaker opened, and the motors damaged, by too high revolutions or current +void physics::Vehicle::MotorFailuresCheck(double const n) +{ + double MotorCurrent; + // awarie + MotorCurrent = abs(Im); // zmienna pomocnicza + + if (MotorCurrent > 0) + { + if (FuzzyLogic(abs(n), nmax * 1.1, p_elengproblem) && MainSwitch(false)) + eventFlag = true; /*zbyt duze obroty - wywalanie wskutek ognia okreznego*/ + if (DamageFlag.HasAll(VehicleDamage::engine) && FuzzyLogic(MotorCurrent, (double)imaxLo / 10.0, p_elengproblem) && MainSwitch(false)) + eventFlag = true; /*uszkodzony silnik (uplywy)*/ + /* or FuzzyLogic(Abs(U/Mn),2*NominalVoltage,1)) then */ /*poprawic potem*/ + if ((FuzzyLogic(abs(Im), Imax * 2, p_elengproblem) || FuzzyLogic(abs(n), nmax * 1.11, p_elengproblem)) && DamageFlag.Set(VehicleDamage::engine)) + eventFlag = true; + /*! dorobic grzanie oporow rozruchowych i silnika*/ + } +} + +// rozruch wysoki (true) albo niski (false) +bool physics::Vehicle::CurrentSwitch(bool const State) +{ + // TBD, TODO: split off shunt mode toggle into a separate command? It doesn't make much sense to have these two together like that + // the diesels with a shunt mode have no motor overload relay threshold to switch, the switch sets their shunt mode alone. + // MaxCurrentSwitch() takes any change of the setting, so asked first it took the first move of the switch (eu07/maszyna#497) + if (true == ShuntModeAllow && (EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric)) + { + // dla 2Ls150 przed ustawieniem kierunku, for SM42/SP42 at the controller's zero position + if (EngineType == TEngineType::DieselEngine ? DirActive != 0 : false == IsMainCtrlNoPowerPos()) + { + return false; + } + ShuntMode = State; + return true; + } + + if (MaxCurrentSwitch(State)) + { + if (trainType != train_type::emu) + { + MinCurrentSwitch(State); + } + return true; + } + + return false; +}; + +bool physics::Vehicle::IsMotorOverloadRelayHighThresholdOn() const +{ + + return imaxHi > imaxLo && Imax > imaxLo; +} + +double physics::Vehicle::ShowEngineRotation(int VehN) const +{ // Zwraca wartość prędkości obrotowej silnika wybranego pojazdu. Do 3 pojazdów (3×SN61). + int b; + switch (VehN) + { // numer obrotomierza + case 1: + return std::abs(enrot); + case 2: + for (b = 0; b <= 1; ++b) + if (Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Power > 0.01) + return fabs(Couplers[b].Connected->enrot); + break; + case 3: // to nie uwzględnia ewentualnego odwrócenia pojazdu w środku + for (b = 0; b <= 1; ++b) + if (Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Power > 0.01 && Couplers[b].Connected->Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Couplers[b].Connected->Power > 0.01) + return fabs(Couplers[b].Connected->Couplers[b].Connected->enrot); + break; + default: + break; + } + return 0.0; +}; + +void physics::Vehicle::MotorBlowersCheck(double const Timestep) +{ + // activation check + for (auto &blower : MotorBlowers) + { + auto disable = blower.is_disabled; + auto const start{(Vel >= blower.min_start_velocity && std::abs(Im) > 0.5)}; + auto const stop{(Vel < 0.5 && std::abs(Im) < 0.5)}; + if (blower.min_start_velocity >= 0) + { + if (stop) + { + blower.stop_timer += static_cast(Timestep); + if (blower.stop_timer > blower.sustain_time) + { + disable = true; + } + } + else if (start) + { + blower.stop_timer = 0; + } + else + { + disable |= !blower.is_active; + } + } + blower.is_active = + // TODO: bind properly power source when ld is in place + MotorBlowerPowerIsAvailable(blower) // power source + // breaker condition disabled until it's implemented in the class data + // && ( true == blower.breaker ) + && false == disable && + (true == blower.is_active || (blower.stop_timer == 0.f // HACK: will be true for blower with exceeded start_velocity, and for one without start_velocity + && (blower.start_type == start_t::manual ? blower.is_enabled : true))); + } + // update + for (auto &fan : MotorBlowers) + { + + auto const revolutionstarget{(fan.is_active ? (fan.speed > 0.f ? fan.speed * static_cast(enrot) * 60 : fan.speed * -1) : 0.f)}; + + if (std::abs(fan.revolutions - revolutionstarget) < 0.01f) + { + fan.revolutions = revolutionstarget; + continue; + } + if (revolutionstarget > 0.f) + { + auto const speedincreasecap{std::max(50.f, fan.speed * 0.05f * -1)}; // 5% of fixed revolution speed, or 50 + fan.revolutions += static_cast(std::clamp(revolutionstarget - fan.revolutions, speedincreasecap * -2, speedincreasecap) * Timestep); + } + else + { + fan.revolutions *= static_cast(std::max(0.0, 1.0 - Timestep)); + } + } +} + +bool physics::Vehicle::MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const +{ + switch (Blower.start_type) + { + case start_t::battery: + return lowVoltage.Is24vAvailable(); + case start_t::converter: + return lowVoltage.Is110vAvailable(); + default: + return MainCircuitPowered(); + } +} + +double physics::Vehicle::ShowCurrent(int AmpN) const +{ // Odczyt poboru prądu na podanym amperomierzu + return Drive().ShowCurrent(*this, AmpN); +}; + +bool physics::Vehicle::MotorBlowersSwitch(bool State, VehicleEnd const Side, range_t const Notify) +{ + + auto &fan{MotorBlowers[Side]}; + + if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + return false; + } + + bool const initialstate{fan.is_enabled}; + + fan.is_enabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(Side == VehicleEnd::front ? VehicleCommand::motorBlowersFrontSwitch : VehicleCommand::motorBlowersRearSwitch, fan.is_enabled ? 1 : 0, CabActive, + Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return fan.is_enabled != initialstate; +} + +bool physics::Vehicle::MotorBlowersSwitchOff(bool State, VehicleEnd const Side, range_t const Notify) +{ + + auto &fan{MotorBlowers[Side]}; + + if (fan.start_type != start_t::manual && fan.start_type != start_t::manualwithautofallback) + { + // automatic device ignores 'manual' state commands + return false; + } + + bool const initialstate{fan.is_disabled}; + + fan.is_disabled = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(Side == VehicleEnd::front ? VehicleCommand::motorBlowersFrontSwitchOff : VehicleCommand::motorBlowersRearSwitchOff, fan.is_disabled ? 1 : 0, CabActive, + Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return fan.is_disabled != initialstate; +} + +// the traction selector of a dual-mode vehicle: moves only with the line breaker open, and only where a genset is +bool physics::Vehicle::TractionModeSwitch(traction_mode const Mode, range_t const Notify) +{ + auto const initialstate{tractionModeSetting}; + // refused with the line breaker closed, and then not passed on either, so the train stays on one source + auto const accepted{false == lineBreaker.IsClosed()}; + + if (Genset.fitted() && accepted) + { + tractionModeSetting = Mode; + } + + if (Notify != range_t::local && accepted) + { + SendCtrlToNext(VehicleCommand::tractionMode, Mode == traction_mode::genset ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return tractionModeSetting != initialstate; +} + +// ************************************************************************************************* +// zwiększenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// uzywane gdy SplitEDPneumaticBrake = true +// ************************************************************************************************* +bool physics::Vehicle::IncDynamicBrakeLevel(float const CtrlSpeed) +{ + if (false == brakes.electrodynamic.splitFromPneumatic) + return false; + if (brakes.electrodynamic.controllerPositions < 1) + return false; + if (brakes.electrodynamic.controllerPosition < 1.0) + { + brakes.electrodynamic.controllerPosition = std::min(1.0, brakes.electrodynamic.controllerPosition + (double)CtrlSpeed / (double)brakes.electrodynamic.controllerPositions); + return true; + } + return false; +} + +// ************************************************************************************************* +// zmniejszenie nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// ************************************************************************************************* +bool physics::Vehicle::DecDynamicBrakeLevel(float const CtrlSpeed) +{ + if (false == brakes.electrodynamic.splitFromPneumatic) + return false; + if (brakes.electrodynamic.controllerPositions < 1) + return false; + if (brakes.electrodynamic.controllerPosition > 0.0) + { + brakes.electrodynamic.controllerPosition = std::max(0.0, brakes.electrodynamic.controllerPosition - (double)CtrlSpeed / (double)brakes.electrodynamic.controllerPositions); + return true; + } + return false; +} + +// ************************************************************************************************* +// bezposrednie ustawienie nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// ************************************************************************************************* +bool physics::Vehicle::DynamicBrakeLevelSet(double Position) +{ + if (false == brakes.electrodynamic.splitFromPneumatic) + return false; + brakes.electrodynamic.controllerPosition = std::clamp(Position, 0.0, 1.0); + return true; +} + +// ************************************************************************************************* +// odczyt nastawy nastawnika hamulca elektrodynamicznego (DynamicBrakeCtrl) +// zwraca 0 jezeli SplitEDPneumaticBrake nie jest aktywne (dla zachowania starej logiki) +// ************************************************************************************************* +double physics::Vehicle::DynamicBrakeRatio(void) const +{ + if (false == brakes.electrodynamic.splitFromPneumatic) + return 0.0; + return std::clamp(brakes.electrodynamic.controllerPosition, 0.0, 1.0); +} + +// ************************************************************************************************* +// czy hamulec ED jest aktualnie dostepny w oknie predkosci Vh0..Vh1 +// ************************************************************************************************* +bool physics::Vehicle::DynamicBrakeAvailable(void) const +{ + double const vh0{inductionMotor.braking.offSpeed}; + if (double const vh1{inductionMotor.braking.fullSpeed}; vh1 <= 0.001) + { + // brak zdefiniowanej strefy - ED dziala zawsze + return true; + } + // strefa wylaczenia jest definiowana przez Vh0 (minimum); powyzej Vh0 ED dziala + return Vel >= vh0; +} + +// ************************************************************************************************* +// Q: 20160713 +// reczne przelaczanie hamulca elektrodynamicznego +// ************************************************************************************************* +bool physics::Vehicle::DynamicBrakeSwitch(bool Switch) +{ + bool DBS; + + if (brakes.electrodynamic.type == dbrake_switch && IsMainCtrlNoPowerPos()) + { + brakes.electrodynamic.on = Switch; + DBS = true; + for (auto &thiscoupler : Couplers) + // with Couplers[b] do + if (thiscoupler.CouplingFlag.HasAll(Coupling::control)) + thiscoupler.Connected->brakes.electrodynamic.on = Switch; + // end; + // if (DynamicBrakeType=dbrake_passive) and (TrainType=train_type::et42) then + // begin + // DynamicBrakeFlag:=false; + // DynamicBrakeSwitch:=false; + } + else + DBS = false; + + return DBS; +} + +// ************************************************************************************************* +// Q: 20160714 +// oblicza sile trakcyjna lokomotywy (dla elektrowozu tez calkowity prad) +// ************************************************************************************************* +double physics::Vehicle::TractionForce(double dt) +{ + ft = 0; + double dtrans{0.0}; + double dmoment{0.0}; + auto const revolutions{UpdateEngineRevolutions(dt, dtrans, dmoment)}; + + eAngleValue += enrot * dt; + if (eAngleValue > M_PI * 2.0) + eAngleValue = std::fmod(eAngleValue, M_PI * 2.0); + /* + while (eAngleValue > M_PI * 2.0) + // eAngle = Pirazy2 - eAngle; <- ABu: a nie czasem tak, jak nizej? + eAngleValue -= M_PI * 2.0; + */ + // hunter-091012: przeniesione z if DirActive<>0 (zeby po zejsciu z kierunku dalej spadala predkosc wentylatorow) + // wentylatory rozruchowe + // TBD, TODO: move this to update, it doesn't exactly have much to do with traction + auto const &drive{Drive()}; + drive.UpdateVentilators(*this, dt); + auto const PosRatio{drive.UpdateEnginePower(*this)}; + VoltageRelaysCheck(); + + drive.BeforeTractionForce(*this, dt); + if (DirActive != 0) + { + drive.UpdateTractionForce(*this, DriveStep{dt, PosRatio, revolutions, dmoment, dtrans}); + } + drive.AfterTractionForce(*this); + + return ft; +} + +// the starting resistors' blowers, and the diesels' radiator fans +void physics::Vehicle::UpdateVentilators(double dt) +{ + Drive().UpdateVentilators(*this, dt); +} + +// the starting resistors' blowers of the series motors with the line breaker closed, worked by hand or by the current +void physics::Vehicle::UpdateResistorBlowers(double dt) +{ + switch (RVentType) + { + + case 1: + { // manual + if (true == rventForceOn || (DirActive != 0 && RList[MainCtrlActualPos].R > RVentCutOff)) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + case 2: + { // automatic + auto const motorcurrent{std::min(imaxHi, std::abs(Im))}; + if (std::abs(Itot) > RVentMinI && RList[MainCtrlActualPos].R > RVentCutOff) + { + + RventRot += (RVentnmax * std::min(1.0, motorcurrent / nPoweredAxles / RVentMinI) * motorcurrent / imaxLo - RventRot) * RVentSpeed * dt; + } + else if (brakes.electrodynamic.type == dbrake_automatic && true == brakes.electrodynamic.on) + { + RventRot += (RVentnmax * motorcurrent / imaxLo - RventRot) * RVentSpeed * dt; + } + else if (rventForceOn) + { + RventRot += (RVentnmax - RventRot) * RVentSpeed * dt; + } + else + { + RventRot *= std::max(0.0, 1.0 - RVentSpeed * dt); + } + break; + } + + default: + { + break; + } + } // rventtype +} + +// the power of a dumb or diesel engine; returns the ratio of the power a dumb engine is set to +double physics::Vehicle::UpdateEnginePower() +{ + return Drive().UpdateEnginePower(*this); +} + +// the line breaker opened by a voltage out of the motors' range, and the line contactors of a diesel-electric +void physics::Vehicle::VoltageRelaysCheck() +{ + Drive().CheckVoltageRelays(*this); +} + +void physics::Vehicle::DumbTractionForce(double const PosRatio) +{ + if (lineBreaker.IsClosed() && CabActive != 0) + { + if (Vel > 0.1) + { + ft = std::min(1000.0 * Power / std::abs(travelSpeed), Ftmax) * PosRatio; + } + else + { + ft = Ftmax * PosRatio; + } + ft = ft * DirAbsolute; // DirActive*CabActive; + } + else + { + ft = 0; + } +} + +void physics::Vehicle::WheelsDrivenTractionForce(double dt) +{ + if (EnginePowerSource.SourceType == TPowerSource::InternalSource && EnginePowerSource.PowerType == TPowerType::BioPower) + ft = Sign(sin(eAngleValue)) * PulseForce * Transmision.Ratio; + PulseForceTimer = PulseForceTimer + dt; + if (PulseForceTimer > CtrlDelay) + { + PulseForce = 0; + if (PulseForceCount > 0) + PulseForceCount--; + } + EnginePower = ft * (1.0 + Vel); +} + +void physics::Vehicle::SeriesMotorTractionForce(double dt) +{ + // enrot:=Transmision.Ratio*nrot; + // yB: szereg dwoch sekcji w ET42 + if (trainType == train_type::et42 && Imax == imaxHi) + EngineVoltage = EngineVoltage / 2.0; + motorMoment = Momentum(Current(enrot, EngineVoltage)); // oblicza tez prad p/slinik + + if (trainType == train_type::et42) + { + if (Imax == imaxHi) + EngineVoltage = EngineVoltage * 2; + if (brakes.electrodynamic.on && abs(Im) > 300) // przeiesione do physics.cpp + FuseOff(); + } + if (brakes.electrodynamic.type == dbrake_automatic && brakes.electrodynamic.on) + { + SeriesMotorDynamicBrake(dt); + } + + if (trainType == train_type::et22 && delayCtrlFlag) // szarpanie przy zmianie układu w byku + motorMoment = motorMoment * RList[MainCtrlActualPos].Bn / (RList[MainCtrlActualPos].Bn + 1); // zrobione w momencie, żeby nie dawac elektryki w przeliczaniu sił + + if (abs(Im) > Imax) + Vhyp += dt; //*(abs(Im) / Imax - 0.9) * 10; // zwieksz czas oddzialywania na PN + else + Vhyp = 0; + if (Vhyp > CtrlDelay / 2) // jesli czas oddzialywania przekroczony + FuseOff(); // wywalanie bezpiecznika z powodu przetezenia silnikow + + if ((brakes.electrodynamic.type == dbrake_automatic || brakes.electrodynamic.type == dbrake_switch) && brakes.electrodynamic.on) + Itot = Im * 2; // 2x2 silniki w EP09 + else if (trainType == train_type::emu && imin == IminLo && ScndS) // yBARC - boczniki na szeregu poprawnie + Itot = Im; + else + Itot = Im * RList[MainCtrlActualPos].Bn; // prad silnika * ilosc galezi + Mw = motorMoment * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / wheelDiameter; + ft = Fw * nPoweredAxles; // sila trakcyjna +} + +// the automatic dynamic brake of the series motors: the excitation current, by the stages of the ep brake (TUHEX) +void physics::Vehicle::SeriesMotorDynamicBrake(double dt) +{ + if (TUHEX_Stages > 0) // hamowanie wielostopniowe, nadpisuje wartości domyślne + { + if (Vel > 100) + TUHEX_StageActual = std::min(TUHEX_StageActual, 1); + switch (TUHEX_StageActual) + { + case 1: + TUHEX_Sum = TUHEX_Sum1; + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance1; + break; + case 2: + TUHEX_Sum = TUHEX_Sum2; + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance1; + break; + case 3: + TUHEX_Sum = TUHEX_Sum3; + if (Vadd > 0.99 * TUHEX_MaxIw && brakes.electrodynamic.resistance == brakes.electrodynamic.resistance1) + TUHEX_ResChange = true; + if (TUHEX_ResChange && Vadd < 0.5 * TUHEX_MaxIw) + { + TUHEX_ResChange = false; + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance2; + } + break; + default: + brakes.electrodynamic.resistance = brakes.electrodynamic.resistance1; + TUHEX_Sum = 0; + break; + } + } + if (Vadd + abs(Im) > TUHEX_Sum + TUHEX_Diff || brakes.distributor->GetEDBCP() < 0.25 || TUHEX_ResChange || (TUHEX_StageActual == 0 && TUHEX_Stages > 0)) + { + Vadd -= 500.0 * dt; + if (Vadd < TUHEX_MinIw) + { + Vadd = 0; + brakes.electrodynamic.on = false; + } + } + else if (brakes.electrodynamic.on && Vadd + abs(Im) < TUHEX_Sum - TUHEX_Diff) + { + Vadd += 70.0 * dt; + Vadd = std::min(std::max(Vadd, TUHEX_MinIw), TUHEX_MaxIw); + } + if (Vadd > 0) + motorMoment = MomentumF(Im, Vadd, 0); +} + +// the shunt field relays of a diesel-electric, each kind its own conditions on the current, the speed or the +// power (tmp, the power the engine gives) +void physics::Vehicle::ShuntFieldRelaysCheck(double const tmpV, double const PosRatio, double const tmp) +{ + auto const shuntfieldstate{scndCtrlPos}; + + switch (RelayType) + { + + case 0: + { + + if (scndCtrlPos < scndCtrlPosNo && Im <= MPTRelay[scndCtrlPos].Iup * PosRatio) + { + ++scndCtrlPos; + } + if (scndCtrlPos > 0 && Im >= MPTRelay[scndCtrlPos].Idown * PosRatio) + { + --scndCtrlPos; + } + break; + } + case 1: + { + + if (scndCtrlPos < scndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel) + { + ++scndCtrlPos; + } + if (scndCtrlPos > 0 && MPTRelay[scndCtrlPos].Idown > Vel) + { + --scndCtrlPos; + } + break; + } + case 2: + { + + ShuntFieldRelaysType2(tmp); + break; + } + case 41: + { + ShuntFieldRelaysType41(tmpV); + break; + } + case 45: + { + ShuntFieldRelaysType45(); + break; + } + case 46: + { + ShuntFieldRelaysType46(); + break; + } + default: + { + break; + } + } // switch RelayType + + if (scndCtrlPos != shuntfieldstate) + { + SetFlag(soundFlag, sound::relay | sound::shuntfield); + } +} + +// the relays of type 2: up by the speed while the engine has power to spare (tmp, the power it gives), down by the current +void physics::Vehicle::ShuntFieldRelaysType2(double const tmp) +{ + if (scndCtrlPos < scndCtrlPosNo && MPTRelay[scndCtrlPos].Iup < Vel && EnginePower < tmp * 0.99) + { + ++scndCtrlPos; + } + if (scndCtrlPos > 0 && MPTRelay[scndCtrlPos].Idown < Im) + { + --scndCtrlPos; + } +} + +// the relays of type 41: up by the speed tmpV at full power, the engine slowed down, down by the current +void physics::Vehicle::ShuntFieldRelaysType41(double const tmpV) +{ + if (scndCtrlPos < scndCtrlPosNo && mainCtrlPos == MainCtrlPosNo && tmpV * 3.6 > MPTRelay[scndCtrlPos].Iup) + { + ++scndCtrlPos; + enrot = enrot * 0.73; + } + if (scndCtrlPos > 0 && Im > MPTRelay[scndCtrlPos].Idown) + { + --scndCtrlPos; + } +} + +// the relays of type 45, by the current and the speed: up from the 11th position, at most two under it, none under the 8th +void physics::Vehicle::ShuntFieldRelaysType45() +{ + if (scndCtrlPos < scndCtrlPosNo && mainCtrlPos >= 11) + { + + if (Im < MPTRelay[scndCtrlPos].Iup) + { + ++scndCtrlPos; + } + // check for cases where the speed drops below threshold for level 2 or 3 + if (scndCtrlPos > 1 && Vel < MPTRelay[scndCtrlPos - 1].Idown) + { + --scndCtrlPos; + } + } + // malenie + if (scndCtrlPos > 0 && mainCtrlPos < 11) + { + + if (scndCtrlPos == 1) + { + if (Im > MPTRelay[scndCtrlPos - 1].Idown) + { + --scndCtrlPos; + } + } + else + { + if (Vel < MPTRelay[scndCtrlPos].Idown) + { + --scndCtrlPos; + } + } + } + // 3rd level drops with master controller at position lower than 10... + if (mainCtrlPos < 11) + { + scndCtrlPos = std::min(2, scndCtrlPos); + } + // ...and below position 7 field shunt drops altogether + if (mainCtrlPos < 8) + { + scndCtrlPos = 0; + } + /* + // crude woodward approximation; difference between rpm for consecutive positions is ~5% + // so we get full throttle until ~half way between desired and previous position, or zero on rpm reduction + auto const woodward { std::clamp( + ( DElist[ mainCtrlPos ].RPM / ( enrot * 60.0 ) - 1.0 ) * 50.0, + 0.0, 1.0 ) }; + */ +} + +// the relays of type 46, by the current and the speed: up from the 12th position, down under it below 50 km/h, at most two +// under the 11th, none under the 8th +void physics::Vehicle::ShuntFieldRelaysType46() +{ + // wzrastanie + if (mainCtrlPos >= 12 && scndCtrlPos < scndCtrlPosNo) + { + ShuntFieldRelaysType46Up(); + } + // malenie + if (mainCtrlPos < 12 && scndCtrlPos > 0 && Vel < 50.0) + { + ShuntFieldRelaysType46Down(); + } + if (mainCtrlPos < 11) + { + scndCtrlPos = std::min(2, scndCtrlPos); + } + if (mainCtrlPos < 8) + { + scndCtrlPos = 0; + } +} + +// a relay of type 46 down: an even one by the current, an odd one by the current and the speed +void physics::Vehicle::ShuntFieldRelaysType46Down() +{ + // above 50 km/h already active shunt field can be maintained until lower controller setting + if (scndCtrlPos % 2 == 0) + { + if (MPTRelay[scndCtrlPos].Idown < Im) + { + --scndCtrlPos; + } + } + else + { + if (MPTRelay[scndCtrlPos + 1].Idown < Im && MPTRelay[scndCtrlPos].Idown > Vel) + { + --scndCtrlPos; + } + } +} + +// a relay of type 46 up: an even one by the current, an odd one by the current and the speed +void physics::Vehicle::ShuntFieldRelaysType46Up() +{ + if (scndCtrlPos % 2 == 0) + { + if (MPTRelay[scndCtrlPos].Iup > Im) + { + ++scndCtrlPos; + } + } + else + { + if (MPTRelay[scndCtrlPos - 1].Iup > Im && MPTRelay[scndCtrlPos].Iup < Vel) + { + ++scndCtrlPos; + } + } +} + +void physics::Vehicle::InductionMotorTractionForce(double dt) +{ + if (MainCircuitPowered() && !SecuritySystem.is_engine_blocked()) + { + double PosRatio; + double tmp; + double ActiveInverters = 0.0; + for (auto const &inv : inductionMotor.inverters) + { + if (inv.IsActive) + ActiveInverters += 1.0; + } + inductionMotor.inverterRatio = ActiveInverters / (double)inductionMotor.inverterCount; + if (inductionMotor.maxPowerTable.size() > 1) + { + inductionMotor.traction.maxPower = TableInterpolation(inductionMotor.maxPowerTable, Vel); + } + InductionMotorSpeedControl(dt); + InductionMotorBrakeBlending(ActiveInverters, PosRatio, tmp); + // NOTE: the commands to operate the sandbox are likely to conflict with other similar ai decisions + // TODO: gather these in single place so they can be resolved together + if (slippingWheels) + { + PosRatio = 0; + tmp = 10; + SandboxAuto(true, range_t::unit); + } // przeciwposlizg + else + { + // switch sandbox off + SandboxAuto(false, range_t::unit); + } + if (ActiveInverters == 0.0) + { + PosRatio = 0; + inductionMotor.forceShare = 0; + } + + inductionMotor.forceShare += std::max(std::min(PosRatio - inductionMotor.forceShare, 0.02), -0.02) * 12 * tmp /*2{+4*byte(PosRatio 1) + { + SpeedControlByPosition(dt); + } +} + +// the speed control set by the position of the second controller, after it's been held for its delay +void physics::Vehicle::SpeedControlByPosition(double dt) +{ + if (scndCtrlPos != newSpeed) + { + + SpeedCtrlTimer = 0; + newSpeed = scndCtrlPos; + } + else + { + SpeedCtrlTimer += dt; + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + auto NewSCAP = static_cast((float)scndCtrlPos / (float)scndCtrlPosNo * vmax); + if (NewSCAP != SpeedCtrlValue) + { + SpeedCtrlValue = NewSCAP; + // SendCtrlToNext(VehicleCommand::speedControl, SpeedCtrlValue, CabActive); + } + } + } + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; +} + +// the speed control of a four position second controller, by time: the speed set down or up by 10 km/h a step, held, +// or off and at the top +void physics::Vehicle::SpeedControlByTime(double dt) +{ + SpeedCtrlUnit.IsActive = SpeedCtrlValue > 0; + switch (scndCtrlPos) + { + case 0: + newSpeed = 0; + SpeedCtrlValue = 0; + SpeedCtrlTimer = 10; + break; + case 1: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + newSpeed -= 10; + if (newSpeed < 0) + newSpeed = 0; + } + else + SpeedCtrlTimer += dt; + break; + case 2: + SpeedCtrlTimer = 10; + SpeedCtrlValue = newSpeed; + break; + case 3: + if (SpeedCtrlTimer > SpeedCtrlDelay) + { + SpeedCtrlTimer = 0; + newSpeed += 10; + if (newSpeed > vmax) + newSpeed = vmax; + } + else + SpeedCtrlTimer += dt; + break; + case 4: + newSpeed = vmax; + SpeedCtrlValue = vmax; + SpeedCtrlTimer = 10; + break; + default: + break; + } +} + +// whether the induction motors brake, and the share of the electrodynamic and the pneumatic brake; sets the +// force asked of the motors (PosRatio) and how fast the drive follows it (tmp) +void physics::Vehicle::InductionMotorBrakeBlending(double const ActiveInverters, double &PosRatio, double &tmp) +{ + InductionMotorDynamicBrakeFlag(); + auto const edBCP{brakes.distributor->GetEDBCP() * inductionMotor.braking.cylinderPressureGain}; // stala napedu + if (brakes.electrodynamic.on) + { + PosRatio = InductionMotorBrakeRatio(ActiveInverters, edBCP); + tmp = 5; + } + else + { + PosRatio = std::max(eimicReal, 0.); + inductionMotor.state.forceDemand = PosRatio; + if (Flat && inductionMotor.traction.startingForce * inductionMotor.state.fullForce > 0) + PosRatio = std::min(PosRatio * inductionMotor.traction.startingForce / inductionMotor.state.fullForce, 1.); + /* if (ScndCtrlActualPos > 0) //speed control + if (vmax < 250) + PosRatio = std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos - Vel))); + else + PosRatio = + std::min(PosRatio, std::max(-1, 0.5 * (ScndCtrlActualPos * 2 - Vel))); */ + // PosRatio = 1.0 * (PosRatio * 0 + 1) * PosRatio; // 1 * 1 * PosRatio = PosRatio + brakes.distributor->SetED(0); + // (Hamulec as TLSt).SetLBP(LocBrakePress); + tmp = 4; // szybkie malenie, powolne wzrastanie + } +} + +// the electrodynamic brake of the induction motors on: with the doors open or permitted, by the train brake, the local +// brake or its own controller; off without them +void physics::Vehicle::InductionMotorDynamicBrakeFlag() +{ + double const edBCP = brakes.distributor->GetEDBCP(); + auto const localbrakeactive{cabOccupied != 0 && brakes.independentValve->GetCP() > 0.25}; + // gdy SplitEDPneumaticBrake jest aktywne, hamulec pomocniczy (LocalBrake) NIE wymusza + // zalaczenia hamulca elektrodynamicznego - ED jest sterowany wlasnym nastawnikiem + auto const dynbrakectrlactive{brakes.electrodynamic.splitFromPneumatic && DynamicBrakeRatio() > 0.01 && DynamicBrakeAvailable()}; + auto const localbrakeforED{brakes.electrodynamic.splitFromPneumatic ? false : localbrakeactive}; + if (false == Doors.instances[VehicleSide::left].is_closed || false == Doors.instances[VehicleSide::right].is_closed || + (Doors.permit_needed && (Doors.instances[VehicleSide::left].open_permit || Doors.instances[VehicleSide::right].open_permit))) + { + brakes.electrodynamic.on = true; + } + else if ((edBCP < 0.25 && false == localbrakeforED && false == dynbrakectrlactive && anPos < 0.01) || + (edBCP < 0.25 && ShuntModeAllow && false == dynbrakectrlactive && brakes.IndependentPosition() < 0.01)) + brakes.electrodynamic.on = false; + else if (brakes.cylinderPressure > 0.25 && edBCP > 0.25 || localbrakeforED || anPos > 0.02 || dynbrakectrlactive) + brakes.electrodynamic.on = true; +} + +// the share of the electrodynamic brake (negative), and the distributor told how much of the air to let out; none +// when the air brake cuts the electrodynamic one off, or an inverter is out +double physics::Vehicle::InductionMotorBrakeRatio(double const ActiveInverters, double const edBCP) +{ + double PosRatio; + // ustalanie współczynnika blendingu do luzowania hamulca PN + if (inductionMotor.state.maxForce * Sign(travelSpeed) * DirAbsolute < -1) + { + PosRatio = -Sign(travelSpeed) * DirAbsolute * inductionMotor.state.force / (inductionMotor.braking.maxForce * std::max(edBCP, std::max(0.01, brakes.distributor->GetEDBCP())) / brakes.config.maxCylinderPressure[0]); + PosRatio = std::clamp(PosRatio, 0.0, 1.0); + } + else + { + PosRatio = 0; + } + PosRatio = static_cast(Round(20.0 * PosRatio)) / 20.0; // stopniowanie PN/ED + if (PosRatio < 19.5 / 20.0) + PosRatio *= 0.9; + brakes.distributor->SetED(std::max(0.0, std::min(PosRatio, 1.0))); // ustalenie stopnia zmniejszenia ciśnienia + // ustalanie siły hamowania ED + if (brakes.distributor->GetEDBCP() > 0.25 && inductionMotor.braking.cylinderPressureGain < 0.001 || ActiveInverters < inductionMotor.inverterCount) // jeśli PN wyłącza ED + { + PosRatio = 0; + inductionMotor.state.forceDemand = 0; + } + else + { + // strefa wylaczenia ED (Vh0..Vh1) - mnoznik 0..1 zaleznie od predkosci + double const vhRamp = std::max(0.0, std::min(1.0, (Vel - inductionMotor.braking.offSpeed) / (inductionMotor.braking.fullSpeed - inductionMotor.braking.offSpeed))); + if (brakes.electrodynamic.splitFromPneumatic) + { + // w trybie split LocalBrake nie zaleca ED; uzywany jest DynamicBrakeCtrl + // oraz zwykle zapotrzebowanie z hamulca zespolonego (edBCP) + double const edLeverDemand = DynamicBrakeRatio(); + PosRatio = -std::max(std::max(edLeverDemand, std::min(edBCP / brakes.config.maxCylinderPressure[0], 1.0)), anPos) * vhRamp; + inductionMotor.state.forceDemand = -std::min(1.0, std::max(edLeverDemand, edBCP / brakes.config.maxCylinderPressure[0])); + } + else + { + PosRatio = -std::max(std::min(edBCP * 1.0 / brakes.config.maxCylinderPressure[0], 1.0), anPos) * vhRamp; + inductionMotor.state.forceDemand = -std::min(1.0, std::max(LocalBrakeRatio(), edBCP / brakes.config.maxCylinderPressure[0])); + } + } + return PosRatio; +} + +// the model of the induction motors and their inverters: voltage, frequency, currents, moment and force +void physics::Vehicle::InductionMotorDrive(double dt) +{ + double tmp; + if (brakes.electrodynamic.on) + tmp = inductionMotor.converter.brakingLinkVoltage; + else + tmp = inductionMotor.converter.maxLinkVoltage; + + auto f_cfu{brakes.electrodynamic.on ? inductionMotor.converter.brakingVoltsPerHertz : inductionMotor.converter.voltsPerHertz}; + + inductionMotor.state.linkVoltage = std::min(EngineVoltage - inductionMotor.converter.voltageDrop, tmp); + inductionMotor.state.criticalFrequency = inductionMotor.state.linkVoltage / f_cfu; + if (inductionMotor.forceShare < 0) + { + inductionMotor.state.powerLimit = inductionMotor.braking.maxPower; + } + else + { + inductionMotor.state.powerLimit = std::min(inductionMotor.traction.maxPower, 0.001 * EngineVoltage * (inductionMotor.traction.maxCurrent - inductionMotor.converter.noLoadCurrent) * Pirazy2 * inductionMotor.motor.torquePerCurrent / inductionMotor.motor.polePairs / inductionMotor.motor.voltsPerHertz); + if (GensetSelected()) + { + // on the genset of a dual-mode vehicle the traction takes no more than the genset gives + inductionMotor.state.powerLimit = std::min(inductionMotor.state.powerLimit, GensetTractionPowerLimit()); + } + } + inductionMotor.state.absoluteMaxForce = 0.001 * + square(std::min(1.0, inductionMotor.state.criticalFrequency / std::max(abs(enrot) * inductionMotor.motor.polePairs + inductionMotor.motor.maxSlipFrequency * inductionMotor.state.slipShare, inductionMotor.motor.maxSlipFrequency)) * f_cfu / inductionMotor.motor.voltsPerHertz) * + (inductionMotor.motor.maxSlipFrequency * inductionMotor.motor.currentPerSlip * inductionMotor.motor.torquePerCurrent) * Transmision.Ratio * nPoweredAxles * 2.0 / wheelDiameter; + InductionMotorForceLimits(); + for (auto &inv : inductionMotor.inverters) + { + inv.Request = inv.IsActive ? inductionMotor.forceShare : 0.0; + inv.Error = inv.Failure_Const || (inv.Failure_Drive && inv.Request != 0); + inv.IsActive = inv.Activate && !inv.Error; + } + inductionMotor.state.slipShare = inductionMotor.state.force / inductionMotor.state.absoluteMaxForce; + inductionMotor.state.slipFrequency = inductionMotor.state.slipShare * inductionMotor.motor.maxSlipFrequency; + inductionMotor.state.supplyFrequency = DirAbsolute * enrot * inductionMotor.motor.polePairs + inductionMotor.state.slipFrequency; // do przemyslenia dzialanie pp z tmpV + // inductionMotor.state.voltage:=std::max(inductionMotor.state.linkVoltage,std::min(inductionMotor.converter.voltsPerHertz*inductionMotor.state.supplyFrequency,inductionMotor.state.linkVoltage)); + // inductionMotor.state.flux:=inductionMotor.state.voltage/(inductionMotor.state.supplyFrequency*inductionMotor.motor.voltsPerHertz); + if (abs(inductionMotor.state.supplyFrequency) <= inductionMotor.state.criticalFrequency) + inductionMotor.state.flux = f_cfu / inductionMotor.motor.voltsPerHertz; + else + inductionMotor.state.flux = inductionMotor.state.linkVoltage / inductionMotor.motor.voltsPerHertz / abs(inductionMotor.state.supplyFrequency); + inductionMotor.state.voltage = inductionMotor.state.flux * inductionMotor.state.supplyFrequency * inductionMotor.motor.voltsPerHertz; + inductionMotor.state.torqueCurrent = (inductionMotor.state.supplyFrequency - DirAbsolute * enrot * inductionMotor.motor.polePairs) * inductionMotor.motor.currentPerSlip * inductionMotor.state.flux; + inductionMotor.state.fieldCurrent = inductionMotor.state.torqueCurrent * inductionMotor.motor.fieldCurrentRatio; + inductionMotor.state.torque = inductionMotor.state.flux * inductionMotor.state.torqueCurrent * inductionMotor.motor.torquePerCurrent; + inductionMotor.state.lineCurrent = inductionMotor.state.torqueCurrent * nPoweredAxles * inductionMotor.inverterRatio * inductionMotor.state.voltage / (EngineVoltage - inductionMotor.converter.voltageDrop) + inductionMotor.converter.noLoadCurrent; + inductionMotor.state.mechanicalPower = DirActive * inductionMotor.state.torque * nPoweredAxles * inductionMotor.inverterRatio * enrot * Pirazy2 / 1000; + inductionMotor.state.electricalPower = inductionMotor.state.lineCurrent * EngineVoltage / 1000; + inductionMotor.state.efficiency = inductionMotor.state.mechanicalPower / inductionMotor.state.electricalPower; + + Im = inductionMotor.state.fieldCurrent; + if (inductionMotor.state.lineCurrent >= 0) + Vadd *= 1.0 - 2.0 * dt; + else if (GensetSelected()) + Vadd = 1.0; // the genset of a dual-mode vehicle takes nothing back: all the braking energy to the resistors + else if (std::abs(EngineVoltage) < EnginePowerSource.CollectorParameters.MaxV) + Vadd *= 1.0 - dt; + else + Vadd = std::max(Vadd * (1.0 - 0.2 * dt), 0.007 * (std::abs(EngineVoltage) - (EnginePowerSource.CollectorParameters.MaxV - 100))); + Itot = inductionMotor.state.lineCurrent * (0.01 + std::min(0.99, 0.99 - Vadd)); + + EnginePower = abs(inductionMotor.state.torqueCurrent * inductionMotor.state.voltage * nPoweredAxles) / 1000; + // power inverters + UpdateInverterFrequency(); + + motorMoment = inductionMotor.state.torque * DirAbsolute; + Mw = motorMoment * Transmision.Ratio * Transmision.Efficiency; + Fw = Mw * 2.0 / wheelDiameter; + ft = Fw * nPoweredAxles * inductionMotor.inverterRatio; + inductionMotor.state.force = DirAbsolute * ft / 1000; +} + +// the force the motors give at full and at the setting (inductionMotor.forceShare), braking within the power and the force of the +// electrodynamic brake, driving within the power and the starting force +void physics::Vehicle::InductionMotorForceLimits() +{ + if (inductionMotor.forceShare < 0) + { + inductionMotor.state.fullForce = std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(inductionMotor.braking.maxForce, inductionMotor.state.absoluteMaxForce)); + inductionMotor.state.maxForce = -Sign(travelSpeed) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * inductionMotor.forceShare, inductionMotor.state.absoluteMaxForce)); + double pr = inductionMotor.forceShare; + if (inductionMotor.logForce) + pr = -log(1 - 4 * pr) / log(5); + inductionMotor.state.force = -Sign(travelSpeed) * DirAbsolute*std::min(inductionMotor.braking.maxPower * 3.6 / (Vel != 0.0 ? Vel : 0.001), std::min(-inductionMotor.braking.maxForce * pr, inductionMotor.state.absoluteMaxForce)); + if (inductionMotor.inverterRatio < 1.0) + inductionMotor.state.fullForce = 0; + //*std::min(1,(Vel-inductionMotor.braking.offSpeed)/(inductionMotor.braking.fullSpeed-inductionMotor.braking.offSpeed)) + } + else + { + inductionMotor.state.fullForce = std::min(std::min(3.6 * inductionMotor.state.powerLimit / std::max(Vel, 1.), inductionMotor.traction.startingForce - Vel * inductionMotor.traction.forceDropPerSpeed), inductionMotor.state.absoluteMaxForce); + // if(not Flat)then + inductionMotor.state.maxForce = inductionMotor.state.fullForce * inductionMotor.forceShare; + // else + // inductionMotor.state.maxForce:=std::min(inductionMotor.traction.startingForce*inductionMotor.forceShare,inductionMotor.state.fullForce); + double pr = inductionMotor.forceShare; + if (inductionMotor.logForce) + pr = log(1 + 4 * pr) / log(5); + inductionMotor.state.force = inductionMotor.state.fullForce * pr; + } +} + +// the frequency of the inverters at the motors' slip frequency, from the list of the drive or of its brake +void physics::Vehicle::UpdateInverterFrequency() +{ + auto const tmpV{std::abs(inductionMotor.state.supplyFrequency)}; + auto const useFFEDList = FFEDListSize > 0 && brakes.electrodynamic.on; + auto const list = useFFEDList ? FFEDlist : FFlist; + + if (auto const listSize = useFFEDList ? FFEDListSize : FFListSize; listSize > 0 && std::abs(inductionMotor.state.fieldCurrent) > 1.0 && tmpV > 0.0001) + { + + int i = 0; + while (i < listSize - 1 && list[i + 1].v < tmpV) + { + ++i; + } + inductionMotor.inverterFrequency = (tmpV - list[i].v) / std::max(1.0, list[i + 1].v - list[i].v) * (list[i + 1].freq - list[i].freq) + list[i].freq; + } + else + { + inductionMotor.inverterFrequency = 0.0; + } +} + +// the induction motor drive without power, or blocked by the security system +void physics::Vehicle::InductionMotorOff() +{ + for (auto &inv : inductionMotor.inverters) + { + inv.Freal = 0.0; + inv.IsActive = false; + } + Im = 0.0; + motorMoment = 0.0; + Mw = 0.0; + Fw = 0.0; + ft = 0.0; + Itot = 0.0; + inductionMotor.forceShare = 0.0; + EnginePower = 0.0; + { + inductionMotor.state = {}; + } + brakes.distributor->SetED(0.0); + inductionMotor.inverterFrequency = 0.0; //(Hamulec as TLSt).SetLBP(LocBrakePress); +} + +// ************************************************************************************************* +// Q: 20160713 +// Sprawdzenie bezpiecznika nadmiarowego +// ************************************************************************************************* +bool physics::Vehicle::FuseFlagCheck(void) const +{ + bool FFC; + + FFC = false; + if (Power > 0.01) + FFC = FuseFlag; + else // pobor pradu jezeli niema mocy + for (auto &thiscoupler : Couplers) + if (thiscoupler.CouplingFlag.HasAll(Coupling::control) && thiscoupler.Connected->Power > 0.01) + FFC = thiscoupler.Connected->FuseFlagCheck(); + + return FFC; +} + +// ************************************************************************************************* +// Q: 20160713 +// Załączenie bezpiecznika nadmiarowego +// ************************************************************************************************* +bool physics::Vehicle::FuseOn(range_t const Notify) +{ + auto const result{RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload, Notify)}; + + return result; +} + +// ************************************************************************************************* +// Q: 20160713 +// Wyłączenie bezpiecznika nadmiarowego +// ************************************************************************************************* +void physics::Vehicle::FuseOff(void) +{ + if (!FuseFlag) + { + FuseFlag = true; + eventFlag = true; + SetFlag(soundFlag, sound::relay | sound::loud); + } +} + +// resets relays assigned to specified customizable reset button +bool physics::Vehicle::UniversalResetButton(int const Button, range_t const Notify) +{ + + if (auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()}; false == lowvoltagepower) + { + return false; + } + + auto const relays{UniversalResetButtonFlag[Button]}; + if (relays == 0) + { + return false; + } + + auto const result{RelayReset(relays, Notify)}; + + return result; +} + +// resets state of specified relays +bool physics::Vehicle::RelayReset(int const Relays, range_t const Notify) +{ + + auto const lowvoltagepower{lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()}; + bool reset{false}; + + if (TestFlag(Relays, relay_t::maincircuitground) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && + (protection.config.groundStart == start_t::manual || protection.config.groundStart == start_t::manualwithautofallback) && IsMainCtrlNoPowerPos() && scndCtrlPos == 0 && DirActive != 0 && + false == equipmentFaults.HasAll(EquipmentFault::differentialRelay)) + { + // NOTE: true means the relay is operational + reset |= protection.ResetGround(lowvoltagepower); + } + + if (TestFlag(Relays, relay_t::tractionnmotoroverload) && (EngineType == TEngineType::ElectricSeriesMotor || EngineType == TEngineType::DieselElectric) && IsMainCtrlNoPowerPos() && scndCtrlPos == 0 && DirActive != 0 && + false == equipmentFaults.HasAll(EquipmentFault::differentialRelay)) + { + // NOTE: false means the relay is operational + // TODO: cleanup, flip the FuseFlag code to match other relays + // TODO: check whether the power is required, TBD, TODO: make it configurable? + reset |= FuseFlag && lowvoltagepower; + FuseFlag &= !lowvoltagepower; + } + + if (TestFlag(Relays, relay_t::primaryconverteroverload) && converter.config.overloadRelayStart == start_t::manual + // && ( false == Mains ) + && false == converter.IsAllowed()) + { + // NOTE: false means the relay is operational + // TODO: cleanup, flip the FuseFlag code to match other relays + // TODO: check whether the power is required, TBD, TODO: make it configurable? + reset |= converter.ResetOverloadRelay(lowvoltagepower); + } + + if (reset) + { + SetFlag(soundFlag, sound::relay | sound::loud); + } + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::relayReset, Relays, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return reset; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przeliczenie prędkości liniowej na obrotową +// ************************************************************************************************* +double physics::Vehicle::v2n(void) +{ + // przelicza predkosc liniowa na obrotowa + const double dmgn = 0.5; + double n; + double deltan = 0; + + n = travelSpeed / (M_PI * wheelDiameter); // predkosc obrotowa wynikajaca z liniowej [obr/s] + deltan = n - nrotValue; //"pochodna" prędkości obrotowej + /* if (slippingWheels) + if (std::abs(deltan) < 0.001) + slippingWheels = false; // wygaszenie poslizgu */ //poslizg jest w innym miejscu wygaszany też + if (slippingWheels) // nie ma zwiazku z predkoscia liniowa V + { // McZapkie-221103: uszkodzenia kol podczas poslizgu + if (deltan > dmgn && FuzzyLogic(deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::wheelWear)) // podkucie + eventFlag = true; + if (deltan < -dmgn && FuzzyLogic(-deltan, dmgn, p_slippdmg) && DamageFlag.Set(VehicleDamage::thinWheel)) // wycieranie sie obreczy + eventFlag = true; + n = nrotValue; // predkosc obrotowa nie zalezy od predkosci liniowej + } + return n; +} + +// ************************************************************************************************* +// Q: 20160714 +// Oblicza moment siły wytwarzany przez silnik +// ************************************************************************************************* +double physics::Vehicle::Momentum(double I) const +{ + // liczy moment sily wytwarzany przez silnik elektryczny} + int SP; + + SP = ScndCtrlActualPos; + if (ScndInMain && !(RList[MainCtrlActualPos].ScndAct == 255)) + SP = RList[MainCtrlActualPos].ScndAct; + + // Momentum:=mfi*I*(1-1.0/(Abs(I)/mIsat+1)); + return motor_param(SP).mfi * I * (abs(I) / (abs(I) + motor_param(SP).mIsat) - motor_param(SP).mfi0); +} + +// ************************************************************************************************* +// Q: 20160714 +// Oblicza moment siły do sterowania wzbudzeniem +// ************************************************************************************************* +double physics::Vehicle::MomentumF(double I, double Iw, int SCP) const +{ + // umozliwia dokladne sterowanie wzbudzeniem + + return motor_param(SCP).mfi * I * std::max(abs(Iw) / (abs(Iw) + motor_param(SCP).mIsat) - motor_param(SCP).mfi0, 0.); +} + +// ************************************************************************************************* +// Q: 20160713 +// Odłączenie uszkodzonych silników +// ************************************************************************************************* +bool physics::Vehicle::CutOffEngine(void) +{ + bool COE = false; // Ra: wartość domyślna, sprawdzić to trzeba + if (nPoweredAxles > 0 && CabActive == 0 && EngineType == TEngineType::ElectricSeriesMotor && DamageFlag.Clear(VehicleDamage::engine)) + { + nPoweredAxles = nPoweredAxles / 2; // bylo div czyli mod? + COE = true; + } + return COE; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przełączenie wysoki / niski prąd rozruchu +// ************************************************************************************************* +bool physics::Vehicle::MaxCurrentSwitch(bool State, range_t const Notify) +{ + auto const initialstate{motorOverloadRelayHighThreshold}; + + motorOverloadRelayHighThreshold = State; + + if (Notify != range_t::local) + { + SendCtrlToNext(VehicleCommand::maxCurrentSwitch, State ? 1 : 0, CabActive, Notify == range_t::unit ? Coupling::control | Coupling::permanent : Coupling::control); + } + + return State != initialstate; +} + +// ************************************************************************************************* +// Q: 20160713 +// Przełączenie wysoki / niski prąd rozruchu automatycznego +// ************************************************************************************************* +bool physics::Vehicle::MinCurrentSwitch(bool State) +{ + bool MCS = false; + if ((EngineType == TEngineType::ElectricSeriesMotor && IminHi > IminLo) || (trainType == train_type::emu && EngineType != TEngineType::ElectricInductionMotor)) + { + + if (State && imin == IminLo) + { + imin = IminHi; + MCS = true; + if (CabActive != 0) + SendCtrlToNext(VehicleCommand::minCurrentSwitch, 1, CabActive); + } + if (!State && imin == IminHi) + { + imin = IminLo; + MCS = true; + if (CabActive != 0) + SendCtrlToNext(VehicleCommand::minCurrentSwitch, 0, CabActive); + } + } + return MCS; +} + +// ************************************************************************************************* +// Q: 20160713 +// Sprawdzenie wskaźnika jazdy na oporach +// ************************************************************************************************* +bool physics::Vehicle::ResistorsFlagCheck(void) const +{ + bool RFC = false; + + if (Power > 0.01) + RFC = ResistorsFlag; + else // pobor pradu jezeli niema mocy + { + for (auto &thiscoupler : Couplers) + if (thiscoupler.CouplingFlag.HasAll(Coupling::control) && thiscoupler.Connected->Power > 0.01) + RFC = thiscoupler.Connected->ResistorsFlagCheck(); + } + return RFC; +} + +// ************************************************************************************************* +// Q: 20160714 +// Zwraca wartość natężenia prądu na wybranym amperomierzu. Podfunkcja do ShowCurrent. +// ************************************************************************************************* +double physics::Vehicle::ShowCurrentP(int AmpN) const +{ + int Bn; + bool Grupowy; + + // ClearPendingExceptions; + Grupowy = delayCtrlFlag && trainType == train_type::et22; // przerzucanie walu grupowego w ET22; + Bn = RList[MainCtrlActualPos].Bn; // ile równoległych gałęzi silników + + if (brakes.electrodynamic.type == dbrake_automatic && brakes.electrodynamic.on) + Bn = brakes.electrodynamic.ammeters; + if (Power > 0.01) + { + if (AmpN > 0) // podać prąd w gałęzi + { + if (Bn < AmpN || (Grupowy && AmpN == Bn - 1)) + return 0; + else // normalne podawanie pradu + return floor(abs(Im)); + } + else // podać całkowity + return floor(abs(Itot)); + } + else // pobor pradu jezeli niema mocy + { + int current = 0; + for (int b = 0; b < 2; b++) + // with Couplers[b] do + if (Couplers[b].CouplingFlag.HasAll(Coupling::control) && Couplers[b].Connected->Power > 0.01) + current = static_cast(Couplers[b].Connected->ShowCurrent(AmpN)); + return current; + } +} + +// the drive of the kind of engine of the vehicle +TractionDrive const &physics::Vehicle::Drive() const +{ + return DriveOf(EngineType); +} diff --git a/physics/consistbraking.cpp b/physics/consistbraking.cpp new file mode 100644 index 000000000..2f86603cb --- /dev/null +++ b/physics/consistbraking.cpp @@ -0,0 +1,416 @@ +/* +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 "physics/consistbraking.h" + +#include +#include +#include + +#include "physics/vehicle.h" +#include "physics/brakes.h" +#include "utilities/utilities.h" + +// the state shared by the steps of the blending +struct physics::ConsistBrakeBlending::Step { + int np { 0 }; + double masa { 0.0 }; + double FrED { 0.0 }; + double masamax { 0.0 }; + double FmaxPN { 0.0 }; + double FfulED { 0.0 }; + double FmaxED { 0.0 }; + int osie { 0 }; + double eimic { 0.0 }; + double LBR { 0.0 }; + double eim_lb { 0.0 }; + double amax { 0.0 }; + bool doorisopen { false }; + double Fzad { 0.0 }; + double FzadED { 0.0 }; + double FzadPN { 0.0 }; + float nPrzekrF { 0.f }; +}; + +// the consist with induction motors driven and braked as a whole, its braking split between the ED and the EP brakes +double physics::ConsistBrakeBlending::Update(Vehicle &Lead, std::vector const &Consist, Inputs const &Given, double const dt1) +{ + Step state; + SetControl( state, Lead, Given, dt1 ); + SumForces( state, Consist ); + ComputeDeceleration( state, Lead ); + UpdateShuntMode( state, Lead ); + ComputeDemand( state, Lead, dt1 ); + OpenLog( state, Lead ); + ComputeElectrodynamicDemand( state, Lead, dt1 ); + DistributeForces( state, Lead, Consist, dt1 ); + Record( state, Lead, Consist, dt1 ); + + lastEdDemand = state.FzadED; + return state.amax; +} + +// step 0a of the blending: the demand of the integrated controller read and passed down the consist +void physics::ConsistBrakeBlending::SetControl(Step &state, Vehicle &Lead, Inputs const &Given, double const dt1) +{ + // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania + if( Lead.Power < 1 + && Given.owner != nullptr ) { + Lead.SetMainCtrlPos(Given.owner->MainCtrlPos()*Lead.MainCtrlPosNo / std::max(1, Given.owner->MainCtrlPosNo)); + Lead.SpeedCtrlValue = Given.owner->SpeedCtrlValue; + Lead.SpeedCtrlUnit.IsActive = Given.owner->SpeedCtrlUnit.IsActive; + } + Lead.CheckEIMIC(dt1); + Lead.CheckSpeedCtrl(dt1); + + state.eimic = std::min(Lead.eimic, Lead.eimicSpeedCtrl()); + Lead.SetEimicReal(state.eimic); + // Elf: full braking at once in the lowest position, and in the emergency brake position below it + if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos() <= Lead.EIMCtrlEmergencyPositions()) + state.eimic = -1.0; + Lead.SendCtrlToNext(VehicleCommand::integratedController, std::max(0., state.eimic), Lead.CabActive); + state.LBR = std::max(-state.eimic, 0.); + state.eim_lb = Given.aiDriving || !Lead.brakes.config.independentTraxx ? 0 : Lead.eim_localbrake; +} + +// steps 1-2 of the blending: the masses and the most braking forces, pneumatic and ED, summed over the consist +void physics::ConsistBrakeBlending::SumForces(Step &state, std::vector const &Consist) +{ + auto FED { 0.0 }; + auto Frj { 0.0 }; + + // 1. ustal wymagana sile hamowania calego pociagu + // - opoznienie moze byc ustalane na podstawie charakterystyki + // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych + // + + // 2. ustal mozliwa do realizacji sile hamowania ED + // - w szczegolnosci powinien brac pod uwage rozne sily hamowania + for (auto *vehicle : Consist) + { + ++state.np; + state.masamax += + vehicle->brakes.config.maxPressureMass + + ( vehicle->brakes.config.maxPressureMass > 1.0 ? + 0.0 : + vehicle->Mass() ) + + vehicle->Mred(); + auto const Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - + vehicle->brakes.config.cylinders.springForce) * + vehicle->brakes.config.cylinders.leverRatio[0] - + vehicle->brakes.config.cylinders.slackAdjusterForce) * + vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; + state.FmaxPN += Nmax * vehicle->brakes.distributor->GetFC( + Nmax / (vehicle->NAxles() * vehicle->brakes.config.blocksPerAxle), + vehicle->brakes.blending.referenceSpeed) * + 1000; // sila hamowania pn + state.FmaxED += vehicle->lineBreaker.IsClosed() && vehicle->DirActive != 0 && vehicle->inductionMotor.inverterRatio == 1.0 && + vehicle->inductionMotor.braking.maxForce * vehicle->NPoweredAxles() > 0 ? + vehicle->inductionMotor.braking.maxForce * 1000 : + 0; // chwilowy max ED -> do rozdzialu sil + FED -= std::min(vehicle->inductionMotor.state.maxForce, 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + state.FfulED = std::min(vehicle->inductionMotor.state.fullForce, 0.0) * + 1000; // chwilowy max ED -> do rozdzialu sil + state.FrED -= std::min(vehicle->inductionMotor.state.maxForce, 0.0) * + 1000; // chwilowo realizowane ED -> do pneumatyki + Frj += std::max(vehicle->inductionMotor.state.maxForce, 0.0) * + 1000;// chwilowo realizowany napęd -> do utrzymującego + state.masa += vehicle->TotalMass(); + state.osie += vehicle->NAxles(); + } +} + +// the most deceleration of the service braking of the consist, given to the driver too +void physics::ConsistBrakeBlending::ComputeDeceleration(Step &state, Vehicle const &Lead) +{ + double RapidMult = 1.0; + if ((Lead.brakes.config.availableDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R + && Lead.brakes.delaySetting & bdelay_P) + RapidMult = Lead.brakes.config.rapidRatio; + + state.amax = RapidMult * std::min(state.FmaxPN / state.masamax, Lead.brakes.blending.maxDeceleration); + +} + +// the doors open or closed, and from them, the demand and the speed the shunting mode (the holding brake) of the consist +void physics::ConsistBrakeBlending::UpdateShuntMode(Step &state, Vehicle &Lead) +{ + state.doorisopen = + false == Lead.Doors.instances[VehicleSide::left].is_closed + || false == Lead.Doors.instances[VehicleSide::right].is_closed + || ( Lead.Doors.permit_needed + && ( Lead.Doors.instances[ VehicleSide::left ].open_permit + || Lead.Doors.instances[ VehicleSide::right ].open_permit ) ); + state.doorisopen &= !(Lead.brakes.spring.releasesParkingWithDoorOpen && Lead.brakes.spring.isActive); + + if (Lead.Vel < 0.5 && (state.eimic < 0 || state.doorisopen || Lead.brakes.distributor->GetEDBCP())) + { + Lead.ShuntMode = true; + } + if (Lead.ShuntMode) + { + Lead.ShuntModeAllow = false == state.doorisopen && + state.LBR < 0.01; + } + if( Lead.Vel > 1 && false == state.doorisopen ) + { + Lead.ShuntMode = false; + Lead.ShuntModeAllow = Lead.brakes.cylinderPressure > 0.2 && + state.LBR < 0.01; + } +} +// the braking force demanded of the whole consist +void physics::ConsistBrakeBlending::ComputeDemand(Step &state, Vehicle &Lead, double const dt1) +{ + state.Fzad = state.amax * state.LBR * state.masa; + if ((Lead.brakes.HandlePosition() == Lead.brakes.driverValve->GetPos(bh_EB) + && Lead.inductionMotor.braking.cylinderPressureGain < 0.001) || + Lead.brakes.emergencyValve.flow > 0) + state.Fzad = state.amax * state.masa; //pętla bezpieczeństwa - pełne służbowe + if (Lead.ScndS && + Lead.Vel > Lead.inductionMotor.braking.fullSpeed && state.FmaxED > 0) + { + state.Fzad = std::min(state.LBR * state.FmaxED, state.FfulED); + } + // the holding brake lets go once power has been demanded for its delay (SBDReleaseDelay, none by default) + auto const holdingbrakereleased { Lead.UpdateStopBrakeRelease( state.eimic, dt1 ) }; + if (Lead.ShuntMode && false == holdingbrakereleased || state.doorisopen /*|| + (Lead.V() * Lead.DirAbsolute < -0.2)*/) + { + auto const sbd { ( Lead.brakes.spring.isActive && Lead.brakes.spring.releasesParking ? 0.0 : Lead.brakes.holding.deceleration ) }; + state.Fzad = std::max( state.Fzad, sbd * state.masa ); + } +} + +// the log of the braking of the consist opened, once it brakes while moving +void physics::ConsistBrakeBlending::OpenLog(Step const &state, Vehicle const &Lead) +{ + if (state.Fzad > 1 && !log.is_open() && Lead.Vel > 1) + { + log.open( + "MEDLOGS/" + Lead.Name + "_" + std::to_string( ++logCount ) + ".csv", + std::ios::in | std::ios::out | std::ios::trunc ); + log << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; + for(int k=1;k<=state.np;k++) + { + log << "\tBP" << k; + } + log << "\n"; + log.flush(); + logInactiveTime = 0; + logTime = 0; + } +} + +// the part of the demand the ED brake takes, brought in with a delay, and the rest left to the pneumatic brake +void physics::ConsistBrakeBlending::ComputeElectrodynamicDemand(Step &state, Vehicle &Lead, double const dt1) const +{ + state.FzadED = 0.0; + if( state.LBR > Lead.brakes.blending.minEdDemand + && ( Lead.brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ? + (Lead.brakes.operatingMode & bom_MED) != 0 : + Lead.EpFuse() ) ) { + state.FzadED = std::min( state.Fzad, state.FmaxED ); + } + /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia + if (Lead.EIMCtrlType == 2 && Lead.MainCtrlPos() < 2 && Lead.eimic > -0.999) + { + FzadED = std::min(FzadED, lastEdDemand); + } //*/ + //opoznienie wdrazania ED + if (state.FzadED > lastEdDemand) + { + if (Lead.brakes.blending.edDelayTimer <= 0) { + Lead.brakes.blending.edDelayTimer += dt1; + if (Lead.brakes.blending.edDelayTimer > 0) { + + } + else { + state.FzadED = std::min(state.FzadED, lastEdDemand); + } + } + else + { + state.FzadED = std::min(state.FzadED, lastEdDemand); + Lead.brakes.blending.edDelayTimer = state.FrED > 0 ? -Lead.brakes.blending.edNextDelay : -Lead.brakes.blending.edFirstDelay; + } + } + if (Lead.brakes.HandlePosition() == Lead.brakes.driverValve->GetPos(bh_EB) + && Lead.inductionMotor.braking.cylinderPressureGain < 0.001) + state.FzadED = 0; //pętla bezpieczeństwa - bez ED + state.FzadPN = state.Fzad - state.FrED * Lead.brakes.blending.edForceFactor; +} +// steps 3-6 of the blending: the ED and the pneumatic braking forces set to the vehicles of the consist +void physics::ConsistBrakeBlending::DistributeForces(Step &state, Vehicle const &Lead, std::vector const &Consist, double const dt1) +{ + std::vector PrzekrF( state.np ); + state.nPrzekrF = 0; + bool test = true; + std::vector FzED( state.np ); + std::vector FzEP( state.np ); + std::vector FmaxEP( state.np ); + // 3. ustaw pojazdom sile hamowania ED + // - proporcjonalnie do mozliwosci + + // 4. ustal potrzebne dohamowanie pneumatyczne + // - od sily zadanej trzeba odjac realizowana przez ED + // 5. w razie potrzeby wlacz hamulec utrzymujacy + // - gdy zahamowany ma ponizej 2 km/h + // 6. ustaw pojazdom sile hamowania ep + // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak + // bedzie, tak bedzie dobrze + float Fpoj = 0; // Lead.CabOccupied() < 0 + ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa + // 1. najpierw daj kazdemu tyle samo + int i = 0; + for (auto *vehicle : Consist) + { + auto const Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - + vehicle->brakes.config.cylinders.springForce) * + vehicle->brakes.config.cylinders.leverRatio[0] - + vehicle->brakes.config.cylinders.slackAdjusterForce) * + vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; + FmaxEP[i] = Nmax * + vehicle->brakes.distributor->GetFC( + Nmax / (vehicle->NAxles() * vehicle->brakes.config.blocksPerAxle), + vehicle->brakes.blending.referenceSpeed) * + 1000; // sila hamowania pn + + PrzekrF[i] = false; + FzED[i] = state.FmaxED > 0 ? state.FzadED / state.FmaxED : 0; + vehicle->SetAnPos(Lead.ScndS ? state.LBR : FzED[i]); + FzEP[ i ] = static_cast( state.FzadPN * vehicle->NAxles() ) / static_cast( state.osie ); + ++i; + vehicle->ShuntMode = Lead.ShuntMode; + vehicle->ShuntModeAllow = Lead.ShuntModeAllow; + } + while (test) + { + test = false; + i = 0; + float przek = 0; + for (auto *vehicle : Consist) + { + if (FzEP[i] > 0.01 && + FzEP[i] > vehicle->TotalMass() * vehicle->inductionMotor.braking.maxEpDeceleration + std::min(vehicle->inductionMotor.state.maxForce, 0.) * 1000 && + !PrzekrF[i]) + { + float przek1 = -std::min(vehicle->inductionMotor.state.maxForce, 0.) * 1000 + + FzEP[i] - + vehicle->TotalMass() * + vehicle->inductionMotor.braking.maxEpDeceleration * 0.999; + PrzekrF[i] = true; + test = true; + state.nPrzekrF++; + przek1 = std::min(przek1, FzEP[i]); + FzEP[i] -= przek1; + if (FzEP[i] < 0) + FzEP[i] = 0; + przek += przek1; + } + ++i; + } + i = 0; + przek = przek / (state.np - state.nPrzekrF); + for (auto *vehicle : Consist) + { + if (!PrzekrF[i]) + { + FzEP[i] += przek; + } + ++i; + } + } + i = 0; + for (auto *vehicle : Consist) + { + float Nmax = ((vehicle->brakes.config.pressureToForce * vehicle->brakes.config.maxCylinderPressure[0] - + vehicle->brakes.config.cylinders.springForce) * + vehicle->brakes.config.cylinders.leverRatio[0] - + vehicle->brakes.config.cylinders.slackAdjusterForce) * + vehicle->brakes.config.cylinders.count * vehicle->brakes.config.cylinders.riggingEfficiency; + if (state.FrED > 0.1) + vehicle->brakes.blending.epCorrectionTimer = 0; + else + vehicle->brakes.blending.epCorrectionTimer += dt1; + bool EPVC = vehicle->brakes.blending.epCorrection && (vehicle->brakes.blending.epCorrectionTime < 0 || vehicle->brakes.blending.epCorrectionTimer < vehicle->brakes.blending.epCorrectionTime); + float VelC = EPVC ? safe_clamp(vehicle->Vel, vehicle->brakes.blending.minSpeed, vehicle->brakes.blending.maxSpeed) : vehicle->brakes.blending.referenceSpeed;//korekcja EP po prędkości + float FmaxPoj = Nmax * + vehicle->brakes.distributor->GetFC( + Nmax / (vehicle->NAxles() * vehicle->brakes.config.blocksPerAxle), VelC) * + 1000; // sila hamowania pn + vehicle->brakes.SetIndependentPositionEim(FzEP[i] / FmaxPoj); + if (vehicle->brakes.IndependentPositionEim()>0.009) + if (vehicle->brakes.config.pressureToForce * vehicle->brakes.config.cylinders.leverRatio[0] * + vehicle->brakes.config.maxCylinderPressure[0] != 0) + { + float x = (vehicle->brakes.config.cylinders.slackAdjusterForce / vehicle->brakes.config.cylinders.leverRatio[0] + + vehicle->brakes.config.cylinders.springForce) / (vehicle->brakes.config.pressureToForce * + vehicle->brakes.config.maxCylinderPressure[0]); + vehicle->brakes.SetIndependentPositionEim(x + (1 - x) * vehicle->brakes.IndependentPositionEim()); + } + else + vehicle->brakes.SetIndependentPositionEim(vehicle->brakes.IndependentPositionEim()); + else + vehicle->brakes.SetIndependentPositionEim(0); + if (vehicle->brakes.config.independentTraxx) + { + vehicle->eim_localbrake = state.eim_lb; + vehicle->brakes.SetIndependentPositionEim(std::max(vehicle->brakes.IndependentPositionEim(), state.eim_lb)); + } + ++i; + } +} + +// the state of the blending kept for the debug screen, and written to the log of the braking while it is open +void physics::ConsistBrakeBlending::Record(Step const &state, Vehicle const &Lead, std::vector const &Consist, double const dt1) +{ + figures[0] = state.masa*0.001; + figures[1] = state.amax; + figures[2] = state.Fzad*0.001; + figures[3] = state.FmaxPN*0.001; + figures[4] = state.FmaxED*0.001; + figures[5] = state.FrED*0.001; + figures[6] = state.FzadPN*0.001; + figures[7] = state.nPrzekrF; + + if (log.is_open()) + { + log << logTime << "\t" << Lead.Vel << "\t" << state.masa*0.001 << "\t" << state.osie << "\t" << state.FmaxPN*0.001 << "\t" << state.FmaxED*0.001 << "\t" + << state.FfulED*0.001 << "\t" << state.FrED*0.001 << "\t" << state.Fzad*0.001 << "\t" << state.FzadED*0.001 << "\t" << state.FzadPN*0.001; + for (auto *vehicle : Consist) + { + log << "\t" << vehicle->brakes.cylinderPressure; + } + log << "\n"; + if (floor(logTime + dt1) > floor(logTime)) + { + log.flush(); + } + logTime += dt1; + + if (Lead.Vel < 0.1 || Lead.MainCtrlPowerPos() > 0) + { + logInactiveTime += dt1; + } + else + { + logInactiveTime = 0; + } + if (logInactiveTime > 5) + { + log.flush(); + log.close(); + } + + } +} + diff --git a/physics/consistbraking.h b/physics/consistbraking.h new file mode 100644 index 000000000..bef61ff4c --- /dev/null +++ b/physics/consistbraking.h @@ -0,0 +1,68 @@ +/* +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 braking of a consist driven by induction motors as a whole: the vehicle with the driver blends the electrodynamic +// (ED) brakes of the consist with its electropneumatic (EP) ones (the MED of the .fiz), and sets the holding brake. +// it works on the physics of the vehicles alone, given in the order of the consist from the occupied cab + +#pragma once + +#include +#include +#include +#include +#include + +namespace physics +{ + +class Vehicle; + +class ConsistBrakeBlending +{ + public: + // what the blending needs to know beside the vehicles + struct Inputs + { + // the vehicle whose controller an unpowered lead vehicle (a driving trailer) follows, nullptr when none + Vehicle const *owner{nullptr}; + bool aiDriving{false}; // the AI drives: it brakes the locomotive brake of a TRAXX-like handle itself + }; + + // the step of the blending, from the lead vehicle over its consist (the lead among them). returns the most + // deceleration of the service braking of the consist, which the driver goes by + double Update(Vehicle &Lead, std::vector const &Consist, Inputs const &Given, double dt); + + // the figures of the last step for the debug screen, in the order of Labels + static constexpr std::array Labels{"masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: "}; + std::array const &Figures() const { return figures; } + + private: + struct Step; + + static void SetControl(Step &State, Vehicle &Lead, Inputs const &Given, double dt); + static void SumForces(Step &State, std::vector const &Consist); + static void ComputeDeceleration(Step &State, Vehicle const &Lead); + static void UpdateShuntMode(Step &State, Vehicle &Lead); + static void ComputeDemand(Step &State, Vehicle &Lead, double dt); + void OpenLog(Step const &State, Vehicle const &Lead); + void ComputeElectrodynamicDemand(Step &State, Vehicle &Lead, double dt) const; + static void DistributeForces(Step &State, Vehicle const &Lead, std::vector const &Consist, double dt); + void Record(Step const &State, Vehicle const &Lead, std::vector const &Consist, double dt); + + double lastEdDemand{0.0}; // the demand of the ED brake of the step before [N] + std::array figures{}; + // the log of the braking (MEDLOGS/), opened while the consist brakes moving + std::ofstream log; + double logTime{0.0}; + double logInactiveTime{0.0}; + int logCount{0}; +}; + +} // namespace physics diff --git a/McZapkie/couplerphysics.cpp b/physics/couplerphysics.cpp similarity index 98% rename from McZapkie/couplerphysics.cpp rename to physics/couplerphysics.cpp index f6a226b55..ca293f69c 100644 --- a/McZapkie/couplerphysics.cpp +++ b/physics/couplerphysics.cpp @@ -8,7 +8,7 @@ http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" -#include "couplerphysics.h" +#include "physics/couplerphysics.h" #include #include @@ -235,7 +235,7 @@ pair_result update_pair(end_parameters const &First, end_parameters const &Secon else { State.draw_gear.reset(); } - auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap, -Input.gap_rate)}; + auto const pushed{press(buffers_of(First, Second, Input.adapter), State.buffers, -Input.gap - std::max(Input.crush, 0.0), -Input.gap_rate)}; result.tension = pulled.force; result.compression = pushed.force; diff --git a/McZapkie/couplerphysics.h b/physics/couplerphysics.h similarity index 97% rename from McZapkie/couplerphysics.h rename to physics/couplerphysics.h index 47789aba2..d7278cf63 100644 --- a/McZapkie/couplerphysics.h +++ b/physics/couplerphysics.h @@ -4,7 +4,7 @@ #include // the physical model of the coupling of two vehicles, used with couplerphysics set in eu07.ini (the legacy model of -// TMoverParameters::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive +// physics::Vehicle::CouplerForce() otherwise). each vehicle end brings its buffers and its draw gear: progressive // springs with friction hysteresis, pressed in series against those of the other end. the coupling has play (slack) // in tension, or pulls the buffers in when its screw is tightened, and its steel link stretches for good past its // yield force and breaks at its ultimate one, under a steady pull or the jerk of a run-out of the slack @@ -112,6 +112,7 @@ struct pair_input { bool coupled{false}; bool adapter{false}; // an adapter on either end: the buffers don't meet, the coupler takes the push alone bool damage{false}; // the link can stretch and break (crash damage on) + double crush{0.0}; // the ends of both crushed for good (collision.h), the buffers meet that much closer [m] }; struct pair_result { diff --git a/physics/derailment.cpp b/physics/derailment.cpp new file mode 100644 index 000000000..b6962caaf --- /dev/null +++ b/physics/derailment.cpp @@ -0,0 +1,324 @@ +/* +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 "physics/derailment.h" + +#include +#include +#include + +namespace derailment { + +namespace { + +// a curve with a radius under this is taken for a straight track [m] +constexpr double straight{1e-3}; + +bool curved(double const Radius) { + return std::abs(Radius) > straight; +} + +// the height the lateral force on the body acts at, with the lean of the body on its suspension [m] +double leaning_height(double const CentreOfGravity, suspension const &Suspension) { + return CentreOfGravity + Suspension.flexibility * std::max(0.0, CentreOfGravity - Suspension.roll_centre); +} + +bool has(int const Flags, int const Flag) { + return (Flags & Flag) != 0; +} + +// the acceleration [m/s2] of what moves with the track sideways, besides the curve: the sway of the body and the +// short waves of an uneven track +double dynamic_acceleration(track_state const &Track, double const Velocity) { + return body_vibration(Velocity) + uneven_share * Velocity * Velocity * std::abs(Track.uneven_curvature); +} + +// the sideways force of the couplings of both ends on the vehicle, positive out of the curve [N]: pushed in, the +// ends go out of the curve, pulled out, they go into it +double coupling_force(vehicle_state const &Vehicle, track_state const &Track) { + auto force{0.0}; + for (auto const &end : Vehicle.ends) { + force += end.compression * std::sin(coupling_angle(Vehicle.length, end.other_length, Track.radius)); + } + return force; +} + +} // namespace + +double contact_spacing(double const Gauge) { + return Gauge + rail_head_width; +} + +double default_centre_of_gravity(double const BodyHeight, vehicle_class const Class) { + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + return body * (Class == vehicle_class::powered ? 0.38 : 0.35); +} + +double loaded_centre_of_gravity(double const EmptyHeight, double const EmptyMass, double const LoadMass, double const LoadShare, double const Floor, double const BodyHeight) { + if (LoadMass <= 0.0 || EmptyMass + LoadMass <= 0.0) { + return EmptyHeight; + } + auto const body{BodyHeight > 2.0 ? BodyHeight : 4.0}; + // a floor not given (or the older meaning of the keys) is that of a wagon + auto const floor{Floor > 0.3 ? Floor : 1.2}; + auto const load{floor + 0.5 * std::max(0.0, body - floor) * std::clamp(LoadShare, 0.0, 1.0)}; + return (EmptyHeight * EmptyMass + load * LoadMass) / (EmptyMass + LoadMass); +} + +double unbalanced_acceleration(double const Velocity, double const Radius, double const Cant) { + auto const cant{gravity * std::sin(std::abs(Cant))}; + if (false == curved(Radius)) { + return -cant; + } + return Velocity * Velocity / std::abs(Radius) - cant; +} + +double line_curvature(track_state const &Track) { + auto const buckle{buckle_share * Track.buckle_curvature}; + if (false == curved(Track.radius)) { + return std::abs(buckle); + } + return 1.0 / std::abs(Track.radius) + buckle; +} + +double line_acceleration(track_state const &Track, double const Velocity) { + if (Track.buckle_curvature == 0.0) { + return unbalanced_acceleration(Velocity, Track.radius, Track.cant); + } + // bent against the curve, out of the bend is into the curve, where the cant leans the vehicle too + return Velocity * Velocity * line_curvature(Track) - gravity * std::sin(std::abs(Track.cant)); +} + +double unloading_ratio(double const Acceleration, double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return 2.0 / ContactSpacing * std::abs(Acceleration) / gravity * leaning_height(CentreOfGravity, Suspension); +} + +double overturning_acceleration(double const CentreOfGravity, double const ContactSpacing, suspension const &Suspension) { + return gravity * ContactSpacing / (2.0 * leaning_height(CentreOfGravity, Suspension)); +} + +double body_vibration(double const Velocity) { + return vibration * std::min(1.0, std::abs(Velocity) / (100.0 / 3.6)); +} + +double overturning_speed(double const Radius, double const Cant, double const CentreOfGravity, double const Gauge) { + if (false == curved(Radius)) { + return 0.0; + } + vehicle_state vehicle; + vehicle.mass = 1.0; + vehicle.centre_of_gravity = CentreOfGravity; + track_state track; + track.radius = Radius; + track.cant = Cant; + track.gauge = Gauge; + auto const spacing{contact_spacing(Gauge)}; + // the unloading grows with the speed: halve the range until the speed of D = 1 is found + auto low{0.0}; + auto high{200.0}; + for (int iteration = 0; iteration < 60; ++iteration) { + auto const middle{0.5 * (low + high)}; + auto const acceleration{body_acceleration(vehicle, track, middle)}; + // below the balancing speed the cant leans the vehicle the other way + auto const outwards{unbalanced_acceleration(middle, Radius, Cant) > 0.0}; + if (outwards && unloading_ratio(acceleration, CentreOfGravity, spacing) >= 1.0) { + high = middle; + } + else { + low = middle; + } + } + return high; +} + +double nadal_limit(double const FlangeAngle, double const Friction) { + auto const slope{std::tan(FlangeAngle)}; + return (slope - Friction) / (1.0 + Friction * slope); +} + +track_condition condition_of(track_state const &Track) { + track_condition condition; + // the flags make the ride rougher: the sway of the vehicles and the short waves of the track grow, the curve and + // the cant stay what they are. sceneries set them for the jolts of a worn track (damage 31 on all of line 107), + // not for broken rails. a loose rail sways the vehicles 1.4 times as much, as the legacy criterion had it + condition.lateral = 1.0 + 0.4 * has(Track.damage, track_damage::freerail) + 0.5 * has(Track.damage, track_damage::railbend) + 0.1 * has(Track.damage, track_damage::railwear) + + 0.1 * has(Track.damage, track_damage::thinrail); + // the twist of the track lifts a wheel: 1 % of its load for each mm of cross level, up to the 0.6 the twist test + // of EN 14363 lets the load drop by + condition.unloading = std::min(0.6, 0.01 * std::max(0.0, Track.uneven_cross)); + return condition; +} + +double coupling_angle(double const Length, double const OtherLength, double const Radius) { + if (false == curved(Radius) || OtherLength <= 0.0) { + return 0.0; + } + return (Length + OtherLength) / (4.0 * std::abs(Radius)); +} + +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + wheel_forces result; + if (Vehicle.mass <= 0.0) { + return result; + } + auto const axles{static_cast(std::max(Vehicle.axles, 1))}; + auto const condition{condition_of(Track)}; + auto const spacing{contact_spacing(Track.gauge)}; + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + auto const staticload{Vehicle.mass * gravity / (2.0 * axles)}; + + auto const inertia{Vehicle.mass * line_acceleration(Track, Velocity)}; + auto const couplings{coupling_force(Vehicle, Track)}; + auto const quasistatic{inertia + couplings}; + // the sway and the uneven track push the worst way: towards the rail the vehicle already leans on + auto const direction{quasistatic >= 0.0 ? 1.0 : -1.0}; + auto const dynamic{Vehicle.mass * dynamic_acceleration(Track, Velocity) * condition.lateral}; + result.lateral = direction * (std::abs(quasistatic) + dynamic); + + // the leading axle meets the rail at an angle in a curve, the creep force of its inner wheel at most the friction + auto guiding{0.0}; + if (auto const curvature{std::abs(line_curvature(Track))}; curvature > 0.0) { + auto const attack{0.5 * Vehicle.axle_base * curvature}; + guiding = tread_friction * staticload * std::min(1.0, attack / saturated_attack); + } + result.y = std::abs(result.lateral) / axles + guiding; + + // the lateral forces at their heights move the load onto the wheels they push towards + auto const moment{direction * (inertia * height + couplings * buffer_height) + dynamic * height}; + auto const shift{moment / (spacing * axles)}; + result.q = std::max(0.0, (staticload + shift) * (1.0 - condition.unloading)); + return result; +} + +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + if (Vehicle.mass <= 0.0) { + return 0.0; + } + auto const height{leaning_height(Vehicle.centre_of_gravity, suspension{})}; + // the couplings pull at the height of the buffers: as much of a lean as their moment gives + auto const moment{Vehicle.mass * line_acceleration(Track, Velocity) * height + coupling_force(Vehicle, Track) * buffer_height}; + return std::abs(moment) / (Vehicle.mass * height) + dynamic_acceleration(Track, Velocity) * condition_of(Track).lateral; +} + +bool stretch::update(bool const Holds, double const Distance, double const Window) { + if (false == Holds) { + m_distance = 0.0; + return false; + } + m_distance += std::abs(Distance); + return m_distance >= Window; +} + +verdict monitor::update(vehicle_state const &Vehicle, track_state const &Track, double const Velocity, double const Distance) { + verdict result; + result.acceleration = body_acceleration(Vehicle, Track, Velocity); + result.unloading = unloading_ratio(result.acceleration, Vehicle.centre_of_gravity, contact_spacing(Track.gauge)); + result.flange_ratio = flange_forces(Vehicle, Track, Velocity).ratio(); + auto const overturns{m_overturning.update(result.unloading >= 1.0, Distance)}; + auto const climbs{m_climbing.update(result.flange_ratio >= climbing_limit, Distance)}; + if (overturns) { + result.result = outcome::overturned; + } + else if (climbs) { + result.result = outcome::off_rails; + } + return result; +} + +void monitor::reset() { + m_overturning.reset(); + m_climbing.reset(); +} + +double sliding_friction(outcome const Outcome) { + switch (Outcome) { + case outcome::off_rails: + return off_rails_friction; + case outcome::overturned: + return overturned_friction; + default: + return 0.0; + } +} + +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track) { + auto const climbs = [&](double const Velocity) { return flange_forces(Vehicle, Track, Velocity).ratio() >= climbing_limit; }; + // from the speed the cant balances, where the vehicle starts to lean on the outer rail + auto const balancing{curved(Track.radius) ? std::sqrt(gravity * std::abs(Track.radius) * std::sin(std::abs(Track.cant))) : 0.0}; + if (climbs(balancing)) { + return balancing; + } + // in steps of 1 m/s up to the first speed it climbs at, which needn't hold above it, then halving the step + constexpr double fastest{200.0}; + auto const steps{static_cast(std::ceil(fastest - balancing))}; + for (auto step = 0; step < steps; ++step) { + auto low{balancing + step}; + auto high{std::min(low + 1.0, fastest)}; + if (false == climbs(high)) { + continue; + } + for (int iteration = 0; iteration < 30; ++iteration) { + auto const middle{0.5 * (low + high)}; + (climbs(middle) ? high : low) = middle; + } + return high; + } + return std::nullopt; +} + +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity, std::string_view const TrackName) { + auto const cant{1000.0 * contact_spacing(Track.gauge) * std::sin(std::abs(Track.cant))}; + return std::format("{} at {:.0f} km/h on track {}, curve radius {:.0f} m, cant {:.0f} mm: lateral acceleration {:.2f} m/s2, wheel unloading {:.2f}, Y/Q {:.2f}" + " (mass {:.1f} t, centre of gravity {:.2f} m, couplings pushing {:.0f} / {:.0f} kN, track damage {}, cross level {:.0f} mm)", + Verdict.result == outcome::overturned ? "overturned" : "derailed, the flange climbed the rail", std::abs(Velocity) * 3.6, TrackName.empty() ? "(none)" : TrackName, + std::abs(Track.radius), cant, Verdict.acceleration, Verdict.unloading, Verdict.flange_ratio, Vehicle.mass / 1000.0, Vehicle.centre_of_gravity, + Vehicle.ends[0].compression / 1000.0, Vehicle.ends[1].compression / 1000.0, Track.damage, Track.uneven_cross); +} + +std::optional trusted_speed(double const Limit) { + if (Limit < 0.0) { + return std::nullopt; + } + return Limit * trusted_limit_factor + trusted_limit_margin; +} + +bool from_track_alone(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity) { + auto vehicle{Vehicle}; + vehicle.ends = {}; + track_state track; + track.radius = Track.radius; + track.cant = Track.cant; + track.gauge = Track.gauge; + switch (Verdict.result) { + case outcome::overturned: + return unloading_ratio(body_acceleration(vehicle, track, Velocity), vehicle.centre_of_gravity, contact_spacing(track.gauge)) >= 1.0; + case outcome::off_rails: + return flange_forces(vehicle, track, Velocity).ratio() >= climbing_limit; + default: + return false; + } +} + +verdict limited_verdict(verdict const &Verdict, bool const TrackAlone, double const Velocity, double const Limit) { + auto const trusted{trusted_speed(Limit)}; + if (Verdict.result == outcome::none || false == TrackAlone || false == trusted.has_value() || std::abs(Velocity) * 3.6 > *trusted) { + return Verdict; + } + auto result{Verdict}; + result.result = outcome::none; + return result; +} + +std::string held_back_report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double const Velocity, double const Limit, std::string_view const TrackName) { + return std::format("held on the rails on track {} under its trusted speed of {:.0f} km/h (speed limit {:.0f} km/h, too high for the curve: a defect of the scenery): {}", + TrackName.empty() ? "(none)" : TrackName, trusted_speed(Limit).value_or(0.0), Limit, report(Verdict, Vehicle, Track, Velocity, TrackName)); +} + +} // namespace derailment diff --git a/physics/derailment.h b/physics/derailment.h new file mode 100644 index 000000000..d29fbc852 --- /dev/null +++ b/physics/derailment.h @@ -0,0 +1,258 @@ +/* +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 + +#include +#include +#include +#include + +// the criteria of a vehicle leaving the rails, as plain functions of what the vehicle and the track under it are +// like, so the collisions and the buckled track can use them as well as the speed in a curve does +// (physics.derailment new in eu07.ini, see physics::Vehicle::check_derailment()). two ways off the rails: +// +// overturning: the lateral acceleration the cant doesn't balance, a = v^2 / R - g * sin(cant), takes the load off the +// inner wheels; the unloading ratio D = dQ / Q = 2 / s * a / g * (h + s_flex * (h - h_c)) reaches 1 when they lift. +// s the distance between the contact points of the wheels, h the height of the centre of gravity, s_flex and h_c the +// flexibility coefficient and the roll centre height of the suspension, which lets the body lean out of the curve +// (the reference values of the kinematic gauge, EN 15273-2 / UIC 505-1). the body sways on top of that: a lateral +// vibration of 0.05 g at speed (as Kunieda's overturning formula of the Japanese railways adds one) and what the +// uneven track adds +// flange climbing: the ratio of the lateral to the vertical force of the flanging wheel, Y / Q, over Nadal's limit +// (tan d - mu) / (1 + mu * tan d). Y from the force the cant doesn't balance and the sideways part of the forces of +// the couplings in the curve, shared by the axles, plus the guiding force of the leading axle under its angle of +// attack; Q the static wheel load, with what the lateral forces at their heights move onto the wheel +// +// either has to hold over a stretch of track, not at an instant: EN 14363 takes the Y / Q of a 2 m sliding window, so +// a peak shorter than that, or the length of a simulation step, doesn't derail the vehicle +namespace derailment { + +inline constexpr double gravity{9.81}; // [m/s2] + +// the distance between the contact points of the wheels of a wheelset [m]: the gauge and the width of the rail head +// (1.5 m on the standard gauge) +inline constexpr double rail_head_width{0.065}; +double contact_spacing(double Gauge); + +// the suspension of the body, the reference vehicle of the kinematic gauge (EN 15273-2, UIC 505-1) +struct suspension { + double flexibility{0.4}; // roll of the body to the angle of the force on it, s0 + double roll_centre{0.5}; // height of the roll centre above the rail [m], h_c0 +}; + +// ---- the centre of gravity + +// what the vehicle is, for its centre of gravity when its definition gives none +enum class vehicle_class { + powered, // a locomotive, a motor car of a unit + unpowered // a coach, a wagon +}; +// height of the centre of gravity of the empty vehicle above the rail [m], from the height of the body: 0.38 of it for +// a locomotive or a motor car, 0.35 for a coach or a wagon (EU07: 1.65 m, the 430W coal wagon: 1.13 m, a 4 m high +// coach: 1.4 m). a body height up to 2 m in the definition is the height of the floor, the older meaning of the key: +// a 4 m high body is taken then +double default_centre_of_gravity(double BodyHeight, vehicle_class Class); +// the load raises it: the load lies on the floor, its centre half way up to the share of the height of the body +// above the floor it fills (the share of the load it can take), and the heights weigh with the masses [m] +double loaded_centre_of_gravity(double EmptyHeight, double EmptyMass, double LoadMass, double LoadShare, double Floor, double BodyHeight); + +// ---- overturning + +// the lateral acceleration [m/s2] the cant doesn't balance, positive out of the curve: v^2 / R - g sin(cant). the +// sign of the radius and of the cant is left out: the cant lifts the outer rail of a curve. on a straight piece of a +// transition the cant leans the vehicle into the curve to come +double unbalanced_acceleration(double Velocity, double Radius, double Cant); +// D = dQ / Q of the wheels on the inner side, at the lateral acceleration [m/s2] +double unloading_ratio(double Acceleration, double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// the lateral acceleration [m/s2] which lifts the inner wheels off the rail (D = 1) +double overturning_acceleration(double CentreOfGravity, double ContactSpacing, suspension const &Suspension = {}); +// lateral vibration of the body on a good track [m/s2], growing with the speed up to 100 km/h +inline constexpr double vibration{0.05 * gravity}; +double body_vibration(double Velocity); +// the speed [m/s] at which the vehicle overturns in a curve of the radius [m] and the cant [rad], on a good track +double overturning_speed(double Radius, double Cant, double CentreOfGravity, double Gauge); + +// ---- flange climbing + +// Nadal's limit of Y / Q for the flange angle [rad] and the friction of the flange on the rail +double nadal_limit(double FlangeAngle, double Friction); +// 70 degrees, the flange of the S1002 and the Polish 1:40 profiles +inline constexpr double flange_angle{1.2217304763960306}; +// 1.2: Nadal with 70 degrees and a friction of 0.36 on a dry rail; the limit of EN 14363 for the flange climbing test +// in a tight curve on a twisted track. its 0.8 for the tests on the line is that with a margin for the acceptance of +// a vehicle, and a simulator wants the derailment itself +inline constexpr double climbing_limit{1.2}; +// friction of the tread of the inner wheel of the leading axle, the guiding force it gives under the angle of attack +inline constexpr double tread_friction{0.3}; +// angle of attack [rad] at which the creep force of the tread saturates +inline constexpr double saturated_attack{0.005}; +// height of the buffers and the couplings above the rail [m] (UIC: 940 to 1065 mm) +inline constexpr double buffer_height{1.0}; + +// one end of the vehicle in a train +struct end_force { + double compression{0.0}; // force of the coupling along the vehicle, pushing in [N]; negative pulls out + double other_length{0.0}; // length of the vehicle at that end [m], 0 without one +}; + +// the vehicle as the flange climbing sees it +struct vehicle_state { + double mass{0.0}; // with the load, without the rotating masses [kg] + int axles{4}; + double length{0.0}; // over the buffers [m] + double axle_base{0.0}; // the wheelbase of a bogie, or of the vehicle without bogies [m] + double centre_of_gravity{1.5}; // [m] + std::array ends{}; +}; + +// the dtrack_* flags of the track (vehicle.h) the criteria look at +namespace track_damage { +inline constexpr int railwear{2}; +inline constexpr int freerail{4}; +inline constexpr int thinrail{8}; +inline constexpr int railbend{16}; +} // namespace track_damage + +// the track under the vehicle +struct track_state { + double radius{0.0}; // [m], 0 on a straight one + double cant{0.0}; // [rad] + double gauge{1.435}; // [m] + double uneven_curvature{0.0}; // the lateral curvature of the unevenness under the vehicle [1/m] + double uneven_cross{0.0}; // the cross level unevenness of the track [mm] + // the curvature a buckle of the track adds under the vehicle [1/m], see world/TrackBuckle.h: positive bending with + // the curve, on a straight track either way + double buckle_curvature{0.0}; + int damage{0}; // dtrack_* flags +}; + +// what the state of the track does to the lateral forces and the wheel loads +struct track_condition { + double lateral{1.0}; // multiplier of the sway of the vehicle and of the short waves of an uneven track + double unloading{0.0}; // share of the wheel load the twist of the track (its cross level) takes off +}; +track_condition condition_of(track_state const &Track); +// share of the vehicle that follows the short waves of an uneven track: the wheelsets and the bogies, the body not +inline constexpr double uneven_share{0.3}; +// and the long wave of a buckle, which the body follows whole, as it does the curve +inline constexpr double buckle_share{1.0}; +// the curvature of the line under the vehicle [1/m], positive towards the centre of the curve: the curve, and a +// buckle on it. negative where a buckle bends the line the other way more than the curve does +double line_curvature(track_state const &Track); +// the lateral acceleration [m/s2] the cant doesn't balance on that line, positive out of the curve: +// unbalanced_acceleration() with a buckle +double line_acceleration(track_state const &Track, double Velocity); + +// the angle [rad] between the vehicle and the line of the force of the coupling at the end, in a curve: half the +// angle between the two vehicles, whose middles are half their lengths apart along the curve +double coupling_angle(double Length, double OtherLength, double Radius); + +struct wheel_forces { + double lateral{0.0}; // the lateral force on the vehicle, positive out of the curve [N] + double y{0.0}; // lateral force of the flanging wheel [N] + double q{0.0}; // its vertical force [N] + // a wheel lifted off the rail with a force on it is past any limit; no force at all (a vehicle without a mass) none + double ratio() const { return q > 0.0 ? y / q : (y > 0.0 ? 1e9 : 0.0); } +}; +// the forces of the flanging wheel of the leading axle, at the speed [m/s] +wheel_forces flange_forces(vehicle_state const &Vehicle, track_state const &Track, double Velocity); +// the lateral acceleration of the body the overturning goes by [m/s2]: what the cant doesn't balance, the sideways +// pull of the couplings, the vibration and the uneven track, by the state of the track +double body_acceleration(vehicle_state const &Vehicle, track_state const &Track, double Velocity); + +// ---- the stretch a condition holds over + +// the distance [m] a condition has to hold over: the window of EN 14363 +inline constexpr double window{2.0}; + +// the distance travelled while the condition held, without a break. the same distance with any step: a step the +// condition holds at counts with its whole length +class stretch { +public: + // true once the condition held over the window, given the distance of the step [m] + bool update(bool Holds, double Distance, double Window = window); + double distance() const { return m_distance; } + void reset() { m_distance = 0.0; } + +private: + double m_distance{0.0}; +}; + +enum class outcome { + none, + off_rails, // the flange climbed the rail: the vehicle runs off the rails, upright + overturned // the vehicle fell over out of the curve +}; + +// what the vehicle came to in a step, with the values the decision went by +struct verdict { + outcome result{outcome::none}; + double unloading{0.0}; // D + double flange_ratio{0.0}; // Y / Q + double acceleration{0.0}; // of the body, [m/s2] +}; + +// both criteria of a vehicle, step by step +class monitor { +public: + // the step travelled the distance [m]; the condition at its end goes for the whole of it + verdict update(vehicle_state const &Vehicle, track_state const &Track, double Velocity, double Distance); + void reset(); + +private: + stretch m_overturning; + stretch m_climbing; +}; + +// the friction of a derailed vehicle sliding along [-]: on its wheels on the sleepers and the ballast, or on its side +inline constexpr double off_rails_friction{0.3}; +inline constexpr double overturned_friction{0.5}; +double sliding_friction(outcome Outcome); + +// the lowest speed [m/s] from the one the cant balances at which the flange of the leading axle climbs the rail (Y / Q +// at the climbing limit); none when it doesn't climb up to 200 m/s: a lone vehicle on a good track mostly overturns +// first, its Y / Q goes to the ratio of the contact spacing to the height of the centre of gravity at speed +std::optional climbing_speed(vehicle_state const &Vehicle, track_state const &Track); + +// what the criteria found, for the log: "overturned at 113 km/h on track t1, curve radius 300 m, cant 0 mm: lateral +// acceleration ..., wheel unloading ..., Y/Q ... (mass ..., centre of gravity ..., couplings pushing ... / ... kN, +// track damage ..., cross level ... mm)" +std::string report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double Velocity, std::string_view TrackName); + +// ---- the speed limits of the tracks trusted (physics.derailment.trustlimits in eu07.ini) +// +// some tracks of the sceneries allow more speed than a vehicle survives in their curves (physics.trackcheck finds +// them). a vehicle the curve and the cant alone would derail there at a speed under the trusted one below runs as the +// scenery tells its driver to: the limit is the defect, not the driving, so the vehicle stays on the rails and the log +// tells of the track. over the trusted speed the driver went too fast, and the verdict goes. a verdict the forces of the +// couplings, a buckle, the damage flags or the unevenness of the track bring about goes at any speed + +// the speed limit of a track is trusted up to limit * factor + margin [km/h]: the overspeed a driver keeps to, and a +// margin for the slow limits +inline constexpr double trusted_limit_factor{1.1}; +inline constexpr double trusted_limit_margin{5.0}; // [km/h] +// the speed [km/h] up to which the speed limit [km/h] of a track is trusted; none for a track without a limit (a +// negative one): there the drivers go by the signals and the timetable, and the criteria decide +std::optional trusted_speed(double Limit); + +// whether the curve and the cant alone give the verdict: its criterion holds as well for the vehicle without the forces +// of its couplings, on the track without a buckle, damage flags and unevenness (the track physics.trackcheck checks the +// limits on). the condition at the step of the verdict; the window it held over is the verdict's +bool from_track_alone(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double Velocity); + +// the verdict that goes with the speed limits trusted, at the speed [m/s] on a track with the limit [km/h]: the given +// one, or one with no outcome (and the values of the given one) when the track alone gives it under the trusted speed +verdict limited_verdict(verdict const &Verdict, bool TrackAlone, double Velocity, double Limit); + +// what the log tells of a verdict held back, after the name of the vehicle: "held on the rails on track t1 under its +// trusted speed of 159 km/h (speed limit 140 km/h, too high for the curve: a defect of the scenery): " and the report +std::string held_back_report(verdict const &Verdict, vehicle_state const &Vehicle, track_state const &Track, double Velocity, double Limit, std::string_view TrackName); + +} // namespace derailment diff --git a/McZapkie/friction.cpp b/physics/friction.cpp similarity index 99% rename from McZapkie/friction.cpp rename to physics/friction.cpp index 6ecf5a064..bb4d872d8 100644 --- a/McZapkie/friction.cpp +++ b/physics/friction.cpp @@ -13,7 +13,7 @@ Copyright (C) 2007-2013 Maciej Cierniak */ #include "stdafx.h" -#include "friction.h" +#include "physics/friction.h" double TFricMat::GetFC(double N, double Vel) { diff --git a/McZapkie/friction.h b/physics/friction.h similarity index 100% rename from McZapkie/friction.h rename to physics/friction.h diff --git a/McZapkie/Oerlikon_ESt.cpp b/physics/oerlikonest.cpp similarity index 99% rename from McZapkie/Oerlikon_ESt.cpp rename to physics/oerlikonest.cpp index 0717eff5d..70c3d4f8e 100644 --- a/McZapkie/Oerlikon_ESt.cpp +++ b/physics/oerlikonest.cpp @@ -13,7 +13,7 @@ Copyright (C) 2007-2014 Maciej Cierniak */ #include "stdafx.h" -#include "Oerlikon_ESt.h" +#include "physics/oerlikonest.h" #include "utilities/utilities.h" // wstepny nacisk sprezyn na glowny przyrzad rozrzadczy, wyrazony jako roznica cisnien ZS - PG [bar] diff --git a/McZapkie/Oerlikon_ESt.h b/physics/oerlikonest.h similarity index 98% rename from McZapkie/Oerlikon_ESt.h rename to physics/oerlikonest.h index eaae2c032..eedf80dc9 100644 --- a/McZapkie/Oerlikon_ESt.h +++ b/physics/oerlikonest.h @@ -19,8 +19,8 @@ http://mozilla.org/MPL/2.0/. #include #include -#include "hamulce.h" // Pascal unit -#include "friction.h" // Pascal unit +#include "physics/brakes.h" // Pascal unit +#include "physics/friction.h" // Pascal unit /* (C) youBy diff --git a/physics/vehicle.h b/physics/vehicle.h new file mode 100644 index 000000000..ddefd28ee --- /dev/null +++ b/physics/vehicle.h @@ -0,0 +1,2061 @@ +/* +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 +//--------------------------------------------------------------------------- +// Q: 20160805 - odlaczenie pliku fizyki .pas od kompilacji +#include +#include +#include +#include +#include "physics/brakes.h" +#include "physics/couplerphysics.h" +#include "physics/derailment.h" +#include "physics/collision.h" +#include "scripting/ladderlogic.h" +#include "vehicle/derailmotion.h" +#include "vehicle/odometerreading.h" +#include "physics/vehicletypes.h" +#include "physics/components/dieselengine.h" +#include "physics/components/inductionmotor.h" +#include "physics/components/braking.h" +#include "physics/components/airsupply.h" +#include "physics/components/devices.h" +#include "physics/components/pantographs.h" +#include "physics/components/maincircuit.h" +#include "physics/components/lowvoltage.h" + +class TractionDrive; + +class cParser; +namespace physics +{ +class Vehicle; +} +/* +MaSzyna EU07 locomotive simulator +Copyright (C) 2001-2004 Maciej Czapkiewicz and others + +*/ + +/* +(C) McZapkie v.2004.02 +Co brakuje: +6. brak pantografow itp 'Nie do konca, juz czesc zrobiona - Winger +7. brak efektu grzania oporow rozruchowych, silnika, osi +9. ulepszyc sprzeg sztywny oraz automatyczny +10. klopoty z EN57 +... +n. Inne lokomotywy oprocz elektrowozu pradu stalego +*/ +/* +Zrobione: +1. model szeregowego silnika elektrycznego sterowanego reostatem +2. fizyka ruchu - sily oporu, nachylenia, przyspieszenia styczne i normalne, +przyczepnosc/poslizg przy hamowaniu i rozruchu +3. docisk klockow hamulcowych -hamulec reczny oraz pomocniczy hamulec pneumatyczny +4. ubytki cisnienia wskutek hamowania, kompresor - ladowanie zbiornika +5. niektore uszkodzenia i awarie - logika rozmyta +a) silnik elektryczny - za duzy prad, napiecie, obroty +b) sprzegi - zerwanie gdy zbyt duze sily +6. flagi niektorych dzwiekow +7. hamulec zasadniczy - elektropneumatyczny (impulsowanie), pneumatyczny - zmiany cisnienia +zwiekszenie nacisku przy duzych predkosciach w hamulcach Oerlikona +8. sprzegi - sila, tlumiennosc +9. lok. el. - wylacznik glowny, odlacznik uszkodzonych silnikow +10. parametry trakcji +11. opoznienia w zalaczaniu stycznikow +12. trakcja wielokrotna +13. informacja na temat zrodla mocy dla silnikow trakcyjnych, ogrzewania, oswietlenia +14. dumb - uproszczony model lokomotywy (tylko dla AI) +15. ladunki - ilosc, typ, szybkosc na- i rozladunku, funkcje przetestowac! +16. ulepszony model fizyczny silnika elektrycznego (hamowanie silnikiem, ujemne napiecia) +17. poprawione hamulce - parametry cylindrow itp +18. ulepszone hamulce - napelnianie uderzeniowe, stopnie hamowania +19. poprawione hamulce - wyszczegolnenie cisnienia dla stopni hamowania +20. poprawione hamulce elektropneumatyczne +21. poprawione hamowanie przeciwposlizgowe i odluzniacz +22. dodany model mechanicznego napedu recznego (drezyna) +23. poprawiona szybkosc hamowania pomocniczego i przeciwposlizgowego, odlaczanie silnikow, odlaczanie bocznikow +24. wprowadzone systemy zabezpieczenia: SHP, Czuwak, sygnalizacja kabinowa (nie dzialaja w DebugMode). +25. poprawiona predkosc propagacji fali cisnienia (normalizacja przez kwadrat dlugosci) //to jest zdeka liniowe +26. uwzgledniona masa ladunku, przesuniecie w/m toru ruchu +27. lampy/sygnaly przednie/tylne +28. wprowadzona pozycja odciecia hamulca (yB: tja, ale oerlikona....) +29. rozne poprawki: slizganie, wykolejanie itp +30. model silnika spalinowego z przekladnia mechaniczna +31. otwieranie drzwi, sprezarka, przetwornica +32. wylaczanie obliczen dla nieruchomych wagonow +33. Zbudowany model rozdzielacza powietrza roznych systemow +34. Poprawiona pozycja napelniania uderzeniowego i hamulec EP +35. Dodane baterie akumulatorow (KURS90) +36. Hamowanie elektrodynamiczne w ET42 i poprawione w EP09 +37. jednokierunkowosc walu kulakowego w EZT (nie do konca) +38. wal kulakowy w ET40 +39. poprawiona blokada nastawnika w ET40 +... +*/ + +/// Steam-locomotive grate parameters. +struct TGrateType +{ + /// Fuel type burned on this grate. + TFuelType FuelType; + /// Grate surface area [m²]. + double GrateSurface; + /// Fuel transport speed (stoker rate). + double FuelTransportSpeed; + /// Fuel ignition temperature [°C]. + double IgnitionTemperature; + /// Maximum allowable grate temperature [°C]. + double MaxTemperature; + // inline TGrateType() { + // FuelType = Undefined; + // GrateSurface = 0.0; + // FuelTransportSpeed = 0.0; + // IgnitionTemperature = 0.0; + // MaxTemperature = 0.0; + // } +}; +/// Steam-locomotive boiler parameters. +struct TBoilerType +{ + /// Boiler internal volume [m³]. + double BoilerVolume; + /// Heat exchange surface of the boiler [m²]. + double BoilerHeatSurface; + /// Superheater surface [m²]. + double SuperHeaterSurface; + /// Maximum water volume [m³]. + double MaxWaterVolume; + /// Minimum (safety) water volume [m³]. + double MinWaterVolume; + /// Maximum boiler pressure [bar]. + double MaxPressure; + // inline TBoilerType() { + // BoilerVolume = 0.0; + // BoilerHeatSurface = 0.0; + // SuperHeaterSurface = 0.0; + // MaxWaterVolume = 0.0; + // MinWaterVolume = 0.0; + // MaxPressure = 0.0; + // } +}; +/// Pantograph (current collector) model identifier. +enum TPantType +{ + /// AKP-4E pantograph (PKP single-arm). + AKP_4E, + /// DSA-series pantograph (Stemmann). + DSAx, + /// EC160/EC200 pantograph. + EC160_200, + /// WBL85 pantograph. + WBL85 +}; +/// Current-collector (pantograph) configuration block. +struct TCurrentCollector +{ + /// Number of pantographs of this type. + long CollectorsNo; // musi być tu, bo inaczej się kopie + /// Minimum pantograph height [m] (currently unused). + double MinH; + /// Maximum pantograph height [m] (currently unused). + double MaxH; + /// Working width of the contact strip [m]. + double CSW; // szerokość części roboczej (styku) ślizgacza + /// Minimum acceptable contact-line voltage [V]. + double MinV; + /// Maximum acceptable contact-line voltage [V]. + double MaxV; + /// True if an over-voltage protection relay is fitted. + bool OVP; // czy jest przekaznik nadnapieciowy + /// Minimum voltage required to engage the main switch [V]. + double InsetV; // minimalne napięcie wymagane do załączenia + /// Minimum air pressure required to operate [bar]. + double MinPress; // minimalne ciśnienie do załączenia WS + /// Maximum air pressure after the reductor [bar]. + double MaxPress; // maksymalne ciśnienie za reduktorem + /// True if power output is faked (e.g. for AI vehicles without a model). + bool FakePower; + /// Physical layout id (orientation / side). + int PhysicalLayout; + /// Pantograph type (model). + TPantType PantographType; + // inline TCurrentCollector() { + // CollectorsNo = 0; + // MinH, MaxH, CSW, MinV, MaxV = 0.0; + // OVP, InsetV, MinPress, MaxPress = 0.0; + // } +}; +/// Power-source kind (where the vehicle gets electrical or mechanical energy from). +enum class TPowerSource +{ + NotDefined, + InternalSource, + Transducer, + Generator, + Accumulator, + CurrentCollector, + PowerCable, + Heater, + Main +}; + +/// Diesel engine driven generator parameters and outputs. +struct engine_generator +{ + // ld inputs + /// Pointer to the prime-mover revolutions [rev/s]. + double *engine_revolutions; // revs per second of the prime mover + // config + /// Minimum working rev rate [rev/s]. + double revolutions_min; // min working revolutions rate, in revs per second + /// Maximum working rev rate [rev/s]. + double revolutions_max; // max working revolutions rate, in revs per second + /// Voltage generated at revolutions_min [V]. + double voltage_min; // voltage generated at min working revolutions + /// Voltage generated at revolutions_max [V]. + double voltage_max; // voltage generated at max working revolutions + // ld outputs + /// Current rev rate [rev/s]. + double revolutions; + /// Current generated voltage [V]. + double voltage; +}; + +/// Battery / accumulator power source. +struct TAccumulator +{ + /// Maximum capacity [Ah]. + double MaxCapacity; + /// Source used to recharge the battery. + TPowerSource RechargeSource; + // inline _vehicle__1() { + // MaxCapacity = 0.0; + // RechargeSource = NotDefined; + // } +}; + +/// Permanent power cable (e.g. to a heater) carrying a specific power form. +struct TPowerCable +{ + /// Type of power transmitted. + TPowerType PowerTrans; + /// Steam pressure (when SteamPower is transmitted) [bar]. + double SteamPressure; + // inline _vehicle__2() { + // SteamPressure = 0.0; + // PowerTrans = NoPower; + // } +}; + +/// Steam locomotive boiler-and-grate combo. +struct THeater +{ + /// Grate parameters. + TGrateType Grate; + /// Boiler parameters. + TBoilerType Boiler; +}; + +/// Transducer (DC-DC / converter) parameters. +struct TTransducer +{ + // ld inputs + /// Input voltage [V]. + double InputVoltage; +}; + +/// +/// Generic power-source parameters. The trailing union holds source-specific +/// configuration depending on SourceType. +/// +struct TPowerParameters +{ + /// Maximum source voltage [V]. + double MaxVoltage{0.0}; + /// Maximum source current [A]. + double MaxCurrent{0.0}; + /// Internal resistance [Ω]. + double IntR{0.001}; + /// Type of source (selects which union member is meaningful). + TPowerSource SourceType; + union + { + struct + { + THeater RHeater; + }; + struct + { + TPowerCable RPowerCable; + }; + struct + { + TCurrentCollector CollectorParameters; + }; + struct + { + TAccumulator RAccumulator; + }; + struct + { + engine_generator EngineGenerator; + }; + struct + { + TTransducer Transducer; + }; + struct + { + TPowerType PowerType; + }; + }; + inline TPowerParameters() + { + SourceType = TPowerSource::NotDefined; + PowerType = TPowerType::NoPower; + RPowerCable.PowerTrans = TPowerType::NoPower; + } +}; + +/*dla lokomotyw elektrycznych:*/ +struct TScheme +{ + int Relay = 0; /*numer pozycji rozruchu samoczynnego*/ + double R = 0.0; /*opornik rozruchowy*/ /*dla dizla napelnienie*/ + int Bn = 0; + int Mn = 0; /*ilosc galezi i silnikow w galezi*/ /*dla dizla Mn: czy luz czy nie*/ + bool AutoSwitch = false; /*czy dana pozycja nastawniana jest recznie czy autom.*/ + int ScndAct = 0; /*jesli ma bocznik w nastawniku, to ktory bocznik na ktorej pozycji*/ +}; +using TSchemeTable = TScheme[ResArraySize + 1]; /*tablica rezystorow rozr.*/ +struct TDEScheme +{ + double RPM = 0.0; /*obroty diesla*/ + double GenPower = 0.0; /*moc maksymalna*/ + double Umax = 0.0; /*napiecie maksymalne*/ + double Imax = 0.0; /*prad maksymalny*/ +}; +using TDESchemeTable = TDEScheme[33]; /*tablica WWList dla silnikow spalinowych*/ +struct TFFScheme +{ + double v = 0.0; // parametr wejsciowy + double freq = 0.0; // wyjscie: czestotliwosc falownika +}; +using TFFSchemeTable = TFFScheme[33]; + +struct TWiperScheme +{ + uint8_t byteSum = 0; // suma bitowa pracujacych wycieraczek + double WiperSpeed = 0.0; // predkosc wycieraczki + double interval = 0.0; // interwal pracy wycieraczki + double outBackDelay = 0.0; // czas po jakim wycieraczka zacznie wracac z konca do poczatku +}; +using TWiperSchemeTable = TWiperScheme[16]; + +struct TShuntScheme +{ + double Umin = 0.0; + double Umax = 0.0; + double Pmin = 0.0; + double Pmax = 0.0; +}; +using TShuntSchemeTable = TShuntScheme[33]; +struct TMPTRelay +{ /*lista przekaznikow bocznikowania*/ + double Iup = 0.0; + double Idown = 0.0; +}; +using TMPTRelayTable = TMPTRelay[MotorParametersArraySize + 1]; // indexed like MotorParam + +struct TMotorParameters +{ + double mfi{0.0}; + double mIsat{0.0}; + double mfi0{0.0}; // aproksymacja M(I) silnika} {dla dizla mIsat=przekladnia biegu + double fi{0.0}; + double Isat{0.0}; + double fi0{0.0}; // aproksymacja E(n)=fi*n} {dla dizla fi, mfi: predkosci przelozenia biegu <-> + bool AutoSwitch{false}; +}; + +struct TUniversalCtrl +{ + int mode = 0; /*tryb pracy zadajnika - pomocnicze*/ + double MinCtrlVal = 0.0; /*minimalna wartosc nastawy*/ + double MaxCtrlVal = 0.0; /*maksymalna wartosc nastawy*/ + double SetCtrlVal = 0.0; /*docelowa wartosc nastawy*/ + double SpeedUp = 0.0; /*szybkosc zwiekszania nastawy*/ + double SpeedDown = 0.0; /*szybkosc zmniejszania nastawy*/ + int ReturnPosition = 0; /*pozycja na ktora odskakuje zadajnik*/ + int NextPosFastInc = 0; /*nastepna duza pozycja przy przechodzeniu szybkim*/ + int PrevPosFastDec = 0; /*poprzednia duza pozycja przy przechodzeniu szybkim*/ +}; +using TUniversalCtrlTable = std::array; + +class TSecuritySystem +{ + bool vigilance_enabled = false; + bool cabsignal_enabled = false; + bool radiostop_enabled = false; + + bool cabsignal_active = false; + bool pressed = false; + bool enabled = false; + bool is_sifa = false; // Sifa-like pedal device, with inverted input for convenient keyboard usage + bool separate_acknowledge = false; // cabsignal reset button is separate from vigilance + bool cabsignal_lock = false; + bool vigilance_suspended = false; // the vigilance device switched off by the shunt mode of the vehicle, see AwareOffInShuntMode + + double vigilance_timer = 0.0; + double alert_timer = 0.0; + double press_timer = 0.0; + + double velocity = 0.0; + bool power = false; + int cabactive = 0; + + double AwareDelay = 30.0; + double AwareMinSpeed = 0.0; + double SoundSignalDelay = 5.0; + double EmergencyBrakeDelay = 5.0; + double MaxHoldTime = 1.5; + bool CabDependent = false; + bool AwareOffInShuntMode = false; // the shunt mode of the vehicle switches the vigilance device off, as on the SM42 + + public: + void set_enabled(bool e); + void acknowledge_press(); + void acknowledge_release(); + void cabsignal_reset(); + void update(double dt, double Vel, bool pwr, int cab); + void set_cabsignal(); + void set_cabsignal_lock(bool); + void set_shunt_mode(bool State); + bool is_blinking() const; + bool is_vigilance_blinking() const; + bool is_cabsignal_blinking() const; + bool is_beeping() const; + bool is_cabsignal_beeping() const; + bool is_braking() const; + bool is_engine_blocked() const; + bool radiostop_available() const; + bool has_separate_acknowledge() const; + void load(std::string const &line, double vmax); + + double MagnetLocation = 0.0; +}; + +struct TTransmision +{ // liczba zebow przekladni + int NToothM = 0; + int NToothW = 0; + double Ratio = 1.0; + double Efficiency = 1.0; +}; + +enum class TCouplerType +{ + NoCoupler, + Articulated, + Bare, + Chain, + Screw, + Automatic +}; + +struct power_coupling +{ + double current{0.0}; + double voltage{0.0}; + bool is_local{false}; // whether the power comes from external or onboard source + bool is_live{false}; // whether the coupling with next vehicle is live +}; + +struct TCoupling +{ + /*parametry*/ + double SpringKB = 1.0; /*stala sprezystosci zderzaka/sprzegu, %tlumiennosci */ + double DmaxB = 0.1; /*tolerancja scisku/rozciagania, sila rozerwania*/ + double FmaxB = 1000.0; + double SpringKC = 1.0; + double DmaxC = 0.1; + double FmaxC = 1000.0; + double beta = 0.0; + TCouplerType CouplerType = TCouplerType::NoCoupler; /*typ sprzegu*/ + CouplingSet AutomaticCouplingFlag{Coupling::coupler}; + CouplingSet AllowedFlag{Coupling::coupler | Coupling::brakeHose}; // Ra: maska dostępnych + CouplingSet PowerFlag{Coupling::power110v | Coupling::power24v}; + CouplingSet PowerCoupling{Coupling::permanent}; // type of coupling required for power transfer + /*zmienne*/ + bool AutomaticCouplingAllowed{true}; // whether automatic coupling can be currently performed + CouplingSet CouplingFlag; // what the coupling joins; none: the vehicles only see each other + class physics::Vehicle *Connected = nullptr; /*co jest podlaczone*/ + int ConnectedNr = 0; // Ra: od której strony podłączony do (Connected): 0=przód, 1=tył + // the end of the vehicle connected to, while there is one + VehicleEnd ConnectedEnd() const + { + return static_cast(ConnectedNr); + } + double CForce = 0.0; /*sila z jaka dzialal*/ + double Dist = 0.0; /*strzalka ugiecia zderzaków*/ + bool CheckCollision = false; /*czy sprawdzac sile czy pedy*/ + float stretch_duration{0.f}; // seconds, elapsed time with excessive force applied to the coupler + bool broken{false}; // the coupler broke (damage_coupler()), until it's repaired (repair_coupler()) + // optional adapter piece + double adapter_length{0.0}; // meters, value added on the given end to standard vehicle (half)length + double adapter_height{0.0}; // meters, distance from rail level + TCouplerType adapter_type = TCouplerType::NoCoupler; // CouplerType override if other than NoCoupler + + power_coupling power_high; + power_coupling power_110v; + power_coupling power_24v; + // the circuit of the power coupling given, nullptr for a coupling which isn't one + power_coupling *power(Coupling const kind) + { + switch (kind) + { + case Coupling::highVoltage: + return &power_high; + case Coupling::power110v: + return &power_110v; + case Coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } + power_coupling const *power(Coupling const kind) const + { + switch (kind) + { + case Coupling::highVoltage: + return &power_high; + case Coupling::power110v: + return &power_110v; + case Coupling::power24v: + return &power_24v; + default: + return nullptr; + } + } + + // the physical model of the coupling (couplerphysics in eu07.ini), see couplerphysics.h: the parameters of this end, + // and the state of the coupling with the vehicle at this end, which that vehicle keeps alike on its own end + coupler_physics::end_parameters physics; + coupler_physics::pair_state physics_state; + // the collisions past the buffers (physics.collisions new), see collision.h: the optional keys of this end, the depth + // it's crushed to for good [m], and the hit of the pair in the step: whether either vehicle handled it already, its + // peak force [N] and how long that acted [s] + collision::end_definition collision; + double crush{0.0}; + double closing{0.0}; // the velocity the buffers of the pair closed in at, at the start of the step [m/s] + bool hit_handled{false}; + double hit_force{0.0}; + double hit_duration{0.0}; + // physics.collisions monitor: the log told of the crush of this hit of the pair already + bool crush_monitored{false}; + // the energy the contact of the pair brought to its buffers, for the budget of the crush + collision::contact_energy contact; + // the log told of the vehicle at this end being inside this one already + bool inside_reported{false}; + + int sounds{0}; // sounds emitted by the coupling devices + bool Render = false; /*ABu: czy rysowac jak zaczepiony sprzeg*/ + std::string control_type; // abstraction of control coupling interface and communication standard + + inline bool has_adapter() const + { + return adapter_type != TCouplerType::NoCoupler; + } + inline TCouplerType type() const + { + return adapter_type == TCouplerType::NoCoupler ? CouplerType : adapter_type; + } +}; + + +struct speed_control +{ + bool IsActive = false; + bool Start = false; + bool ManualStateOverride = true; + bool BrakeIntervention = false; + bool BrakeInterventionBraking = false; + bool BrakeInterventionUnbraking = false; + bool Standby = false; + bool Parking = false; + double InitialPower = 1.0; + double FullPowerVelocity = -1; + double StartVelocity = -1; + double VelocityStep = 5; + double PowerStep = 0.1; + double MinPower = 0.0; + double MaxPower = 1.0; + double MinVelocity = 0; + double MaxVelocity = 120; + double DesiredVelocity = 0; + double DesiredPower = 1.0; + double Offset = -0.5; + double FactorPpos = 0.5; + double FactorPneg = 0.5; + double FactorIpos = 0.0; + double FactorIneg = 0.0; + double BrakeInterventionVel = 30.0; + double PowerUpSpeed = 1000; + double PowerDownSpeed = 1000; +}; + +namespace physics +{ + +class Vehicle +{ // Ra: wrapper na kod pascalowy, przejmujący jego funkcje Q: 20160824 - juz nie wrapper a klasa bazowa :) + public: + bool reload_FIZ(); + double const &MoveLength() const { return moveLength; } + void SetMoveLength(double const Value) { moveLength = Value; } + /*---opis lokomotywy, wagonu itp*/ + /*--opis serii--*/ + int CategoryFlag = 1; /*1 - pociag, 2 - samochod, 4 - statek, 8 - samolot*/ + /*--sekcja stalych typowych parametrow*/ + std::string TypeName; /*nazwa serii/typu*/ + train_type const &TrainType() const { return trainType; } // the vehicles of a handling of their own, from the Type of the .fiz + // an electric or a diesel multiple unit + bool is_multiple_unit() const + { + return trainType == train_type::emu || trainType == train_type::dmu; + } + TEngineType EngineType = TEngineType::None; /*typ napedu*/ + TPowerParameters EnginePowerSource; /*zrodlo mocy dla silnikow*/ + TPowerParameters HeatingPowerSource; /*zrodlo mocy dla ogrzewania*/ + double const &Vmax() const { return vmax; } + double const &Mass() const { return emptyMass; } + double Power = 0.0; /*max. predkosc kontrukcyjna, masa wlasna, moc*/ + double const &Mred() const { return mred; } /*Ra: zredukowane masy wirujące; potrzebne do obliczeń hamowania*/ + double const &TotalMass() const { return totalMass; } /*wyliczane przez ComputeMass*/ + double LightPower = 0.0; /*moc pobierana na ogrzewanie/oswietlenie*/ + bool const &EpFuse() const { return epFuse; } /*Czy jest wlaczony hamulec EP*/ + double EpForce = 0.0; /*Poziom zadanej sily EP*/ + bool const &Signalling() const { return signalling; } /*Czy jest zalaczona sygnalizacja hamowania ostatniego wagonu*/ + void SetSignalling(bool const Value) { signalling = Value; } + bool const &Radio() const { return radio; } /*Czy jest zalaczony radiotelefon*/ + void SetRadio(bool const Value) { radio = Value; } + // the cut-off in the radio's power supply: a fuse in the cabinet, a lever on the desk or the switch on the radio's power + // supply (eu07/maszyna#438). Closed unless the driver opens it, so vehicles without such a switch work as before + bool const &RadioFuse() const { return radioFuse; } + void SetRadioFuse(bool const Value) { radioFuse = Value; } + TDimension Dim; /*wymiary*/ + double Cx = 0.0; /*wsp. op. aerodyn.*/ + float Floor = 0.96f; // poziom podłogi dla ładunków + float const &WheelDiameter() const { return wheelDiameter; } /*srednica kol napednych*/ + float WheelDiameterL = 0.9f; // Ra: srednica kol tocznych przednich + float WheelDiameterT = 0.9f; // Ra: srednica kol tocznych tylnych + float TrackW = 1.435f; /*nominalna szerokosc toru [m]*/ + double AxleInertialMoment = 0.0; /*moment bezwladnosci zestawu kolowego*/ + std::string AxleArangement; /*uklad osi np. Bo'Bo' albo 1'C*/ + int const &NPoweredAxles() const { return nPoweredAxles; } /*ilosc osi napednych liczona z powyzszego*/ + int const &NAxles() const { return nAxles; } /*ilosc wszystkich osi j.w.*/ + int BearingType = 1; /*lozyska: 0 - slizgowe, 1 - toczne*/ + double const &ADist() const { return aDist; } + double const &BDist() const { return bDist; } /*odlegosc osi oraz czopow skretu*/ + int SandCapacity = 0; /*zasobnik piasku [kg]*/ + + int const &WiperSwitchPos() const { return wiperSwitchPos; } // pozycja przelacznika wycieraczek + void SetWiperSwitchPos(int const Value) { wiperSwitchPos = Value; } + double WiperAngle = {45.0}; // kat pracy wycieraczek + + LowVoltageSupply lowVoltage; // the battery and the low voltage circuits (physics/components/lowvoltage.h) + TrainHeating trainHeating; + LineBreaker lineBreaker; // the main circuit (physics/components/maincircuit.h) + LineContactors lineContactors; + ProtectionRelays protection; + PowerConverter converter; + ByEnd pantographs; + PantographCircuit pantographCircuit; // their voltages, switches, presets (physics/components/pantographs.h) + PantographAir pantographAir; // their reservoir, the small compressor, the valves + TrainPipe brakePipe; // the brake pipe along the train + TrainPipe mainPipe; // the main reservoir pipe along the train + AirSupply air; // the compressor and the main reservoir (physics/components/airsupply.h) + Braking brakes; // the blending, the holding brake, the spring brake (physics/components/braking.h) + + int TurboTest = 0; + /*nastawniki:*/ + int MainCtrlPosNo = 0; /*ilosc pozycji nastawnika*/ + int const &ScndCtrlPosNo() const { return scndCtrlPosNo; } + int LightsPosNo = 0; + bool LightsWrap = false; + ByEnd> Lights; // pozycje świateł, przód - tył, 1 .. 16 (17 do lightsset) + // the cab interior light each light preset sets, from the optional third column of LightsList (bits of + // lights_preset_cablight::flag); -1: the preset leaves the cab light as it is (eu07/maszyna#529) + std::array LightsCabLight{[] { + std::array positions; + positions.fill(-1); + return positions; + }()}; + double maxTachoSpeed = {0.0}; // maksymalna predkosc na tarczce predkosciomierza analogowego + bool HideDirStatusWhenMoving{false}; // Czy gasic lampki kierunku powyzej predkosci zdefiniowanej przez HideDirStatusSpeed + int HideDirStatusSpeed{1}; // Predkosc od ktorej lampki kierunku sa wylaczane + bool isDoubleClickForMeasureNeeded = {false}; // czy rozpoczecie pomiaru odleglosci odbywa sie po podwojnym wcisnienciu przycisku? + float DistanceCounterDoublePressPeriod = {1.f}; // czas w jakim nalezy podwojnie wcisnac przycisk, aby rozpoczac pomiar odleglosci + TSecuritySystem SecuritySystem; + int EmergencyBrakeWarningSignal{0}; // combined with basic warningSignal when manual emergency brake is active + horn_supply const &HornSupply() const { return hornSupply; } // of the low and high tone horns (warningSignal 1 and 2) + horn_supply Horn3Supply{horn_supply::air}; // of the third horn (warningSignal 4) + // main reservoir pressure [bar, as MinCP and MaxCP] below which a pneumatic horn stays silent + static constexpr double HornMinPressure{2.0}; + TUniversalCtrlTable UniCtrlList; /*lista pozycji uniwersalnego nastawnika*/ + bool UniCtrlIntegratedBrakeCtrl = false; /*zintegrowany nastawnik JH obsluguje hamowanie*/ + bool const &UniCtrlIntegratedLocalBrakeCtrl() const { return uniCtrlIntegratedLocalBrakeCtrl; } /*zintegrowany nastawnik JH obsluguje hamowanie hamulcem pomocniczym*/ + // UCList CtrlValStep: the universal controller (EIMCtrlType 3) changes its setting in steps of this size (e.g. 0.05 for the + // 5% steps of the 6Dg), one at once when moved to a raising or lowering position, then one each time its SpeedUp / SpeedDown + // covers a step; 0 (the default) changes it continuously + double const &UniCtrlValStep() const { return uniCtrlValStep; } + + /*-sekcja parametrow dla lokomotywy elektrycznej*/ + TSchemeTable RList; /*lista rezystorow rozruchowych i polaczen silnikow, dla dizla: napelnienia*/ + int RlistSize = 0; + TMotorParameters MotorParam[MotorParametersArraySize + 1]; + /*rozne parametry silnika przy bocznikowaniach*/ + /*dla lokomotywy spalinowej z przekladnia mechaniczna: przelozenia biegow*/ + // bounds-safe read access to MotorParam + TMotorParameters const &motor_param(int const Position) const + { + if (Position < 0) + return MotorParam[0]; + if (Position > MotorParametersArraySize) + return MotorParam[MotorParametersArraySize]; + return MotorParam[Position]; + } + TTransmision Transmision; + // record {liczba zebow przekladni} + // NToothM, NToothW : byte; + // Ratio: real; {NToothW/NToothM} + // end; + double NominalVoltage = 0.0; /*nominalne napiecie silnika*/ + double const &WindingRes() const { return windingRes; } + double CircuitRes = 0.0; /*rezystancje silnika i obwodu*/ + int IminLo = 0; + int IminHi = 0; /*prady przelacznika automatycznego rozruchu, uzywane tez przez ai_driver*/ + int const &ImaxLo() const { return imaxLo; } // maksymalny prad niskiego rozruchu + int const &ImaxHi() const { return imaxHi; } // maksymalny prad wysokiego rozruchu + bool const &MotorOverloadRelayHighThreshold() const { return motorOverloadRelayHighThreshold; } + double nmax = 0.0; /*maksymalna dop. ilosc obrotow /s*/ + double const &InitialCtrlDelay() const { return initialCtrlDelay; } + double CtrlDelay = 0.0; /* -//- -//- miedzy kolejnymi poz.*/ + double CtrlDownDelay = 0.0; /* -//- -//- przy schodzeniu z poz.*/ /*hunter-101012*/ + int BackwardsBranchesAllowed = 1; + int const &AutoRelayType() const { return autoRelayType; } /*0 -brak, 1 - jest, 2 - opcja*/ + // FieldShuntSwitch=Yes: the switch of AutoRelay=Optional of a diesel-electric is its switch of the field shunting, as the SU45's + // and SP45's (fieldshunting.h): off, the field stays full. without it, off hands the shunting to the second controller, as before + bool const &FieldShuntSwitch() const { return fieldShuntSwitch; } + bool CoupledCtrl = false; /*czy mainctrl i scndctrl sa sprzezone*/ + bool HasCamshaft{false}; + // the dynamic brake of a diesel-electric vehicle (Engine: EDBrake=...): the traction motors brake into resistors while + // the engine runs, with the force of the definition rather than from a circuit, as the drive of these vehicles is + // computed from the generator's power. no definition, no dynamic brake (MaSzyna-EU07/maszyna#82) + struct diesel_electric_dynamic_brake + { + enum class control + { + none, + controller, // the negative range of the integrated controller (EIMCtrlType > 0), as the TRAXX one of the BR285 + lever // a lever of its own (the SplitEDPneumaticBrake one, DBPN steps), with the master controller at zero + }; + control source{control::none}; + double max_force{0.0}; // [N] at the wheel rims of the whole vehicle, EDBrakeFmax [kN] + double max_power{0.0}; // [W] the resistors take, EDBrakePmax [kW]; 0: no limit + double fade_low{0.0}; // [km/h] EDBrakeV0: no force below + double fade_high{0.0}; // [km/h] EDBrakeV1: the whole force above, rising in between + double rate{0.5}; // [1/s] EDBrakeRate: how fast the effort follows the demand + bool blending{false}; // EDBrakeBlending: the locomotive's train brake lets off while the dynamic brake works (Hamulec->SetED) + // state + double level{0.0}; // the effort, 0..1 + double force{0.0}; // [N] the braking force, against the motion + }; + diesel_electric_dynamic_brake DEDynamicBrake; + double RVentnmax = 1.0; /*maks. obroty wentylatorow oporow rozruchowych*/ + double RVentSpeed{0.5}; // rozpedzanie sie wentylatora obr/s^2} + bool const &RVentForceOn() const { return rventForceOn; } // forced activation switch + void SetRVentForceOn(bool const Value) { rventForceOn = Value; } + + // the diesel engine, its torque converter and its retarder (physics/components/dieselengine.h) + DieselEngine diesel; + TorqueConverter torqueConverter; + Retarder retarder; + /*- dla lokomotyw spalinowo-elektrycznych -*/ + double const &AnPos() const { return anPos; } // pozycja sterowania dokladnego (analogowego) + void SetAnPos(double const Value) { anPos = Value; } + bool ShuntModeAllow = false; + bool ShuntMode = false; + + TDESchemeTable DElist; + TWiperSchemeTable WiperList; + int WiperListSize; + + double Vadd = 1.0; + int RelayType = 0; + /*- dla uproszczonego modelu silnika (dumb) oraz dla drezyny*/ + /*- dla lokomotyw z silnikami indukcyjnymi -*/ + // the drive of induction motors (physics/components/inductionmotor.h) + InductionMotor inductionMotor; + + /*-dla wagonow*/ + struct load_attributes + { + std::string name; // name of the cargo + float offset_min{0.f}; // offset applied to cargo model when load amount is 0 + + load_attributes() = default; + load_attributes(std::string const &Name, float const Offsetmin) : name(Name), offset_min(Offsetmin) {} + }; + std::vector LoadAttributes; + float const &MaxLoad() const { return maxLoad; } /*masa w T lub ilosc w sztukach - ladownosc*/ + void SetMaxLoad(float const Value) { maxLoad = Value; } + double OverLoadFactor = 0.0; /*ile razy moze byc przekroczona ladownosc*/ + float LoadSpeed = 0.f; + float UnLoadSpeed = 0.f; /*szybkosc na- i rozladunku jednostki/s*/ +#ifdef EU07_USEOLDDOORCODE + int DoorOpenCtrl = 0; + int DoorCloseCtrl = 0; /*0: przez pasazera, 1: przez maszyniste, 2: samoczynne (zamykanie)*/ + double DoorStayOpen = 0.0; /*jak dlugo otwarte w przypadku DoorCloseCtrl=2*/ + bool DoorClosureWarning = false; /*czy jest ostrzeganie przed zamknieciem*/ + bool DoorClosureWarningAuto = false; // departure signal plays automatically while door closing button is held down + double DoorOpenSpeed = 1.0; + double DoorCloseSpeed = 1.0; /*predkosc otwierania i zamykania w j.u. */ + double DoorMaxShiftL = 0.5; + double DoorMaxShiftR = 0.5; + double DoorMaxPlugShift = 0.1; /*szerokosc otwarcia lub kat*/ + int DoorOpenMethod = 2; /*sposob otwarcia - 1: przesuwne, 2: obrotowe, 3: trójelementowe*/ + float DoorCloseDelay{0.f}; // delay (in seconds) before the door begin closing, once conditions to close are met + double PlatformSpeed = 0.5; /*szybkosc stopnia*/ + double PlatformMaxShift{0.0}; /*wysuniecie stopnia*/ + int PlatformOpenMethod{2}; /*sposob animacji stopnia*/ +#endif + double MirrorMaxShift{90.0}; + double MirrorVelClose{5.0}; + bool const &MirrorForbidden() const { return mirrorForbidden; } /*czy jest pozwolenie na otworzenie lusterek (przycisk)*/ + void SetMirrorForbidden(bool const Value) { mirrorForbidden = Value; } + bool ScndS = false; /*Czy jest bocznikowanie na szeregowej*/ + bool ScndCtrlResistiveLock{false}; // the shunt controller can't be moved, up or down, while the master controller is at zero or on a resistive position, and drops to 0 when the master controller gets there (ScndCtrlResistiveLock=Yes in Cntrl.) + bool const &SpeedCtrl() const { return speedCtrl; } /*czy jest tempomat*/ + speed_control SpeedCtrlUnit; /*parametry tempomatu*/ + double SpeedCtrlValue = 0; /*wybrana predkosc jazdy na tempomacie*/ + /*--sekcja zmiennych*/ + /*--opis konkretnego egzemplarza taboru*/ + TLocation const &Loc() const { return location; } // pozycja pojazdów do wyznaczenia odległości pomiędzy sprzęgami + void SetLoc(TLocation const Value) { location = Value; } + std::string Name; /*nazwa wlasna*/ + ByEnd Couplers; // urzadzenia zderzno-sprzegowe, polaczenia miedzy wagonami + // the physical coupler model covers the vehicle: it's in the player's train or in one the player's train closes in on + // (vehicle_table::update_coupler_physics()); with couplerphysics all in eu07.ini every vehicle is covered + bool const &CouplerPhysics() const { return couplerPhysics; } + void SetCouplerPhysics(bool const Value) { couplerPhysics = Value; } + ByEnd Neighbours; // potential collision sources + // something out of the ordinary happened (the line breaker knocked out, a derailment), for the sounds to follow up + bool EventFlag() const { return eventFlag; } + void RaiseEventFlag() { eventFlag = true; } + void ClearEventFlag() { eventFlag = false; } + // the events of the step the sounds are to follow up (sound::), cleared once they did + int SoundFlag() const { return soundFlag; } + void ClearSoundFlags() { soundFlag = 0; } + int const &AIFlag() const { return aiFlag; } // HACK: events of interest for consist owner + // the flag of an event the AI has seen to + void ClearAIFlag(int Flag); + double const &DistCounter() const { return distCounter; } /*! licznik kilometrow */ + void SetDistCounter(double const Value) { distCounter = Value; } + // the criteria of derailment (physics.derailment new), and the distance travelled since they were checked [m] + derailment::monitor derailment_monitor; + double const &DerailmentDistance() const { return derailmentDistance; } + void SetDerailmentDistance(double const Value) { derailmentDistance = Value; } + // physics.derailment monitor: the name of the track the criteria were last reported on (one report on a track), and + // how many reports there were + std::optional derailment_reported; + int const &derailment_reports() const { return derailmentreportsValue; } + odometer::reading Odometer; // total distance run, kept between the sessions (eu07/maszyna#72) + std::pair EnergyMeter; // energy from grid [kWh] + double const &V() const { return travelSpeed; } // predkosc w [m/s] względem sprzęgów (dodania gdy jedzie w stronę 0) + void SetV(double const Value) { travelSpeed = Value; } + double Vel = 0.0; // moduł prędkości w [km/h], używany przez AI + double const &AccS() const { return accS; } // efektywne przyspieszenie styczne w [m/s^2] (wszystkie siły) + void SetAccS(double const Value) { accS = Value; } + double const &AccSVBased() const { return accSVBased; } // tangential acceleration calculated from velocity change + double const &AccN() const { return accN; } // przyspieszenie normalne w [m/s^2] + void SetAccN(double const Value) { accN = Value; } + double const &AccVert() const { return accVert; } // vertical acceleration + void SetAccVert(double const Value) { accVert = Value; } + // a jolt of the track under the vehicle: up and down, or along and across (a switch) + void ShakeVertically(double const Acceleration) { accVert += Acceleration; } + void ShakeHorizontally(double const Acceleration) + { + accS += Acceleration; + accN += Acceleration; + } + double const &nrot() const { return nrotValue; } // predkosc obrotowa kol (obrotow na sekunde) + double const &WheelFlat() const { return wheelFlat; } + void SetWheelFlat(double const Value) { wheelFlat = Value; } + bool const &TruckHunting() const { return truckHunting; } // enable/disable truck hunting calculation + void SetTruckHunting(bool const Value) { truckHunting = Value; } + /*! rotacja kol [obr/s]*/ + double EnginePower = 0.0; /*! chwilowa moc silnikow*/ + double const &Fb() const { return brakingForce; } + double Ff = 0.0; /*przesuniecie, sila hamowania i tarcia*/ + double FStand = 0.0; /*! sila pociagowa i oporow ruchu*/ + bool const &SlippingWheels() const { return slippingWheels; } + bool const &SandDose() const { return sandDose; } /*! poslizg kol, sypanie piasku*/ + bool SandDoseManual = false; /*piaskowanie reczne*/ + bool SandDoseAuto = false; /*piaskowanie automatyczne*/ + bool SandDoseAutoAllow = true; /*zezwolenie na automatyczne piaskowanie*/ + double Sand = 0.0; /*ilosc piasku*/ + /*! przyrosty cisnienia w kroku czasowym*/ + fuel_pump FuelPump; + oil_pump OilPump; + genset_device Genset; // of a dual-mode vehicle, fitted() only with GensetPower + // the source the traction circuit takes its voltage from (the traction selector of a dual-mode vehicle) + enum class traction_mode { catenary, genset }; + traction_mode const &TractionMode() const { return tractionModeSetting; } + bool GensetSelected() const { return tractionModeSetting == traction_mode::genset; } + water_pump WaterPump; + water_heater WaterHeater; + bool const &WaterCircuitsLink() const { return waterCircuitsLink; } // optional connection between water circuits + ByEnd MotorBlowers; + door_data Doors; + float DoorsOpenWithPermitAfter{-1.f}; // remote open if permit button is held for specified time. NOTE: separate from door data as its cab control thing + int const &DoorsPermitLightBlinking() const { return doorsPermitLightBlinking; } // when the doors permit signal light is blinking + + /* + */ + bool const &RadioStopFlag() const { return radioStopFlag; } /*hamowanie nagle*/ + void SetRadioStopFlag(bool const Value) { radioStopFlag = Value; } + int TUHEX_StageActual = 0; /*aktualny stopien tuhexa*/ + bool TUHEX_Active = false; /*czy hamowanie ED wywołane z zewnątrz*/ + // NapUdWsp: integer; + double const &ActFlowSpeed() const { return actFlowSpeed; } /*szybkosc stabilizatora*/ + void SetActFlowSpeed(double const Value) { actFlowSpeed = Value; } + + DamageSet DamageFlag; // the damage of the vehicle + EquipmentFaultSet equipmentFaults; // the faults of the equipment set on the vehicle (SetEquipmentFaults()) + + // EndSignalsFlag: byte; {ABu 060205: zmiany - koncowki: 1/16 - swiatla prz/tyl, 2/31 - blachy prz/tyl} + // HeadSignalsFlag: byte; {ABu 060205: zmiany - swiatla: 1/2/4 - przod, 16/32/63 - tyl} + TCommand CommandIn; + /*komenda przekazywana przez PutCommand*/ + /*i wykonywana przez RunInternalCommand*/ + + TTrackShape RunningShape; /*geometria toru po ktorym jedzie pojazd*/ + TTrackParam RunningTrack; /*parametry toru po ktorym jedzie pojazd*/ + double const &OffsetTrackH() const { return offsetTrackH; } + void SetOffsetTrackH(double const Value) { offsetTrackH = Value; } + double const &OffsetTrackV() const { return offsetTrackV; } /*przesuniecie poz. i pion. w/m osi toru*/ + void SetOffsetTrackV(double const Value) { offsetTrackV = Value; } + + /*-zmienne dla lokomotyw*/ + int const &MainCtrlPos() const { return mainCtrlPos; } /*polozenie glownego nastawnika*/ + void SetMainCtrlPos(int const Value) { mainCtrlPos = Value; } + int const &ScndCtrlPos() const { return scndCtrlPos; } /*polozenie dodatkowego nastawnika*/ + void SetScndCtrlPos(int const Value) { scndCtrlPos = Value; } + int const &LightsPos() const { return lightsPos; } /*polozenie przelacznika wielopozycyjnego swiatel*/ + void SetLightsPos(int const Value) { lightsPos = Value; } + int DirActive = 0; // czy lok. jest wlaczona i w ktorym kierunku: względem wybranej kabiny: -1 - do tylu, +1 - do przodu, 0 - wylaczona + int DirAbsolute = 0; // zadany kierunek jazdy względem sprzęgów (1=w strone 0,-1=w stronę 1) + int const &MainCtrlMaxDirChangePos() const { return mainCtrlMaxDirChangePos; } // can't change reverser state with master controller set above this position + int CabActive = 0; // numer kabiny, z której jest sterowanie: 1 lub -1; w przeciwnym razie brak sterowania - rozrzad + int const &CabOccupied() const { return cabOccupied; } // numer kabiny, w ktorej jest obsada (zwykle jedna na skład) // TODO: move to TController + void SetCabOccupied(int const Value) { cabOccupied = Value; } + bool const &CabMaster() const { return cabMaster; } // czy pojazd jest nadrzędny w składzie + // pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): the vehicle is prepared for being hauled dead in a + // train, see PulleeModeSwitch() + bool const &PulleeMode() const { return pulleeMode; } + inline bool IsCabMaster() const + { + return CabActive == cabOccupied && cabMaster; + } // czy aktualna kabina jest na pewno tą, z której można sterować + bool AutomaticCabActivation = true; // czy zmostkowany rozrzad przelacza sie sam przy zmianie kabiny + int InactiveCabFlag = 0; // co sie dzieje przy dezaktywacji kabiny + bool const &InactiveCabPantsCheck() const { return inactiveCabPantsCheck; } // niech DynamicObject sprawdzi pantografy + void SetInactiveCabPantsCheck(bool const Value) { inactiveCabPantsCheck = Value; } + double LastSwitchingTime = 0.0; /*czas ostatniego przelaczania czegos*/ + int const &WarningSignal() const { return warningSignal; } // 0: nie trabi, 1,2,4: trabi + void SetWarningSignal(int const Value) { warningSignal = Value; } + bool const &DepartureSignal() const { return departureSignalOn; } /*sygnal odjazdu*/ + bool const &InsideConsist() const { return insideConsist; } + void SetInsideConsist(bool const Value) { insideConsist = Value; } + /*-zmienne dla lokomotywy elektrycznej*/ + double enrot = 0.0; // ilosc obrotow silnika + double Im = 0.0; // prad silnika + /* + // currently not used + double IHeating = 0.0; + double ITraction = 0.0; + */ + double Itot = 0.0; // prad calkowity + double TotalCurrent = 0.0; + // momenty + double const &Mm() const { return motorMoment; } + double const &Ft() const { return ft; } + // Ra: Im jest ujemny, jeśli lok jedzie w stronę sprzęgu 1 + // a ujemne powinien być przy odwróconej polaryzacji sieci... + // w wielu miejscach jest używane abs(Im) + int const &Imin() const { return imin; } + int Imax = 0; /*prad przelaczania automatycznego rozruchu, prad bezpiecznika*/ + double EngineVoltage = 0.0; // voltage supplied to engine + int MainCtrlActualPos = 0; /*wskaznik RList*/ + int ScndCtrlActualPos = 0; /*wskaznik MotorParam*/ + bool const &DelayCtrlFlag() const { return delayCtrlFlag; } // czy czekanie na 1. pozycji na załączenie? + bool const &AutoRelayFlag() const { return autoRelayFlag; } /*mozna zmieniac jesli autoRelayType=2*/ + bool FuseFlag = false; /*!o bezpiecznik nadmiarowy*/ + double LouvresOpenPressure{5.0}; // main reservoir pressure [bar] at which the pneumatic louvres of the motor fans open (ET22) + bool ResistorsFlag = false; /*!o jazda rezystorowa*/ + double RventRot = 0.0; /*!s obroty wentylatorow rozruchowych*/ + std::array, 4> PowerCircuits; // 24v, 110v, 3x400v and 3000v power circuits, voltage from local sources and current draw pairs + + /*- zmienne dla lokomotyw z silnikami indukcyjnymi -*/ + double eimic = 0; /*aktualna pozycja zintegrowanego sterowania jazda i hamowaniem*/ + double const &EimicAnalog() const { return eimicAnalog; } /*pozycja zadajnika analogowa*/ + void SetEimicAnalog(double const Value) { eimicAnalog = Value; } + // the demand of the integrated controller the vehicle goes by, the speed control counted /*faktycznie uzywana pozycja zintegrowanego sterowania jazda i hamowaniem*/ + double const &EimicReal() const { return eimicReal; } + void SetEimicReal(double const Value) { eimicReal = Value; } + double eim_localbrake = 0; /*nastawa hamowania dodatkowego pneumatycznego lokomotywy*/ + int EIMCtrlType = 0; /*rodzaj wariantu zadajnika jazdy*/ + bool const &SpeedCtrlTypeTime() const { return speedCtrlTypeTime; } /*czy tempomat sterowany czasowo*/ + int SpeedCtrlAutoTurnOffFlag = 0; /*czy tempomat sam się wyłącza*/ + bool const &EIMCtrlEmergency() const { return eimCtrlEmergency; } /*czy ma dodatkowe zero jazdy i zero hamowania */ + bool const &EIMCtrlMainEmergency() const { return eimCtrlMainEmergency; } /*czy zadajnik typu 2 (Elf) ma pozycje hamowania naglego ponizej swojej pozycji 0*/ + double const &eimicSpeedCtrl() const { return eimicSpeedCtrlValue; } /*pozycja sugerowana przez tempomat*/ + double const &NewSpeed() const { return newSpeed; } /*nowa predkosc do zadania*/ + + /*-zmienne dla drezyny*/ + + /*dla drezyny, silnika spalinowego i parowego*/ + double const &eAngle() const { return eAngleValue; } + + /*-dla wagonow*/ + float const &LoadAmount() const { return loadAmount; } /*masa w T lub ilosc w sztukach - zaladowane*/ + void SetLoadAmount(float const Value) { loadAmount = Value; } + load_attributes LoadType; + // the exchange of the load: +1 unloading, +2 loading, +4 finished, 0 the model of the load updated + int LoadStatus() const { return loadStatus; } + // a step of the exchange: so much taken out, or put in up to the capacity, and the mass with it + void UnloadStep(float Amount); + void LoadStep(float Amount); + void FinishLoadExchange() { loadStatus = 4; } + // the end of the exchange seen to, the model of the load updated + void AcknowledgeLoadExchange() { loadStatus &= 1 | 2; } + void SetLoadStatusForTest(int const Value) { loadStatus = Value; } + // the kind of the load changed, for the model of the load to follow; true once, until changed again + bool LoadTypeChange() const { return loadTypeChange; } + bool TakeLoadTypeChange() + { + auto const changed{loadTypeChange}; + loadTypeChange = false; + return changed; + } + double LastLoadChangeTime = 0.0; // raz (roz)ładowania +#ifdef EU07_USEOLDDOORCODE + bool DoorBlocked = false; // Czy jest blokada drzwi + bool DoorLockEnabled{true}; + bool DoorLeftOpened = false; // stan drzwi + double DoorLeftOpenTimer{-1.0}; // left door closing timer for automatic door type + bool DoorRightOpened = false; + double DoorRightOpenTimer{-1.0}; // right door closing timer for automatic door type +#endif + + int DoubleTr = 1; // trakcja ukrotniona - przedni pojazd 'Winger 160304 + basic_light CompartmentLights; + + bool const &PhysicActivation() const { return physicActivation; } + // what the brake force (Fb) came from when the physics fell asleep (switch_physics()), for the test of ComputeTotalForce(): + // asleep, a vehicle keeps the Fb and FStand of its last step, and a change of these wakes it + struct + { + double cylinder{0.0}; // BrakePress + double spring{0.0}; // brakes.spring.pressure + int manual{0}; // ManualBrakePos + double local{0.0}; // LocalBrakePosA + } sleep_brakes; + + /*ABu: stale dla wyznaczania sil (i nie tylko) po optymalizacji*/ + double TotalMassxg = 0.0; /*totalMass*g*/ + + // the lights switched on at each end (light::), from which the current they draw is counted + ByEnd const &LitLights() const { return litLights; } + void SetLitLights(VehicleEnd const End, int const Lights) { litLights[End] = Lights; } + + // Status nowszego hebelka od przyciemniania swiatel/swiatel dlugich + // 0 - swiatla wylaczone (opcja dziala tylko gdy w fiz zdefiniowano OffState w sekcji Switches; w przeciwnym wypadku pstryk startuje z wartoscia == 1 + // 1 - swiatla normalne przyciemnione + // 2 - swiatla normalne + // 3 - swiatla dlugie przyciemnione + // 4 - swiatla dlugie normalne + + struct dimPosition + { + bool isOff = false; + bool isDimmed = false; + bool isHighBeam = false; + }; + + // default positions + std::vector dimPositions = {{false, false, false}, // 0 - Not dimmed + {false, true, false}}; // 1 - Dimmed + + int const &DimmerPosition() const { return modernDimmerPosition; } + void SetDimmerPosition(int const Value) { modernDimmerPosition = Value; } + int modernDimmerDefaultPosition{0}; + // bool modernContainOffPos{true}; + bool const &enableModernDimmer() const { return enableModernDimmerValue; } + // the given dimmer position brought into the DimmerList, to its first or last entry; 0 for an empty list + int clampDimmerPosition(int Position) const; + // the entry of the current dimmer position, or a plain one (not off, not dimmed, no high beam) when the + // position is outside the DimmerList: the .fiz can give a short or an empty list, or a DefaultPos past its end + dimPosition currentDimPosition() const; + // moves the dimmer by Step positions within the DimmerList, around to its other end when it can cycle; + // a position outside the list is brought into it first. false when the dimmer doesn't move + bool stepDimmerPosition(int Step); + + // Barwa reflektora + int refR{255}; // Czerwony + int refG{255}; // Zielony + int refB{255}; // Niebieski + + double dimMultiplier{0.6f}; // mnoznik swiatel przyciemnionych + double normMultiplier{1.0f}; // mnoznik swiatel zwyklych + double highDimMultiplier{2.5f}; // mnoznik dlugich przyciemnionych + double highMultiplier{2.8f}; // mnoznik dlugich + + + int const &AIHintPantstate() const { return aiHintPantstate; } // suggested pantograph setup + // suggested pantograph setup in shunting (AI: ShuntPantstate=, eu07/maszyna#461), the bits as in Pantstate: 1 front, + // 2 rear, 3 both; 0 (the default) shunts with the pantographs handled as in train mode + int const &AIHintShuntPantstate() const { return aiHintShuntPantstate; } + bool AIHintPantUpIfIdle{true}; // whether raise both pantographs if idling for a while + double const &AIHintLocalBrakeAccFactor() const { return aiHintLocalBrakeAccFactor; } // suggested acceleration weight for local brake operation + + Vehicle(double VelInitial, std::string const &TypeNameInit, std::string const &NameInit, int Cab); + // obsługa sprzęgów + static double CouplerDist(physics::Vehicle const *Left, physics::Vehicle const *Right); + static double Distance(const TLocation &Loc1, const TLocation &Loc2, const TDimension &Dim1, const TDimension &Dim2); + bool Attach(int ConnectNo, int ConnectToNr, physics::Vehicle *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true); + int DettachStatus(int ConnectNo); + int DettachStatus(VehicleEnd const ConnectNo) + { + return DettachStatus(NumberOf(ConnectNo)); + } + bool Dettach(int ConnectNo); + // the same by the ends, where they are known to be ends + bool Attach(VehicleEnd const ConnectNo, VehicleEnd const ConnectToNr, physics::Vehicle *ConnectTo, CouplingSet CouplingType, bool Enforce = false, bool Audible = true) + { + return Attach(NumberOf(ConnectNo), NumberOf(ConnectToNr), ConnectTo, CouplingType, Enforce, Audible); + } + bool Dettach(VehicleEnd const ConnectNo) + { + return Dettach(NumberOf(ConnectNo)); + } + void damage_coupler(VehicleEnd const End); + // repairs the broken coupler of the end, and the one of the vehicle it was coupled with, so they can be coupled + // again; the vehicles clear their coupler damage once neither of their couplers is broken. returns: whether there + // was a broken coupler to repair + bool repair_coupler(VehicleEnd const End); + void Derail(DerailReason Reason); + // the velocity of the vehicles coupled to this one changes by the Change along the axis of this one [m/s], as the + // legacy derailment changes the velocity of this one (physics.collisions new) + void change_train_velocity(double Change); + // physics.derailment new: the criteria of derailment.h over the step, which travelled the Distance [m]; monitor: what + // they would do, to the log + void check_derailment(TTrackShape const &Shape, TTrackParam const &Track, double Distance); + // the vehicle leaves the rails, as the criteria of derailment.h found + void derail(derailment::verdict const &Verdict, derailment::vehicle_state const &Vehicle, derailment::track_state const &Track, std::string const *TrackName = nullptr); + // height of the centre of gravity above the rail with the load [m] + double centre_of_gravity() const; + // the vehicle is back on the rails (resetconsist, SetDamage taking VehicleDamage::derailed off): not derailed any more, and the + // criteria of derailment start from scratch, so a later derailment goes the way its model has it + void rerail(); + // what resetconsist does to a vehicle: no damage of any kind, the alarm chain released, back on the rails + void repair_damage(); + // how the vehicle left the rails by the criteria of derailment.h: upright, or on its side. none for any other + // derailment, which stops it as the legacy model does (with physics.collisions new by a friction of its weight, the + // forces of the vehicles coupled to it acting on it) + derailment::outcome const &Derailed() const { return derailOutcome; } + // physics.derailment new: how the vehicle left the rails, for the way it leaves the track (vehicle/derailmotion.h): + // what derailed it, the lateral acceleration of its body out of the curve then [m/s2] (negative into the curve, where a + // buckle bends the line the other way), and the side it was pulled off to by a coupling (1 the left of its front, -1 + // the right; 0 the side the acceleration throws it to, from the track) + derail_motion::cause const &DerailCause() const { return derailCause; } + double const &DerailAcceleration() const { return derailAcceleration; } + int const &DerailSide() const { return derailSide; } + // the vehicle off the track, on the ground: begun and stepped by TDynamicObject, which knows the ground; its friction + // and the grade under it go into the forces of this one + derail_motion::body OffTrack; + // physics.derailment new: the vehicle derailed by the physical criteria, the end of the track or a collision has to + // leave the track and its motion on the ground isn't begun yet. never with physics.derailment monitor, old or off + bool leaves_track() const; + // physics.derailment new: a coupling of a vehicle off the track pulls this one off the rails sideways, to the Side + // (1 the left of its front, -1 the right), with the lateral acceleration [m/s2] of the pull on it + void pull_off(int Side, double Acceleration, std::string const &Why); + // physics.collisions new: what the vehicle is for the defaults of its crush and its buffers, the crush curve and the + // height of the buffers of an end, and how long the push of its ends held its wheels over the climbing limit + collision::vehicle_kind collision_kind() const; + collision::crush_curve crush_curve_at(VehicleEnd End) const; + double buffer_height_at(VehicleEnd End) const; + collision::pushed_monitor pushed_off_monitor; + // how the vehicle left the rails in a collision (physics.collisions new): overriding or pushed off, NONE otherwise + DerailReason const &CollisionDerail() const { return collisionDerail; } + // physics.collisions monitor: how many crushes the log told of, of the hits of this vehicle on the others + int const &crush_reports() const { return crushreportsValue; } + // physics.collisions new: the hit of the end on the stop of its buffers, harder than the steel takes, crushes the + // weaker end and may let one vehicle climb onto the other one, see collision.h. returns: whether it did, and the + // velocities took the hit; the legacy collision takes the rest. physics.collisions monitor: the log tells what the + // crush of the whole hit would be, once for a hit, nothing changes, and it returns false + bool crush_hit(VehicleEnd End, double dt); + // the force pressing the ends pushes the vehicle off the track (physics.collisions new), the step travelled the + // Distance [m]: the flange climbs while the wheels roll on + void check_pushed_off(double dt, double Distance); + // the vehicle leaves the rails in a collision, the reason told in the log, and slides on as the criteria of + // derailment.h have it + void derail_in_collision(DerailReason Reason, std::string const &Why); + bool DirectionForward(); + bool DirectionBackward(void); /*! kierunek ruchu*/ + bool EIMDirectionChangeAllow(void) const; + inline double IsVehicleEIMBrakingFactor() const + { + return brakes.electrodynamic.on && ResistorsFlag ? 0.0 : inductionMotor.state.lineCurrent < 0 ? -1.0 : 1.0; + } + void BrakeLevelSet(double b); + bool BrakeLevelAdd(double b); + bool IncBrakeLevel(); // wersja na użytek AI + bool DecBrakeLevel(); + bool ChangeCab(int direction); + bool CurrentSwitch(bool const State); + bool IsMotorOverloadRelayHighThresholdOn() const; + void UpdateBatteryVoltage(double dt); + double BatteryDrain(double dt, bool converteractive) const; + double BatteryDrainCharged(double dt, bool converteractive) const; + double BatteryDrainLow(double dt, bool converteractive) const; + double BatteryDrainSwitchedOff(double dt) const; + double ComputeMovement(double dt, double dt1, const TTrackShape &Shape, TTrackParam const &Track, TTractionParam const &ElectricTraction, TLocation const &NewLoc, + TRotation const &NewRot); // oblicza przesuniecie pojazdu + double FastComputeMovement(double dt, const TTrackShape &Shape, TTrackParam &Track, TLocation const &NewLoc, TRotation const &NewRot); // oblicza przesuniecie pojazdu - wersja zoptymalizowana + void compute_movement_(double const Deltatime); + double ShowEngineRotation(int VehN) const; + + // Q ******************************************************************************************* + double GetTrainsetVoltage(CouplingSet const couplings = Coupling::heating | Coupling::highVoltage) const; + double GetTrainsetHighVoltage() const; + // what turns the physics on, counted for the debug panel (Timer::switching_counter) + enum class wake_cause + { + other, + mainpipe, // air flowing in from a neighbour along the brake pipe + scndpipe, // along the main reservoir pipe + command, + speed, // the test of ComputeTotalForce(): the vehicle moves + acceleration, // accelerates + neighbour, // a neighbour moves or accelerates + rest // active cab, switching, ezt/dmu + }; + bool switch_physics(bool const State, wake_cause const Cause = wake_cause::other); + // whether the vehicle accelerates, for the test which turns the physics off in vehicles standing still (ComputeTotalForce()). + // standing still, its acceleration is the pull of the slope and of the couplers, as the brakes and the resistance count only + // against a speed (FTotal); with Global.physics_sleepheld one held by them, the way ComputeMovement() keeps it standing, doesn't + bool accelerating() const; + // with Global.physics_sleepheld, wakes the physics of a vehicle a brake of which was set by hand: one held by its brakes sleeps + // with the brake force it had (accelerating()) + void wake_for_brake(); + // whether the brakes of a vehicle whose physics sleeps have changed since it fell asleep, see sleep_brakes + bool brakes_changed_asleep() const; + double LocalBrakeRatio(void) const; + double ManualBrakeRatio(void) const; + double PipeRatio(void) const; /*ile napelniac*/ + double RealPipeRatio(void) const; /*jak szybko*/ + double BrakeVP(void) const; + double EngineRPMRatio() const; // returns current engine revolutions as percentage of max engine revolutions, in range 0-1 + double EngineIdleRPM() const; + double EngineMaxRPM() const; + + /*! przesylanie komend sterujacych*/ + bool SendCtrlToNext(VehicleCommand const CtrlCommand, double const ctrlvalue, double const dir, CouplingSet const Couplertype = Coupling::control); + bool SetInternalCommand(VehicleCommand const NewCommand, double NewValue1, double NewValue2, CouplingSet const Couplertype = Coupling::control); + bool RunCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet const Couplertype = Coupling::control, std::string_view Argument = {}); + // the parts of RunCommand(), by the area of the commands + bool RunControllerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunRelaysCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunCabCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunBrakeCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunBrakeEquipmentCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunAuxiliariesCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunPumpsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunBlowersCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunPowerCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + bool RunDoorsCommand(VehicleCommand const Command, double CValue1, double CValue2, CouplingSet Couplertype, bool &OK); + void DoorPermitCommand(double CValue1, double CValue2); + void DoorRemoteCommand(bool Open, double CValue1, double CValue2); + bool RunLoadCommand(VehicleCommand const Command, double CValue1, double CValue2, std::string_view Argument, bool &OK); + bool RunInternalCommand(); + void PutCommand(std::string const &NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation); + bool CabActivisation(bool const Enforce = false); + bool CabDeactivisation(bool const Enforce = false); + bool CabActivisationAuto(bool const Enforce = false); + bool CabDeactivisationAuto(bool const Enforce = false); + + /*! funkcje zwiekszajace/zmniejszajace nastawniki*/ + /*! glowny nastawnik:*/ + bool IncMainCtrl(int CtrlSpeed); + bool DecMainCtrl(int CtrlSpeed); + // the parts of IncMainCtrl() and DecMainCtrl() which depend on the kind of the engine + bool IncMainCtrlByEngine(int CtrlSpeed); + bool IncMainCtrlSeriesMotor(int CtrlSpeed); + bool DecMainCtrlByEngine(int CtrlSpeed); + bool DecMainCtrlSeriesMotor(int CtrlSpeed); + bool IsMainCtrlActualNoPowerPos() const; // whether the master controller is actually set to position which won't generate any extra power + bool IsMainCtrlNoPowerPos() const; // whether the master controller is set to position which won't generate any extra power + bool IsMainCtrlMaxPowerPos() const; + int MainCtrlNoPowerPos() const; // highest setting of master controller which won't cause engine to generate extra power + int MainCtrlActualPowerPos() const; // current actual setting of master controller, relative to the highest setting not generating extra power + int MainCtrlPowerPos() const; // current setting of master controller, relative to the highest setting not generating extra power + // positions the master controller of the EIMCtrlType 2 (Elf) has below its own position 0, the emergency brake (0 or 1) + int EIMCtrlEmergencyPositions() const; + // whether the master controller is in its emergency brake position (EIMCtrlType 2 with EIMCtrlMainEmergency) + bool IsMainCtrlEmergencyPos() const; + // the master controller position sent to the coupled vehicles ("MainCtrl"), the same with and without + // EIMCtrlMainEmergency: the Elf's positions without the emergency brake one, which goes as the full braking + int MainCtrlPosForCoupled() const; + // the master controller position of this vehicle for one received from a coupled vehicle ("MainCtrl") + int MainCtrlPosFromCoupled(int Position) const; + /*! pomocniczy nastawnik:*/ + bool IncScndCtrl(int CtrlSpeed); + bool DecScndCtrl(int CtrlSpeed); + int GetVirtualScndPos() const; + // whether ScndCtrlResistiveLock keeps the shunt controller from being moved at the current master controller position + bool IsScndCtrlLockedByMainCtrl() const; + // ScndCtrlResistiveLock: the shunt controller drops to 0 once the master controller is at zero or on a resistive position, so it + // can't stay engaged there, locked in place (eu07/maszyna#402) + void ScndCtrlResistiveLockCheck(); + // NOTE: with the cruise control, either end of the secondary controller, as before the split of the two (eu07/maszyna#69) + bool IsScndCtrlNoPowerPos() const; + bool IsScndCtrlMaxPowerPos() const; + + bool AddPulseForce(int Multipler); /*dla drezyny*/ + + bool SandboxManual(bool const State, range_t const Notify = range_t::consist); /*wlacza/wylacza reczne sypanie piasku*/ + bool SandboxAuto(bool const State, range_t const Notify = range_t::consist); /*wlacza/wylacza automatyczne sypanie piasku*/ + bool Sandbox(bool const State, range_t const Notify = range_t::consist); /*wlacza/wylacza sypanie piasku*/ + bool SandboxAutoAllow(bool const State); /*wlacza/wylacza zezwolenie na automatyczne sypanie piasku*/ + + /*! zbijanie czuwaka/SHP*/ + void SecuritySystemReset(void); + void SecuritySystemCheck(double dt); + + bool BatterySwitch(bool State, range_t const Notify = range_t::consist); + bool EpFuseSwitch(bool State); + bool SpringBrakeActivate(bool State); + bool SpringBrakeShutOff(bool State); + bool SpringBrakeRelease(); + bool PulleeModeSwitch(bool const State); + + /*! stopnie hamowania - hamulec zasadniczy*/ + bool IncBrakeLevelOld(void); + bool DecBrakeLevelOld(void); + bool IncLocalBrakeLevel(float const CtrlSpeed); + bool DecLocalBrakeLevel(float const CtrlSpeed); + /*! ABu 010205: - skrajne polozenia ham. pomocniczego*/ + bool IncManualBrakeLevel(int CtrlSpeed); + bool DecManualBrakeLevel(int CtrlSpeed); + /*! oddzielny nastawnik hamulca elektrodynamicznego (gdy SplitEDPneumaticBrake)*/ + bool IncDynamicBrakeLevel(float const CtrlSpeed); + bool DecDynamicBrakeLevel(float const CtrlSpeed); + bool DynamicBrakeLevelSet(double Position); + double DynamicBrakeRatio(void) const; + bool DynamicBrakeAvailable(void) const; /*czy ED dostepny w aktualnym oknie predkosci Vh0..Vh1*/ + bool DynamicBrakeSwitch(bool Switch); + bool RadiostopSwitch(bool Switch); + bool AlarmChainSwitch(bool const State); + bool AntiSlippingBrake(void); + bool BrakeReleaser(int state); + bool UniversalBrakeButton(int button, int state); /*uniwersalny przycisk hamulca*/ + bool SwitchEPBrake(int state); + // whether the EP brake control of the cab has power: battery, the reverser out of neutral and the EP fuse on + bool EPBrakeControlPowered() const; + bool AntiSlippingButton(void); /*! reczny wlacznik urzadzen antyposlizgowych*/ + + /*funkcje dla ukladow pneumatycznych*/ + bool IncBrakePress(double &brake, double PressLimit, double dp); + bool DecBrakePress(double &brake, double PressLimit, double dp); + bool BrakeDelaySwitch(int BDS); /*! przelaczanie nastawy opoznienia*/ + bool IncBrakeMult(void); /*przelaczanie prozny/ladowny*/ + bool DecBrakeMult(void); + /*pomocnicze funkcje dla ukladow pneumatycznych*/ + void UpdateBrakePressure(double dt); + void UpdatePipePressure(double dt); + // the parts of UpdatePipePressure() + void UpdateLocalBrakeValve(double dt); + void UpdateMainValve(double dt); + double MainValveSupply(); + double MainValveHandlePosition() const; + void UpdateEmergencyValve(double dt); + void UpdateDistributorSettings(); + void UpdateEPBrake(); + void CompressorCheck(double dt); /*wlacza, wylacza kompresor, laduje zbiornik*/ + void UpdatePantVolume(double dt); // Ra + void PantPressureSwitchCheck(); + void PantPressureSwitchTrip(); + // what the air of the pantographs needs to know in the step + PantographAirSupply PantographAirSupplyNow() const; + void UpdateScndPipePressure(double dt); + void UpdateSpringBrake(double dt); + double GetDVc(double dt); + int PipeCouplersSubsteps(double dt) const; + double GetScndDVc(double dt); + int ScndPipeCouplersSubsteps(double dt) const; + // the air exchange through the brake and main reservoir hoses, after the vehicles stepped + static void UpdatePipeCouplers(std::vector const &Vehicles, double dt); + + /*funkcje obliczajace sily*/ + void ComputeConstans(void); // ABu: wczesniejsze wyznaczenie stalych dla liczenia sil + void ComputeMass(void); + void ComputeTotalForce(double dt); + double Adhesive(double staticfriction) const; + double TractionForce(double dt); + // the parts of TractionForce(), in the order it makes them + double UpdateEngineRevolutions(double dt, double &dtrans, double &dmoment); + double DieselElectricTargetRevolutions(); + void UpdateVentilators(double dt); + void UpdateResistorBlowers(double dt); + double UpdateEnginePower(); + void VoltageRelaysCheck(); + void DumbTractionForce(double PosRatio); + void WheelsDrivenTractionForce(double dt); + void SeriesMotorTractionForce(double dt); + void SeriesMotorDynamicBrake(double dt); + void DieselEngineTractionForce(double dt, double dmoment, double dtrans); + void DieselElectricTractionForce(double tmp); + void DieselElectricShuntForce(double tmpV, double &tmp); + double DieselElectricDigitalForce(double tmpV, double &tempUmax, double &tempImax); + double DieselElectricForce(double tmpV, double LinePower, double Ratio, double HyperbolaPower) const; + void DieselElectricShuntPower(double tmp); + void DieselElectricGenerator(double tmp, double tempUmax, double tempImax); + void ShuntFieldRelaysCheck(double tmpV, double PosRatio, double tmp); + void ShuntFieldRelaysType2(double tmp); + void ShuntFieldRelaysType41(double tmpV); + void ShuntFieldRelaysType45(); + void ShuntFieldRelaysType46(); + void ShuntFieldRelaysType46Up(); + void ShuntFieldRelaysType46Down(); + void InductionMotorTractionForce(double dt); + void InductionMotorSpeedControl(double dt); + void SpeedControlByTime(double dt); + void SpeedControlByPosition(double dt); + void InductionMotorBrakeBlending(double ActiveInverters, double &PosRatio, double &tmp); + void InductionMotorDynamicBrakeFlag(); + double InductionMotorBrakeRatio(double ActiveInverters, double edBCP); + void InductionMotorDrive(double dt); + void InductionMotorForceLimits(); + void UpdateInverterFrequency(); + void InductionMotorOff(); + // the dynamic brake of a diesel-electric vehicle: the effort following the demand, the force it gives at the speed + void update_dieselelectric_dynamic_brake(double dt); + double dieselelectric_dynamic_brake_demand() const; // 0..1, the effort the driver asks for + double dieselelectric_dynamic_brake_limit() const; // [N] the force at full effort at the speed + void apply_dieselelectric_dynamic_brake(double dt); // the force in place of the drive's one, over the step dt + double dieselelectric_motor_current(double Moment) const; // the current of the motors giving the moment + double FrictionForce() const; + double BrakeForceR(double ratio, double velocity) const; + double BrakeForceP(double press, double velocity) const; + double BrakeForce(const TTrackParam &Track); + double CouplerForce(VehicleEnd const End, double dt); + void CouplerStretchCheck(VehicleEnd End, double CF, double dt); + // whether the coupling at the end is computed by the physical model: couplerphysics set in eu07.ini, and this + // vehicle or the one at the end covered by it (CouplerPhysics), or every vehicle with couplerphysics all + bool coupler_physics_at(VehicleEnd const End) const; + // the force of the coupling at the end by the physical model (couplerphysics in eu07.ini), see couplerphysics.h + double coupler_force_physical(VehicleEnd const End, double const dt); + // how much the distance to the vehicle at the End grows [m, or m/s] when this vehicle moves (Own) and the other one + // moves (Other) along their axes: along a track the difference of the two moves; with either vehicle off the + // track (Neighbours[End].off_track) by the shares of them the ends have in the direction they are apart in + double coupler_gap_change(VehicleEnd const End, double const Own, double const Other) const; + // with the physical model: whether the vehicles at the end hit the stop of their springs at the last update and + // still close in on it, so that they collide; a hit hard enough breaks the coupling or crushes the buffers + bool coupler_stop_hit(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd); + // couples the automatic couplers of the end and of the other vehicle pressed against each other, unless the hit + // is too fast for them to catch + void automatic_coupling(VehicleEnd const End, physics::Vehicle &Other, VehicleEnd const OtherEnd); + void CollisionDetect(VehicleEnd const End, double const dt); + // closing speed of a collision [km/h] above which the vehicles involved may derail, adjusted for their mass ratio + static constexpr double SafeCollisionVelocity{15.0}; + // closing speed [km/h] of the End of this vehicle and the OtherEnd of the other vehicle it touches, along the coupler + // axis: the sum of the speeds in a head-on collision, the difference in a rear-end one, negative when they part + double CollisionVelocity(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; + // velocity [m/s] of this vehicle relative to the other vehicle it touches with its End and the OtherEnd of the + // other one, along this vehicle's axis + double CouplerVelocityDifference(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; + // whether the automatic couplers at the End of this vehicle and the OtherEnd of the other one can catch each other on + // contact, rather than the vehicles colliding (with crash damage enabled, only at a closing speed which doesn't derail them) + bool AutomaticCouplingSafe(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; + // whether the control coupling (multiple-unit control) can join the End of this vehicle and the OtherEnd of the other + // one: not between an electric and a diesel traction vehicle, unless both couplers name the same control system + // (ControlType). Vehicles without own traction (cars, control trailers) take any. Global.control_coupling_engine_check + // off allows it always (eu07/maszyna#520) + bool ControlCouplingAllowed(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd) const; + // the CouplingType to join the End of this vehicle and the OtherEnd of the other one with, without the control coupling + // when ControlCouplingAllowed() rules it out. a permanent coupling (of the vehicles of one unit) is kept whole + CouplingSet CompatibleCoupling(VehicleEnd const End, physics::Vehicle const &Other, VehicleEnd const OtherEnd, CouplingSet const CouplingType) const; + // the horns of the Signal (warningSignal bits) which have the air or the voltage they need to sound + int SoundingHorns(int const Signal) const; + // whether the signal lamps of the main circuit (line contactors, ground relay, motor overload relays) can light: + // the pressure switch, when fitted, cuts the start off and puts them out, otherwise they go out once the brakes are applied + bool MainCircuitLampsEnabled() const + { + return false == protection.PressureSwitchTripped() && (protection.config.hasPressureSwitch || brakes.cylinderPressure < 1.0); + } + // whether an emergency brake application holds the line breaker open: the brake pipe below the pressure taken for one + // (EmergencyBrakeMainOffPressure) while the master controller is on a power position + bool EmergencyBrakeHoldsMainOff() const + { + return lineBreaker.config.emergencyOffPressure > 0.0 && brakePipe.Pressure() < lineBreaker.config.emergencyOffPressure && false == IsMainCtrlNoPowerPos(); + } + // whether the lamp of the open line contactors is lit. on the electric locomotives it tells the start can be made, so + // it goes out with the start cut off; on the diesel-electric ones (the SU45 and SU46 family) it just tells the + // contactors are open, whatever opened them: the master controller at 0, or the pressure switch (eu07/maszyna#263) + bool LineContactorsLampLit() const + { + if (EngineType == TEngineType::DieselElectric) + { + return false == lineContactors.IsClosed(); + } + return false == lineContactors.IsClosed() && MainCircuitLampsEnabled(); + } + // the vehicles the line breaker / engine start switch of this vehicle works, and its engine stopping on its own + // stops: the whole consist, or with JointEngineStart=No this vehicle alone (eu07/maszyna#80) + range_t MainSwitchRange() const + { + return lineBreaker.config.jointStart ? range_t::consist : range_t::local; + } + // whether the pneumatic louvres of the motor fans are still closed, the main reservoir short of the pressure that opens them + bool LouvresClosed() const + { + return air.MainReservoirPressure() < LouvresOpenPressure; + } + // whether the devices the line contactors are interlocked with (LineContactorsInterlock) let them close + bool LineContactorsInterlockReleased() const; + // whether the line contactors wait for the converter of the vehicle, switched off with its local switch (converterlocal_sw). + // the AI driver doesn't leave it so: the converters of the other vehicles running, it would wait for the contactors forever + bool LineContactorsHeldByLocalConverterSwitch() const + { + return lineContactors.config.interlock == line_contactors_interlock::converter && false == converter.LocalSwitchOn(); + } + // whether the vehicle has a driver's cab: it has the driver's brake valve (BrakeHandle in the Cntrl. section of the + // .fiz), which the wagons and most cars of the units without a cab don't (a few copy the Cntrl. section of the cab + // car, as the EN57 s car does). it's the vehicle type's, unlike the cab the scenario puts a driver in + bool HasDriverCab() const + { + return brakes.config.driverValveType != TBrakeHandle::NoHandle; + } + // whether the cab command opening the main circuit opens it where the only cab switch of the circuit is the button + // closing it: on a diesel that's the starter button, and the command is the one way to stop an engine whose fuel pump + // starts on its own (eu07/maszyna#427). the other vehicles with such a button keep ignoring the command + bool MainCircuitOpensWithStarterOnly() const + { + return EngineType == TEngineType::DieselEngine || EngineType == TEngineType::DieselElectric; + } + // whether the pumps a joint oil and fuel pump switch works, those not started automatically, are all switched on + bool OilFuelPumpsEnabled() const + { + auto const fuelmanual{FuelPump.start_type != start_t::automatic}; + auto const oilmanual{OilPump.start_type != start_t::automatic}; + return (fuelmanual || oilmanual) && (false == fuelmanual || FuelPump.is_enabled) && (false == oilmanual || OilPump.is_enabled); + } + // whether the radio is switched on, its power supply isn't cut off and it has the low voltage to work + bool RadioPowered() const + { + return radio && radioFuse && (lowVoltage.Is24vAvailable() || lowVoltage.Is110vAvailable()); + } + /*obrot kol uwzgledniajacy poslizg*/ + double ComputeRotatingWheel(double WForce, double dt, double n) const; + + /*--funkcje dla lokomotyw*/ + bool WaterPumpBreakerSwitch(bool State, range_t const Notify = range_t::consist); // water pump breaker state toggle + bool WaterPumpSwitch(bool State, range_t const Notify = range_t::consist); // water pump state toggle + bool WaterPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // water pump state toggle + bool WaterHeaterBreakerSwitch(bool State, range_t const Notify = range_t::consist); // water heater breaker state toggle + bool WaterHeaterSwitch(bool State, range_t const Notify = range_t::consist); // water heater state toggle + bool WaterCircuitsLinkSwitch(bool State, range_t const Notify = range_t::consist); // water circuits link state toggle + bool FuelPumpSwitch(bool State, range_t const Notify = range_t::consist); // fuel pump state toggle + bool FuelPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // fuel pump state toggle + bool OilPumpSwitch(bool State, range_t const Notify = range_t::consist); // oil pump state toggle + bool OilPumpSwitchOff(bool State, range_t const Notify = range_t::consist); // oil pump state toggle + bool MotorBlowersSwitch(bool State, VehicleEnd const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle + bool MotorBlowersSwitchOff(bool State, VehicleEnd const Side, range_t const Notify = range_t::consist); // traction motor fan state toggle + bool CompartmentLightsSwitch(bool State, range_t const Notify = range_t::consist); // compartment lights state toggle + bool CompartmentLightsSwitchOff(bool State, range_t const Notify = range_t::consist); // compartment lights state toggle + bool MainSwitch(bool const State, range_t const Notify = range_t::consist); /*! wylacznik glowny*/ + void MainSwitch_(bool const State); + bool MainSwitchCheck() const; // checks conditions for closing the line breaker + bool ConverterSwitch(bool State, range_t const Notify = range_t::consist); /*! wl/wyl przetwornicy*/ + bool CompressorSwitch(bool State, range_t const Notify = range_t::consist); /*! wl/wyl sprezarki*/ + bool ChangeCompressorPreset(int const Change, range_t const Notify = range_t::consist); + bool HeatingSwitch(bool const State, range_t const Notify = range_t::consist); + void HeatingSwitch_(bool const State); + double EnginePowerSourceVoltage() const; // returns voltage of defined main engine power source + bool TractionModeSwitch(traction_mode const Mode, range_t const Notify = range_t::consist); // traction selector of a dual-mode vehicle + bool GensetSwitch(bool const State, range_t const Notify = range_t::consist); // genset start/stop request + double TractionSourceVoltage() const; // of the vehicle's own source the traction selector picks: the pantographs' or the genset's + double TractionSupplyVoltage() const; // what the traction circuit gets: the own source's, or the train's high voltage line's + double TractionSupplyMinVoltage() const; // below it the line breaker opens (undervoltage) + double GensetTractionPowerLimit() const; // [kW] at the wheels, the largest double unless running on the genset + double CatenaryCurrent() const; // [A] what the vehicle draws through its pantographs, if they touch the wire + // whether the main circuit feeds what runs on it (the converter, a compressor, the heating, the motor and resistor + // blowers, the traction motors): the line breaker closed, and where it closes ahead of the pantographs and holds + // without traction voltage (PantographsRequireMains) also the voltage there, at least the one the undervoltage + // trip takes. everywhere else it's the same as Mains + bool MainCircuitPowered() const; + + /*-funkcje typowe dla lokomotywy elektrycznej*/ + void LowVoltagePowerCheck(double const Deltatime); + void MainsCheck(double const Deltatime); + void PowerCouplersCheck(double const Deltatime, Coupling const kind); + // the parts of PowerCouplersCheck() + double LocalPowerVoltage(Coupling kind); + void PowerCouplersVoltage(Coupling kind, double abslocalvoltage, bool localpowersource); + void PowerCouplersCurrent(Coupling kind, bool localpowersource); + double *PowerCircuitCurrent(Coupling kind); + void ConverterCheck(double const Timestep); // przetwornica + void HeatingCheck(double const Timestep); + void WaterPumpCheck(double const Timestep); + void WaterHeaterCheck(double const Timestep); + void FuelPumpCheck(double const Timestep); + void OilPumpCheck(double const Timestep); + void MotorBlowersCheck(double const Timestep); + // whether the circuit a traction motor blower runs off has power: the battery, the converter or the main circuit, by its start type + bool MotorBlowerPowerIsAvailable(cooling_fan const &Blower) const; + void PantographsCheck(double const Timestep); + void GensetCheck(double const Deltatime); + void LightsCheck(double const Timestep); + bool FuseOn(range_t const Notify = range_t::consist); // bezpiecznik nadamiary + bool FuseFlagCheck(void) const; // sprawdzanie flagi nadmiarowego + void FuseOff(void); // wylaczenie nadmiarowego + // the faults of the equipment the scenery or the network sets: each sets its fault, or clears it where it was set + void SetEquipmentFaults(EquipmentFaultSet Faults); + // the stabiliser of the brake pipe set to the pressure the pipe has, as a driver taking over a cab finds it + void ResetPipeStabiliser() + { + brakes.pipeLimiterPressure = brakePipe.Pressure(); + actFlowSpeed = 0; + } + // the spring brake released by hand, without the command to the other vehicles (SpringBrakeActivate()) + void ReleaseSpringBrake() { brakes.spring.activate = false; } + // the mode of the brake (bom_*: PS/PN/EP/MED) set at the selector + void SetBrakeOperatingMode(int const Mode) { brakes.operatingMode = Mode; } + // the brake cut out or put back by the player, which the AI's wagon inspector no longer puts back on its own + void ClaimBrakeCutOut() { brakes.cutOutByInspector = false; } + // the pressure of the brake pipe of the consist, as the driver's vehicle measures it + void SetEquivalentPipePressure(double const Pressure) { brakes.equivalentPipePressure = Pressure; } + // the inverters of an induction motor drive, switched in and out from the cab + bool InverterActivated(std::size_t const Index) const { return inductionMotor.inverters[Index].Activate; } + void SwitchInverter(std::size_t const Index, bool const State) { inductionMotor.inverters[Index].Activate = State; } + // the distance run, kept between the sessions, and whether a cab shows it + void SetOdometer(odometer::reading const &Reading) { Odometer = Reading; } + void ShowOdometer() { Odometer.shown = true; } + bool UniversalResetButton(int const Button, range_t const Notify = range_t::consist); + bool RelayReset(int const Relays, range_t const Notify = range_t::consist); // resets specified relays + // the drive of the kind of engine of the vehicle (physics/components/drive.h) + TractionDrive const &Drive() const; + double ShowCurrent(int AmpN) const; // pokazuje bezwgl. wartosc pradu na wybranym amperomierzu + double ShowCurrentP(int AmpN) const; // pokazuje bezwgl. wartosc pradu w wybranym pojezdzie //Q 20160722 + + /*!o pokazuje bezwgl. wartosc obrotow na obrotomierzu jednego z 3 pojazdow*/ + /*function ShowEngineRotation(VehN:int): integer; //Ra 2014-06: przeniesione do C++*/ + /*funkcje uzalezniajace sile pociagowa od predkosci: v2n, n2r, current, momentum*/ + double v2n(void); + double Current(double n, double U); + // the parts of Current() + void UpdateSeriesMotorDynamicBrakeFlag(); + double SeriesMotorCurrent(double n, double U, double R, double Mn) const; + double SeriesMotorDrivingCurrent(double n, double U, double Rz, double Mn, int SP) const; + void MotorFailuresCheck(double n); + double Momentum(double I) const; + double MomentumF(double I, double Iw, int SCP) const; + + bool CutOffEngine(void); // odlaczenie udszkodzonych silnikow + /*funkcje automatycznego rozruchu np EN57*/ + bool MaxCurrentSwitch(bool State, range_t const Notify = range_t::consist); // przelacznik pradu wysokiego rozruchu + bool MinCurrentSwitch(bool State); // przelacznik pradu automatycznego rozruchu + bool AutoRelaySwitch(bool State); // przelacznik automatycznego rozruchu + bool AutoRelayCheck(); // symulacja automatycznego rozruchu + // the parts of AutoRelayCheck() + bool AutoRelayShuntStep(bool ARFASI2); + bool AutoRelayMainStep(bool ARFASI); + bool AutoRelayMainUp(bool ARFASI); + bool AutoRelayMainNotchUp(); + bool AutoRelayMainDown(); + bool AutoRelayLineContactorsStep(bool motorconnectorsoff); + bool CamshaftRunDown(); + bool CamshaftRunDownEMU(); + bool MotorConnectorsCheck(); + bool ResistorsFlagCheck(void) const; // sprawdzenie kontrolki oporow rozruchowych NBMX + + bool OperatePantographsValve(operation_t const State, range_t const Notify = range_t::consist); + bool OperatePantographValve(VehicleEnd const End, operation_t const State, range_t const Notify = range_t::consist); + bool DropAllPantographs(bool const State, range_t const Notify = range_t::consist); + + void CheckEIMIC(double dt); // sprawdzenie i zmiana nastawy zintegrowanego nastawnika jazdy/hamowania + // the parts of CheckEIMIC(), by the kind of the controller + void EIMICFromController(double brakeDemand, double offset, double multiplier); + void EIMICFromSteps(double dt); + void EIMICFromFourPositions(double dt); + void EIMICFromUniversalController(double dt, double brakeDemand); + void UniversalControllerTrainBrake(); + void EIMICTraxxLocalBrake(double dt); + void EIMICLimit(); + // whether the holding brake (brakes.holding) lets go at the power demand (eimic, above 0 when power is demanded) of this step of + // Dt seconds: once the demand has stayed above 0 for brakes.holding.releaseDelay. a demand of 0 or less starts the count again + bool UpdateStopBrakeRelease(double Demand, double Dt); + void CheckSpeedCtrl(double dt); + void SpeedCtrlRegulator(double dt, double accfactor); + // whether the cruise control has a switch of its own: the secondary controller doubles as its switch unless it + // shunts the field of the traction motors already, or there's none (the 6Dg, the ST45; eu07/maszyna#69) + bool IsSpeedCtrlSeparate() const; + // whether the cruise control is switched on: by its own switch, or by the secondary controller off its zero position + bool IsSpeedCtrlEngaged() const; + // the driver's switch of the cruise control: on, to hold the speed of the moment, or off. its own switch, or the + // secondary controller doubling as one (first position on, back to zero off); returns whether it did anything + bool SpeedCtrlSwitch(bool State); + void SpeedCtrlButton(int button); + void SpeedCtrlInc(); + void SpeedCtrlDec(); + bool SpeedCtrlPowerInc(); + bool SpeedCtrlPowerDec(); + + /*-funkcje typowe dla lokomotywy spalinowej z przekladnia mechaniczna*/ + bool dizel_EngageSwitch(double state); + bool dizel_EngageChange(double dt); + bool dizel_AutoGearCheck(void); + bool dizel_GearShiftCheck(double VelUp, double VelDown); + bool dizel_GearShiftRequest(double VelUp, double VelDown); + void dizel_ClutchCheck(); + void dizel_ClutchByController(); + void dizel_ClutchByIntegratedController(); + double dizel_fillcheck(int mcp, double dt); + double dizel_DigitalFill(double dt); + double dizel_GovernorFill(int mcp, double realfill) const; + double dizel_GovernorRevolutions(int mcp, double &realfill) const; + double dizel_Momentum(double Fill, double n, double dt); + void hydro_TCFillCheck(double dt); + void hydro_TCTorque(); + double dizel_MomentumRetarder(double n, double dt); // moment hamowania retardera + void dizel_HeatSet(float const Value); + void dizel_Heat(double const dt); + bool dizel_StartupCheck(); + bool dizel_Update(double dt); + + /* funckje dla wagonow*/ + bool AssignLoad(std::string const &Name, float const Amount = 0.f); + bool LoadingDone(double LSpeed, std::string_view Loadname); + bool PermitDoors(VehicleSide const Door, bool const State = true, range_t const Notify = range_t::consist); + void PermitDoors_(VehicleSide const Door, bool const State = true); + bool ChangeDoorPermitPreset(int const Change, range_t const Notify = range_t::consist); + bool PermitDoorStep(bool const State, range_t const Notify = range_t::consist); + bool ChangeDoorControlMode(bool const State, range_t const Notify = range_t::consist); + bool OperateDoors(VehicleSide const Door, bool const State, range_t const Notify = range_t::consist); + bool LockDoors(bool const State, range_t const Notify = range_t::consist); + bool signal_departure(bool const State, range_t const Notify = range_t::consist); // toggles departure warning + void update_doors(double const Deltatime); // door controller update + door_closure_t door_closure() const; // state of the door closure signalling of this vehicle + // whether the door closure lamp in the cab of this vehicle is lit: with DoorClosureSignal, for the given state of the + // consist; without it, for the lock of the vehicle's own doors, as the lamp always worked + bool door_closure_lamp_lit(door_closure_t const Consist, bool const BlinkLit) const; + // whether the doors have the voltage they work on + bool doors_powered() const; + + /* funkcje dla samochodow*/ + bool ChangeOffsetH(double DeltaOffset); + + /*funkcje ladujace pliki opisujace pojazd*/ + bool LoadFIZ(std::string const &chkpath); // Q 20160717 bool LoadChkFile(std::string chkpath); + bool LoadFIZ_Text(std::string const &Text); // the same, from text in the .fiz format + bool CheckLocomotiveParameters(bool ReadyFlag, int Dir); + // the parts of CheckLocomotiveParameters() + void CreateBrakeValve(); + void CreateBrakeHandles(); + void CreateBrakePipes(); + double InitialScndPipePress(double HosePressure) const; + void SetReadyToDepart(); + void SetBraked(); + std::string EngineDescription(int what) const; + // the cab interior light the light preset at given position (1-based, as lightsPos) sets, if it sets one + std::optional LightsPresetCabLight(int Position) const; + + private: + // the state and the definition no code outside the vehicle uses + double eimicReal = 0; + std::string chkPath; + TPowerParameters SystemPowerSource; /*zrodlo mocy dla systemow sterowania/przetwornic/sprezarek*/ + TPowerParameters AlterHeatPowerSource; /*alternatywne zrodlo mocy dla ogrzewania*/ + TPowerParameters LightPowerSource; /*zrodlo mocy dla oswietlenia*/ + TPowerParameters AlterLightPowerSource; /*alternatywne mocy dla oswietlenia*/ + // height of the centre of gravity of the empty vehicle above the rail [m] (CoGH in the Dimensions of the .fiz), + // negative when the definition gives none: derailment::default_centre_of_gravity() then + double CentreOfGravity = -1.0; + int UniversalResetButtonFlag[3] = {0, 0, 0}; // customizable reset buttons assignments + int LightsDefPos = 1; + int ScndInMain{0}; /*zaleznosc bocznika od nastawnika*/ + int UniCtrlListSize = 0; /*wielkosc listy pozycji uniwersalnego nastawnika*/ + bool UniCtrlIntegratedBrakePNCtrl = false; /*zintegrowany nastawnik JH obsluguje hamulec PN*/ + int UniCtrlNoPowerPos{0}; // cached highesr position not generating traction force + double u = 0.0; // wspolczynnik tarcia yB wywalic!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + int FastSerialCircuit = 0; /*0 - po kolei zamyka styczniki az do osiagniecia szeregowej, 1 - natychmiastowe wejscie na szeregowa*/ /*hunter-111012*/ + double TUHEX_Sum = 750; /*nastawa sterownika hamowania ED - aktualna*/ + double TUHEX_Diff = 10; /*histereza działania sterownika hamowania ED*/ + double TUHEX_MinIw = 60; /*minimalny prąd wzbudzenia przy hamowaniu ED - wynika z chk silnika*/ + double TUHEX_MaxIw = 400; /*maksymalny prąd wzbudzenia przy hamowaniu ED - ograniczenie max siły*/ + double TUHEX_Sum1 = 750; /*nastawa1 sterownika hamowania ED*/ + double TUHEX_Sum2 = 750; /*nastawa2 sterownika hamowania ED*/ + double TUHEX_Sum3 = 750; /*nastawa3 sterownika hamowania ED*/ + int TUHEX_Stages = 0; /*liczba stopni hamowania ED*/ + // TODO: wrap resistor fans variables and state into a device + int RVentType = 0; /*0 - brak, 1 - jest, 2 - automatycznie wlaczany*/ + double RVentCutOff = 0.0; /*rezystancja wylaczania wentylatorow dla RVentType=2*/ + double RVentMinI{50.0}; // przy jakim pradzie sie wylaczaja} + bool Trafo = false; /*pojazd wyposażony w transformator*/ + double engagedownspeed = 0.9; + double engageupspeed = 0.5; + bool AnalogCtrl = false; // + bool AnMainCtrl = false; // + bool Flat = false; + double Vhyp = 1.0; + TFFSchemeTable FFlist; + int FFListSize = 0; + TFFSchemeTable FFEDlist; + int FFEDListSize = 0; + int WiperDefaultPos{0}; + int modernWpierListSize; + TMPTRelayTable MPTRelay; + TShuntSchemeTable SST; + double PowerCorRatio = 1.0; // Wspolczynnik korekcyjny + double Ftmax = 0.0; + double SpeedCtrlButtons[10]{30, 40, 50, 60, 70, 80, 90, 100, 110, 120}; /*przyciski prędkości*/ + double SpeedCtrlDelay = 2; /*opoznienie dzialania tempomatu z wybieralna predkoscia*/ + TRotation Rot{0.0, 0.0, 0.0}; + glm::vec3 Front{}; + double nrot_eps = 0.0; // przyspieszenie kątowe kół (bez kierunku) + double dL = 0.0; + double FTrain = 0.0; + double FTotal = 0.0; /*! calkowita sila dzialajaca na pojazd*/ + double Ntotal = 0.0; /*!s siła nacisku klockow*/ + bool TUHEX_ResChange = false; /*czy zmiana rezystancji hamowania ED - odwzbudzanie*/ + bool ReleaserEnabledOnlyAtNoPowerPos{false}; + TTractionParam RunningTraction; /*parametry sieci trakcyjnej najblizej lokomotywy*/ + double Mw = 0.0; + // sily napedne + double Fw = 0.0; + bool s_CAtestebrake = false; // hunter-091012: zmienna dla testu ca + double eimic_step_progress{0.0}; // the part of the next UniCtrlValStep the controller has covered so far + bool EIMCtrlAdditionalZeros = false; /*czy ma dodatkowe zero jazdy i zero hamowania */ + double SpeedCtrlTimer = 0; /*zegar dzialania tempomatu z wybieralna predkoscia*/ + double eimicSpeedCtrlIntegral = 0; /*calkowany blad ustawienia predkosci*/ + double PulseForce = 0.0; /*przylozona sila*/ + double PulseForceTimer = 0.0; + int PulseForceCount = 0; + std::string LoadQuantity; // jednostki miary + double FrictConst1 = 0.0; + double FrictConst2s = 0.0; + double FrictConst2d = 0.0; + int iProblem = 0; // flagi problemów z taborem, aby AI nie musiało porównywać; 0=może jechać + bool modernDimmerCanCycle{false}; + plc::basic_controller m_plc; + // what the vehicle works out or is defined with, which the rest of the simulator only reads + double vmax = -1.0; + train_type trainType{train_type::generic}; + double totalMass = 0.0; + double ft = 0.0; + int scndCtrlPosNo = 0; + bool slippingWheels = false; + int nAxles = 0; + bool speedCtrl = false; + double nrotValue = 0.0; + double aDist = 0.0; + bool sandDose = false; + float wheelDiameter = 1.f; + DerailReason collisionDerail{NONE}; + bool autoRelayFlag = false; + double bDist = 0.0; + bool physicActivation = true; + bool waterCircuitsLink{false}; + bool enableModernDimmerValue{false}; + double mred = 0.0; + bool delayCtrlFlag = false; + int crushreportsValue{0}; + bool epFuse = true; + int imaxHi = 0; + double initialCtrlDelay = 0.0; + double accSVBased{}; + derail_motion::cause derailCause{derail_motion::cause::off_rails}; + int nPoweredAxles = 0; + bool motorOverloadRelayHighThreshold{false}; + int doorsPermitLightBlinking{0}; + int mainCtrlMaxDirChangePos{0}; + double derailAcceleration{0.0}; + int derailmentreportsValue = 0; + bool cabMaster = false; + bool pulleeMode{false}; + int imin = 0; + bool speedCtrlTypeTime = false; + bool eimCtrlEmergency = false; + double eimicSpeedCtrlValue = 1; + double newSpeed = 0; + int aiHintPantstate{0}; + double uniCtrlValStep{0.0}; + int imaxLo = 0; + int autoRelayType = 0; + bool fieldShuntSwitch = false; + int aiFlag{0}; + bool eimCtrlMainEmergency = false; + double eAngleValue = M_PI * 0.5; + int aiHintShuntPantstate{0}; + double aiHintLocalBrakeAccFactor{1.05}; + int derailSide{0}; + horn_supply hornSupply{horn_supply::air}; + bool uniCtrlIntegratedLocalBrakeCtrl = false; + double windingRes = 0.0; + // what the vehicle works out or is defined with, which the rest of the simulator only reads + double brakingForce = 0.0; + derailment::outcome derailOutcome{derailment::outcome::none}; + bool departureSignalOn = false; + double emptyMass = 0.0; + traction_mode tractionModeSetting{traction_mode::catenary}; + double motorMoment = 0.0; + // the switches and the controllers the cab, the AI and the scenery change only through the operations above + double travelSpeed = 0.0; + TLocation location{0.0, 0.0, 0.0}; + double offsetTrackH = 0.0; + double offsetTrackV = 0.0; + double accS = 0.0; + double accN = 0.0; + double accVert = 0.0; + double distCounter = 0.0; + double moveLength = 0.0; + double wheelFlat = 0.0; + bool truckHunting{true}; + double derailmentDistance = 0.0; + bool insideConsist = false; + bool couplerPhysics{false}; + bool inactiveCabPantsCheck = false; + double eimicAnalog = 0; + double actFlowSpeed = 0.0; + float maxLoad = 0.f; + bool eventFlag = false; + int soundFlag = 0; + float loadAmount = 0.f; + int loadStatus = 0; + bool loadTypeChange{false}; + ByEnd litLights; + bool signalling = false; + bool radio = false; + bool radioFuse = true; + int wiperSwitchPos = 0; + bool rventForceOn{false}; + double anPos = 0.0; + bool mirrorForbidden{false}; + bool radioStopFlag = false; + int mainCtrlPos = 0; + int scndCtrlPos = 0; + int lightsPos = 0; + int cabOccupied = 0; + int warningSignal = 0; + int modernDimmerPosition{0}; + + bool LoadFIZ_Parse(cParser &Parser); // reads the definition from either of the above + // the parts of LoadFIZ_Parse(), for a line of the definition + bool LoadFIZ_TableEnd(std::string const &inputline) const; + bool LoadFIZ_Section(std::string const &inputline, std::map> &fizlines); + bool LoadFIZ_TableSection(std::string const &inputline, std::map> &fizlines); + void LoadFIZ_TableRow(std::string const &inputline); + void LoadFIZ_Param(std::string const &line); + void LoadFIZ_Load(std::string const &line); + void LoadFIZ_Dimensions(std::string const &line); + void LoadFIZ_Wheels(std::string const &line); + void LoadFIZ_Brake(std::string const &line); + void LoadFIZ_Doors(std::string const &line); + void LoadFIZ_BuffCoupl(std::string const &line, int const Index); + void LoadFIZ_TurboPos(std::string const &line); + void LoadFIZ_Cntrl(std::string const &line); + void LoadFIZ_CntrlBrakes(std::string const &line); + void LoadFIZ_CntrlTrainBrake(std::string const &line); + void LoadFIZ_CntrlAntiSlipBrake(std::string_view asb); + void LoadFIZ_CntrlControllers(std::string const &line); + void LoadFIZ_CntrlStarts(std::string const &line); + void LoadFIZ_Blending(std::string const &line); + void LoadFIZ_DCEMUED(std::string const &line); + void LoadFIZ_SpringBrake(std::string const &line); + void LoadFIZ_Light(std::string const &line); + void LoadFIZ_Headlights(std::string const &Line); + void LoadFIZ_Clima(std::string const &line); + void LoadFIZ_Power(std::string const &Line); + void LoadFIZ_Genset(std::string const &Line); + void LoadFIZ_SpeedControl(std::string const &Line); + void LoadFIZ_Engine(std::string const &Input); + void LoadFIZ_EngineDiesel(std::string const &Input); + void LoadFIZ_EngineDieselElectric(std::string const &Input); + void LoadFIZ_EngineInductionMotor(std::string const &Input); + void LoadFIZ_EngineDieselShared(std::string const &Input); + void LoadFIZ_Switches(std::string const &Input); + void LoadFIZ_MotorParamTable(std::string const &Input); + void LoadFIZ_Circuit(std::string const &Input); + void LoadFIZ_AI(std::string const &Input); + void LoadFIZ_RList(std::string const &Input); + void LoadFIZ_UCList(std::string const &Input); + void LoadFIZ_DieselElectricDynamicBrake(std::string const &Input); + void LoadFIZ_DList(std::string const &Input); + void LoadFIZ_FFList(std::string const &Input); + void LoadFIZ_FFEDList(std::string const &Input); + void LoadFIZ_WiperList(std::string const &Input); + void LoadFIZ_LightsList(std::string const &Input); + void LoadFIZ_DimmerList(std::string const &Input); + void LoadFIZ_CompressorList(std::string const &Input); + void LoadFIZ_PowerParamsDecode(TPowerParameters &Powerparameters, std::string const &Prefix, std::string const &Input); + TPowerType LoadFIZ_PowerDecode(std::string const &Power) const; + TPowerSource LoadFIZ_SourceDecode(std::string const &Source) const; + TEngineType LoadFIZ_EngineDecode(std::string const &Engine) const; + bool readMPT0(std::string const &line); + bool readMPT(std::string const &line); // Q 20160717 + bool readMPTElectricSeries(std::string const &line); + bool readMPTDieselElectric(std::string const &line); + bool readMPTDieselEngine(std::string const &line); + bool readBPT(/*int const ln,*/ std::string const &line); // Q 20160721 + bool readRList(std::string const &Input); + bool readUCList(std::string const &Input); + bool readDList(std::string const &line); + bool readDMList(std::string const &line); + bool readV2NMAXList(std::string const &line); + bool readHTCList(std::string const &line); + bool readPmaxList(std::string const &line); + bool readFFList(std::string const &line); + bool readFFEDList(std::string const &line); + bool readWWList(std::string const &line); + bool readWiperList(std::string const &line); + bool readDimmerList(std::string const &line); + bool readLightsList(std::string const &Input); + bool readCompressorList(std::string const &Input); + void BrakeValveDecode(std::string const &s); // Q 20160719 + void BrakeSubsystemDecode(); // Q 20160719 +}; + +} // namespace physics + +// double Distance(TLocation Loc1, TLocation Loc2, TDimension Dim1, TDimension Dim2); + +namespace simulation +{ + +using weights_table = std::unordered_map; + +extern weights_table Weights; + +} // namespace simulation diff --git a/physics/vehiclecommand.cpp b/physics/vehiclecommand.cpp new file mode 100644 index 000000000..c07b0546f --- /dev/null +++ b/physics/vehiclecommand.cpp @@ -0,0 +1,127 @@ +/* +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 "physics/vehiclecommand.h" + +#include +#include +#include + +#include "utilities/utilities.h" + +namespace +{ + +using enum VehicleCommand; + +// the names of the commands, as the scenery files write them +constexpr std::array, 59> commandNames{{ + {mainController, "MainCtrl"}, + {secondaryController, "ScndCtrl"}, + {integratedController, "EIMIC"}, + {speedControl, "SpeedCntrl"}, + {speedControlParking, "SpeedCtrlUnit.Parking"}, + {direction, "Direction"}, + {autoRelaySwitch, "AutoRelaySwitch"}, + {maxCurrentSwitch, "MaxCurrentSwitch"}, + {minCurrentSwitch, "MinCurrentSwitch"}, + {relayReset, "RelayReset"}, + {cabActivation, "CabActivisation"}, + {cabSignal, "CabSignal"}, + {departureSignal, "DepartureSignal"}, + {tractionMode, "TractionMode"}, + {brake, "Brake"}, + {emergencyBrake, "Emergency_brake"}, + {brakeDelay, "BrakeDelay"}, + {brakeReleaser, "BrakeReleaser"}, + {springBrakeActivate, "SpringBrakeActivate"}, + {epFuseSwitch, "EpFuseSwitch"}, + {sandbox, "Sandbox"}, + {sandboxAutoAllow, "SandboxAutoAllow"}, + {compressorSwitch, "CompressorSwitch"}, + {compressorPreset, "CompressorPreset"}, + {converterSwitch, "ConverterSwitch"}, + {batterySwitch, "BatterySwitch"}, + {mainSwitch, "MainSwitch"}, + {heatingSwitch, "HeatingSwitch"}, + {gensetSwitch, "GensetSwitch"}, + {pantographValve, "PantValve"}, + {pantographsValve, "PantsValve"}, + {pantographsAllDown, "PantAllDown"}, + {compartmentLightsSwitch, "CompartmentLightsSwitch"}, + {compartmentLightsSwitchOff, "CompartmentLightsSwitchOff"}, + {waterPumpBreakerSwitch, "WaterPumpBreakerSwitch"}, + {waterPumpSwitch, "WaterPumpSwitch"}, + {waterPumpSwitchOff, "WaterPumpSwitchOff"}, + {waterHeaterBreakerSwitch, "WaterHeaterBreakerSwitch"}, + {waterHeaterSwitch, "WaterHeaterSwitch"}, + {waterCircuitsLinkSwitch, "WaterCircuitsLinkSwitch"}, + {fuelPumpSwitch, "FuelPumpSwitch"}, + {fuelPumpSwitchOff, "FuelPumpSwitchOff"}, + {oilPumpSwitch, "OilPumpSwitch"}, + {oilPumpSwitchOff, "OilPumpSwitchOff"}, + {motorBlowersFrontSwitch, "MotorBlowersFrontSwitch"}, + {motorBlowersFrontSwitchOff, "MotorBlowersFrontSwitchOff"}, + {motorBlowersRearSwitch, "MotorBlowersRearSwitch"}, + {motorBlowersRearSwitchOff, "MotorBlowersRearSwitchOff"}, + {doorOpen, "DoorOpen"}, + {doorClose, "DoorClose"}, + {doorLock, "DoorLock"}, + {doorMode, "DoorMode"}, + {doorPermit, "DoorPermit"}, + {doorStep, "DoorStep"}, + {setDamage, "SetDamage"}, + {load, "Load="}, + {unload, "UnLoad="}, + {none, ""}, + {unknown, ""}, +}}; + +// the name of the load after Load= or UnLoad= (key) at the start of the text, empty when nothing follows the = but +// spaces: extract_value() would throw there, reading past the end of the text +std::string loadName(std::string_view const key, std::string_view const text) +{ + if (text.find_first_not_of(' ', key.size() + 1) == std::string_view::npos) + { + return {}; + } + return extract_value(std::string{key}, std::string{text}); +} + +} // namespace + +ParsedVehicleCommand ParseVehicleCommand(std::string const &Text) +{ + if (Text.empty()) + { + return {none, {}}; + } + // Load= and UnLoad= begin the text, the name of the load follows + if (Text.starts_with("Load=")) + { + return {load, loadName("Load", Text)}; + } + if (Text.starts_with("UnLoad=")) + { + return {unload, loadName("UnLoad", Text)}; + } + auto const named{std::ranges::find(commandNames, std::string_view{Text}, &std::pair::second)}; + if (named == commandNames.end() || named->first == load || named->first == unload) + { + return {unknown, {}}; + } + return {named->first, {}}; +} + +std::string_view VehicleCommandName(VehicleCommand const Command) +{ + auto const named{std::ranges::find(commandNames, Command, &std::pair::first)}; + return named != commandNames.end() ? named->second : std::string_view{}; +} diff --git a/physics/vehiclecommand.h b/physics/vehiclecommand.h new file mode 100644 index 000000000..fff9b1fc8 --- /dev/null +++ b/physics/vehiclecommand.h @@ -0,0 +1,105 @@ +/* +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 commands the vehicles of a train pass to each other through their couplings (the control wire of the multiple +// unit, the brake pipe and the others), and the ones a scenery, a script or the driver gives a vehicle. inside the +// simulation they are VehicleCommand; their names are only read where a command comes as text (events, Lua) and +// written where it is shown (the log, the AI) + +#pragma once + +#include +#include +#include + +enum class VehicleCommand +{ + none, // no command + unknown, // a command given as text which no vehicle knows: the AI may still read it + // the controllers + mainController, // MainCtrl + secondaryController, // ScndCtrl + integratedController, // EIMIC: the integrated controller of an induction motor drive, relative traction or braking + speedControl, // SpeedCntrl + speedControlParking, // SpeedCtrlUnit.Parking + // the direction, the automatic start and the current relays + direction, // Direction + autoRelaySwitch, // AutoRelaySwitch + maxCurrentSwitch, // MaxCurrentSwitch + minCurrentSwitch, // MinCurrentSwitch + relayReset, // RelayReset + // the cab + cabActivation, // CabActivisation + cabSignal, // CabSignal + departureSignal, // DepartureSignal + tractionMode, // TractionMode + // the brakes + brake, // Brake + emergencyBrake, // Emergency_brake + brakeDelay, // BrakeDelay + brakeReleaser, // BrakeReleaser + springBrakeActivate, // SpringBrakeActivate + epFuseSwitch, // EpFuseSwitch: passed on, but no vehicle acts on it + sandbox, // Sandbox + sandboxAutoAllow, // SandboxAutoAllow: passed on, but no vehicle acts on it + // the compressor and the converter + compressorSwitch, // CompressorSwitch + compressorPreset, // CompressorPreset + converterSwitch, // ConverterSwitch + // the power + batterySwitch, // BatterySwitch + mainSwitch, // MainSwitch + heatingSwitch, // HeatingSwitch + gensetSwitch, // GensetSwitch + pantographValve, // PantValve + pantographsValve, // PantsValve + pantographsAllDown, // PantAllDown + compartmentLightsSwitch, // CompartmentLightsSwitch + compartmentLightsSwitchOff, // CompartmentLightsSwitchOff + // the pumps of a diesel engine + waterPumpBreakerSwitch, // WaterPumpBreakerSwitch + waterPumpSwitch, // WaterPumpSwitch + waterPumpSwitchOff, // WaterPumpSwitchOff + waterHeaterBreakerSwitch, // WaterHeaterBreakerSwitch + waterHeaterSwitch, // WaterHeaterSwitch + waterCircuitsLinkSwitch, // WaterCircuitsLinkSwitch + fuelPumpSwitch, // FuelPumpSwitch + fuelPumpSwitchOff, // FuelPumpSwitchOff + oilPumpSwitch, // OilPumpSwitch + oilPumpSwitchOff, // OilPumpSwitchOff + // the traction motor blowers + motorBlowersFrontSwitch, // MotorBlowersFrontSwitch + motorBlowersFrontSwitchOff, // MotorBlowersFrontSwitchOff + motorBlowersRearSwitch, // MotorBlowersRearSwitch + motorBlowersRearSwitchOff, // MotorBlowersRearSwitchOff + // the doors + doorOpen, // DoorOpen + doorClose, // DoorClose + doorLock, // DoorLock + doorMode, // DoorMode + doorPermit, // DoorPermit + doorStep, // DoorStep + // the load and the damage + load, // Load= + unload, // UnLoad= + setDamage, // SetDamage +}; + +// a command read from its text, with the name of the load for Load= and UnLoad= +struct ParsedVehicleCommand +{ + VehicleCommand command{VehicleCommand::none}; + std::string argument; // the name of the load, as extract_value() gives it +}; + +// the command a text names: none for an empty text, unknown for a text no vehicle knows. the names are the ones the +// scenery files, the scripts and the AI have always used, compared exactly +ParsedVehicleCommand ParseVehicleCommand(std::string const &Text); +// the name of a command, as the scenery files write it; empty for none and unknown +std::string_view VehicleCommandName(VehicleCommand Command); diff --git a/physics/vehicletypes.h b/physics/vehicletypes.h new file mode 100644 index 000000000..c8db5e270 --- /dev/null +++ b/physics/vehicletypes.h @@ -0,0 +1,827 @@ +/* +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 vocabulary of the vehicles: their ends, sides, couplings, lights, sounds, types of drive and brake, the +// flags and the small structures the rest of the simulator passes around without needing the physics itself + +#pragma once + +#include +#include +#include +#include +#include + +#include "utilities/enumset.h" + +#include "physics/vehiclecommand.h" + +/// Global counter incremented when a string-to-numeric conversion fails during config parsing. +extern int ConversionError; + +/// Static friction coefficient for steel-on-steel contact (used for adhesion at standstill). +const double Steel2Steel_friction = 0.15; // tarcie statyczne +/// Earth gravitational acceleration [m/s^2]. +const double g = 9.81; // przyspieszenie ziemskie +/// Sand consumption rate when sanding is active [kg/s]. +const double SandSpeed = 0.1; // ile kg/s} +/// 2*pi shortcut. +const double Pirazy2 = 6.2831853071794f; + +//-- var, const, procedure --------------------------------------------------- +/// Truthy alias used by CheckLocomotiveParameters() to ignore a check failure. +static bool const Go = true; +/// Falsy alias used by CheckLocomotiveParameters() to abort on a check failure. +static bool const Hold = false; /*dla CheckLocomotiveParameters*/ +/// Maximum number of resistor / scheme entries for electric motor traction. +static int const ResArraySize = 64; /*dla silnikow elektrycznych*/ +/// Maximum number of motor-parameter table entries (gear stages). +static int const MotorParametersArraySize = 10; +/// Maximum number of pantograph current collectors per vehicle. +static int const maxcc = 4; /*max. ilosc odbierakow pradu*/ +// static int const LocalBrakePosNo = 10; /*ilosc nastaw hamulca pomocniczego*/ +// static int const MainBrakeMaxPos = 10; /*max. ilosc nastaw hamulca zasadniczego*/ +/// Number of positions on the manual (parking) brake handle. +static int const ManualBrakePosNo = 20; /*ilosc nastaw hamulca recznego*/ +/// Number of positions on the lights selector switch. +static int const LightsSwitchPosNo = 16; +/// Maximum number of positions of the universal (auxiliary) controller. +static int const UniversalCtrlArraySize = 32; /*max liczba pozycji uniwersalnego nastawnika*/ + +/*uszkodzenia toru*/ +/// Track damage flag: rail wear. +static int const dtrack_railwear = 2; +/// Track damage flag: free / loose rail. +static int const dtrack_freerail = 4; +/// Track damage flag: thin (worn-out) rail. +static int const dtrack_thinrail = 8; +/// Track damage flag: bent rail. +static int const dtrack_railbend = 16; +/// Track damage flag: vegetation overgrowth. +static int const dtrack_plants = 32; +/// Track damage flag: track impassable for movement. +static int const dtrack_nomove = 64; +/// Track damage flag: rails missing entirely. +static int const dtrack_norail = 128; + +/// The damage of a vehicle, DamageFlag. A bit means one thing for a locomotive and another for a wagon, +/// where two values share it. The numbers are the ones of the SetDamage command of the scenery. +enum class VehicleDamage : unsigned +{ + thinWheel = 0x1, // a locomotive: a wheel worn thin + loadShift = 0x1, // a wagon: the load shifted + wheelWear = 0x2, // the wheels worn + bearing = 0x4, // a bearing failed + coupling = 0x8, // the coupling broken + ventilator = 0x10, // an electric locomotive: a ventilator failed + loadDamage = 0x10, // a wagon: the load damaged + engine = 0x20, // a locomotive: the engine failed + loadDestroyed = 0x20, // a wagon: the load destroyed + axle = 0x40, // an axle broken + derailed = 0x80, // off the rails + pantograph = 0x100, // a pantograph broken +}; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using DamageSet = EnumSet; + +// the faults of the equipment of a vehicle the scenery or the network sets (TDynamicObject::Damage()), in the numbers of +// the messages that carry them +enum class EquipmentFault : unsigned +{ + differentialRelay = 0x1, // the differential relay tripped: the line breaker opens and the fuse with it + control = 0x2, // the control: the line contactors open and the start doesn't go on + converter = 0x4, // the converter locked + compressor = 0x8, // the compressor locked + camshaft = 0x10, // the camshaft locked: the controller doesn't step + emergencyBrake = 0x20, // an emergency brake application, which does nothing more yet +}; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using EquipmentFaultSet = EnumSet; + +/// Reason for a derailment event. +enum DerailReason +{ + /// No derailment. + NONE = 0, + /// End of track reached. + END_OF_TRACK = 1, // Ra: powód wykolejenia: brak szyn + /// Speed too high for curve (overturn). + TOO_HIGH_SPEED = 2, // Ra: powód wykolejenia: przewrócony na łuku + /// Track gauge does not match wheelset gauge. + GAUGE_MISMATCH = 3, // Ra: powód wykolejenia: za szeroki tor + /// Track type incompatible with this vehicle. + WRONG_TRACK_TYPE = 4, // Ra: powód wykolejenia: nieodpowiednia trajektoria + /// Collision with another vehicle. + COLLISION = 5, // powód wykolejenia: zderzenie z innym pojazdem + /// Trailing through a switch with a movable nose set the other way. + TRAILED_SWITCH = 6, // powód wykolejenia: rozprucie rozjazdu z ruchomym dziobem + /// Climbed onto the vehicle it hit, its end crushed (physics.collisions new). + COLLISION_OVERRIDE = 7, // najechanie + /// Pushed off the track by the force pressing its end (physics.collisions new). + COLLISION_PUSHED_OFF = 8, // wyciśnięcie z toru +}; + +/*wagi prawdopodobienstwa dla funkcji FuzzyLogic*/ +/// Fuzzy-logic probability weight: electric engine general problem. +#define p_elengproblem (1e-02) +/// Fuzzy-logic probability weight: electric engine damage. +#define p_elengdamage (1e-01) +/// Fuzzy-logic probability weight: coupler damage. +#define p_coupldmg (2e-03) +/// Fuzzy-logic probability weight: derailment. +#define p_derail (1e-03) +/// Fuzzy-logic probability weight: acceleration-related event. +#define p_accn (1e-01) +/// Fuzzy-logic probability weight: damage caused by wheel slip. +#define p_slippdmg (1e-03) + +/// Vehicle ends — front or rear (mutually exclusive). The numbers are the ones of the formats (the +/// couplers of the .scn, the network) and the places in a . +enum class VehicleEnd : int +{ + /// Front end. + front = 0, + /// Rear end. + rear = 1 +}; + +/// Vehicle sides — right or left (mutually exclusive), the places in a . +enum class VehicleSide : int +{ + /// Right side. + right = 0, + /// Left side. + left = 1 +}; + +/// Both ends and both sides, to go through them. +constexpr std::array VehicleEnds{VehicleEnd::front, VehicleEnd::rear}; +constexpr std::array VehicleSides{VehicleSide::right, VehicleSide::left}; + +/// The other end of the vehicle. +constexpr VehicleEnd Opposite(VehicleEnd const vehicleEnd) +{ + return vehicleEnd == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front; +} + +/// The other side of the vehicle. +constexpr VehicleSide Opposite(VehicleSide const vehicleSide) +{ + return vehicleSide == VehicleSide::right ? VehicleSide::left : VehicleSide::right; +} + +/// The number of the end or the side, where a format or a count needs it. +constexpr int NumberOf(VehicleEnd const vehicleEnd) +{ + return static_cast(vehicleEnd); +} + +constexpr int NumberOf(VehicleSide const vehicleSide) +{ + return static_cast(vehicleSide); +} + +/// The end of the given number (0 front, 1 rear), as the formats have it; the number is kept as it is. +constexpr VehicleEnd EndOf(int const number) +{ + return static_cast(number); +} + +/// The side of the given number (0 right, 1 left); the number is kept as it is. +constexpr VehicleSide SideOf(int const number) +{ + return static_cast(number); +} + +/// The end of the vehicle the cab of the given number is at (CabActive, CabOccupied): cab 1 at the front, +/// cab -1 at the rear; none for 0, no cab. +constexpr std::optional CabEnd(int const cab) +{ + if (cab > 0) + { + return VehicleEnd::front; + } + if (cab < 0) + { + return VehicleEnd::rear; + } + return std::nullopt; +} + +/// The end a pantograph of the model counts for, by its number among the pantograph animations: the even +/// ones the front (Pantographs[front], PantFrontVolt), the odd ones the rear. +constexpr VehicleEnd PantographEnd(int const index) +{ + return (index & 1) != 0 ? VehicleEnd::rear : VehicleEnd::front; +} + +/// Two values, one for each end or side of a vehicle, indexed by the enum; by a number too, where a loop +/// counts them. +template +struct EnumPair : std::array +{ + using std::array::operator[]; + constexpr Value &operator[](Key const key) + { + return std::array::operator[](static_cast(key)); + } + constexpr Value const &operator[](Key const key) const + { + return std::array::operator[](static_cast(key)); + } +}; + +template +using ByEnd = EnumPair; +template +using BySide = EnumPair; + +/// The kinds of connection a coupling between two vehicles makes. The numbers are the ones of the scenery +/// files and the vehicle definitions (AllowedFlag, the coupling of a vehicle in a train), where they add up. +enum class Coupling : unsigned +{ + none = 0x0, // the vehicles only see each other (virtual) + coupler = 0x1, // the mechanical coupler + brakeHose = 0x2, // the brake pipe + control = 0x4, // the control cable of the multiple unit + highVoltage = 0x8, // the high voltage cable of the traction supply + gangway = 0x10, // the gangway for the passengers + mainHose = 0x20, // the main reservoir pipe (8 bar, yellow) + heating = 0x40, // the high voltage cable of the train heating + permanent = 0x80, // not parted by usual shunting (between the sections of a unit); negative in a definition + power24v = 0x100, // the 24 V cable + power110v = 0x200, // the 110 V cable + power3x400v = 0x400, // the 3x400 V cable +}; + +/// A set of the kinds of connection of a coupling: what a coupling joins, what a vehicle allows, what a +/// command needs to pass. +template <> struct IsEnumSetKind : std::true_type +{ +}; +using CouplingSet = EnumSet; + +/// Range of effect for a control command (mutually exclusive). +enum class range_t +{ + /// Affects only this vehicle. + local, + /// Affects this multiple-unit (vehicles permanently coupled into a unit). + unit, + /// Affects the entire consist. + consist +}; +/// State of the door closure signalling (SOD) of a vehicle or a consist, ordered from the least to the most +/// severe: the state of a consist is the most severe state of its vehicles. +enum class door_closure_t +{ + /// No doors worked by the crew: the vehicle doesn't take part in the signalling. + none, + /// All doors closed and locked: they can't be opened. + locked, + /// All doors closed, but released: a permit is given, or no lock holds them shut. + released, + /// A door is open, or not fully closed yet. + open +}; +/// Whether the door closure signalling lamp is lit: steadily for locked doors, in the lit phase of the +/// blinking for released ones, never with a door open or with no doors signalled. +bool door_closure_lamp(door_closure_t const State, bool const BlinkLit); +/// Possible settings for an enable/disable input pair (mutually exclusive). +enum class operation_t +{ + /// No input. + none = 0, + /// Enable input held active. + enable, + /// Disable input held active. + disable, + /// Enable button press transition (rising edge). + enable_on, + /// Enable button release transition. + enable_off, + /// Disable button press transition. + disable_on, + /// Disable button release transition. + disable_off, +}; +/// What else the line contactors of a vehicle need before they can close (LineContactorsInterlock in the Cntrl. section). +enum class line_contactors_interlock +{ + /// Nothing more, the legacy behaviour. + none, + /// The converter of the vehicle itself running, where it drives the traction motor fans (ET42). + converter, + /// The traction motor blowers of the vehicle running. + motor_blowers +}; +/// Auto-start method for ancillary devices (mutually exclusive). +enum class start_t +{ + /// Device cannot be started. + disabled, + /// Manual start only. + manual, + /// Starts automatically. + automatic, + /// Manual start with automatic fallback. + manualwithautofallback, + /// Driven by the converter state. + converter, + /// Driven by the battery state. + battery, + /// Driven by direction selector state. + direction +}; +/// Bit flags representing vehicle external lights (positions and types). Combinable. +enum light +{ + + /// Headlight, left. + headlight_left = 1 << 0, + /// Red marker, left. + redmarker_left = 1 << 1, + /// Headlight, upper centre. + headlight_upper = 1 << 2, + // TBD, TODO: redmarker_upper support? + /// Headlight, right. + headlight_right = 1 << 4, + /// Red marker, right. + redmarker_right = 1 << 5, + /// Rear-end markers (combined). + rearendsignals = 1 << 6, + /// Auxiliary light, left (e.g. ditch light). + auxiliary_left = 1 << 7, + /// Auxiliary light, right. + auxiliary_right = 1 << 8, + /// High-beam headlight, left. + highbeamlight_left = 1 << 9, + /// High-beam headlight, right. + highbeamlight_right = 1 << 10 +}; + +/// The cab interior light a position of the light preset selector sets (eu07/maszyna#529). +struct lights_preset_cablight +{ + /// Bits of the optional third column of a LightsList row. + enum flag + { + /// The cab light is on. + light_on = 1 << 0, + /// The cab light is dimmed. + light_dimmed = 1 << 1 + }; + bool light{false}; + bool dim{false}; +}; + +/// Door operation method (who controls them and how) — mutually exclusive. +enum control_t +{ + /// Local; passengers operate manually, doors open/close for the duration of loading. + passenger, // local, opened/closed for duration of loading + /// Remote; driver-operated. + driver, // remote, operated by the driver + /// Local autonomous; close when the vehicle moves and/or after a timeout. + autonomous, // local, closed when vehicle moves and/or after timeout + /// Remote; conductor-operated. + conductor, // remote, operated by the conductor + /// Primarily manual but also responds to remote control. + mixed // primary manual but answers also to remote control +}; +/*typ hamulca elektrodynamicznego*/ +/// Electrodynamic-brake type: no ED brake. +static int const dbrake_none = 0; +/// Electrodynamic-brake type: passive (always on while moving). +static int const dbrake_passive = 1; +/// Electrodynamic-brake type: switchable (driver toggles). +static int const dbrake_switch = 2; +/// Electrodynamic-brake type: reversal (engaged via reverser). +static int const dbrake_reversal = 4; +/// Electrodynamic-brake type: automatic (engages from main brake). +static int const dbrake_automatic = 8; + +/*dzwieki*/ +/// Bit flags identifying sound events emitted by a vehicle. Combinable. +enum sound +{ + /// No sound event. + none, + /// Generic "loud" event flag (e.g. impact / forced action). + loud = 1 << 0, + /// Coupler stretching to its limit. + couplerstretch = 1 << 1, + /// Buffer clash (vehicles colliding). + bufferclash = 1 << 2, + /// Contactor / relay clicking. + relay = 1 << 3, + /// Series-parallel switch operating. + parallel = 1 << 4, + /// Field-shunt contactor operating. + shuntfield = 1 << 5, + /// Generic pneumatic event. + pneumatic = 1 << 6, + /// Coupling detached. + detach = 1 << 7, + /// Mechanical coupler attached. + attachcoupler = 1 << 8, + /// Brake hose attached. + attachbrakehose = 1 << 9, + /// Main air hose attached. + attachmainhose = 1 << 10, + /// Control cable attached. + attachcontrol = 1 << 11, + /// Gangway attached. + attachgangway = 1 << 12, + /// Heating cable attached. + attachheating = 1 << 13, + /// Adapter piece attached to coupler. + attachadapter = 1 << 14, + /// Adapter piece removed from coupler. + removeadapter = 1 << 15, + /// Door-open permission signalling. + doorpermit = 1 << 16, +}; + +/// Bit flags for the customizable reset button — which protective relay it resets. Combinable. +enum relay_t +{ + /// Main circuit ground-fault relay. + maincircuitground = 1 << 0, + /// Auxiliary circuit ground-fault relay. + auxiliarycircuitground = 1 << 1, + /// Traction motor overload relay. + tractionnmotoroverload = 1 << 2, + /// Primary converter overload relay. + primaryconverteroverload = 1 << 3, + /// Secondary converter overload relay. + secondaryconverteroverload = 1 << 4, + /// Ventilator overload relay. + ventillatoroverload = 1 << 5, + /// Heating overload relay. + heatingoverload = 1 << 6, + /// Electrodynamic-brake overload relay. + electrodynamicbrakesoverload = 1 << 7, +}; + +/// Bit flags for actions triggered on cab activation / deactivation. Combinable. +enum activation +{ + /// Engage the emergency brake. + emergencybrake = 1 << 0, + /// Operate cab mirrors. + mirrors = 1 << 1, + /// Raise the pantographs. + pantographsup = 1 << 2, + /// Switch on red end-of-train markers. + redmarkers = 1 << 3, + /// Set door-open permit. + doorpermition = 1 << 4, + /// Engage the spring brake. + springbrakeon = 1 << 5, + /// Release the spring brake. + springbrakeoff = 1 << 6, + /// Place the reverser in neutral. + neutraldirection = 1 << 7, +}; + +/// The vehicles the code handles in a way of their own, by the Type of the Param section of the .fiz +/// (TrainType). A vehicle is of one of them; a .fiz type not listed is generic. +enum class train_type +{ + /// No handling of its own. + generic, + /// Electric multiple unit (Type=EZT). + emu, + /// Diesel multiple unit (Type=DMU). + dmu, + /// ET22 locomotive (Type=ET22, since the Megapack). + et22, + /// ET40 locomotive. + et40, + /// ET41 locomotive. + et41, + /// ET42 locomotive. + et42, + /// EP05 locomotive. + ep05, + /// SN61 railcar: the physics has nothing of its own for it; the AI, after setting the direction, moves the master controller up to a position with engine torque so the engine doesn't stall (TController::DirectionForward()). + sn61, + /// Pseudo-diesel (an electric drivetrain with the input model of a diesel). + pseudodiesel, + /// Škoda 181 and 182 locomotives (Type=181 or 182). + skoda181, +}; + +/// Brake-of-mode flag: PS (pneumatic, primary). +static int const bom_PS = 1; +/// Brake-of-mode flag: PN (pneumatic, no electrodynamic). +static int const bom_PN = 2; +/// Brake-of-mode flag: EP (electro-pneumatic). +static int const bom_EP = 4; +/// Brake-of-mode flag: MED (mixed pneumatic+ED). +static int const bom_MED = 8; + +/// Bit flags reporting vehicle problems that prevent driving. +enum TProblem // lista problemów taboru, które uniemożliwiają jazdę +{ // flagi bitowe + /// The vehicle has the brake applied or seized axles. + pr_Hamuje = 1, // pojazd ma załączony hamulec lub zatarte osie + /// The vehicle requires pantographs to be inflated/raised. + pr_Pantografy = 2, // pojazd wymaga napompowania pantografów + /// Reserved sentinel — last bit flag. + pr_Ostatni = 0x80000000 // ostatnia flaga bitowa +}; + +/// Compressor parameter list — indices into the compressor programmer table. +enum TCompressorList // lista parametrów w programatorze sprężarek +{ // pozycje kolejne + /// Compressor enable permission (0/1). + cl_Allow = 0, // zezwolenie na pracę sprężarek + /// Compressor output multiplier. + cl_SpeedFactor = 1, // mnożnik wydajności + /// Pressure-switch lower threshold multiplier. + cl_MinFactor = 2, // mnożnik progu załącznika ciśnieniowego + /// Pressure-switch upper threshold multiplier. + cl_MaxFactor = 3 // mnożnik progu wyłącznika ciśnieniowego +}; + +/// 3-D position in world coordinates [m]. +struct TLocation +{ + /// X coordinate. + double X; + /// Y coordinate (vertical). + double Y; + /// Z coordinate. + double Z; +}; + +/// Euler-angle rotation (radians) around X / Y / Z axes. +struct TRotation +{ + /// Rotation around X axis. + double Rx; + /// Rotation around Y axis. + double Ry; + /// Rotation around Z axis. + double Rz; +}; + +/// Vehicle bounding box (width × length × height [m]). +struct TDimension +{ + /// Width. + double W = 0.0; + /// Length. + double L = 0.0; + /// Height. + double H = 0.0; +}; + +/// A pending command queued for the vehicle, with its arguments and propagation rules. +struct TCommand +{ + /// The command. + VehicleCommand Command{VehicleCommand::none}; + /// The command as it came, where it came as text (an event, a script): the AI reads it. + std::string Text; + /// The name of the load of Load= and UnLoad=. + std::string Argument; + /// First numeric argument. + double Value1 = 0.0; /*argumenty komendy*/ + /// Second numeric argument. + double Value2 = 0.0; + /// Coupling flag controlling how the command propagates between vehicles. + CouplingSet couplings{Coupling::control}; // the couplings the command passes through + /// World-space location associated with the command. + TLocation Location; +}; + +/*tory*/ +/// Geometric shape of a track segment under the vehicle. +struct TTrackShape +{ /*ksztalt odcinka*/ + /// Curvature radius [m]; 0 means straight track. + double R = 0.0; // promien + /// Segment length [m]. + double Len = 0.0; // dlugosc + /// Track gradient (rise/run). + double dHtrack = 0.0; // nachylenie + /// Track cant / superelevation. + double dHrail = 0.0; // przechylka + /// Lateral curvature of the track unevenness under the vehicle [1/m], see world/TrackUneven.h. + double uneven_curvature = 0.0; + /// Cross level unevenness of the track [mm]. + double uneven_cross = 0.0; + /// Curvature a buckle of the track adds under the body [1/m], positive with the curve, see world/TrackBuckle.h. + double buckle_curvature = 0.0; +}; + +/// Per-segment track parameters: gauge, friction, category, load capacity, damage. +struct TTrackParam +{ /*parametry odcinka - szerokosc, tarcie statyczne, kategoria, obciazalnosc w t/os, uszkodzenia*/ + /// Track gauge / width [m]. + double Width = 0.0; + /// Static friction coefficient on this segment. + double friction = 0.0; + /// Track category bit flags. + int CategoryFlag = 0; + /// Track-quality bit flags. + int QualityFlag = 0; + /// Track-damage bit flags (dtrack_*). + int DamageFlag = 0; + /// Maximum allowed velocity on this segment (used by AI driver). + double Velmax; /*dla uzytku maszynisty w ai_driver*/ + /// Name of the track, for the log; nullptr where there is none. + std::string const *Name = nullptr; +}; + +/// Traction-supply parameters at the vehicle's current location. +struct TTractionParam +{ + /// Catenary voltage [V]. + double TractionVoltage = 0.0; /*napiecie*/ + /// Catenary frequency [Hz] (0 for DC). + double TractionFreq = 0.0; /*czestotliwosc*/ + /// Maximum current capacity [A]. + double TractionMaxCurrent = 0.0; /*obciazalnosc*/ + /// Pantograph-catenary contact resistance [Ω]. + double TractionResistivity = 0.0; /*rezystancja styku*/ +}; +/*powyzsze parametry zwiazane sa z torem po ktorym aktualnie pojazd jedzie*/ + +// what a horn needs to sound: air from the main reservoir, or the low voltage +enum class horn_supply +{ + air, + electric +}; + +/// High-level brake-system family. +enum class TBrakeSystem +{ + /// Individual (vehicle-only) brake. + Individual, + /// Pneumatic brake (Westinghouse-style). + Pneumatic, + /// Electro-pneumatic brake. + ElectroPneumatic +}; +/// Brake-system subtype identifying the manufacturer's distributor family. +enum class TBrakeSubSystem +{ + ss_None, + ss_W, + ss_K, + ss_KK, + ss_Hik, + ss_ESt, + ss_KE, + ss_LSt, + ss_MT, + ss_Dako +}; +/// Specific brake-distributor (valve) model. +enum class TBrakeValve +{ + NoValve, + W, + W_Lu_VI, + W_Lu_L, + W_Lu_XR, + K, + Kg, + Kp, + Kss, + Kkg, + Kkp, + Kks, + Hikg1, + Hikss, + Hikp1, + KE, + SW, + EStED, + NESt3, + ESt3, + LSt, + ESt4, + ESt3AL2, + EP1, + EP2, + M483, + CV1_L_TR, + CV1, + CV1_R, + Other +}; +/// Specific driver's brake-handle model (cab valve). +enum class TBrakeHandle +{ + NoHandle, + West, + FV4a, + M394, + M254, + FVE408, + FVel6, + D2, + Knorr, + FD1, + BS2, + testH, + St113, + MHZ_P, + MHZ_T, + MHZ_EN57, + MHZ_K5P, + MHZ_K8P, + MHZ_6P +}; +/// Type of the auxiliary (independent) brake. +enum class TLocalBrake +{ + NoBrake, + ManualBrake, + PneumaticBrake, + HydraulicBrake +}; +/// Brake delay parameter table (apply/release for passenger and freight). +using TBrakeDelayTable = double[4]; + +/// One row of the brake pressure / pipe pressure / flow-speed table for a brake handle position. +struct TBrakePressure +{ + /// Brake pipe pressure target [bar]. + double PipePressureVal = 0.0; + /// Brake cylinder pressure target [bar]. + double BrakePressureVal = 0.0; + /// Flow speed (orifice scaling). + double FlowSpeedVal = 0.0; + /// Brake system this entry applies to. + TBrakeSystem BrakeType = TBrakeSystem::Pneumatic; +}; + +/// Brake pressure table indexed by handle position. +using TBrakePressureTable = std::map; + +/// Engine / drive type. +enum class TEngineType +{ + None, + Dumb, + WheelsDriven, + ElectricSeriesMotor, + ElectricInductionMotor, + DieselEngine, + SteamEngine, + DieselElectric, + Main +}; +/// Form of energy supplied by the power source. +enum class TPowerType +{ + NoPower, + BioPower, + MechPower, + ElectricPower, + SteamPower +}; +/// Fuel type for combustion engines. +enum class TFuelType +{ + Undefined, + Coal, + Oil +}; + +class TDynamicObject; +struct neighbour_data +{ + TDynamicObject *vehicle{nullptr}; // detected obstacle + int vehicle_end{-1}; // facing end of the obstacle + float distance{10000.f}; // distance to the obstacle // NOTE: legacy value. TBD, TODO: use standard -1 instead? + // physics.derailment new, either vehicle off the track: the distance is between the ends where they are, and it + // changes with the moves of the vehicles (along their own axes, as V() and MoveLength() go) by these shares of them, + // rather than as along a track. see physics::Vehicle::coupler_gap_change() + bool off_track{false}; + double own_share{0.0}; + double other_share{0.0}; + + // the facing end of the obstacle there is + VehicleEnd FacingEnd() const + { + return static_cast(vehicle_end); + } +}; diff --git a/pr-reviews/PR-150.md b/pr-reviews/PR-150.md deleted file mode 100644 index 4362b0e00..000000000 --- a/pr-reviews/PR-150.md +++ /dev/null @@ -1,25 +0,0 @@ -# Review PR #150 — refactor: split OnCommands from Train - -Autor: @jerrrrycho · base: `master` · 39 plików, +12675/−12526 · ostatnia aktualizacja 10.10 -https://github.com/MaSzyna-EU07/maszyna/pull/150 - -**Werdykt: Approve kierunku; Request changes — rebase i ustalenie kolejności z PR-ami dotykającymi `Train.cpp`** - -## Podsumowanie -`vehicle/Train.cpp` rozbity skryptem na `vehicle/train/`: `Train.cpp`, `TrainCabSetup.cpp`, `TrainCommands{Auxiliary,Brakes,Controls,Doors,Electrical,Lights,Misc,Radio}.cpp`, `TrainSounds.cpp`, `TrainState.cpp`. `Train.h` przeniesiony do `vehicle/train/Train.h`, include'y w ~20 plikach poprawione. Przy okazji poprawki Sonara. - -## Co sprawdziłem (mechanicznie) -Porównałem wszystkie linie usunięte z `Train.cpp` z liniami dodanymi w `vehicle/train/*` (bez białych znaków): -- ~12 500 linii przeniesionych 1:1; różni się ~160 linii usuniętych / ~300 dodanych, z czego większość to nagłówki licencji i `#include` w nowych plikach. ✔ -- Pozostałe różnice to połączenie zagnieżdżonych `if` (S1066), np. `else if (RELEASE) { if (type == push) … }` → `else if (RELEASE && type == push)`. Sprawdziłem, że w tych miejscach to ostatnia gałąź łańcucha, a przy `EpFuseSwitch(true) && dsbPneumaticSwitch` wywołanie z efektem ubocznym zostaje po lewej. Semantyka zachowana. ✔ - -## Uwagi blokujące -1. **Rebase.** Od 10.10 do `master` doszły pliki, które włączają stary nagłówek — np. `world/RoadPoint.cpp` ma `#include "vehicle/Train.h"`, a PR go nie zmienia → po merge build się wysypie. Po rebase: `git grep '"vehicle/Train.h"'` musi zwracać pusto. -2. **Kolejność z innymi PR-ami.** Ten PR koliduje z każdym otwartym PR-em, który zmienia `Train.cpp`/`Train.h`: #234, #259, #261, #165, #172 (i pośrednio `feat/gl46-migration`). Proponuję ustalić z maintainerami okno: albo najpierw zmergować te małe PR-y, a potem rebase tego (skrypt da się puścić ponownie), albo odwrotnie i poprosić autorów o rebase. Skoro podział robi skrypt, warto go dołączyć do PR-a (np. `tools/`), żeby dało się go powtórzyć na świeżym `master`. - -## Pozostałe uwagi -3. **Rozdzielić przeniesienie od poprawek.** Poprawki Sonara w tym samym commicie co przeniesienie utrudniają review (`git diff --color-moved` nie pokaże ich czysto). Najlepiej: commit 1 — czysty move (skrypt), commit 2 — poprawki. Przy merge **nie** squashować, żeby `git blame -C` dalej działał. -4. **Zakomentowany kod** (np. stary `ConverterSwitch` w `TrainCommandsElectrical.cpp`) został przerobiony z `//` na `/* … */`, a nie usunięty. Skoro i tak gaśniemy uwagi Sonara (S125), lepiej go usunąć. -5. **Nazewnictwo / folder** — opis mówi „TBD”. `vehicle/train/` jest OK; trzeba to tylko potwierdzić przed merge, bo późniejsza zmiana to kolejny duży konflikt. -6. **„Probably works™” / „Please test them as well”.** Testy jednostkowe nie linkują `TTrain`, więc regresje wyjdą tylko w grze. Proszę o krótką listę ręcznie przetestowanych komend (światła, pantografy, drzwi, hamulce, radio) albo o checklistę dla testerów. -7. `CMakeLists.txt` — sprawdzić, że nowe pliki są też w innych systemach budowania, jeśli jakieś są (np. projekt VS, skrypty `build-dispatch`). diff --git a/pr-reviews/PR-159.md b/pr-reviews/PR-159.md deleted file mode 100644 index 7ea442ddb..000000000 --- a/pr-reviews/PR-159.md +++ /dev/null @@ -1,29 +0,0 @@ -# Review PR #159 — Trainset spawning, various Lua scripting changes - -Autor: @jakubg1 · base: `master` · 10 plików, +65/−38 · ostatnia aktualizacja 21.10 -https://github.com/MaSzyna-EU07/maszyna/pull/159 - -**Werdykt: Request changes — otwarte uwagi z rundy 21.10 nadal aktualne** - -## Podsumowanie -- `api.spawn_trainset(trainset)` w Lua — cały wpis `trainset … endtrainset` jak ze Startera. -- `state_serializer::insert_trainset_full()`. -- Rejestracja źródeł dymu i świateł pojazdu przeniesiona z `deserialize_node()` do `TDynamicObject::Init()` (`init_smoke_sources()`), więc działa też dla pojazdów wstawianych w trakcie symulacji. -- `insert_trainset()` dostaje parametr `Velocity`. - -## Co sprawdziłem -- Warunek świateł w `Init()` ma już poprawne nawiasy (`CategoryFlag == 1 && (front || rear)`) — uwaga @jerrrrycho z 04.09 zaadresowana. ✔ -- `Init()` zwraca `0.0` (porażka, pojazd jest potem kasowany) tylko przed `TurnOff()`, czyli przed nową rejestracją dymu/świateł — więc brak wiszących wskaźników w `Particles`/`Lights`. ✔ Wyjątek: pojazd z `Dim.L == 0` w `.fiz` przejdzie rejestrację, a potem zostanie usunięty jako „błąd”. Rzadkie, ale warto zabezpieczyć (rejestrować po sprawdzeniu długości albo wyrejestrować przy `delete`). - -## Uwagi blokujące (z poprzedniej rundy, wciąż w kodzie) -1. **Pętla w `insert_trainset_full()` nie zatrzymuje się na `endtrainset`.** Przykład @jerrrrycho: dwa składy w jednym stringu → oba wylądują na torze pierwszego. Do tego brak `endtrainset` nie daje błędu, a skład zostaje „w połowie”. Proponuję: czytać `node` aż do `endtrainset`; jeśli go nie ma — `ErrorLog` i usunąć już utworzone pojazdy (albo jasno udokumentować, że zostają). -2. **`lua_tostring()` może zwrócić `NULL`** (argument nie jest stringiem/liczbą) → `std::string` z `nullptr` = UB/crash. Zapowiedziany osobny PR dla wszystkich funkcji API jest OK, ale dla nowej funkcji to jedna linia: `luaL_checkstring(L, 1)`. -3. **Unikalne nazwy pojazdów.** Ponowne wywołanie z tym samym wpisem tworzy duplikaty nazw (`Vehicles.insert` zwróci `false`, log „duplicate vehicle name”), a pojazd i tak zostaje w świecie. Dla API skryptowego, które *z założenia* będzie wołane wielokrotnie, warto automatyczny sufiks albo jawny błąd i odrzucenie. - -## Pozostałe uwagi -4. **Parametr `Velocity` w `insert_trainset()`** — oba wywołania podają `0`, a `insert_trainset_full()` go nie używa. Jeśli to przygotowanie pod przyszłość — lepiej dodać go w PR, który go użyje (YAGNI). -5. **`init_smoke_sources() const`** — metoda `const`, która rejestruje `this` w globalnym menedżerze cząsteczek. Kompiluje się (jest przeciążenie `insert(…, TDynamicObject const*, …)`), ale semantycznie to efekt uboczny; bez `const` będzie czytelniej. -6. **Synchroniczne ładowanie** (zamrożenie przy spawnie) — zaakceptowane w dyskusji; warto dopisać to w dokumentacji funkcji Lua. -7. **Test dymu i świateł** — @jakubg1 sam prosił o sprawdzenie, że dym i światła pojawiają się poprawnie. Proszę o potwierdzenie (np. zrzut parowozu z dymem i składu z oświetleniem czoła) zarówno dla scenerii wczytanej, jak i składu ze `spawn_trainset`. -8. **Tytuł/opis**: „various Lua scripting changes”, a dochodzi jedna funkcja — opis do zaktualizowania. Historia commitów jest pomieszana (autor sam to pisze), więc squash przy merge. -9. Formatowanie: mieszane tabulatory/spacje w `DynObj.h` i `simulationstateserializer.cpp` (`if (!vehicle)` + tab). diff --git a/pr-reviews/PR-165.md b/pr-reviews/PR-165.md deleted file mode 100644 index 649dd5f19..000000000 --- a/pr-reviews/PR-165.md +++ /dev/null @@ -1,28 +0,0 @@ -# Review PR #165 — feat: optional in-game HUD overlay (speed, vehicle data, notch, signals, CA/SHP) - -Autor: @DJ-YASHITAKA · base: `master` · 11 plików, +2210/−11 · ostatnia aktualizacja 10.10 -https://github.com/MaSzyna-EU07/maszyna/pull/165 - -**Werdykt: Request changes — przypadkowe regresje w `Globals.h`, konflikty; proponuję zamienić na draft** - -## Podsumowanie -Przeciągalny HUD (prędkość z kolorowaniem limitu, łuki napięcia/prądu/pozycji/bocznika, nastawnik, sygnały, CA/SHP), tryby Standard/Custom/Off, okno personalizacji, konfiguracja w osobnym `hud.ini`. F1 przełącza tryby HUD, stary „Driving Aid” przechodzi pod Shift+F1. - -## Uwagi blokujące -1. **Niezwiązane zmiany w `utilities/Globals.h` — wyglądają na błąd przy merge:** - - `targetfps { 60.0f }` → `{ 0.0f }` — zmienia domyślny limit klatek wszystkim graczom, - - usunięty wpis `{"dynamicbrake", &uart_conf.dynamicenable}` z konfiguracji UART — psuje odczyt `eu07.ini` dla sprzętu UART (łamie zasadę „every existing file must still be read the way it was”). - Oba trzeba przywrócić. -2. **Konflikty** — GitHub pokazuje stan `dirty`. Od 10.10 na `master` weszło sporo zmian w `driveruilayer`/`Train.h`, więc rebase będzie konieczny. -3. **F1 zmienia znaczenie.** Gracze od lat mają pod F1 „Driving Aid”, a teraz dostaną cykl trybów HUD. Wg `CLAUDE.md` funkcja zmieniająca to, co symulator pokazuje, ma się dać wyłączyć w `eu07.ini`, a po wyłączeniu wszystko ma działać jak wcześniej — w tym klawisz F1. Proponuję: HUD domyślnie **wyłączony**, F1 bez zmian, osobny skrót/menu dla HUD (albo F1 przełącza HUD dopiero gdy `gui.hud.enabled yes`). -4. **Domyślny stan jest niejasny.** `hud_config::enabled { true }`, `mode { 0 }` (= Standard), a komentarz w `driveruilayer.cpp` mówi „fresh installs start OFF”. Proszę ustalić jedno i zgodnie z `CLAUDE.md` (pkt 3) — domyślnie wyłączony. - -## Pozostałe uwagi -5. **Gdzie leży `hud.ini`.** W dyskusji padło „game directory”. Gra z Steam/GOG bywa w `Program Files`, gdzie zapis się nie uda. `eu07.ini` jest czytane z profilu użytkownika (`user_config_path`) — `hud.ini` powinno iść tą samą ścieżką (czytanie z profilu, potem z folderu gry). Komentarz w `Globals.cpp` też wymaga aktualizacji, bo dyskusja w PR przewijała się między `eu07.ini` a `hud.ini`. -6. **`friend class hud_panel`** w `TTrain` i `TController` — HUD czyta prywatne pola. Lepiej dodać publiczne gettery `const` dla tego, co HUD potrzebuje (`fBlinkTimer` itd.), żeby UI nie wiązało się z wnętrzem klas. -7. **Konfiguracja w `Globals.h`**: kilkadziesiąt pól z tablicami C (`float arc_r[4]`, `int arc_col[4]`…) w globalnym `Global` — przenieść do własnego nagłówka HUD i użyć `std::array` (Sonar S5945). -8. **Font `fonts/lcdd.ttf`** — to asset z SVN. Fallback jest (dobrze), ale PR musi powiedzieć, co dodać do SVN i w jakiej kolejności. -9. **Znany błąd `VelNext == -1`** — do poprawy przed merge (wyświetlać „—” albo nic). -10. **Tłumaczenia** — nowe `STR_C(...)` wymagają wpisów w `lang/*.po` w SVN; @spot57 zwracał uwagę na jakość polskich tekstów. -11. **UX** — uwagi @spot57 i @maj00r (układ odporny na długość tłumaczeń, łuki zamiast pasków, bez dokładnego odwzorowania świateł) — warto odpisać, które przyjęte. -12. Autor sam pytał o przełączenie na draft — sugeruję to zrobić, dopóki pkt 1–4 nie są rozwiązane. diff --git a/pr-reviews/PR-167.md b/pr-reviews/PR-167.md deleted file mode 100644 index a73ef96bc..000000000 --- a/pr-reviews/PR-167.md +++ /dev/null @@ -1,22 +0,0 @@ -# Review PR #167 — whois: add lookahead mode for the timetable entry after the next stop - -Autor: @pwarszawski · base: `master` · 3 pliki, +42/−1 · Closes #164 -https://github.com/MaSzyna-EU07/maszyna/pull/167 - -**Werdykt: Approve z drobnymi uwagami** - -## Podsumowanie -Nowy tryb `whois +48` (`whois_name | whois_load`, bez `mode_alt`): do komórki pamięci trafia nazwa wpisu rozkładu o jedną pozycję za `StationIndex`, 0 i flaga postoju (1/0). Akcesor `TTrainParameters::TimeTableEntryAhead(Offset)` zwraca `TimeTable[0]` („nowhere”, `Ah == -1`) poza zakresem. - -## Co jest dobrze -- Kontynuacja sekwencji +0…+40, +56 zostaje wolne — zgodnie z wcześniejszym review. -- Uczciwie opisana zmiana dla +48 (dotąd działało jak +32) — wymagane przez zasady kompatybilności formatów. -- Akcesor z kontrolą zakresu, `TimeTable[0]` jako bezpieczna wartość. - -## Uwagi -1. **Kompatybilność +48.** Zmiana znaczenia istniejącej wartości flagi formalnie łamie regułę „every existing file must still be read the way it was”. Ryzyko jest małe, ale proponuję sprawdzić (grep po SVN `pctga`, katalog `scenery/`) czy żadna sceneria nie używa `whois` z wartością 48–55 — i dopisać wynik do opisu PR. -2. **Przeloty.** „passthroughs are not skipped” — dla dyżurnego rozróżniającego kierunki zwykle liczy się następna *stacja* rozgałęźna, a w rozkładzie po stacji często stoi kilka punktów przelotowych (posterunki, podg). Wtedy +48 zwróci posterunek, a nie kierunek. Warto to opisać w dokumentacji eventu albo przewidzieć w przyszłości wariant (+56?) z pomijaniem przelotów. -3. **Nazwa „none”.** Gdy brak maszynisty/właściciela, wpisuje się `"none"`, a poza końcem rozkładu `"nowhere"`. Dwie różne wartości dla „nic” to OK, ale proszę je udokumentować razem z trybem (wiki / dokumentacja eventów), bo skrypty scenerii będą je porównywać. -4. **Log.** `WriteLog` z konkatenacją — w nowym kodzie Sonar woli `std::format` (S6185). Treść logu można zachować identyczną. -5. **`TimeTableEntryAhead(int Offset)`** — komentarz w nagłówku mówi `Offset>=1`, ale funkcja przyjmuje też 0 i ujemne (zwraca odpowiednie wpisy lub `[0]`). Albo zaktualizować komentarz, albo dodać `assert`. -6. Na PR są 4 wcześniejsze komentarze review — upewnić się, że wszystkie są rozwiązane przed merge. diff --git a/pr-reviews/PR-172.md b/pr-reviews/PR-172.md deleted file mode 100644 index 538f12685..000000000 --- a/pr-reviews/PR-172.md +++ /dev/null @@ -1,35 +0,0 @@ -# Review PR #172 — UART MaSzyna Hardware Protocol v2 - -Autor: @Hirek193 · base: `master` · 34 pliki, +4860/−185 · ostatnia aktualizacja 10.10 -https://github.com/MaSzyna-EU07/maszyna/pull/172 - -**Werdykt: Request changes — konflikty, wątek startowany zawsze, brak testów kodeka** - -> Przegląd wyrywkowy: architektura, `hardware_manager`, `protocol_codec`, konfiguracja, zmiany w `Train.cpp`/`zmq_input`. `protocol_session.cpp` (1327 linii) tylko pobieżnie. - -## Podsumowanie -Nowy podsystem `hardware/`: transport (serial, przygotowany pod TCP), kodek ramek (COBS + CRC32C), sesja protokołu z heartbeatem, rejestry stanów/komend/symboli, subskrypcje, panel diagnostyczny w UI. Wspólny rejestr stanu `TrainState` używany też przez ZMQ. Nowe klucze `uart2*` w `eu07.ini`; stary UART działa bez zmian. - -## Co jest dobrze -- Przemyślany protokół z dokumentacją na wiki i biblioteką Arduino. -- Kodek ostrożny wobec danych z portu: `cobs_decode` sprawdza `index + runlength > Size`, `reader::require()` przed odczytem, limit rozmiaru ramki, CRC32C. ✔ -- Stary UART nietknięty, nowy włączany osobnymi kluczami — zgodne z zasadami kompatybilności `eu07.ini`. -- `get_engine_voltage()` wydzielone z `TTrain::Update()` bez zmiany logiki (sprawdziłem gałęzie: ED → `|Im·5|`, `Mn > 0 && |Im| > 0` → wzór, inaczej 0). ✔ -- ZMQ: nazwy pól wyjściowych zachowane w rejestrze (sprawdziłem m.in. `shp`, `springbrake_active`, `hv_current_3`, `time_millisecond_of_day`). ✔ - -## Uwagi blokujące -1. **Konflikty** — GitHub pokazuje stan `dirty`, ostatnia aktualizacja 10.10. Rebase na aktualny `master`. -2. **Wątek roboczy startuje zawsze.** `WITH_HARDWARE_PROTOCOL_V2` jest domyślnie `ON`, a `hardware_manager` uruchamia `std::thread` „even with no links configured” i co kilka sekund skanuje porty szeregowe. U każdego gracza, który nie ma żadnego sprzętu. Na Windows enumeracja COM-ów (np. porty Bluetooth) potrafi trwać, a dla niektórych sterowników jest widoczna. `CLAUDE.md`: nowa funkcja ma się dać wyłączyć i bez niej ma być jak dawniej. Proponuję startować wątek dopiero gdy jest `uart2` w `eu07.ini` albo gdy użytkownik otworzy panel diagnostyczny. -3. **Testy jednostkowe kodeka.** `protocol_codec` (COBS, CRC32C, `frame_decoder::feed`, reader/writer) to czyste funkcje — idealne do `tests/unit`. Proszę o testy: round-trip, ramka uszkodzona/ucięta, przekroczony limit rozmiaru, sklejone ramki w jednym `feed()`. To kod parsujący dane z zewnątrz, więc testy są tu szczególnie ważne. - -## Pozostałe uwagi -4. **Sonar / `CLAUDE.md`:** - - `std::thread` → `std::jthread` (S6168; tutaj wątek jest zawsze joinowany w destruktorze, więc zamiana bezpieczna), - - `std::lock_guard` → `std::scoped_lock` (S5997), - - `s_instance` — globalny wskaźnik na singleton (S5421); rozważyć przekazanie przez `drivermode_input`, - - `protocol_session.cpp` 1327 linii — prawie na pewno S3776/S134; proszę przejrzeć raport Sonara po rebase. -5. **`uart2ratelimit`** czyta 3 wartości bez walidacji (w odróżnieniu od pozostałych kluczy z `ParseOneClamped`) — wartości ujemne/zero mogą zablokować komunikację. -6. **Refaktor ZMQ w tym samym PR.** Przeniesienie pól ZMQ do wspólnego rejestru jest sensowne, ale zmienia działające API dla istniejących klientów. Proszę potwierdzić test z realnym klientem ZMQ (np. pulpit z kolejki SOPI) albo wydzielić do osobnego PR-a. -7. **`version_info.h.in` / gałąź w `VERSION_INFO`** — niezwiązane z UART, a zmienia linię wersji w logu. W CI (detached HEAD) `rev-parse --abbrev-ref HEAD` zwróci `HEAD`. Osobny mały PR. -8. Opis PR to tylko 2 linki — dopisać: co testowano (jaki sprzęt, ile linków naraz, reconnect po wypięciu kabla), wpływ na wydajność, i że stary `uart` działa obok (na różnych portach). -9. Komentarze po polsku bez polskich znaków (`napiecie`, `pradu`) — drobne, ale reszta kodu używa UTF-8. diff --git a/pr-reviews/PR-187.md b/pr-reviews/PR-187.md deleted file mode 100644 index 3ef178461..000000000 --- a/pr-reviews/PR-187.md +++ /dev/null @@ -1,35 +0,0 @@ -# Review PR #187 — AI braking: descents, approaches to a lower speed, and stopping 8-15 m short of a signal - -Autor: @pwarszawski · base: `master` (merge-base 66a940d, 21.10) · 6 plików, +319/−54 · Fixes #180 -https://github.com/MaSzyna-EU07/maszyna/pull/187 - -**Werdykt: Approve kierunku; Request changes — poprawki pod Sonar/GCC przed merge** - -> To jest podstawa stosu #187 → #263 → #264 → #265. Recenzje tamtych PR-ów dotyczą tylko ich przyrostu ponad ten PR. - -## Podsumowanie -1. `BrakeForceR()` bierze próg rapidu z rozrządu (`TBrake::GetRapidRatio`, NESt3/ESt4: 50 km/h zamiast stałych 40 km/h). -2. Utrzymywanie prędkości na spadku: horyzont przewidywania = połowa czasu reakcji hamulca (`brake_response_horizon`), ciągłe prawo regulacji zamiast skoku hamuj/jedź, rozdzielenie `AccDesired` (tylko hamulec) i `fAccDesiredGravity`. -3. Planowanie dojazdu z tablicy hamowania składu (`shaped_braking_demand` — bisekcja po stopniu hamowania), zatrzymanie 8–15 m przed semaforem, na wzniesieniu trzymanie składu hamulcem zespolonym. -4. Brak „puszczania” hamulca w strefie zbliżenia przy dojeździe do niższej prędkości; próba hamowania nie nadpisuje stopu/ograniczenia przed pociągiem. - -## Co jest dobrze -- Wyjątkowo rzetelna metodyka: 32 składy × 4 profile, czas rzeczywisty i x20, recheck na aktualnym master, testy na śliskiej szynie (0.3/0.5), konsultacja z youBy. Wyniki jednoznaczne (np. spadek: defekty 21/32 → 5/32, przejechania semafora 4 → 0). -- Zmiany predykcji (`GetRapidRatio`) zrobione wirtualnie w `TBrake` z domyślną dotychczasową aproksymacją — inne rozrządy bez zmian. -- Dobrze opisane znane ograniczenia (Rlmmp, 764, 413S/AL2) zamiast ich zamiatania. - -## Uwagi do poprawy (Sonar / GCC — wg `CLAUDE.md`) -1. **S107** — `shaped_braking_demand()` ma 8 parametrów (limit 7). Proponuję struct, np. `consist_brake_table { double vmax; std::span a0, a1; }` — przy okazji znikną surowe wskaźniki na tablice C (`double const *Brakea0`). -2. **S3358** — zagnieżdżony `?:` w `brake_response_horizon()` (`… ? BrakeDelay[isrelease ? 0 : 1] : BrakeDelay[isrelease ? 2 : 3]`). Ten sam wybór „opóźnienie napełniania wg G/P” pojawia się też w `IncBrake()` i `control_braking_force()` — warto helper `brake_fill_time(Vehicle)` / `brake_release_time(Vehicle)`. -3. **`&&` mieszane z `||` bez nawiasów** w `control_tractive_force()` (`velocity + 1.0 < VelNext || VelNext == 0.0 && … && …`) — GCC `-Wparentheses` i Sonar. Proszę dodać nawiasy (bez zmiany semantyki). -4. **S3608** — lambdy `fullbraking`/`travel` łapią `[&]`; jawne capture. -5. **S134/S3776** — `adjust_desired_speed_for_target_speed()` było już mocno zagnieżdżone, nowy blok „final approach” dokłada 2–3 poziomy. Wydzielenie gałęzi pociągowej (`Obey_train`) do osobnej metody, np. `final_approach_demand(vel, stoppingroom)`, i bloku „uphill coasting” (powtarza się 2×, różni się tylko offsetem) do helpera. -6. Funkcje `static` w pliku → anonimowy namespace (konwencja z `CLAUDE.md`). - -## Uwagi merytoryczne / pytania -7. **Przełącznik w `eu07.ini`?** `CLAUDE.md`: zmiana tego, co symulator robi z istniejącymi sceneriami, ma się dać wyłączyć. Tu można bronić tezy, że to poprawka błędów (przejechania semafora, piłowanie hamulcem), ale skala zmiany zachowania AI jest duża (np. zatrzymanie 8–15 m zamiast dotychczasowych marginesów zależnych od długości). Proszę maintainerów o świadomą decyzję: poprawka vs. funkcja z przełącznikiem. -8. **Koszt obliczeń.** `shaped_braking_demand` = do 30 iteracji bisekcji × 24 kroki całkowania, wołane do 2× na przebłysk AI. Przy scenerii z kilkudziesięcioma składami AI to wciąż mało, ale warto zmierzyć (profiler na l053_poludnie) albo zmniejszyć liczbę iteracji (tolerancja ~0.01 osiągana po ~9). -9. **Magiczne liczby**: 0.025 (próg „pod górę”), 0.15, 3.5, 50.0, 0.04, 15.0/7.5 — przynajmniej te używane w kilku miejscach jako `constexpr` z nazwą. -10. **Konflikt z #205**: wspomniane w komentarzu `int autoswitch;` — dobrze, że pominięte; potwierdzić kolejność merge. -11. **Komentarze w `Driver.h`** dla nowych pól są po polsku, a w `.cpp` po angielsku — drobne, ale lepiej jednolicie. -12. Opis PR bardzo długi; do merge commitu warto dać streszczenie + link, a szczegóły pomiarów zostawić w PR. diff --git a/pr-reviews/PR-224.md b/pr-reviews/PR-224.md deleted file mode 100644 index d1ef2c286..000000000 --- a/pr-reviews/PR-224.md +++ /dev/null @@ -1,29 +0,0 @@ -# Review PR #224 — Migrate from float3d to glm (second approach) - -Autor: @docentYT · base: `master` · 22 pliki, +204/−639 -https://github.com/MaSzyna-EU07/maszyna/pull/224 - -**Werdykt: Request changes — build VR, opis, kilka miejsc do sprawdzenia** - -## Podsumowanie -Usunięcie `utilities/Float3d.{h,cpp}` (`float3`, `float4`, `float4x4`) na rzecz `glm::vec3/quat/mat4`. `TSubModel::fMatrix` z wskaźnika (w unii z `iMatrix`) staje się wartością `glm::mat4 {1.0f}`; o tym, czy macierz jest niejednostkowa, decyduje już tylko flaga `0x8000`. Serializacja `.e3d` przez nowe `utilities/serialize.h`. - -## Co sprawdziłem (OK) -- **Kolejność elementów macierzy w `.e3d`/`.t3d`:** `float4x4::operator()(x)[y]` = `e[4x+y]`, a `glm::make_mat4(e)` jest column-major, więc `matrix[x][y]` w nowym `readMatrix` i w `(de)serialize_float32/64` daje dokładnie ten sam układ bajtów. ✔ Pliki binarne pozostają zgodne w obie strony. -- `InitialRotateMatrix()` jest wierną kopią `float4x4::InitialRotate()`. ✔ -- Brak `new/delete` dla macierzy — uwagi z poprzedniej rundy (@jakubg1, @Hirek193) zaadresowane. ✔ -- `BinInit`: `m.size() > iMatrix` przy `iMatrix == -1` — `-1` konwertuje się do `size_t` max, więc warunek jest fałszywy i zostaje jednostkowa. Działa, ale patrz pkt 4. - -## Uwagi blokujące -1. **Build z OpenVR się nie skompiluje.** `vr/openvr_imp.cpp` (linie ~253 i ~349 na master) woła `TSubModel::ReplaceMatrix()`, które ten PR usuwa, a pliku `vr/` PR nie zmienia. CI buduje bez VR, więc tego nie złapie. Trzeba podmienić na przypisanie `fMatrix` **i ustawienie `iFlags |= 0x8000`** (patrz pkt 2). -2. **Flaga `0x8000` jest teraz jedynym źródłem prawdy.** Wcześniej renderer mnożył przez macierz, gdy wskaźnik nie był pusty. Teraz każde miejsce, które przypisuje `fMatrix` z zewnątrz (VR, ewentualne skrypty, przyszły kod), musi też ustawić flagę, inaczej macierz zostanie po cichu zignorowana. Proponuję setter `SetMatrix(glm::mat4 const&)`, który ustawia/kasuje flagę wg `== glm::mat4(1.0f)`, i prywatne `fMatrix`. -3. **Inne gałęzie i PR-y.** Usunięcie `Float3d.h` łamie każdy otwarty kod, który używa `float3` — np. #261 dodaje nowe `SetRotate(float3(1, 0, 0), …)`, a `feat/gl46-migration` (#216) pewnie też go używa. Proszę ustalić kolejność merge z maintainerami i zostawić komentarz w #261/#216. Sprawdzić też `betterRenderer/` (np. `IntelTAA.h` ma trafienia `float3`; to prawdopodobnie HLSL, ale build z `WITH_BETTER_RENDERER=ON` trzeba przepuścić). - -## Pozostałe uwagi -4. `if (m.size() > iMatrix)` — porównanie `size_t` z `int` (GCC `-Wsign-compare`, Sonar). Lepiej `if (iMatrix >= 0 && static_cast(iMatrix) < m.size())`. To też jawnie pokazuje intencję. Przy okazji: indeks poza zakresem w uszkodzonym pliku był wcześniej UB, teraz jest cicho ignorowany — warto zalogować `Bad model`. -5. **Zakomentowany kod** w `ParentMatrix()` z dopiskiem „It will not work, fMatrix is not a pointer anymore” — lepiej usunąć cały martwy blok (Sonar S125). -6. `TSubModel *Root … TODO: Fix missing delete` — jeśli to znany wyciek, lepiej osobne issue niż TODO w kodzie wprowadzone przy okazji. -7. **Pamięć:** każdy `TSubModel` ma teraz 64 B macierzy zamiast 8 B wskaźnika, a submodele binarne nie współdzielą już tablicy `Matrices`. Dla dużych scenerii (tysiące instancji modeli) warto zmierzyć zużycie RAM przed/po — opis wymienia to jako „potential downside”, przydałaby się liczba. -8. **Opis PR** jest bardzo skąpy jak na zmianę tej skali. Proszę dopisać: co testowano (np. wczytanie kilku scenerii z `.t3d` i `.e3d`, konwersja `convertmodels`, porównanie zrzutów ekranu, pantografy — tam jest dużo matematyki macierzowej), oraz że format plików się nie zmienia. -9. Formatowanie: `fMatrix =glm::mat4();` (brak spacji), mieszane wcięcia w `DynObj.cpp` (spacje vs tabulatory w zmienianych liniach). -10. `SafeNormalize` w `glmHelpers.h` — brak nowej linii na końcu pliku. diff --git a/pr-reviews/PR-227.md b/pr-reviews/PR-227.md deleted file mode 100644 index 169acce5d..000000000 --- a/pr-reviews/PR-227.md +++ /dev/null @@ -1,15 +0,0 @@ -# Review PR #227 — simulationenvironment: Adjust turbidity values - -Autor: @dos1 · base: `master` · 1 plik, +6/−6 -https://github.com/MaSzyna-EU07/maszyna/pull/227 - -**Werdykt: Approve po uzupełnieniu opisu** - -## Podsumowanie -Zmiana mapowania zachmurzenia (`Global.Overcast`) na mętność atmosfery (`fTurbidity`): minimum 3 → 4 (bo 3 psuje model w nocy) i wyższe wartości w środkowym/wysokim zakresie. - -## Uwagi -1. **Pierwsze dwa progi są teraz identyczne** (`<= 0.10 ? 4` i `<= 0.20 ? 4`), podobnie `0.30/0.40 → 5`, `0.50/0.60 → 6` i `0.90/else → 9`. Drabinka 10 zagnieżdżonych `?:` z powtórzonymi wartościami to dobry moment, żeby ją uprościć — np. tablica `std::array` progów albo krótka funkcja. Przy okazji zniknie zgłoszenie Sonara S3358 (zagnieżdżony operator `?:`), które i tak dotyczy zmienianych linii. -2. **„Turbidity 3 breaks the model at night”** — warto w opisie dodać 1–2 zdania, *jak* się psuje (NaN? czarne/świecące niebo?) i ewentualnie zrzut ekranu. Jeśli problem jest w samym modelu Preetham (znane ograniczenie dla T < ~2–3 przy słońcu pod horyzontem), lepszym miejscem na poprawkę może być clamp w modelu nieba, a nie w mapowaniu pogody — wtedy wartość 3 zostałaby dostępna w dzień. -3. **Zmiana wyglądu istniejących scenerii** — przy bezchmurnej pogodzie niebo będzie bardziej mgliste niż dotąd. To uzasadniona poprawka, ale wg `CLAUDE.md` należy to wprost opisać w PR (najlepiej porównanie przed/po dla 0.0, 0.5 i 0.9 overcast, dzień i noc). -4. Do przetestowania razem z #228 (sRGB) i #230 (rozmiar Słońca/Księżyca) — wszystkie trzy zmieniają odbiór nieba. diff --git a/pr-reviews/PR-228.md b/pr-reviews/PR-228.md deleted file mode 100644 index 34c3e3d98..000000000 --- a/pr-reviews/PR-228.md +++ /dev/null @@ -1,18 +0,0 @@ -# Review PR #228 — utilities: XYZtoRGB: Use sRGB colorspace - -Autor: @dos1 · base: `master` · 1 plik, +2/−2 -https://github.com/MaSzyna-EU07/maszyna/pull/228 - -**Werdykt: Approve z drobnymi uwagami** - -## Podsumowanie -Zamiana macierzy odwrotnej XYZ→RGB z Adobe RGB na sRGB. Merytorycznie słuszne: reszta pipeline'u (tekstury, framebuffer sRGB, tonemapping) pracuje w sRGB/Rec.709, więc współrzędne Adobe RGB (szerszy gamut) wyświetlane jako sRGB dawały zbyt mało nasycone kolory nieba. - -## Uwagi -1. **Komentarz nad macierzą jest teraz mylący.** Nad aktywną linią nadal stoi `// M^-1 for Adobe RGB …`, a pod zakomentowaną `// m^-1 for sRGB:`. Proponuję odwrócić komentarze albo usunąć martwą macierz Adobe RGB całkiem — to jest dokładnie to, co Sonar oznacza jako „commented-out code” (S125). -2. **Widoczna zmiana wyglądu.** Wg `CLAUDE.md`: „A feature doesn't make existing sceneries look suddenly different after an update”. To jest poprawka błędu, więc mieści się w wyjątku, ale warto w opisie PR jasno napisać, co się zmienia wizualnie (kolor nieba/słońca), najlepiej ze zrzutami przed/po w kilku porach dnia. -3. **Renderer GL4.6.** Plik `utilities/color.h` zostaje po migracji, ale warto potwierdzić, czy `feat/gl46-migration` (#216) korzysta z tej samej funkcji i czy tam też ma iść ta zmiana (albo czy gałąź już ją ma). -4. Opis: literówka „depite” → „despite”. - -## Sugestia -Rozważyć połączenie/uzgodnienie z #227 (turbidity) — obie zmiany wpływają na ten sam model nieba i dobrze byłoby je przetestować razem. diff --git a/pr-reviews/PR-230.md b/pr-reviews/PR-230.md deleted file mode 100644 index fc06e8690..000000000 --- a/pr-reviews/PR-230.md +++ /dev/null @@ -1,15 +0,0 @@ -# Review PR #230 — opengl33renderer: Fix up the sizes of Sun and Moon - -Autor: @dos1 · base: `master` · 1 plik, +5/−6 -https://github.com/MaSzyna-EU07/maszyna/pull/230 - -**Werdykt: Approve z prośbą o wskazanie odpowiednika w GL4.6** - -## Podsumowanie -Przywrócenie rozmiarów tarcz Słońca i Księżyca z legacy renderera (`lerp` zależny od wysokości nad horyzontem) w miejsce „fizycznych” 0.00463/0.00451, które przy typowym FoV wyglądają na zbyt małe. - -## Uwagi -1. **Renderer, który odchodzi.** Wg `CLAUDE.md` cała rodzina `rendering/opengl33*` zostanie usunięta przez #216, a zmiany na `master` w tym kodzie mają mieć w PR wskazany odpowiednik na `feat/gl46-migration` albo informację, że gałąź już go ma. Proszę dopisać, gdzie w `rendering/opengl46/` / `vulkan14/` liczony jest rozmiar tarcz i czy tam też trzeba to zmienić — inaczej po migracji regresja wróci. -2. **Komentarz TODO dla Słońca mówi „from the moon object”** — skopiowany z bloku Księżyca. Skoro linie i tak są dotykane, warto poprawić na „sun object”. -3. **Uzasadnienie „fails to take FoV into account”** — rozmiar kątowy *jest* niezależny od FoV; problem jest raczej percepcyjny (zbyt mała tarcza na ekranie przy 45°+ FoV). Sugeruję doprecyzować opis, żeby ktoś za rok nie „naprawił” tego z powrotem na wartości fizyczne. Rozważyć stałą nazwaną z komentarzem („celowo ~7× większe niż rzeczywiste ze względów percepcyjnych”). -4. Zrzut przed/po w opisie bardzo by się przydał (zmiana wyglądu istniejących scenerii — wg `CLAUDE.md` powinna być opisana). diff --git a/pr-reviews/PR-231.md b/pr-reviews/PR-231.md deleted file mode 100644 index ef57ede81..000000000 --- a/pr-reviews/PR-231.md +++ /dev/null @@ -1,20 +0,0 @@ -# Review PR #231 — driveruilayer: Allow to toggle AI driver from the menu - -Autor: @dos1 · base: `master` · 1 plik, +13/−0 -https://github.com/MaSzyna-EU07/maszyna/pull/231 - -**Werdykt: Request changes (drobne)** - -## Podsumowanie -Nowe menu „Vehicle” z przełącznikiem „Autopilot”, wysyłające `aidriverenable` / `aidriverdisable` przez `m_relay`. Świetny pomysł dla nowych graczy, mała i czysta zmiana. - -## Uwagi -1. **Warunek widoczności jest bardziej restrykcyjny niż klawiatura.** Menu jest ukryte, gdy `Global.RealisticControlMode && !DebugModeFlag` — zawsze, także gdy gracz siedzi w kabinie. Tymczasem `command_relay::post()` (input/command.cpp ~l. 891) blokuje komendy pojazdu w trybie realistycznym tylko przy `FreeFlyModeFlag`. Czyli Shift+Q w kabinie działa, a pozycja menu znika. Proponuję warunek zgodny z relay'em: - ```cpp - bool const blocked = FreeFlyModeFlag && Global.RealisticControlMode && !DebugModeFlag; - ``` - i najlepiej `ImGui::BeginDisabled(blocked)` zamiast ukrywania — gracz widzi, że opcja istnieje. -2. **Skrót w menu.** `MenuItem` przyjmuje skrót — warto podać `"Shift+Q"` / `"Q"` (domyślne bindy z `driverkeyboardinput.cpp`), tak jak robią to pozycje w „Mode windows”. Uwaga: bindy są konfigurowalne, więc albo pobrać aktualny z mapy klawiszy, albo pominąć. -3. **Tłumaczenia.** `STR_C("Vehicle")` i `STR_C("Autopilot")` to nowe klucze — trzeba je dodać do `lang/*.po` w SVN (w repo jest tylko `editor_pl.po`). Proszę napisać w opisie PR, co dodać do SVN; bez tego gracze PL zobaczą angielskie napisy. Sprawdzić też, czy w innych miejscach UI tryb AI nie nazywa się inaczej (np. „AI driver”) — lepiej trzymać jedną nazwę. -4. **Multiplayer (#173)**: przy sterowaniu cudzym pojazdem/wspólną sesją przełączanie AI z menu może wymagać dodatkowych warunków — nie blokuje tego PR, ale warto mieć na uwadze. -5. Drobne: `auto const *driver` — `Mechanik` to wskaźnik nie-const, a `AIControllFlag` tylko czytamy, więc OK; Sonar może jednak zgłosić S6004 (zmienna używana tylko w warunku → `if (auto const *driver = …; driver && …)`). diff --git a/pr-reviews/PR-234.md b/pr-reviews/PR-234.md deleted file mode 100644 index d8f669141..000000000 --- a/pr-reviews/PR-234.md +++ /dev/null @@ -1,20 +0,0 @@ -# Review PR #234 — Train: Handle 3-way light switches in headlighttoggle actions - -Autor: @dos1 · base: `master` · 1 plik (`vehicle/Train.cpp`), +60/−16 -https://github.com/MaSzyna-EU07/maszyna/pull/234 - -**Werdykt: Approve z uwagami (głównie refaktor i opis zmiany zachowania)** - -## Podsumowanie -`headlighttoggleleft/right` dla przełączników 3-pozycyjnych (brak `ggLeftEndLightButton`, jest `ggLeftLightButton`) cyklicznie przełącza: wył. → reflektor → czerwone → wył. Dzięki temu przełącznik da się obsłużyć myszą/VR. Poprzednia uwaga @jakubg1 (pojazdy bez przełączników) jest zaadresowana warunkiem `|| ggLeftLightButton.SubModel == nullptr`. - -## Uwagi -1. **Zmiana zachowania klawiatury.** `headlighttoggle*` to ta sama komenda, którą wywołuje klawisz. Na ~110 pojazdach z listy (303E, 4E, EN57, ET22, TEM2…) drugie wciśnięcie klawisza zapali teraz czerwone zamiast zgasić reflektor, a dopiero trzecie zgasi. To może zaskoczyć graczy (i scenariusze szkoleniowe). Proszę opisać to wprost w PR, albo rozważyć rozróżnienie źródła (mysz/VR vs klawiatura) — np. przez osobną komendę „cycle” dla kliknięcia na przełącznik. -2. **Duplikacja.** Blok lewy i prawy są identyczne poza maskami i przyciskami — razem ~60 linii kopii. Warto wyciągnąć helper w anonimowym namespace, np. - ```cpp - void toggle_headlight_3way(TTrain *Train, command_data const &Command, side Side); - ``` - albo przynajmniej `bool has_3way_switch(TGauge const &End, TGauge const &Main)`. Ta sama heurystyka („brak dedykowanego przełącznika = 3-way”) jest już w `OnCommand_redmarkerenableleft` — dobrze mieć ją w jednym miejscu. -3. **Złożoność.** Dodatkowe zagnieżdżenie `if` w `if (GLFW_PRESS)` może podbić S134/S3776 w Sonarze (QG przeszedł, ale warto zerknąć na szczegóły). Wczesny `return` dla `Command.action != GLFW_PRESS` uprości kod. -4. **Stan niespójny.** Jeśli oba bity (`headlight_left` i `redmarker_left`) są ustawione (np. przez inną komendę/skrypt), gałąź `else if` przejdzie na czerwone — OK, ale warto to świadomie skomentować. -5. Formatowanie: `} else {` w jednej linii odbiega od stylu reszty pliku (klamra w nowej linii). diff --git a/pr-reviews/PR-239.md b/pr-reviews/PR-239.md deleted file mode 100644 index 637e52111..000000000 --- a/pr-reviews/PR-239.md +++ /dev/null @@ -1,23 +0,0 @@ -# Review PR #239 — Refactor/mover long functions - -Autor: @jerrrrycho · base: `master` · 103 pliki, +13168/−3871 · 67 commitów -https://github.com/MaSzyna-EU07/maszyna/pull/239 - -**Werdykt: Request changes — rebase, opis, kolejność ze stosem AI/hamulców** - -> Przegląd wyrywkowy (rozmiar). Skupiłem się na strukturze zmian i na ryzyku dla innych PR-ów. - -## Podsumowanie -Rozbicie długich funkcji `TMoverParameters` (`RunCommand`, `TractionForce`, `UpdatePipePressure`, `IncMainCtrl`/`DecMainCtrl`, bateria…) i części `hamulce.cpp` na nazwane metody (`RunBrakeCommand`, `SeriesMotorTractionForce`, `UpdateMainValve`, `DieselElectricForce`…). Zmiana czysto strukturalna — pod S3776/S134. - -## Uwagi blokujące -1. **Diff zawiera infrastrukturę testów, która jest już na `master`.** `tests/unit/golden.cpp`, `test_controls.cpp`, `COVERAGE.md`, dane `tests/unit/data/fiz/*` itd. (~8 tys. linii) pokazują się jako „dodane”, bo trafiły na `master` innym PR-em (squash). Po rebase na aktualny `master` zostanie właściwy przyrost: `Mover.cpp`, `MOVER.h`, `hamulce.cpp` i ewentualne zmiany testów. Bez tego nie da się rzetelnie zrecenzować. -2. **Brak opisu.** Dla refaktoru tej skali proszę o: listę rozbitych funkcji, zapewnienie „bez zmian zachowania” i — kluczowe — **wynik testów golden** (`Unit tests: N/N passed`, bez regeneracji golden). Golden traces to tu jedyna siatka bezpieczeństwa; jeśli jakiś ślad trzeba było zregenerować, to znak zmiany zachowania i musi być opisany. -3. **Kolizja ze stosem #187 → #262 → #263 → #264 → #265** (wszystkie zmieniają `Mover.cpp::BrakeForceR`, `hamulce.h`, `Oerlikon_ESt`) oraz z #259/#260 (`MOVER.h`). Przeniesienie kodu do nowych funkcji sprawi, że tamte łatki się nie nałożą. Trzeba ustalić kolejność z maintainerami; moja propozycja: najpierw mniejsze PR-y z poprawkami zachowania, potem ten refaktor (refaktor łatwiej powtórzyć niż przepisać poprawki fizyki). - -## Pozostałe uwagi (z `MOVER.h`) -4. **Sygnatury `Run*Command(…, bool &OK)` zwracające też `bool`.** Dwa kanały wyniku (zwracany „obsłużono” i wyjściowy `OK`) są mylące. Rozważyć `std::optional` (brak = komenda nie z tej grupy) albo mały struct. -5. **Duplikacja `power()` const / non-const.** Można zaimplementować wersję non-const przez `const_cast` z wersji const (wzorzec Meyersa) albo zostawić jedną `const` + osobny setter. -6. **Nowe metody prywatne czy publiczne?** Większość pomocników (`UpdateMainValve`, `DieselElectricShuntForce`…) powinna być `private` — sprawdzić, że nie powiększają publicznego API `TMoverParameters`. -7. Parametry wyjściowe przez referencję (`double &dtrans, double &dmoment`, `double &tempUmax`) — przy okazji refaktoru warto zwracać struct (czytelność, Sonar). -8. 67 commitów — przy merge squash albo uporządkowanie historii. diff --git a/pr-reviews/PR-240.md b/pr-reviews/PR-240.md deleted file mode 100644 index ead0ab495..000000000 --- a/pr-reviews/PR-240.md +++ /dev/null @@ -1,25 +0,0 @@ -# Review PR #240 — fix(gl46): editor cursor depth read in the biased depth pass (port of 7078edf) - -Autor: @miloszunio · base: `feat/gl46-migration` · 2 pliki, +86/−27 · Fixes #238 -https://github.com/MaSzyna-EU07/maszyna/pull/240 - -**Werdykt: Approve po teście w symulatorze i poprawkach pod Sonar** - -## Podsumowanie -Port poprawki z Vulkana do GL4.6: odczyt głębokości pod kursorem edytora w przebiegu głębi sceny (z `glPolygonOffset(-1,-1)`) dawał punkt ~1 piksel dalej — przy kącie ślizgowym nawet metry. Teraz: -- czytany jest blok 3×3 (PBO, a przy MSAA renderbuffer 3×3), -- bias jest kompensowany (mniejsza różnica sąsiadów na oś, większa z osi + `2^(ilogb(d)-23)`), -- unprojekcja używa widoku/projekcji/kamery z klatki, w której zlecono odczyt; punkt trzymany w world space (`dvec3`). - -## Co jest dobrze -- Poprawna analiza: przy reversed-Z ujemny offset oddala powierzchnię, więc dodanie `m + r` ją przywraca. -- Zapamiętanie widoku z klatki żądania usuwa drugi, niezależny błąd (ruch kamery między żądaniem a odczytem). -- Sprawdzenie wyniku `read_data()` zamiast sentinela `max()`. - -## Uwagi -1. **Brak testu w symulatorze** („Not run in the simulator yet”). Proszę przed merge sprawdzić scenariusz z opisu (SSR/AO on, perspektywa, kąt ślizgowy) oraz MSAA on/off i `gfx_skippipeline` — blit 3×3 z bufora MSAA to nowa ścieżka. -2. **Sonar S3608 / S1188.** Lambdy `depth_at` i `slope` łapią `[&]` i nie są przekazywane do algorytmu standardowego — Sonar to zgłosi. Proponuję jawne capture (`[&depths, this]`, `[&depth_at, pointdepth]`) albo funkcje wolne w anonimowym namespace (`depth_bias_slope(depths, size, centre)`). Zmniejszy to też złożoność `Update_Mouse_Position()`. -3. **Nagłówki (GCC).** `std::ldexp`, `std::ilogb` → ``, `std::array` → ``. Upewnić się, że są dołączone wprost (lista z `CLAUDE.md`). -4. **`m_mouseknown`** nigdy nie wraca do `false` (np. po zmianie scenerii / resecie renderera) — `Mouse_Position()` zwróci wtedy stary punkt z poprzedniego świata. Drobne, ale łatwo zresetować przy `Init()`/zmianie scenerii. -5. **Komentarz o biasie** jest bardzo długi (7 linii jednym ciągiem) — dobrze, że jest, ale czytelniej byłoby rozbić na punkty lub dać odnośnik do commita Vulkana 7078edf. -6. Opis PR wspomina „Built with `-fsyntax-only`” — warto poczekać na pełny build CI na gałęzi `feat/gl46-migration`. diff --git a/pr-reviews/PR-241.md b/pr-reviews/PR-241.md deleted file mode 100644 index cf9052948..000000000 --- a/pr-reviews/PR-241.md +++ /dev/null @@ -1,29 +0,0 @@ -# Review PR #241 — feat(editor): area fill: Enter finishes an area, Esc drops the outline, a list of filled areas to change later - -Autor: @miloszunio · base: `feat/gl46-migration` · 7 plików, +751/−97 -https://github.com/MaSzyna-EU07/maszyna/pull/241 - -**Werdykt: Request changes — test w edytorze, undo przez regenerację, opis formatu** - -## Podsumowanie -Narzędzie wypełniania obszaru dostaje cykl życia: Enter kończy obszar, Esc porzuca kontur, lista wypełnionych obszarów (Zmień / Pokaż / Usuń), undo dla dodania/zmiany/usunięcia, ziarno `std::mt19937` przechowywane z obszarem. Trwałość w nowym `editor/editorFillStore.{hpp,cpp}` jako linie-komentarze w plikach warstw, modele nazwane `_`. - -## Co jest dobrze -- Realny problem UX (nie dało się zakończyć konturu) rozwiązany kompletnie, z listą i edycją. -- Format w liniach-komentarzach — symulator je pomija, więc sceneria z tą funkcją dalej czyta się w obecnym wydaniu (zgodnie z `CLAUDE.md`). -- `fill_store` wzorowany na istniejącym `switch_store` — spójna architektura. - -## Uwagi blokujące -1. **Nie uruchomione w edytorze** („Built with -fsyntax-only… Not run in the editor yet”). Przy tej skali zmian (zapis do pliku, usuwanie modeli po nazwie) proszę o przejście scenariusza z opisu, najlepiej skryptem `EU07_EDITOR_SELFTEST` na kopii scenerii: kontur → Enter → Zmień → przesuń punkt → Enter → Usuń → Undo → zapis → wczytanie → Zmień. -2. **Opis i kod mówią o różnych znacznikach.** Opis PR: `//$f`; kod (`kMark`, `editormarks`, komentarz w `.hpp`): `//$w`. Proszę ujednolicić opis i upewnić się, że `//$w` nie koliduje z niczym w Rainsted/StarterNG ani w innych narzędziach piszących do scenerii. -3. **Undo zmiany/usunięcia odtwarza modele z ziarna.** `std::uniform_real_distribution` jest zależne od implementacji biblioteki standardowej (MSVC ≠ libstdc++), a lista szablonów z banku węzłów może się zmienić między sesjami. W tej samej sesji i tym samym buildzie to zadziała, ale nie jest to „te same obiekty” w ogólności (`CLAUDE.md`: nie polegać na zachowaniu nieprzenośnym). Bezpieczniej: przed usunięciem zrobić snapshot usuwanych węzłów (`export_as_text`) i przy undo wstawić dokładnie je. Jeśli zostaje regeneracja — opisać ograniczenie w komentarzu. -4. **Identyfikacja modeli po nazwie `fillN_k`.** `owns()` uzna każdy węzeł o nazwie `fill1_7` za część obszaru `fill1` — także ręcznie nazwany przez autora scenerii. „Zmień”/„Usuń” go skasuje. `next_id()` sprawdza tylko `fillN_0`. Rozważyć mniej kolizyjny prefiks (np. `$fill1_7`) albo zapis listy nazw modeli w `//$w`. - -## Uwagi (Sonar / styl) -5. `std::string seed, density, spacing, …` w jednej deklaracji — S1659. -6. `erase(std::remove_if(...))` → `std::erase_if` (S6165); `std::find_if(begin, end, …)` → `std::ranges::find_if` (S6197). -7. `g_areas`, `g_loaded` — niestałe zmienne globalne (S5421). Jeśli `switch_store` robi tak samo, to OK dla spójności, ale lepiej trzymać stan w obiekcie należącym do `editor_mode`. -8. Magiczne `100000` (limit punktów konturu) → nazwana stała. - -## Pytanie o gałąź -9. Funkcja edytora trafia do `feat/gl46-migration` (#216, draft, merge po 26.11). Czy to celowe (narzędzie istnieje tylko na tej gałęzi)? Jeśli kod narzędzia jest też na `master`, `CLAUDE.md` każe robić funkcje na własnej gałęzi od `master`. diff --git a/pr-reviews/PR-243.md b/pr-reviews/PR-243.md deleted file mode 100644 index 45cf45495..000000000 --- a/pr-reviews/PR-243.md +++ /dev/null @@ -1,29 +0,0 @@ -# Review PR #243 — Editor, NMT location: assign the place from the camera; //$g found in included files - -Autor: @miloszunio · base: `feat/switch-blades` · 3 pliki, +55/−1 -https://github.com/MaSzyna-EU07/maszyna/pull/243 - -**Werdykt: Request changes (konflikty + struktura kodu)** - -## Podsumowanie -1. „Przypisz z kamery” — odwrotność „The scenery is here”: kliknięty punkt mapy = obecna pozycja kamery, z tego liczony jest początek układu (`E0 = E + x`, `N0 = N − z`). -2. „Środek zapisany w pliku scenerii” — przywraca początek z linii `//$g`. -3. `read_georeference()` szuka `//$g` także w plikach `include` (jeden poziom). - -Bardzo przydatne — dziś jeden błędny klik psuł georeferencję. - -## Co sprawdziłem -- Wzór kamery jest zgodny z istniejącą konwersją w `editormode.cpp` (`config.north + Camera.Pos.z`, `config.east - Camera.Pos.x`). ✔ -- Kolejność `{m_georeference_origin.y, m_georeference_origin.x}` zgadza się z `nmt_place_scenery` (`Point.x = east`). ✔ -- `read_georeference()` jest wołane co klatkę w `render_nmt_place`, ale ma cache `m_georeference_read`, więc pliki czytane są raz. ✔ - -## Uwagi -1. **Konflikty.** GitHub pokazuje stan `dirty` — PR wymaga rebase na aktualny `feat/switch-blades`. Jest też `split/3-switch-blades` — warto ustalić, na którą gałąź ma finalnie trafić. -2. **Zagnieżdżenie i wcięcia w `read_georeference()`.** Wewnętrzna pętla nie została wcięta po dodaniu zewnętrznego `for`, a głębokość to teraz for→for→if→if→if — Sonar zgłosi S134 i prawdopodobnie S3776. Proponuję: - - helper `std::optional include_target(std::string_view line)` w anonimowym namespace, - - helper `bool parse_georeference_line(std::string const &line, …)`, - - pętlę po plikach z wczesnym `continue`. -3. **Ścieżki include.** `Global.asCurrentSceneryPath / name` — sprawdzić wielkość liter (na Linuksie `irt/IRT_sceneria.inc` vs `irt/irt_sceneria.inc`); funkcja dla głównego pliku już ma fallback na porównanie bez wielkości liter, include'y nie. -4. **Limit `files.size() < 8`** — magiczna liczba, warto nazwaną stałą z komentarzem. -5. **Ochrona przed pomyłką u źródła.** Skoro problemem jest przypadkowe „The scenery is here”, rozważyć potwierdzenie (popup) tego przycisku, gdy sceneria ma już `//$g` albo ułożone tory. Nowe przyciski to dobra droga powrotu, ale prewencja byłaby jeszcze lepsza. -6. Opis PR zawiera link do sesji Claude Code — do usunięcia przed merge (nie wnosi nic dla recenzenta). diff --git a/pr-reviews/PR-259.md b/pr-reviews/PR-259.md deleted file mode 100644 index fd77baeb8..000000000 --- a/pr-reviews/PR-259.md +++ /dev/null @@ -1,21 +0,0 @@ -# Review PR #259 — fix(cab): a diesel with only the starter button stops its engine with the main switch off command - -Autor: @jerrrrycho · base: `master` · 4 pliki, +136/−1 · Fixes eu07/maszyna#427 -https://github.com/MaSzyna-EU07/maszyna/pull/259 - -**Werdykt: Approve z drobnymi uwagami** - -## Podsumowanie -SM03/SM04/2Ls150 (i DL2, ST44, TEM2) mają w kabinie tylko `main_on_bt`. `OnCommand_linebreakeropen()` dla takich pojazdów tylko animowało przycisk i wychodziło — silnika nie dało się zgasić. Teraz dla `DieselEngine`/`DieselElectric` komenda otwiera obwód (`MainSwitch(false)`), a przycisk rozruchu nie jest animowany. - -## Co jest dobrze -- Bardzo dobra analiza przyczyny (automatyczna pompa paliwa + przetwornica podtrzymująca 110 V). -- Tabela „przed/po” z gry, lista dotkniętych pojazdów — zgodnie z `CLAUDE.md` (zmiana zachowania z istniejącymi danymi jest opisana). -- Świadome nieruszanie kwestii „pozycja 0 = stop” (to zmiana danych, wymaga decyzji). - -## Uwagi -1. **Testy nie pokrywają właściwej zmiany.** Testy sprawdzają `MainSwitch(false)` w fizyce, co działało już przed PR. Zmieniona jest gałąź w `TTrain::OnCommand_linebreakeropen()`, której testy nie dotykają (TTrain nie jest linkowany w unit testach?). Test `REQUIRE(shunter->MainCircuitOpensWithStarterOnly())` sprawdza tylko typ silnika. Proponuję albo opisać to uczciwie w komentarzu testu, albo wydzielić decyzję „czy komenda otwiera obwód” do funkcji, którą da się przetestować bez `TTrain` (np. wolna funkcja przyjmująca: jest `main_off_bt`/`main_bt`/`main_on_bt` + typ silnika). -2. **Nazwa `MainCircuitOpensWithStarterOnly()` myli.** Funkcja nie sprawdza nic o kabinie/starterze — tylko typ silnika. Czytając `Train.cpp` można pomyśleć, że sprawdza konfigurację przycisków. Propozycja: `MainSwitchOffStopsEngine()` albo `IsDieselEngine()`; warunek o samym `main_on_bt` zostaje w `Train.cpp`. -3. **ST44 / TEM2** — dotąd gaszone pompą paliwa, teraz także `m`. Warto upewnić się u twórców tych pojazdów (lub w dokumentacji), że to pożądane — w realu TEM2 ma przycisk „stop silnika”, więc raczej tak, ale niech to będzie świadome. -4. **Brak wizualnej reakcji** po `m` na tych pojazdach — uzasadnione (trzymany przycisk uruchomiłby silnik), ale gracz może sądzić, że klawisz nie działa. Może dźwięk przełącznika (`dsbSwitch`) mimo braku animacji? Teraz `fMainRelayTimer = 0` daje dźwięk przekaźnika — proszę potwierdzić, że coś słychać. -5. Test JSON `diesel_shunter.json` — dobry, ale `_comment` zawiera opis SM03; warto dodać nazwę pliku `.fiz`, z którego pochodzą parametry, żeby dało się je zaktualizować. diff --git a/pr-reviews/PR-260.md b/pr-reviews/PR-260.md deleted file mode 100644 index f053d656b..000000000 --- a/pr-reviews/PR-260.md +++ /dev/null @@ -1,20 +0,0 @@ -# Review PR #260 — fix(cab): on the SU45 and SU46 the open line contactors lamp lights with the contactors opened by the pressure switch - -Autor: @jerrrrycho · base: `master` · 3 pliki, +124/−1 · Fixes eu07/maszyna#263 -https://github.com/MaSzyna-EU07/maszyna/pull/260 - -**Werdykt: Approve** - -## Podsumowanie -`LineContactorsLampLit()` dla `DieselElectric` zwraca samo `!StLinFlag` — lampka styczników liniowych na SU45/SU46/SP45 świeci także, gdy styczniki otworzył presostat (PG < 3.6 bar albo hamulec > 2 bar). Lokomotywy elektryczne bez zmian. - -## Co jest dobrze -- Precyzyjna tabela stanów (przed/po) i weryfikacja w grze krok po kroku. -- Lista pojazdów w danych, których to dotyczy — zgodnie z `CLAUDE.md`. -- Testy z nowym `diesel_electric.json`, a test na niskie ciśnienie failuje bez poprawki. - -## Uwagi -1. **Rozróżnienie po `EngineType`.** Semantyka lampki to cecha obwodu konkretnej lokomotywy, a nie typu napędu. Dziś w danych to się pokrywa (tylko SU45/SU46/SP45), ale przyszła spalinowo-elektryczna lokomotywa z lampką „start możliwy” dostanie złe zachowanie. Rozważyć opcjonalny klucz w `.fiz`/`.mmd` (domyślnie: obecna heurystyka po typie silnika), albo przynajmniej komentarz „heurystyka, zmienić gdy pojawi się pojazd …”. -2. **`i-contactorsb`** — opis mówi, że dotyczy też tej lampki; w testach jest tylko `LineContactorsLampLit()`. Jeśli `i-contactorsb` używa tej samej funkcji — OK, warto to zaznaczyć w opisie testu. -3. Drobne: komentarz nad funkcją w `MOVER.h` jest długi (3 linie z historią issue). Szczegóły historyczne lepiej w commit message, w kodzie wystarczy reguła. -4. Do rozważenia: SP45 (`DumbDE`) nie był sprawdzany w grze — tylko SU46. Szybki test na SP45 przed merge. diff --git a/pr-reviews/PR-261.md b/pr-reviews/PR-261.md deleted file mode 100644 index f5ba5911d..000000000 --- a/pr-reviews/PR-261.md +++ /dev/null @@ -1,24 +0,0 @@ -# Review PR #261 — feat(cab): 401Da oil pump lamp and slotted speedometer lever - -Autor: @jerrrrycho · base: `master` · 7 plików, +218/−1 · Closes eu07/maszyna#546 -https://github.com/MaSzyna-EU07/maszyna/pull/261 - -**Werdykt: Request changes — wydzielić poprawkę AVX2, reszta OK** - -## Podsumowanie -- Nowa lampka `i-oilpump:` (pompa smarowania wstępnego; gaśnie po uruchomieniu silnika). -- Nowy klucz `.mmd` `animslottedlever:` — dźwignia z jarzmem napędzana czopem wiązara (napęd prędkościomierza). -- Dodatkowe testy opóźnienia startu sprężarki (`CompressorStartDelay`, już na master z #217). -- **Poprawka builda:** `GLM_FORCE_AVX2` tylko gdy kompilator faktycznie celuje w AVX2. - -## Uwagi -1. **Poprawka AVX2 powinna być osobnym PR-em.** To ważna poprawka (crash na CPU bez AVX2 przy `ENABLE_AVX2=OFF`), niezwiązana z 401Da. Osobny PR szybciej przejdzie review, łatwiej ją zcherry-pickować na gałąź wydania 26.11 i na `feat/gl46-migration`, i będzie widoczna w changelogu. Sama zmiana (`#elif defined(__AVX2__)`) jest poprawna dla MSVC (`/arch:AVX2`) i GCC (`-mavx2`). -2. **`animslottedlever:` — kompatybilność OK** (nowy opcjonalny klucz; bez niego nic się nie zmienia). Proszę o: - - wpis do dokumentacji formatu `.mmd` (wiki), skoro żaden pojazd jeszcze go nie używa, - - informację, czy brak submodelu ma logować błąd `Bad model` — dla nowej funkcji to OK (prawdziwy błąd danych). -3. **Matematyka bez testu.** `slottedlever_angle()` to czysta funkcja geometrii, a nie jest testowana tylko dlatego, że siedzi w `TDynamicObject`. Proponuję przenieść ją do małego nagłówka (np. `utilities/` albo wolna funkcja w anonimowym namespace + deklaracja w nagłówku testowalnym) i dopisać testy: oś wewnątrz okręgu → pełny obrót, okrąg przez oś → wahanie ±90°. -4. **`float3`** w `SetRotate(float3(1,0,0), angle)` — #224 właśnie migruje `float3d` na `glm`. Nowy kod lepiej od razu na `glm::vec3`, żeby nie powiększać konfliktu. -5. **`update_slottedlevers()`** jest wołane w `ABuLittleUpdate()` poza sprawdzeniem odległości (`ObjSqrDist < 50*50`) — dla pustego wektora to nic nie kosztuje, ale dla pojazdów z dźwigniami liczy się zawsze. Rozważyć wołanie razem z animacjami kół (te same warunki LOD). -6. **Indeks `wheelid`**: warunek `lever.axle < iAnimType[ANIM_WHEELS] && lever.axle < pAnimations.size()` zakłada, że animacje kół są na początku `pAnimations` — proszę o komentarz albo assert. -7. **Lampka `i-oilpump:`** pokazuje `OilPump.is_active`. Dla pojazdów, gdzie pompa oleju pracuje cały czas (nie tylko smarowanie wstępne), lampka będzie świecić stale — to raczej poprawne, ale warto opisać semantykę w dokumentacji `.mmd`. -8. Opis: „SM42 stood in for the diesel” — test z prawdziwym modelem 401Da jest w „Known issues”; OK, ale niech ktoś od modelu 401Da potwierdzi przed wydaniem. diff --git a/pr-reviews/PR-262.md b/pr-reviews/PR-262.md deleted file mode 100644 index 789dd6a05..000000000 --- a/pr-reviews/PR-262.md +++ /dev/null @@ -1,18 +0,0 @@ -# Review PR #262 — AI: use the locomotive releaser only when starting off - -Autor: @pwarszawski · base: `master` · 1 plik, +4/−1 -https://github.com/MaSzyna-EU07/maszyna/pull/262 - -**Werdykt: Approve** - -## Podsumowanie -Reguła „wyluzuj lokomotywę, to szybciej ruszymy” w `TController::control_releaser()` nie miała warunku prędkości i odpalała odluźniacz w biegu (104 z 122 włączeń powyżej 1 km/h w pomiarze), opróżniając zbiornik sterujący lokomotywy przy zahamowanym pociągu. Dodano `mvOccupied->Vel < 1.0`. - -## Co jest dobrze -- Minimalna, celowana zmiana zgodna z intencją oryginalnego komentarza. -- Bardzo dobry opis z pomiarem master vs master+PR. - -## Uwagi -1. **Próg 1 km/h a ruszanie.** Przy ruszaniu AI najpierw zadaje jazdę, a lokomotywa może już pełznąć (>1 km/h), zanim cylinder spadnie poniżej 0.4 bar — wtedy reguła przestanie działać w pół ruszania. Proszę potwierdzić w logu z pomiaru, że czas ruszania (od zadania jazdy do np. 10 km/h) się nie wydłużył, szczególnie dla ciężkich składów towarowych z ESt3. Ewentualnie próg np. 5 km/h byłby bezpieczniejszy, a dalej odcinałby wszystkie przypadki z pomiaru (7–100 km/h). -2. **Kolejność merge z #263/#264/#265.** Te PR-y tego samego autora też dotykają `control_releaser()` / logiki hamowania AI. Warto zaznaczyć w opisach, w jakiej kolejności mają wchodzić i czy #262 jest zawarty w pozostałych (żeby uniknąć konfliktów i podwójnego review). -3. Drobne: komentarz po angielsku obok polskiego — OK, ale można go skrócić do jednej linii. diff --git a/pr-reviews/PR-263.md b/pr-reviews/PR-263.md deleted file mode 100644 index 2d9829eb2..000000000 --- a/pr-reviews/PR-263.md +++ /dev/null @@ -1,35 +0,0 @@ -# Review PR #263 — ESt3 distributor: spring preload, minimum stage, releaser and AL2 timing; AI predicts the new characteristic - -Autor: @pwarszawski · base: `master` (zbudowany na #187) · przyrost ponad #187: 4 pliki, ~+60/−15 -https://github.com/MaSzyna-EU07/maszyna/pull/263 - -**Werdykt: Approve merytorycznie; przed merge — testy golden / CI i decyzja o kolejności z #264** - -> Recenzja dotyczy tylko przyrostu ponad #187 (interdiff policzony lokalnie). - -## Podsumowanie -Model rozrządu `TNESt3`: -- wstępny nacisk sprężyn 0.21 bar zamiast 0.05 (`dPSprezyny`), `BVM` liczone z tego samego offsetu → pełne hamowanie dalej daje `MaxBP`, -- minimalny stopień 0.28 bar (`pStopnia`), pełne odluźnienie gdy cel = 0, -- odluźniacz automatyczny: ZS 15 l z 5.0 do 0.4 bar w ~23 s (było 5.6 s), -- `dTN` 1.65 → 1.62 (literówka), -- AL2: komora impulsowa 1 l, dysze cylindra przeskalowane wg tablicy 3-9. - -AI: `TNESt3::GetBrakeRatio()` zwraca rzeczywisty udział ciśnienia w cylindrze dla danego spadku w PG, więc tablice hamowania AI odpowiadają charakterystyce zaworu. - -## Co sprawdziłem -- `GetBrakeRatio(1.0) == 1.0`: `spadek = MaxBP/BVM + 0.21 = HPP − LPP`, `cel = (spadek − 0.21)·BVM = MaxBP`. ✔ Dzięki temu wywołania `BrakeForceR(1.0, …)` w `DynObj.cpp` i `Train.cpp` (wskaźniki siły hamowania) się nie zmieniają. -- Nowe progi w `CheckState()` to stare progi przeskalowane do domeny ciśnienia w cylindrze (`0.01 → 0.01·BVM`) — równoważne poza nowym minimalnym stopniem. ✔ -- Zmiana fizyki dotyczy każdego pojazdu z ESt3 bez zmian w `.fiz` — opis PR mówi to wprost, zgodnie z `CLAUDE.md`. ✔ - -## Uwagi -1. **Testy golden / CI.** Na `master` są ślady golden (`tests/unit/data/golden/consist/`, `test_consist.cpp` loguje m.in. `BrakeForceR0.25`), a także `test_brakes.cpp` / `test_brake_cycle.cpp` z pojazdami ESt3 (`401W`, `430W`…). PR nie zmienia żadnego testu, a GitHub pokazuje stan `unstable`. Proszę po rebase na master sprawdzić, które testy się zmieniły, i zaktualizować golden świadomie (z opisem w PR, co się zmieniło i dlaczego). -2. **Testy akceptacyjne jako unit testy.** W opisie jest „valve test bench that runs the acceptance procedures” (77 → 40 wyników poza tolerancją). Bardzo proszę dołożyć choć część tych prób (stopień minimalny — próby 12/22, odluźniacz — próba 27, czasy AL2 — tablica 3-9) do `tests/unit`. To najlepsza ochrona tej poprawki przed regresją. -3. **Kolejność merge.** Opis przyznaje, że sam #263 pogarsza precyzję zatrzymań (403 → 363 w oknie 8–15 m) i daje problem z ciężkim G na śliskim spadku, który naprawia dopiero #264. Proponuję merge #263 i #264 razem (albo w jednym oknie wydania), a nie #263 osobno przed 26.11. -4. **Wolniejszy odluźniacz a reszta AI.** 4× wolniejsze opróżnianie ZS wpływa też na reguły `control_releaser()` przy łączeniu/rozłączaniu i na #265 (ruszanie pod górę z odluźniaczem). Czy scenariusze manewrowe (sprzęganie/odczepianie, odhamowanie składu po połączeniu) zostały sprawdzone? Gracz używający odluźniacza na wagonach też odczuje różnicę — warto to wspomnieć w changelogu. -5. **Kod:** - - `static double const dPSprezyny/pStopnia` → `constexpr double` (wytyczne GCC/Sonar w `CLAUDE.md`) i najlepiej w anonimowym namespace. - - Współczynniki AL2 `0.914 / 0.885 / 0.82 / 0.8` — dopisać w komentarzu, z jakich czasów tablicy 3-9 wynikają (albo jak je wyliczono), żeby dało się je odtworzyć. - - `0.0049` w odluźniaczu — podobnie, nazwana stała z odniesieniem do próby 27. - - W `BrakeForceR()` `GetBrakeRatio` jest stosowane przed korektą ED (`dbrake_automatic`), rapidem i `DMU -0.3`. Wydaje się poprawne, ale proszę potwierdzić, że kolejność jest zamierzona. -6. **Konsultacja z youBy** — warto, żeby youBy zostawił w PR formalne approve części fizycznej; to jego model. diff --git a/pr-reviews/PR-264.md b/pr-reviews/PR-264.md deleted file mode 100644 index 446c3e910..000000000 --- a/pr-reviews/PR-264.md +++ /dev/null @@ -1,27 +0,0 @@ -# Review PR #264 — AI braking: smaller steps, earlier, while approaching a stop or a lower speed - -Autor: @pwarszawski · base: `master` (zbudowany na #187 + #263 + #262) · przyrost: `Driver.cpp/.h`, ~+70/−10 -https://github.com/MaSzyna-EU07/maszyna/pull/264 - -**Werdykt: Approve z uwagami (struktura logiki, stałe)** - -> Recenzja dotyczy tylko przyrostu ponad #263 (interdiff policzony lokalnie). Przyrost zawiera też zmianę z #262 (odluźniacz < 1 km/h) — po merge #262 zniknie z diffu. - -## Podsumowanie -- Margines dociążenia hamulca przy dojeździe do niższej prędkości: pół stopnia zamiast pełnego (`brake_increase_margin()`). -- Śledzenie „niedoboru” opóźnienia co 3 s (`fShortfall`, `iShortfallGrowth`) — rosnący niedobór przy nieruszanym kranie → mały stopień od razu. -- `DecBrake()`: pozycja poniżej pierwszej traktowana jak pierwsza (minimalny stopień z #263). -- Utrzymywanie prędkości na spadku: wzmocnienie ograniczone do `1/(3.6·horizon)`, czyli różnica zdejmowana w czasie reakcji hamulca. - -## Co jest dobrze -- Każda zmiana ma uzasadnienie fizyczne w komentarzu. -- Wynik na śliskim spadku wyraźny (defekty 7.0 % → 1.0 %, >30 m przed semaforem 7.3 % → 4.3 %). - -## Uwagi -1. **Wyniki mieszane na suchym spadku.** „Stops more than 30 m short” 3.2 % → 5.4 % i defekty 3.9 % → 4.2 %. Przy 3 vs 4 przebiegach to może być szum — proszę podać rozrzut między przebiegami albo dorobić 4. przebieg, żeby porównanie było symetryczne. -2. **Dwie ścieżki „dodaj stopień, bo pociąg nie nadąża”.** Jedna w `IncBrake()` (`fShortfall > 0.02 && fBrakeHeldTime > horizon`), druga w `control_braking_force()` (`iShortfallGrowth >= 2 && …`), która i tak woła `IncBrake()` przez `cue_action`. Trudno to śledzić — proszę o jeden helper typu `bool is_falling_behind() const` używany w obu miejscach, albo komentarz opisujący, jak się te warunki składają. -3. **Deklaracja zapowiadająca `static brake_response_horizon(...)`** w środku pliku — lepiej przenieść definicję wyżej (lub wszystkie helpery do anonimowego namespace na początku pliku). -4. **Magiczne liczby**: `0.02`, `0.005`, `3.0` s, `2` sprawdzenia, `0.04` — `constexpr` z nazwami (część jest współdzielona z #187/#265). -5. **Zmiana w warunku `room`** (usunięcie `VelNext > 0.0`) zmienia też dojazd do *niższej prędkości* z już zaciągniętym hamulcem — opis PR o tym nie wspomina. Proszę dopisać jedno zdanie. -6. **Zakres `brake_increase_margin()`** — tylko `TBrakeSystem::Pneumatic`; dla EP/ED zostaje pełny stopień. OK, ale warto to zaznaczyć w komentarzu (EP reaguje od razu, więc nie potrzebuje). -7. Komentarze nowych pól w `Driver.h` są po angielsku, sąsiednie po polsku — drobne, jednolitość. diff --git a/pr-reviews/PR-265.md b/pr-reviews/PR-265.md deleted file mode 100644 index b5df4b81c..000000000 --- a/pr-reviews/PR-265.md +++ /dev/null @@ -1,32 +0,0 @@ -# Review PR #265 — AI on up gradients: hold a train coming to a stand, start on the train brake - -Autor: @pwarszawski · base: `master` (zbudowany na #264 → #263 → #187, #262) · przyrost: `Driver.cpp/.h`, ~+150/−5 -https://github.com/MaSzyna-EU07/maszyna/pull/265 - -**Werdykt: Request changes — ryzyko dla sprzęgów i stan `bUphillStart`** - -> Recenzja dotyczy tylko przyrostu ponad #264 (interdiff policzony lokalnie). - -## Podsumowanie -1. **Zatrzymanie pod górę:** hamulec zespolony zaciągany zanim samo wzniesienie zatrzyma pociąg; bez luzowania poniżej 10 km/h (`uphill_stop_hold()`); bez „dociągania” gdy hamulec już działa (`uphill_brake_committed()`); hamulec lokomotywy < 3 km/h i natychmiast przy staczaniu. -2. **Ruszanie pod górę** (`control_uphill_start()`): hamulec zespolony zostaje, lokomotywa odhamowana (dodatkowy + odluźniacz), moc podawana przeciw zahamowanemu składowi; zwolnienie hamulca gdy Ft > 1.1 × siła z pochylenia, pociąg ruszy, albo po 45 s. - -Wyniki bardzo dobre: staczanie po zatrzymaniu 51 → 0, ruszanie ze staczaniem 7/62 → 0/155. - -## Uwagi blokujące -1. **Pełna moc przeciw zahamowanemu składowi przez 10–18 s.** Opis sam to przyznaje („still applies full power at once”). Dla ciężkich towarów to klasyczny przepis na zerwanie sprzęgu (por. dyskusję w #187 i fix #255). Proszę o: - - statystykę maks. sił w sprzęgach podczas ruszania (base vs PR) dla najcięższych składów (ET42 + 30 wagonów, ET41 + 25), - - albo ograniczenie mocy do wartości potrzebnej na utrzymanie (np. do ~1.1–1.2 × `holdingforce`) dopóki `bUphillStart`. -2. **`bUphillStart` może utknąć na `true`.** Flaga jest resetowana tylko w `control_uphill_start()`, wołanym z `control_tractive_force()`. Jeśli AI zostanie wyłączone w trakcie ruszania (Shift+Q / Q, a po #231 także z menu), flaga zostaje, a w `determine_consist_state()` `heldforstart` dalej: - - ignoruje niezluzowane hamulce przy ustalaniu `Ready`, - - zeruje `fReady`. - Proszę resetować `bUphillStart` przy przejęciu sterowania przez gracza / zmianie rozkazu / `OrderCurrentGet()`, a w `determine_consist_state()` warunkować to dodatkowo `AIControllFlag`. -3. **`Ready` ignoruje *każde* hamowanie** podczas ruszania (także `vehicle->Fb > 10 kN`, np. zaciągnięty hamulec ręczny wagonu albo niezluzowany wagon z innego powodu). Przez 45 s AI będzie ciągnąć przeciw nim. Lepiej ignorować tylko hamulec zespolony (`b_on|b_hld` przy zaciągniętym kranie), a `Fb` od hamulca ręcznego/postojowego nadal blokować. - -## Pozostałe uwagi -4. **Niespójne progi pochylenia:** `-0.005` (`uphill_stop_hold`, lokomotywa przy staczaniu), `-0.01` (`control_uphill_start`), `-0.025` (`uphill_brake_committed`, #187), `-0.05` (staczanie w `control_braking_force`). Proszę o nazwane stałe i krótkie uzasadnienie różnic. -5. **Odluźniacz przy ruszaniu a #263.** Po #263 odluźniacz ESt3 opróżnia ZS ~23 s zamiast ~6 s — czy pomiary „10–18 s pulling against the brake” były robione już z nowym odluźniaczem (stos sugeruje, że tak — proszę potwierdzić)? -6. **Złożoność (Sonar S3776/S134/S1067):** warunek `independentbrakeapply` w `control_braking_force()` ma 9 członów z mieszanym `&&`/`||` — wydzielić do `bool should_hold_on_independent_brake(double velocity) const`. -7. **`break` w `DecBrake()`** — działa, bo jesteśmy w `switch`, ale przy dwóch nowych `break` przed właściwą logiką czytelniej byłoby jedno wczesne wyjście z komentarzem. -8. `fUphillStartTime` mierzony `ElapsedTime` — przy pauzie/przyspieszeniu czasu OK, ale 45 s powinno być stałą nazwaną (`uphill_start_timeout`). -9. **Kolejność merge:** całego stosu #187 → #262 → #263 → #264 → #265 — zaproponuję maintainerom zmergować to w jednym oknie po kolei, z rebase każdego PR po poprzednim, żeby CI/Sonar liczyły tylko przyrost. diff --git a/pr-reviews/README.md b/pr-reviews/README.md deleted file mode 100644 index 10dd03576..000000000 --- a/pr-reviews/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# Recenzje otwartych PR-ów — MaSzyna-EU07/maszyna (stan na 7.11.2026) - -23 PR-y (bez draftów #216, #221, #203, #173, #137). Każda recenzja w osobnym pliku `PR-.md`, gotowa do wklejenia na GitHuba. -Punktem odniesienia były zasady zespołu z `CLAUDE.md` (GCC, Sonar, kompatybilność danych, renderer GL4.6). - -| PR | Tytuł (skrót) | Autor | Werdykt | -|---|---|---|---| -| #265 | AI pod górę: trzymanie i ruszanie na hamulcu | pwarszawski | Request changes | -| #264 | AI: mniejsze, wcześniejsze stopnie hamowania | pwarszawski | Approve z uwagami | -| #263 | ESt3: nacisk sprężyn, stopień min., odluźniacz, AL2 | pwarszawski | Approve; golden/CI do sprawdzenia | -| #262 | AI: odluźniacz tylko przy ruszaniu | pwarszawski | Approve | -| #261 | 401Da: lampka pompy oleju, dźwignia prędkościomierza | jerrrrycho | Request changes (wydzielić AVX2) | -| #260 | SU45/SU46: lampka styczników liniowych | jerrrrycho | Approve | -| #259 | SM03: gaszenie silnika wyłącznikiem | jerrrrycho | Approve z drobnymi | -| #243 | Edytor NMT: przypisz z kamery, `//$g` w include | miloszunio | Request changes | -| #241 | Edytor: lista wypełnionych obszarów | miloszunio | Request changes | -| #240 | GL46: głębia kursora edytora | miloszunio | Approve po teście | -| #239 | Refaktor długich funkcji Mover | jerrrrycho | Request changes (rebase) | -| #234 | Przełączniki świateł 3-pozycyjne | dos1 | Approve z uwagami | -| #231 | Przełączanie AI z menu | dos1 | Request changes (drobne) | -| #230 | Rozmiar Słońca i Księżyca | dos1 | Approve (+ odpowiednik GL46) | -| #228 | XYZ→RGB w sRGB | dos1 | Approve z drobnymi | -| #227 | Wartości turbidity | dos1 | Approve po opisie | -| #224 | float3d → glm | docentYT | Request changes (build VR) | -| #187 | AI: spadki, dojazdy, 8–15 m przed semaforem | pwarszawski | Approve kierunku; Sonar/GCC | -| #172 | UART Hardware Protocol v2 | Hirek193 | Request changes | -| #167 | whois +48 | pwarszawski | Approve z drobnymi | -| #165 | HUD | DJ-YASHITAKA | Request changes → draft | -| #159 | Spawn składów z Lua | jakubg1 | Request changes | -| #150 | Podział OnCommands z Train | jerrrrycho | Approve kierunku; rebase | - -## Najważniejsze znaleziska -- **#165** — przypadkowe zmiany w `Globals.h`: `targetfps` 60 → 0 i usunięty klucz UART `dynamicbrake` (psuje odczyt `eu07.ini`). -- **#224** — usuwa `ReplaceMatrix()`, którego używa `vr/openvr_imp.cpp` → build z OpenVR się nie skompiluje (CI tego nie łapie). -- **#265** — flaga `bUphillStart` może zostać `true` po przejęciu sterowania przez gracza; pełna moc przeciw zahamowanemu składowi przez 10–18 s to ryzyko dla sprzęgów. -- **#150** — po 10.10 doszedł `world/RoadPoint.cpp` ze starym `#include "vehicle/Train.h"` → po merge build się wysypie bez rebase. -- **#263** — zmienia fizykę każdego ESt3, a nie rusza testów golden; GitHub pokazuje `unstable`. -- **#159** — `insert_trainset_full()` nie zatrzymuje się na `endtrainset`; `lua_tostring` może zwrócić `NULL`. - -## Proponowana kolejność merge (konflikty) -1. Małe, niezależne: #262, #260, #259, #167, #228, #227, #230, #234, #231 (po poprawce). -2. Stos AI/hamulce, po kolei z rebase: #187 → #263 → #264 → #265 (najlepiej w jednym oknie). -3. Poprawka AVX2 z #261 jako osobny PR, potem #261. -4. Refaktory na końcu, z ponownym puszczeniem skryptu / rebase: #150 (Train.cpp), #239 (Mover.cpp), #224 (float3 → glm). -5. Gałęzie poboczne: #240, #241 → `feat/gl46-migration`; #243 → `feat/switch-blades`. -6. Do rozmowy z autorami / draft: #165, #172, #159. diff --git a/ref/licenses/README.md b/ref/licenses/README.md new file mode 100644 index 000000000..10ff550eb --- /dev/null +++ b/ref/licenses/README.md @@ -0,0 +1,29 @@ +# License texts of the Windows audio DLLs + +The Windows build ships `OpenAL32.dll` (OpenAL Soft 1.25.2) and `libsndfile-1.dll` (libsndfile 1.2.2), and in +`licenses/` next to them the texts of those libraries and of what they have built in. The DLLs and OpenAL Soft's own +`COPYING` come from the release zips, which CI downloads; the texts below are kept here, so a build doesn't depend on +the servers they come from. CI copies them into `licenses/` and checks each one by the SHA-256 in +`.github/workflows/build_bin.yml` (step "Add the OpenAL Soft and libsndfile DLLs"). `.gitattributes` keeps them byte +for byte as upstream (`-text`), whatever the line ending settings of a checkout. What each text covers is in +`audio-libraries.txt`, which that step writes. + +| File | Taken from | SHA-256 | +|------|------------|---------| +| `libsndfile-COPYING.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/COPYING | `ad01ea5cd2755f6048383c8d54c88459cd6fcb17757c5c8892f8c5ea060f6140` | +| `libsndfile-ALAC-LICENSE.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/ALAC/LICENSE | `232efbd83786e157286b0b96c68ebb673541b69b33036287bf1e5ec5067a49d9` | +| `libsndfile-GSM610-COPYRIGHT.txt` | https://raw.githubusercontent.com/libsndfile/libsndfile/1.2.2/src/GSM610/COPYRIGHT | `1bbe7119b1bcd1489e0f36cb95b8902f7f0ceec9a2f3a67394bc9f4709a4e0a7` | +| `libogg-COPYING.txt` | https://raw.githubusercontent.com/xiph/ogg/v1.3.5/COPYING | `d2ab5758336489da61c12cc5bb757da5339c4ae9001f9bb0562b4370249af814` | +| `libvorbis-COPYING.txt` | https://raw.githubusercontent.com/xiph/vorbis/v1.3.7/COPYING | `ec1815db59fcd302846df949d7424876cb2e2dc5ed1606c5fb0b36787b1cf43a` | +| `flac-COPYING.Xiph.txt` | https://raw.githubusercontent.com/xiph/flac/1.4.2/COPYING.Xiph | `6e58d3036f05e2a0d58af854c12a505ddbe75011d71a598a2170987f3b15408d` | +| `opus-COPYING.txt` | https://raw.githubusercontent.com/xiph/opus/v1.4/COPYING | `8338ce8d922bb4416ce3dd1e5680173332435e3f0755007ac7801ccd674fe682` | +| `mpg123-COPYING.txt` | https://scm.orgis.org/view/mpg123/tags/1.31.3/COPYING?view=co | `c22482728a634a8dfdb4ff72a96d4c1ed64cd8f3e79335c401751ac591609366` | +| `lame-COPYING.txt` | https://sources.debian.org/data/main/l/lame/3.100-6/COPYING (the same file as in LAME 3.100) | `bfe4a52dc4645385f356a8e83cc54216a293e3b6f1cb4f79f5fc0277abf937fd` | +| `openal-soft-pffft-LICENSE.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/LICENSE-pffft | `64056328b3e7bc104e24ef96accc1a7abead156f0c02d1b87c97e3f3a28030de` | +| `openal-soft-gsl-LICENSE.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/gsl/LICENSE | `4c21dc82a1c7186ea754fd59d504c00947953a3401fe8e24eaa44109ef8e2555` | +| `openal-soft-BSD-3Clause.txt` | https://raw.githubusercontent.com/kcat/openal-soft/1.25.2/BSD-3Clause | `b5a08cf98996dd83aa906a72c163600f6cb17a65ce546a553815a1267abd43ff` | +| `openal-soft-winpthreads-COPYING.txt` | https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/mingw-w64-libraries/winpthreads/COPYING | `63263614cdd29f2f93cba85e992f041b31f9fc7b4033692f31269489a8a1b177` | +| `openal-soft-mingw-w64-runtime.txt` | https://raw.githubusercontent.com/mingw-w64/mingw-w64/v13.0.0/COPYING.MinGW-w64-runtime/COPYING.MinGW-w64-runtime.txt | `e9b2dc02451ea29092a1f25fa0f3c07207ed421f1807dffb0c4e6dce69dee7bd` | + +When a DLL is updated to another version, its texts here are replaced by those of the new version's source tree, and +their SHA-256 in the workflow with them. diff --git a/ref/licenses/flac-COPYING.Xiph.txt b/ref/licenses/flac-COPYING.Xiph.txt new file mode 100644 index 000000000..edd24f719 --- /dev/null +++ b/ref/licenses/flac-COPYING.Xiph.txt @@ -0,0 +1,29 @@ +Copyright (C) 2000-2009 Josh Coalson +Copyright (C) 2011-2022 Xiph.Org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.Org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/lame-COPYING.txt b/ref/licenses/lame-COPYING.txt new file mode 100644 index 000000000..f5030495b --- /dev/null +++ b/ref/licenses/lame-COPYING.txt @@ -0,0 +1,481 @@ + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if +you distribute copies of the library, or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link a program with the library, you must provide +complete object files to the recipients so that they can relink them +with the library, after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +General Public License (also called "this License"). Each licensee is +addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also compile or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + c) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + d) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the source code distributed need not include anything that is normally +distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Library General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/ref/licenses/libogg-COPYING.txt b/ref/licenses/libogg-COPYING.txt new file mode 100644 index 000000000..6111c6c5a --- /dev/null +++ b/ref/licenses/libogg-COPYING.txt @@ -0,0 +1,28 @@ +Copyright (c) 2002, Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/libsndfile-ALAC-LICENSE.txt b/ref/licenses/libsndfile-ALAC-LICENSE.txt new file mode 100644 index 000000000..7d8595490 --- /dev/null +++ b/ref/licenses/libsndfile-ALAC-LICENSE.txt @@ -0,0 +1,170 @@ +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the +copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other +entities that control, are controlled by, or are under common control +with that entity. For the purposes of this definition, "control" means +(i) the power, direct or indirect, to cause the direction or management +of such entity, whether by contract or otherwise, or (ii) ownership +of fifty percent (50%) or more of the outstanding shares, or (iii) +beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, +including but not limited to software source code, documentation source, +and configuration files. + +"Object" form shall mean any form resulting from mechanical +transformation or translation of a Source form, including but not +limited to compiled object code, generated documentation, and +conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object +form, made available under the License, as indicated by a copyright +notice that is included in or attached to the work (an example is +provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object +form, that is based on (or derived from) the Work and for which the +editorial revisions, annotations, elaborations, or other modifications +represent, as a whole, an original work of authorship. For the purposes +of this License, Derivative Works shall not include works that remain +separable from, or merely link (or bind by name) to the interfaces of, +the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original +version of the Work and any modifications or additions to that Work or +Derivative Works thereof, that is intentionally submitted to Licensor +for inclusion in the Work by the copyright owner or by an individual +or Legal Entity authorized to submit on behalf of the copyright owner. +For the purposes of this definition, "submitted" means any form of +electronic, verbal, or written communication sent to the Licensor +or its representatives, including but not limited to communication +on electronic mailing lists, source code control systems, and issue +tracking systems that are managed by, or on behalf of, the Licensor +for the purpose of discussing and improving the Work, but excluding +communication that is conspicuously marked or otherwise designated in +writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity +on behalf of whom a Contribution has been received by Licensor and +subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions +of this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable +copyright license to reproduce, prepare Derivative Works of, publicly +display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of +this License, each Contributor hereby grants to You a perpetual, +worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except +as stated in this section) patent license to make, have made, use, +offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such +Contributor that are necessarily infringed by their Contribution(s) +alone or by combination of their Contribution(s) with the Work to which +such Contribution(s) was submitted. If You institute patent litigation +against any entity (including a cross-claim or counterclaim in a +lawsuit) alleging that the Work or a Contribution incorporated within +the Work constitutes direct or contributory patent infringement, then +any patent licenses granted to You under this License for that Work +shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the +Work or Derivative Works thereof in any medium, with or without +modifications, and in Source or Object form, provided that You meet the +following conditions: + +You must give any other recipients of the Work or Derivative Works a +copy of this License; and + +You must cause any modified files to carry prominent notices stating +that You changed the files; and + +You must retain, in the Source form of any Derivative Works that You +distribute, all copyright, patent, trademark, and attribution notices +from the Source form of the Work, excluding those notices that do not +pertain to any part of the Derivative Works; and + +If the Work includes a "NOTICE" text file as part of its distribution, +then any Derivative Works that You distribute must include a readable +copy of the attribution notices contained within such NOTICE file, +excluding those notices that do not pertain to any part of the +Derivative Works, in at least one of the following places: within a +NOTICE text file distributed as part of the Derivative Works; within +the Source form or documentation, if provided along with the Derivative +Works; or, within a display generated by the Derivative Works, if and +wherever such third-party notices normally appear. The contents of the +NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative +Works that You distribute, alongside or as an addendum to the NOTICE +text from the Work, provided that such additional attribution notices +cannot be construed as modifying the License. You may add Your own +copyright statement to Your modifications and may provide additional +or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as +a whole, provided Your use, reproduction, and distribution of the Work +otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, +any Contribution intentionally submitted for inclusion in the Work by +You to the Licensor shall be under the terms and conditions of this +License, without any additional terms or conditions. Notwithstanding +the above, nothing herein shall supersede or modify the terms of any +separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. This License does not grant permission to use the trade +names, trademarks, service marks, or product names of the Licensor, +except as required for reasonable and customary use in describing the +origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed +to in writing, Licensor provides the Work (and each Contributor +provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied, including, without +limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, +MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your +exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, +whether in tort (including negligence), contract, or otherwise, unless +required by applicable law (such as deliberate and grossly negligent +acts) or agreed to in writing, shall any Contributor be liable to You +for damages, including any direct, indirect, special, incidental, or +consequential damages of any character arising as a result of this +License or out of the use or inability to use the Work (including but +not limited to damages for loss of goodwill, work stoppage, computer +failure or malfunction, or any and all other commercial damages or +losses), even if such Contributor has been advised of the possibility of +such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the +Work or Derivative Works thereof, You may choose to offer, and charge a +fee for, acceptance of support, warranty, indemnity, or other liability +obligations and/or rights consistent with this License. However, in +accepting such obligations, You may act only on Your own behalf and +on Your sole responsibility, not on behalf of any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor +harmless for any liability incurred by, or claims asserted against, such +Contributor by reason of your accepting any such warranty or additional +liability. diff --git a/ref/licenses/libsndfile-COPYING.txt b/ref/licenses/libsndfile-COPYING.txt new file mode 100644 index 000000000..c396169ee --- /dev/null +++ b/ref/licenses/libsndfile-COPYING.txt @@ -0,0 +1,503 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + diff --git a/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt b/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt new file mode 100644 index 000000000..eba0e523b --- /dev/null +++ b/ref/licenses/libsndfile-GSM610-COPYRIGHT.txt @@ -0,0 +1,16 @@ +Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann, +Technische Universitaet Berlin + +Any use of this software is permitted provided that this notice is not +removed and that neither the authors nor the Technische Universitaet Berlin +are deemed to have made any representations as to the suitability of this +software for any purpose nor are held responsible for any defects of +this software. THERE IS ABSOLUTELY NO WARRANTY FOR THIS SOFTWARE. + +As a matter of courtesy, the authors request to be informed about uses +this software has found, about bugs in this software, and about any +improvements that may be of general interest. + +Berlin, 28.11.1994 +Jutta Degener +Carsten Bormann diff --git a/ref/licenses/libvorbis-COPYING.txt b/ref/licenses/libvorbis-COPYING.txt new file mode 100644 index 000000000..fb456a87b --- /dev/null +++ b/ref/licenses/libvorbis-COPYING.txt @@ -0,0 +1,28 @@ +Copyright (c) 2002-2020 Xiph.org Foundation + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of the Xiph.org Foundation nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/mpg123-COPYING.txt b/ref/licenses/mpg123-COPYING.txt new file mode 100644 index 000000000..14e14f01c --- /dev/null +++ b/ref/licenses/mpg123-COPYING.txt @@ -0,0 +1,772 @@ +This is the file that contains the terms of use, copying, etc. for the mpg123 distribution package. + +Main message, to include in "About ..." boxes, etc: + + Copyright (c) 1995-2020 by Michael Hipp and others, + free software under the terms of the LGPL v2.1 + +There is an attempt to cover the actual list of authors in the AUTHORS file. +Project maintainer since 2006 is Thomas Orgis and many people have contributed +since the Michael Hipp era, but he stays the initial source and it would +be impractical to count them all individually, so it's "and others". +Source files contain the phrase "the mpg123 project" to the same effect +in their license boilerplate; especially those that were added after +maintainership changed. The person mainly responsible for the first version +is usually named in the phrase "initially written by ...". + +All files in the distribution that don't carry a license note on their own are +licensed under the terms of the LGPL 2.1; exceptions may apply, especially to +files not in the official distribution but in the revision control repository. + +The formal license text follows. + +======================= +1. The LGPL version 2.1 +======================= + + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + +==================== +2. The GPL version 2 +==================== + + + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/ref/licenses/openal-soft-BSD-3Clause.txt b/ref/licenses/openal-soft-BSD-3Clause.txt new file mode 100644 index 000000000..b1c2dbd76 --- /dev/null +++ b/ref/licenses/openal-soft-BSD-3Clause.txt @@ -0,0 +1,31 @@ +Portions of this software are licensed under the BSD 3-Clause license. + +Copyright (c) 2015, Archontis Politis +Copyright (c) 2019, Anis A. Hireche +Copyright (c) 2019, Christopher Robinson +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Spherical-Harmonic-Transform nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/ref/licenses/openal-soft-gsl-LICENSE.txt b/ref/licenses/openal-soft-gsl-LICENSE.txt new file mode 100644 index 000000000..aa58667a3 --- /dev/null +++ b/ref/licenses/openal-soft-gsl-LICENSE.txt @@ -0,0 +1,21 @@ +Copyright (c) 2015 Microsoft Corporation. All rights reserved. + +This code is licensed under the MIT License (MIT). + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/ref/licenses/openal-soft-mingw-w64-runtime.txt b/ref/licenses/openal-soft-mingw-w64-runtime.txt new file mode 100644 index 000000000..ca6a077e2 --- /dev/null +++ b/ref/licenses/openal-soft-mingw-w64-runtime.txt @@ -0,0 +1,240 @@ +MinGW-w64 runtime licensing +*************************** + +This program or library was built using MinGW-w64 and statically +linked against the MinGW-w64 runtime. Some parts of the runtime +are under licenses which require that the copyright and license +notices are included when distributing the code in binary form. +These notices are listed below. + + +======================== +Overall copyright notice +======================== + +Copyright (c) 2009, 2010, 2011, 2012, 2013 by the mingw-w64 project + +This license has been certified as open source. It has also been designated +as GPL compatible by the Free Software Foundation (FSF). + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions in source code must retain the accompanying copyright + notice, this list of conditions, and the following disclaimer. + 2. Redistributions in binary form must reproduce the accompanying + copyright notice, this list of conditions, and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + 3. Names of the copyright holders must not be used to endorse or promote + products derived from this software without prior written permission + from the copyright holders. + 4. The right to distribute this software or to use it for any purpose does + not give you the right to use Servicemarks (sm) or Trademarks (tm) of + the copyright holders. Use of them is covered by separate agreement + with the copyright holders. + 5. If any files are modified, you must cause the modified files to carry + prominent notices stating that you changed the files and the date of + any change. + +Disclaimer + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED +OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +======================================== +getopt, getopt_long, and getop_long_only +======================================== + +Copyright (c) 2002 Todd C. Miller + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +Sponsored in part by the Defense Advanced Research Projects +Agency (DARPA) and Air Force Research Laboratory, Air Force +Materiel Command, USAF, under agreement number F39502-99-1-0512. + + * * * * * * * + +Copyright (c) 2000 The NetBSD Foundation, Inc. +All rights reserved. + +This code is derived from software contributed to The NetBSD Foundation +by Dieter Baron and Thomas Klausner. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + + +=============================================================== +gdtoa: Converting between IEEE floating point numbers and ASCII +=============================================================== + +The author of this software is David M. Gay. + +Copyright (C) 1997, 1998, 1999, 2000, 2001 by Lucent Technologies +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + * * * * * * * + +The author of this software is David M. Gay. + +Copyright (C) 2005 by David M. Gay +All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that the copyright notice and this permission notice and warranty +disclaimer appear in supporting documentation, and that the name of +the author or any of his current or former employers not be used in +advertising or publicity pertaining to distribution of the software +without specific, written prior permission. + +THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN +NO EVENT SHALL THE AUTHOR OR ANY OF HIS CURRENT OR FORMER EMPLOYERS BE +LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY +DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + + * * * * * * * + +The author of this software is David M. Gay. + +Copyright (C) 2004 by David M. Gay. +All Rights Reserved +Based on material in the rest of /netlib/fp/gdota.tar.gz, +which is copyright (C) 1998, 2000 by Lucent Technologies. + +Permission to use, copy, modify, and distribute this software and +its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that the copyright notice and this +permission notice and warranty disclaimer appear in supporting +documentation, and that the name of Lucent or any of its entities +not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +LUCENT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, +INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. +IN NO EVENT SHALL LUCENT OR ANY OF ITS ENTITIES BE LIABLE FOR ANY +SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. + + +========================= +Parts of the math library +========================= + +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunSoft, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + * * * * * * * + +Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + +Developed at SunPro, a Sun Microsystems, Inc. business. +Permission to use, copy, modify, and distribute this +software is freely granted, provided that this notice +is preserved. + + * * * * * * * + +FIXME: Cephes math lib +Copyright (C) 1984-1998 Stephen L. Moshier + +It sounds vague, but as to be found at +, it gives an +impression that the author could be willing to give an explicit +permission to distribute those files e.g. under a BSD style license. So +probably there is no problem here, although it could be good to get a +permission from the author and then add a license into the Cephes files +in MinGW runtime. At least on follow-up it is marked that debian sees the +version a-like BSD one. As MinGW.org (where those cephes parts are coming +from) distributes them now over 6 years, it should be fine. + +=================================== +Headers and IDLs imported from Wine +=================================== + +Some header and IDL files were imported from the Wine project. These files +are prominent maked in source. Their copyright belongs to contributors and +they are distributed under LGPL license. + +Disclaimer + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. diff --git a/ref/licenses/openal-soft-pffft-LICENSE.txt b/ref/licenses/openal-soft-pffft-LICENSE.txt new file mode 100644 index 000000000..5f1a8493f --- /dev/null +++ b/ref/licenses/openal-soft-pffft-LICENSE.txt @@ -0,0 +1,38 @@ +A modified PFFFT is included, with the following license. + +Copyright (c) 2023 Christopher Robinson + +Copyright (c) 2013 Julien Pommier ( pommier@modartt.com ) + +Copyright (c) 2004 the University Corporation for Atmospheric +Research ("UCAR"). All rights reserved. Developed by NCAR's +Computational and Information Systems Laboratory, UCAR, +www.cisl.ucar.edu. + +Redistribution and use of the Software in source and binary forms, +with or without modification, is permitted provided that the +following conditions are met: + +- Neither the names of NCAR's Computational and Information Systems +Laboratory, the University Corporation for Atmospheric Research, +nor the names of its sponsors or contributors may be used to +endorse or promote products derived from this Software without +specific prior written permission. + +- Redistributions of source code must retain the above copyright +notices, this list of conditions, and the disclaimer below. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions, and the disclaimer below in the +documentation and/or other materials provided with the +distribution. + +THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE +SOFTWARE. diff --git a/ref/licenses/openal-soft-winpthreads-COPYING.txt b/ref/licenses/openal-soft-winpthreads-COPYING.txt new file mode 100644 index 000000000..350770123 --- /dev/null +++ b/ref/licenses/openal-soft-winpthreads-COPYING.txt @@ -0,0 +1,57 @@ +Copyright (c) 2011 mingw-w64 project + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +/* + * Parts of this library are derived by: + * + * Posix Threads library for Microsoft Windows + * + * Use at own risk, there is no implied warranty to this code. + * It uses undocumented features of Microsoft Windows that can change + * at any time in the future. + * + * (C) 2010 Lockless Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of Lockless Inc. nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AN + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ diff --git a/ref/licenses/opus-COPYING.txt b/ref/licenses/opus-COPYING.txt new file mode 100644 index 000000000..9c739c34a --- /dev/null +++ b/ref/licenses/opus-COPYING.txt @@ -0,0 +1,44 @@ +Copyright 2001-2011 Xiph.Org, Skype Limited, Octasic, + Jean-Marc Valin, Timothy B. Terriberry, + CSIRO, Gregory Maxwell, Mark Borgerding, + Erik de Castro Lopo + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +- Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + +- Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +- Neither the name of Internet Society, IETF or IETF Trust, nor the +names of specific contributors, may be used to endorse or promote +products derived from this software without specific prior written +permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Opus is subject to the royalty-free patent licenses which are +specified at: + +Xiph.Org Foundation: +https://datatracker.ietf.org/ipr/1524/ + +Microsoft Corporation: +https://datatracker.ietf.org/ipr/1914/ + +Broadcom Corporation: +https://datatracker.ietf.org/ipr/1526/ diff --git a/rendering/common/cabprobe.h b/rendering/common/cabprobe.h index 88eed383f..f066f4687 100644 --- a/rendering/common/cabprobe.h +++ b/rendering/common/cabprobe.h @@ -23,7 +23,7 @@ class TModel3d; namespace gfx { -// the probe of the occupied cab (Global.gfx_cabprobe, the stage A4 of claude/renderers-plan.md), the part shared by the renderers; +// the probe of the occupied cab (Global.gfx_cabprobe), the part shared by the renderers; // the backend (opengl46_cab_probe, vk14::cab_probe_maps) keeps the maps and draws to them through the gpu_* methods. // - two cube maps drawn from the middle of the box of the cab model (mdKabina), in the space of the model, so they stay right while // the vehicle moves and turns: the light of the lights of the cab (the lamp, the light points of the cab model, the brightest diff --git a/rendering/common/exposure.h b/rendering/common/exposure.h index 7b3eabb59..53522ef3b 100644 --- a/rendering/common/exposure.h +++ b/rendering/common/exposure.h @@ -7,9 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// what the automatic exposure and the bloom of the renderers share (the part of the stage S3 of -// claude/gl46-renderer-features-plan.md which isn't the work of the gpu, taken out of opengl46_exposure for the vulkan renderer, -// stage P1 of claude/vulkan14-renderer-plan.md): the parameters of the histogram and of the adaptation +// what the automatic exposure and the bloom of the renderers share (the part which isn't the work of the gpu, taken out of +// opengl46_exposure for the vulkan renderer): the parameters of the histogram and of the adaptation // (exposure_histogram.comp, exposure_average.comp), the sizes of the levels of the bloom chain and the parameters of its steps // (postfx_bloom_*.frag), the parameters of the tonemapping and the controls of the debug window diff --git a/rendering/common/instancecull.h b/rendering/common/instancecull.h index 2533abea5..1661bf933 100644 --- a/rendering/common/instancecull.h +++ b/rendering/common/instancecull.h @@ -25,8 +25,8 @@ class TAnimModel; namespace gfx { -// the cpu side of the culling of the model instances of a render pass in compute passes, shared by the renderers (stage N6c of -// claude/vulkan14-renderer-plan.md); the backend (opengl46_instance_cull, vk14 instance_cull) keeps the buffers and runs the passes: +// the cpu side of the culling of the model instances of a render pass in compute passes, shared by the renderers; +// the backend (opengl46_instance_cull, vk14 instance_cull) keeps the buffers and runs the passes: // - the records of the instances (scene::basic_cell::instance_record) are kept in one buffer, each bucket of a scene cell // in its own place, and sent again only when the bucket made them anew // - every bucket queued in the pass becomes a job; the buckets of one model and one set of skins make a group, whose @@ -119,6 +119,11 @@ class instance_cull { return m_twophase; } + // the culling of the pass was dispatched: there are results of it to draw from + bool dispatched() const + { + return m_dispatched; + } // groups of the pass and the lod bounds they refer to, valid from the dispatch to end_pass() std::vector const &draw_groups() const { diff --git a/rendering/common/locallights.cpp b/rendering/common/locallights.cpp index 24ad17f85..07f8fc5fb 100644 --- a/rendering/common/locallights.cpp +++ b/rendering/common/locallights.cpp @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/common/locallights.h" +#include "rendering/common/moths.h" #include #include @@ -194,9 +195,15 @@ void gfx::local_lights::gather(glm::dvec3 const &Camera, scene::basic_region &Re m_scenerycount = m_vehiclecount = m_compartmentcount = 0; m_walkgeometry = &Geometry; - // the editor adds, moves and removes instances in the cells. it can also do it in the frame it is turned off in + // the editor adds, moves and removes instances in the cells. it can also do it in the frame it is turned off in. the cells not + // visited in such a frame (in the daylight, or out of range) are made anew too when they are visited next: an instance replaced in + // the place of another leaves the size and the address of the list of the cell as they were auto const rebuild{EditorModeFlag || m_editorseen}; m_editorseen = EditorModeFlag; + if (rebuild) + { + m_cells.clear(); + } if (Global.gfx_lights_clustered) { @@ -265,6 +272,9 @@ void gfx::local_lights::gather(glm::dvec3 const &Camera, scene::basic_region &Re }); } + // the moths fly about the lamps of the scenery which shine + Moths.update(m_lights, Camera, Framestamp); + auto const elapsed{std::chrono::duration(std::chrono::steady_clock::now() - start).count()}; m_gathertime = (m_gathertime == 0.0 ? elapsed : m_gathertime * 0.95 + elapsed * 0.05); } @@ -308,6 +318,12 @@ void gfx::local_lights::reset() m_sections.clear(); m_models.clear(); m_scenerycount = m_vehiclecount = m_compartmentcount = m_placed = m_dropped = 0; + Moths.reset(); +} + +void gfx::local_lights::forget(scene::basic_node const *) +{ + m_cells.clear(); } void gfx::local_lights::gather_instance(TAnimModel *Instance, glm::dvec3 const &Camera, float const Brightness, unsigned int const Framestamp) @@ -396,7 +412,7 @@ void gfx::local_lights::gather_vehicle(TDynamicObject *Vehicle, glm::dvec3 const { auto const &name{section.compartment->pName}; cabsection &= (name.size() >= 4) && name.starts_with("cab"); - auto const level{section.light_level * (cabsection ? 1.f : Vehicle->MoverParameters->CompartmentLights.intensity)}; + auto const level{section.light_level * (cabsection ? 1.f : Vehicle->CompartmentLightIntensity())}; if ((level <= 0.f) || (Global.fLuminance > section.compartment->fLight) || (section.compartment->iVisible == 0)) { continue; @@ -760,7 +776,7 @@ std::string gfx::local_lights::info() const { return "local lights: " + std::to_string(m_lights.size()) + " (scenery " + std::to_string(m_scenerycount) + ", vehicles " + std::to_string(m_vehiclecount) + ", compartments " + std::to_string(m_compartmentcount) + ")" + (m_cablampon ? " + cab lights " + std::to_string(m_cablights.size()) : "") + ", placed " + std::to_string(m_placed) + ", over capacity " + std::to_string(m_dropped) + - ", gather " + to_string(m_gathertime, 2) + " ms"; + ", gather " + to_string(m_gathertime, 2) + " ms, moth swarms " + std::to_string(Moths.shown()) + "/" + std::to_string(Moths.count()); } void gfx::local_lights::draw_debug_ui() @@ -774,6 +790,10 @@ void gfx::local_lights::draw_debug_ui() ImGui::SliderFloat("cab lamp brightness", &Global.gfx_lights_cab_intensity, 0.f, 10.f); ImGui::SliderFloat("cab ambient kept", &Global.gfx_lights_cab_bounce, 0.f, 1.f); ImGui::SliderFloat("range, m", &Global.gfx_lights_range, 0.f, 1000.f); + ImGui::Checkbox("moths at the lamps of the scenery", &Global.moths); + ImGui::SliderFloat("moths: part of the lamps", &Global.moths_share, 0.f, 1.f); + ImGui::SliderFloat("moths: range, m", &Global.moths_range, 0.f, 300.f); + ImGui::Text("moth swarms shown %u, made %u", static_cast(Moths.shown()), static_cast(Moths.count())); ImGui::Text("gathered %u: scenery %u, vehicles %u, compartments %u, cab %u", static_cast(m_lights.size()), m_scenerycount, m_vehiclecount, m_compartmentcount, static_cast(m_cablights.size())); ImGui::Text("in the light buffer %u, over capacity %u", m_placed, m_dropped); diff --git a/rendering/common/locallights.h b/rendering/common/locallights.h index 140122836..9fa109a90 100644 --- a/rendering/common/locallights.h +++ b/rendering/common/locallights.h @@ -19,6 +19,7 @@ namespace scene { class basic_region; class basic_cell; +class basic_node; } // namespace scene namespace gfx { @@ -78,6 +79,9 @@ class local_lights void gather(glm::dvec3 const &Camera, scene::basic_region &Region, gfx::geometrybank_manager const &Geometry, unsigned int const Framestamp); // forgets the lights and everything kept about the scene, which is about to be replaced (a scenery being loaded) void reset(); + // a node of the scene is about to go: the lists of the lit instances of the cells, which may hold it, are made anew when the + // cells are visited next + void forget(scene::basic_node const *Node); // the flashlight of the player, when it's on (Global.flashlight), added by gather() void add_flashlight(); // the lights of models and vehicles, the most important (closest and brightest) first diff --git a/rendering/common/localshadows.cpp b/rendering/common/localshadows.cpp index 87fc056f8..867473ed1 100644 --- a/rendering/common/localshadows.cpp +++ b/rendering/common/localshadows.cpp @@ -583,7 +583,7 @@ std::vector const &local_shadows::pick_headli if (std::max(beam.r, std::max(beam.g, beam.b)) <= 0.f) continue; // the part of the beam the shadows are cast in: from the end of the vehicle to the reach ahead of it - auto const &dimensions{light.owner->MoverParameters->Dim}; + auto const &dimensions{light.owner->Dimensions()}; auto const radius{range * 0.5 + std::max(dimensions.W, dimensions.H) + 2.0}; auto const centre{light.position + glm::dvec3{light.direction} * (range * 0.5 + 2.0)}; if (glm::length(centre - camera) - radius > range) diff --git a/rendering/common/localshadows.h b/rendering/common/localshadows.h index bc50f1da2..b04f4501a 100644 --- a/rendering/common/localshadows.h +++ b/rendering/common/localshadows.h @@ -25,8 +25,8 @@ class opengl_camera; namespace gfx { -// the shadow maps of the lamps (Global.gfx_lights_shadows), the part shared by the renderers (stage P4 of -// claude/vulkan14-renderer-plan.md): which lamps and headlights get maps, when they are drawn, what the shading reads; the +// the shadow maps of the lamps (Global.gfx_lights_shadows), the part shared by the renderers: +// which lamps and headlights get maps, when they are drawn, what the shading reads; the // backend (opengl46_local_shadows, the vulkan renderer) keeps the maps and draws to them through the gpu_* methods. // - the lights of the occupied cab (gfx::local_lights::cab_lights(): its lamps, the lights of its desk), the brightest // Global.gfx_lights_shadows_cab of them, with the shadows cast by the cab (the model drawn by Render_cab()). the map of a light is diff --git a/rendering/common/moths.cpp b/rendering/common/moths.cpp new file mode 100644 index 000000000..a4a58208d --- /dev/null +++ b/rendering/common/moths.cpp @@ -0,0 +1,143 @@ +/* +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 "rendering/common/moths.h" +#include +#include +#include +#include "utilities/Globals.h" +#include "model/AnimModel.h" +#include "scene/scenenode.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" + +namespace +{ + +// the model of a swarm, models/ and the extension left out +char const *const Swarmmodel{"animals/cmy"}; + +// a number 0-1 for the place, the same every time for the same place (whole half metres) +double place_number(glm::dvec3 const &Position) +{ + auto const x{static_cast(std::floor(Position.x * 2.0))}; + auto const y{static_cast(std::floor(Position.y * 2.0))}; + auto const z{static_cast(std::floor(Position.z * 2.0))}; + auto hash{static_cast(x) * 0x9E3779B97F4A7C15ull ^ static_cast(y) * 0xC2B2AE3D27D4EB4Full ^ static_cast(z) * 0x165667B19E3779F9ull}; + hash ^= hash >> 33; + hash *= 0xff51afd7ed558ccdull; + hash ^= hash >> 33; + hash *= 0xc4ceb9fe1a85ec53ull; + hash ^= hash >> 33; + return static_cast(hash >> 11) / static_cast(1ull << 53); +} + +// moths fly in the warm part of the year +bool moths_fly() +{ + return Global.moths && (Global.Season != "winter:") && (Global.AirTemperature >= Global.moths_temperature); +} + +} // namespace + +gfx::moths gfx::Moths; + +void gfx::moths::update(std::vector const &Lights, glm::dvec3 const &Camera, unsigned int const Framestamp) +{ + auto const flying{moths_fly() && (Global.moths_share > 0.f) && (Global.moths_range > 0.f)}; + if (flying) + { + auto const range{static_cast(Global.moths_range)}; + for (auto const &light : Lights) + { + // the lamps of the scenery models, shining downwards (street and platform lamps; not the signals) + if ((light.owner == nullptr) || (light.part == nullptr) || (light.direction.y > -0.5f)) + { + continue; + } + auto const key{std::make_pair(light.owner, light.part)}; + auto lookup{m_lamps.find(key)}; + if ((lookup != m_lamps.end()) && (glm::length(lookup->second.position - light.position) > 0.5)) + { + // another lamp in the place of the one met before (the editor took it away and put a new one) + if (lookup->second.model != nullptr) + { + lookup->second.model->visible(false); + } + lookup = m_lamps.end(); + m_lamps.erase(key); + } + if (lookup == m_lamps.end()) + { + if (glm::length(light.position - Camera) > range) + { + // decided when the lamp comes closer + continue; + } + swarm entry; + entry.position = light.position; + auto chosen{place_number(light.position) < static_cast(Global.moths_share)}; + for (auto const &place : m_places) + { + if (glm::length(place - light.position) < 1.0) + { + // the other light point of the same lamp has a swarm already + chosen = false; + break; + } + } + if (chosen) + { + auto const definition{"node " + std::to_string(static_cast(std::ceil(range))) + " 0 none model 0 0 0 0 " + std::string{Swarmmodel} + ".t3d none endmodel"}; + auto *model{simulation::State.create_model(definition, "none", light.position)}; + if (model != nullptr) + { + // not a part of the scenery: no layer of it, not saved, not edited + scene::Layers.count(model->layer(), scene::layer_item::model, -1); + model->layer(null_handle); + model->m_dirty = false; + model->m_generated = true; + model->visible(false); + ++scene::node_state_version; + entry.model = model; + m_places.emplace_back(light.position); + ++m_count; + } + } + lookup = m_lamps.emplace(key, entry).first; + } + lookup->second.seen = Framestamp; + } + } + // the swarms of the lamps lit in this frame are shown. a swarm shown before stays so while its lamp is out of the lights of the + // frame by its distance (the range of the swarm, as of its node, hides it there): it changes, and the version of the state of + // the nodes with it, only when its lamp goes out, not each time the camera passes the range of the lights + auto const keepbeyond{static_cast(Global.moths_range) * 0.9}; + m_shown = 0; + for (auto &lamp : m_lamps) + { + auto &entry{lamp.second}; + if (entry.model == nullptr) + { + continue; + } + auto const shown{flying && ((entry.seen == Framestamp) || (entry.model->visible() && (glm::length(entry.position - Camera) > keepbeyond)))}; + entry.model->visible(shown); + m_shown += (shown ? 1 : 0); + } +} + +void gfx::moths::reset() +{ + // the instances go with the scenery + m_lamps.clear(); + m_places.clear(); + m_count = m_shown = 0; +} diff --git a/rendering/common/moths.h b/rendering/common/moths.h new file mode 100644 index 000000000..ca2e71643 --- /dev/null +++ b/rendering/common/moths.h @@ -0,0 +1,63 @@ +/* +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 + +#include +#include +#include +#include "rendering/common/locallights.h" + +class TAnimModel; + +// moths flying about the lit lamps of the scenery. a part of the lamps of the scenery models which shine downwards (Global.moths_share, +// picked by the places of the lamps, so always the same ones) gets a swarm: an instance of the model animals/cmy (animated by textures, +// shader vat: the swarms differ in the moment and the clip of the animation by their places) put in the scenery at the light point. +// the swarm is shown while its lamp shines (the light points the local lights gathered in the frame), in the warm part of the year +// (not in the winter, the air not colder than Global.moths_temperature), to Global.moths_range from the camera. the swarms are made +// when their lamps first come within the range, aren't parts of the scenery (not saved, not edited) and go with it +namespace gfx +{ + +class moths +{ + public: + // after the lights of the frame were gathered: makes the swarms of the lamps which came within the range, shows the swarms of the + // lit lamps and hides the others + void update(std::vector const &Lights, glm::dvec3 const &Camera, unsigned int const Framestamp); + // forgets the swarms: the scenery they were put in is about to be replaced + void reset(); + // swarms made, and shown in the last frame + std::size_t count() const + { + return m_count; + } + std::size_t shown() const + { + return m_shown; + } + + private: + struct swarm + { + glm::dvec3 position{0.0}; // of the light point the swarm was decided for + TAnimModel *model{nullptr}; // nullptr: the lamp has no swarm + unsigned int seen{0}; // the frame the lamp shone last in + }; + // the lamps met: the instance and the submodel of the light point + std::map, swarm> m_lamps; + std::vector m_places; // of the swarms made, so two light points of one lamp don't both get one + std::size_t m_count{0}; + std::size_t m_shown{0}; +}; + +// the swarms of the scenery, kept by the local lights (local_lights::gather(), reset()) +extern moths Moths; + +} // namespace gfx diff --git a/rendering/common/scenewalk.cpp b/rendering/common/scenewalk.cpp index 2e27b081f..ad0dafae0 100644 --- a/rendering/common/scenewalk.cpp +++ b/rendering/common/scenewalk.cpp @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the walk of the scene shared by the renderers (stage N6 of claude/vulkan14-renderer-plan.md): what is drawn in a pass, in +// the walk of the scene shared by the renderers: what is drawn in a pass, in // which order, with which material and transform. the backends get the draws through the walk_* methods, the opengl renderer // makes them at once, the vulkan renderer records them. moved out of opengl46renderer.cpp without changes to what it does @@ -185,16 +185,16 @@ bool scene_walk::Render_interior( bool const Alpha ) { glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.pass_camera.position() }; float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) }; dynamics.emplace_back( squaredistance, dynamic ); - dynamic = dynamic->Next( coupling::permanent ); + dynamic = dynamic->Next( Coupling::permanent ); } // draw also interiors of permanently coupled vehicles in front, if there's any - dynamic = simulation::Train->Dynamic()->Prev( coupling::permanent ); + dynamic = simulation::Train->Dynamic()->Prev( Coupling::permanent ); while( dynamic != nullptr ) { glm::dvec3 const originoffset { dynamic->vPosition - m_renderpass.pass_camera.position() }; float const squaredistance{ glm::length2( glm::vec3{ originoffset } / Global.ZoomFactor ) }; dynamics.emplace_back( squaredistance, dynamic ); - dynamic = dynamic->Prev( coupling::permanent ); + dynamic = dynamic->Prev( Coupling::permanent ); } if( Alpha ) { std::sort( @@ -287,19 +287,19 @@ bool scene_walk::Render_lowpoly( TDynamicObject *Dynamic, float const Squaredist return true; } -bool scene_walk::Render_coupler_adapter( TDynamicObject *Dynamic, float const Squaredistance, int const End, bool const Alpha ) { +bool scene_walk::Render_coupler_adapter( TDynamicObject *Dynamic, float const Squaredistance, VehicleEnd const End, bool const Alpha ) { if( Dynamic->m_coupleradapters[ End ] == nullptr ) { return false; } gfx::walk_sync::vehicle_hold hold; auto const position { glm::dvec3 { 0.f, - Dynamic->MoverParameters->Couplers[ End ].adapter_height, - ( Dynamic->MoverParameters->Couplers[ End ].adapter_length + Dynamic->MoverParameters->Dim.L * 0.5 ) * ( End == end::front ? 1 : -1 ) } }; + Dynamic->CouplerAdapterHeight( End ), + ( Dynamic->CouplerAdapterLength( End ) + Dynamic->Dimensions().L * 0.5 ) * ( End == VehicleEnd::front ? 1 : -1 ) } }; auto const angle { glm::vec3{ 0, - ( End == end::front ? 0 : 180 ), + ( End == VehicleEnd::front ? 0 : 180 ), 0 } }; if( Alpha ) { @@ -1930,8 +1930,8 @@ bool scene_walk::Render(TDynamicObject *Dynamic) Render( attachment, Dynamic->Material(), squaredistance ); } // optional coupling adapters - Render_coupler_adapter( Dynamic, squaredistance, end::front ); - Render_coupler_adapter( Dynamic, squaredistance, end::rear ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::front ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::rear ); // post-render cleanup if (gfx::vehicle_shade(Dynamic) > 0.0f) @@ -1956,8 +1956,8 @@ bool scene_walk::Render(TDynamicObject *Dynamic) Render( attachment, Dynamic->Material(), squaredistance ); } // optional coupling adapters - Render_coupler_adapter( Dynamic, squaredistance, end::front ); - Render_coupler_adapter( Dynamic, squaredistance, end::rear ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::front ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::rear ); if( Dynamic->mdLoad ) { // renderowanie nieprzezroczystego ładunku Render( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} ); @@ -2138,6 +2138,37 @@ bool scene_walk::Render(TModel3d *Model, material_data const *Material, float co return result; } +// opaque characters of a text display, laid out in a row the same way as the translucent ones +void scene_walk::Render_text(TSubModel *Submodel) +{ + if (TSubModel::pasText == nullptr) + { + return; + } + ::glPushMatrix(); + for (auto *p : Submodel->text_letters(*TSubModel::pasText)) + { + Render(p); + if (p->fMatrix) + ::glMultMatrixf(p->fMatrix->readArray()); // move on to the place of the next character + } + ::glPopMatrix(); +} + +// opaque sub-models under the given one. the children of a text display are its character set, only the characters +// of the displayed text are drawn +void scene_walk::Render_children(TSubModel *Submodel) +{ + if (Submodel->eType == TP_TEXT) + { + Render_text(Submodel); + } + else + { + Render(Submodel->Child); + } +} + void scene_walk::Render(TSubModel *Submodel) { glDebug("Render TSubModel"); @@ -2298,7 +2329,7 @@ void scene_walk::Render(TSubModel *Submodel) } if (Submodel->Child != nullptr) if (Submodel->iAlpha & Submodel->iFlags & 0x001F0000) - Render(Submodel->Child); + Render_children(Submodel); if (Submodel->iFlags & 0xC000) { @@ -3098,8 +3129,8 @@ bool scene_walk::Render_Alpha(TDynamicObject *Dynamic) Render_Alpha( attachment, Dynamic->Material(), squaredistance ); } // optional coupling adapters - Render_coupler_adapter( Dynamic, squaredistance, end::front, true ); - Render_coupler_adapter( Dynamic, squaredistance, end::rear, true ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::front, true ); + Render_coupler_adapter( Dynamic, squaredistance, VehicleEnd::rear, true ); if( Dynamic->mdLoad ) { // renderowanie nieprzezroczystego ładunku Render_Alpha( Dynamic->mdLoad, Dynamic->Material(), squaredistance, { 0.f, Dynamic->LoadOffset, 0.f }, {} ); diff --git a/rendering/common/scenewalk.h b/rendering/common/scenewalk.h index 1668d74e9..0bdfa63e9 100644 --- a/rendering/common/scenewalk.h +++ b/rendering/common/scenewalk.h @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the walk of the scene shared by the renderers (stage N6 of claude/vulkan14-renderer-plan.md, decision K11): the decisions of +// the walk of the scene shared by the renderers: the decisions of // what is drawn in a pass (the sections, cells, tracks, shapes, models, instances, vehicles, the cab, the translucent parts), // in which order, with which material, transform and level of detail. a renderer derives from it and gets the draws through // the walk_* methods: the opengl renderer makes them at once (the same gl calls in the same order as before the walk was @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include "physics/vehicletypes.h" #include "rendering/geometrybank.h" #include "rendering/openglcamera.h" #include "scene/scene.h" @@ -163,6 +164,8 @@ class scene_walk bool Render(TModel3d *Model, material_data const *Material, float const Squaredistance, glm::dvec3 const &Position, glm::vec3 const &Angle); bool Render(TModel3d *Model, material_data const *Material, float const Squaredistance); void Render(TSubModel *Submodel); + void Render_children(TSubModel *Submodel); // opaque sub-models under the given one + void Render_text(TSubModel *Submodel); // opaque characters of a text display void Render(TTrack *Track); void Render(scene::basic_cell::path_sequence::const_iterator First, scene::basic_cell::path_sequence::const_iterator Last); // renders the per-track sleeper instances (TTrack::m_sleeper_local_transforms) via GPU instancing. @@ -178,7 +181,7 @@ class scene_walk bool Render_cab(TDynamicObject const *Dynamic, float const Lightlevel, bool const Alpha = false); bool Render_interior(bool const Alpha = false); bool Render_lowpoly(TDynamicObject *Dynamic, float const Squaredistance, bool const Setup, bool const Alpha = false); - bool Render_coupler_adapter(TDynamicObject *Dynamic, float const Squaredistance, int const End, bool const Alpha = false); + bool Render_coupler_adapter(TDynamicObject *Dynamic, float const Squaredistance, VehicleEnd const End, bool const Alpha = false); void Render(TMemCell *Memcell); void Render_Alpha(scene::basic_region *Region); void Render_Alpha(cell_sequence::reverse_iterator First, cell_sequence::reverse_iterator Last); @@ -297,7 +300,7 @@ class scene_walk virtual void walk_instances_end() {} // the geometry of the backend and whether it draws blended now, for the draws recorded for the gpu culling virtual gfx::geometrybank_manager &walk_geometry() = 0; - // the walks of the groups of a culling split among several threads (the stage M3 of claude/vulkan14-renderer-plan.md): whether the + // the walks of the groups of a culling split among several threads: whether the // backend does it for this many groups (by default not), and the tasks run, each by a helper given the state of this walk (its // pass, its model block and blending, its recording of the draws), which Work walks a part of the groups with; returns once all of // them are done diff --git a/rendering/common/scenewalkindirect.cpp b/rendering/common/scenewalkindirect.cpp index c526fabce..661986bec 100644 --- a/rendering/common/scenewalkindirect.cpp +++ b/rendering/common/scenewalkindirect.cpp @@ -8,7 +8,7 @@ http://mozilla.org/MPL/2.0/. */ // the part of the shared walk of the scene which feeds the gpu culling of the instances and records the draws made from its -// result (stage N6c of claude/vulkan14-renderer-plan.md): the records of the sleepers and of the models drawn on their own, the +// result: the records of the sleepers and of the models drawn on their own, the // queueing of buckets, the walks of the submodel trees of the culled groups and the order of the recorded draws #include "stdafx.h" @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "model/Model3d.h" #include "utilities/Globals.h" #include "utilities/utilities.h" +#include "vehicle/DynObj.h" #include @@ -282,10 +283,10 @@ bool scene_walk::Queue_Model(TAnimModel *Instance, bool const Inrange) auto &records{m_modelrecords[Instance]}; auto &bucket{records.bucket}; - if ((bucket.recordsversion != m_instancerecordsversion) || (bucket.records.size() != 1)) + if ((bucket.recordsversion != m_instancerecordsversion) || (bucket.records.size() != 1) || (records.area.center != Instance->location())) { // the key, the instance and the record anew: the editor may have given the instance another model or skins, or - // another instance may have taken the place of a deleted one + // another instance may have taken the place of a deleted one, or the game moved it (world/deer.cpp) auto &key{records.key}; key = {}; key.pModel = Instance->Model(); @@ -865,9 +866,11 @@ void scene_walk::Replay_Walk(walk_band const &Walk, bool const Shadows) draw.ubs = model_ubs; draw.ubs.modelview = walked.modelview; draw.ubs.modelviewnormal = walked.modelviewnormal; + // the parameters of the material go with the shadows too: a material which moves its vertices in a vertex shader of its own + // reads them there (vat_speed of mat_vat.vert, without which its shadow stands still); the common shadow programs don't + std::memcpy(&draw.ubs.param[0], &walked.param[0], sizeof(draw.ubs.param)); if (false == Shadows) { - std::memcpy(&draw.ubs.param[0], &walked.param[0], sizeof(draw.ubs.param)); draw.ubs.opacity = walked.opacity; draw.ubs.alpha_mult = walked.alpha_mult; } diff --git a/rendering/common/screenreflections.cpp b/rendering/common/screenreflections.cpp index a00ad7f05..c730d97bd 100644 --- a/rendering/common/screenreflections.cpp +++ b/rendering/common/screenreflections.cpp @@ -59,7 +59,7 @@ void gfx::screen_reflections::begin_frame(glm::mat4 const &Projection, glm::dmat { m_reprojectioncab = glm::mat4{m_history.projection * glm::dmat4{m_history.view} * m_history.cab * glm::inverse(m_current.cab) * toworld}; // the vehicle stands on the origin of its model, along z, up to its height - auto const &dimensions{Cab->MoverParameters->Dim}; + auto const &dimensions{Cab->Dimensions()}; glm::dvec3 const lower{-0.5 * dimensions.W - CAB_BOX_MARGIN, -CAB_BOX_MARGIN, -0.5 * dimensions.L - CAB_BOX_MARGIN}; glm::dvec3 const upper{0.5 * dimensions.W + CAB_BOX_MARGIN, dimensions.H + CAB_BOX_MARGIN, 0.5 * dimensions.L + CAB_BOX_MARGIN}; auto const centre{0.5 * (lower + upper)}; diff --git a/rendering/common/shadersource.cpp b/rendering/common/shadersource.cpp index 0f151b7e0..47373fc18 100644 --- a/rendering/common/shadersource.cpp +++ b/rendering/common/shadersource.cpp @@ -66,6 +66,9 @@ std::string read_file(std::string const &Path) std::unordered_map const components_mapping = { {"R", shader_components::R}, {"RG", shader_components::RG}, {"RGB", shader_components::RGB}, {"RGBA", shader_components::RGBA}, {"sRGB", shader_components::sRGB}, {"sRGB_A", shader_components::sRGB_A}}; +std::unordered_map const defaulttextures_mapping = { + {"black", shader_texture_default::black}, {"white", shader_texture_default::white}, {"red", shader_texture_default::red}, {"yellow", shader_texture_default::yellow}}; + std::unordered_map const defaultparams_mapping = { {"required", shader_param_default::required}, {"nan", shader_param_default::nan}, {"zero", shader_param_default::zero}, {"one", shader_param_default::one}, {"ambient", shader_param_default::ambient}, {"diffuse", shader_param_default::diffuse}, {"specular", shader_param_default::specular}, {"glossiness", shader_param_default::glossiness}}; @@ -138,7 +141,7 @@ void parse_texture_entries(std::string &Text, shader_source &Source) while ((start = find_directive(Text, "texture", start, arguments)) != std::string::npos) { auto const args{take_directive(Text, start, arguments)}; - if (args.size() != 3) + if ((args.size() != 3) && (args.size() != 4)) { log_error(Source.name, "invalid argument count to #pragma texture"); continue; @@ -160,6 +163,17 @@ void parse_texture_entries(std::string &Text, shader_source &Source) continue; } conf.components = components->second; + if (args.size() == 4) + { + // a texture the material may leave out + auto const fallback{defaulttextures_mapping.find(args[3])}; + if (fallback == defaulttextures_mapping.end()) + { + log_error(Source.name, "unknown texture default: " + args[3]); + continue; + } + conf.fallback = fallback->second; + } if (args[0].empty()) { log_error(Source.name, "empty name"); @@ -575,6 +589,12 @@ std::vector load_shader_binary(shader_source const &Source, std:: std::lock_guard lock(manifest_mutex); auto const &manifest{manifest_of(directory)}; auto const entry{manifest.entries.find(name)}; + if ((entry == manifest.entries.end()) && Source.has_source) + { + // nothing vouches for the binary, and the source is there to compile from + Reason = name + " isn't in the manifest of " + directory; + return {}; + } if (entry != manifest.entries.end()) { auto const sourcedir{shader_source_dir(Source.api)}; diff --git a/rendering/common/shadersource.h b/rendering/common/shadersource.h index 9387d9841..1ad572dd7 100644 --- a/rendering/common/shadersource.h +++ b/rendering/common/shadersource.h @@ -67,10 +67,23 @@ enum class shader_components : int sRGB_A = 0x8C42 }; +// what a unit shows when the material gives no texture for it, as the optional fourth argument of #pragma texture names it: a +// single texel of that colour. none: the material has to give the texture. the texels hold only 0 and 255, which read the +// same whether the unit takes them as sRGB or not +enum class shader_texture_default +{ + none, + black, + white, + red, + yellow +}; + struct shader_texture_entry { std::size_t id; shader_components components; + shader_texture_default fallback{shader_texture_default::none}; }; enum class shader_param_default @@ -157,8 +170,8 @@ shader_source preprocess_shader(shader_api Api, std::string const &Name, std::st std::string const &Basedir = {}); // the SPIR-V binary of a shader from the directory of the binaries of its api. empty when there's none, when the manifest of the -// binaries says the binary was compiled from other sources than those there now, or when the file isn't SPIR-V; Reason says -// which (empty when there's simply no binary) +// binaries says the binary was compiled from other sources than those there now, when the manifest doesn't list it while its +// source is there, or when the file isn't SPIR-V; Reason says which (empty when there's simply no binary) std::vector load_shader_binary(shader_source const &Source, std::string &Reason); // the ids of the specialization constants of a SPIR-V module (OpDecorate ... SpecId) diff --git a/rendering/common/skylight.h b/rendering/common/skylight.h index 28b9b402f..bd8d99f37 100644 --- a/rendering/common/skylight.h +++ b/rendering/common/skylight.h @@ -7,8 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the light of the sky the renderers share (the part of the stage S of claude/gl46-renderer-features-plan.md which isn't the -// work of the gpu, taken out of opengl46_sky for the vulkan renderer, stage P1 of claude/vulkan14-renderer-plan.md): +// the light of the sky the renderers share (the part which isn't the work of the gpu, taken out of opengl46_sky for the vulkan +// renderer): // - the directional part of the ambient light, as spherical harmonics (gl::sky_data), worked out from the colours of the sky // dome or from the physical atmosphere // - the parameters of the physical atmosphere (gl::atmosphere_ubs) and when its look-up tables are to be made again diff --git a/rendering/common/skyocclusion.cpp b/rendering/common/skyocclusion.cpp index 4aef4cce1..8b6238507 100644 --- a/rendering/common/skyocclusion.cpp +++ b/rendering/common/skyocclusion.cpp @@ -165,6 +165,13 @@ double shape_reach(scene::shape_node &Shape) return (radius > 0.0 ? radius : std::numeric_limits::max()); } +// the sub-models under the given one which are geometry of the model. the children of a text display are its whole +// character set, not the characters it shows, and are left out +TSubModel *geometry_children(TSubModel const *Submodel) +{ + return (Submodel->eType == TP_TEXT ? nullptr : Submodel->Child); +} + } // namespace sky_occlusion::layout sky_occlusion::layout_of(int const Level) @@ -848,7 +855,7 @@ void sky_occlusion::gather_submodel(TSubModel *Submodel, std::uint32_t const Alp } } if (part->Child != nullptr) - gather_submodel(part->Child, Alpha, transform, Corner, Far, Triangles); + gather_submodel(geometry_children(part), Alpha, transform, Corner, Far, Triangles); } } diff --git a/rendering/common/skyocclusion.h b/rendering/common/skyocclusion.h index 80c862b63..3d661cd2a 100644 --- a/rendering/common/skyocclusion.h +++ b/rendering/common/skyocclusion.h @@ -36,8 +36,8 @@ class basic_cell; namespace gfx { -// the occlusion of the sky and of the sun by the scenery around the camera (Global.gfx_skyvisibility, the track T of -// claude/renderers-plan.md), the part shared by the renderers; the backend (opengl46_sky_occlusion, vk14::sky_occlusion_maps) keeps +// the occlusion of the sky and of the sun by the scenery around the camera (Global.gfx_skyvisibility), +// the part shared by the renderers; the backend (opengl46_sky_occlusion, vk14::sky_occlusion_maps) keeps // two textures the shading reads and copies to them what this part works out, through the gpu_* methods. // tunnels, the ground under bridges and roofs, cuttings and the foot of slopes are dark because the geometry around holds back the // sky and the sun, not because of the environment flags of the tracks (tunnel, canyon), which the renderers leave alone now diff --git a/rendering/common/walksync.h b/rendering/common/walksync.h index c99f6650a..5030ee875 100644 --- a/rendering/common/walksync.h +++ b/rendering/common/walksync.h @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the walks of the scene made by several threads at once (the stage M2 of claude/vulkan14-renderer-plan.md). only the vulkan renderer +// the walks of the scene made by several threads at once. only the vulkan renderer // opens the window in which they are (gfx.vulkan.parallelpasses); outside of it everything here does nothing, and the opengl renderer // never opens it. while it's open: // - every thread walking the scene holds the walk lock shared (a pass of a walker from the start to the end, the main thread from the diff --git a/rendering/common/weatherstate.h b/rendering/common/weatherstate.h index b7c254f03..4eb1641c6 100644 --- a/rendering/common/weatherstate.h +++ b/rendering/common/weatherstate.h @@ -7,8 +7,8 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the weather the renderers draw (the part of the stage F of claude/gl46-renderer-features-plan.md which isn't the work of the -// gpu, taken out of opengl46_weather for the vulkan renderer, stage P2 of claude/vulkan14-renderer-plan.md): the block of the +// the weather the renderers draw (the part which isn't the work of the gpu, taken out of opengl46_weather for the vulkan +// renderer): the block of the // weather of the shaders (gl::weather_ubs) made from the weather of the simulation (environment/weather.h) for the frame and for // each pass, the quality levels, the place of the map of the shadows of the clouds, the bands of the panorama of the clouds, the // sampling of the fog volume over the frames, and the stars of the catalogue (environment/starcatalog.h) diff --git a/rendering/common/windscreenwater.cpp b/rendering/common/windscreenwater.cpp index 9a52eb3fe..a369d4a48 100644 --- a/rendering/common/windscreenwater.cpp +++ b/rendering/common/windscreenwater.cpp @@ -10,6 +10,10 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/common/windscreenwater.h" +#include +#include +#include + #include "model/Model3d.h" #include "model/material.h" #include "rendering/renderer.h" @@ -17,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/utilities.h" #include "vehicle/DynObj.h" #include "vehicle/Train.h" @@ -38,17 +43,42 @@ double constexpr WIND_SHARE{0.5}; float constexpr LEAST_DROP{0.5f}; // the water a flake of snow brings, mm3 on average (water_spawn.comp: 0.3 .. 2.5) float constexpr FLAKE_WATER{1.4f}; +// how much warmer than the air a glass of the cab is, degrees: the cab is heated (the blowing on the glass isn't simulated), +// less so at speed, when the air cools the glass from the outside (water_snow.comp) +float constexpr GLASS_WARMTH{3.f}; // the most landings tried on a glass in a step std::uint32_t constexpr MOST_TRIES{1024}; // the longest step, seconds: a longer frame slows the water down rather than let it jump double constexpr LONGEST_STEP{0.05}; -// whether the material is a glass: one of mat_rain_windscreen, with a mask of the wipers -bool is_glass(opengl_material const *Material) +// whether the material is a glass of the water: one of mat_rain_windscreen, with a mask of the wipers +bool is_water_glass(opengl_material const *Material) { return (Material != nullptr) && (Material->shader != nullptr) && (Material->shader->texture_conf.count("wipermask") > 0) && (Material->shader->param_conf.count("water_slot") > 0); } +// whether the material is a glass of the snow: one of mat_snow_windscreen, with a mask of the wipers (its param snow_slot is in +// the place of water_slot) +bool is_snow_glass(opengl_material const *Material) +{ + return (Material != nullptr) && (Material->shader != nullptr) && (Material->shader->texture_conf.count("wipermask") > 0) && (Material->shader->param_conf.count("snow_slot") > 0); +} + +// whether the material is a glass, of the water or of the snow +bool is_glass(opengl_material const *Material) +{ + return is_water_glass(Material) || is_snow_glass(Material); +} + +// what a material of the cab with a mask of the wipers is now: 0 no glass, 1 a glass of the water, 2 a glass of the snow (its +// shader goes with the weather) +int glass_kind(opengl_material const *Material) +{ + if (is_snow_glass(Material)) + return 2; + return is_water_glass(Material) ? 1 : 0; +} + // calls Visit for every submodel of the branch, its children and its siblings template void visit_submodels(TSubModel *Submodel, Visit &&Visitor) { @@ -94,6 +124,11 @@ void windscreen_water::release() assign(false); m_glasses = {}; m_glasscount = 0; + m_layerslot = -1; + m_logged.fill(-1); + m_layerlogged = -1; + m_kinds.clear(); + m_cabmaterials.clear(); m_vehicle = nullptr; m_cab = nullptr; } @@ -112,7 +147,13 @@ void windscreen_water::assign(bool const Assigned) } for (std::size_t slot = 0; slot < m_glasscount; ++slot) { - auto const &glass{m_glasses[slot]}; + auto &glass{m_glasses[slot]}; + // the material of the glass as the cab has it now: the renderer may give the glass a fresh copy of its material (after the + // weather changed), which takes the slot then + if (Assigned && (glass.submodel != nullptr) && (glass.submodel->m_material != glass.material) && is_glass(m_host.material(glass.submodel->m_material))) + { + glass.material = glass.submodel->m_material; + } if (auto *material{m_host.material(glass.material)}; is_glass(material)) { material->params[SLOT_PARAM].z = (Assigned && glass.baked ? static_cast(slot + 1) : 0.f); @@ -230,6 +271,14 @@ void windscreen_water::build(TModel3d &Cab) } } auto const material{Submodel->m_material}; + if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && (std::find(m_cabmaterials.begin(), m_cabmaterials.end(), material) == m_cabmaterials.end())) + m_cabmaterials.push_back(material); + if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && std::ranges::none_of(m_kinds, [material](auto const &Kind) { return Kind.first == material; })) + { + // every material with a mask of the wipers, what it is kept: it's a glass of another kind when the weather changes + if (auto const *opengl{m_host.material(material)}; (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->texture_conf.count("wipermask") > 0)) + m_kinds.emplace_back(material, glass_kind(opengl)); + } if ((material != null_handle) && (material > 0) && (Submodel->eType == GL_TRIANGLES) && (std::find(materials.begin(), materials.end(), material) == materials.end()) && is_glass(m_host.material(material))) { materials.push_back(material); @@ -254,7 +303,12 @@ void windscreen_water::build(TModel3d &Cab) auto &glass{m_glasses[m_glasscount]}; glass = windscreen_water::glass{}; glass.material = material; + visit_submodels(root, [&](TSubModel *Submodel) { + if ((glass.submodel == nullptr) && (Submodel->m_material == material) && (Submodel->eType == GL_TRIANGLES)) + glass.submodel = Submodel; + }); auto const *opengl{m_host.material(material)}; + glass.snow = is_snow_glass(opengl); glass.mask = opengl->textures[opengl->shader->texture_conf.at("wipermask").id]; for (std::size_t texel = 0; texel < texels; ++texel) { @@ -309,6 +363,31 @@ void windscreen_water::build(TModel3d &Cab) } } +bool windscreen_water::wants_rain_cells() +{ + // without the simulation the cab isn't looked at: the cells as before, whenever it rains + if (m_state <= 0) + return true; + // a glass of the cab with drops, as it is in this weather: a material with an atlas of drops (raindropsatlas: the rain, or the + // insects, which don't come with rain), but not one of the snow (snow_slot) + return std::ranges::any_of(m_cabmaterials, [this](material_handle const Material) { + auto const *opengl{m_host.material(Material)}; + return (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->texture_conf.count("raindropsatlas") > 0) && + (opengl->shader->param_conf.count("snow_slot") == 0); + }); +} + +bool windscreen_water::wants_glass_requests() +{ + if ((m_state <= 0) || (false == bool(m_host.material)) || FreeFlyModeFlag || (false == Global.render_cab) || (simulation::Train == nullptr)) + return true; + // the glasses of the rain, of the insects and of the snow all have the atlas of the drops + return std::ranges::any_of(m_cabmaterials, [this](material_handle const Material) { + auto const *opengl{m_host.material(Material)}; + return (opengl != nullptr) && (opengl->shader != nullptr) && (opengl->shader->texture_conf.count("raindropsatlas") > 0); + }); +} + void windscreen_water::update(double const Seconds) { if (false == available()) @@ -317,7 +396,10 @@ void windscreen_water::update(double const Seconds) } auto const *vehicle{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; auto *cab{vehicle != nullptr ? vehicle->mdKabina : nullptr}; - if ((vehicle != m_vehicle) || (cab != m_cab)) + // a material of the glasses of another kind: the weather changed, the materials have the shaders of the other weather (the + // snow comes with the shader of the snow and goes with it) + auto const changed{std::ranges::any_of(m_kinds, [this](auto const &Kind) { return glass_kind(m_host.material(Kind.first)) != Kind.second; })}; + if ((vehicle != m_vehicle) || (cab != m_cab) || changed) { // another cab: its glasses dry release(); @@ -339,7 +421,7 @@ void windscreen_water::update(double const Seconds) // the blades of the wipers of the vehicle, as the glasses read them (the channels of the mask follow the wipers of the cab // the vehicle is driven from) glm::vec4 blades{-1.f}; - if (auto const cabactive{vehicle->MoverParameters->CabActive}; cabactive != 0) + if (auto const cabactive{vehicle->ActiveCab()}; cabactive != 0) { auto const count{static_cast(vehicle->dWiperPos.size())}; for (int i = 0; i < 4; ++i) @@ -355,7 +437,7 @@ void windscreen_water::update(double const Seconds) auto const toworld{glm::dmat3{vehicle->mMatrix}}; auto const tomodel{glm::inverse(toworld)}; auto const up{glm::normalize(glm::vec3{tomodel * glm::dvec3{0.0, 1.0, 0.0}})}; - auto const air{glm::vec3{tomodel * (glm::dvec3{simulation::Environment.wind()} * WIND_SHARE - vehicle->VectorFront() * vehicle->MoverParameters->V)}}; + auto const air{glm::vec3{tomodel * (glm::dvec3{simulation::Environment.wind()} * WIND_SHARE - vehicle->VectorFront() * vehicle->Speed())}}; auto const heavy{std::clamp(Global.Overcast - 1.f, 0.f, 1.f)}; auto const snow{Global.Weather == "snow:"}; auto const fall{snow ? SNOW_FALL : RAIN_FALL}; @@ -409,11 +491,23 @@ void windscreen_water::update(double const Seconds) auto const coming{glm::length(air - up * fall)}; std::uint32_t most{0}; m_tries = 0; + bool anysnow{false}; for (std::size_t slot = 0; slot < m_glasscount; ++slot) { auto &glass{m_glasses[slot]}; auto const *material{m_host.material(glass.material)}; - auto const simulated{glass.baked && is_glass(material)}; + auto const snowed{glass.baked && glass.snow && is_snow_glass(material)}; + block.snow_slots[static_cast(slot)] = (snowed ? 1.f : 0.f); + // the state of the glass in the log once it changes: why a glass stays without its water or snow + if (auto const state{(glass.baked ? 1 : 0) | (glass.snow ? 2 : 0) | (glass_kind(material) << 2) | (snowed ? 16 : 0)}; state != m_logged[slot]) + { + m_logged[slot] = state; + WriteLog("windscreen water: glass " + std::to_string(slot + 1) + (glass.baked ? " baked" : " not baked yet (the mask of the wipers not loaded)") + + (glass.snow ? ", built as a glass of the snow" : ", built as a glass of the water") + ", its material now " + + std::to_string(glass_kind(material)) + " (0 none, 1 water, 2 snow)" + (snowed ? ", its snow simulated" : "")); + } + anysnow = anysnow || snowed; + auto const simulated{glass.baked && (false == glass.snow) && is_water_glass(material)}; glass.landings += static_cast(perground / fall * coming * glass.densest) * seconds; auto const whole{std::floor(glass.landings)}; glass.landings -= whole; @@ -432,8 +526,107 @@ void windscreen_water::update(double const Seconds) m_bladesbefore.x < 0.f ? blades.x : m_bladesbefore.x, m_bladesbefore.y < 0.f ? blades.y : m_bladesbefore.y, m_bladesbefore.z < 0.f ? blades.z : m_bladesbefore.z, m_bladesbefore.w < 0.f ? blades.w : m_bladesbefore.w}; block.rain = glm::vec4{LEAST_DROP, lambda, 1.f, 0.f}; block.counts = glm::uvec4{m_step * 2654435761u, most, 0u, 0u}; + block.snow = glm::vec4{snow ? perground : 0.f, GLASS_WARMTH, static_cast(std::abs(vehicle->Speed())), static_cast(m_snowmap)}; m_bladesbefore = blades; gpu_step(block, most); + if (anysnow) + { + lay_snow(block); + // the step wrote the other map of the snow + m_snowmap = 1 - m_snowmap; + } +} + +namespace +{ + +// a texture of the material by its name in the shader, none when the shader has no such texture +texture_handle material_texture(opengl_material const &Material, std::string const &Name) +{ + if ((Material.shader == nullptr) || (Material.shader->texture_conf.count(Name) == 0)) + { + return null_handle; + } + return Material.textures[Material.shader->texture_conf.at(Name).id]; +} + +} // namespace + +std::array windscreen_water::layer_info(std::size_t const Slot, std::vector const &Axes) +{ + std::array info{}; + if ((Slot >= m_glasses.size()) || (false == m_glasses[Slot].snow) || ((m_layerslot >= 0) && (m_layerslot != static_cast(Slot)))) + { + return info; + } + auto const size{static_cast(gl::WATER_MAP)}; + glm::ivec2 least{size}; + glm::ivec2 most{-1}; + glm::dvec2 span{0.0}; + auto on{0}; + for (int y = 0; y < size; ++y) + { + for (int x = 0; x < size; ++x) + { + auto const texel{static_cast(y * size + x)}; + if ((texel * 2 + 1 >= Axes.size()) || (Axes[texel * 2].w <= 0.f)) + { + continue; + } + least = glm::min(least, glm::ivec2{x, y}); + most = glm::max(most, glm::ivec2{x, y}); + if (Axes[texel * 2].w >= 1.f) + { + // metres of the glass in a unit of its uv, across and down + span += glm::dvec2{glm::length(glm::vec3{Axes[texel * 2]}), glm::length(glm::vec3{Axes[texel * 2 + 1]})}; + ++on; + } + } + } + if ((on == 0) || (most.x < least.x) || (most.y < least.y)) + { + return info; + } + m_layerslot = static_cast(Slot); + span /= static_cast(on); + auto const corner{glm::vec2{least} / static_cast(size)}; + auto const extent{glm::vec2{most - least + 1} / static_cast(size)}; + // the texels across and down as the glass is wide and high (the same size in metres both ways) + auto const wide{std::max(static_cast(extent.x) * span.x, 1e-3)}; + auto const high{std::max(static_cast(extent.y) * span.y, 1e-3)}; + auto const texels{static_cast(gl::WATER_LAYER_TEXELS)}; + auto const across{static_cast(std::clamp(std::round(std::sqrt(texels * wide / high)), 16.0, texels / 16.0))}; + auto const down{static_cast(gl::WATER_LAYER_TEXELS / across)}; + info = {std::bit_cast(corner.x), std::bit_cast(corner.y), std::bit_cast(extent.x), std::bit_cast(extent.y), across, down, 0u, 0u}; + return info; +} + +void windscreen_water::lay_snow(gl::water_ubs const &Block) +{ + // the one glass with the layer + if ((m_layerslot < 0) || (static_cast(m_layerslot) >= m_glasscount)) + { + return; + } + auto const slot{static_cast(m_layerslot)}; + if (Block.snow_slots[static_cast(slot)] >= 0.5f) + { + auto const *material{m_host.material(m_glasses[slot].material)}; + auto const atlas{(material != nullptr) ? material_texture(*material, "raindropsatlas") : null_handle}; + auto const normal{(material != nullptr) ? material_texture(*material, "normalmap") : null_handle}; + if ((atlas != null_handle) && (normal != null_handle)) + { + auto layer{Block}; + layer.counts.z = static_cast(slot); + layer.counts.w = m_step; + auto const laid{gpu_snow_layer(slot, atlas, normal, layer)}; + if (int const state{laid ? 1 : 0}; state != m_layerlogged) + { + m_layerlogged = state; + WriteLog("windscreen water: the layer of the snow of glass " + std::to_string(slot + 1) + (laid ? " laid" : " not laid (the atlas of the snow not loaded)")); + } + } + } } std::string windscreen_water::info() const diff --git a/rendering/common/windscreenwater.h b/rendering/common/windscreenwater.h index 2c09951ba..3d3470fe7 100644 --- a/rendering/common/windscreenwater.h +++ b/rendering/common/windscreenwater.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include @@ -62,6 +63,13 @@ class windscreen_water // once a frame, before the colour passes: the cab of the train followed, the step of the simulation run. Seconds: of the // simulation since the frame before (0 when it's paused) void update(double Seconds); + // whether the glasses need the cells of the rain worked out: the cab of the train has a glass with drops, not of the snow (or + // the simulation isn't used, the cab not looked at) + bool wants_rain_cells(); + // whether a glass in the view may ask the post-processing for its drops and haze in the velocity target (mat_rain_windscreen, + // mat_bugs_windscreen, mat_snow_windscreen): the cab seen from inside has such a glass, or the view is not from the cab + // (the glasses of any vehicle may be seen then), or the cab isn't looked at + bool wants_glass_requests(); // the materials let go of their slots, the glasses forgotten (the storage stays as it is, unused) void release(); std::string info() const; @@ -79,16 +87,22 @@ class windscreen_water virtual bool gpu_bake(std::size_t Slot, texture_handle Mask, gl::water_ubs const &Block) = 0; // the step of the simulation of the glasses Block says are simulated; Tries: the most landings tried on a glass virtual void gpu_step(gl::water_ubs const &Block, std::uint32_t Tries) = 0; + // the snow of a glass of the snow laid together from the sprites of its atlas into its layer, after the step + // (water_snowlayer.comp; Block.counts: z the glass, w the step); Atlas, Normal: the atlas of the snow and its normal map (textures + // of the renderer); false when they aren't ready yet + virtual bool gpu_snow_layer(std::size_t Slot, texture_handle Atlas, texture_handle Normal, gl::water_ubs const &Block) = 0; private: struct glass { material_handle material{null_handle}; + TSubModel *submodel{nullptr}; // the first piece of the glass in the cab, for the material it has now texture_handle mask{null_handle}; float densest{0.f}; // the most metres squared a unit of the uv holds float area{0.f}; // metres squared of the glass double landings{0.0}; // the share of a landing left over from the steps before bool baked{false}; + bool snow{false}; // a glass of the snow (mat_snow_windscreen), else of the water }; // the glasses of the model of a cab found and set up @@ -97,17 +111,35 @@ class windscreen_water void rasterize(TSubModel *Submodel, material_handle Material, glm::vec3 const &Inside, std::vector &Axes) const; // the slots given to the materials of the glasses (every frame: a material made anew takes its default params) void assign(bool Assigned); + // the snow of the glasses of the snow Block says are simulated laid together, after the step + void lay_snow(gl::water_ubs const &Block); + + protected: + // where the layer of the snow of a glass lies (water.glsl): the rectangle of the uv its map holds the glass in (the corner and + // the size, the bits of floats) and the texels of the layer across and down, as the glass is wide and high in metres (0 when + // the map holds no glass or the glass has no layer) + // the eight uint the renderer puts at gl::WATER_LAYER_INFO_OFFSET for the glass of Slot (set up with its map Axes): the cab has + // one layer, for its first glass of the snow, the others get none (zeros) + std::array layer_info(std::size_t Slot, std::vector const &Axes); + + private: host m_host; int m_state{0}; // 0: not set up yet, 1: ready, -1: can't be used TDynamicObject const *m_vehicle{nullptr}; TModel3d const *m_cab{nullptr}; + std::vector m_cabmaterials; // the materials of the cab (for the glasses with rain it has, wants_rain_cells()) + std::vector> m_kinds; // the materials of the cab with a mask of the wipers, what kind of glass they were std::array m_glasses{}; std::size_t m_glasscount{0}; + int m_layerslot{-1}; // the glass with the layer of the snow, -1 none + std::array m_logged{-1, -1, -1, -1}; // what the log last said of each glass (baked, snow, the shader, simulated) + int m_layerlogged{-1}; // what the log last said of the layer of the snow glm::vec4 m_bladesbefore{-1.f}; double m_time{0.0}; // seconds the simulation runs std::uint32_t m_step{0}; std::uint32_t m_tries{0}; // landings tried in the last step, all glasses + int m_snowmap{0}; // the map of the snow of the glasses the next step reads (0, 1) }; } // namespace gfx diff --git a/rendering/lightarray.cpp b/rendering/lightarray.cpp index 15020894b..bfa20349a 100644 --- a/rendering/lightarray.cpp +++ b/rendering/lightarray.cpp @@ -22,8 +22,8 @@ light_array::insert( TDynamicObject const *Owner ) { // we're only storing lights for locos, which have two sets of lights, front and rear // for a more generic role this function would have to be tweaked to add vehicle type-specific light combinations - data.emplace_back( Owner, end::front ); - data.emplace_back( Owner, end::rear ); + data.emplace_back( Owner, NumberOf( VehicleEnd::front ) ); + data.emplace_back( Owner, NumberOf( VehicleEnd::rear ) ); } void @@ -38,7 +38,7 @@ light_array::update() { for( auto &light : data ) { // update light parameters to match current data of the owner - if( light.index == end::front ) { + if( EndOf( light.index ) == VehicleEnd::front ) { // front light set light.position = light.owner->GetPosition() + ( light.owner->VectorFront() * ( std::max( 0.0, light.owner->GetLength() * 0.5 - 2.0 ) ) );// +( light.owner->VectorUp() * 0.25 ); light.direction = glm::make_vec3( glm::value_ptr(light.owner->VectorFront()) ); // TODO: It is needed to get value_ptr and then make_vec3? @@ -51,11 +51,10 @@ light_array::update() { light.direction.z = -light.direction.z; } // determine intensity of this light set - if( ( true == light.owner->MoverParameters->Power24vIsAvailable ) - || ( true == light.owner->MoverParameters->Power110vIsAvailable ) ) { + if( true == light.owner->LowVoltagePowered() ) { // with power on, the intensity depends on the state of activated switches // first we cross-check the list of enabled lights with the lights installed in the vehicle... - auto const lights { light.owner->MoverParameters->iLights[ light.index ] & light.owner->LightList( static_cast( light.index ) ) }; + auto const lights { light.owner->LightsSwitchedOn( static_cast( light.index ) ) & light.owner->LightList( static_cast( light.index ) ) }; // ...then check their individual state light.count = 0 + ( ( lights & light::headlight_left ) ? 1 : 0 ) @@ -66,21 +65,14 @@ light_array::update() { // set intensity if( light.count > 0 ) { - bool isEnabled = light.index == end::front ? !light.owner->HeadlightsAoff : !light.owner->HeadlightsBoff; + bool isEnabled = EndOf( light.index ) == VehicleEnd::front ? !light.owner->HeadlightsAoff : !light.owner->HeadlightsBoff; light.intensity = std::max(0.0f, std::log((float)light.count + 1.0f)); - if (light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // tylko przyciemnione - light.intensity *= static_cast(light.owner->MoverParameters->dimMultiplier); - else if (!light.owner->DimHeadlights && !light.owner->HighBeamLights && isEnabled) // normalne - light.intensity *= static_cast(light.owner->MoverParameters->normMultiplier); - else if (light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // przyciemnione dlugie - light.intensity *= static_cast(light.owner->MoverParameters->highDimMultiplier); - else if (!light.owner->DimHeadlights && light.owner->HighBeamLights && isEnabled) // dlugie zwykle - light.intensity *= static_cast(light.owner->MoverParameters->highMultiplier); - else if (!isEnabled) - { + auto const multiplier{light.owner->HeadlightsMultiplier()}; + if (isEnabled) + light.intensity *= static_cast(multiplier); + else light.intensity = 0.0f; - } // TBD, TODO: intensity can be affected further by other factors light.state = { @@ -88,24 +80,9 @@ light_array::update() { ( ( lights & light::headlight_upper ) ? 1.f : 0.f ), ( ( lights & light::headlight_right | light::highbeamlight_right) ? 1.f : 0.f ) }; - light.color = { - static_cast(light.owner->MoverParameters->refR) / 255.0f, - static_cast(light.owner->MoverParameters->refG) / 255.0f, - static_cast(light.owner->MoverParameters->refB) / 255.0f - }; + light.color = light.owner->HeadlightsColor(); - if (light.owner->DimHeadlights && !light.owner->HighBeamLights) // tylko przyciemnione - light.state *= light.owner->MoverParameters->dimMultiplier; - else if (!light.owner->DimHeadlights && !light.owner->HighBeamLights) // normalne - light.state *= light.owner->MoverParameters->normMultiplier; - else if (light.owner->DimHeadlights && light.owner->HighBeamLights) // przyciemnione dlugie - light.state *= light.owner->MoverParameters->highDimMultiplier; - else if (!light.owner->DimHeadlights && light.owner->HighBeamLights) // dlugie zwykle - light.state *= light.owner->MoverParameters->highMultiplier; - else if (!isEnabled) - { - light.state = glm::vec3{0.f}; - } + light.state *= multiplier; } else { light.intensity = 0.0f; diff --git a/rendering/opengl46/opengl46ao.cpp b/rendering/opengl46/opengl46ao.cpp index a5e82d1b1..4198a33cc 100644 --- a/rendering/opengl46/opengl46ao.cpp +++ b/rendering/opengl46/opengl46ao.cpp @@ -12,8 +12,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -28,18 +31,31 @@ void opengl46_ao::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_main_program = make_compute("gtao_main.comp"); - m_denoise_program = make_compute("gtao_denoise.comp"); + try { + m_main_program = make_compute("gtao_main.comp"); + m_denoise_program = make_compute("gtao_denoise.comp"); gl::shader vertex("quad.vert"); gl::shader fragment("postfx_ssao_apply.frag"); m_apply_program = std::make_unique(std::vector>{vertex, fragment}); } + catch (gl::shader_exception const &e) + { + // off before the viewports are made, which then have no targets for it + ErrorLog(std::format("ambient occlusion not available: {}", e.what())); + m_main_program.reset(); + m_denoise_program.reset(); + m_apply_program.reset(); + Global.gfx_postfx_ao = 0; + return; + } m_vao = std::make_unique(); } void opengl46_ao::compute(opengl_texture &Depth, opengl_texture &Raw, opengl_texture &Smooth, glm::mat4 const &Projection) { + if (m_denoise_program == nullptr) + return; m_timer.begin(); m_timing = true; @@ -70,6 +86,8 @@ void opengl46_ao::compute(opengl_texture &Depth, opengl_texture &Raw, opengl_tex void opengl46_ao::apply(int const Mode, opengl_texture &Depth, opengl_texture &Occlusion, gl::framebuffer &Target, glm::mat4 const &Projection) { + if (m_apply_program == nullptr) + return; Target.bind(); m_apply_program->bind(); m_vao->bind(); diff --git a/rendering/opengl46/opengl46ao.h b/rendering/opengl46/opengl46ao.h index dcc848743..a6e94a710 100644 --- a/rendering/opengl46/opengl46ao.h +++ b/rendering/opengl46/opengl46ao.h @@ -34,7 +34,8 @@ class opengl46_ao opengl46_ao(const opengl46_ao &) = delete; opengl46_ao &operator=(const opengl46_ao &) = delete; - // creates the programs. throws gl::shader_exception + // creates the programs. without them (a shader which doesn't compile) there is no ambient occlusion: logged, and + // gfx.postfx.ao switched off void init(); // ground truth ambient occlusion from the depth of the scene drawn with the given projection: Raw gets the result of // the horizon search, Smooth the smoothed one. both half the size of Depth diff --git a/rendering/opengl46/opengl46backend.cpp b/rendering/opengl46/opengl46backend.cpp index e050daa30..7956558f6 100644 --- a/rendering/opengl46/opengl46backend.cpp +++ b/rendering/opengl46/opengl46backend.cpp @@ -14,6 +14,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46renderer.h" #include "utilities/Globals.h" #include "utilities/Logs.h" +#include "utilities/hardwareprobe.h" namespace { @@ -76,6 +77,9 @@ bool after_window(GLFWwindow *Window) return false; } + // which of the GPUs the context runs on, and its memory + hardware::log_gl_context(); + return true; } diff --git a/rendering/opengl46/opengl46cabprobe.cpp b/rendering/opengl46/opengl46cabprobe.cpp index 09afd9b23..67148a31e 100644 --- a/rendering/opengl46/opengl46cabprobe.cpp +++ b/rendering/opengl46/opengl46cabprobe.cpp @@ -17,6 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -51,20 +53,6 @@ opengl46_cab_probe::~opengl46_cab_probe() void opengl46_cab_probe::init() { - gl::shader vertex("cabprobe.vert"); - gl::shader geometry("cabprobe.geom"); - { - gl::shader fragment("cabprobe.frag"); - m_program = std::make_unique(std::vector>{vertex, geometry, fragment}); - } - { - gl::shader fragment("cabprobe_alpha.frag"); - m_alpha_program = std::make_unique(std::vector>{vertex, geometry, fragment}); - } - { - gl::shader compute("cabprobe_sh.comp"); - m_sh_program = std::make_unique(std::vector>{compute}); - } m_sh = std::make_unique(static_cast(sizeof(gl::cab_probe_data)), gl::CAB_PROBE_SSBO_BINDING); m_sh->update(gl::cab_probe_data{}); @@ -76,6 +64,31 @@ void opengl46_cab_probe::init() glTextureStorage2D(m_white, 1, GL_RGBA8, 1, 1); std::uint8_t const white[4]{255, 255, 255, 255}; glClearTexImage(m_white, 0, GL_RGBA, GL_UNSIGNED_BYTE, white); + + try + { + gl::shader vertex("cabprobe.vert"); + gl::shader geometry("cabprobe.geom"); + { + gl::shader fragment("cabprobe.frag"); + m_program = std::make_unique(std::vector>{vertex, geometry, fragment}); + } + { + gl::shader fragment("cabprobe_alpha.frag"); + m_alpha_program = std::make_unique(std::vector>{vertex, geometry, fragment}); + } + gl::shader compute("cabprobe_sh.comp"); + m_sh_program = std::make_unique(std::vector>{compute}); + } + catch (gl::shader_exception const &e) + { + // the shading reads the stand-ins; no maps are made (gpu_allocate()) + ErrorLog(std::format("cab probe not available: {}", e.what())); + m_program.reset(); + m_alpha_program.reset(); + m_sh_program.reset(); + Global.gfx_cabprobe = 0; + } } void opengl46_cab_probe::bind() @@ -89,6 +102,8 @@ void opengl46_cab_probe::bind() bool opengl46_cab_probe::gpu_allocate(int const Size) { + if (m_sh_program == nullptr) + return false; m_light = make_cube(GL_RGBA16F, Size, true); m_albedo = make_cube(GL_RGBA8, Size, true); m_depth = make_cube(GL_DEPTH_COMPONENT32F, Size, false); diff --git a/rendering/opengl46/opengl46cabprobe.h b/rendering/opengl46/opengl46cabprobe.h index c26f81d31..c920b34de 100644 --- a/rendering/opengl46/opengl46cabprobe.h +++ b/rendering/opengl46/opengl46cabprobe.h @@ -26,7 +26,8 @@ class opengl46_cab_probe : public gfx::cab_probe opengl46_cab_probe() = default; ~opengl46_cab_probe() override; - // creates the programs, the stand-ins and the storage of the spherical harmonics. throws gl::shader_exception + // creates the stand-ins, the storage of the spherical harmonics and the programs. without the programs (a shader which + // doesn't compile) there is no probe: logged, and gfx.cabprobe switched off void init(); // puts the maps (or the stand-ins) on their texture units, gl::CAB_PROBE_TEX, gl::CAB_PROBE_ALBEDO_TEX and the mask on // gl::CAB_PROBE_MASK_TEX, and the spherical harmonics on gl::CAB_PROBE_SSBO_BINDING. once per context and frame diff --git a/rendering/opengl46/opengl46exposure.cpp b/rendering/opengl46/opengl46exposure.cpp index d2b5f3476..ec925dcc7 100644 --- a/rendering/opengl46/opengl46exposure.cpp +++ b/rendering/opengl46/opengl46exposure.cpp @@ -13,8 +13,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -29,11 +32,7 @@ void opengl46_exposure::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_histogram_program = make_compute("exposure_histogram.comp"); - m_average_program = make_compute("exposure_average.comp"); - m_bloom_down = std::make_unique("bloom_down"); - m_bloom_up = std::make_unique("bloom_up"); - + // the tonemapping reads the buffer, also without the passes which work the exposure out m_exposure_ssbo = std::make_unique(sizeof(gl::exposure_data), gl::EXPOSURE_SSBO_BINDING); gl::exposure_data data{}; data.adapted_luminance = Global.gfx_postfx_autoexposure_key; @@ -41,6 +40,31 @@ void opengl46_exposure::init() data.average_luminance = Global.gfx_postfx_autoexposure_key; data.valid = 0; m_exposure_ssbo->update(data); + + try + { + m_histogram_program = make_compute("exposure_histogram.comp"); + m_average_program = make_compute("exposure_average.comp"); + } + catch (gl::shader_exception const &e) + { + ErrorLog(std::format("automatic exposure not available: {}", e.what())); + m_histogram_program.reset(); + m_average_program.reset(); + Global.gfx_postfx_autoexposure = false; + } + try + { + m_bloom_down = std::make_unique("bloom_down"); + m_bloom_up = std::make_unique("bloom_up"); + } + catch (gl::shader_exception const &e) + { + ErrorLog(std::format("bloom not available: {}", e.what())); + m_bloom_down.reset(); + m_bloom_up.reset(); + Global.gfx_postfx_bloom = false; + } } void opengl46_exposure::bind() @@ -76,6 +100,8 @@ std::unique_ptr opengl46_exposure::make_bloom_ch void opengl46_exposure::measure(opengl_texture &Image, double const Deltatime) { + if (m_average_program == nullptr) + return; float data[4]; if (m_readback.pop(data)) std::copy(std::begin(data), std::end(data), std::begin(m_readback_data)); @@ -106,6 +132,8 @@ void opengl46_exposure::measure(opengl_texture &Image, double const Deltatime) opengl_texture *opengl46_exposure::bloom(bloom_chain &Chain, opengl_texture &Image, gl::stream_ubo &Modelubo, gl::model_ubs &Model) { + if (m_bloom_up == nullptr) + return nullptr; m_bloom_timer.begin(); // down, the first step from the image itself for (std::size_t level = 0; level < Chain.sizes.size(); ++level) diff --git a/rendering/opengl46/opengl46exposure.h b/rendering/opengl46/opengl46exposure.h index 44b91a3d3..00f91d7dc 100644 --- a/rendering/opengl46/opengl46exposure.h +++ b/rendering/opengl46/opengl46exposure.h @@ -47,7 +47,8 @@ class opengl46_exposure opengl46_exposure(const opengl46_exposure &) = delete; opengl46_exposure &operator=(const opengl46_exposure &) = delete; - // creates the programs and the buffer. throws gl::shader_exception + // creates the buffer and the programs. a shader which doesn't compile is logged, and gfx.postfx.autoexposure or + // gfx.postfx.bloom switched off void init(); // binds the buffer the tonemapping reads; bindings are context state, so done in every context void bind(); diff --git a/rendering/opengl46/opengl46hiz.cpp b/rendering/opengl46/opengl46hiz.cpp index 142c22867..a431df930 100644 --- a/rendering/opengl46/opengl46hiz.cpp +++ b/rendering/opengl46/opengl46hiz.cpp @@ -13,8 +13,11 @@ http://mozilla.org/MPL/2.0/. #include "gl/ubo.h" #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + opengl46_hiz::~opengl46_hiz() { release(); @@ -22,8 +25,18 @@ opengl46_hiz::~opengl46_hiz() void opengl46_hiz::init() { - gl::shader shader("hiz_build.comp"); - m_program = std::make_unique(std::vector>{shader}); + try + { + gl::shader shader("hiz_build.comp"); + m_program = std::make_unique(std::vector>{shader}); + } + catch (gl::shader_exception const &e) + { + // no pyramid: the instances are culled without the occlusion test + ErrorLog(std::format("occlusion test of the instances not available: {}", e.what())); + m_program.reset(); + Global.gfx_gpucull_occlusion = false; + } } void opengl46_hiz::release() @@ -72,7 +85,7 @@ void opengl46_hiz::allocate(int const Width, int const Height) void opengl46_hiz::build(GLuint const Source, int const Width, int const Height, bool const Second) { - if ((Width <= 0) || (Height <= 0)) + if ((Width <= 0) || (Height <= 0) || (m_program == nullptr)) return; if (m_sourcesize != glm::ivec2{Width, Height}) allocate(Width, Height); diff --git a/rendering/opengl46/opengl46hiz.h b/rendering/opengl46/opengl46hiz.h index c75d6b0bb..9ee48ae7a 100644 --- a/rendering/opengl46/opengl46hiz.h +++ b/rendering/opengl46/opengl46hiz.h @@ -29,7 +29,8 @@ class opengl46_hiz opengl46_hiz(const opengl46_hiz &) = delete; opengl46_hiz &operator=(const opengl46_hiz &) = delete; - // creates the program. throws gl::shader_exception + // creates the program. without it (a shader which doesn't compile) no pyramid is made: logged, and gfx.gpucull.occlusion is + // switched off void init(); // makes the pyramid from the depth attachment of Source, a framebuffer of Width x Height pixels. // leaves the framebuffer bindings alone, texture unit 0 and image unit 0 are used (the unit cache is reset). diff --git a/rendering/opengl46/opengl46instancecull.cpp b/rendering/opengl46/opengl46instancecull.cpp index e36790ef5..a18b1fe23 100644 --- a/rendering/opengl46/opengl46instancecull.cpp +++ b/rendering/opengl46/opengl46instancecull.cpp @@ -12,8 +12,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -32,6 +35,9 @@ void opengl46_instance_cull::init(opengl46_instance_cull const *Shared) { if (Shared != nullptr) { + // nothing to share when the programs of the one shared aren't there + if (false == Shared->available()) + return; m_shared = Shared->m_shared; share_records(*Shared); } @@ -41,10 +47,21 @@ void opengl46_instance_cull::init(opengl46_instance_cull const *Shared) gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_shared = std::make_shared(); - m_shared->cull_program = make_compute("instance_cull.comp"); - m_shared->offsets_program = make_compute("instance_cull_offsets.comp"); - m_shared->commands_program = make_compute("instance_cull_commands.comp"); + auto shared{std::make_shared()}; + try + { + shared->cull_program = make_compute("instance_cull.comp"); + shared->offsets_program = make_compute("instance_cull_offsets.comp"); + shared->commands_program = make_compute("instance_cull_commands.comp"); + } + catch (gl::shader_exception const &e) + { + // the instances are culled on the cpu + ErrorLog(std::format("instance culling on the gpu not available: {}", e.what())); + Global.gfx_gpucull = 0; + return; + } + m_shared = std::move(shared); m_shared->records = std::make_unique(65536 * RECORD_SIZE, gl::INSTANCE_RECORD_SSBO_BINDING); } diff --git a/rendering/opengl46/opengl46instancecull.h b/rendering/opengl46/opengl46instancecull.h index 7812eac9a..002117399 100644 --- a/rendering/opengl46/opengl46instancecull.h +++ b/rendering/opengl46/opengl46instancecull.h @@ -42,8 +42,14 @@ class opengl46_instance_cull : public gfx::instance_cull opengl46_instance_cull() = default; - // creates the buffers, and the programs and the record buffer, or takes the ones of Shared. throws gl::shader_exception + // creates the buffers, and the programs and the record buffer, or takes the ones of Shared. without the programs (a shader + // which doesn't compile) nothing is made: logged, and gfx.gpucull is switched off void init(opengl46_instance_cull const *Shared = nullptr); + // the programs are there, the culling can run + bool available() const + { + return m_shared != nullptr; + } // runs the culling passes for the buckets added. View: rotation of the view of the pass. Occlusion: the depth pyramid // to test the instances against, or null. Twophase: with the occlusion test, only the instances seen in the previous // frame pass for now, dispatch_second() takes the others diff --git a/rendering/opengl46/opengl46localshadows.cpp b/rendering/opengl46/opengl46localshadows.cpp index 61b0a3c0c..c32f52255 100644 --- a/rendering/opengl46/opengl46localshadows.cpp +++ b/rendering/opengl46/opengl46localshadows.cpp @@ -16,6 +16,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -103,6 +105,38 @@ opengl46_local_shadows::~opengl46_local_shadows() } void opengl46_local_shadows::init() +{ + // a shadow sampler with no depth texture to read from is undefined, also where the shading doesn't read it + glCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &m_empty); + glTextureStorage3D(m_empty, 1, GL_DEPTH_COMPONENT32F, 1, 1, 6); + glTextureParameteri(m_empty, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTextureParameteri(m_empty, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); + glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); + float const farthest{0.f}; + glClearTexImage(m_empty, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); + m_emptyheadlights = make_array(1, 1); + glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glClearTexImage(m_emptyheadlights, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); + + try + { + init_programs(); + } + catch (gl::shader_exception const &e) + { + // the shading reads the stand-ins; no maps are made (gpu_allocate()) + ErrorLog(std::format("shadows of the lights not available: {}", e.what())); + m_program.reset(); + m_alpha_program.reset(); + m_multidraw_program.reset(); + m_alpha_multidraw_program.reset(); + Global.gfx_lights_shadows = 0; + } +} + +void opengl46_local_shadows::init_programs() { gl::shader vertex("shadowcube.vert"); gl::shader geometry("shadowcube.geom"); @@ -135,20 +169,6 @@ void opengl46_local_shadows::init() m_alpha_multidraw_program.reset(); } set_layer(0); - - // a shadow sampler with no depth texture to read from is undefined, also where the shading doesn't read it - glCreateTextures(GL_TEXTURE_CUBE_MAP_ARRAY, 1, &m_empty); - glTextureStorage3D(m_empty, 1, GL_DEPTH_COMPONENT32F, 1, 1, 6); - glTextureParameteri(m_empty, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTextureParameteri(m_empty, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); - glTextureParameteri(m_empty, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); - float const farthest{0.f}; - glClearTexImage(m_empty, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); - m_emptyheadlights = make_array(1, 1); - glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTextureParameteri(m_emptyheadlights, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glClearTexImage(m_emptyheadlights, 0, GL_DEPTH_COMPONENT, GL_FLOAT, &farthest); } void opengl46_local_shadows::set_near(float const Near) @@ -173,6 +193,9 @@ void opengl46_local_shadows::set_layer(int const Layer) bool opengl46_local_shadows::gpu_allocate(int const Count, int const Size) { + // no programs to draw the maps with + if (m_program == nullptr) + return false; m_texture = make_cube_array(Size, Count); m_framebuffer = make_framebuffer(m_texture); return (m_framebuffer != 0); @@ -190,6 +213,9 @@ void opengl46_local_shadows::gpu_release() bool opengl46_local_shadows::gpu_allocate_lamps(int const Count, int const Size) { + // no programs to draw the maps with + if (m_program == nullptr) + return false; // the scenery parts and the working copies m_lampstexture = make_cube_array(Size, 2 * Count); m_lampsframebuffer = make_framebuffer(m_lampstexture); @@ -208,6 +234,9 @@ void opengl46_local_shadows::gpu_release_lamps() bool opengl46_local_shadows::gpu_allocate_headlights(int const Count, int const Size) { + // no programs to draw the maps with + if (m_program == nullptr) + return false; m_headlightstexture = make_array(Size, Count); glCreateFramebuffers(1, &m_headlightsframebuffer); glNamedFramebufferTextureLayer(m_headlightsframebuffer, GL_DEPTH_ATTACHMENT, m_headlightstexture, 0, 0); diff --git a/rendering/opengl46/opengl46localshadows.h b/rendering/opengl46/opengl46localshadows.h index 225e9e371..e37ce1032 100644 --- a/rendering/opengl46/opengl46localshadows.h +++ b/rendering/opengl46/opengl46localshadows.h @@ -31,7 +31,8 @@ class opengl46_local_shadows : public gfx::local_shadows opengl46_local_shadows() = default; ~opengl46_local_shadows() override; - // creates the programs and the stand-in maps. throws gl::shader_exception + // creates the stand-in maps and the programs. without the programs (a shader which doesn't compile) the lights have no + // shadows: logged, and gfx.lights.shadows is switched off void init(); // puts the maps (or the stand-ins, which shadow nothing) on their texture units, gl::LOCAL_SHADOW_TEX and // gl::LOCAL_SHADOW_LAMPS_TEX. once per context and frame @@ -67,6 +68,8 @@ class opengl46_local_shadows : public gfx::local_shadows void gpu_headlights_timer(bool const Begin) override; private: + // throws gl::shader_exception + void init_programs(); void set_layer(int const Layer); void set_near(float const Near); diff --git a/rendering/opengl46/opengl46particles.cpp b/rendering/opengl46/opengl46particles.cpp index c9a78e217..22d0c5145 100644 --- a/rendering/opengl46/opengl46particles.cpp +++ b/rendering/opengl46/opengl46particles.cpp @@ -10,6 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/opengl46/opengl46particles.h" +#include + #include "rendering/particles.h" #include "rendering/openglcamera.h" #include "simulation/simulation.h" @@ -109,9 +111,9 @@ opengl46_particles::render() { if (!m_vao) { m_vao.emplace(); - m_vao->setup_attrib(*m_buffer, 0, 3, GL_FLOAT, sizeof(particle_vertex), 0); - m_vao->setup_attrib(*m_buffer, 1, 4, GL_FLOAT, sizeof(particle_vertex), 12); - m_vao->setup_attrib(*m_buffer, 2, 2, GL_FLOAT, sizeof(particle_vertex), 28); + m_vao->setup_attrib(*m_buffer, 0, 3, GL_FLOAT, sizeof(particle_vertex), static_cast(offsetof(particle_vertex, position))); + m_vao->setup_attrib(*m_buffer, 1, 4, GL_FLOAT, sizeof(particle_vertex), static_cast(offsetof(particle_vertex, color))); + m_vao->setup_attrib(*m_buffer, 2, 2, GL_FLOAT, sizeof(particle_vertex), static_cast(offsetof(particle_vertex, texture))); gl::buffer::unbind(gl::buffer::ARRAY_BUFFER); gl::vao::unbind(); diff --git a/rendering/opengl46/opengl46renderer.cpp b/rendering/opengl46/opengl46renderer.cpp index 4180d3b12..d7b1cb24f 100644 --- a/rendering/opengl46/opengl46renderer.cpp +++ b/rendering/opengl46/opengl46renderer.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/opengl46/opengl46renderer.h" +#include "rendering/common/shadersource.h" #include "utilities/color.h" #include "utilities/Globals.h" #include "utilities/Timer.h" @@ -29,7 +30,25 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46geometrybank.h" #include "rendering/screenshot.h" #include "rendering/editoroverlay.h" +#include "vehicle/DynObj.h" #include +#include + +namespace +{ +// the camera of a pass in the world for the scene block (gl::scene_ubs::camera_hi, camera_lo) +void scene_camera_place(gl::scene_ubs &Ubs, glm::dvec3 const &Place) +{ + auto const high{glm::floor(Place / 64.0) * 64.0}; + Ubs.camera_hi = glm::vec4{glm::vec3{high}, 0.f}; + Ubs.camera_lo = glm::vec4{glm::vec3{Place - high}, 0.f}; +} +} // namespace + +#include +#include +#include +#include //#define EU07_DEBUG_OPENGL @@ -61,6 +80,61 @@ ErrorCallback( GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei l + message ); } +namespace +{ + +// a shader the scene can't be drawn without failed: logged, and on windows the player is told the way a context which can't +// be made is (opengl46backend.cpp), as the game closes then +void shaders_failed(std::string_view const Reason) +{ + ErrorLog(std::format("invalid shader: {}", Reason)); +#ifdef _WIN32 + auto const message{std::format( + "MaSzyna can't draw the scene: a shader of the OpenGL 4.6 renderer could not be compiled by the graphics driver.\n\n" + "Details: {}\n\n" + "Update the graphics driver, or check the shaders folder of the game.", + Reason)}; + MessageBoxA(nullptr, message.c_str(), "MaSzyna", MB_ICONERROR | MB_OK); +#endif +} + +// the most samples a renderbuffer of the format can have; the driver lists the counts from the highest +GLint format_samples(GLenum const Format) +{ + GLint counts{0}; + ::glGetInternalformativ(GL_RENDERBUFFER, Format, GL_NUM_SAMPLE_COUNTS, 1, &counts); + if (counts <= 0) + return 1; + std::vector samples(static_cast(counts), 1); + ::glGetInternalformativ(GL_RENDERBUFFER, Format, GL_SAMPLES, counts, samples.data()); + return std::ranges::max(samples); +} + +// multisampling above what the driver gives the targets of the colour pass (init_viewport()) falls back to the most it gives, +// rather than the targets failing to be made +void clamp_multisampling() +{ + if (Global.iMultisampling <= 0) + return; + GLint maxsamples{1}; + ::glGetIntegerv(GL_MAX_SAMPLES, &maxsamples); + if (false == Global.gfx_skippipeline) + { + maxsamples = std::min({maxsamples, format_samples(Global.gfx_format_color), format_samples(Global.gfx_format_depth)}); + if (Global.gfx_motion_vectors()) + maxsamples = std::min(maxsamples, format_samples(Global.gfx_postfx_motionblur_format)); + } + auto multisampling{Global.iMultisampling}; + while ((multisampling > 0) && ((1 << multisampling) > maxsamples)) + --multisampling; + if (multisampling == Global.iMultisampling) + return; + WriteLog(std::format("multisampling x{} not supported by the graphics driver (at most x{}), using x{}", 1 << Global.iMultisampling, maxsamples, 1 << multisampling)); + Global.iMultisampling = multisampling; +} + +} // namespace + bool opengl46_renderer::Init(GLFWwindow *Window) { if (Global.gfx_gldebug) { @@ -148,7 +222,8 @@ bool opengl46_renderer::Init(GLFWwindow *Window) } catch (gl::shader_exception const &e) { - ErrorLog("invalid shader: " + std::string(e.what())); + // the scene can't be drawn without these + shaders_failed(e.what()); return false; } @@ -205,27 +280,21 @@ bool opengl46_renderer::Init(GLFWwindow *Window) m_scenecommandstream.reset(); } - try - { - m_sky.init(); - m_weather.init(); - m_instancecull.init(); - for (auto &shadowcull : m_shadowcull) - shadowcull.init(&m_instancecull); - m_hiz.init(); - m_timbers.init(); - m_shadowfit.init(); - m_exposure.init(); - m_ao.init(); - m_localshadows.init(); - m_cabprobe.init(); - m_skyocclusion.init(); - } - catch (gl::shader_exception const &e) - { - ErrorLog("invalid shader: " + std::string(e.what())); - return false; - } + // the effects whose shaders don't compile switch themselves off (logged, and their settings put off); the scene is drawn + // without them. they come before the viewports, which leave out the targets of what is off + m_sky.init(); + m_weather.init(); + m_instancecull.init(); + for (auto &shadowcull : m_shadowcull) + shadowcull.init(&m_instancecull); + m_hiz.init(); + m_timbers.init(); + m_shadowfit.init(); + m_exposure.init(); + m_ao.init(); + m_localshadows.init(); + m_cabprobe.init(); + m_skyocclusion.init(); // better initialize with 0 to not crash driver/whole system // when we forget @@ -1488,7 +1557,10 @@ void opengl46_renderer::draw_debug_ui() if (ImGui::Begin("Instance culling")) { char const *modes[]{"cpu", "gpu, drawn from its result", "cpu, compared with the gpu"}; - ImGui::Combo("instance culling (gfx.gpucull)", &Global.gfx_gpucull, modes, IM_ARRAYSIZE(modes)); + if (m_instancecull.available()) + ImGui::Combo("instance culling (gfx.gpucull)", &Global.gfx_gpucull, modes, IM_ARRAYSIZE(modes)); + else + ImGui::TextUnformatted("(instance culling on the gpu not available, see the log)"); if (Global.gfx_gpucull == 1) { ImGui::Checkbox("leave out instances hidden behind the depth drawn before them (gfx.gpucull.occlusion)", &Global.gfx_gpucull_occlusion); @@ -1622,16 +1694,77 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) // vehicle (V is along the front of the vehicle) glm::dvec3 air{glm::dvec3{simulation::Environment.wind()} * 0.5}; if (TDynamicObject const *owner = Global.pCamera.m_owner) - air -= owner->VectorFront() * owner->MoverParameters->V; + air -= owner->VectorFront() * owner->Speed(); scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->MoverParameters->CabActive) + // the wipers of the vehicle the camera is in, or of the train driven when the camera is outside it: the moments the blades + // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass + // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle. the views from outside + // (freefly, the views of the consist) put the camera at any vehicle of the train, one with an active cab of its own too: they + // follow the train driven, so going round them doesn't wipe the insects and the memory of the blades + TDynamicObject const *owner = FreeFlyModeFlag ? nullptr : Global.pCamera.m_owner; + if ((owner == nullptr) || (owner->ActiveCab() == 0)) + owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; + if (owner != m_wipervehicle) { + m_wipervehicle = owner; + scene_ubs.wiper_timer_out = glm::vec4{-1000.}; + scene_ubs.wiper_timer_return = glm::vec4{-1000.}; + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + for (auto &pass : scene_ubs.wiper_rain_pass) + pass = glm::vec4{-1.f}; + m_wiperlastpos.fill(-1.0); + m_wiperbugs = 0.0; + } + // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of + // driving at 100 km/h. none in winter, and the rain or the snow washes them off: once it stops (and out of winter) the glass + // gets them anew from none, and what the blades left of them before is forgotten + // the glass meets the insects and the rain once a frame, not once a view (the views of a frame have its time) + auto const glassstep{(scene_ubs.time != m_glasssteptime) ? Timer::GetDeltaTime() : 0.0}; + m_glasssteptime = scene_ubs.time; + auto const insects{(Global.Season != "winter:") && (Global.Weather != "rain:") && (Global.Weather != "snow:")}; + if (false == insects) + { + if (m_wiperbugs > 0.0) + { + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + } + m_wiperbugs = 0.0; + } + else if (owner != nullptr) + m_wiperbugs += glassstep * std::max(std::abs(owner->Speed()) * 3.6 - 20.0, 0.0) / 80.0; + scene_ubs.rain_wind.w = static_cast(m_wiperbugs); + // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while + // it rains, and is clear at once when it doesn't (the rain stopped, or the glass holds snow) + { + constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) + constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain + auto const dt{glassstep}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->Speed()) * 3.6 / 100.0, 1.0) : 0.0}; + auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; + m_wiperrain += dt * meet; + if ((percipitation_intensity > 0.f) && (Global.Weather == "rain:")) + m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + else + m_glasswet = 0.0; + // w: the cells of the rain worked out in this frame (set again once they are, below), the glasses read them only then + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), m_windscreenwater.rain_cells_valid() ? 1.f : 0.f}; + } + if (owner != nullptr) + { + auto const cabactive{owner->ActiveCab() != 0 ? owner->ActiveCab() : 1}; for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->MoverParameters->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + // the places of its sweep the blade went over since the last frame get the rain fallen now + auto const position{owner->dWiperPos[index]}; + gl::wiper_pass_mark(scene_ubs, i, (m_wiperlastpos[i] < 0.0) ? position : m_wiperlastpos[i], position, static_cast(m_wiperrain)); + m_wiperlastpos[i] = position; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1640,10 +1773,12 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (owner->dWiperPos[index] < .025) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; + scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; + scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); } } else @@ -1651,14 +1786,16 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.wiper_pos[i] = 0.; scene_ubs.wiper_timer_out[i] = -1000.; scene_ubs.wiper_timer_return[i] = -1000.; + scene_ubs.wiper_bugs_out[i] = -1.; + scene_ubs.wiper_bugs_return[i] = -1.; + gl::wiper_pass_mark(scene_ubs, i, 0.0, 1.0, -1.f); + m_wiperlastpos[i] = -1.0; } } } else { scene_ubs.wiper_pos = glm::vec4{0.}; - scene_ubs.wiper_timer_out = glm::vec4{-1000.}; - scene_ubs.wiper_timer_return = glm::vec4{-1000.}; } } // the reflections: the ground below the horizon of the environment map, and the screen space ones set up for the colour @@ -1669,11 +1806,25 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) m_skyocclusion.setup_scene(scene_ubs, m_colorpass.pass_camera.position()); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse( glm::mat4{ glm::mat3{ m_colorpass.pass_camera.modelview() } } ); + scene_camera_place( scene_ubs, m_colorpass.pass_camera.position() ); scene_ubo->update(scene_ubs); scene_ubo->bind_uniform(); // the water on the windscreens of the cab: a step of its simulation once a frame, its storage for the glasses of every view if (vp.main) + { m_windscreenwater.update(Timer::GetDeltaTime()); + // the drops and the rivulets of the glasses with rain, for the time of the block of the scene + // (the drops a cell may hold: as many as the glass is wet) + // (none for a cab without a glass of the rain) + m_windscreenwater.update_rain_cells(scene_ubs.time, ((scene_ubs.rain_state.y > 0.001f) && m_windscreenwater.wants_rain_cells()) ? std::min(scene_ubs.rain_state.y + 0.01f, 1.f) : 0.f); + // whether the glasses read the cells: as they are now + auto const cellsvalid{m_windscreenwater.rain_cells_valid() ? 1.f : 0.f}; + if (scene_ubs.rain_state.w != cellsvalid) + { + scene_ubs.rain_state.w = cellsvalid; + scene_ubo->update(scene_ubs); + } + } m_windscreenwater.bind(); if (Global.bWireFrame) @@ -1743,16 +1894,18 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) if (vp.main && (Global.pCamera.m_owner != nullptr)) m_freecamera.reset(); auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; - // the motion blur only when something in the view moves: the vehicle of the camera, the camera with no vehicle of its own, - // or a vehicle drawn in the last frame. - // with nothing moving the velocity is zero everywhere, the blur takes a single sample of each pixel and gives back the - // image it was given, so the velocity target, its resolve and the blur are left out and the picture stays the same. - // a vehicle setting off is blurred from its second frame, when its velocity is still far below a pixel - auto const motionblur{ + // the motion is blurred only when something in the view moves: the vehicle of the camera, the camera with no vehicle of its + // own, or a vehicle drawn in the last frame (a vehicle setting off is blurred from its second frame, when its velocity is + // still far below a pixel). the pass itself runs also when a glass in the view may ask it in the velocity target for the + // picture in its drops and its haze (mat_rain_windscreen, mat_bugs_windscreen, mat_snow_windscreen), standing still, with the + // motion blur off and with any anti-aliasing: the motion is then blurred by 0. with neither the velocities aren't drawn + // (but for the taa), the pass is left out + auto const moving{ Global.gfx_postfx_motionblur_enabled && (m_vehiclesmoved || (freecameramovement != glm::vec3{0.f}) || ((Global.pCamera.m_owner != nullptr) && (Global.pCamera.m_owner->get_future_movement() != glm::dvec3{0.0})))}; + auto const motionblur{Global.gfx_motion_vectors() && (vp.main_texv != nullptr) && (moving || m_windscreenwater.wants_glass_requests())}; if (!Global.gfx_skippipeline) { @@ -1852,6 +2005,7 @@ void opengl46_renderer::Render_pass(viewport_config &vp, rendermode const Mode) scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); // back to the rotation of the camera after the faces of the environment map, which are drawn with their own scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_colorpass.pass_camera.modelview()}}); + scene_camera_place(scene_ubs, m_colorpass.pass_camera.position()); scene_ubo->update(scene_ubs); Render(&simulation::Environment); @@ -2063,7 +2217,7 @@ if (!Global.gfx_skippipeline) { if (taa) gpupart("motion blur"); - model_ubs.param[0].x = m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter); + model_ubs.param[0].x = moving ? m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter) : 0.0; model_ubo->update(model_ubs); m_pfx_motionblur->apply({image, vp.main_texv.get(), vp.main_texd.get()}, vp.main2_fb.get()); } @@ -2110,7 +2264,9 @@ if (!Global.gfx_skippipeline) if (Global.gfx_postfx_bloom && vp.bloom) { bloomtexture = m_exposure.bloom(*vp.bloom, *vp.main2_tex, *model_ubo, model_ubs); - bloomlevels = vp.bloom->sizes.size(); + // none when its programs aren't there + if (bloomtexture != nullptr) + bloomlevels = vp.bloom->sizes.size(); } model_ubs.param[0] = m_exposure.tonemap_params(bloomlevels); // the dither goes to the last pass before the window: the chromatic aberration, when it follows @@ -2208,6 +2364,10 @@ if (!Global.gfx_skippipeline) glViewport(0, 0, m_shadowbuffersize, m_shadowbuffersize); auto csmstageboundaries { Shadow_Fixed_Splits() }; + // the rotation of the camera of the view, given back to the scene block after the cascades + auto const colorinvview { scene_ubs.inv_view }; + auto const colorcamerahi { scene_ubs.camera_hi }; + auto const colorcameralo { scene_ubs.camera_lo }; // the cascades fitted to the depth of the view (gfx.shadow.sdsm) go between the distances of its pixels, each map // covering the area of the pixels its cascade takes std::array>, gl::MAX_CASCADES> fitareas; @@ -2235,6 +2395,10 @@ if (!Global.gfx_skippipeline) setup_matrices(); scene_ubs.projection = OpenGLMatrices.data( GL_PROJECTION ); + // the rotation of the camera of this pass (the sun's): the shaders which put the model in the world (mat_vat.vert, the + // moment of the animation of every one of the people from its turn) see the same turn as in the color pass + scene_ubs.inv_view = glm::inverse( glm::mat4{ glm::mat3{ m_renderpass.pass_camera.modelview() } } ); + scene_camera_place( scene_ubs, m_renderpass.pass_camera.position() ); auto const csmstagezfar { (csmstageboundaries[ idx + 1 ]) + ( m_shadowpass.size() - idx ) }; // we can fairly safely add some extra padding in the early stages @@ -2253,6 +2417,10 @@ if (!Global.gfx_skippipeline) } } m_shadow_fb->unbind(); + scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; + scene_ubo->update( scene_ubs ); glDebug("rendermode::shadows end"); @@ -2289,6 +2457,7 @@ if (!Global.gfx_skippipeline) scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); // world space directions of the shading of the face (the sky, the directional ambient light) scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}}); + scene_camera_place(scene_ubs, m_renderpass.pass_camera.position()); scene_ubo->update(scene_ubs); Render(&simulation::Environment); // the passes after this one expect the state the opaque scenery left behind (depth writes on, no blending) @@ -3221,7 +3390,19 @@ std::shared_ptr opengl46_renderer::Fetch_Shader(const std:: if (it == m_shaders.end()) { gl::shader fragment("mat_" + name + ".frag"); - gl::program *program = new gl::program({fragment, *m_vertex_shader.get()}); + gl::program *program{nullptr}; + // a material can move its vertices in a vertex shader of its own, mat_.vert (people animated by textures, + // mat_vat.vert), the others take the common one + if (std::filesystem::exists(gfx::shader_source_dir(gfx::shader_api::opengl46) + "mat_" + name + ".vert")) + { + gl::shader vertex("mat_" + name + ".vert"); + program = new gl::program({fragment, vertex}); + m_ownvertexprograms.insert(program); + } + else + { + program = new gl::program({fragment, *m_vertex_shader.get()}); + } m_shaders.insert({name, std::shared_ptr(program)}); // the variant for the multi draws of the instances, made now rather than when the instances first come into view if ((Global.gfx_gpucull == 1) && Global.gfx_gpucull_multidraw) @@ -3456,6 +3637,24 @@ void opengl46_renderer::Bind_Material_Shadow(material_handle const Material) { auto &material = m_materials.material(Material); + if (false == m_cubeshadows) + { + // a material which moves its vertices itself casts the shadow of where they are: its vertex shader, with the + // textures and the params it reads them by + if (auto *program{Material_Shadow_Program(Material, material.textures[0] != null_handle)}) + { + for (std::size_t unit = 0; unit < gl::MAX_TEXTURES; ++unit) + { + if (material.textures[unit] == null_handle) + break; + m_textures.bind(unit, material.textures[unit]); + } + memcpy(&model_ubs.param[0], &material.params[0], sizeof(model_ubs.param)); + program->bind(); + return; + } + } + if (material.textures[0] != null_handle) { m_textures.bind(0, material.textures[0]); @@ -3661,7 +3860,8 @@ int opengl46_renderer::Prepass_Class( material_handle const Material ) "detail_normalmap", "detail_normalmap_specgloss", "normalmap", "normalmap_specgloss", "reflmap", "reflmap_specgloss", "shadowlessnormalmap", "shadowlessnormalmap_specgloss", "sunlessnormalmap", "sunlessnormalmap_specgloss", - "trackblend", "trackblend_normalmap", "trackblend_specgloss" }; + "trackblend", "trackblend_normalmap", "trackblend_specgloss", + "pbr", "pbr_detail", "pbr_coat" }; static std::unordered_set const solid { "colored", "default_0", "terrain", "water", "water_specgloss", "invalid" }; auto prepassclass { 0 }; for( auto const &shader : m_shaders ) { @@ -3911,8 +4111,11 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ ++index; continue; } - if( prepassclass == 2 ) { - m_textures.bind( 0, texture ); + // a texture which isn't there (yet) would leave the one bound before to the alpha test. the draw is left to the colour + // pass, which tests and writes its depth as usual + if( ( prepassclass == 2 ) && ( false == m_textures.mark_as_used( texture ).bind( 0 ) ) ) { + ++index; + continue; } auto const &draw { m_indirectdraws[ index ] }; if( multidrawprogram != nullptr ) { @@ -4015,8 +4218,16 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ for( std::size_t index = 0; index < count; ) { auto const &draw { m_indirectdraws[ index ] }; auto const texture { Indirect_Shadow_Texture( draw.material ) }; + if( ( texture != null_handle ) && ( false == m_textures.mark_as_used( texture ).bind( 0 ) ) ) { + // a texture which isn't there (yet) would leave the one bound before to the alpha test; no shadow until it is + ++index; + continue; + } + // the materials with a vertex shader of their own are drawn one by one, with it (Bind_Material_Shadow()) + auto const ownvertex = [ this ]( material_handle const Material ) { + return ( false == m_cubeshadows ) && ( Material_Shadow_Program( Material, Indirect_Shadow_Texture( Material ) != null_handle ) != nullptr ); }; auto *multidrawprogram { - m_indirectmultidraw ? + ( m_indirectmultidraw && ( false == ownvertex( draw.material ) ) ) ? ( m_cubeshadows ? m_localshadows.multidraw_program( texture != null_handle ) : ( texture != null_handle ? m_alpha_shadow_multidraw_shader.get() : m_shadow_multidraw_shader.get() ) ) : @@ -4028,12 +4239,10 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ && ( m_indirectdraws[ last ].group == draw.group ) && ( m_indirectdraws[ last ].type == draw.type ) && ( m_indirectcommands[ last ].indexed == m_indirectcommands[ index ].indexed ) - && ( Indirect_Shadow_Texture( m_indirectdraws[ last ].material ) == texture ) ) { + && ( Indirect_Shadow_Texture( m_indirectdraws[ last ].material ) == texture ) + && ( false == ownvertex( m_indirectdraws[ last ].material ) ) ) { ++last; } - if( texture != null_handle ) { - m_textures.bind( 0, texture ); - } multidrawprogram->bind(); auto const drawcount { static_cast( last - index ) }; Bind_Indirect_Blocks( index, drawcount ); @@ -4042,8 +4251,10 @@ opengl46_renderer::indirect_counts opengl46_renderer::Render_Instances_Indirect_ index = last; } else { - Bind_Material_Shadow( draw.material ); + // the block of the draw first: Bind_Material_Shadow() puts the params of the material in it, for the materials which + // read them in their vertex shader model_ubs = draw.ubs; + Bind_Material_Shadow( draw.material ); model_ubo->update( model_ubs ); m_geometry.draw_indirect( draw.geometry, m_indirectcull->draw_command_offset( Set, index ) ); ++counts.draws; @@ -4108,7 +4319,14 @@ gl::program *opengl46_renderer::Multidraw_Program( gl::program const *Program ) if( shader.second.get() != Program ) { continue; } try { gl::shader fragment( "mat_" + shader.first + ".frag", "#define MODEL_DRAWS 1\n" ); - variant = std::make_unique( std::vector>{ fragment, *m_vertex_multidraw_shader } ); + if( m_ownvertexprograms.count( Program ) > 0 ) { + // the vertex shader of the material itself, in its variant of the multi draws + gl::shader vertex( "mat_" + shader.first + ".vert", "#define MODEL_DRAWS 1\n" ); + variant = std::make_unique( std::vector>{ fragment, vertex } ); + } + else { + variant = std::make_unique( std::vector>{ fragment, *m_vertex_multidraw_shader } ); + } } catch( gl::shader_exception const &e ) { ErrorLog( "material " + shader.first + " drawn without multi draws: " + std::string( e.what() ) ); @@ -4120,6 +4338,35 @@ gl::program *opengl46_renderer::Multidraw_Program( gl::program const *Program ) return result; } +gl::program *opengl46_renderer::Material_Shadow_Program( material_handle const Material, bool const Alphatest ) +{ + if( Material == null_handle ) { return nullptr; } + auto const &material { m_materials.material( Material ) }; + if( ( false == material.is_good ) || ( material.shader == nullptr ) ) { return nullptr; } + auto const *program { static_cast( material.shader.get() ) }; + if( m_ownvertexprograms.count( program ) == 0 ) { return nullptr; } + auto &programs { m_materialshadowprograms[ Alphatest ? 1 : 0 ] }; + auto const lookup { programs.find( program ) }; + if( lookup != programs.end() ) { return lookup->second.get(); } + + std::unique_ptr shadow; + for( auto const &shader : m_shaders ) { + if( shader.second.get() != program ) { continue; } + try { + gl::shader vertex( "mat_" + shader.first + ".vert", "#define MATERIAL_SHADOW 1\n" ); + gl::shader fragment( Alphatest ? "alphashadowmap.frag" : "shadowmap.frag" ); + shadow = std::make_unique( std::vector>{ vertex, fragment } ); + } + catch( gl::shader_exception const &e ) { + ErrorLog( "material " + shader.first + " casts its shadow in the pose of the model: " + std::string( e.what() ) ); + } + break; + } + auto *result { shadow.get() }; + programs.emplace( program, std::move( shadow ) ); + return result; +} + // depth of the whole opaque scene of the colour pass, before its colour. the same walk as the colour pass makes (the cab drawn // early, then the region), so the same things are seen at the same levels of detail; the programs of the depth prepass draw // them (Bind_Material(), draw()), with the depth a little farther than the surface like the prepass of the instances, so the @@ -4187,8 +4434,9 @@ void opengl46_renderer::Render_Scene_Depth( glm::mat4 const &Future, bool const m_scenerecordedparts = static_cast( m_scenechunks.size() ); } else { - // the conditions of the cab drawn early by the colour pass - if( ( false == FreeFlyModeFlag ) && ( Global.Overcast <= 1.0f ) && ( Global.render_cab ) ) { + // the cab first, also in the rain: the colour pass draws it after the rain then (the rain inside it hidden), but with its depth + // here nothing the cab hides is shaded by the opaque pass + if( ( false == FreeFlyModeFlag ) && ( Global.render_cab ) ) { model_ubs.future = m_cabfuture; auto const *vehicle { simulation::Train->Dynamic() }; Render_cab( vehicle, vehicle->InteriorLightLevel, false ); @@ -5031,7 +5279,7 @@ std::uint32_t opengl46_renderer::walk_instances(glm::mat4 const *Modelviews, std bool opengl46_renderer::walk_timbers_gpu() const { - return true; + return m_timbers.gpu(); } bool opengl46_renderer::walk_timbers_place(std::vector const &Tracks, bool const Restart) @@ -5099,28 +5347,109 @@ void opengl46_renderer::walk_glare(bool const Enabled) } } +// the frames a result of the glare queries is good for: a point not drawn for longer may have something else in front of it now +constexpr unsigned int GLARE_RESULT_FRAMES{2}; +// the frames after which the entries of points no longer drawn are dropped +constexpr unsigned int GLARE_KEEP_FRAMES{600}; + +opengl46_renderer::glare_visibility *opengl46_renderer::glare_entry(TSubModel const *Submodel, bool const Create) +{ + glare_key const key{Submodel, TSubModel::iInstance}; + if (false == Create) + { + auto const lookup{m_glares.find(key)}; + return (lookup != m_glares.end() ? &lookup->second : nullptr); + } + if (m_framestamp - m_glarepruned > GLARE_KEEP_FRAMES) + { + m_glarepruned = m_framestamp; + auto const framestamp{m_framestamp}; + // a query whose result nobody reads any more is deleted along + std::erase_if(m_glares, [framestamp](auto const &Entry) { return framestamp - Entry.second.frame > GLARE_KEEP_FRAMES; }); + } + return &m_glares.try_emplace(key).first->second; +} + +void opengl46_renderer::glare_read(glare_visibility &Entry) +{ + // the results once the gpu has both of them, nothing waits for them + auto const seen{Entry.seen.result()}; + if (false == seen.has_value()) + { + return; + } + auto const all{Entry.all.result()}; + if (false == all.has_value()) + { + return; + } + Entry.pending = false; + Entry.share = (*all > 0 ? std::clamp(static_cast(*seen) / static_cast(*all), 0.f, 1.f) : 0.f); +} + void opengl46_renderer::walk_glare_draw(TSubModel *Submodel, gfx::geometry_handle const &Geometry) { - if (Submodel->occlusion_query) { - glBeginConditionalRender(*Submodel->occlusion_query, GL_QUERY_WAIT); + if (false == gl::vao::use_vao) + { draw(Geometry); - glEndConditionalRender(); + return; } - else - draw(Geometry); + // as bright as the part of the point seen in the main view, by the results of an earlier frame; none for a point not seen + // lately + auto const *entry{glare_entry(Submodel, false)}; + if ((entry == nullptr) || (m_framestamp - entry->frame > GLARE_RESULT_FRAMES) || (entry->share <= 0.f)) + { + return; + } + auto const opacity{model_ubs.param[0].w}; + model_ubs.param[0].w = opacity * entry->share; + draw(Geometry); + model_ubs.param[0].w = opacity; } void opengl46_renderer::walk_light_query(TSubModel *Submodel, bool const Begin) { - if (false == gl::vao::use_vao) + if ((false == gl::vao::use_vao) || (m_renderpass.draw_mode != rendermode::color) || (m_current_viewport == nullptr) || (false == m_current_viewport->main)) + { return; - if (Begin) { - if (!Submodel->occlusion_query) - Submodel->occlusion_query.emplace(gl::query::ANY_SAMPLES_PASSED); - Submodel->occlusion_query->begin(); } - else - Submodel->occlusion_query->end(); + if (false == Begin) + { + if (m_glarequery == nullptr) + { + return; + } + m_glarequery->seen.end(); + // the whole point, unseen: what the samples seen are compared with + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + glDisable(GL_DEPTH_TEST); + m_glarequery->all.begin(); + draw(Submodel->m_geometry.handle); + m_glarequery->all.end(); + glEnable(GL_DEPTH_TEST); + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + m_glarequery->pending = true; + m_glarequery = nullptr; + return; + } + auto &entry{*glare_entry(Submodel, true)}; + if (m_framestamp - entry.frame > GLARE_RESULT_FRAMES) + { + // not drawn lately: what it saw then is no good, it starts over unseen + entry.share = 0.f; + entry.pending = false; + } + entry.frame = m_framestamp; + if (entry.pending) + { + glare_read(entry); + } + if (false == entry.pending) + { + // new queries once the results of the last ones are read + entry.seen.begin(); + m_glarequery = &entry; + } } void opengl46_renderer::walk_region_begin() @@ -5483,6 +5812,7 @@ void opengl46_renderer::Update_Pick_Control() void opengl46_renderer::Forget_Node(scene::basic_node const *Node) { + m_locallights.forget(Node); if (m_picksceneryitem == Node) m_picksceneryitem = nullptr; std::replace_if(m_picksceneryitems.begin(), m_picksceneryitems.end(), [Node](scene::basic_node const *Item) { return Item == Node; }, nullptr); @@ -5760,6 +6090,95 @@ std::string const &opengl46_renderer::info_stats() const return m_debugstatstext; } +std::pair opengl46_renderer::Prewarm_Shaders( double const Milliseconds ) +{ + auto &prewarm { m_prewarm }; + if( false == prewarm.started ) { + prewarm.started = true; + // the programs of the materials and their variants for the multi draws of the instances + for( auto const &shader : m_shaders ) { + if( shader.second != nullptr ) { prewarm.programs.emplace_back( shader.second.get() ); } + } + for( auto const &variant : m_multidrawprograms ) { + if( variant.second != nullptr ) { prewarm.programs.emplace_back( variant.second.get() ); } + } + // the formats and the samples of the colour pass (init_viewport()), 4 x 4 pixels + auto const samples { 1 << Global.iMultisampling }; + prewarm.color = std::make_unique(); + prewarm.color->alloc( Global.gfx_format_color, 4, 4, samples ); + prewarm.depth = std::make_unique(); + prewarm.depth->alloc( Global.gfx_format_depth, 4, 4, samples ); + prewarm.target = std::make_unique(); + prewarm.target->attach( *prewarm.color, GL_COLOR_ATTACHMENT0 ); + prewarm.target->attach( *prewarm.depth, GL_DEPTH_ATTACHMENT ); + if( Global.gfx_motion_vectors() ) { + prewarm.motion = std::make_unique(); + prewarm.motion->alloc( Global.gfx_postfx_motionblur_format, 4, 4, samples ); + prewarm.target->attach( *prewarm.motion, GL_COLOR_ATTACHMENT1 ); + } + // a triangle with no area: drawn, nothing comes of it, but the program is made ready for the state of the draw + gfx::vertex_array vertices( 3, gfx::basic_vertex( glm::vec3( 0.f ), glm::vec3( 0.f, 1.f, 0.f ), glm::vec2( 0.f ) ) ); + gfx::userdata_array userdata; + prewarm.bank = Create_Bank(); + prewarm.triangle = Insert( vertices, userdata, prewarm.bank, GL_TRIANGLES ); + if( false == m_multidrawprograms.empty() ) { + // the variants of the multi draws read the model block of the draw from a storage buffer, which the frames bind for + // their multi draws only. drawn here with a plain draw, they read the block of the draw 0; without a buffer there + // the draw would be undefined + prewarm.draws = std::make_unique( static_cast( sizeof( gl::model_ubs ) ), gl::MODEL_DRAW_SSBO_BINDING ); + prewarm.draws->update( model_ubs ); + } + if( false == prewarm.target->is_complete() ) { + ErrorLog( "the programs of the materials weren't prepared: the target of the drawing can't be made" ); + prewarm.next = prewarm.programs.size(); + } + WriteLog( "preparing " + std::to_string( prewarm.programs.size() ) + " programs of the materials before the first frame" ); + } + auto const total { prewarm.programs.size() + opengl46_windscreen_water::program_count() }; + if( prewarm.next >= prewarm.programs.size() ) { + // then the programs of the water on the windscreens, one at a time: the longest of all to compile, the first frame of the + // simulation made them before + if( ( false == prewarm.water_done ) && m_windscreenwater.prepare_next() ) { + ++prewarm.water; + } + else if( false == prewarm.water_done ) { + prewarm.water_done = true; + WriteLog( "the programs of the windscreen water prepared" ); + } + return { prewarm.water_done ? total : prewarm.next + prewarm.water, total }; + } + + auto const until { std::chrono::steady_clock::now() + std::chrono::duration( Milliseconds ) }; + prewarm.target->bind(); + prewarm.target->setup_drawing( prewarm.motion ? 2 : 1 ); + ::glViewport( 0, 0, 4, 4 ); + ::glEnable( GL_DEPTH_TEST ); + model_ubo->update( model_ubs ); + if( prewarm.draws != nullptr ) { + // every multi draw of a frame binds its own blocks there afterwards (Bind_Indirect_Blocks()) + prewarm.draws->bind_base(); + } + while( ( prewarm.next < prewarm.programs.size() ) && ( std::chrono::steady_clock::now() < until ) ) { + prewarm.programs[ prewarm.next ]->bind(); + // as the opaque things are drawn, and as the translucent ones are + ::glDisable( GL_BLEND ); + ::glDepthMask( GL_TRUE ); + m_geometry.draw( prewarm.triangle ); + ::glEnable( GL_BLEND ); + ::glDepthMask( GL_FALSE ); + m_geometry.draw( prewarm.triangle ); + ++prewarm.next; + } + ::glDisable( GL_BLEND ); + ::glDepthMask( GL_TRUE ); + gl::program::unbind(); + gl::framebuffer::unbind(); + if( prewarm.next >= prewarm.programs.size() ) { + WriteLog( "the programs of the materials prepared" ); + } + return { prewarm.next, total }; +} + void opengl46_renderer::MakeScreenshot() { // rows are tightly packed RGB: the renderer sets GL_PACK_ALIGNMENT to 1 @@ -5882,6 +6301,7 @@ void opengl46_renderer::Preview_Color(TAnimModel *Instance, float const Squaredi scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{View}}); + scene_camera_place(scene_ubs, Eye); scene_ubs.time = 0.f; for (auto idx = 0; idx < m_shadowpass.size(); ++idx) { @@ -6603,7 +7023,7 @@ void opengl46_renderer::Render_lamp_shadow(std::size_t const Slot, bool const Ve void opengl46_renderer::Headlight_Projector(light_array::light_record const &Light, glm::dvec3 &Position, glm::mat3 &Rotation, glm::mat4 &Projection, float &Near, float &Fieldofview) { - auto const &ownerdimensions{Light.owner->MoverParameters->Dim}; + auto const &ownerdimensions{Light.owner->Dimensions()}; auto const up{static_cast(Light.owner->VectorUp())}; auto const size{static_cast(std::max(ownerdimensions.W, ownerdimensions.H) * 1.0)}; // ensure square ratio auto const cone{5.f}; @@ -6695,7 +7115,13 @@ void opengl46_renderer::Render_headlight_shadow(std::size_t const Slot, light_ar camera.update_frustum(glm::perspective(fieldofview, 1.f, nearplane, reach)); setup_matrices(); auto const colorprojection{scene_ubs.projection}; + auto const colorinvview{scene_ubs.inv_view}; + auto const colorcamerahi{scene_ubs.camera_hi}; + auto const colorcameralo{scene_ubs.camera_lo}; scene_ubs.projection = projection; + // the rotation and the place of the projector, as the ones of the sun in its shadows (see rendermode::shadows) + scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{camera.modelview()}}); + scene_camera_place(scene_ubs, camera.position()); scene_ubo->update(scene_ubs); m_localshadows.begin_headlight(Slot, projector, rotation, projection, Light.direction, m_framestamp); @@ -6711,6 +7137,9 @@ void opengl46_renderer::Render_headlight_shadow(std::size_t const Slot, light_ar m_shadowskipvehicle = nullptr; m_localshadows.end_headlight(static_cast(m_renderpass.draw_stats.drawcalls)); scene_ubs.projection = colorprojection; + scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; scene_ubo->update(scene_ubs); m_renderpass = m_colorpass; glPolygonMode(GL_FRONT_AND_BACK, Global.bWireFrame ? GL_LINE : GL_FILL); @@ -7073,6 +7502,7 @@ bool opengl46_renderer::Init_caps() WriteLog("shadows map size capped at " + std::to_string(m_shadowbuffersize) + "p"); } + clamp_multisampling(); if (Global.iMultisampling) { WriteLog("using multisampling x" + std::to_string(1 << Global.iMultisampling)); diff --git a/rendering/opengl46/opengl46renderer.h b/rendering/opengl46/opengl46renderer.h index 08d92e4b7..2f50985d1 100644 --- a/rendering/opengl46/opengl46renderer.h +++ b/rendering/opengl46/opengl46renderer.h @@ -54,6 +54,10 @@ http://mozilla.org/MPL/2.0/. #include "rendering/common/freecameramotion.h" #include "rendering/common/screenreflections.h" +#include +#include +#include + // bare-bones render controller, in lack of anything better yet class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { public: @@ -183,6 +187,7 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { std::vector const & info_sections() const override; void MakeScreenshot() override; + std::pair Prewarm_Shaders( double const Milliseconds ) override; bool Render_Preview( TAnimModel *Instance, int const Size, int const Margin, bool const Shadows, std::vector &Image ) override; @@ -412,6 +417,10 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // the variant of a material program for multi draws (built with MODEL_DRAWS), made the first time it's asked for. // nullptr if there's none (a program not fetched by Fetch_Shader(), or one which didn't compile) gl::program *Multidraw_Program( gl::program const *Program ); + // the program of the sun shadows of a material which moves its vertices in its own vertex shader (mat_.vert, see + // Fetch_Shader()): that shader with MATERIAL_SHADOW and the shadow fragment shader (Alphatest: alphashadowmap.frag). + // nullptr for the materials of the common vertex shader, which the shadow programs draw as they are + gl::program *Material_Shadow_Program( material_handle const Material, bool const Alphatest ); // how the depth prepass treats the material: 0 left out, 1 drawn without alpha test, 2 with the alpha test of the diffuse texture int Prepass_Class( material_handle const Material ); // depth of the whole opaque scene of the colour pass, before its colour (Global.gfx_depthprepass_scene): the colour pass @@ -650,6 +659,28 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // programs of the multi draws: the vertex shader of the materials, variants of the material programs, of the depth prepass std::unique_ptr m_vertex_multidraw_shader; std::unordered_map> m_multidrawprograms; + // the material programs with a vertex shader of their own (mat_.vert), and their programs of the sun shadows + std::unordered_set m_ownvertexprograms; + std::unordered_map> m_materialshadowprograms[ 2 ]; + // Prewarm_Shaders(): the programs to draw with, the next one, and a small target of the formats of the colour pass with a + // triangle of no area to draw + struct shader_prewarm + { + bool started{ false }; + std::vector programs; + std::size_t next{ 0 }; + std::size_t water{ 0 }; // programs of the windscreen water made ahead + bool water_done{ false }; + std::unique_ptr color; + std::unique_ptr depth; + std::unique_ptr motion; + std::unique_ptr target; + // one model block for the variants of the multi draws, which read theirs from a storage buffer (MODEL_DRAW_SSBO_BINDING) + std::unique_ptr draws; + gfx::geometrybank_handle bank{}; + gfx::geometry_handle triangle{}; + }; + shader_prewarm m_prewarm; std::unique_ptr m_prepass_multidraw_shader; std::unique_ptr m_prepass_alpha_multidraw_shader; std::unique_ptr m_shadow_multidraw_shader; // and of the sun shadows @@ -844,6 +875,17 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { // persistently mapped with Global.gfx_bufferstreaming std::unique_ptr m_instancestream; gl::scene_ubs scene_ubs; + // the vehicle whose wipers the timers of the blades in scene_ubs (wiper_timer_out / wiper_timer_return) follow + TDynamicObject const *m_wipervehicle{nullptr}; + // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) + double m_wiperbugs{0.0}; + // the place of each blade (dWiperPos) the last frame, -1 not known: the places it went over since get the rain fallen + // (gl::wiper_pass_mark) + std::array m_wiperlastpos{-1.0, -1.0, -1.0, -1.0}; + // the rain the glass met so far and how wet it is (scene_ubs::rain_state) + double m_wiperrain{0.0}; + double m_glasswet{0.0}; + double m_glasssteptime{-1.0}; // the time of the frame the glass last met the insects and the rain in gl::light_data light_data; std::unordered_map> m_shaders; @@ -854,6 +896,37 @@ class opengl46_renderer : public gfx_renderer, public gfx::scene_walk { unsigned int m_editor_overlay_revision{0}; std::unique_ptr m_freespot_shader; std::unique_ptr m_billboard_shader; + // the glare of a light point is as bright as the part of its point seen in the main view, counted by a pair of occlusion + // queries of its own for each light point of each model (the submodel and the instance drawn, TSubModel::iInstance): the + // samples which passed the depth test and all of them. the results are read once the gpu has them, without waiting, so the + // glare follows its point a frame or two late + struct glare_key + { + TSubModel const *submodel{nullptr}; + std::uintptr_t instance{0}; + bool operator==(glare_key const &) const = default; + }; + struct glare_key_hash + { + std::size_t operator()(glare_key const &Key) const + { + return std::hash{}(Key.submodel) ^ (std::hash{}(Key.instance) * 31u); + } + }; + struct glare_visibility + { + gl::query seen{gl::query::SAMPLES_PASSED}; + gl::query all{gl::query::SAMPLES_PASSED}; + bool pending{false}; // the queries were issued and their results aren't read yet + float share{0.f}; // the part of the point seen, by the last results read + unsigned int frame{0}; // the frame the point was last drawn in the main view + }; + // the visibility of the point the walk draws, for the queries around it (walk_light_query()) + glare_visibility *glare_entry(TSubModel const *Submodel, bool Create); + static void glare_read(glare_visibility &Entry); + std::unordered_map m_glares; + glare_visibility *m_glarequery{nullptr}; // the entry whose queries are under way + unsigned int m_glarepruned{0}; // the frame the entries of points no longer drawn were last dropped std::unique_ptr m_celestial_shader; std::unique_ptr m_hiddenarea_shader; std::unique_ptr m_copy_shader; diff --git a/rendering/opengl46/opengl46shadowfit.cpp b/rendering/opengl46/opengl46shadowfit.cpp index d84c557c0..bdbe87437 100644 --- a/rendering/opengl46/opengl46shadowfit.cpp +++ b/rendering/opengl46/opengl46shadowfit.cpp @@ -12,8 +12,11 @@ http://mozilla.org/MPL/2.0/. #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + opengl46_shadow_fit::~opengl46_shadow_fit() { release(); @@ -25,8 +28,20 @@ void opengl46_shadow_fit::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_depthprogram = make_compute("shadow_fit_depth.comp"); - m_boundsprogram = make_compute("shadow_fit_bounds.comp"); + try + { + m_depthprogram = make_compute("shadow_fit_depth.comp"); + m_boundsprogram = make_compute("shadow_fit_bounds.comp"); + } + catch (gl::shader_exception const &e) + { + // the cascades keep to their fixed splits + ErrorLog(std::format("sun shadows fitted to the depth not available: {}", e.what())); + m_depthprogram.reset(); + m_boundsprogram.reset(); + Global.gfx_shadow_sdsm = false; + return; + } m_buffer = std::make_unique(sizeof(gl::shadow_fit_data), gl::SHADOW_FIT_SSBO_BINDING); m_readback = std::make_unique(sizeof(gl::shadow_fit_data)); } @@ -60,7 +75,7 @@ void opengl46_shadow_fit::allocate(int const Width, int const Height) void opengl46_shadow_fit::measure(GLuint const Depth, GLuint const Source, int const Width, int const Height, view const &View, unsigned int const Frame) { - if ((Width <= 0) || (Height <= 0) || (View.range <= 0.f)) + if ((Width <= 0) || (Height <= 0) || (View.range <= 0.f) || (m_boundsprogram == nullptr)) return; m_timer.begin(); diff --git a/rendering/opengl46/opengl46shadowfit.h b/rendering/opengl46/opengl46shadowfit.h index dfc162b49..7accf75a0 100644 --- a/rendering/opengl46/opengl46shadowfit.h +++ b/rendering/opengl46/opengl46shadowfit.h @@ -32,7 +32,8 @@ class opengl46_shadow_fit : public gfx::shadow_fit opengl46_shadow_fit(const opengl46_shadow_fit &) = delete; opengl46_shadow_fit &operator=(const opengl46_shadow_fit &) = delete; - // creates the programs and the buffer. throws gl::shader_exception + // creates the programs and the buffer. without the programs (a shader which doesn't compile) nothing is measured: logged, + // and gfx.shadow.sdsm switched off void init(); // measures the depth of the view: Depth, its resolved depth texture of Width x Height pixels, or 0 to resolve the depth // attachment of Source, the multisampled framebuffer, into a texture of its own. Frame: the frame of the renderer. diff --git a/rendering/opengl46/opengl46sky.cpp b/rendering/opengl46/opengl46sky.cpp index ed21906a4..9f87800a5 100644 --- a/rendering/opengl46/opengl46sky.cpp +++ b/rendering/opengl46/opengl46sky.cpp @@ -11,9 +11,11 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46sky.h" #include +#include #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" @@ -47,11 +49,33 @@ void opengl46_sky::init() gl::shader shader(Name); return std::make_unique(std::vector>{shader}); }; - m_transmittance_program = make_compute("atmosphere_transmittance.comp"); - m_multiscattering_program = make_compute("atmosphere_multiscattering.comp"); - m_skyview_program = make_compute("atmosphere_skyview.comp"); - m_ambient_program = make_compute("atmosphere_ambient.comp"); - m_prefilter_program = make_compute("envmap_prefilter.comp"); + try + { + m_transmittance_program = make_compute("atmosphere_transmittance.comp"); + m_multiscattering_program = make_compute("atmosphere_multiscattering.comp"); + m_skyview_program = make_compute("atmosphere_skyview.comp"); + m_ambient_program = make_compute("atmosphere_ambient.comp"); + } + catch (gl::shader_exception const &e) + { + // the sky of the sky dome, as without the atmosphere + ErrorLog(std::format("physical atmosphere not available: {}", e.what())); + m_transmittance_program.reset(); + m_multiscattering_program.reset(); + m_skyview_program.reset(); + m_ambient_program.reset(); + Global.gfx_atmosphere = false; + } + try + { + m_prefilter_program = make_compute("envmap_prefilter.comp"); + } + catch (gl::shader_exception const &e) + { + // the rough reflections keep to the mipmaps of the environment map + ErrorLog(std::format("rough reflections of the environment map not available: {}", e.what())); + Global.gfx_envmap_ggx = false; + } m_sky_ssbo = std::make_unique(sizeof(gl::sky_data), gl::SKY_SSBO_BINDING); m_sky_ssbo->update(m_sky_data); @@ -75,6 +99,8 @@ void opengl46_sky::bind() void opengl46_sky::update_atmosphere(glm::vec3 const &Sundirection) { + if (m_ambient_program == nullptr) + return; bool mediumchanged{false}; if (false == m_light.atmosphere_changed(Sundirection, mediumchanged)) return; @@ -151,6 +177,8 @@ glm::vec3 opengl46_sky::sun_disc_color(glm::vec3 const &Oldcolor) const void opengl46_sky::prefilter(gl::cubemap const &Source) { + if (m_prefilter_program == nullptr) + return; if (!m_prefiltered) { m_prefiltered = std::make_unique(); diff --git a/rendering/opengl46/opengl46sky.h b/rendering/opengl46/opengl46sky.h index 7cc44a2cc..c5fbba8c1 100644 --- a/rendering/opengl46/opengl46sky.h +++ b/rendering/opengl46/opengl46sky.h @@ -43,7 +43,8 @@ class opengl46_sky opengl46_sky(const opengl46_sky &) = delete; opengl46_sky &operator=(const opengl46_sky &) = delete; - // creates the buffers, tables and programs. throws gl::shader_exception + // creates the buffers, tables and programs. a shader which doesn't compile is logged, and gfx.atmosphere or gfx.envmap.ggx + // switched off void init(); // binds the buffers the shaders read; bindings are context state, so done in every context void bind(); diff --git a/rendering/opengl46/opengl46timbers.cpp b/rendering/opengl46/opengl46timbers.cpp index e6d122ff6..39579ed84 100644 --- a/rendering/opengl46/opengl46timbers.cpp +++ b/rendering/opengl46/opengl46timbers.cpp @@ -11,15 +11,20 @@ http://mozilla.org/MPL/2.0/. #include "rendering/opengl46/opengl46timbers.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "world/Track.h" +#include #include +#include namespace { // the buffer to start with, and how soon after being started over it's too small for the tracks in sight std::uint32_t constexpr initial_capacity{65536}; unsigned int constexpr restart_frames{600}; +// how much bigger than the room for the instances to place a buffer grows by being started over soon +std::uint64_t constexpr restart_growth{8}; // the instances of a track, in the order they lie in the buffer std::uint32_t count_of(track_sleepers::laid const &Laid) @@ -30,6 +35,20 @@ std::uint32_t count_of(track_sleepers::laid const &Laid) return static_cast(count); } +// a buffer for Capacity instances, 0 when there's no memory for it +GLuint make_buffer(std::uint64_t const Capacity) +{ + GLuint buffer{0}; + glCreateBuffers(1, &buffer); + glNamedBufferStorage(buffer, static_cast(Capacity * sizeof(glm::mat4)), nullptr, GL_DYNAMIC_STORAGE_BIT); + if (::glGetError() == GL_OUT_OF_MEMORY) + { + glDeleteBuffers(1, &buffer); + return 0; + } + return buffer; +} + } // namespace opengl46_timbers::~opengl46_timbers() @@ -40,30 +59,58 @@ opengl46_timbers::~opengl46_timbers() void opengl46_timbers::init() { - gl::shader shader("timber_instances.comp"); - m_program = std::make_unique(std::vector>{shader}); + try + { + gl::shader shader("timber_instances.comp"); + m_program = std::make_unique(std::vector>{shader}); + } + catch (gl::shader_exception const &e) + { + // the walk turns the instances on the cpu + ErrorLog(std::format("track sleepers on the gpu not available: {}", e.what())); + m_gpu = false; + return; + } // the modelviews of the origins and the runs, both placed at whole matrices m_ranges = std::make_unique( static_cast(4096 * sizeof(gl::timber_range)), static_cast(sizeof(glm::mat4)), Global.gfx_bufferstreaming); restart(0); + m_gpu = (false == m_failed); } -void opengl46_timbers::restart(std::uint32_t const Needed) +bool opengl46_timbers::restart(std::uint32_t const Needed) { - auto capacity{std::max(m_capacity, initial_capacity)}; + // room for twice the instances to place, and when the buffer was started over not long before, the tracks in sight change + // fast: twice the buffer before, but not more than restart_growth times that room. a buffer started over later goes back to it + std::uint64_t minimum{initial_capacity}; + while (minimum < 2 * static_cast(Needed)) + minimum *= 2; + auto capacity{minimum}; if ((m_capacity > 0) && (m_frame - m_restartframe < restart_frames)) - capacity *= 2; - while (capacity < 2 * Needed) - capacity *= 2; + capacity = std::clamp(2 * static_cast(m_capacity), minimum, restart_growth * minimum); + auto buffer{make_buffer(capacity)}; + if ((buffer == 0) && (capacity > Needed)) + { + // no memory for the room to spare: only the instances to place + capacity = std::max(Needed, 1); + buffer = make_buffer(capacity); + } + if (buffer == 0) + { + // the old buffer stays, the tracks are turned on the cpu from the next frame on + ErrorLog("openGL error: out of memory; failed to create the buffer of the track sleepers, they're placed by the cpu"); + m_failed = true; + return false; + } // the draws and passes issued with the old buffer keep it until the gpu is done with them if (m_buffer != 0) glDeleteBuffers(1, &m_buffer); - glCreateBuffers(1, &m_buffer); - glNamedBufferStorage(m_buffer, static_cast(capacity) * static_cast(sizeof(glm::mat4)), nullptr, GL_DYNAMIC_STORAGE_BIT); - m_capacity = capacity; + m_buffer = buffer; + m_capacity = static_cast(capacity); m_fill = 0; m_restartframe = m_frame; m_tracks.clear(); + return true; } bool opengl46_timbers::place(std::vector const &Tracks, bool const Restart) @@ -85,9 +132,8 @@ bool opengl46_timbers::place(std::vector const &Tracks, bool const Res return true; if (m_fill + needed > m_capacity) { - if (false == Restart) + if ((false == Restart) || (false == restart(all))) return false; - restart(all); } for (auto const *track : Tracks) { @@ -148,5 +194,9 @@ void opengl46_timbers::expand(std::vector const &Origins, std::vector void opengl46_timbers::next_frame() { ++m_frame; - m_ranges->next_frame(); + if (m_ranges) + m_ranges->next_frame(); + // between the frames, so the walks of a frame all gather and draw the timbers the same way + if (m_failed) + m_gpu = false; } diff --git a/rendering/opengl46/opengl46timbers.h b/rendering/opengl46/opengl46timbers.h index 5790e8f2e..b09794d26 100644 --- a/rendering/opengl46/opengl46timbers.h +++ b/rendering/opengl46/opengl46timbers.h @@ -31,7 +31,7 @@ class opengl46_timbers opengl46_timbers &operator=(opengl46_timbers const &) = delete; ~opengl46_timbers(); - // throws gl::shader_exception + // without the program (a shader which doesn't compile) the walk turns the instances on the cpu (gpu()), logged void init(); // the instances of the tracks on the gpu, sent again for a track laid anew since; when those to send don't fit in what's left // of the buffer, it's started over for all the tracks, a bigger one when it was started over not long before. without @@ -43,6 +43,12 @@ class opengl46_timbers // the runs written to the instance buffer Output, each as the modelview of its origin times its transforms, for the draws after void expand(std::vector const &Origins, std::vector const &Ranges, GLuint const Output); void next_frame(); + // the instances are kept and turned on the gpu; false from the frame after a buffer for them couldn't be had, then the walk + // turns them on the cpu + bool gpu() const + { + return m_gpu; + } private: struct placed @@ -51,8 +57,8 @@ class opengl46_timbers std::uint32_t first; }; - // a new buffer, room for Needed instances at least, the tracks to be sent again - void restart(std::uint32_t const Needed); + // a new buffer, room for Needed instances at least, the tracks to be sent again. false: no memory for it, the old one stays + bool restart(std::uint32_t const Needed); std::unique_ptr m_program; std::unique_ptr m_ranges; @@ -61,6 +67,8 @@ class opengl46_timbers std::uint32_t m_fill{0}; unsigned int m_frame{0}; unsigned int m_restartframe{0}; + bool m_failed{false}; // a buffer couldn't be had + bool m_gpu{true}; std::unordered_map m_tracks; std::vector m_upload; // the origins and the runs of an expand(), as they're sent }; diff --git a/rendering/opengl46/opengl46water.cpp b/rendering/opengl46/opengl46water.cpp index 805ae1bd8..980e779df 100644 --- a/rendering/opengl46/opengl46water.cpp +++ b/rendering/opengl46/opengl46water.cpp @@ -10,9 +10,14 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "rendering/opengl46/opengl46water.h" +#include "model/Texture.h" #include "rendering/renderer.h" #include "utilities/Logs.h" +#include +#include +#include + namespace { @@ -21,35 +26,150 @@ GLuint groups(std::size_t const Count) return static_cast((Count + gl::WATER_GROUP_SIZE - 1) / gl::WATER_GROUP_SIZE); } +// a texture a kernel reads, made ready: read from its file first when nothing read it yet. the opengl renderer reads a texture +// when a draw binds it, and the glasses never draw the mask of their wipers (only the kernels read it), so without this the mask +// stayed unread and the glass never got its map +bool kernel_texture(ITexture &Texture) +{ + if (auto *source{dynamic_cast(&Texture)}; (source != nullptr) && (source->data_state == resource_state::none) && (false == source->is_rendertarget)) + source->load(); + return Texture.create() && Texture.get_is_ready() && (Texture.get_id() != 0); +} + } // namespace -bool opengl46_windscreen_water::gpu_init() +namespace +{ +// the programs of the passes, in their order (opengl46_windscreen_water::pass). the passes of the snow (from pass::snow on) are +// optional: without them the glasses of the snow stay clear and the rain works on +constexpr std::array PROGRAM_NAMES{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp", + "water_snowlayer.comp"}; +} // namespace + +// the program of a pass made; false when it doesn't compile (a pass of the snow then leaves the snow out, both of its passes) +bool opengl46_windscreen_water::make_program(std::size_t const Index) { try { - std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp"}; - for (std::size_t i = 0; i < names.size(); ++i) - { - gl::shader shader(names[i]); - m_programs[i] = std::make_unique(std::vector>{shader}); - } + gl::shader shader(PROGRAM_NAMES[Index]); + m_programs[Index] = std::make_unique(std::vector>{shader}); + return true; } catch (gl::shader_exception const &e) { - ErrorLog("windscreen water: can't use the programs of the simulation: " + std::string(e.what())); + if (Index >= pass::snow) + { + ErrorLog("windscreen water: can't use " + std::string(PROGRAM_NAMES[Index]) + ", the glasses of the snow stay clear: " + std::string(e.what())); + m_nosnow = true; + m_programs[pass::snow].reset(); + m_programs[pass::snowlayer].reset(); + } + else + { + ErrorLog("windscreen water: " + std::string(PROGRAM_NAMES[Index]) + " not made: " + std::string(e.what())); + } return false; } +} + +// the program of the cells of the rain (rain_cells.comp) made, once; its storage is made with the first bind() +void opengl46_windscreen_water::make_rain_cells_program() +{ + if (m_raincelltried) + return; + m_raincelltried = true; + try + { + gl::shader shader("rain_cells.comp"); + m_raincellprogram = std::make_unique(std::vector>{shader}); + } + catch (gl::shader_exception const &e) + { + ErrorLog("rain cells: can't use rain_cells.comp, the glasses with rain stay dry: " + std::string(e.what())); + m_raincellprogram.reset(); + } +} + +bool opengl46_windscreen_water::prepare_next() +{ + static_assert(PROGRAM_NAMES.size() == pass::count, "a name for every pass of the water"); + for (std::size_t index = 0; index < PROGRAM_NAMES.size(); ++index) + { + if (m_programs[index] || ((index >= pass::snow) && m_nosnow)) + continue; + // a pass of the water which doesn't compile is left to gpu_init(), which goes without the simulation + return (make_program(index) || (index >= pass::snow)); + } + // the cells of the rain made ahead as well, so the first rain doesn't compile them in the middle of a frame + if (false == m_raincelltried) + { + make_rain_cells_program(); + return true; + } + return false; +} + +bool opengl46_windscreen_water::gpu_init() +{ + // the ones made ahead (prepare_next()) are kept + for (std::size_t i = 0; i < PROGRAM_NAMES.size(); ++i) + { + if (m_programs[i] || ((i >= pass::snow) && m_nosnow)) + continue; + if ((false == make_program(i)) && (i < pass::snow)) + { + ErrorLog("windscreen water: can't use the programs of the simulation"); + return false; + } + } m_storage = std::make_unique(static_cast(gl::WATER_STORAGE_SIZE), gl::WATER_SSBO_BINDING); ::glClearNamedBufferData(*m_storage, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, nullptr); m_block = std::make_unique(sizeof(gl::water_ubs), gl::WATER_UBO_BINDING); return true; } -void opengl46_windscreen_water::bind() const +void opengl46_windscreen_water::make_rain_cells_storage() +{ + if (m_raincells) + return; + m_raincells = std::make_unique(static_cast(gl::RAIN_CELLS_COUNT * 16), gl::RAIN_CELLS_SSBO_BINDING); + ::glClearNamedBufferData(*m_raincells, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, nullptr); +} + +void opengl46_windscreen_water::bind() { if (m_storage) m_storage->bind_base(); + // the glasses of the rain always find the cells at their point (they read them only when worked out in the frame) + make_rain_cells_storage(); + m_raincells->bind_base(); +} + +void opengl46_windscreen_water::update_rain_cells(float const Time, float const Rain) +{ + m_raincellsvalid = false; + if (Rain <= 0.f) + return; + make_rain_cells_program(); + if (!m_raincellprogram) + return; + make_rain_cells_storage(); + // the glasses of the frame before read the cells, this one writes them + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + m_raincells->bind_base(); + auto const groups = [](std::size_t const Count) { return static_cast((Count + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE); }; + ::glProgramUniform1f(*m_raincellprogram, 0, Time); + ::glProgramUniform1f(*m_raincellprogram, 1, Rain); + // the cells, then the reach of the drops into the quarters of each drop cell, which reads them + ::glProgramUniform1i(*m_raincellprogram, 2, 0); + m_raincellprogram->dispatch(groups(gl::RAIN_MASK_BASE)); + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + ::glProgramUniform1i(*m_raincellprogram, 2, 1); + m_raincellprogram->dispatch(groups(gl::RAIN_CELLS_COUNT - gl::RAIN_MASK_BASE)); + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + gl::program::unbind(); + m_raincellsvalid = true; } void opengl46_windscreen_water::gpu_setup(std::size_t const Slot, std::vector const &Axes) @@ -63,6 +183,9 @@ void opengl46_windscreen_water::gpu_setup(std::size_t const Slot, std::vector(part.first), static_cast(part.second), GL_RED_INTEGER, GL_UNSIGNED_INT, nullptr); auto const axes{gl::water_slot_parts(Slot)[1]}; m_storage->update(Axes.data(), static_cast(axes.first), static_cast(std::min(axes.second, Axes.size() * sizeof(glm::vec4)))); + // where the layer of its snow lies + auto const info{layer_info(Slot, Axes)}; + m_storage->update(info.data(), static_cast(gl::WATER_LAYER_INFO_OFFSET + gl::WATER_LAYER_INFO_SIZE * Slot), static_cast(sizeof(info))); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT | GL_BUFFER_UPDATE_BARRIER_BIT); } @@ -71,7 +194,7 @@ bool opengl46_windscreen_water::gpu_bake(std::size_t const Slot, texture_handle if ((!m_storage) || (Mask == null_handle)) return false; auto &texture{GfxRenderer->Texture(Mask)}; - if ((false == texture.create()) || (false == texture.get_is_ready()) || (texture.get_id() == 0)) + if (false == kernel_texture(texture)) return false; m_storage->bind_base(); m_block->update(Block); @@ -84,6 +207,27 @@ bool opengl46_windscreen_water::gpu_bake(std::size_t const Slot, texture_handle return true; } +bool opengl46_windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_handle const Atlas, texture_handle const Normal, gl::water_ubs const &Block) +{ + if ((!m_storage) || (!m_programs[pass::snowlayer]) || (Slot >= gl::WATER_SLOTS) || (Atlas == null_handle) || (Normal == null_handle)) + return false; + auto &atlas{GfxRenderer->Texture(Atlas)}; + auto &normal{GfxRenderer->Texture(Normal)}; + if ((false == kernel_texture(atlas)) || (false == kernel_texture(normal))) + return false; + m_storage->bind_base(); + m_block->update(Block); + m_block->bind_uniform(); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_ATLAS_TEX), static_cast(atlas.get_id())); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_NORMAL_TEX), static_cast(normal.get_id())); + m_programs[pass::snowlayer]->dispatch(groups(gl::WATER_LAYER_TEXELS)); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_ATLAS_TEX), 0); + ::glBindTextureUnit(static_cast(gl::WATER_SNOW_NORMAL_TEX), 0); + ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); + gl::program::unbind(); + return true; +} + void opengl46_windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const Tries) { if (!m_storage) @@ -100,17 +244,24 @@ void opengl46_windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32 m_programs[Pass]->dispatch(Groups, slots); ::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); }; + // the drops only where a glass of the water is (the glasses of the snow have passes of their own) + auto const water{std::ranges::any_of(Block.slots, [](glm::vec4 const &Slot) { return Slot.z > 0.5f; })}; + auto const drop_groups{water ? drops : 0u}; + auto const cell_groups{water ? cells : 0u}; // the wetted paths the blades went over in the step wiped - if (Block.blades != Block.blades_before) + if (water && (Block.blades != Block.blades_before)) run(pass::trail, groups(static_cast(gl::WATER_TRAIL) * gl::WATER_TRAIL)); - run(pass::spawn, groups(Tries)); - run(pass::move, drops); - run(pass::clear, cells); - run(pass::grid, drops); - run(pass::merge, drops); - run(pass::gather, drops); - run(pass::settle, drops); - run(pass::clear, cells); - run(pass::grid, drops); + run(pass::spawn, water ? groups(Tries) : 0u); + run(pass::move, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + run(pass::merge, drop_groups); + run(pass::gather, drop_groups); + run(pass::settle, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + // the snow of the glasses of the snow, a texel of their maps a thread + if ((Block.snow_slots != glm::vec4{0.f}) && m_programs[pass::snow]) + run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); gl::program::unbind(); } diff --git a/rendering/opengl46/opengl46water.h b/rendering/opengl46/opengl46water.h index 851464e80..db914fb93 100644 --- a/rendering/opengl46/opengl46water.h +++ b/rendering/opengl46/opengl46water.h @@ -25,14 +25,29 @@ class opengl46_windscreen_water : public gfx::windscreen_water opengl46_windscreen_water() = default; ~opengl46_windscreen_water() override = default; - // the storage bound to its point for the glasses drawn next (the bindings are kept by every context of its own) - void bind() const; + // the storage bound to its point for the glasses drawn next (the bindings are kept by every context of its own). the cells + // of the rain are always there and bound, made at the first call + void bind(); + // the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp) worked out for the + // time of the frame (scene_ubs.time), once a frame before the passes; nothing while it doesn't rain + void update_rain_cells(float Time, float Rain); + // whether the cells were worked out in this frame (the last update_rain_cells()): only then the glasses read them + // (scene_ubs.rain_state.w) + bool rain_cells_valid() const + { + return m_raincellsvalid; + } + // the next of the programs of the simulation compiled ahead of its first step (a few seconds each where the driver has none + // of them kept, at the first start of a new version), so the loading screen stays while they're made. false once all are + bool prepare_next(); + static constexpr std::size_t program_count() { return pass::count + 1; } // the passes and the cells of the rain protected: bool gpu_init() override; void gpu_setup(std::size_t Slot, std::vector const &Axes) override; bool gpu_bake(std::size_t Slot, texture_handle Mask, gl::water_ubs const &Block) override; void gpu_step(gl::water_ubs const &Block, std::uint32_t Tries) override; + bool gpu_snow_layer(std::size_t Slot, texture_handle Atlas, texture_handle Normal, gl::water_ubs const &Block) override; private: // the passes of the step, in their order @@ -47,9 +62,21 @@ class opengl46_windscreen_water : public gfx::windscreen_water gather, settle, bake, + snow, + snowlayer, count }; std::array, pass::count> m_programs; std::unique_ptr m_storage; std::unique_ptr m_block; + std::unique_ptr m_raincellprogram; + std::unique_ptr m_raincells; + bool m_raincelltried{false}; + bool m_raincellsvalid{false}; // the cells worked out in this frame + bool m_nosnow{false}; // a pass of the snow didn't compile: the snow is left out + + bool make_program(std::size_t Index); + void make_rain_cells_program(); + // the storage of the cells made, once, cleared + void make_rain_cells_storage(); }; diff --git a/rendering/opengl46/opengl46weather.cpp b/rendering/opengl46/opengl46weather.cpp index d3f407445..18c6ecd7c 100644 --- a/rendering/opengl46/opengl46weather.cpp +++ b/rendering/opengl46/opengl46weather.cpp @@ -15,8 +15,11 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "model/Texture.h" #include "utilities/Globals.h" +#include "utilities/Logs.h" #include "utilities/utilities.h" +#include + namespace { @@ -76,20 +79,34 @@ GLuint opengl46_weather::create_texture(GLenum const Target, GLenum const Format void opengl46_weather::init() { - m_noise_program = make_compute("clouds_noise.comp"); - m_march_program = make_compute("clouds_march.comp"); - m_temporal_program = make_compute("clouds_temporal.comp"); - m_shadow_program = make_compute("clouds_shadow.comp"); - m_horizon_program = make_compute("fog_horizon.comp"); - m_inject_program = make_compute("fog_inject.comp"); - m_integrate_program = make_compute("fog_integrate.comp"); - m_sky_program = make_program("quad.vert", "sky_weather.frag"); - m_stars_program = make_program("stars.vert", "stars.frag"); + try + { + m_noise_program = make_compute("clouds_noise.comp"); + m_march_program = make_compute("clouds_march.comp"); + m_temporal_program = make_compute("clouds_temporal.comp"); + m_shadow_program = make_compute("clouds_shadow.comp"); + m_horizon_program = make_compute("fog_horizon.comp"); + m_inject_program = make_compute("fog_inject.comp"); + m_integrate_program = make_compute("fog_integrate.comp"); + m_sky_program = make_program("quad.vert", "sky_weather.frag"); + m_stars_program = make_program("stars.vert", "stars.frag"); + } + catch (gl::shader_exception const &e) + { + // the fog along the ray, no clouds, no stars, the sky as it's drawn without them; the shading reads the block below + ErrorLog(std::format("clouds, volumetric fog and stars not available: {}", e.what())); + for (auto *program : {&m_noise_program, &m_march_program, &m_temporal_program, &m_shadow_program, &m_horizon_program, &m_inject_program, &m_integrate_program, + &m_sky_program, &m_stars_program}) + program->reset(); + Global.gfx_clouds = 0; + Global.gfx_fog = 0; + } m_weather_ubo = std::make_unique(sizeof(gl::weather_ubs), gl::WEATHER_UBO_BINDING); m_weather_ubo->update(m_state.block()); - make_noise(); + if (m_noise_program != nullptr) + make_noise(); auto const stars{gfx::weather_state::star_vertices()}; m_stars_count = static_cast(stars.size() / 2); @@ -172,8 +189,9 @@ void opengl46_weather::upload_header() void opengl46_weather::update(opengl46_sky const &Sky, glm::vec3 const &Keylight, glm::vec3 const &Keycolor, glm::vec3 const &Ambient, glm::vec3 const &Fogcolor, glm::dvec3 const &Camera) { - m_state.update(Sky.atmosphere_weight(), Sky.skyview_table() != 0, Keylight, Keycolor, Ambient, Fogcolor, Camera); - auto const shadows{m_state.shadows_wanted()}; + // without the programs the colours of the horizon are worked out here, and the clouds left out + m_state.update(Sky.atmosphere_weight(), (Sky.skyview_table() != 0) && (m_horizon_program != nullptr), Keylight, Keycolor, Ambient, Fogcolor, Camera); + auto const shadows{m_state.shadows_wanted() && (m_shadow_program != nullptr)}; if (shadows) { if (m_shadow_size != Global.gfx_clouds_shadows_size) @@ -219,7 +237,7 @@ void opengl46_weather::update(opengl46_sky const &Sky, glm::vec3 const &Keylight m_state.shadows_drawn(false); // a band of the panorama of the clouds, all of it the first time - if (m_state.clouds_drawn()) + if (m_state.clouds_drawn() && (m_march_program != nullptr)) { auto const level{gfx::weather_state::quality(Global.gfx_clouds, Global.gfx_fog_quality)}; if (m_panorama_size != level.panorama) @@ -282,6 +300,8 @@ void opengl46_weather::prepare_view(glm::ivec2 const &Size, quality_level const void opengl46_weather::render_view(glm::mat4 const &Projection, glm::mat4 const &View, glm::dvec3 const &Camera, glm::ivec2 const &Size, int const Cablamps) { + if (m_march_program == nullptr) + return; auto const level{gfx::weather_state::quality(Global.gfx_clouds, Global.gfx_fog_quality)}; prepare_view(Size, level); auto const rotation{glm::mat4{glm::mat3{View}}}; @@ -387,7 +407,7 @@ void opengl46_weather::setup_pass(bool const Volume, glm::ivec2 const &Size) void opengl46_weather::draw_stars(glm::mat4 const &View, float const Sunangle, double const Siderealtime, double const Latitude) { - if (!m_stars_vao || m_stars_count == 0) + if (!m_stars_vao || m_stars_count == 0 || !m_stars_program) return; glm::mat4 toworld, toview; glm::vec4 params; @@ -407,6 +427,8 @@ void opengl46_weather::draw_stars(glm::mat4 const &View, float const Sunangle, d void opengl46_weather::draw_sky(glm::mat4 const &Projection, glm::mat4 const &View, bool const Mainview) { + if (m_sky_program == nullptr) + return; int mode{0}; if (m_state.clouds_drawn()) { diff --git a/rendering/opengl46/opengl46weather.h b/rendering/opengl46/opengl46weather.h index 58ce30036..10a6efbad 100644 --- a/rendering/opengl46/opengl46weather.h +++ b/rendering/opengl46/opengl46weather.h @@ -43,7 +43,8 @@ class opengl46_weather opengl46_weather(const opengl46_weather &) = delete; opengl46_weather &operator=(const opengl46_weather &) = delete; - // creates the programs, buffers and noise textures. throws gl::shader_exception + // creates the programs, buffers and noise textures. without the programs (a shader which doesn't compile) there are no + // clouds, volumetric fog and stars: logged, and gfx.clouds and gfx.fog switched off void init(); // binds the buffer and textures the shading reads; bindings are context state, so done in every context void bind(); diff --git a/rendering/particles.cpp b/rendering/particles.cpp index 87fc7c0b5..07e96d6b9 100644 --- a/rendering/particles.cpp +++ b/rendering/particles.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "utilities/Logs.h" #include "vehicle/smoke.h" +#include "vehicle/DynObj.h" void @@ -174,7 +175,7 @@ smoke_source::accumulate_spawns( double const Timedelta, bool const Onlydespawn if( m_ownertype == owner_type::vehicle ) { - auto const &mover { *m_owner.vehicle->MoverParameters }; + auto const &physics { *m_owner.vehicle->physics }; // NOTE: the smoke keeps the colour of its template, cold engine or not. a grey for a cold engine was once meant // here, but the line compared instead of assigning; made an assignment, it set 128 on the 0-1 scale of the // emitter colour, so the smoke turned pure white, glowing at night, and never changed back @@ -183,7 +184,7 @@ smoke_source::accumulate_spawns( double const Timedelta, bool const Onlydespawn m_spawncount = ( ( true == spawning ) ? smoke::vehicle_spawn_count( - mover, m_owner.vehicle->bEnabled, + physics, m_owner.vehicle->bEnabled, { m_spawncount, m_spawnrate, Global.SmokeFidelity, static_cast( m_max_particles ) }, Timedelta ) : 0.f ); @@ -344,22 +345,7 @@ smoke_source::launch_scales( float &Velocity, float &Opacity ) const { Opacity = 1.f; if( m_ownertype != owner_type::vehicle ) { return; } - Opacity = static_cast(m_owner.vehicle->MoverParameters->dizel_fill); - if (m_owner.vehicle->MoverParameters->EngineType == TEngineType::DieselElectric) - { - if (m_owner.vehicle->MoverParameters->dizel_spinup == true) - { - Velocity = static_cast(0.38*(((m_owner.vehicle->MoverParameters->enrot)/2)*0.5)); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; - - } - else - { - - Velocity = static_cast((((m_owner.vehicle->MoverParameters->enrot)/60)*0.6) * (m_owner.vehicle->MoverParameters->EnginePower *0.03)); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; - //Particle.velocity *= m_owner.vehicle->GetVelocity(); // / m_owner.vehicle->MoverParameters->dizel_fill *0.01)) ; - } - - } + m_owner.vehicle->ExhaustScales( Velocity, Opacity ); } // updates state of provided particle and bounding box. returns: true if particle is still alive afterwards, false otherwise diff --git a/rendering/renderer.h b/rendering/renderer.h index 7cea7928b..d84035b68 100644 --- a/rendering/renderer.h +++ b/rendering/renderer.h @@ -10,7 +10,9 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include +#include #include "rendering/geometrybank.h" #include "interfaces/IMaterial.h" @@ -84,6 +86,11 @@ public: virtual void Shutdown() = 0; // main draw call. returns false on error virtual auto Render() -> bool = 0; + // after the scenery is loaded, while the loading screen is shown: the programs of the materials drawn with once each, for + // about Milliseconds, so the driver compiles them now and not in the first frame of the simulation (a black window that + // doesn't answer for half a minute at the first start of a new version). returns how many are done and how many there are; + // a renderer which needs none of it says it's all done + virtual std::pair Prewarm_Shaders( double const Milliseconds ) { return { 0, 0 }; } virtual void SwapBuffers() = 0; virtual auto Framerate() -> float = 0; // geometry methods diff --git a/rendering/vulkan14/vulkan14bindings.h b/rendering/vulkan14/vulkan14bindings.h index 0e98ccc88..c671e372f 100644 --- a/rendering/vulkan14/vulkan14bindings.h +++ b/rendering/vulkan14/vulkan14bindings.h @@ -86,7 +86,10 @@ constexpr std::uint32_t SKY_OCCLUSION_HEIGHT_TEX = 31; constexpr std::uint32_t SKY_OCCLUSION_TEX = 32; // the probe of the cab drawn last, a small level of its albedo, which the drawing of the probe reads to tell where the windows are constexpr std::uint32_t CAB_PROBE_MASK_TEX = 33; -constexpr std::uint32_t PASS_BINDING_COUNT = 34; +// the drops and the rivulets of the cells of the glasses with rain (mat_rain_windscreen, rain_cells.comp): worked out once a frame +// for every cell, so a glass only reads them +constexpr std::uint32_t RAIN_CELLS_SSBO = 34; +constexpr std::uint32_t PASS_BINDING_COUNT = 35; // the offsets of the bindings above with dynamic offsets, in the order of the bindings constexpr std::uint32_t PASS_DYNAMIC_OFFSETS = 6; // the textures of a material take the bindings of their units (#pragma texture(name, unit, ...)), 0 .. MAX_TEXTURES - 1 diff --git a/rendering/vulkan14/vulkan14capabilities.cpp b/rendering/vulkan14/vulkan14capabilities.cpp index 274b65147..ca2bbf991 100644 --- a/rendering/vulkan14/vulkan14capabilities.cpp +++ b/rendering/vulkan14/vulkan14capabilities.cpp @@ -25,12 +25,12 @@ namespace // columns: structure, name, required, guaranteed by vulkan 1.4, purpose. // -// beyond what vulkan 1.4 requires of every device the renderer needs multiDrawIndirect, shaderDrawParameters, -// textureCompressionBC and geometryShader, so a gpu without one of them is turned down by its name rather than failing later. +// beyond what vulkan 1.4 requires of every device the renderer needs multiDrawIndirect, shaderDrawParameters and +// textureCompressionBC, so a gpu without one of them is turned down by its name rather than failing later. // "guaranteed" follows the minimum requirements of vulkan 1.2-1.4 (VP_LUNARG_minimum_requirements_1_4 of the vulkan sdk) std::vector const g_feature_table = { // VkPhysicalDeviceFeatures (1.0) - {"VkPhysicalDeviceFeatures", "geometryShader", true, false, "map icons and cube shadow maps of the lamps until multiview takes them over", VK14_CORE(geometryShader)}, + {"VkPhysicalDeviceFeatures", "geometryShader", false, false, "none of the shaders is a geometry shader (the cube shadow maps of the lamps are drawn with multiview)", VK14_CORE(geometryShader)}, {"VkPhysicalDeviceFeatures", "multiDrawIndirect", true, false, "multi draw indirect of the gpu culling", VK14_CORE(multiDrawIndirect)}, {"VkPhysicalDeviceFeatures", "textureCompressionBC", true, false, "bc1-bc7 compressed dds textures", VK14_CORE(textureCompressionBC)}, {"VkPhysicalDeviceFeatures", "drawIndirectFirstInstance", true, true, "instanced indirect draws", VK14_CORE(drawIndirectFirstInstance)}, diff --git a/rendering/vulkan14/vulkan14compute.cpp b/rendering/vulkan14/vulkan14compute.cpp index c5dd6e550..d32f746b5 100644 --- a/rendering/vulkan14/vulkan14compute.cpp +++ b/rendering/vulkan14/vulkan14compute.cpp @@ -92,22 +92,40 @@ std::vector reflect_bindings(std::vector= 2) + { + types[op[1]] = {opcode, 0, 0, 0}; + } break; case op_type_sampled_image: - types[op[1]] = {opcode, op[2], 0, 0}; + if (count >= 3) + { + types[op[1]] = {opcode, op[2], 0, 0}; + } break; case op_type_array: - types[op[1]] = {opcode, op[2], op[3], 0}; + if (count >= 4) + { + types[op[1]] = {opcode, op[2], op[3], 0}; + } break; case op_type_runtime_array: - types[op[1]] = {opcode, op[2], 0, 0}; + if (count >= 3) + { + types[op[1]] = {opcode, op[2], 0, 0}; + } break; case op_type_struct: - types[op[1]] = {opcode, 0, 0, 0}; + if (count >= 2) + { + types[op[1]] = {opcode, 0, 0, 0}; + } break; case op_type_pointer: - types[op[1]] = {opcode, op[3], op[2], 0}; + if (count >= 4) + { + types[op[1]] = {opcode, op[3], op[2], 0}; + } break; case op_variable: if (count >= 4) diff --git a/rendering/vulkan14/vulkan14context.h b/rendering/vulkan14/vulkan14context.h index bdc57dc75..26010523c 100644 --- a/rendering/vulkan14/vulkan14context.h +++ b/rendering/vulkan14/vulkan14context.h @@ -68,6 +68,15 @@ enum class vertex_kind : std::uint8_t particle_instance // three vec4 of gl::particle_draw for each instance, the particles of the gpu }; +// the vertices of a particle of the smoke of the cpu (vertex_kind::particle, as opengl46_particles has them) +struct particle_vertex +{ + glm::vec3 position; + glm::vec4 color; + glm::vec2 texture; +}; +static_assert(sizeof(particle_vertex) == 36, "the layout of the vertices of the particles"); + // the push constants of the pipelines of the scene and of the post-processing (shaders/vk14/common.glsl, draw_constants_block) struct draw_constants { @@ -93,6 +102,8 @@ struct scene_program : public gfx::shader_program // the variant of the multi draws of the instances drawn from the gpu culling (MODEL_DRAWS), made when it's first needed std::shared_ptr multidraw; bool multidraw_tried{false}; + // its shaders are being compiled by the background threads, the draws it's for are left out till then + bool multidraw_pending{false}; vertex_kind vertices{vertex_kind::scene}; // the pipelines made, by the key of bind_scene_pipeline(), and the ones the background threads are making (M5). guarded by the // mutex, as are the variants above made when they're first needed: the walks of the passes and the background threads ask for @@ -194,6 +205,9 @@ struct viewport_targets target_formats formats; target_formats output_formats; bool srgb{true}; // the output encodes the colour (gfx.shadergamma no) + // the images couldn't be made for the size and the settings above, and when: tried again after a while (make_targets()) + bool failed{false}; + std::chrono::steady_clock::time_point failed_at{}; }; // the images of the frame generation of dlss (gfx.framegeneration) for the main window, made for its size and its format: the frame @@ -231,6 +245,15 @@ struct window_ring frame_ring ring; VkDeviceSize window{0}; // the size of the window, bytes VkDeviceSize stride{0}; + // a frame had more data than the ring takes, and draws were left out: how many times, said in the log the first time (any thread) + std::atomic full{0}; + void report_full(char const *What) + { + if (full.fetch_add(1) == 0) + { + log_error(std::string("the ring of ") + What + " of a frame is full (" + memory_size_string(ring.capacity()) + "), the draws it has no room for are left out"); + } + } }; // the light clusters (gl::cluster_grid), of the colour pass of each viewport in turn @@ -357,11 +380,29 @@ struct cull_resources std::vector> lamps; hiz_pyramid hiz; bool ready{false}; + // the cullings were tried to be made once (vulkan14_renderer::ensure_cull()), with the renderer they're of + bool tried{false}; // the cascades of the sun shadows fitted to the depth of the main view (gfx.shadow.sdsm), made when they're first needed shadow_fitter shadowfit; bool shadowfit_tried{false}; }; +// a point of light of a lamp with a glare: the submodel, and the object which draws its model (TSubModel::iInstance: a vehicle, an +// instance of a model with animations; 0 for the others). each object has its own points seen or hidden +struct glare_point +{ + TSubModel const *submodel{nullptr}; + std::uintptr_t instance{0}; + bool operator==(glare_point const &) const = default; +}; +struct glare_point_hash +{ + std::size_t operator()(glare_point const &Point) const noexcept + { + return std::hash{}(Point.submodel) ^ (std::hash{}(Point.instance) * 31u); + } +}; + // what the scene is drawn with struct scene_state { @@ -474,6 +515,9 @@ struct scene_state // the depth prepass of the scene (the stage P3): without and with the alpha test, and which of them a program of a material takes std::shared_ptr prepass, prepass_alpha; std::unordered_map prepass_classes; + // the sun shadows of the materials which move their vertices in a vertex shader of their own (mat_.vert, the animals + // and people animated by textures): by the program of the material, without and with the alpha test; made with the program + std::unordered_map, 2>> own_shadows; // the post-processing, by the fragment shader std::unordered_map> post_fragments; std::shared_ptr quad; @@ -492,8 +536,8 @@ struct scene_state // the occlusion queries of the points of light of the lamps, a pool for each frame in flight with the submodels they were made // for; the glare of a lamp is drawn where its point was seen in the frame the gpu was done with last std::vector occlusion_pools; - std::vector> occlusion_submodels; - std::unordered_map glare_visible; + std::vector> occlusion_submodels; + std::unordered_map glare_visible; static constexpr std::uint32_t occlusion_queries{1024}; // the images of the scene were put in their layouts (the stand-ins cleared) bool images_ready{false}; @@ -579,7 +623,26 @@ struct vulkan14_renderer::context std::vector warm_records; std::unordered_set warm_lines; std::atomic warm_made{0}; + // the pipelines of the list of the last session handed to the background threads, and those of them done with, made or not: + // the progress of the loading screen (vulkan14_renderer::Prewarm_Shaders()) + std::atomic warm_queued{0}; + std::atomic warm_finished{0}; std::atomic pipelines_late{0}; + // the pipelines made behind the loading screen once the scenery is loaded (vulkan14_renderer::Prewarm_Shaders()): each with the + // key bind_scene_pipeline() looks it up by in the map of its program, and the next one made on the main thread without the + // background threads + struct prewarm_pipeline + { + std::shared_ptr program; + vk14::target_formats targets; + vk14::blend_mode blend{vk14::blend_mode::none}; + std::uint32_t settings{0}; + bool single{false}; + std::uint64_t key{0}; + }; + std::vector prewarm; + std::size_t prewarm_next{0}; + bool prewarm_listed{false}; // [0]: the main window, then the windows of the extra viewports std::vector> windows; std::vector frames; @@ -623,6 +686,8 @@ struct vulkan14_renderer::context std::uint64_t present_id{0}; // when the main thread handed it over to the render thread std::chrono::steady_clock::time_point handed{}; + // the frame couldn't be recorded or submitted, the device not lost: left out (skip_frame()), its images aren't presented + bool skipped{false}; }; // the render thread and the job it's given std::thread render_thread; @@ -649,11 +714,17 @@ struct vulkan14_renderer::context // the job done; false: Failure says where it failed bool execute(render_job &Job, char const *&Failure); - // the part of it before the presents: its command buffers recorded and submitted + // the part of it before the presents: its command buffers recorded and submitted. a frame which can't be (out of memory and the + // like) is left out, false only when the device is lost bool submit(render_job &Job, char const *&Failure); + // the frame which failed at What left out: its uploads (with Compute after the part of the compute queue submitted) and the waits + // and the signals of the frame, without the rest of it; false when that can't be submitted either + bool skip_frame(render_job &Job, bool Compute, char const *What, char const *&Failure); + // the frames left out so far (skip_frame(), the render thread or the main thread without it) + std::uint64_t skipped_frames{0}; // the windows of the frame submitted last presented, the frames generated for the main window before it (spread over the time - // of a frame when there's the render thread to wait); Id: the id of the present of the main window (0: none); false: the device or - // a surface is lost + // of a frame when there's the render thread to wait); Id: the id of the present of the main window (0: none); false: the device is lost + // (a lost surface is made anew by its swapchain) bool present(std::vector const &Windows, std::uint64_t Id); // the render thread (gfx.vulkan.renderthread, M4): the frames are recorded, submitted and presented by it while the main // thread goes on with the simulation of the next one. the main thread waits for it to be done before it begins a frame and @@ -681,8 +752,9 @@ struct vulkan14_renderer::context VkPipeline make_scene_pipeline(vk14::scene_program &Program, vk14::target_formats const &Targets, vk14::blend_mode Blend, VkPrimitiveTopology Primitiveclass, std::uint32_t Settings, bool Single); bool find_scene_pipeline(vk14::scene_program &Program, vk14::target_formats const &Targets, vk14::blend_mode Blend, VkPrimitiveTopology Primitiveclass, std::uint32_t Settings, bool Single, VkPipeline &Pipeline); + // Late: a draw waits for it (counted as made late); otherwise it's made ahead void queue_scene_pipeline(vk14::scene_program &Program, vk14::target_formats const &Targets, vk14::blend_mode Blend, VkPrimitiveTopology Primitiveclass, std::uint32_t Settings, bool Single, - std::uint64_t Key); + std::uint64_t Key, bool Late = true); void warm_scene_pipelines(); void save_scene_pipelines(); // the value of the timeline the gpu reached, 0 when it can't be read @@ -752,6 +824,9 @@ struct vulkan14_renderer::draw_state }; ring_window draws_window; ring_window instances_window; + // instances had no room in their ring in this frame: the instanced draws are left out till the next one (their matrices aren't + // where their indices say) + bool instances_lost{false}; vk14::ring_cache draws_cache; vk14::ring_cache instances_cache; // the map of a lamp or of headlights the pass draws to (begin_local_shadow_rendering()) diff --git a/rendering/vulkan14/vulkan14cull.cpp b/rendering/vulkan14/vulkan14cull.cpp index 3f2a91e02..0e33cd871 100644 --- a/rendering/vulkan14/vulkan14cull.cpp +++ b/rendering/vulkan14/vulkan14cull.cpp @@ -488,7 +488,12 @@ bool hiz_pyramid::build(command_stream *Commands, VkDevice Device, allocator &Me info.format = desc.format; info.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, level, 1, 0, 1}; VkImageView view{VK_NULL_HANDLE}; - VK14_VERIFY(vkCreateImageView(Device, &info, nullptr, &view)); + if (!VK14_VERIFY(vkCreateImageView(Device, &info, nullptr, &view))) + { + // no pyramid without a view of each of its levels: what was made of it goes, the culling goes without the occlusion test + destroy(Device, &Deletions, Value); + return false; + } m_levels.push_back(view); } // the pyramid stays in the general layout: the kernel reads the levels it wrote, the culling all of them diff --git a/rendering/vulkan14/vulkan14dlss.cpp b/rendering/vulkan14/vulkan14dlss.cpp index ba5679685..a5224ab4e 100644 --- a/rendering/vulkan14/vulkan14dlss.cpp +++ b/rendering/vulkan14/vulkan14dlss.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #if defined(WITH_DLSS) && !defined(_WIN32) @@ -132,6 +133,9 @@ std::filesystem::path program_directory() struct dlss::state { + // ngx isn't to be called by two threads at once: the evaluation of dlss and the frame generation may be replayed in chunks of the + // frame recorded by different workers + std::mutex ngx; // ngx: where it writes its logs, where it looks for the libraries besides the directory of the program std::wstring data_path; std::vector paths; @@ -318,6 +322,7 @@ struct dlss::state static void record(VkCommandBuffer const Buffer, void *const Data) { auto &self{*static_cast(Data)}; + std::scoped_lock const lock{self.ngx}; if (self.failed || (self.parameters == nullptr)) { self.clear_output(Buffer); @@ -444,6 +449,7 @@ struct dlss::state static void record_generation(VkCommandBuffer const Buffer, void *const Data) { auto &self{*static_cast(Data)}; + std::scoped_lock const lock{self.ngx}; if (self.generation_failed || (self.generation_parameters == nullptr) || self.generated.empty()) { self.copy_backbuffer(Buffer); diff --git a/rendering/vulkan14/vulkan14frame.cpp b/rendering/vulkan14/vulkan14frame.cpp index 82aa2645d..1cd33df8b 100644 --- a/rendering/vulkan14/vulkan14frame.cpp +++ b/rendering/vulkan14/vulkan14frame.cpp @@ -101,13 +101,7 @@ glm::mat4 ortho_frustumtest_projection(float l, float r, float b, float t, float glm::mat4 const coordmove{0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0}; // the vertices of a particle of the smoke (opengl46_particles) -struct particle_vertex -{ - glm::vec3 position; - glm::vec4 color; - glm::vec2 texture; -}; -static_assert(sizeof(particle_vertex) == 36, "the layout of the vertices of the particles"); +using vk14::particle_vertex; std::vector> const billboard_vertices{ {{-0.5f, -0.5f, 0.f}, {0.f, 0.f}}, {{0.5f, -0.5f, 0.f}, {1.f, 0.f}}, {{0.5f, 0.5f, 0.f}, {1.f, 1.f}}, {{-0.5f, -0.5f, 0.f}, {0.f, 0.f}}, {{0.5f, 0.5f, 0.f}, {1.f, 1.f}}, {{-0.5f, 0.5f, 0.f}, {0.f, 1.f}}, @@ -331,16 +325,27 @@ bool make_targets(vk14::allocator &Memory, vk14::deletion_queue &Deletions, std: VkExtent2D const extent{static_cast(std::max(Width, 1)), static_cast(std::max(Height, 1))}; // the images after the upscaling of dlss have the size of the window, the others that of the scene VkExtent2D const outputextent{Dlss ? VkExtent2D{static_cast(std::max(OutputWidth, 1)), static_cast(std::max(OutputHeight, 1))} : extent}; - if ((Targets.extent.width == extent.width) && (Targets.extent.height == extent.height) && (Targets.output_extent.width == outputextent.width) && (Targets.output_extent.height == outputextent.height) && - (Targets.samples == samples) && (Targets.motion == motion) && (Targets.taa == Taa) && (Targets.dlss == Dlss) && (Targets.aberration == aberration) && (Targets.srgb == Srgb) && (Targets.reflections == Reflections) && Targets.output) + auto const unchanged{(Targets.extent.width == extent.width) && (Targets.extent.height == extent.height) && (Targets.output_extent.width == outputextent.width) && (Targets.output_extent.height == outputextent.height) && + (Targets.samples == samples) && (Targets.motion == motion) && (Targets.taa == Taa) && (Targets.dlss == Dlss) && (Targets.aberration == aberration) && (Targets.srgb == Srgb) && (Targets.reflections == Reflections)}; + if (unchanged && Targets.output) { return true; } - Deletions.push(Value, [old = std::move(Targets)]() {}); + // the same images couldn't be made a moment ago (no memory for them): tried again after a while, not with every frame + auto const now{std::chrono::steady_clock::now()}; + auto const failedbefore{unchanged && Targets.failed}; + if (failedbefore && (now - Targets.failed_at < std::chrono::seconds{1})) + { + return false; + } auto const oldformats{Targets.formats}; auto const oldoutput{Targets.output_formats}; auto const oldpost{Targets.post_formats}; auto const olddepth{Targets.depth_formats}; + // the ambient occlusion made once stays with the images made anew for another reason: it can be switched on again in the debug + // window only where its images are + auto const hadocclusion{bool(Targets.ssao)}; + Deletions.push(Value, [old = std::move(Targets)]() {}); Targets = vk14::viewport_targets{}; Targets.extent = extent; Targets.output_extent = outputextent; @@ -387,7 +392,8 @@ bool make_targets(vk14::allocator &Memory, vk14::deletion_queue &Deletions, std: { ok = ok && make(Targets.motion_image, velocity, sampledcolour, VK_SAMPLE_COUNT_1_BIT, "scene velocity"); } - if (motion && Global.gfx_postfx_motionblur_enabled) + // the pass of the motion blur runs also without the motion blur: the windscreens ask it for their drops and haze (see render_post()) + if (motion) { ok = ok && make(Targets.blurred, hdr, sampledcolour, VK_SAMPLE_COUNT_1_BIT, "motion blurred", outputextent); } @@ -425,7 +431,7 @@ bool make_targets(vk14::allocator &Memory, vk14::deletion_queue &Deletions, std: make(Targets.dlss_output, hdr, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | historysource, VK_SAMPLE_COUNT_1_BIT, "dlss output", outputextent); } // the ambient occlusion, half the size, when it's on - if (ok && (Global.gfx_postfx_ao != 0)) + if (ok && ((Global.gfx_postfx_ao != 0) || hadocclusion)) { auto makehalf = [&](std::shared_ptr &Image, char const *Name) { vk14::image_desc desc; @@ -486,8 +492,28 @@ bool make_targets(vk14::allocator &Memory, vk14::deletion_queue &Deletions, std: } if (false == ok) { - vk14::log_error("the images of a viewport of " + std::to_string(extent.width) + "x" + std::to_string(extent.height) + " can't be made"); - Targets.output.reset(); + if (false == failedbefore) + { + vk14::log_error("the images of a viewport of " + std::to_string(extent.width) + "x" + std::to_string(extent.height) + " can't be made, trying again every second"); + } + // what was made of them goes: the viewport isn't drawn without all of them + Deletions.push(Value, [partial = std::move(Targets)]() {}); + Targets = vk14::viewport_targets{}; + Targets.extent = extent; + Targets.output_extent = outputextent; + Targets.dlss = Dlss; + Targets.samples = samples; + Targets.motion = motion; + Targets.taa = Taa; + Targets.aberration = aberration; + Targets.srgb = Srgb; + Targets.reflections = Reflections; + Targets.formats = oldformats; + Targets.output_formats = oldoutput; + Targets.post_formats = oldpost; + Targets.depth_formats = olddepth; + Targets.failed = true; + Targets.failed_at = now; return false; } Targets.formats.colour = {hdr, motion ? velocity : VK_FORMAT_UNDEFINED}; @@ -585,6 +611,7 @@ bool vulkan14_renderer::Render() m_draw->instances_cache.reset(&scene.instances.ring, vk14::instance_ring_part); m_draw->draws_window = {}; m_draw->instances_window = {}; + m_draw->instances_lost = false; // the draws which aren't instanced read the identity at the start of the window from the first draw of the frame on open_instance_window(); // the occlusion queries of the lamps the slot made the last time @@ -644,9 +671,22 @@ bool vulkan14_renderer::Render() { texture->apply_pending(); } + // the copies of the textures made are spread over the frames when many come at once: those the frame has no budget left for + // wait for the next one, before the ones made meanwhile + ctx.pending.upload_budget = vk14::pending_textures::upload_budget_frame; + std::vector waiting; for (auto *texture : made) { texture->publish(); + if (texture->made_waiting()) + { + waiting.push_back(texture); + } + } + if (false == waiting.empty()) + { + std::scoped_lock const lock{ctx.pending.mutex}; + ctx.pending.made.insert(ctx.pending.made.begin(), waiting.begin(), waiting.end()); } } @@ -851,11 +891,13 @@ bool vulkan14_renderer::Render() if (drawscene) { render_scene(); - if (m_pickcontrolswanted && simulation::Train) + // nothing is picked in a main window which is minimized: its scene wasn't drawn + auto const picking{(false == ctx.windows.empty()) && (false == ctx.windows.front()->minimized())}; + if (picking && m_pickcontrolswanted && simulation::Train) { render_picking(rendermode::pickcontrols); } - if (m_picknodewanted) + if (picking && m_picknodewanted) { render_picking(rendermode::pickscenery); } @@ -1030,6 +1072,15 @@ bool vulkan14_renderer::Render() report_device_lost(failure); return false; } + if (job.skipped) + { + // the frame was left out: its images aren't presented (SwapBuffers()) + for (auto *window : ctx.acquired) + { + window->drop_images(); + } + ctx.acquired.clear(); + } frame.done = ctx.timelinevalue = value; } @@ -1039,41 +1090,70 @@ bool vulkan14_renderer::Render() return true; } +bool vulkan14_renderer::make_viewport_targets(std::size_t const Index) +{ + if (m_context == nullptr) + { + return false; + } + auto &ctx{*m_context}; + auto &scene{ctx.scene}; + if (scene.targets.size() < m_viewports.size()) + { + scene.targets.resize(m_viewports.size()); + } + auto const &viewport{m_viewports[Index]}; + auto &targets{scene.targets[Index]}; + auto const srgb{false == Global.gfx_shadergamma}; + auto const *history{targets.taa_history[0].get()}; + auto const *upscaled{targets.dlss_output.get()}; + auto const *reflections{targets.ssr_history.get()}; + auto const dlss{viewport.main && dlss_active() && (viewport.output_width > 0) && (viewport.output_height > 0)}; + if (false == make_targets(ctx.memory, ctx.deletions, ctx.uploads.current_value(), scene.formats_count, ctx.device.caps().limits.framebufferColorSampleCounts & ctx.device.caps().limits.framebufferDepthSampleCounts, scene.bloom_format, + scene.history_format, targets, viewport.width, viewport.height, viewport.output_width, viewport.output_height, srgb, viewport.main && Global.gfx_taa(), + viewport.main && (false == Global.gfx_skippipeline) && ((Global.gfx_ssr > 0) || (m_raytracingon && scene.raytracing)), dlss)) + { + return false; + } + if (viewport.main && ((targets.taa_history[0].get() != history) || (targets.dlss_output.get() != upscaled))) + { + // new images of the history, nothing in them yet + m_taa.reset(); + m_dlssreset = true; + } + if (targets.ssr_history.get() != reflections) + { + m_ssr.reset(); + } + return true; +} + void vulkan14_renderer::render_scene() { auto &ctx{*m_context}; auto &scene{ctx.scene}; // the water on the windscreens of the cab: a step of its simulation once a frame, before the passes which draw the glasses scene.water.update(Timer::GetDeltaTime()); + // the drops and the rivulets of the glasses with rain, for the time the block of the scene gets (scene_ubs.time) + // (the drops a cell may hold: as many as the glass is wet, a little more, since it's the wetness of the frame before) + // (none for a cab without a glass of the rain) + scene.water.update_rain_cells(static_cast(Timer::GetTime()), ((m_glasswet > 0.001) && scene.water.wants_rain_cells()) ? static_cast(std::min(m_glasswet + 0.01, 1.0)) : 0.f); if (scene.targets.size() < m_viewports.size()) { scene.targets.resize(m_viewports.size()); } for (std::size_t i = 0; i < m_viewports.size(); ++i) { - auto const &viewport{m_viewports[i]}; - auto const srgb{false == Global.gfx_shadergamma}; - auto const *history{scene.targets[i].taa_history[0].get()}; - auto const *upscaled{scene.targets[i].dlss_output.get()}; - auto const *reflections{scene.targets[i].ssr_history.get()}; - auto const dlss{viewport.main && dlss_active() && (viewport.output_width > 0) && (viewport.output_height > 0)}; - if (false == make_targets(ctx.memory, ctx.deletions, ctx.uploads.current_value(), scene.formats_count, ctx.device.caps().limits.framebufferColorSampleCounts & ctx.device.caps().limits.framebufferDepthSampleCounts, scene.bloom_format, - scene.history_format, scene.targets[i], viewport.width, viewport.height, viewport.output_width, viewport.output_height, srgb, viewport.main && Global.gfx_taa(), - viewport.main && (false == Global.gfx_skippipeline) && ((Global.gfx_ssr > 0) || (m_raytracingon && scene.raytracing)), dlss)) + if (auto const &viewport{m_viewports[i]}; (viewport.window < ctx.windows.size()) && ctx.windows[viewport.window]->minimized()) + { + // nothing of it is shown, and a window without a size has no projection to draw with + continue; + } + if (false == make_viewport_targets(i)) { continue; } - if (viewport.main && ((scene.targets[i].taa_history[0].get() != history) || (scene.targets[i].dlss_output.get() != upscaled))) - { - // new images of the history, nothing in them yet - m_taa.reset(); - m_dlssreset = true; - } auto &targets{scene.targets[i]}; - if (targets.ssr_history.get() != reflections) - { - m_ssr.reset(); - } if (targets.ssr_history && (false == targets.ssr_cleared)) { // the pass sets hold the history from now on, it's read (by none of the pixels) before the first frame goes to it @@ -1273,7 +1353,8 @@ void vulkan14_renderer::setup_pass(viewport_config &Viewport, renderpass_config { float const fovy = glm::radians(Global.FieldOfView / Global.ZoomFactor); // setup virtual screen - glm::vec2 screen_h = glm::vec2(Global.window_size) / 2.0f; + // a minimized window has no size: its projection would be made of nothing but NaN + glm::vec2 screen_h = glm::vec2(glm::max(Global.window_size, glm::ivec2{1})) / 2.0f; float const dist = screen_h.y / glm::tan(fovy / 2.0f); Viewport.projection.pa = glm::vec3(-screen_h.x, -screen_h.y, -dist); Viewport.projection.pb = glm::vec3(screen_h.x, -screen_h.y, -dist); @@ -1486,16 +1567,77 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) // vehicle (V is along the front of the vehicle) glm::dvec3 air{glm::dvec3{simulation::Environment.wind()} * 0.5}; if (TDynamicObject const *owner = Global.pCamera.m_owner) - air -= owner->VectorFront() * owner->MoverParameters->V; + air -= owner->VectorFront() * owner->Speed(); scene_ubs.rain_wind = glm::vec4{glm::vec3{air}, 0.f}; } - if (TDynamicObject const *owner = Global.pCamera.m_owner; owner && !!owner->MoverParameters->CabActive) + // the wipers of the vehicle the camera is in, or of the train driven when the camera is outside it: the moments the blades + // were at the ends of their sweep (the drops on the glass come back from then) are kept while the camera is away, so the glass + // looks as the blades left it when it's back in the cab. they're forgotten only for another vehicle. the views from outside + // (freefly, the views of the consist) put the camera at any vehicle of the train, one with an active cab of its own too: they + // follow the train driven, so going round them doesn't wipe the insects and the memory of the blades + TDynamicObject const *owner = FreeFlyModeFlag ? nullptr : Global.pCamera.m_owner; + if ((owner == nullptr) || (owner->ActiveCab() == 0)) + owner = (simulation::Train != nullptr) ? simulation::Train->Dynamic() : nullptr; + if (owner != m_wipervehicle) { + m_wipervehicle = owner; + scene_ubs.wiper_timer_out = glm::vec4{-1000.}; + scene_ubs.wiper_timer_return = glm::vec4{-1000.}; + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + for (auto &pass : scene_ubs.wiper_rain_pass) + pass = glm::vec4{-1.f}; + m_wiperlastpos.fill(-1.0); + m_wiperbugs = 0.0; + } + // the insects the vehicle meets (mat_bugs_windscreen): none below 20 km/h, above it the more the faster, counted in seconds of + // driving at 100 km/h. none in winter, and the rain or the snow washes them off: once it stops (and out of winter) the glass + // gets them anew from none, and what the blades left of them before is forgotten + // the glass meets the insects and the rain once a frame, not once a view (the views of a frame have its time) + auto const glassstep{(scene_ubs.time != m_glasssteptime) ? Timer::GetDeltaTime() : 0.0}; + m_glasssteptime = scene_ubs.time; + auto const insects{(Global.Season != "winter:") && (Global.Weather != "rain:") && (Global.Weather != "snow:")}; + if (false == insects) + { + if (m_wiperbugs > 0.0) + { + scene_ubs.wiper_bugs_out = glm::vec4{-1.}; + scene_ubs.wiper_bugs_return = glm::vec4{-1.}; + } + m_wiperbugs = 0.0; + } + else if (owner != nullptr) + m_wiperbugs += glassstep * std::max(std::abs(owner->Speed()) * 3.6 - 20.0, 0.0) / 80.0; + scene_ubs.rain_wind.w = static_cast(m_wiperbugs); + // the rain the glass meets (mat_rain_windscreen): counted in seconds of the heaviest rain standing still, more at speed (the + // glass runs into it). the glass fills with it up to as many drops as it gets (a lighter rain only fills it more slowly) while + // it rains, and is clear at once when it doesn't (the rain stopped, or the glass holds snow) + { + constexpr double fill_rate{0.3}; // per second of the heaviest rain: 95% full in 10 s (20 s at cloud cover 1.5) + constexpr double fill_speed{1.5}; // at 100 km/h and more the glass meets x (1 + fill_speed) as much rain + auto const dt{glassstep}; + auto const speed{(owner != nullptr) ? std::min(std::abs(owner->Speed()) * 3.6 / 100.0, 1.0) : 0.0}; + auto const meet{static_cast(percipitation_intensity) * (1.0 + fill_speed * speed)}; + m_wiperrain += dt * meet; + if ((percipitation_intensity > 0.f) && (Global.Weather == "rain:")) + m_glasswet += (1.0 - m_glasswet) * (1.0 - std::exp(-fill_rate * dt * meet)); + else + m_glasswet = 0.0; + // w: the cells of the rain worked out in this frame (render_scene(), before the viewports), the glasses read them only then + scene_ubs.rain_state = glm::vec4{static_cast(m_wiperrain), static_cast(m_glasswet), static_cast(fill_rate), scene.water.rain_cells_valid() ? 1.f : 0.f}; + } + if (owner != nullptr) + { + auto const cabactive{owner->ActiveCab() != 0 ? owner->ActiveCab() : 1}; for (int i = 0; i < 4; ++i) { if (i < owner->dWiperPos.size()) { - int index = owner->MoverParameters->CabActive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + int index = cabactive > 0 ? i : static_cast(owner->dWiperPos.size() - 1) - i; + // the places of its sweep the blade went over since the last frame get the rain fallen now + auto const position{owner->dWiperPos[index]}; + gl::wiper_pass_mark(scene_ubs, i, (m_wiperlastpos[i] < 0.0) ? position : m_wiperlastpos[i], position, static_cast(m_wiperrain)); + m_wiperlastpos[i] = position; scene_ubs.wiper_pos[i] = owner->dWiperPos[index]; if (owner->dWiperPos[index] > 0. && owner->wiperDirection[index]) { @@ -1504,10 +1646,12 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (owner->dWiperPos[index] < .025) { scene_ubs.wiper_timer_out[i] = scene_ubs.time; + scene_ubs.wiper_bugs_out[i] = static_cast(m_wiperbugs); } if (owner->dWiperPos[index] > .975) { scene_ubs.wiper_timer_return[i] = scene_ubs.time; + scene_ubs.wiper_bugs_return[i] = static_cast(m_wiperbugs); } } else @@ -1515,14 +1659,16 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene_ubs.wiper_pos[i] = 0.; scene_ubs.wiper_timer_out[i] = -1000.; scene_ubs.wiper_timer_return[i] = -1000.; + scene_ubs.wiper_bugs_out[i] = -1.; + scene_ubs.wiper_bugs_return[i] = -1.; + gl::wiper_pass_mark(scene_ubs, i, 0.0, 1.0, -1.f); + m_wiperlastpos[i] = -1.0; } } } else { scene_ubs.wiper_pos = glm::vec4{0.}; - scene_ubs.wiper_timer_out = glm::vec4{-1000.}; - scene_ubs.wiper_timer_return = glm::vec4{-1000.}; } } // the stages after D: no contact shadows, no cascades fitted to the depth, no shadow maps of headlights @@ -1589,7 +1735,8 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) if (vp.main && (Global.pCamera.m_owner != nullptr)) m_freecamera.reset(); auto const freecameramovement{(vp.main && (Global.pCamera.m_owner == nullptr)) ? m_freecamera.next_frame(Global.pCamera.Pos) : glm::vec3{0.f}}; - // the motion blur only when something in the view moves (see opengl46_renderer::Render_pass()) + // the motion blurred only when something in the view moves (see opengl46_renderer::Render_pass()); the pass runs also for the + // glasses which ask it (render_post()) auto const motionblur{Global.gfx_postfx_motionblur_enabled && targets.motion && (m_vehiclesmoved || (freecameramovement != glm::vec3{0.f}) || ((Global.pCamera.m_owner != nullptr) && (Global.pCamera.m_owner->get_future_movement() != glm::dvec3{0.0})))}; @@ -1624,6 +1771,12 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) } auto const clustered{clusters && Global.gfx_lights_clustered && (scene.clusters.params.valid != 0)}; update_lights(simulation::Lights, true, clustered); + if (false == clustered) + { + // the lights of the view for the kernels of its clouds and its fog, which run before its rendering begins: without the clusters + // update_lights() leaves the header to the first draw, and the kernels would read the one of an earlier pass + upload_light_header(); + } ctx.passes.end_pass(); // the clouds of the view and the fog volume, which take the lights of the clusters and the shadow map of the pass @@ -1633,6 +1786,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) scene.skyocclusion.setup_scene(scene_ubs, m_colorpass.pass_camera.position()); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_colorpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_colorpass.pass_camera.position()); setup_shadow_matrices(); upload_scene_block(); if (clustered) @@ -1668,6 +1822,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) walk_blending(true); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_colorpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_colorpass.pass_camera.position()); upload_scene_block(); render_environment(&simulation::Environment); @@ -1785,6 +1940,7 @@ void vulkan14_renderer::render_viewport(std::size_t const Index) } commands->end_rendering(); end_draws(); + resolve_colour(Index); if (m_contactshadows || m_ssractive || m_aolighting || m_cabprobelit) { // the depth they read is of this view only, and so is the probe of the cab @@ -1884,8 +2040,9 @@ void vulkan14_renderer::render_scene_depth(std::size_t const Index, glm::mat4 co auto const colourstats{m_renderpass.draw_stats}; m_renderpass.draw_stats = {}; walk_blending(false); - // the conditions of the cab drawn early by the colour pass - if ((false == FreeFlyModeFlag) && (Global.Overcast <= 1.0f) && Global.render_cab && simulation::Train) + // the cab first, also in the rain: the colour pass draws it after the rain then (the rain inside it hidden), but with its depth here + // nothing the cab hides is shaded by the opaque pass (in a station seen from the cab: about a third of the time of the opaque pass) + if ((false == FreeFlyModeFlag) && Global.render_cab && simulation::Train) { model_ubs.future = m_cabfuture; auto const *vehicle{simulation::Train->Dynamic()}; @@ -1997,7 +2154,9 @@ void vulkan14_renderer::setup_screen_reflections(std::size_t const Index, bool c // the ray traced reflections, of the main view only (as the screen space ones, which they fill in) bool vulkan14_renderer::raytracing_wanted(viewport_config const &Viewport) const { - if ((false == m_raytracingon) || (false == bool(m_context->scene.raytracing)) || (false == Viewport.main) || Global.bWireFrame || Global.gfx_skippipeline) + // not while the set of the frame has no structure to trace through (ray_tracing::begin_frame() without memory for it) + if ((false == m_raytracingon) || (false == bool(m_context->scene.raytracing)) || (false == m_context->scene.raytracing->traceable(m_context->slot)) || (false == Viewport.main) || Global.bWireFrame || + Global.gfx_skippipeline) { return false; } @@ -2088,8 +2247,10 @@ void vulkan14_renderer::gather_ray_draw(gfx::geometry_handle const &Geometry) { return 0; } - auto &texture{m_context->textures->mark_as_used(Texture)}; - return ((texture.create() && (m_context->images.find(texture.get_id()) != nullptr)) ? texture.get_id() : 0); + // made by the background threads as the ones of the draws are (gfx.vulkan.asyncresources; made now without them): what the rays + // hit goes without its texture till it's there, the frame doesn't wait for the files of everything within their range + auto &texture{static_cast(m_context->textures->mark_as_used(Texture))}; + return ((texture.request_background() && (m_context->images.find(texture.get_id()) != nullptr)) ? texture.get_id() : 0); }; if ((draw.program != nullptr) && ((draw.program == m_rtterrain[0]) || (draw.program == m_rtterrain[1]))) { @@ -2200,6 +2361,39 @@ void vulkan14_renderer::store_ssr_history(std::size_t const Index, vk14::image & m_ssr.end_frame(); } +// the colour and the velocity of a viewport drawn with more than one sample resolved to the images the post-processing reads, once +// its colour pass is over: a rendering of them with nothing drawn, which resolves them when it ends +void vulkan14_renderer::resolve_colour(std::size_t const Index) +{ + auto &targets{m_context->scene.targets[Index]}; + if (targets.samples == VK_SAMPLE_COUNT_1_BIT) + { + return; + } + VkClearValue const none{}; + std::array colours{}; + colours[0] = attachment_info(targets.msaa_colour->view(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, false, none); + colours[0].resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT; + colours[0].resolveImageView = targets.colour->view(); + colours[0].resolveImageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + if (targets.motion) + { + colours[1] = attachment_info(targets.msaa_motion->view(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, false, none); + colours[1].resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT; + colours[1].resolveImageView = targets.motion_image->view(); + colours[1].resolveImageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; + } + VkRenderingInfo rendering{}; + rendering.sType = VK_STRUCTURE_TYPE_RENDERING_INFO; + rendering.renderArea = {{0, 0}, targets.extent}; + rendering.layerCount = 1; + rendering.colorAttachmentCount = targets.formats.colours; + rendering.pColorAttachments = colours.data(); + // the images are in the layouts the colour pass left them in (colour_target_uses()) + m_commands->begin_rendering(&rendering); + m_commands->end_rendering(); +} + // the rendering of the colour of a viewport: begun with the images cleared, or again after the depth under the cursor was read void vulkan14_renderer::begin_colour_rendering(std::size_t const Index, bool const Clear) { @@ -2211,27 +2405,19 @@ void vulkan14_renderer::begin_colour_rendering(std::size_t const Index, bool con VkClearValue depthclear{}; depthclear.depthStencil = {0.f, 0}; std::array colours{}; + // with more than one sample the colour and the velocity are resolved once, when the pass is over (resolve_colour()): the + // rendering is ended and begun again several times in a pass (the depth of the scene, the culling, the particles), and nothing + // reads the resolved images till it's over colours[0] = attachment_info((msaa ? targets.msaa_colour : targets.colour)->view(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, Clear, colourclear); - if (msaa) - { - colours[0].resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT; - colours[0].resolveImageView = targets.colour->view(); - colours[0].resolveImageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - } if (targets.motion) { colours[1] = attachment_info((msaa ? targets.msaa_motion : targets.motion_image)->view(), VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, Clear, colourclear); - if (msaa) - { - colours[1].resolveMode = VK_RESOLVE_MODE_AVERAGE_BIT; - colours[1].resolveImageView = targets.motion_image->view(); - colours[1].resolveImageLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; - } } auto depth{attachment_info((msaa ? targets.msaa_depth : targets.depth)->view(), VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, Clear, depthclear)}; if (msaa) { - // the depth of the first sample, for the motion blur and the cursor of the editor + // the depth of the first sample, for the motion blur and the cursor of the editor; resolved each time the rendering ends, what + // reads it in the middle of the pass (the depth pyramid of the culling, the particles) takes it from there depth.resolveMode = VK_RESOLVE_MODE_SAMPLE_ZERO_BIT; depth.resolveImageView = targets.depth->view(); depth.resolveImageLayout = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL; @@ -2330,6 +2516,10 @@ void vulkan14_renderer::render_shadows(viewport_config &Viewport) ensure_cull(); } static char const *const parts[] = {"sun shadows 1", "sun shadows 2", "sun shadows 3"}; + // the camera of the view, given back to the scene block after the cascades (walk_cascade() puts the one of each in it) + auto const colorinvview{scene_ubs.inv_view}; + auto const colorcamerahi{scene_ubs.camera_hi}; + auto const colorcameralo{scene_ubs.camera_lo}; for (std::size_t idx = 0; idx < m_shadowpass.size(); ++idx) { ctx.passes.begin_pass(parts[idx], {vk14::use_of(*scene.shadow_map, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, depth_stage, depth_access)}); @@ -2353,6 +2543,9 @@ void vulkan14_renderer::render_shadows(viewport_config &Viewport) } ctx.passes.end_pass(); } + scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; vk14::barriers(commands, {vk14::use_of(*scene.shadow_map, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, sampled_stage, sampled_access)}); } @@ -2377,6 +2570,10 @@ void vulkan14_renderer::walk_cascade(std::size_t const Index) start_draws(scene.shadow_formats, static_cast(scene.shadow_size), static_cast(scene.shadow_size), vk14::scene_state::set_plain, true); m_shadowcascade = static_cast(Index); walk_blending(false); + // the rotation and the place of the camera of the cascade (the sun's): the shaders which put the model in the world (mat_vat.vert, + // the moment of the animation of every one of the animals and people from its place and turn) see the same as in the colour pass + scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_renderpass.pass_camera.position()); upload_scene_block(); if (m_shadowcolor != colors::white) { @@ -2411,7 +2608,9 @@ bool vulkan14_renderer::render_reflections(viewport_config &Viewport) { // no update in progress, check whether it's time for another one auto const timestamp{Timer::GetRenderTime()}; - if ((timestamp - m_environmentupdatetime < Global.reflectiontune.update_interval) && (glm::length2(m_renderpass.pass_camera.position() - m_environmentupdatelocation) < sq(1000.0))) + // the first one doesn't wait: the map holds nothing till then + if (m_environmentready && (timestamp - m_environmentupdatetime < Global.reflectiontune.update_interval) && + (glm::length2(m_renderpass.pass_camera.position() - m_environmentupdatelocation) < sq(1000.0))) { return false; } @@ -2539,6 +2738,7 @@ void vulkan14_renderer::render_reflection_face(viewport_config &Viewport) walk_blending(true); scene_ubs.projection = OpenGLMatrices.data(GL_PROJECTION); scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{m_renderpass.pass_camera.modelview()}}); + gl::set_camera_place(scene_ubs, m_renderpass.pass_camera.position()); upload_scene_block(); // the sky and the clouds alone: the scenery is reflected by the screen space reflections (gfx.ssr) and the ray tracing, the // environment map gives what they don't find @@ -3675,10 +3875,13 @@ void vulkan14_renderer::render_post(std::size_t const Index, bool const Motionbl store_ssr_history(Index, *hdr); } m_ssrframe = false; - if (Motionblur && targets.blurred) + // the pass of the motion blur: with Motionblur, and also when a glass in the view may ask it in the velocity target for the + // picture in its drops and its haze (mat_rain_windscreen, mat_bugs_windscreen, mat_snow_windscreen), standing still, with the + // motion blur off and with any anti-aliasing. the motion is blurred only with Motionblur (by 0 otherwise) + if (targets.blurred && targets.motion_image && (Motionblur || ctx.scene.water.wants_glass_requests())) { vk14::draw_constants constants; - constants.data[0].x = m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter); + constants.data[0].x = Motionblur ? m_framerate / (1.0 / Global.gfx_postfx_motionblur_shutter) : 0.0; // with the frames generated by dlss each frame drawn is shown for a part of its time: the blur as much shorter (the guide of // the frame generation) if (m_generationinputs && m_viewports[Index].main) @@ -4038,7 +4241,7 @@ void vulkan14_renderer::write_local_light(gl::light_element &Light, gfx::local_l void vulkan14_renderer::headlight_projector(light_array::light_record const &Light, glm::dvec3 &Position, glm::mat3 &Rotation, glm::mat4 &Projection, float &Near, float &Fieldofview) { - auto const &ownerdimensions{Light.owner->MoverParameters->Dim}; + auto const &ownerdimensions{Light.owner->Dimensions()}; auto const up{static_cast(Light.owner->VectorUp())}; auto const size{static_cast(std::max(ownerdimensions.W, ownerdimensions.H) * 1.0)}; auto const cone{5.f}; @@ -4317,6 +4520,7 @@ scene::basic_node const *vulkan14_renderer::Pick_Node() const void vulkan14_renderer::Forget_Node(scene::basic_node const *Node) { + m_locallights.forget(Node); if (m_picksceneryitem == Node) { m_picksceneryitem = nullptr; diff --git a/rendering/vulkan14/vulkan14geometry.cpp b/rendering/vulkan14/vulkan14geometry.cpp index bff2da75c..efbc4f53d 100644 --- a/rendering/vulkan14/vulkan14geometry.cpp +++ b/rendering/vulkan14/vulkan14geometry.cpp @@ -124,6 +124,11 @@ void vulkan14_geometrybank::gpu_vertices(geometry_chunk const &Chunk, std::vecto bool vulkan14_geometrybank::build() { + // there was no memory for the buffers a moment ago: tried again after a while, not by every draw of every chunk of the bank + if (m_failed && (std::chrono::steady_clock::now() - m_failedat < std::chrono::seconds{1})) + { + return false; + } release_(); std::vector vertices; @@ -176,12 +181,18 @@ bool vulkan14_geometrybank::build() } if (false == ok) { - log_error("no memory for the geometry of a bank of " + std::to_string(vertices.size()) + " vertices"); + if (false == m_failed) + { + log_error("no memory for the geometry of a bank of " + std::to_string(vertices.size()) + " vertices, trying again every second"); + } release_(); - // tried again when it's drawn the next time + // tried again when it's drawn after a while m_layoutdirty = true; + m_failed = true; + m_failedat = std::chrono::steady_clock::now(); return false; } + m_failed = false; return true; } diff --git a/rendering/vulkan14/vulkan14geometry.h b/rendering/vulkan14/vulkan14geometry.h index e508f351f..487def7ce 100644 --- a/rendering/vulkan14/vulkan14geometry.h +++ b/rendering/vulkan14/vulkan14geometry.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14common.h" #include "rendering/vulkan14/vulkan14memory.h" +#include #include #include @@ -98,6 +99,9 @@ class vulkan14_geometrybank : public gfx::geometry_bank std::vector m_places; bool m_layoutdirty{true}; // the buffers have to be made anew bool m_chunksdirty{false}; // some chunks have to be copied + // the buffers couldn't be made (no memory for them), and when: made again after a while + bool m_failed{false}; + std::chrono::steady_clock::time_point m_failedat{}; VkDeviceSize m_bytes{0}; // the buffers made or updated by one of the threads drawing from the bank at a time std::mutex m_mutex; diff --git a/rendering/vulkan14/vulkan14indirect.cpp b/rendering/vulkan14/vulkan14indirect.cpp index 4daa5849e..d47428fe7 100644 --- a/rendering/vulkan14/vulkan14indirect.cpp +++ b/rendering/vulkan14/vulkan14indirect.cpp @@ -108,10 +108,9 @@ vk14::instance_cull &vulkan14_renderer::pass_cull() void vulkan14_renderer::ensure_cull() { auto &cull{m_context->scene.cull}; - static bool tried{false}; - if ((m_main == nullptr) && (Global.gfx_gpucull != 0) && (false == cull.ready) && (false == tried)) + if ((m_main == nullptr) && (Global.gfx_gpucull != 0) && (false == cull.ready) && (false == cull.tried)) { - tried = true; + cull.tried = true; if (false == init_cull()) { ErrorLog("vulkan: the gpu culling of the instances can't be used, the cpu culls them (gfx.gpucull)"); @@ -277,12 +276,42 @@ void vulkan14_renderer::resume_rendering() // the draws -vk14::scene_program *vulkan14_renderer::multidraw_program(vk14::scene_program &Program) +namespace +{ + +// the variant of a program of the scene for the multi draws (MODEL_DRAWS), null when its shaders can't be made. any thread +std::shared_ptr multidraw_variant(vk14::shader_library &Shaders, std::string const &Defines, std::string const &Vertex, std::string const &Fragment, std::string const &Name) +{ + try + { + auto variant{std::make_shared()}; + variant->defines = Defines + "#define MODEL_DRAWS\n"; + variant->vertex = Shaders.get(Vertex, variant->defines); + variant->fragment = Shaders.get(Fragment, variant->defines); + variant->vertex_name = Vertex; + variant->fragment_name = Fragment; + variant->vertices = vk14::vertex_kind::scene; + variant->name = Name + " (multi draws)"; + variant->multidraw_tried = true; + return variant; + } + catch (gfx::shader_exception const &Exception) + { + vk14::log_error(Exception.what()); + } + return nullptr; +} + +} // namespace + +vk14::scene_program *vulkan14_renderer::multidraw_program(vk14::scene_program &Program, bool &Pending) { // made by one of the threads walking the passes (M2) std::lock_guard lock(Program.mutex); + Pending = false; if (Program.multidraw_tried) { + Pending = Program.multidraw_pending; return Program.multidraw.get(); } Program.multidraw_tried = true; @@ -291,23 +320,22 @@ vk14::scene_program *vulkan14_renderer::multidraw_program(vk14::scene_program &P return nullptr; } auto &ctx{*m_context}; - try + if (Global.gfx_vulkan_asyncresources && ctx.background.running()) { - auto variant{std::make_shared()}; - variant->defines = Program.defines + "#define MODEL_DRAWS\n"; - variant->vertex = ctx.shaders.get(Program.vertex_name, variant->defines); - variant->fragment = ctx.shaders.get(Program.fragment_name, variant->defines); - variant->vertex_name = Program.vertex_name; - variant->fragment_name = Program.fragment_name; - variant->vertices = Program.vertices; - variant->name = Program.name + " (multi draws)"; - variant->multidraw_tried = true; - Program.multidraw = std::move(variant); - } - catch (gfx::shader_exception const &Exception) - { - vk14::log_error(Exception.what()); + // its shaders are compiled by the background threads (gfx.vulkan.asyncresources), the draws left out till they are, as the + // ones without their pipeline are: the walk doesn't wait for the compiler, nor do the other threads binding the program for + // its lock. the program outlives the threads (stopped first when the scene goes) + Program.multidraw_pending = true; + Pending = true; + ctx.background.add([&shaders = ctx.shaders, program = &Program, defines = Program.defines, vertex = Program.vertex_name, fragment = Program.fragment_name, name = Program.name]() { + auto variant{multidraw_variant(shaders, defines, vertex, fragment, name)}; + std::scoped_lock const made{program->mutex}; + program->multidraw = std::move(variant); + program->multidraw_pending = false; + }); + return nullptr; } + Program.multidraw = multidraw_variant(ctx.shaders, Program.defines, Program.vertex_name, Program.fragment_name, Program.name); return Program.multidraw.get(); } @@ -361,8 +389,9 @@ bool vulkan14_renderer::draw_indirect(vk14::instance_cull &Cull, command_set con auto slice{(window.open && (size <= draws.window)) ? draw.draws_cache.allocate_before(size, draws.stride, window.base, window.base + draws.window) : vk14::ring_slice{}}; if ((false == bool(slice)) && (size <= draws.window)) { - slice = draw.draws_cache.allocate(size, draws.stride); - if (slice) + // further on in the ring; the window stays where it is while the blocks lie within it (push_draw_block()) + slice = (window.open ? draw.draws_cache.allocate_after(size, draws.stride, window.base) : draw.draws_cache.allocate(size, draws.stride)); + if (slice && ((false == window.open) || (slice.offset + slice.size > window.base + draws.window))) { window.base = slice.offset; window.open = true; @@ -454,7 +483,8 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_colour(vk14: } walk_material(m_indirectdraws[index].material, m_indirectdraws[index].submodel); auto *program{draw.program}; - auto *multidraw{(m_indirectmultidraw && (program != nullptr)) ? multidraw_program(*program) : nullptr}; + auto pending{false}; + auto *multidraw{(m_indirectmultidraw && (program != nullptr)) ? multidraw_program(*program, pending) : nullptr}; auto last{index + 1}; if (multidraw != nullptr) { @@ -464,7 +494,7 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_colour(vk14: ++last; } } - if (program != nullptr) + if ((program != nullptr) && (false == pending)) { auto const drawcount{static_cast(last - index)}; if (draw_indirect(Cull, Set, index, drawcount, (multidraw != nullptr ? *multidraw : *program), (draw.blending ? vk14::blend_mode::scene_alpha : vk14::blend_mode::none))) @@ -541,7 +571,14 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_depth(vk14:: for (auto prepassclass = 1; prepassclass <= 2; ++prepassclass) { auto &program{prepassclass == 1 ? *scene.prepass : *scene.prepass_alpha}; - auto *multidraw{m_indirectmultidraw ? multidraw_program(program) : nullptr}; + auto pending{false}; + auto *multidraw{m_indirectmultidraw ? multidraw_program(program, pending) : nullptr}; + if (pending) + { + // the shaders of its multi draws are being compiled: its draws are left out, the colour pass writes their depth + m_prepassincomplete = (m_prepassincomplete || draw.depthpass); + continue; + } for (std::size_t index = 0; index < count;) { texture_handle texture; @@ -593,19 +630,42 @@ vulkan14_renderer::indirect_counts vulkan14_renderer::draw_indirect_shadow(vk14: { auto const &entry{m_indirectdraws[index]}; auto const texture{Indirect_Shadow_Texture(entry.material)}; - auto &program{m_cubeshadows ? (texture != null_handle ? *scene.cube_alpha_shadow : *scene.cube_shadow) : (texture != null_handle ? *scene.alpha_shadow : *scene.shadow)}; - auto *multidraw{m_indirectmultidraw ? multidraw_program(program) : nullptr}; + // a material which moves its vertices itself: its own program, with its textures; the draws of it alone go together + auto *own{own_shadow_program(entry.material)}; + auto &program{own != nullptr ? *own : + m_cubeshadows ? (texture != null_handle ? *scene.cube_alpha_shadow : *scene.cube_shadow) : + (texture != null_handle ? *scene.alpha_shadow : *scene.shadow)}; + auto pending{false}; + auto *multidraw{m_indirectmultidraw ? multidraw_program(program, pending) : nullptr}; + if (pending) + { + // the shaders of its multi draws are being compiled: the draw is left out till they're there + ++index; + continue; + } auto last{index + 1}; if (multidraw != nullptr) { // the draws which follow in the same bank and of the same primitive, with the same texture for the alpha test while ((last < count) && (last - index < longest) && (m_indirectdraws[last].group == entry.group) && (m_indirectdraws[last].type == entry.type) && - (m_indirectcommands[last].indexed == m_indirectcommands[index].indexed) && (Indirect_Shadow_Texture(m_indirectdraws[last].material) == texture)) + (m_indirectcommands[last].indexed == m_indirectcommands[index].indexed) && (Indirect_Shadow_Texture(m_indirectdraws[last].material) == texture) && + (own_shadow_program(m_indirectdraws[last].material) == own) && ((own == nullptr) || (m_indirectdraws[last].material == entry.material))) { ++last; } } - if (texture != null_handle) + if (own != nullptr) + { + auto const &textures{m_materials.material(entry.material).textures}; + for (std::size_t unit = 0; unit < gl::MAX_TEXTURES; ++unit) + { + if (textures[unit] != null_handle) + { + walk_texture(unit, textures[unit]); + } + } + } + else if (texture != null_handle) { walk_texture(0, texture); } @@ -624,6 +684,13 @@ void vulkan14_renderer::record_indirect_draws(vk14::instance_cull &Cull, bool co { m_indirectcull = &Cull; Walk_Indirect_Draws(Cull, Cascade); + if (false == Cull.dispatched()) + { + // the culling didn't run (its buffers or its data of the frame couldn't be had): there are no results to draw its instances + // from, and the commands of an earlier frame aren't theirs + m_indirectdraws.clear(); + m_indirectcommands.clear(); + } auto const orderstart{std::chrono::steady_clock::now()}; // with multi draws the draws with the same state follow one another; the order goes into the commands, so it comes first m_indirectmultidraw = Global.gfx_gpucull_multidraw; diff --git a/rendering/vulkan14/vulkan14lamps.cpp b/rendering/vulkan14/vulkan14lamps.cpp index 9857d5108..69f87d463 100644 --- a/rendering/vulkan14/vulkan14lamps.cpp +++ b/rendering/vulkan14/vulkan14lamps.cpp @@ -369,7 +369,13 @@ void vulkan14_renderer::render_headlight_shadow(std::size_t const Slot, light_ar camera.update_frustum(glm::perspective(fieldofview, 1.f, nearplane, reach)); setup_matrices(); auto const colorprojection{scene_ubs.projection}; + auto const colorinvview{scene_ubs.inv_view}; + auto const colorcamerahi{scene_ubs.camera_hi}; + auto const colorcameralo{scene_ubs.camera_lo}; scene_ubs.projection = projection; + // the rotation and the place of the projector, as the ones of the sun in its shadows (walk_cascade()) + scene_ubs.inv_view = glm::inverse(glm::mat4{glm::mat3{camera.modelview()}}); + gl::set_camera_place(scene_ubs, camera.position()); lamps.begin_headlight(Slot, projector, rotation, projection, Light.direction, m_framestamp); begin_local_shadow_rendering(); // the instances culled on the gpu, each slot with a culling of its own; the occupied cab, within the reach @@ -391,6 +397,9 @@ void vulkan14_renderer::render_headlight_shadow(std::size_t const Slot, light_ar lamps.end_headlight(static_cast(m_renderpass.draw_stats.drawcalls)); } scene_ubs.projection = colorprojection; + scene_ubs.inv_view = colorinvview; + scene_ubs.camera_hi = colorcamerahi; + scene_ubs.camera_lo = colorcameralo; m_renderpass = m_colorpass; } diff --git a/rendering/vulkan14/vulkan14memory.cpp b/rendering/vulkan14/vulkan14memory.cpp index 7d6cc88d1..ed0cad182 100644 --- a/rendering/vulkan14/vulkan14memory.cpp +++ b/rendering/vulkan14/vulkan14memory.cpp @@ -795,7 +795,12 @@ ring_slice ring_cache::allocate_before(VkDeviceSize const Size, VkDeviceSize con ring_slice ring_cache::allocate(VkDeviceSize const Size, VkDeviceSize const Alignment) { - if (auto const slice{allocate_before(Size, Alignment, 0, std::numeric_limits::max())}) + return allocate_after(Size, Alignment, 0); +} + +ring_slice ring_cache::allocate_after(VkDeviceSize const Size, VkDeviceSize const Alignment, VkDeviceSize const Base) +{ + if (auto const slice{allocate_before(Size, Alignment, Base, std::numeric_limits::max())}) { return slice; } diff --git a/rendering/vulkan14/vulkan14memory.h b/rendering/vulkan14/vulkan14memory.h index 9563aaaae..7b6b6ec48 100644 --- a/rendering/vulkan14/vulkan14memory.h +++ b/rendering/vulkan14/vulkan14memory.h @@ -297,6 +297,9 @@ class ring_cache // index from Base); empty, with nothing taken, otherwise. the part held may lie below Base: a large slice which got a part of its // own opened the window above it ring_slice allocate_before(VkDeviceSize Size, VkDeviceSize Alignment, VkDeviceSize Base, VkDeviceSize Limit); + // the same as allocate(), with a slice which lies at Base or above it (Base: the offset of a slice the ring gave earlier in the + // frame, the start of a window). a part held which lies below Base is let go for a new one: the ring gives its parts in rising order + ring_slice allocate_after(VkDeviceSize Size, VkDeviceSize Alignment, VkDeviceSize Base); private: // where the next slice aligned to Alignment would begin in the part held, as an offset in the buffer diff --git a/rendering/vulkan14/vulkan14raytracing.cpp b/rendering/vulkan14/vulkan14raytracing.cpp index dbb4edffd..d91a83746 100644 --- a/rendering/vulkan14/vulkan14raytracing.cpp +++ b/rendering/vulkan14/vulkan14raytracing.cpp @@ -42,6 +42,8 @@ std::uint32_t constexpr record_alpha{1}; std::uint32_t constexpr record_terrain{2}; // the bottom level structures built in a frame at most, and their triangles: the rest waits for the next frames std::uint32_t constexpr builds_per_frame{96}; +// the structures which couldn't be made (no memory for them) a frame gives up after +std::uint32_t constexpr failures_per_frame{4}; std::uint64_t constexpr triangles_per_frame{2000000}; // the instances of the top level structure at most (the records take 24 bits of the custom index) std::uint32_t constexpr max_instances{1u << 20}; @@ -429,6 +431,9 @@ void ray_tracing::build(command_stream *Commands, std::uint32_t const Slot, std: std::vector builds; std::uint64_t triangles{0}; std::uint32_t waiting{0}; + // the structures which couldn't be made (no memory for them) count as built: the others like them wait for the next frames, they + // aren't all tried in this one + std::uint32_t failed{0}; VkDeviceSize scratchsize{0}; auto const scratchalignment{static_cast(m_scratchalignment)}; // the structure of each draw, looked up once (null: none, the draw is left out); the map keeps its entries in place @@ -443,7 +448,7 @@ void ray_tracing::build(command_stream *Commands, std::uint32_t const Slot, std: found[drawindex] = &lookup->second; continue; } - if ((builds.size() >= builds_per_frame) || (triangles >= triangles_per_frame)) + if ((builds.size() + failed >= builds_per_frame) || (triangles >= triangles_per_frame) || (failed >= failures_per_frame)) { ++waiting; continue; @@ -470,6 +475,7 @@ void ray_tracing::build(command_stream *Commands, std::uint32_t const Slot, std: if ((false == generated->create(*m_memory, bytes, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR, memory_kind::upload, "ray tracing strip indices")) || (generated->mapped() == nullptr)) { + ++failed; continue; } auto *indices{reinterpret_cast(generated->mapped())}; @@ -506,6 +512,7 @@ void ray_tracing::build(command_stream *Commands, std::uint32_t const Slot, std: auto storage{std::make_shared()}; if (false == storage->create(*m_memory, sizes.accelerationStructureSize, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, memory_kind::device, "ray tracing bottom level")) { + ++failed; continue; } VkAccelerationStructureCreateInfoKHR create{}; @@ -516,6 +523,7 @@ void ray_tracing::build(command_stream *Commands, std::uint32_t const Slot, std: VkAccelerationStructureKHR structure{VK_NULL_HANDLE}; if (!VK14_VERIFY(vkCreateAccelerationStructureKHR(handle, &create, nullptr, &structure))) { + ++failed; continue; } if (lookup != m_bottoms.end()) diff --git a/rendering/vulkan14/vulkan14raytracing.h b/rendering/vulkan14/vulkan14raytracing.h index 076364806..52684d777 100644 --- a/rendering/vulkan14/vulkan14raytracing.h +++ b/rendering/vulkan14/vulkan14raytracing.h @@ -89,6 +89,12 @@ class ray_tracing { return (Slot < m_frames.size() ? m_frames[Slot].set : VK_NULL_HANDLE); } + // the set of the frame holds a structure and its records, which the rays may be traced through: not when begin_frame() had no + // memory for them (the shaders read the set only where the rays are traced) + bool traceable(std::uint32_t const Slot) const + { + return (Slot < m_frames.size()) && (m_frames[Slot].written_top != VK_NULL_HANDLE) && (m_frames[Slot].written_records != VK_NULL_HANDLE); + } // a scenery is being loaded, or the geometry is gone: the bottom level structures go void clear(std::uint64_t Value); // for the debug panel: the structures, their memory, the instances of the last frame diff --git a/rendering/vulkan14/vulkan14renderer.cpp b/rendering/vulkan14/vulkan14renderer.cpp index 417849f54..5d07dd832 100644 --- a/rendering/vulkan14/vulkan14renderer.cpp +++ b/rendering/vulkan14/vulkan14renderer.cpp @@ -273,8 +273,7 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) } if (false == record(frame, Job.uploaded, Job.async)) { - Failure = "recording a frame"; - return false; + return skip_frame(Job, false, "recording a frame", Failure); } if (Job.async) { @@ -300,10 +299,15 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) compute.pCommandBufferInfos = &buffer; compute.signalSemaphoreInfoCount = 1; compute.pSignalSemaphoreInfos = &signal; - if (!VK14_VERIFY(vkQueueSubmit2(device.compute_queue(), 1, &compute, VK_NULL_HANDLE))) + if (auto const result{vkQueueSubmit2(device.compute_queue(), 1, &compute, VK_NULL_HANDLE)}; false == vk14::verify_result(result, "vkQueueSubmit2(compute)", __FILE__, __LINE__)) { - Failure = "submitting the async compute of a frame"; - return false; + // a failed submit leaves the semaphores as they were: the frame is left out, unless the device is lost + if (result == VK_ERROR_DEVICE_LOST) + { + Failure = "submitting the async compute of a frame"; + return false; + } + return skip_frame(Job, false, "submitting the async compute of a frame", Failure); } } // the uploads first, in the same submit: their barriers make them done before the frame uses what they copied @@ -359,10 +363,14 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) submit.pCommandBufferInfos = commands.data() + (Job.async ? first : 0); submit.signalSemaphoreInfoCount = static_cast(Job.signals.size()); submit.pSignalSemaphoreInfos = Job.signals.data(); - if (!VK14_VERIFY(vkQueueSubmit2(device.graphics_queue(), count, submits.data(), VK_NULL_HANDLE))) + if (auto const result{vkQueueSubmit2(device.graphics_queue(), count, submits.data(), VK_NULL_HANDLE)}; false == vk14::verify_result(result, "vkQueueSubmit2", __FILE__, __LINE__)) { - Failure = "submitting a frame"; - return false; + if (result == VK_ERROR_DEVICE_LOST) + { + Failure = "submitting a frame"; + return false; + } + return skip_frame(Job, Job.async, "submitting a frame", Failure); } if (lowlatency) { @@ -371,6 +379,52 @@ bool vulkan14_renderer::context::submit(render_job &Job, char const *&Failure) return true; } +// the timeline reaches the value of the frame and the semaphores of its images are waited for and signalled as with the frame drawn; +// the uploads go with it, as what they copy is used by the frames after it. the images of the windows stay acquired, their +// swapchains are made anew (the main thread drops those it presents itself, Render()) +bool vulkan14_renderer::context::skip_frame(render_job &Job, bool const Compute, char const *What, char const *&Failure) +{ + auto waits{Job.waits}; + if (Compute) + { + VkSemaphoreSubmitInfo compute{}; + compute.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO; + compute.semaphore = compute_timeline; + compute.value = Job.value; + compute.stageMask = VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT; + waits.push_back(compute); + } + VkCommandBufferSubmitInfo uploadbuffer{}; + uploadbuffer.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_SUBMIT_INFO; + uploadbuffer.commandBuffer = Job.target->uploads; + VkSubmitInfo2 empty{}; + empty.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO_2; + empty.waitSemaphoreInfoCount = static_cast(waits.size()); + empty.pWaitSemaphoreInfos = waits.data(); + empty.commandBufferInfoCount = (Job.uploaded ? 1 : 0); + empty.pCommandBufferInfos = &uploadbuffer; + empty.signalSemaphoreInfoCount = static_cast(Job.signals.size()); + empty.pSignalSemaphoreInfos = Job.signals.data(); + if (false == VK14_VERIFY(vkQueueSubmit2(device.graphics_queue(), 1, &empty, VK_NULL_HANDLE))) + { + Failure = What; + return false; + } + for (auto *window : Job.windows) + { + window->drop_images(); + } + Job.windows.clear(); + Job.skipped = true; + // said the first time, then now and then while it goes on + ++skipped_frames; + if ((skipped_frames % 600) == 1) + { + vk14::log_error(std::string(What) + " failed, the frame is left out (" + std::to_string(skipped_frames) + " so far)"); + } + return true; +} + bool vulkan14_renderer::context::present(std::vector const &Windows, std::uint64_t const Id) { auto *main{windows.empty() ? nullptr : windows.front().get()}; @@ -414,7 +468,8 @@ bool vulkan14_renderer::context::present(std::vector const &W info.pImageIndices = ℑ auto const result{vkQueuePresentKHR(device.graphics_queue(), &info)}; main->presented(result); - if ((result == VK_ERROR_DEVICE_LOST) || (result == VK_ERROR_SURFACE_LOST_KHR)) + // a lost surface is made anew with the swapchain before the next image (swapchain::presented()) + if (result == VK_ERROR_DEVICE_LOST) { vk14::log_error(std::string("vkQueuePresentKHR failed with ") + vk14::result_string(result)); return false; @@ -463,7 +518,7 @@ bool vulkan14_renderer::context::present(std::vector const &W { Windows[i]->presented(results[i]); } - if ((result == VK_ERROR_DEVICE_LOST) || (result == VK_ERROR_SURFACE_LOST_KHR)) + if (result == VK_ERROR_DEVICE_LOST) { vk14::log_error(std::string("vkQueuePresentKHR failed with ") + vk14::result_string(result)); return false; @@ -1171,9 +1226,36 @@ void vulkan14_renderer::Update(double const Deltatime) { update_texture_release(); } + save_pipeline_cache(); update_info(); } +// the pipeline cache written to the disk by a background thread once pipelines were made since it was written last and the threads +// have nothing else to do, not more often than every so many seconds: a session which doesn't end as it should (a crash, a lost +// device, the process killed) keeps what it compiled +void vulkan14_renderer::save_pipeline_cache() +{ + if (!m_context) + { + return; + } + auto &ctx{*m_context}; + if ((false == ctx.background.running()) || (ctx.background.pending() > 0)) + { + return; + } + auto const count{ctx.pipelines.count()}; + auto const now{std::chrono::steady_clock::now()}; + if ((count == m_pipelinessaved) || (now - m_pipelinessavedat < std::chrono::seconds{20})) + { + return; + } + m_pipelinessaved = count; + m_pipelinessavedat = now; + // the library outlives the threads (context::destroy() stops them first) + ctx.background.add([&pipelines = ctx.pipelines]() { pipelines.save(); }, false); +} + void vulkan14_renderer::update_info() { m_infotimes.clear(); @@ -1193,7 +1275,13 @@ void vulkan14_renderer::update_info() ctx.memory.budget(usage, budget); m_infostats = "device memory: " + vk14::memory_size_string(usage) + " of " + vk14::memory_size_string(budget) + (ctx.device.memory_budget_enabled() ? "" : " (no budget from the driver)") + "\n" + "images: " + std::to_string(ctx.images.size()) + ", uploaded " + vk14::memory_size_string(ctx.uploads.uploaded()) + ", waiting for the gpu to be deleted: " + std::to_string(ctx.deletions.size()) + "\n" + (ctx.textures ? ctx.textures->info() + "\n" : std::string{}) + ctx.shaders.info() + - "\n" + ctx.pipelines.info() + "\n" + background_info() + "frame ring: " + vk14::memory_size_string(ctx.ring.used()) + " of " + vk14::memory_size_string(ctx.ring.capacity()) + "\n"; + "\n" + ctx.pipelines.info() + "\n" + background_info() + "frame ring: " + vk14::memory_size_string(ctx.ring.used()) + " of " + vk14::memory_size_string(ctx.ring.capacity()) + ", of the draws: " + + vk14::memory_size_string(ctx.scene.draws.ring.used()) + " of " + vk14::memory_size_string(ctx.scene.draws.ring.capacity()) + ", of the instances: " + + vk14::memory_size_string(ctx.scene.instances.ring.used()) + " of " + vk14::memory_size_string(ctx.scene.instances.ring.capacity()) + "\n"; + if (auto const full{ctx.scene.draws.full.load() + ctx.scene.instances.full.load()}; full > 0) + { + m_infostats += "draws left out of full rings: " + std::to_string(full) + "\n"; + } for (auto const &window : ctx.windows) { auto const extent{window->extent()}; diff --git a/rendering/vulkan14/vulkan14renderer.h b/rendering/vulkan14/vulkan14renderer.h index 66cf70fd3..0c2cf8e26 100644 --- a/rendering/vulkan14/vulkan14renderer.h +++ b/rendering/vulkan14/vulkan14renderer.h @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the vulkan 1.4 renderer, picked with gfxrenderer vulkan (claude/vulkan14-renderer-plan.md): the gpu, the windows with their +// the vulkan 1.4 renderer, picked with gfxrenderer vulkan: the gpu, the windows with their // swapchains, the frames in flight, the memory and the uploads, the shaders and the pipelines, the pushed descriptors, the passes // with their barriers and gpu times, the textures and the user interface (imgui) with the launcher (the track R of the plan), and // the scene (the track D): the geometry, the materials, the passes of the colour of the scene with the sun shadows, the @@ -37,6 +37,8 @@ http://mozilla.org/MPL/2.0/. #include "gl/ubo.h" #include +#include +#include #include class world_environment; @@ -71,6 +73,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk bool AddViewport(global_settings::extraviewport_config const &conf) override; void Shutdown() override; bool Render() override; + std::pair Prewarm_Shaders(double const Milliseconds) override; void SwapBuffers() override; float Framerate() override; // geometry @@ -258,7 +261,8 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk // Count recorded draws from First with the program (a multi draw with more than one) and the state of the draws bool draw_indirect(vk14::instance_cull &Cull, command_set const Set, std::size_t const First, std::uint32_t const Count, vk14::scene_program &Program, vk14::blend_mode const Blend); // the variant of a program for the multi draws, nullptr when there's none - vk14::scene_program *multidraw_program(vk14::scene_program &Program); + // Pending: its shaders are being compiled by the background threads, the draws it's for are left out till they're there + vk14::scene_program *multidraw_program(vk14::scene_program &Program, bool &Pending); vk14::instance_cull &pass_cull(); // the shadow maps of the lamps (vulkan14lamps.cpp, the stage P4; opengl46_renderer::Render_local_shadows() and the rest): the cab // lamp, the scenery lamps, one of them, the headlights, one set of them; the culling of a map (nullptr when its instances go @@ -415,6 +419,8 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk void update_clusters(glm::ivec2 const &Targetsize); // which program of the depth prepass stands for the program of the material: 0 none, 1 without the alpha test, 2 with it int prepass_class(material_handle const Material); + // the program of the sun shadows of a material with a vertex shader of its own (mat_.vert), nullptr for the others + vk14::scene_program *own_shadow_program(material_handle const Material) const; // the depth of the whole opaque scene of the colour pass of the main viewport before its colour, for the contact shadows // (Contactonly: with them alone) or for itself (gfx.depthprepass.scene), and the contact shadows set up to read it void render_scene_depth(std::size_t const Viewport, glm::mat4 const &Future); @@ -453,6 +459,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk void end_draws(); // the rendering of the colour of a viewport, begun with the images cleared or again where it was void begin_colour_rendering(std::size_t const Viewport, bool const Clear); + void resolve_colour(std::size_t const Viewport); void push_constants(void const *Constants); // a pipeline of the post-processing (a VkPipeline), nullptr when the shader isn't there. Encode: the colour is encoded by the // shader (OUTPUT_GAMMA), -1: as gfx.shadergamma says @@ -512,6 +519,10 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk // its own, for the gpu times). Repeated: a bit for each input read texel by texel and repeated (the noise of the ssao) void post_pass(char const *Fragment, vk14::image &Target, std::vector const &Inputs, vk14::draw_constants const &Constants, char const *Pass = nullptr, unsigned const Repeated = 0); bool bind_scene_pipeline(vk14::scene_program &Program, vk14::target_formats const &Targets, vk14::blend_mode const Blend, int const Topology); + // the images of a viewport for its size and the settings, made anew when they changed (render_scene(), Prewarm_Shaders()) + bool make_viewport_targets(std::size_t const Index); + // Prewarm_Shaders(): the pipelines the scene loaded will draw with, listed the first time + void list_prewarm_pipelines(); // Triangles: the draw is of triangles, which the prepass draws (keepdepth) void apply_draw_state(bool const Triangles = false); void push_textures(); @@ -550,6 +561,17 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk glm::vec3 m_fogcolor{0.f}; glm::vec4 m_shadowcolor{colors::shadow}; gl::scene_ubs scene_ubs{}; + // the vehicle whose wipers the timers of the blades in scene_ubs (wiper_timer_out / wiper_timer_return) follow + TDynamicObject const *m_wipervehicle{nullptr}; + // the insects that vehicle met so far: seconds of driving at 100 km/h (scene_ubs.rain_wind.w) + double m_wiperbugs{0.0}; + // the place of each blade (dWiperPos) the last frame, -1 not known: the places it went over since get the rain fallen + // (gl::wiper_pass_mark) + std::array m_wiperlastpos{-1.0, -1.0, -1.0, -1.0}; + // the rain the glass met so far and how wet it is (scene_ubs::rain_state) + double m_wiperrain{0.0}; + double m_glasswet{0.0}; + double m_glasssteptime{-1.0}; // the time of the frame the glass last met the insects and the rain in gl::light_data light_data{}; std::uint32_t m_lightcount{1}; // lights written to light_data // the copies of the light buffer in the ring of the frame since the lights were last written, by the header and the sun @@ -562,6 +584,9 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk int m_environmentcubetextureface{0}; int m_environmentupdateface{6}; bool m_environmentready{false}; + // the pipelines made when the pipeline cache was last written to the disk in the session, and when that was (save_pipeline_cache()) + std::size_t m_pipelinessaved{0}; + std::chrono::steady_clock::time_point m_pipelinessavedat{}; double m_environmentupdatetime{0.0}; glm::dvec3 m_environmentupdatelocation{0.0}; bool m_vehiclesmoved{true}; @@ -638,6 +663,7 @@ class vulkan14_renderer : public gfx_renderer, public gfx::scene_walk debug_stats m_laststats; void update_info(); + void save_pipeline_cache(); // the lines of the debug panel about the threads of the renderer other than the recording ones (the stages M2, M3, M5, M6) std::string background_info() const; // the debug windows (vulkan14debug.cpp, opengl46_renderer::draw_debug_ui()), the lines of the cullings and of the scene for them diff --git a/rendering/vulkan14/vulkan14scene.cpp b/rendering/vulkan14/vulkan14scene.cpp index 335d4faeb..0e221446a 100644 --- a/rendering/vulkan14/vulkan14scene.cpp +++ b/rendering/vulkan14/vulkan14scene.cpp @@ -24,10 +24,15 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/color.h" #include "utilities/utilities.h" +#include "vehicle/DynObj.h" #include +#include +#include #include #include +#include +#include #include namespace @@ -55,6 +60,25 @@ VkPrimitiveTopology topology_class(VkPrimitiveTopology const Topology) } } +// the instances of a draw (one when it isn't instanced) within the window of the ring the pass set reads, from its first one on: +// walk_instances() places at most a window of them, those past it aren't drawn. the instances of a culled pass aren't in the window +std::uint32_t drawn_instances(std::size_t const Count, std::uint32_t const First, VkDeviceSize const Capacity, bool const Culled) +{ + if (Count == 0) + { + return 1; + } + if (Culled) + { + return static_cast(Count); + } + if (First >= Capacity) + { + return 0; + } + return static_cast(std::min(Count, Capacity - First)); +} + vk14::vertex_layout layout_of(vk14::vertex_kind const Kind) { vk14::vertex_layout layout; @@ -78,9 +102,11 @@ vk14::vertex_layout layout_of(vk14::vertex_kind const Kind) layout.attributes = {{0, 0, VK_FORMAT_R32G32B32A32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32A32_SFLOAT, sizeof(glm::vec4)}}; break; case vk14::vertex_kind::particle: - // position, colour, texture coordinates (opengl46_particles::particle_vertex) - layout.bindings = {{0, 36, VK_VERTEX_INPUT_RATE_VERTEX}}; - layout.attributes = {{0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0}, {1, 0, VK_FORMAT_R32G32B32A32_SFLOAT, 12}, {2, 0, VK_FORMAT_R32G32_SFLOAT, 28}}; + // position, colour, texture coordinates + layout.bindings = {{0, sizeof(vk14::particle_vertex), VK_VERTEX_INPUT_RATE_VERTEX}}; + layout.attributes = {{0, 0, VK_FORMAT_R32G32B32_SFLOAT, static_cast(offsetof(vk14::particle_vertex, position))}, + {1, 0, VK_FORMAT_R32G32B32A32_SFLOAT, static_cast(offsetof(vk14::particle_vertex, color))}, + {2, 0, VK_FORMAT_R32G32_SFLOAT, static_cast(offsetof(vk14::particle_vertex, texture))}}; break; case vk14::vertex_kind::position_uv: layout.bindings = {{0, sizeof(glm::vec3), VK_VERTEX_INPUT_RATE_VERTEX}, {1, sizeof(glm::vec2), VK_VERTEX_INPUT_RATE_VERTEX}}; @@ -156,6 +182,7 @@ VkDescriptorType pass_binding_type(std::uint32_t const Binding) case CLUSTER_INDEX_SSBO: case SKY_SSBO: case WATER_SSBO: + case RAIN_CELLS_SSBO: case CAB_PROBE_SSBO: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; case ATMOSPHERE_UBO: @@ -1067,6 +1094,7 @@ void vulkan14_renderer::write_pass_sets(vk14::instance_cull *Cull) VkDescriptorBufferInfo const weatherblock{ctx.ring.handle(), 0, offsetof(gl::weather_ubs, fog_horizon)}; VkDescriptorBufferInfo const horizonblock{scene.weather_horizon.handle(), 0, sizeof(glm::vec4) * gl::FOG_HORIZON_SAMPLES}; VkDescriptorBufferInfo const water{scene.water.storage(), 0, VK_WHOLE_SIZE}; + VkDescriptorBufferInfo const raincells{scene.water.rain_cells(), 0, VK_WHOLE_SIZE}; VkDescriptorBufferInfo const cabprobe{scene.cabprobe_bounce.handle(), 0, sizeof(gl::cab_probe_data)}; VkDescriptorImageInfo const headlightsinfo{scene.headlights_sampler, scene.headlights_view, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; std::vector writes; @@ -1102,6 +1130,7 @@ void vulkan14_renderer::write_pass_sets(vk14::instance_cull *Cull) write(handle, WEATHER_UBO, &weatherblock, nullptr); write(handle, WEATHER_HORIZON_UBO, &horizonblock, nullptr); write(handle, WATER_SSBO, &water, nullptr); + write(handle, RAIN_CELLS_SSBO, &raincells, nullptr); write(handle, HEADLIGHT_TEX, nullptr, &headlightsinfo); write(handle, SHADOW_TEX, nullptr, image(ctx.sampling.shadow, views[SHADOW_TEX])); write(handle, ENV_TEX, nullptr, image(ctx.sampling.clamp_linear, views[ENV_TEX])); @@ -1415,10 +1444,14 @@ std::shared_ptr vulkan14_renderer::Fetch_Shader(std::string } // throws gfx::shader_exception, which the materials catch auto program{std::make_shared()}; - program->vertex = m_context->shaders.get("vertex.vert"); + // a material can move its vertices in a vertex shader of its own, mat_.vert (animals and people animated by textures, + // mat_vat.vert), the others take the common one + auto const ownvertex{std::filesystem::exists(gfx::shader_source_dir(gfx::shader_api::vulkan14) + "mat_" + name + ".vert")}; + auto const vertexname{ownvertex ? "mat_" + name + ".vert" : std::string("vertex.vert")}; + program->vertex = m_context->shaders.get(vertexname); program->fragment = m_context->shaders.get("mat_" + name + ".frag"); program->fragment_name = "mat_" + name + ".frag"; - program->vertex_name = "vertex.vert"; + program->vertex_name = vertexname; program->vertices = vk14::vertex_kind::scene; program->name = "mat_" + name; // the directives of the material, of both stages as the opengl program has them @@ -1427,10 +1460,51 @@ std::shared_ptr vulkan14_renderer::Fetch_Shader(std::string program->texture_conf.insert(stage->source.texture_conf.begin(), stage->source.texture_conf.end()); program->param_conf.insert(stage->source.param_conf.begin(), stage->source.param_conf.end()); } + if (ownvertex) + { + // its sun shadows go through the same vertex shader (MATERIAL_SHADOW), so they are cast by where the vertices are + std::array, 2> shadows; + for (auto alpha = 0; alpha < 2; ++alpha) + { + auto shadow{std::make_shared()}; + char const *fragment{alpha ? "alphashadowmap.frag" : "shadowmap.frag"}; + shadow->defines = "#define MATERIAL_SHADOW 1\n"; + shadow->vertex = m_context->shaders.get(vertexname, shadow->defines); + shadow->fragment = m_context->shaders.get(fragment, shadow->defines); + shadow->vertex_name = vertexname; + shadow->fragment_name = fragment; + shadow->vertices = vk14::vertex_kind::scene; + shadow->name = vertexname + " (shadow) + " + fragment; + shadows[alpha] = std::move(shadow); + } + m_context->scene.own_shadows.emplace(program.get(), std::move(shadows)); + } materials.emplace(name, program); return program; } +// the program of the sun shadows of a material with a vertex shader of its own, nullptr for the others (and in the cube maps of +// the lamps, which keep their own programs) +vk14::scene_program *vulkan14_renderer::own_shadow_program(material_handle const Material) const +{ + if ((Material == null_handle) || m_cubeshadows || (false == bool(m_context))) + { + return nullptr; + } + auto const &material{m_materials.material(Material)}; + if ((false == material.is_good) || (material.shader == nullptr)) + { + return nullptr; + } + auto const &shadows{m_context->scene.own_shadows}; + auto const lookup{shadows.find(material.shader.get())}; + if (lookup == shadows.end()) + { + return nullptr; + } + return lookup->second[material.textures[0] != null_handle ? 1 : 0].get(); +} + std::string vulkan14_renderer::Shader_Name(std::shared_ptr const &Program) const { if (m_context) @@ -1634,6 +1708,12 @@ void vulkan14_renderer::walk_material(material_handle const Material, TSubModel void vulkan14_renderer::walk_shadow_material(material_handle const Material) { + // a material which moves its vertices itself reads its params in the vertex shader of its shadow too + auto *own{own_shadow_program(Material)}; + if (own != nullptr) + { + std::memcpy(&model_ubs.param[0], &m_materials.material(Material).params[0], sizeof(model_ubs.param)); + } if (m_indirectrecording) { // the walk of the groups of the gpu culling of a shadow pass only notes the material @@ -1643,6 +1723,20 @@ void vulkan14_renderer::walk_shadow_material(material_handle const Material) } auto &draw{*m_draw}; auto &scene{m_context->scene}; + if (own != nullptr) + { + // its textures (the alpha test and the ones its vertex shader reads) and its program + auto const &textures{m_materials.material(Material).textures}; + for (std::size_t unit = 0; unit < gl::MAX_TEXTURES; ++unit) + { + if (textures[unit] != null_handle) + { + walk_texture(unit, textures[unit]); + } + } + draw.program = own; + return; + } // the cube maps of the lamps with programs of their own (the faces drawn by multiview) if (auto const texture{Indirect_Shadow_Texture(Material)}; texture != null_handle) { @@ -1805,7 +1899,7 @@ void vulkan14_renderer::walk_glare_draw(TSubModel *Submodel, gfx::geometry_handl { // the point of the light wasn't seen by the occlusion query of the last frame done by the gpu auto const &visible{m_context->scene.glare_visible}; - auto const lookup{visible.find(Submodel)}; + auto const lookup{visible.find(vk14::glare_point{Submodel, TSubModel::iInstance})}; if ((lookup != visible.end()) && (false == lookup->second)) { return; @@ -1816,7 +1910,9 @@ void vulkan14_renderer::walk_glare_draw(TSubModel *Submodel, gfx::geometry_handl void vulkan14_renderer::walk_light_query(TSubModel *Submodel, bool const Begin) { auto &draw{*m_draw}; - if (false == draw.rendering) + // the points seen in the view of the colour pass, which draws the glare; the queries of a frame are numbered by the main thread + // alone (a walker draws the cab into the shadow maps at the same time) + if ((false == draw.rendering) || (m_main != nullptr) || (m_renderpass.draw_mode != rendermode::color)) { return; } @@ -1830,7 +1926,7 @@ void vulkan14_renderer::walk_light_query(TSubModel *Submodel, bool const Begin) return; } draw.query = static_cast(submodels.size()); - submodels.push_back(Submodel); + submodels.push_back(vk14::glare_point{Submodel, TSubModel::iInstance}); draw.commands->begin_query(scene.occlusion_pools[m_context->slot], draw.query, 0); } else if (draw.query != ~0u) @@ -1910,15 +2006,20 @@ std::uint32_t vulkan14_renderer::push_draw_block() auto slice{window.open ? draw.draws_cache.allocate_before(draws.stride, draws.stride, window.base, window.base + draws.window) : vk14::ring_slice{}}; if (false == bool(slice)) { - slice = draw.draws_cache.allocate(draws.stride, draws.stride); + // the part of the ring held ran out: the next one lies further on, mostly still within the window, which then stays where it is + slice = (window.open ? draw.draws_cache.allocate_after(draws.stride, draws.stride, window.base) : draw.draws_cache.allocate(draws.stride, draws.stride)); if (false == bool(slice)) { + draws.report_full("the blocks of the draws"); return ~0u; } - // a new window of the blocks, the pass set is bound with its offset - window.base = slice.offset; - window.open = true; - draw.set_dirty = true; + if ((false == window.open) || (slice.offset + slice.size > window.base + draws.window)) + { + // a new window of the blocks, the pass set is bound with its offset + window.base = slice.offset; + window.open = true; + draw.set_dirty = true; + } } std::memcpy(slice.data, &model_ubs, sizeof(gl::model_ubs)); return static_cast((slice.offset - window.base) / draws.stride); @@ -1942,24 +2043,36 @@ std::uint32_t vulkan14_renderer::walk_instances(glm::mat4 const *Modelviews, std auto slice{window.open ? draw.instances_cache.allocate_before(size, instances.stride, window.base, window.base + instances.window) : vk14::ring_slice{}}; if (false == bool(slice)) { - // a new window, which begins with the identity of the draws which aren't instanced, followed by the instances - auto const alignment{m_context->device.caps().limits.minStorageBufferOffsetAlignment}; - auto const block{draw.instances_cache.allocate(instances.stride + size, std::max(alignment, instances.stride))}; + // what's left of the part of the ring held has no room for them: further on in the ring, never below the window (the walk + // draws instances it placed earlier after it placed others, Flush_Timbers(): their indices count from the start of the window, + // which stays where it is as long as the new ones lie within it). with room for the identity a new window begins with + auto const alignment{std::max(m_context->device.caps().limits.minStorageBufferOffsetAlignment, instances.stride)}; + auto const block{window.open ? draw.instances_cache.allocate_after(instances.stride + size, alignment, window.base) : draw.instances_cache.allocate(instances.stride + size, alignment)}; if (false == bool(block)) { - // the ring of the frame is full: the instances are drawn where the draws which aren't instanced are - window.open = false; + // the ring of the frame is full: the instanced draws are left out (draw_chunk()) + instances.report_full("the instances"); + draw.instances_lost = true; return 0; } - glm::mat4 const one{1.f}; - std::memcpy(block.data, &one, sizeof(one)); - window.base = block.offset; - window.open = true; - draw.set_dirty = true; - slice = block; - slice.data += instances.stride; - slice.offset += instances.stride; - slice.size = size; + if (window.open && (block.offset + block.size <= window.base + instances.window)) + { + slice = block; + slice.size = size; + } + else + { + // a new window, which begins with the identity of the draws which aren't instanced, followed by the instances + glm::mat4 const one{1.f}; + std::memcpy(block.data, &one, sizeof(one)); + window.base = block.offset; + window.open = true; + draw.set_dirty = true; + slice = block; + slice.data += instances.stride; + slice.offset += instances.stride; + slice.size = size; + } } std::memcpy(slice.data, Modelviews, static_cast(size)); return static_cast((slice.offset - window.base) / instances.stride); @@ -2061,6 +2174,19 @@ void vulkan14_renderer::draw_chunk(gfx::geometry_handle const &Geometry, bool co // the depth of the scene: what the programs of the prepass don't draw, and no points or lines return; } + if ((m_current_instance_count > 0) && draw.instances_lost) + { + // the matrices of the instances aren't in their ring (walk_instances()) + m_prepassincomplete = (m_prepassincomplete || draw.depthpass); + return; + } + auto const instances{drawn_instances(m_current_instance_count, m_current_instance_base, m_context->scene.instances.window / m_context->scene.instances.stride, draw.cull_sets != nullptr)}; + if (instances == 0) + { + // all of them past the window of their ring (walk_instances() places at most a window of them) + m_prepassincomplete = (m_prepassincomplete || draw.depthpass); + return; + } auto &ctx{*m_context}; auto &scene{ctx.scene}; auto const commands{draw.commands}; @@ -2111,7 +2237,6 @@ void vulkan14_renderer::draw_chunk(gfx::geometry_handle const &Geometry, bool co draw.vertices = chunk.vertices; draw.userdata = chunk.userdata; } - auto const instances{m_current_instance_count > 0 ? static_cast(m_current_instance_count) : 1u}; auto const firstinstance{m_current_instance_count > 0 ? m_current_instance_base : 0u}; if (chunk.indices != VK_NULL_HANDLE) { @@ -2202,10 +2327,23 @@ std::string list_value(std::string const &Field) return result; } -std::string pipeline_list_path() +std::filesystem::path pipeline_list_path() { auto const path{user_config_path("cache")}; - return (path.empty() ? std::string{"cache/vulkan14/pipelines.txt"} : (path / "vulkan14" / "pipelines.txt").string()); + return (path.empty() ? std::filesystem::path{"cache/vulkan14/pipelines.txt"} : (path / "vulkan14" / "pipelines.txt")); +} + +// what a line of the list of the pipelines may hold: the list is a file of the user's profile, which a crash or an editor can leave +// with anything in it, and its values go to the making of pipelines by the driver +bool pipeline_record_valid(vk14::scene_pipeline_record const &Record, std::uint32_t const Vertices, std::uint32_t const Topology) +{ + auto const format = [](VkFormat const Format) { + // the formats of the core, which the targets of the passes are of + return static_cast(Format) <= static_cast(VK_FORMAT_ASTC_12x12_SRGB_BLOCK); + }; + return (Vertices <= static_cast(vk14::vertex_kind::particle_instance)) && (Topology <= static_cast(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN)) && + (Record.blending <= static_cast(vk14::blend_mode::no_colour)) && format(Record.colour[0]) && format(Record.colour[1]) && format(Record.depth) && + std::has_single_bit(Record.samples) && (Record.samples <= 8) && (Record.view_mask <= 0x3fu) && (Record.settings < 64u); } // the number of pipelines the list keeps; the oldest go @@ -2258,8 +2396,6 @@ bool vk14::scene_pipeline_record::parse(std::string const &Line) { values[i] = static_cast(std::stoul(fields[6 + i])); } - vertices = static_cast(values[0]); - topology = static_cast(values[1]); blending = values[2]; colour = {static_cast(values[3]), static_cast(values[4])}; colours = std::min(values[5], 2); @@ -2267,6 +2403,12 @@ bool vk14::scene_pipeline_record::parse(std::string const &Line) samples = values[7]; view_mask = values[8]; settings = values[9]; + if (false == pipeline_record_valid(*this, values[0], values[1])) + { + return false; + } + vertices = static_cast(values[0]); + topology = static_cast(values[1]); } catch (std::exception const &) { @@ -2275,6 +2417,31 @@ bool vk14::scene_pipeline_record::parse(std::string const &Line) return true; } +namespace +{ + +// the settings of the game the shaders of the scene take as specialization constants, for the targets of a pass +std::uint32_t scene_pipeline_settings(vk14::target_formats const &Targets) +{ + auto const motion{Targets.colours > 1}; + return (Global.gfx_shadergamma ? 1u : 0u) | (Global.gfx_shadowmap_enabled ? 2u : 0u) | (Global.gfx_envmap_enabled ? 4u : 0u) | (motion ? 8u : 0u) | 16u | (Global.gfx_extraeffects ? 32u : 0u); +} + +// the key a pipeline of a program is kept by in the map of the program (vk14::scene_program::pipelines) +std::uint64_t scene_pipeline_key(vk14::target_formats const &Targets, vk14::blend_mode const Blend, VkPrimitiveTopology const Primitiveclass, std::uint32_t const Settings) +{ + return (static_cast(Targets.id)) | (static_cast(Blend) << 16) | (static_cast(Primitiveclass) << 24) | (static_cast(Settings) << 32); +} + +// the program has the pipeline of the key, made or found unable to be made +bool has_scene_pipeline(vk14::scene_program &Program, std::uint64_t const Key) +{ + std::scoped_lock lock(Program.mutex); + return Program.pipelines.contains(Key); +} + +} // namespace + // the pipeline of the program for the targets of the pass, the blending and the class of the primitive, made the first time it's // asked for; bound with the primitive as dynamic state. false: it can't be made, or it's being made by the background threads for // the walk of the scene, which leaves out the draw till it's there (gfx.vulkan.asyncresources, the stage M5) @@ -2286,8 +2453,8 @@ bool vulkan14_renderer::bind_scene_pipeline(vk14::scene_program &Program, vk14:: auto const primitiveclass{topology_class(topology)}; // the settings of the game the shaders take as specialization constants auto const motion{Targets.colours > 1}; - std::uint32_t const settings{(Global.gfx_shadergamma ? 1u : 0u) | (Global.gfx_shadowmap_enabled ? 2u : 0u) | (Global.gfx_envmap_enabled ? 4u : 0u) | (motion ? 8u : 0u) | 16u | (Global.gfx_extraeffects ? 32u : 0u)}; - auto const key{(static_cast(Targets.id)) | (static_cast(Blend) << 16) | (static_cast(primitiveclass) << 24) | (static_cast(settings) << 32)}; + auto const settings{scene_pipeline_settings(Targets)}; + auto const key{scene_pipeline_key(Targets, Blend, primitiveclass, settings)}; VkPipeline pipeline{VK_NULL_HANDLE}; if ((draw.lastprogram == &Program) && (draw.lastkey == key)) { @@ -2296,6 +2463,7 @@ bool vulkan14_renderer::bind_scene_pipeline(vk14::scene_program &Program, vk14:: else { auto found{false}; + auto pending{false}; { std::lock_guard lock(Program.mutex); auto const lookup{Program.pipelines.find(key)}; @@ -2304,6 +2472,10 @@ bool vulkan14_renderer::bind_scene_pipeline(vk14::scene_program &Program, vk14:: pipeline = lookup->second; found = true; } + else + { + pending = Program.pending.contains(key); + } } if (false == found) { @@ -2311,6 +2483,11 @@ bool vulkan14_renderer::bind_scene_pipeline(vk14::scene_program &Program, vk14:: auto const single{(false == motion) && (Targets.colours > 0)}; if ((draw.async || (m_main != nullptr)) && Global.gfx_vulkan_asyncresources && ctx.background.running()) { + if (pending) + { + // being made by the background threads: the draws go without it till it's there, none of them asks for it again + return false; + } // made ahead (the list of the last session), or made for another program of the same shaders: taken at once if (false == ctx.find_scene_pipeline(Program, Targets, Blend, primitiveclass, settings, single, pipeline)) { @@ -2443,7 +2620,7 @@ bool vulkan14_renderer::context::find_scene_pipeline(vk14::scene_program &Progra } void vulkan14_renderer::context::queue_scene_pipeline(vk14::scene_program &Program, vk14::target_formats const &Targets, vk14::blend_mode const Blend, VkPrimitiveTopology const Primitiveclass, - std::uint32_t const Settings, bool const Single, std::uint64_t const Key) + std::uint32_t const Settings, bool const Single, std::uint64_t const Key, bool const Late) { auto &ctx{*this}; { @@ -2454,7 +2631,10 @@ void vulkan14_renderer::context::queue_scene_pipeline(vk14::scene_program &Progr return; } } - ++ctx.pipelines_late; + if (Late) + { + ++ctx.pipelines_late; + } // the program and the renderer outlive the background threads (stopped first when the scene goes) ctx.background.add([this, program = &Program, targets = Targets, Blend, Primitiveclass, Settings, Single, Key]() { auto const pipeline{make_scene_pipeline(*program, targets, Blend, Primitiveclass, Settings, Single)}; @@ -2464,6 +2644,110 @@ void vulkan14_renderer::context::queue_scene_pipeline(vk14::scene_program &Progr }); } +// the pipelines the scene loaded will draw with most: those of the programs of its materials for the colour of the main view, opaque +// and blended, and those of the shadows. what else a frame asks for (the variants of the gpu culling, the passes of the extra +// views, the reflections) is made when it's first needed, as before +void vulkan14_renderer::list_prewarm_pipelines() +{ + auto &ctx{*m_context}; + auto &scene{ctx.scene}; + ctx.prewarm_listed = true; + auto const add = [&ctx](std::shared_ptr const &Program, vk14::target_formats const &Targets, vk14::blend_mode const Blend) { + if ((Program == nullptr) || (Program->vertices != vk14::vertex_kind::scene) || (Targets.id == 0)) + { + return; + } + context::prewarm_pipeline pipeline; + pipeline.program = Program; + pipeline.targets = Targets; + pipeline.blend = Blend; + pipeline.settings = scene_pipeline_settings(Targets); + // a shader writing the velocity without its target is reported by the validation layer (bind_scene_pipeline()) + pipeline.single = (Targets.colours == 1); + pipeline.key = scene_pipeline_key(Targets, Blend, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, pipeline.settings); + ctx.prewarm.push_back(std::move(pipeline)); + }; + auto const main{std::ranges::find_if(m_viewports, [](viewport_config const &Viewport) { return Viewport.main; })}; + auto const index{static_cast(std::distance(m_viewports.begin(), main))}; + if ((main != m_viewports.end()) && make_viewport_targets(index)) + { + auto const &targets{scene.targets[index].formats}; + for (auto const &material : scene.materials) + { + add(material.second, targets, vk14::blend_mode::none); + add(material.second, targets, vk14::blend_mode::scene_alpha); + } + } + if (Global.gfx_shadowmap_enabled) + { + add(scene.shadow, scene.shadow_formats, vk14::blend_mode::none); + add(scene.alpha_shadow, scene.shadow_formats, vk14::blend_mode::none); + } + vk14::log_info("pipelines made behind the loading screen: " + std::to_string(ctx.prewarm.size())); +} + +// the pipelines the scene loaded will draw with, made while the loading screen is shown: by the background threads where they run, +// otherwise here, for about Milliseconds a call. a pipeline made for a draw instead would leave the draw out for a few frames (the +// background threads) or hold the frame while it's made. the pipelines of the list of the last session are waited for as well, +// and counted in what's returned +std::pair vulkan14_renderer::Prewarm_Shaders(double const Milliseconds) +{ + if (m_context == nullptr) + { + return {0, 0}; + } + auto &ctx{*m_context}; + if (false == ctx.prewarm_listed) + { + list_prewarm_pipelines(); + } + auto const background{Global.gfx_vulkan_asyncresources && ctx.background.running()}; + if (background) + { + // handed over once, made ahead of what the draws ask for later + for (; ctx.prewarm_next < ctx.prewarm.size(); ++ctx.prewarm_next) + { + auto const &pipeline{ctx.prewarm[ctx.prewarm_next]}; + if (false == has_scene_pipeline(*pipeline.program, pipeline.key)) + { + ctx.queue_scene_pipeline(*pipeline.program, pipeline.targets, pipeline.blend, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, pipeline.settings, pipeline.single, pipeline.key, false); + } + } + } + else + { + auto const start{std::chrono::steady_clock::now()}; + while ((ctx.prewarm_next < ctx.prewarm.size()) && (std::chrono::duration(std::chrono::steady_clock::now() - start).count() < Milliseconds)) + { + auto const &pipeline{ctx.prewarm[ctx.prewarm_next]}; + ++ctx.prewarm_next; + if (has_scene_pipeline(*pipeline.program, pipeline.key)) + { + continue; + } + auto const made{ctx.make_scene_pipeline(*pipeline.program, pipeline.targets, pipeline.blend, VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, pipeline.settings, pipeline.single)}; + std::scoped_lock lock(pipeline.program->mutex); + pipeline.program->pipelines.emplace(pipeline.key, made); + } + } + auto const done{static_cast(std::ranges::count_if(ctx.prewarm, [](context::prewarm_pipeline const &Pipeline) { return has_scene_pipeline(*Pipeline.program, Pipeline.key); }))}; + // the pipelines of the list of the last session count too, up to 4096 of them from any scenery played before: with a cold + // cache of the driver they take most of the time, and the bar moves with them. then one more step: the background threads + // idle, which ends the wait whatever the counts say (a task dropped is never counted as done) + auto const listed{ctx.warm_queued.load()}; + auto const warmed{std::min(ctx.warm_finished.load(), listed)}; + auto const idle{(false == background) || (ctx.background.pending() == 0)}; + auto const total{ctx.prewarm.size() + listed + 1}; + if (idle && (done == ctx.prewarm.size())) + { + // all made: the programs aren't held past the loading screen + ctx.prewarm.clear(); + ctx.prewarm_next = 0; + return {total, total}; + } + return {done + warmed, total}; +} + // the pipelines of the list of the last session made ahead by the background threads, after the ones the draws wait for void vulkan14_renderer::context::warm_scene_pipelines() { @@ -2500,6 +2784,7 @@ void vulkan14_renderer::context::warm_scene_pipelines() } vk14::log_info("pipelines of the last session made ahead: " + std::to_string(records.size())); auto const layout{ctx.scene.scene_layout}; + ctx.warm_queued += records.size(); for (auto const &record : records) { ctx.background.add( @@ -2518,6 +2803,7 @@ void vulkan14_renderer::context::warm_scene_pipelines() // the shader went or changed meanwhile vk14::log_info(std::string("a pipeline of the last session can't be made ahead: ") + Exception.what()); } + ++ctx.warm_finished; }, false); } @@ -2542,8 +2828,9 @@ void vulkan14_renderer::context::save_scene_pipelines() } auto const path{pipeline_list_path()}; std::error_code error; - std::filesystem::create_directories(std::filesystem::path(path).parent_path(), error); - auto const temporary{path + ".tmp"}; + std::filesystem::create_directories(path.parent_path(), error); + auto temporary{path}; + temporary += ".tmp"; { std::ofstream file(temporary, std::ios::trunc); if (false == file.is_open()) @@ -2554,6 +2841,13 @@ void vulkan14_renderer::context::save_scene_pipelines() { file << record.line() << '\n'; } + // a list which wasn't written whole (a full disk) doesn't take the place of the one there + file.close(); + if (file.fail()) + { + std::filesystem::remove(temporary, error); + return; + } } std::filesystem::rename(temporary, path, error); } @@ -2647,7 +2941,7 @@ int vulkan14_renderer::prepass_class(material_handle const Material) static std::unordered_set const alphatested{"default", "default_1", "default_2", "default_detail", "default_specgloss", "detail_normalmap", "detail_normalmap_specgloss", "normalmap", "normalmap_specgloss", "reflmap", "reflmap_specgloss", "shadowlessnormalmap", "shadowlessnormalmap_specgloss", "sunlessnormalmap", "sunlessnormalmap_specgloss", - "trackblend", "trackblend_normalmap", "trackblend_specgloss"}; + "trackblend", "trackblend_normalmap", "trackblend_specgloss", "pbr", "pbr_detail", "pbr_coat"}; static std::unordered_set const solid{"colored", "default_0", "terrain", "water", "water_specgloss", "invalid"}; auto prepassclass{0}; for (auto const &program : scene.materials) diff --git a/rendering/vulkan14/vulkan14shaders.cpp b/rendering/vulkan14/vulkan14shaders.cpp index 6bac1925c..7f6326901 100644 --- a/rendering/vulkan14/vulkan14shaders.cpp +++ b/rendering/vulkan14/vulkan14shaders.cpp @@ -96,6 +96,18 @@ std::vector read_spirv(std::string const &Path) { return {}; } + // the instructions after the header of five words follow one another to the very end of the file: a file cut short or damaged + // (a full disk, a crash while it was written) isn't given to the driver, the shader is compiled again + std::size_t word{5}; + while (word < words.size()) + { + auto const count{static_cast(words[word] >> 16)}; + if ((count == 0) || (count > words.size() - word)) + { + return {}; + } + word += count; + } return words; } @@ -113,8 +125,11 @@ void write_file(std::string const &Path, void const *Data, std::size_t const Siz return; } file.write(static_cast(Data), static_cast(Size)); - if (false == static_cast(file)) + // closed before it's looked at: what's still in the buffer of the stream is written then, and may not fit on the disk + file.close(); + if (file.fail()) { + std::filesystem::remove(temporary, error); return; } } @@ -427,15 +442,7 @@ void pipeline_library::shutdown() } if (m_cache != VK_NULL_HANDLE) { - std::size_t size{0}; - if (VK14_VERIFY(vkGetPipelineCacheData(device, m_cache, &size, nullptr)) && (size > 0)) - { - std::vector data(size); - if (VK14_VERIFY(vkGetPipelineCacheData(device, m_cache, &size, data.data()))) - { - write_file(m_cachepath, data.data(), size); - } - } + save(); vkDestroyPipelineCache(device, m_cache, nullptr); } } @@ -444,6 +451,32 @@ void pipeline_library::shutdown() m_device = nullptr; } +void pipeline_library::save() const +{ + if ((m_device == nullptr) || (m_device->handle() == VK_NULL_HANDLE) || (m_cache == VK_NULL_HANDLE)) + { + return; + } + auto const device{m_device->handle()}; + std::size_t size{0}; + if ((false == VK14_VERIFY(vkGetPipelineCacheData(device, m_cache, &size, nullptr))) || (size == 0)) + { + return; + } + std::vector data(size); + // the cache grew between the two calls (another thread made a pipeline): what fits is a cache of its own + if (auto const result{vkGetPipelineCacheData(device, m_cache, &size, data.data())}; (result == VK_SUCCESS) || (result == VK_INCOMPLETE)) + { + write_file(m_cachepath, data.data(), size); + } +} + +std::size_t pipeline_library::count() const +{ + std::scoped_lock const lock{m_mutex}; + return m_pipelines.size(); +} + std::uint64_t pipeline_library::key_of(pipeline_desc const &Desc) const { std::uint64_t hash{14695981039346656037ull}; @@ -865,6 +898,7 @@ std::string binding_preamble(bool const Raytracing) define("SKY_OCCLUSION_HEIGHT_TEX", SKY_OCCLUSION_HEIGHT_TEX); define("SKY_OCCLUSION_TEX", SKY_OCCLUSION_TEX); define("CAB_PROBE_MASK_TEX", CAB_PROBE_MASK_TEX); + define("RAIN_CELLS_SSBO", RAIN_CELLS_SSBO); define("PASS_BINDING_COUNT", PASS_BINDING_COUNT); define("MATERIAL_TEXTURE_FIRST", MATERIAL_TEXTURE_FIRST); define("CL_CLUSTER_UBO", CL_CLUSTER_UBO); @@ -897,6 +931,7 @@ std::string binding_preamble(bool const Raytracing) define("MAX_PARAMS", static_cast(gl::MAX_PARAMS), "U"); define("MAX_HEADLIGHT_SHADOWS", static_cast(gl::MAX_HEADLIGHT_SHADOWS), "U"); define("MAX_CAB_PROBE_LAMPS", static_cast(gl::MAX_CAB_PROBE_LAMPS), "U"); + define("WIPER_PASS_BUCKETS", static_cast(gl::WIPER_PASS_BUCKETS)); define("CLUSTER_GRID_X", gl::CLUSTER_GRID_X); define("CLUSTER_GRID_Y", gl::CLUSTER_GRID_Y); define("CLUSTER_GRID_Z", gl::CLUSTER_GRID_Z); @@ -936,6 +971,8 @@ std::string binding_preamble(bool const Raytracing) define("WATER_TRAIL", gl::WATER_TRAIL); define("WATER_MAP", gl::WATER_MAP); define("WATER_GROUP_SIZE", gl::WATER_GROUP_SIZE); + define("WATER_LAYER_TEXELS", gl::WATER_LAYER_TEXELS); + define("WATER_LAYER_BANDS", gl::WATER_LAYER_BANDS); define("CAB_PROBE_SH_SIZE", static_cast(gl::CAB_PROBE_SH_SIZE)); define("CAB_PROBE_SH_GROUP_SIZE", static_cast(gl::CAB_PROBE_SH_GROUP_SIZE)); return preamble; diff --git a/rendering/vulkan14/vulkan14shaders.h b/rendering/vulkan14/vulkan14shaders.h index 5fdf4df5e..b03bb1b59 100644 --- a/rendering/vulkan14/vulkan14shaders.h +++ b/rendering/vulkan14/vulkan14shaders.h @@ -132,6 +132,11 @@ class pipeline_library bool init(device const &Device, std::string &Reason); // writes the pipeline cache to the disk and destroys the pipelines void shutdown(); + // the pipeline cache written to the disk as it is now, so a session which doesn't end as it should keeps what it compiled. any + // thread, while the library is there + void save() const; + // the pipelines made so far + std::size_t count() const; // the pipeline of the description, made at the first call (from the cache on the disk, when it has it). null when it can't be made VkPipeline get(pipeline_desc const &Desc); // the pipeline of the description when it was made already (Pipeline: it, null when it couldn't be); false: not made yet diff --git a/rendering/vulkan14/vulkan14swapchain.cpp b/rendering/vulkan14/vulkan14swapchain.cpp index 46e3c2266..7ceb07941 100644 --- a/rendering/vulkan14/vulkan14swapchain.cpp +++ b/rendering/vulkan14/vulkan14swapchain.cpp @@ -14,6 +14,9 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14device.h" #include "utilities/Globals.h" +#include +#include + namespace vk14 { @@ -133,11 +136,17 @@ bool swapchain::build(std::string &Reason) return true; } + if (m_surfacelost && (false == restore_surface(Reason))) + { + return false; + } + VkSurfaceCapabilitiesKHR capabilities{}; auto const result{vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical, m_surface, &capabilities)}; if (result != VK_SUCCESS) { Reason = std::string("the surface of ") + m_name + " can't be queried (" + result_string(result) + ")"; + note_failure(result); return false; } @@ -274,6 +283,7 @@ bool swapchain::build(std::string &Reason) if (created != VK_SUCCESS) { Reason = "the swapchain of " + m_name + " can't be made (" + result_string(created) + ")"; + note_failure(created); return false; } m_swapchain = swapchain; @@ -344,8 +354,25 @@ swapchain::acquire_result swapchain::acquire(std::uint32_t const Frame, std::uin std::string reason; if (false == build(reason)) { - log_error(reason); - return acquire_result::failed; + if (m_devicelost) + { + log_error(reason); + return acquire_result::failed; + } + // a surface or a swapchain which can't be had now (lost, or the window changed meanwhile) is tried again with the next + // frame, the window isn't drawn till then. said once + if (false == m_failing) + { + log_warning(reason + ", trying again with the next frames"); + m_failing = true; + } + m_rebuild = true; + return acquire_result::skipped; + } + if (m_failing && (m_swapchain != VK_NULL_HANDLE)) + { + log_info(m_name + ": the swapchain is back"); + m_failing = false; } } if ((m_swapchain == VK_NULL_HANDLE) || m_rebuild) @@ -362,6 +389,8 @@ swapchain::acquire_result swapchain::acquire(std::uint32_t const Frame, std::uin m_states.resize(m_images.size()); } m_states[m_image] = image_state{VK_IMAGE_LAYOUT_UNDEFINED, VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT, VK_ACCESS_2_NONE}; + ++m_acquired; + destroy_retired(false); } // the images of the generated frames, shown before the one drawn; the swapchain has one image more for each of them, so the // images of a frame can all be acquired. one which can't be had leaves fewer of them @@ -396,11 +425,81 @@ swapchain::acquire_result swapchain::acquire(std::uint32_t const Frame, std::uin case VK_ERROR_OUT_OF_DATE_KHR: m_rebuild = true; return acquire_result::skipped; + case VK_ERROR_DEVICE_LOST: + log_error(std::string("vkAcquireNextImageKHR of ") + m_name + " failed with " + result_string(result)); + return acquire_result::failed; default: break; } - log_error(std::string("vkAcquireNextImageKHR of ") + m_name + " failed with " + result_string(result)); - return acquire_result::failed; + // the surface lost, the exclusive fullscreen taken away and the like: the swapchain (with its surface, when that's what is lost) is + // made anew for the next frame, as build() does when it fails. said once + if (false == m_failing) + { + log_warning(std::string("vkAcquireNextImageKHR of ") + m_name + " failed with " + result_string(result) + ", the swapchain is made anew"); + m_failing = true; + } + note_failure(result); + m_rebuild = true; + return acquire_result::skipped; +} + +bool swapchain::minimized() const +{ + if (m_window == nullptr) + { + return true; + } + int width{0}; + int height{0}; + glfwGetFramebufferSize(m_window, &width, &height); + return (width <= 0) || (height <= 0); +} + +void swapchain::note_failure(VkResult const Result) +{ + if (Result == VK_ERROR_DEVICE_LOST) + { + m_devicelost = true; + } + else if (Result == VK_ERROR_SURFACE_LOST_KHR) + { + m_surfacelost = true; + } +} + +bool swapchain::restore_surface(std::string &Reason) +{ + auto const device{m_device->handle()}; + // the swapchain goes before its surface, once the frames in flight and the presentation are done with its images + if (m_swapchain != VK_NULL_HANDLE) + { + vkQueueWaitIdle(m_device->graphics_queue()); + release_images(); + vkDestroySwapchainKHR(device, m_swapchain, nullptr); + m_swapchain = VK_NULL_HANDLE; + } + if (m_surface != VK_NULL_HANDLE) + { + vkDestroySurfaceKHR(m_instance->handle(), m_surface, nullptr); + m_surface = VK_NULL_HANDLE; + } + if (auto const result{glfwCreateWindowSurface(m_instance->handle(), m_window, nullptr, &m_surface)}; result != VK_SUCCESS) + { + m_surface = VK_NULL_HANDLE; + Reason = "the window of " + m_name + " gives no vulkan surface (" + result_string(result) + ")"; + note_failure(result); + return false; + } + m_instance->set_object_name(device, VK_OBJECT_TYPE_SURFACE_KHR, reinterpret_cast(m_surface), m_name + " surface"); + VkBool32 present{VK_FALSE}; + if (auto const result{vkGetPhysicalDeviceSurfaceSupportKHR(m_device->physical(), m_device->families().graphics, m_surface, &present)}; (result != VK_SUCCESS) || (present == VK_FALSE)) + { + Reason = "the gpu can't show images in the window of " + m_name; + note_failure(result); + return false; + } + m_surfacelost = false; + return true; } bool swapchain::latency_sleep(VkSemaphore const Semaphore, std::uint64_t const Value) const @@ -410,9 +509,7 @@ bool swapchain::latency_sleep(VkSemaphore const Semaphore, std::uint64_t const V return false; } // minimized: nothing is presented, the driver has nothing to measure (the main thread, as glfw wants) - int width{0}, height{0}; - glfwGetFramebufferSize(m_window, &width, &height); - if ((width <= 0) || (height <= 0)) + if (minimized()) { return false; } @@ -438,10 +535,11 @@ void swapchain::latency_marker(std::uint64_t const PresentId, VkLatencyMarkerNV void swapchain::presented(VkResult const Result) { - if ((Result == VK_SUBOPTIMAL_KHR) || (Result == VK_ERROR_OUT_OF_DATE_KHR)) + if ((Result == VK_SUBOPTIMAL_KHR) || (Result == VK_ERROR_OUT_OF_DATE_KHR) || (Result == VK_ERROR_SURFACE_LOST_KHR) || (Result == VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT)) { m_rebuild = true; } + note_failure(Result); } void swapchain::record_clear(command_stream *Commands, glm::vec4 const &Colour) const @@ -506,25 +604,42 @@ void swapchain::release_images() vkDestroyImageView(device, view, nullptr); } } - for (auto semaphore : m_presentsemaphores) - { - if (semaphore != VK_NULL_HANDLE) - { - vkDestroySemaphore(device, semaphore, nullptr); - } - } + // the presentation may still wait for the semaphores after the queue is idle: kept till an image of the next swapchain comes back + std::ranges::copy_if(m_presentsemaphores, std::back_inserter(m_retiredsemaphores), [](VkSemaphore const Semaphore) { return Semaphore != VK_NULL_HANDLE; }); + m_acquired = 0; m_views.clear(); m_presentsemaphores.clear(); m_images.clear(); m_states.clear(); } +void swapchain::destroy_retired(bool const Now) +{ + // an image acquired more times than the swapchain has of them was acquired twice, and so came back from a present queued after + // those of the swapchains before + if (m_retiredsemaphores.empty() || ((false == Now) && (m_acquired <= m_images.size()))) + { + return; + } + auto const device{m_device != nullptr ? m_device->handle() : VK_NULL_HANDLE}; + if (device == VK_NULL_HANDLE) + { + return; + } + for (auto const semaphore : m_retiredsemaphores) + { + vkDestroySemaphore(device, semaphore, nullptr); + } + m_retiredsemaphores.clear(); +} + void swapchain::destroy() { auto const device{m_device != nullptr ? m_device->handle() : VK_NULL_HANDLE}; if (device != VK_NULL_HANDLE) { release_images(); + destroy_retired(true); if (m_swapchain != VK_NULL_HANDLE) { vkDestroySwapchainKHR(device, m_swapchain, nullptr); diff --git a/rendering/vulkan14/vulkan14swapchain.h b/rendering/vulkan14/vulkan14swapchain.h index 855299cec..2079ec0c8 100644 --- a/rendering/vulkan14/vulkan14swapchain.h +++ b/rendering/vulkan14/vulkan14swapchain.h @@ -30,7 +30,7 @@ class swapchain enum class acquire_result { ready, // an image to draw into, its acquire semaphore will be signalled - skipped, // nothing to draw this frame (minimized, or made anew) + skipped, // nothing to draw this frame (minimized, made anew, or its surface or swapchain can't be had now and is tried again) failed // the device is gone }; @@ -66,6 +66,8 @@ class swapchain // the image of the frame Frame (index of the frame in flight), and Generated more for the frames generated from it, which are // shown before it (as many of them as there is room for, generated_count()) acquire_result acquire(std::uint32_t const Frame, std::uint32_t const Generated = 0); + // the window has no size to draw into (minimized); the main thread only, as glfw wants + bool minimized() const; // the image acquired, from undefined to cleared with Colour (linear) and ready to be shown void record_clear(command_stream *Commands, glm::vec4 const &Colour) const; // the image acquired and its view @@ -102,6 +104,12 @@ class swapchain } // the result of the presentation of the image: out of date or suboptimal makes the swapchain anew before the next image void presented(VkResult const Result); + // the images acquired for a frame left out aren't presented: they stay acquired and their present semaphores signalled, so the + // swapchain is made anew before the next image + void drop_images() + { + m_rebuild = true; + } // the most images of the generated frames it can acquire with an image (as made, within what the program may hold at once) std::uint32_t generated_room() const { @@ -159,9 +167,18 @@ class swapchain } private: - // false only when the device is gone or the surface is lost; a minimized window gives true with no swapchain + // false: no swapchain, Reason says why (m_devicelost: the device is gone, anything else may be tried again); a minimized window + // gives true with no swapchain bool build(std::string &Reason); + // the surface of the window made anew after it was lost, the swapchain of the old one gone with it + bool restore_surface(std::string &Reason); + // what a result of the surface, the swapchain or a present says of them: the device or the surface is lost + void note_failure(VkResult Result); + // the views of the images go, their present semaphores are kept till the presentation is done with them (destroy_retired()) void release_images(); + // the present semaphores of the swapchains before this one, once an image of this one came back from the presentation: the + // presents queued before it are done by then. all of them with Now + void destroy_retired(bool Now); // whether the swapchain has to be made anew before the next image bool outdated() const; @@ -181,6 +198,11 @@ class swapchain bool m_vsync{false}; bool m_srgb{false}; bool m_rebuild{false}; + // the surface was lost and is made anew with the swapchain; the device is gone; the swapchain couldn't be had with the last frame + // (said in the log once) + bool m_surfacelost{false}; + bool m_devicelost{false}; + bool m_failing{false}; std::vector m_images; // the states of the images for the barriers of the passes @@ -188,6 +210,11 @@ class swapchain std::vector m_views; // one per image: a semaphore given to the presentation can be reused only once the image comes back std::vector m_presentsemaphores; + // those of the swapchains before this one: a wait of the queue doesn't say the presentation is done with them (that only + // VK_KHR_swapchain_maintenance1 tells, which the device isn't made with), an image of this one acquired twice does. the images + // acquired from this one so far + std::vector m_retiredsemaphores; + std::size_t m_acquired{0}; // one per frame in flight (and one more for each generated frame): free again once the frame which waited for it is done std::vector m_acquiresemaphores; std::uint32_t m_image{0}; diff --git a/rendering/vulkan14/vulkan14tasks.cpp b/rendering/vulkan14/vulkan14tasks.cpp index 0c35b54fa..dc6e526da 100644 --- a/rendering/vulkan14/vulkan14tasks.cpp +++ b/rendering/vulkan14/vulkan14tasks.cpp @@ -102,6 +102,11 @@ void background_tasks::work() { ErrorLog(std::string("vulkan: a background task failed: ") + Exception.what()); } + catch (...) + { + // whatever a task lets out stays in it: the thread goes on with the next one + ErrorLog("vulkan: a background task failed"); + } lock.lock(); --m_busy; if (m_queue.empty() && (m_busy == 0)) diff --git a/rendering/vulkan14/vulkan14terrain.cpp b/rendering/vulkan14/vulkan14terrain.cpp index cde7f9e54..feb7b777e 100644 --- a/rendering/vulkan14/vulkan14terrain.cpp +++ b/rendering/vulkan14/vulkan14terrain.cpp @@ -145,6 +145,11 @@ void terrain_materials::gpu_storage(texture_array const &Array, int const Layers if (vkCreateImageView(device, &info, nullptr, &view) != VK_SUCCESS) { ErrorLog("heightmap terrain: no view of a layer of \"" + target.name + "\""); + // the views made of the layers before it go with it + for (auto const made : images.layers) + { + vkDestroyImageView(device, made, nullptr); + } images.layers.clear(); break; } diff --git a/rendering/vulkan14/vulkan14texture.cpp b/rendering/vulkan14/vulkan14texture.cpp index d369f0d39..c0d469fe6 100644 --- a/rendering/vulkan14/vulkan14texture.cpp +++ b/rendering/vulkan14/vulkan14texture.cpp @@ -17,6 +17,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include +#include +#include #include #include @@ -83,6 +85,25 @@ bool texels_pass_alpha_test(texture_format const &Format, alpha_source const &So } } +// a job of a texture given to the background threads: when it's let go of without having been run, the state of the texture goes back +// to the one given, so nothing waits for the job +struct job_ticket +{ + job_ticket(std::atomic &State, int const Idle) : state{State}, idle{Idle} {} + job_ticket(job_ticket const &) = delete; + job_ticket &operator=(job_ticket const &) = delete; + ~job_ticket() + { + if (false == taken) + { + state = idle; + } + } + std::atomic &state; + int idle; + std::atomic taken{false}; +}; + } // namespace // uploader @@ -582,7 +603,8 @@ bool vulkan14_texture::claim() // what a background thread made is taken over by the thread of the renderer return false; } - publish(); + // the draw waits for the texture: whatever the copies of the frame come to + publish(true); continue; } if (state != job_none) @@ -676,9 +698,25 @@ bool vulkan14_texture::request_background() return false; } ++m_resources.pending->late_count; - // the texture outlives the job: its destruction waits for it (the background threads are stopped before the bank goes, too) - m_resources.background->add([this]() { - auto const result{make(true)}; + // the texture outlives the job: its destruction waits for it (the background threads are stopped before the bank goes, too). a job + // the threads let go of without running it (they were stopped with it in their queue) leaves the texture as it was before it + auto const ticket{std::make_shared(m_job, job_none)}; + m_resources.background->add([this, ticket]() { + ticket->taken = true; + auto result{make_result::failed}; + try + { + result = make(true); + } + catch (std::exception const &Error) + { + // counted as made, without an image: nothing waits for a job which never ends + log_error("the texture " + name + " couldn't be made: " + Error.what()); + m_madeimage.reset(); + m_madeupload = uploader::prepared{}; + m_madestaged = false; + on_failed(); + } m_madefailed = (result == make_result::failed); m_madeempty = (result == make_result::none); std::lock_guard lock(m_resources.pending->mutex); @@ -688,13 +726,24 @@ bool vulkan14_texture::request_background() return false; } -void vulkan14_texture::publish() +void vulkan14_texture::publish(bool const Force) { int expected{job_done}; if (false == m_job.compare_exchange_strong(expected, job_making)) { return; } + if ((false == Force) && (m_madeimage != nullptr) && m_madestaged && (m_resources.pending != nullptr)) + { + // the copy of the staging buffer goes with the uploads of a frame; the first of a frame whatever its size + auto &budget{m_resources.pending->upload_budget}; + if (budget <= 0) + { + m_job = job_done; + return; + } + budget -= static_cast(m_madeupload.staging ? m_madeupload.staging->size() : 0); + } if (m_madeimage != nullptr) { if (m_madestaged) @@ -782,6 +831,11 @@ vulkan14_texture::make_result vulkan14_texture::make(bool const Background) } levels.push_back({offset, {width, height, 1}}); offset += levelsize; + if ((width == 1) && (height == 1)) + { + // the last level an image of the size has, whatever the count the file gives + break; + } width = std::max(width / 2, 1u); height = std::max(height / 2, 1u); } @@ -792,6 +846,12 @@ vulkan14_texture::make_result vulkan14_texture::make(bool const Background) if (format.expand_rgb) { auto const pixels{static_cast(data_width) * data_height}; + if (data.size() < pixels * 3) + { + // a file cut short: not read past what it holds + ErrorLog("Bad texture: \"" + name + "\" holds less data than its size needs", logtype::texture); + return failed(); + } expanded.resize(pixels * 4); for (std::size_t i = 0; i < pixels; ++i) { diff --git a/rendering/vulkan14/vulkan14texture.h b/rendering/vulkan14/vulkan14texture.h index 21d6eab1d..b15846b33 100644 --- a/rendering/vulkan14/vulkan14texture.h +++ b/rendering/vulkan14/vulkan14texture.h @@ -164,6 +164,10 @@ struct pending_textures // the textures made by the background threads since the start, and how many draws went without one std::atomic made_count{0}; std::atomic late_count{0}; + // the bytes of the staging buffers of the textures the background threads made which the frame still takes over (publish()): when + // many of them come at once their copies to the gpu are spread over the frames. the thread of the renderer only + static constexpr std::int64_t upload_budget_frame{64ll * 1024 * 1024}; + std::int64_t upload_budget{upload_budget_frame}; }; // what the images of the renderer need from it @@ -207,8 +211,14 @@ struct vulkan14_texture : public texture_source // the texture for a draw of the walks: true when it's made, otherwise it's made by the background threads (or made now, without // them) and the draw goes without it bool request_background(); - // the thread of the renderer takes over what a background thread made of the texture - void publish(); + // the thread of the renderer takes over what a background thread made of the texture. unless Force, one with a copy to the gpu + // to make is left for a later frame when the copies of the frame reached their budget (pending_textures::upload_budget) + void publish(bool Force = false); + // made by a background thread and not taken over yet + bool made_waiting() const + { + return m_job == job_done; + } void release() override; // as the opengl textures give it: one not made yet has no id of 0, which the materials take for a texture which is missing size_t get_id() const override diff --git a/rendering/vulkan14/vulkan14walkers.cpp b/rendering/vulkan14/vulkan14walkers.cpp index 596c48193..3e6fc9605 100644 --- a/rendering/vulkan14/vulkan14walkers.cpp +++ b/rendering/vulkan14/vulkan14walkers.cpp @@ -7,7 +7,7 @@ obtain one at http://mozilla.org/MPL/2.0/. */ -// the passes walked by the walkers (the stage M2 of claude/vulkan14-renderer-plan.md, gfx.vulkan.parallelpasses). the main thread sets +// the passes walked by the walkers (gfx.vulkan.parallelpasses). the main thread sets // a pass up as it would walk it itself (the camera, the culling, the map it draws to with its barrier, the timestamps around it), hands // the state of the frame over to a walker, splices the stream the walker records into the commands of the frame there and goes on with // the frame; the walkers walk the passes at the same time as the main thread walks the colour pass of the main view, and are joined once @@ -128,6 +128,7 @@ void vulkan14_renderer::take_state(vulkan14_renderer const &Main) draw.instances_cache.reset(&ctx.scene.instances.ring, vk14::instance_ring_part); draw.draws_window = {}; draw.instances_window = {}; + draw.instances_lost = false; draw.used_banks.clear(); draw.used_textures.clear(); m_walkfailed = false; @@ -190,6 +191,11 @@ void vulkan14_renderer::fork_walk(std::function Job, ErrorLog(std::string("vulkan: a walker failed to walk its pass, which is left out: ") + Exception.what()); walker.m_walkfailed = true; } + catch (...) + { + ErrorLog("vulkan: a walker failed to walk its pass, which is left out"); + walker.m_walkfailed = true; + } if (walker.m_walkfailed) { // whatever it left half done (a rendering under way) goes diff --git a/rendering/vulkan14/vulkan14water.cpp b/rendering/vulkan14/vulkan14water.cpp index 4d323b333..61910c0f7 100644 --- a/rendering/vulkan14/vulkan14water.cpp +++ b/rendering/vulkan14/vulkan14water.cpp @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include "rendering/vulkan14/vulkan14commands.h" #include "utilities/Logs.h" +#include + #include namespace vk14 @@ -49,6 +51,21 @@ bool windscreen_water::init(VkDevice const Device, pipeline_library &Pipelines, m_ring = &Ring; m_alignment = std::max(Alignment, 16); m_host = std::move(Host); + // the cells of the rain: the pass sets hold their buffer from the start (made later, the sets of the passes and of the cullings + // would have to be written anew in the middle of a frame). without it a small stand-in, which no glass reads (the glasses with + // rain stay dry, the rest of the simulation works on) + m_raincells = std::make_shared(); + m_raincellsfull = m_raincells->create(Memory, static_cast(gl::RAIN_CELLS_COUNT * 16), storage_usage, memory_kind::device, "rain cells"); + if (false == m_raincellsfull) + { + ErrorLog("rain cells: no storage of " + std::to_string(gl::RAIN_CELLS_COUNT * 16 / (1024 * 1024)) + " MiB, the glasses with rain stay dry"); + m_raincells = std::make_shared(); + if (false == m_raincells->create(Memory, 65536, storage_usage, memory_kind::device, "rain cells")) + { + m_raincells.reset(); + return false; + } + } m_storage = std::make_shared(); m_full = m_storage->create(Memory, static_cast(gl::WATER_STORAGE_SIZE), storage_usage, memory_kind::device, "windscreen water"); if (false == m_full) @@ -75,9 +92,15 @@ void windscreen_water::destroy() { kernel.destroy(m_device); } + m_raincellkernel.destroy(m_device); + m_raincelltried = false; + m_raincellsfull = false; + m_raincellsvalid = false; + m_raincells.reset(); m_storage.reset(); m_device = VK_NULL_HANDLE; m_cleared = false; + m_snowkernels = true; reset(); } @@ -90,12 +113,27 @@ bool windscreen_water::gpu_init() try { std::array const names{"water_trail.comp", "water_spawn.comp", "water_move.comp", "water_clear.comp", "water_grid.comp", - "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp"}; + "water_merge.comp", "water_gather.comp", "water_settle.comp", "water_bake.comp", "water_snow.comp", + "water_snowlayer.comp"}; for (std::size_t i = 0; i < names.size(); ++i) { - if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) + try { - throw gfx::shader_exception(std::string("no compute pipeline of ") + names[i]); + if (false == m_kernels[i].create(m_device, *m_pipelines, m_shaders->get(names[i]), m_passlayout, {}, names[i])) + { + throw gfx::shader_exception(std::string("no compute pipeline of ") + names[i]); + } + } + catch (gfx::shader_exception const &e) + { + if (i < pass::snow) + { + throw; + } + // the passes of the snow are optional: without them the glasses of the snow stay clear, the rain works on + ErrorLog("windscreen water: can't use " + std::string(names[i]) + ", the glasses of the snow stay clear: " + std::string(e.what())); + m_snowkernels = false; + break; } } } @@ -138,6 +176,12 @@ void windscreen_water::gpu_setup(std::size_t const Slot, std::vector commands->fill_buffer(m_storage->handle(), static_cast(parts[part].first), static_cast(parts[part].second), 0); } } + // where the layer of its snow lies, a word at a time + auto const info{layer_info(Slot, Axes)}; + for (std::size_t word = 0; word < info.size(); ++word) + { + commands->fill_buffer(m_storage->handle(), static_cast(gl::WATER_LAYER_INFO_OFFSET + gl::WATER_LAYER_INFO_SIZE * Slot + 4 * word), 4, info[word]); + } // the axes of the map copied after that, from a staging buffer kept until the gpu is done with the frame auto const size{std::min(static_cast(parts[1].second), static_cast(Axes.size() * sizeof(glm::vec4)))}; auto staging{std::make_shared()}; @@ -164,6 +208,57 @@ void windscreen_water::gpu_setup(std::size_t const Slot, std::vector m_deletions->push(m_uploads->current_value(), [staging]() {}); } +void windscreen_water::update_rain_cells(float const Time, float const Rain) +{ + m_raincellsvalid = false; + if ((m_device == VK_NULL_HANDLE) || (false == bool(m_raincells)) || (false == m_raincellsfull) || (Rain <= 0.f) || (false == bool(m_host.commands))) + { + return; + } + if (false == m_raincelltried) + { + m_raincelltried = true; + try + { + if (false == m_raincellkernel.create(m_device, *m_pipelines, m_shaders->get("rain_cells.comp"), m_passlayout, {}, "rain_cells.comp")) + { + ErrorLog("rain cells: no compute pipeline of rain_cells.comp, the glasses with rain stay dry"); + } + } + catch (gfx::shader_exception const &e) + { + ErrorLog("rain cells: can't use rain_cells.comp: " + std::string(e.what())); + } + } + if (false == bool(m_raincellkernel)) + { + return; + } + auto const commands{m_host.commands()}; + if (commands == nullptr) + { + return; + } + // the glasses of the frames before read the cells, this one writes them + memory_barrier(commands, VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_ACCESS_2_SHADER_STORAGE_READ_BIT | VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, + VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT); + struct constants + { + float time; + float rain; + std::int32_t pass; + float pad; + }; + auto const groups = [](std::size_t const Count) { return static_cast((Count + gl::RAIN_CELLS_GROUP_SIZE - 1) / gl::RAIN_CELLS_GROUP_SIZE); }; + std::vector const descriptors{buffer_descriptor(m_raincells->handle(), 0, VK_WHOLE_SIZE)}; + // the cells, then the reach of the drops into the quarters of each drop cell, which reads them + m_raincellkernel.dispatch(commands, descriptors, constants{Time, Rain, 0, 0.f}, groups(gl::RAIN_MASK_BASE)); + compute_barrier(commands); + m_raincellkernel.dispatch(commands, descriptors, constants{Time, Rain, 1, 0.f}, groups(gl::RAIN_CELLS_COUNT - gl::RAIN_MASK_BASE)); + compute_barrier(commands); + m_raincellsvalid = true; +} + ring_slice windscreen_water::block(gl::water_ubs const &Block) { auto const slice{m_ring->allocate(sizeof(gl::water_ubs), m_alignment)}; @@ -201,6 +296,36 @@ bool windscreen_water::gpu_bake(std::size_t const Slot, texture_handle const Mas return true; } +bool windscreen_water::gpu_snow_layer(std::size_t const Slot, texture_handle const Atlas, texture_handle const Normal, gl::water_ubs const &Block) +{ + auto const commands{m_host.commands()}; + if ((commands == nullptr) || (false == m_full) || (false == m_snowkernels) || (Slot >= gl::WATER_SLOTS)) + { + return false; + } + VkImageView atlasview{VK_NULL_HANDLE}; + VkSampler atlassampler{VK_NULL_HANDLE}; + VkImageView normalview{VK_NULL_HANDLE}; + VkSampler normalsampler{VK_NULL_HANDLE}; + if ((false == m_host.texture(Atlas, atlasview, atlassampler)) || (atlasview == VK_NULL_HANDLE) || (false == m_host.texture(Normal, normalview, normalsampler)) || + (normalview == VK_NULL_HANDLE)) + { + return false; + } + auto const slice{block(Block)}; + if (false == bool(slice)) + { + return false; + } + begin(commands); + m_kernels[pass::snowlayer].run(commands, + {buffer_descriptor(m_storage->handle(), 0, VK_WHOLE_SIZE), buffer_descriptor(slice.buffer, slice.offset, sizeof(gl::water_ubs)), + image_descriptor(atlassampler, atlasview, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), image_descriptor(normalsampler, normalview, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL)}, + groups(gl::WATER_LAYER_TEXELS)); + compute_barrier(commands); + return true; +} + void windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const Tries) { auto const commands{m_host.commands()}; @@ -225,20 +350,29 @@ void windscreen_water::gpu_step(gl::water_ubs const &Block, std::uint32_t const }; auto const drops{groups(gl::WATER_DROPS)}; auto const cells{groups(static_cast(gl::WATER_GRID) * gl::WATER_GRID)}; + // the drops only where a glass of the water is (the glasses of the snow have passes of their own) + auto const water{std::ranges::any_of(Block.slots, [](glm::vec4 const &Slot) { return Slot.z > 0.5f; })}; + auto const drop_groups{water ? drops : 0u}; + auto const cell_groups{water ? cells : 0u}; // the wetted paths the blades went over in the step wiped - if (Block.blades != Block.blades_before) + if (water && (Block.blades != Block.blades_before)) { run(pass::trail, groups(static_cast(gl::WATER_TRAIL) * gl::WATER_TRAIL)); } - run(pass::spawn, groups(Tries)); - run(pass::move, drops); - run(pass::clear, cells); - run(pass::grid, drops); - run(pass::merge, drops); - run(pass::gather, drops); - run(pass::settle, drops); - run(pass::clear, cells); - run(pass::grid, drops); + run(pass::spawn, water ? groups(Tries) : 0u); + run(pass::move, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + run(pass::merge, drop_groups); + run(pass::gather, drop_groups); + run(pass::settle, drop_groups); + run(pass::clear, cell_groups); + run(pass::grid, drop_groups); + // the snow of the glasses of the snow, a texel of their maps a thread + if ((Block.snow_slots != glm::vec4{0.f}) && m_snowkernels) + { + run(pass::snow, groups(static_cast(gl::WATER_MAP) * gl::WATER_MAP)); + } } } // namespace vk14 diff --git a/rendering/vulkan14/vulkan14water.h b/rendering/vulkan14/vulkan14water.h index 2b24bbf9d..1673419c0 100644 --- a/rendering/vulkan14/vulkan14water.h +++ b/rendering/vulkan14/vulkan14water.h @@ -50,12 +50,27 @@ class windscreen_water : public gfx::windscreen_water { return m_storage ? m_storage->handle() : VK_NULL_HANDLE; } + // the drops and the rivulets of the cells of the glasses with rain (RAIN_CELLS_SSBO, rain_cells.comp), the pass sets hold it + VkBuffer rain_cells() const + { + return m_raincells ? m_raincells->handle() : VK_NULL_HANDLE; + } + // the cells worked out for the time of the frame (the time of the block of the scene), with the commands of the frame before + // its passes; nothing while it doesn't rain + void update_rain_cells(float Time, float Rain); + // whether the cells were worked out in this frame (the last update_rain_cells()): only then the glasses read them + // (scene_ubs.rain_state.w). never with the stand-in of the storage, which is too small for them + bool rain_cells_valid() const + { + return m_raincellsvalid; + } protected: bool gpu_init() override; void gpu_setup(std::size_t Slot, std::vector const &Axes) override; bool gpu_bake(std::size_t Slot, texture_handle Mask, gl::water_ubs const &Block) override; void gpu_step(gl::water_ubs const &Block, std::uint32_t Tries) override; + bool gpu_snow_layer(std::size_t Slot, texture_handle Atlas, texture_handle Normal, gl::water_ubs const &Block) override; private: // the passes of the step, in their order @@ -70,6 +85,8 @@ class windscreen_water : public gfx::windscreen_water gather, settle, bake, + snow, + snowlayer, count }; // the block of the step in the ring of the frame; empty when the ring is full @@ -89,8 +106,14 @@ class windscreen_water : public gfx::windscreen_water host m_host; std::array m_kernels; std::shared_ptr m_storage; + std::shared_ptr m_raincells; + compute_kernel m_raincellkernel; + bool m_raincelltried{false}; + bool m_raincellsfull{false}; // the cells of the rain have their storage (else a stand-in: the glasses with rain stay dry) + bool m_raincellsvalid{false}; // the cells worked out in this frame bool m_full{false}; // the storage is as large as the simulation needs (else a stand-in, the glasses make their water up) bool m_cleared{false}; + bool m_snowkernels{true}; // the passes of the snow made (they are optional: without them the glasses of the snow stay clear) }; } // namespace vk14 diff --git a/scene/regionfile.cpp b/scene/regionfile.cpp new file mode 100644 index 000000000..593e07e82 --- /dev/null +++ b/scene/regionfile.cpp @@ -0,0 +1,130 @@ +/* +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 "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +namespace scene::region_file { + +std::string +check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ) { + + Input.clear(); + Input.seekg( 0, std::ios::end ); + auto const end { Input.tellg() }; + Input.seekg( 0, std::ios::beg ); + if( ( end < 0 ) || ( false == Input.good() ) ) { + return "can't be read"; + } + auto const filesize { static_cast( end ) }; + + auto const headermain { sn_utils::ld_uint32( Input ) }; + if( auto const headertype { sn_utils::ld_uint32( Input ) }; ( false == Input.good() ) || ( headermain != Header ) || ( headertype != Version ) ) { + return "is of either unrecognized type or version"; + } + auto sectioncount { sn_utils::ld_uint32( Input ) }; + if( false == Input.good() ) { + return "ends before the section count"; + } + if( sectioncount > Sectionlimit ) { + return std::format( "holds {} sections, more than the {} a region has", sectioncount, Sectionlimit ); + } + std::vector present( Sectionlimit, false ); + std::uint64_t position { 3 * sizeof( std::uint32_t ) }; + std::uint32_t sectionnumber { 0 }; + while( sectionnumber < sectioncount ) { + if( filesize - position < section_header_size ) { + return std::format( "ends after {} of its {} sections", sectionnumber, sectioncount ); + } + std::uint32_t index; + std::uint32_t size; + if( auto const error { read_section_header( Input, Sectionlimit, index, size ) }; false == error.empty() ) { + return error; + } + if( true == present[ index ] ) { + return std::format( "holds section {} more than once", index ); + } + present[ index ] = true; + if( filesize - position < size ) { + return std::format( + "ends inside section {} ({} of {}), {} of its {} bytes are there", index, sectionnumber + 1, sectioncount, filesize - position, size ); + } + position += size; + Input.seekg( static_cast( position ), std::ios::beg ); + if( false == Input.good() ) { + return std::format( "can't be read past section {}", index ); + } + ++sectionnumber; + } + if( position != filesize ) { + return std::format( "has {} bytes past its last section", filesize - position ); + } + return {}; +} + +std::string +read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ) { + + Index = sn_utils::ld_uint32( Input ); + Size = sn_utils::ld_uint32( Input ); + if( false == Input.good() ) { + return "ends inside a section header"; + } + if( Index >= Sectionlimit ) { + return std::format( "holds section {}, out of the {} a region has", Index, Sectionlimit ); + } + if( Size < section_header_size ) { + return std::format( "gives section {} the size of {} bytes, less than its header takes", Index, Size ); + } + return {}; +} + +std::string +open_temporary( std::string const &Filename, std::ofstream &Output ) { + + Output.open( Filename + ".tmp", std::ios::binary | std::ios::trunc ); + if( Output.fail() ) { + return "can't write to file \"" + Filename + ".tmp\""; + } + return {}; +} + +std::string +finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ) { + + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + Output.close(); + if( ( true == Error.empty() ) && ( Output.fail() ) ) { + Error = "can't write to file \"" + Filename + ".tmp\""; + } + std::filesystem::path const temporaryfile { Filename + ".tmp" }; + std::error_code result; + if( false == Error.empty() ) { + std::filesystem::remove( temporaryfile, result ); + return Error; + } + // the finished file replaces the previous version in one go, so an interrupted write doesn't leave a broken one behind + std::filesystem::rename( temporaryfile, Filename, result ); + if( result ) { + Error = "can't replace file \"" + Filename + "\": " + result.message(); + std::filesystem::remove( temporaryfile, result ); + return Error; + } + return {}; +} + +} // scene::region_file diff --git a/scene/regionfile.h b/scene/regionfile.h new file mode 100644 index 000000000..dd497a487 --- /dev/null +++ b/scene/regionfile.h @@ -0,0 +1,77 @@ +/* +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 + +#include +#include +#include +#include +#include + +// the parts of the region file (.sbt, the static geometry of a scenery cached by basic_region) which need +// nothing of the scene: checking how a file is laid out, and writing it so that an interrupted write leaves no +// cut-short file behind. kept apart so the unit tests can check them +namespace scene::region_file { + +// layout of the file: the header (two uint32: the file type and its version), the section count (uint32), then for +// each section its index (uint32), its size (uint32, counted from the start of the index, so it covers the index, +// the size itself and the section data) and the section data. all numbers little endian + +// size of the index and the size of a section, the least a section can take +std::uint32_t constexpr section_header_size { 2 * sizeof( std::uint32_t ) }; + +// checks the layout of the file held by the stream, read from its start: the header has to match the provided type +// and version, the sections have to have indices below Sectionlimit, each one no more than once, and their sizes have +// to add up to the length of the file. the section data itself isn't read. returns: the empty string if the layout +// holds, the reason why not otherwise +std::string + check_layout( std::istream &Input, std::uint32_t const Header, std::uint32_t const Version, std::uint32_t const Sectionlimit ); + +// reads the index and the size of the next section, and checks them: the index has to be below Sectionlimit, and the +// section no smaller than its own index and size. returns: the empty string if both were read and are sound, the +// reason why not otherwise +std::string + read_section_header( std::istream &Input, std::uint32_t const Sectionlimit, std::uint32_t &Index, std::uint32_t &Size ); + +// opens the temporary file write_through_temporary() writes into. returns: the empty string on success, the reason of +// the failure otherwise +std::string + open_temporary( std::string const &Filename, std::ofstream &Output ); + +// closes the temporary file write_through_temporary() wrote into, and puts it in place of the file, unless Error holds +// the reason why the writing failed. the temporary file is removed on a failure. returns: the empty string on success, +// the reason of the failure otherwise +std::string + finish_temporary( std::string const &Filename, std::ofstream &Output, std::string Error ); + +// writes a file with the provided function (taking the std::ostream to write into) into a temporary file next to it +// (the name with .tmp added), which then replaces the file in one go. if the writing fails or is cut short, the +// previous file (or none) stays in place, rather than a partial one; the temporary file is removed when the failure is +// noticed. returns: the empty string on success, the reason of the failure otherwise +template +std::string + write_through_temporary( std::string const &Filename, Writer_ const &Write ) { + + std::ofstream output; + if( auto const openerror { open_temporary( Filename, output ) }; false == openerror.empty() ) { + return openerror; + } + std::string error; + try { + Write( output ); + output.flush(); + } + catch( std::exception const &Exception ) { + error = "can't write to file \"" + Filename + ".tmp\": " + Exception.what(); + } + return finish_temporary( Filename, output, std::move( error ) ); +} + +} // scene::region_file diff --git a/scene/scene.cpp b/scene/scene.cpp index e64bdc7fd..03b10d8f1 100644 --- a/scene/scene.cpp +++ b/scene/scene.cpp @@ -19,9 +19,15 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "scene/sn_utils.h" +#include "scene/regionfile.h" #include "scene/sceneterrain.h" #include "rendering/renderer.h" #include "widgets/map_objects.h" +#include "vehicle/aiwire.h" +#include "physics/vehicle.h" +#include "vehicle/DynObj.h" + +#include namespace scene { @@ -29,6 +35,57 @@ std::string const EU07_FILEEXTENSION_REGION { ".sbt" }; std::uint32_t const EU07_FILEHEADER { MAKE_ID4( 'E','U','0','7' ) }; std::uint32_t const EU07_FILEVERSION_REGION { MAKE_ID4( 'S', 'B', 'T', '2' ) }; std::map Hierarchy; + +namespace { + +// name of the region file kept for specified scenario file +std::string +region_file_name( std::string const &Scenariofile ) { + + auto filename { Scenariofile }; + while( filename[ 0 ] == '$' ) { + // trim leading $ char rainsted utility may add to the base name for modified .scn files + filename.erase( 0, 1 ); + } + erase_extension( filename ); + filename = Global.asCurrentSceneryPath + filename; + filename += EU07_FILEEXTENSION_REGION; + + return filename; +} + +// reads the next section of a region file into the provided list. returns: the empty string on success, the reason +// of the failure otherwise +std::string +read_region_section( std::istream &Input, std::uint32_t const Sectionlimit, std::vector>> &Sections ) { + + // section index, followed by section data size (counted from the start of the index), followed by section data + std::uint32_t sectionindex; + std::uint32_t sectionsize; + if( auto const error { region_file::read_section_header( Input, Sectionlimit, sectionindex, sectionsize ) }; false == error.empty() ) { + return error; + } + // the section is read out of its own data, it can't reach into the next one + std::string data( sectionsize - region_file::section_header_size, '\0' ); + Input.read( data.data(), static_cast( data.size() ) ); + if( false == Input.good() ) { + return std::format( "ends inside section {}", sectionindex ); + } + std::istringstream sectioninput { std::move( data ) }; + auto section { std::make_unique() }; + section->deserialize( sectioninput ); + std::string error; + if( true == sectioninput.fail() ) { + error = std::format( "has section {} shorter than its content", sectionindex ); + } + else if( sectioninput.peek() != std::char_traits::eof() ) { + error = std::format( "has section {} longer than its content", sectionindex ); + } + Sections.emplace_back( sectionindex, std::move( section ) ); + return error; +} + +} // namespace // potentially activates event handler with the same name as provided node, and within handler activation range void @@ -57,25 +114,15 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex for( auto *traction : m_directories.traction ) { - // współczynniki równania parametrycznego - auto const paramfrontdot = glm::dot( traction->vParametric, vFront ); - auto const fRaParam = - -( glm::dot( traction->pPoint1, vFront ) - glm::dot( pantographposition, vFront ) ) - / ( paramfrontdot != 0.0 ? - paramfrontdot : - 0.001 ); // div0 trap - - if( fRaParam < -0.001 - || fRaParam > 1.001 ) { continue; } + // the span against the pantograph, the geometry the AI uses to find the wire as well + auto const contact = ai_wire::span_contact( + traction->pPoint1, traction->vParametric, pantographposition, vFront, vUp, vLeft, pantograph->fWidth ); // jeśli tylko jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft - // punkt styku płaszczyzny z drutem (dla generatora łuku el.) - auto const vStyk = traction->pPoint1 + fRaParam * traction->vParametric; - // wektor musi się mieścić w przedziale ruchu pantografu - auto const vGdzie = vStyk - pantographposition; - auto fVertical = glm::dot( vGdzie, vUp ); + if( false == contact.within ) { continue; } + auto fVertical = contact.vertical; if( fVertical >= 0.0 ) { // jeśli ponad pantografem (bo może łapać druty spod wiaduktu) - auto const fHorizontal = std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth; + auto const fHorizontal = contact.horizontal; if (Global.bEnableTraction && fVertical < pantograph->PantWys - 0.15 ) { @@ -84,12 +131,12 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex // i do tego jeszcze wejdzie pod ślizg if( fHorizontal <= 0.0 ) { // 0.635 dla AKP-1 AKP-4E - SetFlag( Vehicle->MoverParameters->DamageFlag, dtrain_pantograph ); + Vehicle->physics->DamageFlag.Set(VehicleDamage::pantograph); pantograph->PantWys = -1.0; // ujemna liczba oznacza połamanie pantograph->hvPowerWire = nullptr; // bo inaczej się zasila w nieskończoność z połamanego - if( Vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { + if( Vehicle->physics->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { // liczba pantografów teraz będzie mniejsza - --Vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo; + --Vehicle->physics->EnginePowerSource.CollectorParameters.CollectorsNo; } ErrorLog( "Bad traction: " + Vehicle->name() + " broke pantograph at " + to_string( pantographposition ), logtype::traction ); @@ -120,6 +167,24 @@ basic_cell::update_traction( TDynamicObject *Vehicle, int const Pantographindex } } +// checks whether a wire of the cell, not broken, is within reach of a pantograph at specified point +bool +basic_cell::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + for( auto const *traction : m_directories.traction ) { + if( ( traction->DamageFlag & 128 ) != 0 ) { + // a broken wire powers nothing + continue; + } + if( ai_wire::reaches( + ai_wire::span_contact( traction->pPoint1, traction->vParametric, Point, Front, Up, Left, Halfwidth ), + Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, updates sounds and polls event launchers within radius around specified point void basic_cell::update_events() { @@ -232,22 +297,38 @@ basic_cell::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // cell shapes // shape count followed by opaque shape data + // NOTE: a damaged count is cut short by the end of the data rather than followed auto itemcount { sn_utils::ld_uint32( Input ) }; - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapesopaque.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_shapestranslucent.emplace_back( shape_node().deserialize( Input ) ); } itemcount = sn_utils::ld_uint32( Input ); - while( itemcount-- ) { + while( ( itemcount-- ) && ( true == Input.good() ) ) { m_lines.emplace_back( lines_node().deserialize( Input ) ); } // cell activation flag m_active = true == m_active || false == m_shapesopaque.empty() || false == m_shapestranslucent.empty() || false == m_lines.empty(); } +// takes over the content restored from a file into another cell, as deserialize() would have added it to this one +void +basic_cell::merge( basic_cell &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapesopaque.insert( m_shapesopaque.end(), std::make_move_iterator( Other.m_shapesopaque.begin() ), std::make_move_iterator( Other.m_shapesopaque.end() ) ); + m_shapestranslucent.insert( m_shapestranslucent.end(), std::make_move_iterator( Other.m_shapestranslucent.begin() ), std::make_move_iterator( Other.m_shapestranslucent.end() ) ); + m_lines.insert( m_lines.end(), std::make_move_iterator( Other.m_lines.begin() ), std::make_move_iterator( Other.m_lines.end() ) ); + m_active = true == m_active || true == Other.m_active; + Other.m_shapesopaque.clear(); + Other.m_shapestranslucent.clear(); + Other.m_lines.clear(); +} + // sends content of the class in legacy (text) format to provided stream void basic_cell::export_as_text( std::ostream &Output ) const { @@ -782,6 +863,22 @@ basic_section::update_traction( TDynamicObject *Vehicle, int const Pantographind } } +// checks whether a wire of the section's cells around specified point is within reach of a pantograph at the point +bool +basic_section::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + auto const radius { EU07_CELLSIZE * 0.5 }; // the same area of interest the pantographs look for their wire in + + for( auto const &cell : m_cells ) { + // we reject early cells which aren't within our area of interest + if( glm::length2( cell.area().center - Point ) < sq( cell.area().radius + radius ) + && cell.wire_over( Point, Front, Up, Left, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // legacy method, polls event launchers within radius around specified point void basic_section::update_events( glm::dvec3 const &Location, float const Radius ) { @@ -857,7 +954,7 @@ basic_section::deserialize( std::istream &Input ) { m_area.deserialize( Input ); // section shapes: shape count followed by shape data auto shapecount { sn_utils::ld_uint32( Input ) }; - while( shapecount-- ) { + while( ( shapecount-- ) && ( true == Input.good() ) ) { m_shapes.emplace_back( shape_node().deserialize( Input ) ); } // partitioned data @@ -866,6 +963,19 @@ basic_section::deserialize( std::istream &Input ) { } } +// takes over the content restored from a file into another section, as deserialize() would have added it to this one +void +basic_section::merge( basic_section &&Other ) { + + m_area.center = Other.m_area.center; + m_area.radius = std::max( m_area.radius, Other.m_area.radius ); + m_shapes.insert( m_shapes.end(), std::make_move_iterator( Other.m_shapes.begin() ), std::make_move_iterator( Other.m_shapes.end() ) ); + Other.m_shapes.clear(); + for( std::size_t index { 0 }; index < m_cells.size(); ++index ) { + m_cells[ index ].merge( std::move( Other.m_cells[ index ] ) ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_section::export_as_text( std::ostream &Output ) const { @@ -1165,30 +1275,44 @@ basic_region::update_traction( TDynamicObject *Vehicle, int const Pantographinde } } +// checks whether there's a contact wire over specified point, within reach of a pantograph there +bool +basic_region::wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const { + + // the vertical up and the horizontal left of the heading. the tilt of the track in curves is left out + auto const up { glm::dvec3 { 0.0, 1.0, 0.0 } }; + auto const left { glm::cross( up, Front ) }; + auto const leftlength { glm::length( left ) }; + if( leftlength <= 0.0 ) { + // no heading along the ground + return false; + } + // a list of its own, not the shared scratchpad of the region + std::vector sectionlist; + sections( Point, EU07_CELLSIZE * 0.5, sectionlist ); + for( auto const *section : sectionlist ) { + if( section->wire_over( Point, Front, up, left / leftlength, Halfwidth, Minheight, Maxheight ) ) { + return true; + } + } + return false; +} + // checks whether specified file is a valid region data file bool basic_region::is_scene( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { return false; } - // file type and version check + // file type and version check, and whether the sections add up to the whole file. a file cut short (by a write + // interrupted with an older version, or a copy) is caught here, while the scenery can still be loaded from the text std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain{ sn_utils::ld_uint32( input ) }; - uint32_t headertype{ sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type + if( auto const layout { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, static_cast( m_sections.size() ) ) }; + false == layout.empty() ) { + WriteLog( "Bad file: \"" + filename + "\" " + layout + ", ignored" ); return false; } @@ -1199,38 +1323,35 @@ basic_region::is_scene( std::string const &Scenariofile ) const { void basic_region::serialize( std::string const &Scenariofile ) const { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; - std::ofstream output { filename, std::ios::binary }; - - // region file version 1 - // header: EU07SBT + version (0-255) - sn_utils::ls_uint32( output, EU07_FILEHEADER ); - sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); - // sections - // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - std::uint32_t sectioncount { 0 }; - for( auto *section : m_sections ) { - if( section != nullptr ) { - ++sectioncount; + // the file is written under a temporary name and takes the final one only when complete, so a write cut short + // (a crash, the process killed) leaves no partial file to be read on the next start + auto const error { region_file::write_through_temporary( filename, [ this ]( std::ostream &output ) { + // region file version 1 + // header: EU07SBT + version (0-255) + sn_utils::ls_uint32( output, EU07_FILEHEADER ); + sn_utils::ls_uint32( output, EU07_FILEVERSION_REGION ); + // sections + // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range + std::uint32_t sectioncount { 0 }; + for( auto *section : m_sections ) { + if( section != nullptr ) { + ++sectioncount; + } } - } - // section count, followed by section data - sn_utils::ls_uint32( output, sectioncount ); - std::uint32_t sectionindex { 0 }; - for( auto *section : m_sections ) { - // section data: section index, followed by length of section data, followed by section data - if( section != nullptr ) { - sn_utils::ls_uint32( output, sectionindex ); - section->serialize( output ); } - ++sectionindex; + // section count, followed by section data + sn_utils::ls_uint32( output, sectioncount ); + std::uint32_t sectionindex { 0 }; + for( auto *section : m_sections ) { + // section data: section index, followed by length of section data, followed by section data + if( section != nullptr ) { + sn_utils::ls_uint32( output, sectionindex ); + section->serialize( output ); } + ++sectionindex; + } } ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: binary version of the scenery wasn't written, " + error ); } } @@ -1238,48 +1359,69 @@ basic_region::serialize( std::string const &Scenariofile ) const { bool basic_region::deserialize( std::string const &Scenariofile ) { - auto filename { Scenariofile }; - while( filename[ 0 ] == '$' ) { - // trim leading $ char rainsted utility may add to the base name for modified .scn files - filename.erase( 0, 1 ); - } - erase_extension( filename ); - filename = Global.asCurrentSceneryPath + filename; - filename += EU07_FILEEXTENSION_REGION; + auto const filename { region_file_name( Scenariofile ) }; if( false == FileExists( filename ) ) { Global.file_binary_terrain_state = false; return false; } // region file version 1 - // file type and version check + // file type and version check, and whether the sections add up to the whole file std::ifstream input( filename, std::ios::binary ); - - uint32_t headermain { sn_utils::ld_uint32( input ) }; - uint32_t headertype { sn_utils::ld_uint32( input ) }; - - if( headermain != EU07_FILEHEADER || headertype != EU07_FILEVERSION_REGION ) { - // wrong file type - WriteLog( "Bad file: \"" + filename + "\" is of either unrecognized type or version" ); + auto const sectionlimit { static_cast( m_sections.size() ) }; + auto error { region_file::check_layout( input, EU07_FILEHEADER, EU07_FILEVERSION_REGION, sectionlimit ) }; + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); return false; } // sections // TBD, TODO: build table of sections and file offsets, if we postpone section loading until they're within range - // section count - auto sectioncount { sn_utils::ld_uint32( input ) }; - while( sectioncount-- ) { - // section index, followed by section data size, followed by section data - auto const sectionindex { sn_utils::ld_uint32( input ) }; - auto const sectionsize { sn_utils::ld_uint32( input ) }; - if( m_sections[ sectionindex ] == nullptr ) { - m_sections[ sectionindex ] = new basic_section(); + // the sections are restored apart from the region, which takes them over only once the whole file was read + // without a fault: a damaged file leaves nothing of itself behind + std::vector>> sections; + try { + input.clear(); + input.seekg( 2 * sizeof( std::uint32_t ), std::ios::beg ); + // section count + auto sectioncount { sn_utils::ld_uint32( input ) }; + sections.reserve( sectioncount ); + while( ( sectioncount-- ) && ( true == error.empty() ) ) { + error = read_region_section( input, sectionlimit, sections ); + } + } + catch( std::exception const &Exception ) { + error = std::string( "can't be read, " ) + Exception.what(); + } + if( false == error.empty() ) { + ErrorLog( "Bad file: \"" + filename + "\" " + error + ", the geometry it holds is missing" ); + return false; + } + for( auto &[ sectionindex, section ] : sections ) { + if( m_sections[ sectionindex ] == nullptr ) { + m_sections[ sectionindex ] = section.release(); + } + else { + m_sections[ sectionindex ]->merge( std::move( *section ) ); } - m_sections[ sectionindex ]->deserialize( input ); } return true; } +// removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew +void +basic_region::discard_scene( std::string const &Scenariofile ) const { + + auto const filename { region_file_name( Scenariofile ) }; + std::error_code error; + if( true == std::filesystem::remove( filename, error ) ) { + WriteLog( "Bad file: \"" + filename + "\" removed, it will be made anew from the scenery on the next start" ); + } + else if( error ) { + ErrorLog( "Bad file: \"" + filename + "\" can't be removed, " + error.message() + ". Remove it to have it made anew from the scenery" ); + } +} + // sends content of the class in legacy (text) format to provided stream void basic_region::export_as_text( std::ostream &Output ) const { diff --git a/scene/scene.h b/scene/scene.h index 5560171bb..e92b11988 100644 --- a/scene/scene.h +++ b/scene/scene.h @@ -107,6 +107,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers within radius around specified point void update_events(); @@ -132,6 +136,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another cell, as deserialize() would have added it to this one + void + merge( basic_cell &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -347,6 +354,10 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether a wire, not broken, is within reach of a pantograph at specified point: the plane of the pantograph's + // movement, normal to Front, crosses it over the slide of half width Halfwidth, between Minheight and Maxheight along Up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, updates sounds and polls event launchers within radius around specified point void update_events( glm::dvec3 const &Location, float const Radius ); @@ -362,6 +373,9 @@ public: // restores content of the class from provided stream void deserialize( std::istream &Input ); + // takes over the content restored from a file into another section, as deserialize() would have added it to this one + void + merge( basic_section &&Other ); // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; @@ -476,6 +490,11 @@ public: // legacy method, finds and assigns traction piece to specified pantograph of provided vehicle void update_traction( TDynamicObject *Vehicle, int const Pantographindex ); + // checks whether there's a contact wire, not broken, over specified point of a track with heading Front, within reach of + // a pantograph there: over its slide of half width Halfwidth, between Minheight and Maxheight above the point. the + // geometry is the one the pantographs find their wire with (ai_wire::span_contact), with the vertical up + bool + wire_over( glm::dvec3 const &Point, glm::dvec3 const &Front, double const Halfwidth, double const Minheight, double const Maxheight ) const; // legacy method, polls event launchers around camera void update_events(); @@ -491,6 +510,9 @@ public: // restores content of the class from file with specified name. returns: true on success, false otherwise bool deserialize( std::string const &Scenariofile ); + // removes the region file of specified scenario file, which turned out to be damaged, so the next start writes it anew + void + discard_scene( std::string const &Scenariofile ) const; // sends content of the class in legacy (text) format to provided stream void export_as_text( std::ostream &Output ) const; diff --git a/scene/scenelayers.cpp b/scene/scenelayers.cpp index 9e075d063..e729fac7b 100644 --- a/scene/scenelayers.cpp +++ b/scene/scenelayers.cpp @@ -393,6 +393,14 @@ bool node_layers::editable(basic_node const *Node, std::string *Reason) const { return false; } + if (Node->m_generated) + { + if (Reason != nullptr) + { + *Reason = STR_C("it's made by the game while it runs (the moths at a lamp), not a part of the scenery"); + } + return false; + } if (Node->m_catenary) { // moved, copied or deleted by itself it would part from the catenary which keeps it (and is rebuilt from its own file) diff --git a/scene/scenelayerssave.cpp b/scene/scenelayerssave.cpp index 37983e147..5d52689e9 100644 --- a/scene/scenelayerssave.cpp +++ b/scene/scenelayerssave.cpp @@ -27,6 +27,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "editor/editorFormat.hpp" +#include #include #include #include @@ -1768,8 +1769,8 @@ save_result node_layers::save(std::vector const &Rootstatements, st // without the copy nothing is replaced { auto const now{std::time(nullptr)}; - char stamp[32]; - std::strftime(stamp, sizeof(stamp), "%Y%m%d-%H%M%S", std::localtime(&now)); + std::tm const local{local_tm(now)}; + auto const stamp{std::format("{:04}{:02}{:02}-{:02}{:02}{:02}", local.tm_year + 1900, local.tm_mon + 1, local.tm_mday, local.tm_hour, local.tm_min, local.tm_sec)}; for (auto const output : written) { auto const filepath{path(output)}; diff --git a/scene/scenenode.cpp b/scene/scenenode.cpp index 426f0e077..0e68b391a 100644 --- a/scene/scenenode.cpp +++ b/scene/scenenode.cpp @@ -87,6 +87,35 @@ shape_node::shapenode_data::serialize( std::ostream &Output ) const { } } +// legacy scenery shapes frequently come with all-zero normals (e.g. pkp/szafa-przek1.inc). +// the shaders normalize the interpolated normal, which turns a zero vector into NaN; with the gl46 +// lighting (ambient sh, envmap, sky occlusion all depend on the normal) that blackens the whole surface. +// replace missing normals with the flat normal of the triangle, using the same winding as authored data +void +fill_missing_normals( std::vector &Vertices ) { + + for( std::size_t idx = 0; idx + 2 < Vertices.size(); idx += 3 ) { + auto *triangle { &Vertices[ idx ] }; + if( ( glm::length2( triangle[ 0 ].normal ) > 1e-12f ) + && ( glm::length2( triangle[ 1 ].normal ) > 1e-12f ) + && ( glm::length2( triangle[ 2 ].normal ) > 1e-12f ) ) { + continue; + } + auto const facenormal { glm::cross( + triangle[ 1 ].position - triangle[ 0 ].position, + triangle[ 2 ].position - triangle[ 0 ].position ) }; + auto const normal { ( + glm::length2( facenormal ) > 0.0 ? + glm::vec3{ glm::normalize( facenormal ) } : + glm::vec3{ 0.f, 1.f, 0.f } ) }; + for( int vertexidx = 0; vertexidx < 3; ++vertexidx ) { + if( glm::length2( triangle[ vertexidx ].normal ) <= 1e-12f ) { + triangle[ vertexidx ].normal = normal; + } + } + } +} + // restores content of the struct from provided input stream void shape_node::shapenode_data::deserialize( std::istream &Input ) { @@ -108,7 +137,13 @@ shape_node::shapenode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); if(has_userdata) userdata.resize(vertices.size()); gfx::basic_vertex localvertex; @@ -118,6 +153,8 @@ shape_node::shapenode_data::deserialize( std::istream &Input ) { if(has_userdata) userdata[i].deserialize( Input ); } + // binary caches created by older builds may still hold the zero normals + fill_missing_normals( vertices ); } @@ -143,7 +180,7 @@ shape_node::deserialize( std::istream &Input ) { // restores content of the node from provided input stream shape_node & -shape_node::import( cParser &Input, scene::node_data const &Nodedata ) { +shape_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; @@ -312,6 +349,8 @@ shape_node::import( cParser &Input, scene::node_data const &Nodedata ) { } while( token != "endtri" && false == token.empty() ); // data which ends without closing the node would otherwise keep the loop going forever + fill_missing_normals( m_data.vertices ); + return *this; } @@ -527,7 +566,13 @@ lines_node::linesnode_data::deserialize( std::istream &Input ) { origin = sn_utils::d_dvec3( Input ); // NOTE: geometry handle is acquired during geometry creation // vertex data - vertices.resize( sn_utils::ld_uint32( Input ) ); + auto const vertexcount { sn_utils::ld_uint32( Input ) }; + if( vertexcount > sn_utils::remaining( Input ) / ( 8 * sizeof( float ) ) ) { + // each vertex takes 8 floats of the data at least: a count the rest of it can't hold comes from a damaged file + Input.setstate( std::ios::failbit ); + return; + } + vertices.resize( vertexcount ); gfx::basic_vertex localvertex; for( auto &vertex : vertices ) { localvertex.deserialize( Input ); @@ -561,7 +606,7 @@ lines_node::deserialize( std::istream &Input ) { // restores content of the node from provded input stream lines_node & -lines_node::import( cParser &Input, scene::node_data const &Nodedata ) { +lines_node::import_from( cParser &Input, scene::node_data const &Nodedata ) { // import common data m_name = Nodedata.name; @@ -764,6 +809,8 @@ basic_node::deserialize( std::istream &Input ) { void basic_node::export_as_text( std::ostream &Output ) const { + // what the game made while it runs isn't a part of the scenery + if( m_generated ) { return; } Output // header << "node" diff --git a/scene/scenenode.h b/scene/scenenode.h index f10ac0d16..0f0faa3a3 100644 --- a/scene/scenenode.h +++ b/scene/scenenode.h @@ -74,6 +74,9 @@ struct node_data { instance_handle instance { 0 }; // include of an *.inc template which defines the node, if it isn't defined directly by a scenery layer file }; +// gives the vertices of each triangle with a zero normal the flat normal of the triangle, by its authored winding +void fill_missing_normals( std::vector &Vertices ); + // holds unique piece of geometry, covered with single material class shape_node { @@ -122,7 +125,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream shape_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // imports data from provided submodel shape_node & convert( TSubModel const *Submodel ); @@ -254,7 +257,7 @@ public: deserialize( std::istream &Input ); // restores content of the node from provided input stream lines_node & - import( cParser &Input, scene::node_data const &Nodedata ); + import_from( cParser &Input, scene::node_data const &Nodedata ); // adds content of provided node to already enclosed geometry. returns: true if merge could be performed bool merge( lines_node &Lines ); @@ -423,6 +426,7 @@ public: bool m_layerhidden { false }; // the node was visible until the editor hid its scenery layer, or the include which defines it bool m_preview { false }; // the node was made by the editor to show an include it placed or changed, and is replaced when the include changes bool m_catenary { false }; // a part the catenary assembled (world/catenary_scene.cpp): it's changed by the catenary tool, not edited as a node + bool m_generated { false }; // made by the game while it runs (the moths at the lamps, rendering/common/moths.cpp): not edited, not saved scene::layer_handle m_layer { null_handle }; // scenery layer this node belongs to, if any // include of an *.inc template which defines the node; 0 if the node is defined directly by a scenery layer file. // such nodes can't be rewritten one by one on scenery save. set only for scenery opened for editing diff --git a/scene/scenenodegroups.cpp b/scene/scenenodegroups.cpp index 781287806..e3d1bc463 100644 --- a/scene/scenenodegroups.cpp +++ b/scene/scenenodegroups.cpp @@ -207,12 +207,12 @@ node_groups::update_map() continue; last_switch->track[lastc - 'a'] = track; - for (auto trk : last_switch->track) - if (!trk) - goto skip_e; + // all four tracks of the cross switch have to be known before it's assigned + if (!std::ranges::all_of(last_switch->track, [](TTrack const *Track) { return Track != nullptr; })) + continue; if (!assign_cross_switch(*last_switch, sw_name, "ac", 0)) - skip_e: continue; + continue; if (!assign_cross_switch(*last_switch, sw_name, "ad", 1)) continue; if (!assign_cross_switch(*last_switch, sw_name, "bc", 2)) diff --git a/scene/sceneterrain.cpp b/scene/sceneterrain.cpp index d0453f2b3..4248d4592 100644 --- a/scene/sceneterrain.cpp +++ b/scene/sceneterrain.cpp @@ -455,7 +455,7 @@ bool terrain_file::write(std::string const &Text, std::string const &Binaryfile, Message = "node of type \"" + nodedata.type + "\" (line " + std::to_string(input.Line()) + ") can't be a part of binary terrain"; return false; } - auto shape{shape_node().import(input, nodedata)}; + auto shape{shape_node().import_from(input, nodedata)}; // the shapes are all sent to the section cells, which groups them the way it'd be done for translucent geometry. // whether they can be merged into section-wide pieces instead is decided when the file is loaded, see the layout notes shape.m_data.translucent = true; @@ -799,7 +799,7 @@ bool read_text_triangles(std::string const &Text, terrain_reference const &Refer input >> nodedata.range_max >> nodedata.range_min >> nodedata.name >> nodedata.type; if (nodedata.type == "triangles" || nodedata.type == "triangle_strip" || nodedata.type == "triangle_fan") { - auto const shape{shape_node().import(input, nodedata)}; + auto const shape{shape_node().import_from(input, nodedata)}; auto const &data{shape.data()}; auto const *material{GfxRenderer->Material(data.material)}; auto const name{material != nullptr ? material->GetName() : std::string{}}; @@ -1130,6 +1130,8 @@ void terrain_file::load(basic_section &Section, terrain_block const &Block) vertex.texture.t = std::clamp(vertex.texture.t, 0.001f, 0.999f); } } + // a file written by an older build can hold the zero normals of its text + fill_missing_normals(shapedata.vertices); if (true == shapedata.translucent || shapedata.rangesquared_max <= 90000.0 || shapedata.rangesquared_min > 0.0) { diff --git a/scene/sn_utils.cpp b/scene/sn_utils.cpp index b6a3f7c32..fbdbcb7f0 100644 --- a/scene/sn_utils.cpp +++ b/scene/sn_utils.cpp @@ -93,14 +93,26 @@ std::string sn_utils::d_str(std::istream &s) char c{}; while (true) { - s.read(&c, 1); - if (c == 0) + // a string cut short by the end of the data ends there too + if (!s.read(&c, 1) || c == 0) break; r.push_back(c); } return r; } +// number of bytes left to read in the stream, 0 if it failed or can't tell +std::uint64_t sn_utils::remaining(std::istream &s) +{ + auto const position{s.tellg()}; + if (position < 0) + return 0; + s.seekg(0, std::ios::end); + auto const end{s.tellg()}; + s.seekg(position); + return end > position ? static_cast(end - position) : 0; +} + bool sn_utils::d_bool(std::istream& s) { return ld_uint16(s) == 1; diff --git a/scene/sn_utils.h b/scene/sn_utils.h index 4212ac29a..87da22d93 100644 --- a/scene/sn_utils.h +++ b/scene/sn_utils.h @@ -20,6 +20,8 @@ public: static glm::dvec3 d_dvec3(std::istream&); static glm::vec3 d_vec3(std::istream&); static glm::vec4 d_vec4(std::istream&); + // number of bytes left to read in the stream, 0 if it failed or can't tell + static std::uint64_t remaining(std::istream&); static void ls_uint16(std::ostream&, uint16_t); static void ls_uint32(std::ostream&, uint32_t); diff --git a/script_screens_doc.md b/script_screens_doc.md index 52ccc9ced..3e9248d11 100644 --- a/script_screens_doc.md +++ b/script_screens_doc.md @@ -137,6 +137,48 @@ used: - on the cpu, in the screens' worker, when the renderer can't do it on the gpu (the NVRHI renderer, OpenGL ES, a shader that failed to load) or `screens.gpupost` is 0. A shader that fails is logged once, and the cpu takes over. +### Limits of a Lua script + +Besides the 200 million instructions of a call, a Lua screen is held to what runs in C, where the count doesn't reach: + +- memory: a screen holds at most 128 MB: its Lua heap and the pixels of its images, fonts and sprites (4 bytes a pixel + of an image, 1 of a font or a sprite). An object that would take the screen over is refused (`memory limit + exceeded`), and a screen found holding more stops with that error. Garbage doesn't count: the check collects it + first, every thousand instructions and before the calls below. Between the checks the screen's heap goes through a + counter of the game's, in front of LuaJIT's own allocator, which refuses a block that would take the screen over + twice the limit as it is asked for (`not enough memory`, an error the script may catch). So what one instruction + makes is held as well: a loop doubling a string (`for i = 1, 11 do s = s .. s end` on a 1 MB `s`) stops at the + concatenation that would go over 256 MB, not at LuaJIT's own heap limit of about 2 GB; +- `string.rep` makes no string over 1 MB; `string.format`, `table.concat` and `string.gsub` (with a string or a table to + replace with) refuse a result that may be over the memory of a screen, counted from the lengths of what they are + given; +- the pattern functions (`string.find`, `match`, `gmatch`, `gsub`) backtrack, and some patterns take hours on a long + subject (`("a"):rep(1e6):find(".-b")`). A call is refused (`the pattern may take too long`) when the steps it may + take at worst are over 100 million, about a tenth of a second at worst: the length of the subject (plus one), times the + length of the pattern, times the subject again for each repetition (`*`, `+`, `-`, `%b`, a back reference `%1`) but + one followed by what always matches (nothing, as in a repetition that ends the pattern, or `(.-)%s*$`), times 2 for + each `?`, and taken once rather than from every position for a pattern anchored with `^` (not in `gmatch`). A + repetition of a character or a `%` class right before the final `$` (`%s*$`) counts the longest run of it in the + subject rather than the whole subject. A plain search (`find` with `plain`, or a pattern of no special characters) is + the subject times the pattern. So a pattern ending in its only repetition (`"[^\n]+"`, `"%d+"`) works on any subject, + one more repetition (`"(%w+)=(%w+)"`) on some 3 000 to 5 000 bytes, and each further one divides that a lot. The + usual trim, `s:match("^%s*(.-)%s*$")`, costs the line times its longest run of spaces: a line of words, even a + megabyte long, is fine, but a long run of spaces inside it is refused, since the trim really takes the square of that. + A trim that stays linear on any string: + + ```lua + local function trim(s) + local first = s:find("%S") + if not first then return "" end + return s:sub(first, #s - s:reverse():find("%S") + 1) + end + ``` +- `xpcall` is made of `pcall`: the handler gets the error once it has left the function, and a coroutine may yield + inside either. There is no `newproxy`, so no finalizer (`__gc`) of the script's own: LuaJIT runs those without the + instruction count; +- the game reads `render` and `init` of the script's table in protected mode, so a metatable of the script's + (`__index`) may provide them; one that fails or runs over switches the screen off. + ## WebAssembly modules A module exports: @@ -208,3 +250,64 @@ clang --target=wasm32 -O2 -nostdlib -Wl,--no-entry -o ekran.wasm ekran.c Any language that compiles to WebAssembly works the same way (Rust `wasm32-unknown-unknown`, Zig, AssemblyScript), as long as the module imports nothing but the `eu07` functions above. + +## Scenery scripts + +A scenery runs a Lua script with `lua ` in its `.scn`, while the scenery loads. The script registers events +and works with memcells, tracks and vehicles through the table `eu07.events` (`event_create`, `event_dispatch`, +`memcell_update`, `writelog` and the rest, see `scripting/lua.cpp`). It shares the sandbox of the Lua screens: + +- the file is a path relative to the scenery folder (`scenery/`), and stays inside it: no `..`, no drive, no leading + `/`. `/` and `\` both separate folders, on Linux too. It is text, of at most 16 MB; precompiled code is not loaded; +- the script gets the base library, `table`, `string`, `math` and `bit`, and of `os` only the clock: `os.time`, + `os.clock`, `os.difftime` and `os.date` (with the C89 conversions only, `%Y`, `%d`, `%H` and so on). It gets no + `io`, the rest of `os`, `ffi`, `debug`, `jit`, `package`, `require`, `dofile`, `load`, `loadfile` or `loadstring`; +- a script that fails stops there, the error goes to the log with the file name and line, and the scenery goes on + loading. An event handler that fails is logged with the name of the event, and the simulation goes on; +- the events, tracks, isolated circuits, memcells and vehicles the functions give (`event_find`, `track_find`, + `memcell_find`, the event and the vehicle an event handler gets...) are handles of their kind: equal for the same + object, usable as keys of a table, and taken only where that kind goes. Another kind, or any other value, is an + error (`bad argument #1 to 'memcell_update' (eu07.memcell expected, got userdata)`); `nil`, which the find + functions give for a missing object, is taken as no object, as before. An event run without a vehicle gives its + handler `nil` for the vehicle. + +Instead of `io`, a scenery script reads and writes files through `eu07`, as the Lua screens read theirs: + +| function | meaning | +|----------------------------------|------------------------------------------------------------------------------------------| +| `eu07.read_file(path)` | the contents of a file of the scenery folder (`scenery/`), or `nil`: a regular file of at most 16 MB, the path as for `lua ` | +| `eu07.write_file(path, text)` | writes `text` (any bytes) to a file of the scenery's data folder, replacing what was there, and makes the folders of `path`; returns `true`, or `nil` and the reason | +| `eu07.read_data_file(path)` | the contents of a file of the scenery's data folder, or `nil`: what `write_file` wrote there | + +The data folder is the scenery's own, in the player's folder of the game: `%APPDATA%\MaSzyna\scenery_data\\` +on Windows, `~/.config/MaSzyna/scenery_data//` on Linux (`~/Library/Application Support/MaSzyna/...` on a +Mac), `` being the `.scn` file without `.scn` (`td.scn`: `scenery_data/td/`). The game writes nowhere else +for a script, and never into its own folder; the log says where the folder is when the scenery loads its first +script. What is written there stays for the next run of the scenery, and the player may delete it. + +A path to write to is relative, with `/` or `\` between the folders, at most 8 folders deep and 200 bytes long, and +each name in it portable: no `..`, no `.`, no empty name, no drive, no `:` `<` `>` `"` `|` `?` `*` or control +characters, no `.` or space at the end, and none of the names Windows keeps for its devices (`con`, `nul`, `com1`, +`lpt1`... with or without an extension). A file is at most 1 MB (1048576 bytes), and the data folder of a scenery holds at most 256 +files and 16 MB together; a write over these limits is refused, and leaves the file as it was. + +```lua +local saved = eu07.read_data_file("state.txt") +local runs = tonumber(saved or "0") + 1 +local ok, reason = eu07.write_file("state.txt", tostring(runs)) +if not ok then eu07.events.writelog("state not saved: " .. reason) end +``` + +A script written for the earlier full libraries stops at the first call to one of them (`attempt to index global +'io' (a nil value)` in the log). For a scenery you trust, `eu07.ini` can give the scripts all of LuaJIT's libraries +again: + +| key | default | meaning | +|---------------------|---------|------------------------------------------------------------------------------------------| +| `lua.fulllibraries` | no | yes: the scenery scripts get all of LuaJIT's libraries (`io`, `os`, `ffi`, `require`...), and with them the files and programs of the computer. The Lua screens stay sandboxed | + +Only `eu07.ini` turns it on: a `config` block of a scenery doesn't (the log says the key was ignored). Nor does it set +the other keys that would take a scenery out of its sandbox or reach the computer: `execonexit`, `extcam.cmd`, +`extcam.rec`, `screenshotsdir`, `network.server`, `network.client`, `zmq.address`, `motiontelemetry`, `uart`, +`feedbackmode`, `feedbackport`, nor does it switch on `python.enabled`, `luascreens.enabled` or `wasm.enabled` when +`eu07.ini` has them off. A scenery may still switch those three off, or `lua.fulllibraries` off, as it always could. diff --git a/scripting/lua.cpp b/scripting/lua.cpp index 14ecbb75d..93e542742 100644 --- a/scripting/lua.cpp +++ b/scripting/lua.cpp @@ -5,6 +5,9 @@ #include "world/MemCell.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" +#include "scripting/luasandbox.h" +#include "utilities/utilities.h" +#include "physics/vehicle.h" lua::lua() { @@ -12,7 +15,13 @@ lua::lua() if (!state) throw std::runtime_error("cannot create lua state"); lua_atpanic(state, atpanic); - luaL_openlibs(state); + // sandboxed as the script screens are: no io, ffi, debug, require or load*, and of os only the clock. + // lua.fulllibraries in eu07.ini opens the rest when the scenery loads its first script (interpret()) + lua_sandbox::open_safe_libraries(state); + lua_sandbox::open_clock_library(state); + // the events, tracks, isolated circuits, vehicles and memcells a script holds: a userdata of a metatable of each + // kind, which the functions check + lua_sandbox::open_handles(state); static constexpr luaL_Reg api[] = { @@ -41,6 +50,9 @@ lua::lua() {nullptr, nullptr} }; luaL_register(state, "eu07.events", api); + lua_pop(state, 1); + // eu07.read_file, eu07.write_file and eu07.read_data_file, the files of the scenery in place of io + lua_sandbox::open_file_library(state, &files); } lua::~lua() @@ -51,21 +63,38 @@ lua::~lua() std::string lua::get_error() const { - return lua_tostring(state, -1); + auto const *error = lua_tostring(state, -1); + return error ? error : "unknown error"; } -void lua::interpret(const std::string& file) const +void lua::interpret(const std::string &folder, const std::string &file) { - if (luaL_dofile(state, file.c_str())) { - std::string str = lua_tostring(state, -1); - ErrorLog("lua: Runtime error: " + str, logtype::lua); + if (Global.lua_fulllibraries && !full_libraries) { + // all of LuaJIT's libraries, as before the sandbox: the scripts may then reach files, programs and ffi + luaL_openlibs(state); + full_libraries = true; + WriteLog("lua: lua.fulllibraries is on, the scenery scripts run with all libraries (io, os, ffi, require...)", logtype::lua); + } + // the scripts read the files of the scenery folder, and write theirs into a folder of the scenery among the + // player's files (%APPDATA%/MaSzyna, ~/.config/MaSzyna), never into the game + files.scenery = folder; + if (auto data = lua_sandbox::scenery_data_folder(user_config_path("scenery_data"), Global.SceneryFile); data != files.data) { + files.data = std::move(data); + auto const name = files.data.u8string(); + if (!name.empty()) + WriteLog("lua: the scenery scripts write their files (eu07.write_file) to \"" + std::string(name.begin(), name.end()) + "\"", logtype::lua); + } + // a relative path inside the scenery folder, a file of text, run in protected mode: a script that fails stops + // there, and the scenery goes on loading + if (auto const error = lua_sandbox::run_script_file(state, folder, file)) { + ErrorLog("lua: " + *error, logtype::lua); } } int lua::atpanic(lua_State *s) { - std::string err = lua_tostring(s, -1); - ErrorLog("lua: Runtime error: " + err, logtype::lua); + auto const *err = lua_tostring(s, -1); + ErrorLog(std::string("lua: Runtime error: ") + (err ? err : "unknown error"), logtype::lua); return 0; } @@ -75,13 +104,37 @@ void lua::unref(lua_State *L, const int ref) luaL_unref(L, LUA_REGISTRYINDEX, ref); } +namespace { + +struct event_call { + int handler; + basic_event *event; + TDynamicObject *activator; +}; + +// calls the handler of the event (event_call) with the handles of the event and its activator (nil when there is none) +int call_handler(lua_State *L) +{ + auto const &call = *static_cast(lua_touserdata(L, 1)); + lua_rawgeti(L, LUA_REGISTRYINDEX, call.handler); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, call.event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::vehicle, call.activator); + lua_call(L, 2, 0); + return 0; +} + +} // namespace + /// Executes the callback function of an event created with `scriptapi_event_create`. void lua::dispatch_event(lua_State *L, const int handler, basic_event *event, const TDynamicObject *activator) { - lua_rawgeti(L, LUA_REGISTRYINDEX, handler); - lua_pushlightuserdata(L, event); - lua_pushlightuserdata(L, const_cast(activator)); - lua_call(L, 2, 0); + event_call call{handler, event, const_cast(activator)}; + // in protected mode, the handles made as well: a handler that fails is logged, and the simulation goes on + if (lua_cpcall(L, call_handler, &call) != 0) { + auto const *error = lua_tostring(L, -1); + ErrorLog("lua: event " + (event ? event->m_name : std::string("?")) + ": " + (error ? error : "unknown error"), logtype::lua); + lua_pop(L, 1); + } } void lua::push_memcell_values(lua_State *L, const TMemCell *mc) @@ -103,11 +156,17 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) // For negative indices, we need to account for the extra item that is the key name/value extracted from the table. if (idx < 0) idx--; - memcell_values mc{nullptr, 0.0, 0.0}; + luaL_checktype(L, idx, LUA_TTABLE); + // no text in the table is an empty one: the memcell and the vehicle take the text as a string. copied: the text of + // a number is made on the stack, and gone with it + memcell_values mc{"", 0.0, 0.0}; lua_pushstring(L, "str"); lua_gettable(L, idx); - if (lua_isstring(L, -1)) - mc.str = lua_tostring(L, -1); + if (lua_isstring(L, -1)) { + std::size_t length = 0; + auto const *text = lua_tolstring(L, -1, &length); + mc.str.assign(text, length); + } lua_pop(L, 1); lua_pushstring(L, "num1"); lua_gettable(L, idx); @@ -124,7 +183,7 @@ memcell_values lua::get_memcell_values(lua_State *L, int idx) int lua::scriptapi_event_create(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); double delay = lua_tonumber(L, 2); double randomdelay = lua_tonumber(L, 3); lua_pushvalue(L, 4); @@ -136,7 +195,7 @@ int lua::scriptapi_event_create(lua_State *L) event->m_delayrandom = randomdelay; if (simulation::Events.insert(event)) { - lua_pushlightuserdata(L, event); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, event); return 1; } return 0; @@ -144,11 +203,11 @@ int lua::scriptapi_event_create(lua_State *L) int lua::scriptapi_event_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) { - lua_pushlightuserdata(L, foundevent); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, foundevent); return 1; } ErrorLog("lua: missing event: " + name); @@ -157,7 +216,7 @@ int lua::scriptapi_event_find(lua_State *L) int lua::scriptapi_event_exists(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); basic_event *foundevent = simulation::Events.FindEvent(name); lua_pushboolean(L, foundevent != nullptr); return 1; @@ -165,7 +224,7 @@ int lua::scriptapi_event_exists(lua_State *L) int lua::scriptapi_event_getname(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); if (event) { lua_pushstring(L, event->m_name.c_str()); @@ -176,8 +235,8 @@ int lua::scriptapi_event_getname(lua_State *L) int lua::scriptapi_event_dispatch(lua_State *L) { - auto *event = static_cast(lua_touserdata(L, 1)); - auto *activator = static_cast(lua_touserdata(L, 2)); + auto *event = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::event); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); if (event) simulation::Events.AddToQuery(event, activator, delay); @@ -186,8 +245,8 @@ int lua::scriptapi_event_dispatch(lua_State *L) int lua::scriptapi_event_dispatch_n(lua_State *L) { - std::string name = lua_tostring(L, 1); - auto *activator = static_cast(lua_touserdata(L, 2)); + std::string name = luaL_checkstring(L, 1); + auto *activator = lua_sandbox::check_handle(L, 2, lua_sandbox::handle_kind::vehicle); double delay = lua_tonumber(L, 3); basic_event *foundevent = simulation::Events.FindEvent(name); if (foundevent) @@ -199,11 +258,11 @@ int lua::scriptapi_event_dispatch_n(lua_State *L) int lua::scriptapi_track_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { - lua_pushlightuserdata(L, track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, track); return 1; } ErrorLog("lua: missing track: " + name); @@ -212,7 +271,7 @@ int lua::scriptapi_track_find(lua_State *L) int lua::scriptapi_track_isoccupied(lua_State *L) { - auto *track = static_cast(lua_touserdata(L, 1)); + auto *track = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track); if (track) { lua_pushboolean(L, !track->IsEmpty()); @@ -223,7 +282,7 @@ int lua::scriptapi_track_isoccupied(lua_State *L) int lua::scriptapi_track_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TTrack *track = simulation::Paths.find(name); if (track) { @@ -236,11 +295,11 @@ int lua::scriptapi_track_isoccupied_n(lua_State *L) int lua::scriptapi_isolated_find(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { - lua_pushlightuserdata(L, isolated); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::isolated, isolated); return 1; } ErrorLog("lua: missing isolated: " + name); @@ -249,7 +308,7 @@ int lua::scriptapi_isolated_find(lua_State *L) int lua::scriptapi_isolated_isoccupied(lua_State *L) { - auto *isolated = static_cast(lua_touserdata(L, 1)); + auto *isolated = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::isolated); if (isolated) { lua_pushboolean(L, isolated->Busy()); @@ -260,7 +319,7 @@ int lua::scriptapi_isolated_isoccupied(lua_State *L) int lua::scriptapi_isolated_isoccupied_n(lua_State *L) { - std::string name = lua_tostring(L, 1); + std::string name = luaL_checkstring(L, 1); TIsolated *isolated = TIsolated::Find(name); if (isolated) { @@ -273,7 +332,7 @@ int lua::scriptapi_isolated_isoccupied_n(lua_State *L) int lua::scriptapi_train_getname(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); if (dyn && dyn->Mechanik) { lua_pushstring(L, dyn->Mechanik->TrainName().c_str()); @@ -284,7 +343,7 @@ int lua::scriptapi_train_getname(lua_State *L) int lua::scriptapi_dynobj_putvalues(lua_State *L) { - auto *dyn = static_cast(lua_touserdata(L, 1)); + auto *dyn = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::vehicle); auto [str, num1, num2] = get_memcell_values(L, 2); if (!dyn) return 0; @@ -292,17 +351,17 @@ int lua::scriptapi_dynobj_putvalues(lua_State *L) if (dyn->Mechanik) dyn->Mechanik->PutCommand(str, num1, num2, loc); else - dyn->MoverParameters->PutCommand(str, num1, num2, loc); + dyn->physics->PutCommand(str, num1, num2, loc); return 0; } int lua::scriptapi_memcell_find(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); if (mc) { - lua_pushlightuserdata(L, mc); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, mc); return 1; } ErrorLog("lua: missing memcell: " + str); @@ -311,14 +370,14 @@ int lua::scriptapi_memcell_find(lua_State *L) int lua::scriptapi_memcell_read(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); push_memcell_values(L, mc); return 1; } int lua::scriptapi_memcell_read_n(lua_State *L) { - std::string str = lua_tostring(L, 1); + std::string str = luaL_checkstring(L, 1); TMemCell *mc = simulation::Memory.find(str); push_memcell_values(L, mc); if (!mc) @@ -328,7 +387,7 @@ int lua::scriptapi_memcell_read_n(lua_State *L) int lua::scriptapi_memcell_update(lua_State *L) { - auto *mc = static_cast(lua_touserdata(L, 1)); + auto *mc = lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell); auto [str, num1, num2] = get_memcell_values(L, 2); if (mc) mc->UpdateValues(str, num1, num2, @@ -338,7 +397,7 @@ int lua::scriptapi_memcell_update(lua_State *L) int lua::scriptapi_memcell_update_n(lua_State *L) { - std::string mstr = lua_tostring(L, 1); + std::string mstr = luaL_checkstring(L, 1); auto [str, num1, num2] = get_memcell_values(L, 2); TMemCell *mc = simulation::Memory.find(mstr); if (mc) @@ -359,14 +418,14 @@ int lua::scriptapi_random(lua_State *L) int lua::scriptapi_writelog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); WriteLog("lua: log: " + txt, logtype::lua); return 0; } int lua::scriptapi_writeerrorlog(lua_State *L) { - std::string txt = lua_tostring(L, 1); + std::string txt = luaL_checkstring(L, 1); ErrorLog("lua: log: " + txt, logtype::lua); return 0; } diff --git a/scripting/lua.h b/scripting/lua.h index 07d729264..dc28a01e4 100644 --- a/scripting/lua.h +++ b/scripting/lua.h @@ -1,15 +1,22 @@ #pragma once #include #include +#include "scripting/luasandbox.h" + +#include class basic_event; class TMemCell; class TDynamicObject; -struct memcell_values { const char *str; double num1; double num2; }; +struct memcell_values { std::string str; double num1; double num2; }; class lua { lua_State *state; + bool full_libraries = false; // lua.fulllibraries: all of LuaJIT's libraries opened + // what eu07.read_file reads (the scenery folder) and eu07.write_file writes (the scenery's data folder), known + // when the scenery loads its scripts (interpret()) + lua_sandbox::file_folders files; static int atpanic(lua_State *s); @@ -41,7 +48,9 @@ public: ~lua(); std::string get_error() const; - void interpret(const std::string& file) const; + // runs the script file, a relative path inside folder (the scenery folder), sandboxed (scripting/luasandbox.h). + // a script that can't be read or fails is logged + void interpret(const std::string &folder, const std::string &file); static void unref(lua_State *L, int ref); static void dispatch_event(lua_State *L, int handler, basic_event *event, const TDynamicObject *activator); static void push_memcell_values(lua_State *L, const TMemCell *mc); diff --git a/scripting/luaprogram.cpp b/scripting/luaprogram.cpp index 36d95d271..a79018a3d 100644 --- a/scripting/luaprogram.cpp +++ b/scripting/luaprogram.cpp @@ -8,14 +8,19 @@ http://mozilla.org/MPL/2.0/. */ // the Lua screens: scripts run by LuaJIT, each screen in a state of its own, with the eu07 table of -// script_screens_doc.md. the state has no io, os, ffi, debug or require, reads files only through eu07 and below the -// script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction count hook -// can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code) +// script_screens_doc.md. the state has no io, os, ffi, debug, require or newproxy, reads files only through eu07 and +// below the script's folder, takes no precompiled code, and runs without the JIT compiler, so that the instruction +// count hook can stop a script stuck in a loop (LuaJIT calls no hooks in compiled code). what runs in C without the +// hook is held to limits of its own: the pattern functions to the steps they may take, what makes large strings and +// images to the memory of the screen. the game reads the script's table in protected mode, as its metamethods may +// fail #include "stdafx.h" #include "scripting/scriptscreenprogram.h" #include "scripting/scriptscreendrawing.h" #include "scripting/scriptscreenkernels.h" +#include "scripting/scriptscreenrules.h" +#include "scripting/luasandbox.h" #include "utilities/Logs.h" #include "utilities/dictionary.h" @@ -27,11 +32,11 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include -#include -#include #include +#include #include #include #include @@ -43,20 +48,109 @@ namespace { constexpr int hook_interval{1000}; -constexpr char const *image_metatable{"eu07.image"}; -constexpr char const *font_metatable{"eu07.font"}; -constexpr char const *sprite_metatable{"eu07.sprite"}; +// the longest string string.rep makes +constexpr double max_repeat{1024 * 1024}; +// arrays, to be arguments of collect<> +constexpr char image_metatable[]{"eu07.image"}; +constexpr char font_metatable[]{"eu07.font"}; +constexpr char sprite_metatable[]{"eu07.sprite"}; // the address is the key of the program in the registry of its state constexpr char program_key{0}; +// what set_lua_screen_memory_limit() set +std::atomic &memory_limit_setting() +{ + static std::atomic setting{max_screen_memory}; + return setting; +} + +// what lua_screen_memory_peak() gives +std::atomic &memory_peak() +{ + static std::atomic peak{0}; + return peak; +} + +// the memory of a screen: what its Lua heap holds and the pixels of its images, fonts and sprites, which the objects +// keep outside the heap +struct screen_memory +{ + std::size_t limit{max_screen_memory}; // what the screen may hold, read when its state is made + std::size_t heap{0}; + std::size_t objects{0}; + std::size_t peak{0}; // the most the screen held + bool enforced{false}; // a call into the script is in progress: the allocator refuses what goes over the limit + // what the screen holds when it is checked next (lua_program::over_memory) with a full collection + std::size_t collect_at{max_screen_memory}; + // LuaJIT's own allocator of the state, which limited_alloc gives the blocks to + lua_Alloc base{nullptr}; + void *base_data{nullptr}; +}; + +// keeps the most the screen held +void note_peak(screen_memory &Memory) +{ + auto const held{Memory.heap + Memory.objects}; + if (held <= Memory.peak) + { + return; + } + Memory.peak = held; + auto &peak{memory_peak()}; + auto seen{peak.load()}; + while (held > seen && false == peak.compare_exchange_weak(seen, held)) + { + // a failed exchange put the value another screen stored in seen; try again while held is still more + } +} + +// the allocator of a screen's state, put in front of LuaJIT's own (lua_setallocf) once the state is made: LuaJIT 2.0 +// on x64 (the game's on Windows) and 2.1 on x64 without GC64 make no state with an allocator of the game's +// (lua_newstate gives nullptr), as their heap has to stay in the low addresses only their own allocator keeps to. so +// LuaJIT's allocator still makes every block; this one counts them, and refuses a block that would take the screen over +// twice its limit (what it holds, and its garbage between the collections) while a call into the script is in +// progress: LuaJIT raises "not enough memory" there, in the protected call, before the block is made. that holds what +// one instruction makes, which the instruction hook sees only once it is made (a concatenation, a .. b). the game's own +// work between the calls isn't refused, as it isn't protected +void *limited_alloc(void *Data, void *Block, std::size_t Old, std::size_t New) +{ + auto &memory{*static_cast(Data)}; + if (Block == nullptr) + { + Old = 0; + } + if (New > Old && memory.enforced && memory.heap - std::min(Old, memory.heap) + New + memory.objects > 2 * memory.limit) + { + return nullptr; + } + auto *result{memory.base(memory.base_data, Block, Old, New)}; + if (New == 0 || result != nullptr) + { + memory.heap = memory.heap - std::min(Old, memory.heap) + New; + note_peak(memory); + } + return result; +} + class lua_program final : public program { public: - lua_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + lua_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("Lua screen \"{}\"", Script)} + { + } ~lua_program() override { if (m_state != nullptr) { + // the finalizers lua_close runs aren't counted: the budget of the last call may be spent + lua_sethook(m_state, nullptr, 0, 0); + // LuaJIT's own allocator back: lua_close frees the whole heap of its allocator only when the state has it, + // and otherwise leaves the heap's own bookkeeping behind + if (memory.base != nullptr) + { + lua_setallocf(m_state, memory.base, memory.base_data); + } lua_close(m_state); } } @@ -71,7 +165,15 @@ class lua_program final : public program std::string const folder; render_call *call{nullptr}; // the refresh in progress bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + output_limits output; std::int64_t budget{0}; // instructions left to the call in progress + char const *stopped{nullptr}; // why the call in progress is being stopped: the hook raises it at every instruction + screen_memory memory; + + // true when the screen would hold more than its limit with Adding bytes more. checked with a full collection + // once it has made a quarter of the limit since the last one, so a screen near its limit isn't collected over and + // over + bool over_memory(lua_State *L, std::size_t Adding); private: // calls what's on the stack, with the instruction limit. logs a failure @@ -92,6 +194,19 @@ lua_program *program_of(lua_State *L) return self; } +bool lua_program::over_memory(lua_State *L, std::size_t const Adding) +{ + if (memory.heap + memory.objects + Adding <= memory.collect_at) + { + return false; + } + // what is garbage doesn't count + lua_gc(L, LUA_GCCOLLECT, 0); + auto const held{memory.heap + memory.objects}; + memory.collect_at = std::max(memory.limit, held + memory.limit / 4); + return held + Adding > memory.limit; +} + void count_hook(lua_State *L, lua_Debug * /*Debug*/) { auto *self{program_of(L)}; @@ -99,33 +214,71 @@ void count_hook(lua_State *L, lua_Debug * /*Debug*/) { return; } - self->budget -= hook_interval; - if (self->budget < 0) + if (self->stopped == nullptr) { - luaL_error(L, "instruction limit exceeded"); + self->budget -= hook_interval; + if (self->budget < 0) + { + self->stopped = "instruction limit exceeded"; + } + else if (self->over_memory(L, 0)) + { + // what the allocator lets through, up to twice the limit with the garbage, is caught here + self->stopped = "memory limit exceeded"; + } } + if (self->stopped != nullptr) + { + // from now on the hook runs at every instruction, and raises the error again. a script that catches it (pcall, + // xpcall, coroutine.resume) gets it again at its next instruction, so the error comes out of every level of the + // script in turn, and the call ends. run() sets the interval back for the next call. the hook is the state's, + // shared by its coroutines + lua_sethook(L, count_hook, LUA_MASKCOUNT, 1); + luaL_error(L, "%s", self->stopped); + } +} + +// raises a Lua error when the screen can't take Bytes more: called before an object of the api is made +void reserve_memory(lua_State *L, std::size_t const Bytes) +{ + if (auto *self{program_of(L)}; self != nullptr && self->over_memory(L, Bytes)) + { + luaL_error(L, "memory limit exceeded (%d MB)", static_cast(self->memory.limit / (1024 * 1024))); + } +} + +// the memory the screen of the state may hold +std::size_t memory_limit(lua_State *L) +{ + auto const *self{program_of(L)}; + return self != nullptr ? self->memory.limit : max_screen_memory; } // objects of the api ------------------------------------------------------------------------------------------------- +// where the userdata of an object keeps the bytes it counts in the screen's memory, after the object +template constexpr std::size_t charge_offset{(sizeof(Type_) + alignof(std::size_t) - 1) / alignof(std::size_t) * alignof(std::size_t)}; + // puts the object in a new userdata with the metatable, left on the stack: an rvalue is moved in, an lvalue copied. -// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given -template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable) +// what's stored is the plain type (no reference, no const), the one collect<> and check_object<> are given. Bytes: what +// the object holds outside the heap (its pixels), counted in the screen's memory until it is collected, and checked +// with reserve_memory() before the object was made +template std::remove_cvref_t *push_object(lua_State *L, Type_ &&Object, char const *Metatable, std::size_t const Bytes) { using object_type = std::remove_cvref_t; - auto *memory{lua_newuserdata(L, sizeof(object_type))}; + auto *memory{static_cast(lua_newuserdata(L, charge_offset + sizeof(std::size_t)))}; auto *object{new (memory) object_type(std::forward(Object))}; + std::memcpy(memory + charge_offset, &Bytes, sizeof(Bytes)); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects += Bytes; + note_peak(self->memory); + } luaL_getmetatable(L, Metatable); lua_setmetatable(L, -2); return object; } -template int collect(lua_State *L) -{ - static_cast(lua_touserdata(L, 1))->~Type_(); - return 0; -} - // the object at the index when it has the metatable, otherwise nullptr template Type_ *test_object(lua_State *L, int const Index, char const *Metatable) { @@ -140,6 +293,25 @@ template Type_ *test_object(lua_State *L, int const Index, char return matches ? static_cast(object) : nullptr; } +// __gc. the metatables are locked (make_metatable), so only the collector calls it; all the same it destroys only an +// object of its own type, and once: the object loses its metatable, which its methods check for +template int collect(lua_State *L) +{ + if (auto *object{test_object(L, 1, Metatable_)}; object != nullptr) + { + std::size_t bytes{0}; + std::memcpy(&bytes, reinterpret_cast(object) + charge_offset, sizeof(bytes)); + object->~Type_(); + lua_pushnil(L); + lua_setmetatable(L, 1); + if (auto *self{program_of(L)}; self != nullptr) + { + self->memory.objects -= std::min(bytes, self->memory.objects); + } + } + return 0; +} + template Type_ &check_object(lua_State *L, int const Index, char const *Metatable) { auto *object{test_object(L, Index, Metatable)}; @@ -198,6 +370,28 @@ struct lua_image } }; +// the pixels an image holds: as drawn, and as its post-processing leaves it +std::size_t image_bytes(int const Width, int const Height, int const Finalwidth, int const Finalheight) +{ + auto const drawn{static_cast(Width) * static_cast(Height)}; + auto const done{Width == Finalwidth && Height == Finalheight ? 0 : static_cast(Finalwidth) * static_cast(Finalheight)}; + return (drawn + done) * 4; +} + +std::size_t image_bytes(lua_image const &Image) +{ + return image_bytes(Image.drawn.width(), Image.drawn.height(), Image.width(), Image.height()); +} + +// a new image, Image a step further, counted in the screen's memory +void push_image_then(lua_State *L, lua_image const &Image, post_step const &Step) +{ + reserve_memory(L, image_bytes(Image.drawn.width(), Image.drawn.height(), width_after(Step, Image.width()), height_after(Step, Image.height()))); + auto next{Image.then(Step)}; + auto const bytes{image_bytes(next)}; + push_object(L, std::move(next), image_metatable, bytes); +} + lua_image &check_lua_image(lua_State *L, int const Index) { return check_object(L, Index, image_metatable); @@ -262,6 +456,12 @@ std::optional read_png(std::string const &Folder, std::string_vie int width{0}; int height{0}; int channels{0}; + // the size first: a small file may declare an image of gigabytes + if (0 == stbi_info_from_memory(reinterpret_cast(file->data()), static_cast(file->size()), &width, &height, &channels) || + false == valid_image_side(width) || false == valid_image_side(height)) + { + return std::nullopt; + } // the texture loader turns every image bottom row first, for all threads (model/Texture.cpp): fonts and sprites are // read top row first, as led_util reads them stbi_set_flip_vertically_on_load_thread(0); @@ -285,7 +485,9 @@ int api_image(lua_State *L) luaL_argcheck(L, valid_image_side(width), 1, "between 1 and 4096"); luaL_argcheck(L, valid_image_side(height), 2, "between 1 and 4096"); auto const color{lua_isnoneornil(L, 3) ? rgb{0, 0, 0} : check_color(L, 3)}; - push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable); + auto const bytes{image_bytes(width, height, width, height)}; + reserve_memory(L, bytes); + push_object(L, lua_image{canvas{width, height, color}, {}}, image_metatable, bytes); return 1; } @@ -300,9 +502,12 @@ int api_font(lua_State *L) auto const description{read_screen_file(self->folder, std::string{path} + ".txt")}; if (image.has_value() && description.has_value()) { + // the glyphs keep a bit of each pixel; a byte is counted + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); if (auto font{bitmap_font::parse(image->pixels, image->width, image->height, *description)}; font.has_value()) { - push_object(L, std::move(*font), font_metatable); + push_object(L, std::move(*font), font_metatable, bytes); loaded = true; } } @@ -323,7 +528,9 @@ int api_sprite(lua_State *L) { if (auto const image{read_png(self->folder, std::string{path} + ".png")}; image.has_value()) { - push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable); + auto const bytes{static_cast(image->width) * static_cast(image->height)}; + reserve_memory(L, bytes); + push_object(L, bitmap_font::sprite(image->pixels, image->width, image->height), sprite_metatable, bytes); loaded = true; } } @@ -362,9 +569,13 @@ int api_log(lua_State *L) { lua_concat(L, count * 2 - 1); } - auto const *self{program_of(L)}; - auto const *text{lua_tostring(L, -1)}; - WriteLog(std::format("Lua screen \"{}\": {}", self->script, text != nullptr ? text : "")); + auto *self{program_of(L)}; + std::size_t length{0}; + auto const *text{lua_tolstring(L, -1, &length)}; + if (auto const line{self->output.take_log(text != nullptr ? std::string_view{text, length} : std::string_view{})}; line.has_value()) + { + WriteLog(*line); + } return 0; } @@ -388,7 +599,10 @@ int api_command(lua_State *L) } return 0; } - self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + if (self->output.take_command(*self->call, name)) + { + self->call->commands.emplace_back(std::string{name}, param1, param2, self->call->vehicle); + } return 0; } @@ -411,12 +625,7 @@ int api_read_file(lua_State *L) // loads a script as text: precompiled code is refused. leaves the chunk, or an error message, on the stack bool load_chunk(lua_State *L, std::string_view const Code, std::string const &Name) { - if (false == Code.empty() && Code.front() == '\x1b') - { - lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); - return false; - } - return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); + return lua_sandbox::load_text_chunk(L, Code, Name); } // eu07.include(path): runs another script below the script's folder and returns what it returns @@ -566,7 +775,7 @@ int image_led_post(lua_State *L) post_step step; step.type = post_step::kind::led; step.bloom = bloom; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } @@ -582,14 +791,16 @@ int image_resize(lua_State *L) step.type = post_step::kind::resize; step.width = width; step.height = height; - push_object(L, image.then(step), image_metatable); + push_image_then(L, image, step); return 1; } int image_copy(lua_State *L) { auto const &image{check_lua_image(L, 1)}; - push_object(L, lua_image{image}, image_metatable); + auto const bytes{image_bytes(image)}; + reserve_memory(L, bytes); + push_object(L, lua_image{image}, image_metatable, bytes); return 1; } @@ -663,6 +874,227 @@ constexpr std::array api_functions{ luaL_Reg{nullptr, nullptr}, }; +// string.rep, which makes no string longer than max_repeat. a separator (a third argument, where LuaJIT takes one) +// is counted as well +int api_repeat(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto const count{luaL_checknumber(L, 2)}; + std::size_t separator{0}; + luaL_optlstring(L, 3, "", &separator); + // as a double: no overflow for any count, and a count of NaN fails both comparisons + if (false == (count <= 0) && false == (static_cast(length) * count + static_cast(separator) * (count - 1) <= max_repeat)) + { + return luaL_error(L, "string.rep: the result would be over %d bytes", static_cast(max_repeat)); + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, 1); + return 1; +} + +// the functions of the libraries that make a string in one call, around the library's own (the upvalue): refused when +// the result may be over the memory of a screen. what they make otherwise is counted with the rest of the heap +int too_large(lua_State *L, char const *Function) +{ + return luaL_error(L, "%s: the result may be over the memory of a screen (%d MB)", Function, static_cast(memory_limit(L) / (1024 * 1024))); +} + +// calls the library's own function, the upvalue, with the arguments, and returns what it returns +int call_library(lua_State *L) +{ + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +// string.format: no longer than the format and its arguments, each string as %q writes it (a character as up to 4, +// "\0" as "\000"), anything else in at most 512 characters +int api_format(lua_State *L) +{ + std::size_t length{0}; + luaL_checklstring(L, 1, &length); + auto total{static_cast(length)}; + for (int idx = 2; idx <= lua_gettop(L); ++idx) + { + total += lua_type(L, idx) == LUA_TSTRING ? 4.0 * static_cast(lua_objlen(L, idx)) : 512.0; + } + if (total > static_cast(memory_limit(L))) + { + return too_large(L, "string.format"); + } + return call_library(L); +} + +// table.concat: the items and the separators between them. the items are read as the library reads them, up to the +// first one that isn't a string or a number, on which the library raises its error +int api_concat(lua_State *L) +{ + luaL_checktype(L, 1, LUA_TTABLE); + std::size_t separator{0}; + luaL_optlstring(L, 2, "", &separator); + auto const first{luaL_optinteger(L, 3, 1)}; + auto const last{lua_isnoneornil(L, 4) ? static_cast(lua_objlen(L, 1)) : luaL_checkinteger(L, 4)}; + auto const limit{static_cast(memory_limit(L))}; + auto total{0.0}; + for (auto idx = first; idx <= last; ++idx) + { + lua_rawgeti(L, 1, static_cast(idx)); + auto const type{lua_type(L, -1)}; + // a number in at most 32 characters + total += (type == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0) + (idx > first ? static_cast(separator) : 0.0); + lua_pop(L, 1); + if (type != LUA_TSTRING && type != LUA_TNUMBER) + { + break; + } + if (total > limit) + { + return too_large(L, "table.concat"); + } + } + return call_library(L); +} + +// the pattern functions, upvalue 2 telling which +enum class pattern_function +{ + find, + match, + gmatch, + gsub +}; + +constexpr std::array pattern_function_names{"string.find", "string.match", "string.gmatch", "string.gsub"}; + +// the longest text a replacement of gsub puts in place of the matches: a string (or a number) as it is, with each %0-%9 +// as long as a match, a table by its longest value. nothing when it can't be told (a function, a table with a +// metatable): what those give is made in Lua, under the hook +std::optional replacement_length(lua_State *L, int const Index, double const Subject, double const Matches) +{ + if (lua_type(L, Index) == LUA_TSTRING || lua_type(L, Index) == LUA_TNUMBER) + { + std::size_t length{0}; + auto const *text{lua_tolstring(L, Index, &length)}; + auto const captures{static_cast(std::count(text, text + length, '%'))}; + // the matches don't overlap: a capture of each takes at most the subject; a position capture is a number + return Matches * static_cast(length) + captures * (Subject + 24.0 * Matches); + } + if (lua_type(L, Index) == LUA_TTABLE) + { + if (lua_getmetatable(L, Index) != 0) + { + // pushed: off the stack again, or the library gets it as the 4th argument + lua_pop(L, 1); + return std::nullopt; + } + auto longest{0.0}; + lua_pushnil(L); + while (lua_next(L, Index) != 0) + { + longest = std::max(longest, lua_type(L, -1) == LUA_TSTRING ? static_cast(lua_objlen(L, -1)) : 32.0); + lua_pop(L, 1); + } + return Matches * longest; + } + return std::nullopt; +} + +// string.find, match, gmatch and gsub, refused for a pattern that may take too long on the subject: they run in C, +// without the instruction hook (see lua_pattern_cost() and max_pattern_cost). gsub with a string or a table is refused +// as well when its result may be over the memory of a screen +int api_pattern(lua_State *L) +{ + auto const function{static_cast(lua_tointeger(L, lua_upvalueindex(2)))}; + auto const *name{pattern_function_names[static_cast(function)]}; + std::size_t subject{0}; + auto const *text{luaL_checklstring(L, 1, &subject)}; + std::size_t length{0}; + auto const *pattern{luaL_checklstring(L, 2, &length)}; + auto const plain{function == pattern_function::find && lua_toboolean(L, 4) != 0}; + if (lua_pattern_cost(std::string_view{pattern, length}, std::string_view{text, subject}, plain, function != pattern_function::gmatch) > max_pattern_cost) + { + return luaL_error(L, "%s: the pattern may take too long on a subject of %d bytes", name, static_cast(subject)); + } + if (function == pattern_function::gsub) + { + auto const size{static_cast(subject)}; + auto const matches{lua_isnumber(L, 4) ? std::clamp(static_cast(lua_tonumber(L, 4)), 0.0, size + 1.0) : size + 1.0}; + if (auto const replaced{replacement_length(L, 3, size, matches)}; replaced.has_value() && size + *replaced > static_cast(memory_limit(L))) + { + return too_large(L, name); + } + } + return call_library(L); +} + +// xpcall(f, handler, ...), in Lua on top of pcall: LuaJIT calls the handler of its own xpcall where the error was +// raised, before the stack unwinds, which for the error of the instruction hook is while the hook still runs, when no +// hook is called, so a handler that loops would never be stopped. here the handler is called once the error has left +// f, under pcall as well, and a script has no debug library to look at the stack with. made in Lua, a coroutine yields +// across it as across pcall +constexpr std::string_view xpcall_source{R"lua( +local pcall, select, error = pcall, select, error +local function finish(handler, ok, ...) + if ok then + return true, ... + end + local _, handled = pcall(handler, (...)) + return false, handled +end +return function(...) + if select("#", ...) < 2 then + error("bad argument #2 to 'xpcall' (value expected)", 2) + end + local f, handler = ... + return finish(handler, pcall(f, select(3, ...))) +end +)lua"}; + +// what the screens get of the libraries in place of the library's own functions, which run in C without the hook: +// string.rep, string.format and table.concat with a cap on the length of the result, the pattern functions with a cap +// on the steps they take, and xpcall made of pcall. strings share the string table as their methods +void limit_libraries(lua_State *L) +{ + lua_getglobal(L, LUA_STRLIBNAME); + lua_getfield(L, -1, "rep"); + lua_pushcclosure(L, api_repeat, 1); + lua_setfield(L, -2, "rep"); + lua_getfield(L, -1, "format"); + lua_pushcclosure(L, api_format, 1); + lua_setfield(L, -2, "format"); + for (std::size_t idx = 0; idx < pattern_function_names.size(); ++idx) + { + // "string.find": the name in the table is past the dot + auto const *name{pattern_function_names[idx] + sizeof("string.") - 1}; + lua_getfield(L, -1, name); + lua_pushinteger(L, static_cast(idx)); + lua_pushcclosure(L, api_pattern, 2); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); + + lua_getglobal(L, LUA_TABLIBNAME); + lua_getfield(L, -1, "concat"); + lua_pushcclosure(L, api_concat, 1); + lua_setfield(L, -2, "concat"); + lua_pop(L, 1); + + if (0 == luaL_loadbuffer(L, xpcall_source.data(), xpcall_source.size(), "=xpcall") && 0 == lua_pcall(L, 0, 1, 0)) + { + lua_setglobal(L, "xpcall"); + } + else + { + // a script then gets no xpcall rather than the one the hook doesn't reach + lua_pop(L, 1); + lua_pushnil(L); + lua_setglobal(L, "xpcall"); + } +} + template void make_metatable(lua_State *L, char const *Name, std::array const &Methods, lua_CFunction Collect) { luaL_newmetatable(L, Name); @@ -679,6 +1111,9 @@ template void make_metatable(lua_State *L, char const *Name, lua_setfield(L, -2, "__index"); lua_pushcfunction(L, Collect); lua_setfield(L, -2, "__gc"); + // getmetatable() of an object gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); lua_pop(L, 1); } @@ -724,30 +1159,12 @@ void push_state(lua_State *L, dictionary_source const &Input) } } -void open_library(lua_State *L, lua_CFunction Open, char const *Name) -{ - lua_pushcfunction(L, Open); - lua_pushstring(L, Name); - lua_call(L, 1, 0); -} - void lua_program::open_libraries() { - open_library(m_state, luaopen_base, ""); - open_library(m_state, luaopen_table, LUA_TABLIBNAME); - open_library(m_state, luaopen_string, LUA_STRLIBNAME); - open_library(m_state, luaopen_math, LUA_MATHLIBNAME); - open_library(m_state, luaopen_bit, LUA_BITLIBNAME); - // what reaches files or loads code - for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require"}) - { - lua_pushnil(m_state); - lua_setglobal(m_state, name); - } - lua_getglobal(m_state, LUA_STRLIBNAME); - lua_pushnil(m_state); - lua_setfield(m_state, -2, "dump"); - lua_pop(m_state, 1); + // base, table, string, math and bit, without what reaches files or loads code + lua_sandbox::open_safe_libraries(m_state); + // what runs in C without the hook is held to limits of its own + limit_libraries(m_state); } void lua_program::register_api() @@ -757,9 +1174,9 @@ void lua_program::register_api() lua_pushlightuserdata(L, this); lua_rawset(L, LUA_REGISTRYINDEX); - make_metatable(L, image_metatable, image_methods, collect); - make_metatable(L, font_metatable, font_methods, collect); - make_metatable(L, sprite_metatable, sprite_methods, collect); + make_metatable(L, image_metatable, image_methods, collect); + make_metatable(L, font_metatable, font_methods, collect); + make_metatable(L, sprite_metatable, sprite_methods, collect); lua_newtable(L); for (auto const &function : api_functions) @@ -780,16 +1197,48 @@ void lua_program::register_api() bool lua_program::run(int const Arguments, int const Results, std::string_view const What) { budget = instruction_limit; - if (0 == lua_pcall(m_state, Arguments, Results, 0)) + stopped = nullptr; + // the interval, which the hook shortens once the budget of a call is spent + lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); + output.start_call(); + memory.enforced = true; + auto const status{lua_pcall(m_state, Arguments, Results, 0)}; + memory.enforced = false; + if (0 == status) { return true; } auto const *message{lua_tostring(m_state, -1)}; ErrorLog(std::format("Lua screen \"{}\": {} failed: {}", script, What, message != nullptr ? message : "unknown error")); lua_pop(m_state, 1); + // what the call left behind, a heap run over the limit + lua_gc(m_state, LUA_GCCOLLECT, 0); return false; } +// render and init of the table the script returned (the argument), read in protected mode: the table may have a +// metatable of the script's, whose __index runs the script and may fail +int screen_functions(lua_State *L) +{ + lua_getfield(L, 1, "render"); + lua_getfield(L, 1, "init"); + return 2; +} + +// a refresh: render of the screen's table (its reference, the second argument) called with the state of the refresh +// (the dictionary_source, the first). in protected mode, the reading of render and the making of the state as well +int call_render(lua_State *L) +{ + auto const &input{*static_cast(lua_touserdata(L, 1))}; + auto const screen{static_cast(lua_tointeger(L, 2))}; + lua_settop(L, 0); + lua_rawgeti(L, LUA_REGISTRYINDEX, screen); + lua_getfield(L, 1, "render"); + push_state(L, input); + lua_call(L, 1, 1); + return 1; +} + bool lua_program::start() { m_state = luaL_newstate(); @@ -798,20 +1247,25 @@ bool lua_program::start() ErrorLog(std::format("Lua screen \"{}\": failed to create the state", script)); return false; } + // the screen's allocator in front of LuaJIT's own, counting from what the state holds already + memory.limit = memory_limit_setting().load(); + memory.collect_at = memory.limit; + memory.heap = static_cast(lua_gc(m_state, LUA_GCCOUNT, 0)) * 1024 + static_cast(lua_gc(m_state, LUA_GCCOUNTB, 0)); + memory.base = lua_getallocf(m_state, &memory.base_data); + lua_setallocf(m_state, limited_alloc, &memory); // no compiled code: LuaJIT calls no hooks in it, and the hook is what stops a script stuck in a loop luaJIT_setmode(m_state, 0, LUAJIT_MODE_ENGINE | LUAJIT_MODE_OFF); open_libraries(); register_api(); lua_sethook(m_state, count_hook, LUA_MASKCOUNT, hook_interval); - std::ifstream file{script, std::ios::binary}; - if (false == file.is_open()) + auto const code{read_regular_file(script)}; + if (false == code.has_value()) { - ErrorLog(std::format("Lua screen \"{}\": file not found", script)); + ErrorLog(std::format("Lua screen \"{}\": file not found, or larger than {} bytes", script, max_screen_file)); return false; } - std::string const code{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; - if (false == load_chunk(m_state, code, script)) + if (false == load_chunk(m_state, *code, script)) { ErrorLog(std::format("Lua screen \"{}\": {}", script, lua_tostring(m_state, -1))); return false; @@ -825,19 +1279,22 @@ bool lua_program::start() ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - lua_getfield(m_state, -1, "render"); - auto const renders{lua_isfunction(m_state, -1)}; - lua_pop(m_state, 1); - if (false == renders) + lua_pushcfunction(m_state, screen_functions); + lua_pushvalue(m_state, -2); + if (false == run(1, 2, "reading render and init")) + { + return false; + } + // the table, render, init + if (false == lua_isfunction(m_state, -2)) { ErrorLog(std::format("Lua screen \"{}\": the script has to return a table with a render function", script)); return false; } - m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); - - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "init"); lua_remove(m_state, -2); + lua_insert(m_state, -2); + // init, the table + m_screen = luaL_ref(m_state, LUA_REGISTRYINDEX); if (lua_isfunction(m_state, -1)) { if (false == run(0, 0, "init")) @@ -856,11 +1313,10 @@ bool lua_program::start() bool lua_program::render(render_call &Call) { call = &Call; - lua_rawgeti(m_state, LUA_REGISTRYINDEX, m_screen); - lua_getfield(m_state, -1, "render"); - lua_remove(m_state, -2); - push_state(m_state, Call.input); - auto const rendered{run(1, 1, "render")}; + lua_pushcfunction(m_state, call_render); + lua_pushlightuserdata(m_state, const_cast(&Call.input)); + lua_pushinteger(m_state, m_screen); + auto const rendered{run(2, 1, "render")}; call = nullptr; if (false == rendered) { @@ -902,6 +1358,17 @@ class lua_runtime_host final : public runtime } // namespace +void set_lua_screen_memory_limit(std::size_t const Bytes) +{ + memory_limit_setting().store(Bytes); + memory_peak().store(0); +} + +std::size_t lua_screen_memory_peak() +{ + return memory_peak().load(); +} + std::unique_ptr make_lua_runtime() { return std::make_unique(); diff --git a/scripting/luasandbox.cpp b/scripting/luasandbox.cpp new file mode 100644 index 000000000..16e7f70ba --- /dev/null +++ b/scripting/luasandbox.cpp @@ -0,0 +1,522 @@ +/* +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 "scripting/luasandbox.h" + +#include "scripting/scriptscreenrules.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace lua_sandbox +{ + +namespace +{ + +void open_library(lua_State *L, lua_CFunction Open, char const *Name) +{ + lua_pushcfunction(L, Open); + lua_pushstring(L, Name); + lua_call(L, 1, 0); +} + +// the conversions of strftime in C89, which every C library knows. LuaJIT hands each one to strftime on its own +constexpr std::string_view date_conversions{"aAbBcdHIjmMpSUwWxXyYZ%"}; + +// os.date(format, time), the library's own (the upvalue) for a format of known conversions only: the Microsoft +// C library ends the program on one it doesn't know ("%Q", "%#") +int api_date(lua_State *L) +{ + std::size_t length{0}; + auto const *format{luaL_optlstring(L, 1, "%c", &length)}; + std::string_view const text{format, length}; + for (std::size_t idx = 0; idx + 1 < text.size(); ++idx) + { + if (text[idx] != '%') + { + continue; + } + ++idx; + if (date_conversions.find(text[idx]) == std::string_view::npos) + { + return luaL_error(L, "os.date: unknown conversion '%%%c'", text[idx]); + } + } + lua_pushvalue(L, lua_upvalueindex(1)); + lua_insert(L, 1); + lua_call(L, lua_gettop(L) - 1, LUA_MULTRET); + return lua_gettop(L); +} + +} // namespace + +std::string with_forward_slashes(std::string_view const Path) +{ + std::string result{Path}; + std::ranges::replace(result, '\\', '/'); + return result; +} + +void open_safe_libraries(lua_State *L) +{ + open_library(L, luaopen_base, ""); + open_library(L, luaopen_table, LUA_TABLIBNAME); + open_library(L, luaopen_string, LUA_STRLIBNAME); + open_library(L, luaopen_math, LUA_MATHLIBNAME); + open_library(L, luaopen_bit, LUA_BITLIBNAME); + // what reaches files or loads code, and newproxy: a userdata of a metatable of the script's own, whose __gc LuaJIT + // runs without the hooks (the instruction limit of the Lua screens), at any allocation and in lua_close + for (auto const *name : {"dofile", "loadfile", "load", "loadstring", "module", "require", "newproxy"}) + { + lua_pushnil(L); + lua_setglobal(L, name); + } + lua_getglobal(L, LUA_STRLIBNAME); + lua_pushnil(L); + lua_setfield(L, -2, "dump"); + lua_pop(L, 1); +} + +void open_clock_library(lua_State *L) +{ + // the whole library, of which a new table takes what only reads the clock + open_library(L, luaopen_os, LUA_OSLIBNAME); + lua_getglobal(L, LUA_OSLIBNAME); + lua_newtable(L); + for (auto const *name : {"time", "clock", "difftime"}) + { + lua_getfield(L, -2, name); + lua_setfield(L, -2, name); + } + lua_getfield(L, -2, "date"); + lua_pushcclosure(L, api_date, 1); + lua_setfield(L, -2, "date"); + // the new table in place of the library: the global, and the one the libraries know as loaded, which + // luaL_openlibs fills up again rather than make a new global + lua_pushvalue(L, -1); + lua_setglobal(L, LUA_OSLIBNAME); + lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED"); + lua_pushvalue(L, -2); + lua_setfield(L, -2, LUA_OSLIBNAME); + // _LOADED, the new table, the library + lua_pop(L, 3); +} + +bool load_text_chunk(lua_State *L, std::string_view const Code, std::string const &Name) +{ + if (false == Code.empty() && Code.front() == '\x1b') + { + lua_pushfstring(L, "%s: precompiled scripts aren't loaded", Name.c_str()); + return false; + } + return 0 == luaL_loadbufferx(L, Code.data(), Code.size(), ("@" + Name).c_str(), "t"); +} + +std::optional read_file(std::filesystem::path const &Folder, std::string_view const Path, std::uintmax_t const Limit) +{ + // a NUL would end the name the system sees + if (false == script_screens::is_safe_relative_path(Path) || Path.find('\0') != std::string_view::npos) + { + return std::nullopt; + } + // a folder or a device (CON, NUL, COM1...) isn't a regular file. in the code page of the system, as the game opens + // its files + auto const path{Folder / with_forward_slashes(Path)}; + std::error_code error; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > Limit) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; + if (false == file.is_open()) + { + return std::nullopt; + } + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +std::optional read_script_file(std::string const &Folder, std::string_view const Path) +{ + return read_file(std::filesystem::path{Folder}, Path, max_script_file); +} + +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view const Path) +{ + auto const name{Folder + std::string{Path}}; + auto const code{read_script_file(Folder, Path)}; + if (false == code.has_value()) + { + return name + ": not found, not a file, larger than " + std::to_string(max_script_file) + + " bytes, or outside the folder (an absolute path, a drive or '..')"; + } + if (false == load_text_chunk(L, *code, name) || 0 != lua_pcall(L, 0, 0, 0)) + { + std::size_t length{0}; + auto const *message{lua_tolstring(L, -1, &length)}; + std::string result{message != nullptr ? std::string{message, length} : name + ": unknown error"}; + lua_pop(L, 1); + return result; + } + return std::nullopt; +} + +namespace +{ + +char lower_case(char const Character) +{ + return Character >= 'A' && Character <= 'Z' ? static_cast(Character - 'A' + 'a') : Character; +} + +// the names Windows opens as its devices, whatever the extension +bool is_device_name(std::string_view Name) +{ + // the extension, and the spaces before it, don't count ("nul.txt", "con .log") + Name = Name.substr(0, Name.find('.')); + while (false == Name.empty() && Name.back() == ' ') + { + Name.remove_suffix(1); + } + std::string name; + std::ranges::transform(Name, std::back_inserter(name), lower_case); + if (name == "con" || name == "prn" || name == "aux" || name == "nul" || name == "conin$" || name == "conout$") + { + return true; + } + return name.size() == 4 && (name.starts_with("com") || name.starts_with("lpt")) && name[3] >= '0' && name[3] <= '9'; +} + +// a name of a file or a folder that every system takes as it is +bool is_portable_name(std::string_view const Name) +{ + if (Name.empty() || Name == "." || Name == ".." || Name.back() == '.' || Name.back() == ' ') + { + return false; + } + for (auto const character : Name) + { + if (static_cast(character) < 0x20 || character == 0x7f || + std::string_view{"<>:\"|?*"}.find(character) != std::string_view::npos) + { + return false; + } + } + return false == is_device_name(Name); +} + +// true when Path, a canonical path, is Folder, a canonical path, or inside it +bool is_inside(std::filesystem::path const &Path, std::filesystem::path const &Folder) +{ + return std::mismatch(Folder.begin(), Folder.end(), Path.begin(), Path.end()).first == Folder.end(); +} + +file_folders const &folders_of(lua_State *L) +{ + return *static_cast(lua_touserdata(L, lua_upvalueindex(1))); +} + +std::string_view check_text(lua_State *L, int const Index) +{ + std::size_t length{0}; + auto const *text{luaL_checklstring(L, Index, &length)}; + return {text, length}; +} + +void push_contents(lua_State *L, std::optional const &Contents) +{ + if (Contents.has_value()) + { + lua_pushlstring(L, Contents->data(), Contents->size()); + } + else + { + lua_pushnil(L); + } +} + +// eu07.read_file(path): the contents of a file of the scenery folder, or nil +int api_read_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.scenery.empty() ? std::nullopt : read_file(folders.scenery, path, max_script_file)); + return 1; +} + +// eu07.read_data_file(path): the contents of a file of the scenery's data folder, or nil +int api_read_data_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const &folders{folders_of(L)}; + push_contents(L, folders.data.empty() ? std::nullopt : read_file(folders.data, path, max_data_file)); + return 1; +} + +// eu07.write_file(path, text): writes the file of the scenery's data folder. true, or nil and why not +int api_write_file(lua_State *L) +{ + auto const path{check_text(L, 1)}; + auto const contents{check_text(L, 2)}; + if (auto const error{write_data_file(folders_of(L).data, path, contents)}; error.has_value()) + { + lua_pushnil(L); + lua_pushlstring(L, error->data(), error->size()); + return 2; + } + lua_pushboolean(L, 1); + return 1; +} + +} // namespace + +bool is_safe_write_path(std::string_view const Path) +{ + if (Path.size() > max_data_path || false == script_screens::is_safe_relative_path(Path)) + { + return false; + } + std::size_t names{0}; + std::size_t start{0}; + while (start <= Path.size()) + { + auto const end{std::min(Path.find_first_of("/\\", start), Path.size())}; + if (false == is_portable_name(Path.substr(start, end - start))) + { + return false; + } + ++names; + start = end + 1; + } + // the folders, and the file in them + return names <= max_data_depth + 1; +} + +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view const Path, std::string_view const Contents) +{ + namespace fs = std::filesystem; + std::string const name{Path}; + if (Folder.empty()) + { + return name + ": no folder to write to (the game knows no folder of the player)"; + } + if (false == is_safe_write_path(Path)) + { + return name + ": not a path to write to (a relative path of portable names, at most " + std::to_string(max_data_path) + + " bytes and " + std::to_string(max_data_depth) + " folders deep, without '..')"; + } + if (Contents.size() > max_data_file) + { + return name + ": larger than " + std::to_string(max_data_file) + " bytes"; + } + auto const target{Folder / with_forward_slashes(Path)}; + std::error_code error; + // a link, a folder or anything else that isn't a file stays as it is + auto const status{fs::symlink_status(target, error)}; + auto const exists{status.type() != fs::file_type::not_found}; + if (exists && status.type() != fs::file_type::regular) + { + return name + ": not a file"; + } + std::uintmax_t replaced{0}; + if (exists) + { + replaced = fs::file_size(target, error); + if (error) + { + return name + ": can't be replaced"; + } + } + // what the folder holds, and will hold with the file in place of what was there + std::uintmax_t held{0}; + std::size_t files{0}; + if (fs::is_directory(Folder, error)) + { + for (fs::recursive_directory_iterator entry{Folder, error}, end; !error && entry != end; entry.increment(error)) + { + std::error_code entryerror; + if (entry->symlink_status(entryerror).type() == fs::file_type::regular) + { + auto const size{entry->file_size(entryerror)}; + held += entryerror ? 0 : size; + ++files; + } + } + if (error) + { + return name + ": the data folder can't be read"; + } + } + if (files + (exists ? 0 : 1) > max_data_files) + { + return name + ": the data folder holds " + std::to_string(max_data_files) + " files already"; + } + if (held - std::min(replaced, held) + Contents.size() > max_data_folder) + { + return name + ": the data folder would hold more than " + std::to_string(max_data_folder) + " bytes"; + } + fs::create_directories(target.parent_path(), error); + if (error) + { + return name + ": its folder can't be made"; + } + // still inside the data folder, should a link in it lead elsewhere + auto const root{fs::canonical(Folder, error)}; + auto const parent{error ? fs::path{} : fs::canonical(target.parent_path(), error)}; + if (error || false == is_inside(parent, root)) + { + return name + ": outside the data folder"; + } + std::ofstream file{parent / target.filename(), std::ios::binary | std::ios::trunc}; + if (false == file.is_open()) + { + return name + ": can't be opened to write"; + } + file.write(Contents.data(), static_cast(Contents.size())); + file.close(); + if (file.fail()) + { + return name + ": couldn't be written whole"; + } + return std::nullopt; +} + +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view const Scenery) +{ + auto name{with_forward_slashes(Scenery)}; + if (name.size() >= 4) + { + std::string extension; + std::ranges::transform(std::string_view{name}.substr(name.size() - 4), std::back_inserter(extension), lower_case); + if (extension == ".scn") + { + name.resize(name.size() - 4); + } + } + if (Root.empty() || false == is_safe_write_path(name)) + { + return {}; + } + return Root / name; +} + +void open_file_library(lua_State *L, file_folders const *Folders) +{ + // eu07, which the scenery scripts have for eu07.events, made when there is none + lua_getglobal(L, "eu07"); + if (false == lua_istable(L, -1)) + { + lua_pop(L, 1); + lua_newtable(L); + lua_pushvalue(L, -1); + lua_setglobal(L, "eu07"); + } + // luaL_Reg, not std::pair: GCC deduces std::pair{"read_file", api_read_file} as a pair of an array and a function + static constexpr luaL_Reg functions[]{{"read_file", api_read_file}, {"write_file", api_write_file}, {"read_data_file", api_read_data_file}}; + for (auto const &[name, function] : functions) + { + lua_pushlightuserdata(L, const_cast(Folders)); + lua_pushcclosure(L, function, 1); + lua_setfield(L, -2, name); + } + lua_pop(L, 1); +} + +namespace +{ + +constexpr std::array handle_names{"eu07.event", "eu07.track", "eu07.isolated", "eu07.vehicle", "eu07.memcell"}; +// the addresses are the keys of the handles of each kind in the registry: the objects, to their userdata +constexpr std::array handle_cache_keys{}; + +void *cache_key(handle_kind const Kind) +{ + return const_cast(&handle_cache_keys[static_cast(Kind)]); // NOSONAR: the address is only a key +} + +} // namespace + +char const *handle_name(handle_kind const Kind) +{ + return handle_names[static_cast(Kind)]; +} + +void open_handles(lua_State *L) +{ + for (std::size_t idx = 0; idx < handle_names.size(); ++idx) + { + auto const kind{static_cast(idx)}; + luaL_newmetatable(L, handle_name(kind)); + // getmetatable() of a handle gives this instead of the table + lua_pushboolean(L, 0); + lua_setfield(L, -2, "__metatable"); + lua_pop(L, 1); + // the handles made, weak: a handle the script dropped is collected, and made again when asked for + lua_pushlightuserdata(L, cache_key(kind)); + lua_newtable(L); + lua_createtable(L, 0, 1); + lua_pushliteral(L, "v"); + lua_setfield(L, -2, "__mode"); + lua_setmetatable(L, -2); + lua_rawset(L, LUA_REGISTRYINDEX); + } +} + +void push_handle(lua_State *L, handle_kind const Kind, void *Object) +{ + if (Object == nullptr) + { + lua_pushnil(L); + return; + } + lua_pushlightuserdata(L, cache_key(Kind)); + lua_rawget(L, LUA_REGISTRYINDEX); + lua_pushlightuserdata(L, Object); + lua_rawget(L, -2); + if (false == lua_isnil(L, -1)) + { + // the cache, the handle + lua_remove(L, -2); + return; + } + lua_pop(L, 1); + *static_cast(lua_newuserdata(L, sizeof(void *))) = Object; + luaL_getmetatable(L, handle_name(Kind)); + lua_setmetatable(L, -2); + lua_pushlightuserdata(L, Object); + lua_pushvalue(L, -2); + lua_rawset(L, -4); + lua_remove(L, -2); +} + +void *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + if (lua_isnoneornil(L, Index)) + { + return nullptr; + } + return *static_cast(luaL_checkudata(L, Index, handle_name(Kind))); +} + +} // namespace lua_sandbox diff --git a/scripting/luasandbox.h b/scripting/luasandbox.h new file mode 100644 index 000000000..dfb1cd024 --- /dev/null +++ b/scripting/luasandbox.h @@ -0,0 +1,134 @@ +/* +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 + +// what the Lua states of the game share to run scripts sandboxed: the scenery scripts (scripting/lua.cpp, lua in the +// .scn) and the script screens (scripting/luaprogram.cpp). a sandboxed script reaches no files, no other programs, no +// ffi and no debug library, and loads no code of its own: no require, dofile, load or precompiled chunks + +#include + +#include +#include +#include +#include +#include +#include + +namespace lua_sandbox +{ + +// the largest script file a scenery loads +constexpr std::uintmax_t max_script_file{16 * 1024 * 1024}; + +// the libraries a sandboxed script gets: base, table, string, math and bit, without dofile, loadfile, load, +// loadstring, module, require and string.dump +void open_safe_libraries(lua_State *L); + +// the os table with only what reads the clock: os.time, os.clock, os.difftime and os.date, the last refusing the +// conversions the C library doesn't know (the Microsoft one ends the program on them) +void open_clock_library(lua_State *L); + +// loads Code as text, under the name Name: precompiled code is refused. leaves the chunk, or an error message, on the +// stack +bool load_text_chunk(lua_State *L, std::string_view Code, std::string const &Name); + +// Path with each '\' turned into '/', as the game reads the paths in its data (replace_slashes): a scenery made on +// Windows may name its folders either way, and on Linux only '/' separates them +std::string with_forward_slashes(std::string_view Path); + +// the file Path of Folder, when Path is a relative path inside Folder (no '..', no drive, no leading separator) and +// names a regular file of at most max_script_file bytes. nothing otherwise. '\' separates folders in Path as '/' does, +// on every system +std::optional read_script_file(std::string const &Folder, std::string_view Path); + +// reads the script Path of Folder (as read_script_file), loads it as text and runs it in protected mode. nothing when +// it ran, otherwise why it didn't +std::optional run_script_file(lua_State *L, std::string const &Folder, std::string_view Path); + +// the files a scenery script reads and writes itself (eu07.read_file, eu07.write_file, eu07.read_data_file): it reads +// the files of the scenery folder, and writes only into a data folder of its scenery, outside the game + +// the largest file a script writes, all the files of a data folder together, and how many files a data folder holds +constexpr std::uintmax_t max_data_file{1024 * 1024}; +constexpr std::uintmax_t max_data_folder{16 * 1024 * 1024}; +constexpr std::size_t max_data_files{256}; +// the longest path a script writes to, and how many folders deep it goes +constexpr std::size_t max_data_path{200}; +constexpr std::size_t max_data_depth{8}; + +// the file Path of Folder, when Path is a relative path inside Folder (as read_script_file) and names a regular file of +// at most Limit bytes. nothing otherwise +std::optional read_file(std::filesystem::path const &Folder, std::string_view Path, std::uintmax_t Limit); + +// true for a path a script may write to: a relative path inside the folder (is_safe_relative_path), '/' or '\' between +// the folders, at most max_data_path bytes and max_data_depth folders deep, each name portable: not empty, not '.' or +// '..', none of the characters Windows refuses (: < > " | ? * and the control characters), no '.' or ' ' at the end, +// and not a device of Windows (con, prn, aux, nul, com0-9, lpt0-9, conin$, conout$, with an extension or without) +bool is_safe_write_path(std::string_view Path); + +// writes Contents to the file Path of Folder (a data folder), replacing what was there, and makes Folder and the folders +// of Path. refused for a path that isn't safe (is_safe_write_path), for more than max_data_file bytes, when Folder would +// hold more than max_data_files files or max_data_folder bytes, when Path names something else than a file, and when it +// leads out of Folder through a link. nothing when written, otherwise why not +std::optional write_data_file(std::filesystem::path const &Folder, std::string_view Path, std::string_view Contents); + +// the data folder of the scenery Scenery (its .scn file, relative to the scenery folder) in Root: Root and the file +// without ".scn" (td.scn: Root/td). empty when Root is, or the name isn't a safe path (is_safe_write_path) +std::filesystem::path scenery_data_folder(std::filesystem::path const &Root, std::string_view Scenery); + +// where the file functions of a scenery script read and write +struct file_folders +{ + // the scenery folder, which eu07.read_file reads, ending with a separator. empty: nothing is read + std::string scenery; + // the data folder of the scenery, which eu07.write_file writes and eu07.read_data_file reads. empty: nothing is + // written there or read from it + std::filesystem::path data; +}; + +// adds eu07.read_file(path), eu07.write_file(path, text) and eu07.read_data_file(path) to the state, on the folders of +// Folders, read on every call: Folders is to outlive the state +void open_file_library(lua_State *L, file_folders const *Folders); + +// the objects of the simulation a scenery script holds (eu07.events): each kind is a userdata of a metatable of its +// own, so a function given the handle of another kind, a light userdata or anything else raises a Lua error, and never +// takes one object for another. the objects outlive the state (the scenery's events, tracks, memcells and isolated +// track circuits, and its vehicles, which the game takes off the tracks but doesn't delete) +enum class handle_kind +{ + event, + track, + isolated, + vehicle, + memcell +}; + +// the name of the metatable of the kind, as the errors give it ("eu07.memcell expected, got userdata") +char const *handle_name(handle_kind Kind); + +// makes the metatables of the handles; once, before the first handle. a script can't reach them (getmetatable gives +// false) +void open_handles(lua_State *L); + +// pushes the handle of Object, of the kind, or nil for nullptr. one object has one handle while the script holds it: +// the handles of an object found twice are equal, and the same key of a table +void push_handle(lua_State *L, handle_kind Kind, void *Object); + +// the object of the handle at Index: nullptr for nil or nothing (what the find functions give for a missing object), +// a Lua error (bad argument) for anything else than a handle of the kind +void *check_handle(lua_State *L, int Index, handle_kind Kind); + +template Type_ *check_handle(lua_State *L, int const Index, handle_kind const Kind) +{ + return static_cast(check_handle(L, Index, Kind)); +} + +} // namespace lua_sandbox diff --git a/scripting/scriptscreendrawing.cpp b/scripting/scriptscreendrawing.cpp index f738d9292..870b5b8a3 100644 --- a/scripting/scriptscreendrawing.cpp +++ b/scripting/scriptscreendrawing.cpp @@ -64,13 +64,11 @@ bool lit_pixel(std::span const Rgba, int const Width, int co glyph cut_glyph(std::span const Rgba, int const Width, int const Height, int const First, int const Count) { std::vector lit(static_cast(Count) * Height, false); - for (auto column = 0; column < Count; ++column) + // only the columns inside the image are read + auto const last{static_cast(std::min(static_cast(First) + Count, Width))}; + for (auto x = std::max(First, 0); x < last; ++x) { - auto const x{First + column}; - if (x < 0 || x >= Width) - { - continue; - } + auto const column{x - First}; for (auto y = 0; y < Height; ++y) { lit[static_cast(column) * Height + y] = lit_pixel(Rgba, Width, x, y); @@ -128,14 +126,15 @@ std::u32string decode_utf8(std::string_view const Text) std::optional bitmap_font::parse(std::span const Rgba, int const Width, int const Height, std::string_view const Description) { - if (Width <= 0 || Height <= 0 || Rgba.size() < static_cast(Width) * Height * 4) + if (Width <= 0 || Height <= 0 || Width > max_font_image_side || Height > max_font_image_side || Rgba.size() < static_cast(Width) * Height * 4) { return std::nullopt; } bitmap_font font; font.m_height = Height; auto const all{lines(Description)}; - auto x{0}; + auto x{0}; // where the glyph starts: at most max_font_columns + auto glyphs{0}; // the first line is a comment for (std::size_t line = 1; line < all.size(); ++line) { @@ -157,10 +156,14 @@ std::optional bitmap_font::parse(std::span cons digits.remove_suffix(1); } auto width{0}; - if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0) + if (std::from_chars(digits.data(), digits.data() + digits.size(), width).ec != std::errc{} || width < 0 || width > max_font_image_side) { continue; } + if (++glyphs > max_font_glyphs || x + width > max_font_columns) + { + return std::nullopt; + } auto cut{cut_glyph(Rgba, Width, Height, x, width)}; if (font.m_glyphs.empty()) { diff --git a/scripting/scriptscreendrawing.h b/scripting/scriptscreendrawing.h index 215f2bf73..5b8166efa 100644 --- a/scripting/scriptscreendrawing.h +++ b/scripting/scriptscreendrawing.h @@ -57,12 +57,19 @@ class glyph std::vector m_lit; }; +// what a font may be: an image no larger than a screen image, a glyph no wider; no more glyphs, nor columns of them +// side by side, than a font can use. a glyph past the image's edge is unlit there, as with led_util +constexpr int max_font_image_side{4096}; +constexpr int max_font_glyphs{4096}; +constexpr int max_font_columns{2 * max_font_image_side}; + class bitmap_font { public: // a font as led_util.load_font() reads it: Rgba (Width x Height) has the glyphs side by side, a column apart; // Description has a comment line, then a line per glyph: the character and its width. a pixel is lit unless it is - // opaque white. nothing for a description without glyphs + // opaque white. a glyph wider than max_font_image_side is skipped. nothing for a description without glyphs, or + // beyond the limits above static std::optional parse(std::span Rgba, int Width, int Height, std::string_view Description); // a sprite as led_util.load_spr() reads it: the whole image as one glyph static glyph sprite(std::span Rgba, int Width, int Height); diff --git a/scripting/scriptscreenprogram.h b/scripting/scriptscreenprogram.h index 6b0d1b70b..10bed2124 100644 --- a/scripting/scriptscreenprogram.h +++ b/scripting/scriptscreenprogram.h @@ -14,11 +14,13 @@ http://mozilla.org/MPL/2.0/. #include "scripting/scriptscreens.h" +#include #include #include #include #include #include +#include #include namespace script_screens @@ -28,6 +30,23 @@ namespace script_screens constexpr int max_image_side{4096}; // the most instructions one call into a screen may run, so that a script stuck in a loop can't hang the worker constexpr std::int64_t instruction_limit{200'000'000}; +// what one call into a screen may send and log; the rest is dropped, which the log tells once per screen. the longest +// name of a command the engine knows is under 40 characters +constexpr std::size_t max_commands_per_call{64}; +constexpr std::size_t max_command_name{64}; +constexpr int max_log_lines_per_call{32}; +constexpr std::size_t max_log_line{1024}; // bytes of the text, a longer one is cut +// the largest file a screen reads: its script or module, a file below its folder +constexpr std::uintmax_t max_screen_file{16 * 1024 * 1024}; +// the memory a Lua screen may hold: its Lua heap, and the pixels of its images, fonts and sprites. checked with a full +// collection, so its garbage doesn't count; between the collections it may take the screen up to twice this, which +// the screen's allocator refuses to go over as each block is asked for +constexpr std::size_t max_screen_memory{128 * 1024 * 1024}; + +// for the unit tests, which fill the memory of a screen and stay small: the memory a Lua screen made from now on may +// hold in place of max_screen_memory, and the most any Lua screen held since it was set (its heap and its objects) +void set_lua_screen_memory_limit(std::size_t Bytes); +std::size_t lua_screen_memory_peak(); struct pending_command { @@ -86,6 +105,31 @@ std::unique_ptr make_wasm_runtime(); std::string utf8_text(std::string const &Text); // a file of the screen's folder or below; nothing for a path leading outside, or no such file std::optional read_screen_file(std::string const &Folder, std::string_view Path); +// the file, when it is a regular file of at most max_screen_file bytes: not a folder, a device or anything larger +std::optional read_regular_file(std::string const &Path); + +// what a screen sends and logs, held to the limits of one call. Name: how the log names the screen +class output_limits +{ + public: + explicit output_limits(std::string Name) : m_name{std::move(Name)} {} + + // a new call into the screen + void start_call() + { + m_log_lines = 0; + } + // true when the command may go with the call; a command over the limits is dropped + bool take_command(render_call const &Call, std::string_view Name); + // the line to log, cut to max_log_line; nothing when the call logged enough + std::optional take_log(std::string_view Text); + + private: + std::string m_name; + int m_log_lines{0}; + bool m_commands_dropped{false}; // logged once + bool m_logs_dropped{false}; // logged once +}; // seconds of a steady clock, the same for every screen, for animations that don't depend on how often the screen is // refreshed double screen_time(); diff --git a/scripting/scriptscreenrules.cpp b/scripting/scriptscreenrules.cpp index 58c69efde..5aa71cdd4 100644 --- a/scripting/scriptscreenrules.cpp +++ b/scripting/scriptscreenrules.cpp @@ -13,6 +13,9 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include +#include +#include namespace script_screens { @@ -123,4 +126,322 @@ bool is_safe_relative_path(std::string_view const Path) return true; } +std::optional screen_script_path(std::string const &Folder, std::string const &Script) +{ + // as substr_path() tells a folder + auto path{Script.find('/') == std::string::npos ? Folder + Script : Script}; + if (false == is_safe_relative_path(path)) + { + return std::nullopt; + } + return path; +} + +namespace +{ + +// the end of the set that starts at Start ('['), past its ']'; Pattern.size() for a set that doesn't end. as Lua's +// classEnd: a ']' right after '[' or '[^' is in the set, and '%' escapes the character after it +std::size_t set_end(std::string_view const Pattern, std::size_t Start) +{ + auto idx{Start + 1}; + if (idx < Pattern.size() && Pattern[idx] == '^') + { + ++idx; + } + do + { + if (idx >= Pattern.size()) + { + return Pattern.size(); + } + if (Pattern[idx++] == '%') + { + ++idx; + } + } while (idx >= Pattern.size() || Pattern[idx] != ']'); + return idx + 1; +} + +// one item of a pattern, as Lua's matcher takes them +struct pattern_item +{ + enum class kind + { + single, // a character, '.', a %class or a [set], with its quantifier if any + paren, // '(' or ')': a capture costs nothing + scan, // %bxy or a back reference %1-%9: goes along the subject + frontier, // %f[set]: a test of one position + end_anchor // '$' that ends the pattern + }; + kind type{kind::single}; + std::size_t begin{0}; // of a single, without its quantifier + std::size_t end{0}; + char quantifier{0}; // '*', '+', '-', '?' or none +}; + +std::vector pattern_items(std::string_view const Pattern, std::size_t idx) +{ + std::vector items; + while (idx < Pattern.size()) + { + auto const character{Pattern[idx]}; + if (character == '(' || character == ')') + { + items.push_back({pattern_item::kind::paren, idx, idx + 1}); + ++idx; + continue; + } + if (character == '$' && idx + 1 == Pattern.size()) + { + items.push_back({pattern_item::kind::end_anchor, idx, idx + 1}); + break; + } + std::size_t end{idx + 1}; + if (character == '%' && idx + 1 < Pattern.size()) + { + auto const next{Pattern[idx + 1]}; + if (next == 'b') + { + items.push_back({pattern_item::kind::scan, idx, idx + 4}); + idx += 4; + continue; + } + if (next == 'f') + { + auto const after{idx + 2 < Pattern.size() && Pattern[idx + 2] == '[' ? set_end(Pattern, idx + 2) : idx + 2}; + items.push_back({pattern_item::kind::frontier, idx, after}); + idx = after; + continue; + } + if (next >= '0' && next <= '9') + { + items.push_back({pattern_item::kind::scan, idx, idx + 2}); + idx += 2; + continue; + } + end = idx + 2; + } + else if (character == '[') + { + end = set_end(Pattern, idx); + } + pattern_item item{pattern_item::kind::single, idx, end}; + if (end < Pattern.size() && (Pattern[end] == '*' || Pattern[end] == '+' || Pattern[end] == '-' || Pattern[end] == '?')) + { + item.quantifier = Pattern[end]; + ++end; + } + items.push_back(item); + idx = end; + } + return items; +} + +// when the rest of a pattern matches, once the matcher gets to it +enum class rest_match +{ + always, // from any position: whatever comes before it is tried once + at_end, // at least at the end of the subject + maybe +}; + +rest_match match_with(std::string_view const Pattern, pattern_item const &Item, rest_match const Rest) +{ + switch (Item.type) + { + case pattern_item::kind::paren: + return Rest; + case pattern_item::kind::end_anchor: + return rest_match::at_end; + case pattern_item::kind::single: + if (Item.quantifier == '*' || Item.quantifier == '-' || Item.quantifier == '?') + { + // matches nothing as well; '.' repeated goes on to the end of the subject + auto const dot{Item.quantifier != '?' && Item.end - Item.begin == 1 && Pattern[Item.begin] == '.'}; + return dot && Rest == rest_match::at_end ? rest_match::always : Rest; + } + return rest_match::maybe; + default: + return rest_match::maybe; + } +} + +// whether Character is in the %class Class, as Lua's match_class +bool in_class(unsigned char const Character, unsigned char const Class) +{ + bool in{false}; + switch (std::tolower(Class)) + { + case 'a': in = std::isalpha(Character) != 0; break; + case 'c': in = std::iscntrl(Character) != 0; break; + case 'd': in = std::isdigit(Character) != 0; break; + case 'l': in = std::islower(Character) != 0; break; + case 'p': in = std::ispunct(Character) != 0; break; + case 's': in = std::isspace(Character) != 0; break; + case 'u': in = std::isupper(Character) != 0; break; + case 'w': in = std::isalnum(Character) != 0; break; + case 'x': in = std::isxdigit(Character) != 0; break; + case 'z': in = Character == 0; break; + default: return Class == Character; + } + return std::isupper(Class) != 0 ? !in : in; +} + +// the longest run of the subject that the single item (a character, '.' or a %class) matches; the whole subject for a +// set, which isn't gone through here +std::size_t longest_run(std::string_view const Pattern, pattern_item const &Item, std::string_view const Subject) +{ + auto const single{Pattern.substr(Item.begin, Item.end - Item.begin)}; + if (single == "." || single.front() == '[') + { + return Subject.size(); + } + std::size_t longest{0}; + std::size_t run{0}; + for (auto const character : Subject) + { + auto const c{static_cast(character)}; + auto const in{single.size() == 2 ? in_class(c, static_cast(single[1])) : c == static_cast(single[0])}; + run = in ? run + 1 : 0; + longest = std::max(longest, run); + } + return longest; +} + +// the characters Lua's matchbalance goes along for a %bxy tried in the subject: from each opening character to the one +// that closes it, or to the end of the subject when nothing does +struct balance_walks +{ + double longest{0.0}; // of one try + double total{0.0}; // of a try at every opening character +}; + +// the openings held while their closing characters are looked for; a subject nested deeper counts as never closed +constexpr std::size_t max_balance_depth{65536}; + +balance_walks balance_walks_of(char const Open, char const Close, std::string_view const Subject) +{ + balance_walks walks; + auto const size{Subject.size()}; + auto const add{[&walks](std::size_t const Walk) { + walks.longest = std::max(walks.longest, static_cast(Walk)); + walks.total += static_cast(Walk); + }}; + if (Open == Close) + { + // the next one closes it, and opens the try that starts there + auto previous{Subject.find(Open)}; + while (previous != std::string_view::npos) + { + auto const next{Subject.find(Open, previous + 1)}; + add((next != std::string_view::npos ? next : size) - previous); + previous = next; + } + return walks; + } + std::vector open; + for (std::size_t idx{0}; idx < size; ++idx) + { + if (Subject[idx] == Close) + { + if (false == open.empty()) + { + add(idx - open.back()); + open.pop_back(); + } + } + else if (Subject[idx] == Open) + { + if (open.size() >= max_balance_depth) + { + auto const openings{static_cast(std::count(Subject.begin(), Subject.end(), Open))}; + return {static_cast(size), openings * static_cast(size)}; + } + open.push_back(idx); + } + } + for (auto const idx : open) + { + add(size - idx); + } + return walks; +} + +// how many times over a %bxy counts: it goes along the subject on its own, whatever follows it, so it counts where it +// ends the pattern as well. without the subject, as many times as the subject has positions. with it: the longest walk +// of one try (plus one); or, when nothing but captures is before it in a pattern tried from every position, each +// opening character is tried once, and it's the walks of all of them over the positions (plus one) +double balance_cost(std::string_view const Pattern, pattern_item const &Item, std::string_view const *Subject, double const Positions, bool const Once) +{ + if (Subject == nullptr) + { + return Positions; + } + if (Item.begin + 3 >= Pattern.size()) + { + // malformed: the function raises its error + return 1.0; + } + auto const walks{balance_walks_of(Pattern[Item.begin + 2], Pattern[Item.begin + 3], *Subject)}; + return Once ? 1.0 + walks.total / Positions : 1.0 + walks.longest; +} + +double pattern_cost(std::string_view const Pattern, std::size_t const Size, std::string_view const *Subject, bool const Plain, bool const Anchorable) +{ + auto const length{static_cast(std::max(Pattern.size(), 1))}; + auto const positions{static_cast(Size) + 1.0}; + // LuaJIT searches plainly for a pattern without the special characters as well + if (Plain || Pattern.find_first_of("^$*+?.([%-") == std::string_view::npos) + { + return positions * length; + } + auto const anchored{Anchorable && Pattern.front() == '^'}; + auto const items{pattern_items(Pattern, anchored ? 1U : 0U)}; + auto cost{anchored ? 1.0 : positions}; + // from the end: what follows each item, and whether that's only the end of the subject + auto rest{rest_match::always}; + auto only_end{true}; + // the first item that isn't a capture: a %bxy there is tried once from each position + auto const first{std::find_if(items.begin(), items.end(), [](pattern_item const &Item) { return Item.type != pattern_item::kind::paren; })}; + for (auto item{items.rbegin()}; item != items.rend(); ++item) + { + if (item->type == pattern_item::kind::single && item->quantifier == '?') + { + cost *= 2.0; + } + if (item->type == pattern_item::kind::scan && Pattern[item->begin + 1] == 'b') + { + cost *= balance_cost(Pattern, *item, Subject, positions, false == anchored && first != items.end() && &*item == &*first); + only_end = false; + rest = rest_match::maybe; + continue; + } + auto const repeated{item->type == pattern_item::kind::scan + || (item->type == pattern_item::kind::single && item->quantifier != 0 && item->quantifier != '?')}; + // a repetition followed by what always matches is tried once (as one that ends the pattern): past it the match + // is over. otherwise the rest is tried at each length it takes, as many as the subject has positions; before + // '$' alone, as many as its longest run in the subject, past which it stops + if (repeated && rest != rest_match::always) + { + auto const before_end{only_end && rest == rest_match::at_end && item->type == pattern_item::kind::single}; + cost *= before_end && Subject != nullptr ? static_cast(longest_run(Pattern, *item, *Subject)) + 1.0 : positions; + } + only_end = only_end && (item->type == pattern_item::kind::paren || item->type == pattern_item::kind::end_anchor); + rest = match_with(Pattern, *item, rest); + } + return cost * length; +} + +} // namespace + +double lua_pattern_cost(std::string_view const Pattern, std::size_t const Subject, bool const Plain, bool const Anchorable) +{ + return pattern_cost(Pattern, Subject, nullptr, Plain, Anchorable); +} + +double lua_pattern_cost(std::string_view const Pattern, std::string_view const Subject, bool const Plain, bool const Anchorable) +{ + return pattern_cost(Pattern, Subject.size(), &Subject, Plain, Anchorable); +} } // namespace script_screens diff --git a/scripting/scriptscreenrules.h b/scripting/scriptscreenrules.h index d7d753841..bd751e50b 100644 --- a/scripting/scriptscreenrules.h +++ b/scripting/scriptscreenrules.h @@ -10,6 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include #include #include @@ -72,4 +73,36 @@ class frame_schedule // drive or a leading separator bool is_safe_relative_path(std::string_view Path); +// the path the game opens the script of a screen by: a name without a folder is in the vehicle's folder (Folder), a +// path is from the game's folder. nothing for a path that leads outside the game's folder (as for the files a screen +// reads: absolute, with a drive, or with ".."), since the script's folder is the one the screen then reads files from +std::optional screen_script_path(std::string const &Folder, std::string const &Script); + +// the Lua pattern functions (string.find, match, gmatch, gsub) run in C, where the instruction limit doesn't reach, and +// backtrack: ("a"):rep(1e6):find(".-b") would take hours. a call is refused when the steps it may take at worst, by +// lua_pattern_cost(), are over this: LuaJIT 2.0 goes through the worst patterns that cost as much (a):rep(5770) and +// .-b) in about a tenth of a second +constexpr double max_pattern_cost{1e8}; + +// the steps a Lua pattern function may take at worst on a subject of Subject bytes, Pattern being m bytes long: +// - a plain search (string.find with plain set, or a pattern without special characters): Subject x m; +// - a pattern: tried from every position of the subject (Subject + 1), or from the first only when Anchored (it starts +// with '^', and the function anchors: find, match, gsub, not gmatch), times (Subject + 1) for each repetition ('*', +// '+', '-', %b, a back reference %1-%9) but one followed by what always matches (nothing, ')', a repetition with '*' +// or '-' or a '?' of what always matches, '.*' / '.-' before '$'), where the match is over: so neither the last +// repetition nor the first %s* of "^%s*(.-)%s*$" multiplies. times 2 for each '?', times m for the work of each step +// (a set is gone through item by item) +// - a %bxy goes along the subject on its own, whatever follows it, so it counts where it ends the pattern as well: +// ("("):rep(1e6):find("%b()") walks to the end of the subject from each of its characters +// a malformed pattern costs nothing here: the function raises its error itself +double lua_pattern_cost(std::string_view Pattern, std::size_t Subject, bool Plain, bool Anchorable); +// as above, on the subject itself: a repetition of a character or a %class right before the final '$' ("%s*$") counts +// as many times as the longest run of it in the subject (plus one), not the whole subject: past that run it fails or +// gets to the end, so the trim "^%s*(.-)%s*$" costs about the subject times its longest run of spaces +// a %bxy counts as many times as the longest way from an opening character to the one that closes it (to the end of +// the subject when nothing does), plus one; when only captures are before it in a pattern tried from every position, +// each opening character is tried once, and it's the ways from all of them over the positions of the subject. so +// "%b()" on a long text of short balanced pairs is cheap, and on one that doesn't balance it's the subject squared +double lua_pattern_cost(std::string_view Pattern, std::string_view Subject, bool Plain, bool Anchorable); + } // namespace script_screens diff --git a/scripting/scriptscreens.cpp b/scripting/scriptscreens.cpp index 08314932e..224a2f27e 100644 --- a/scripting/scriptscreens.cpp +++ b/scripting/scriptscreens.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -34,6 +35,7 @@ http://mozilla.org/MPL/2.0/. #include #include #include +#include #include #include #include @@ -99,12 +101,73 @@ std::optional read_screen_file(std::string const &Folder, std::stri { return std::nullopt; } - std::ifstream file{Folder + std::string{Path}, std::ios::binary}; + return read_regular_file(Folder + std::string{Path}); +} + +std::optional read_regular_file(std::string const &Path) +{ + // a folder or a device (CON, NUL, COM1...) isn't a regular file + std::error_code error; + // in the code page of the system, as the game opens its files + std::filesystem::path const path{Path}; + if (false == std::filesystem::is_regular_file(path, error)) + { + return std::nullopt; + } + auto const size{std::filesystem::file_size(path, error)}; + if (error || size > max_screen_file) + { + return std::nullopt; + } + std::ifstream file{path, std::ios::binary}; if (false == file.is_open()) { return std::nullopt; } - return std::string{std::istreambuf_iterator{file}, std::istreambuf_iterator{}}; + std::string contents(static_cast(size), '\0'); + file.read(contents.data(), static_cast(contents.size())); + // what was read, should the file have shrunk meanwhile + contents.resize(static_cast(file.gcount())); + return contents; +} + +bool output_limits::take_command(render_call const &Call, std::string_view const Name) +{ + if (Call.commands.size() < max_commands_per_call && Name.size() <= max_command_name) + { + return true; + } + if (false == m_commands_dropped) + { + m_commands_dropped = true; + ErrorLog(std::format("{}: commands over {} in a refresh, or with names over {} characters, are dropped", m_name, max_commands_per_call, max_command_name)); + } + return false; +} + +std::optional output_limits::take_log(std::string_view Text) +{ + if (m_log_lines >= max_log_lines_per_call) + { + if (false == m_logs_dropped) + { + m_logs_dropped = true; + ErrorLog(std::format("{}: log lines over {} in a call are dropped", m_name, max_log_lines_per_call)); + } + return std::nullopt; + } + ++m_log_lines; + if (Text.size() <= max_log_line) + { + return std::format("{}: {}", m_name, Text); + } + // cut on the start of a UTF-8 character + auto end{max_log_line}; + while (end > 0 && (static_cast(Text[end]) & 0xC0) == 0x80) + { + --end; + } + return std::format("{}: {} [cut at {} of {} bytes]", m_name, Text.substr(0, end), end, Text.size()); } double screen_time() diff --git a/scripting/wasmprogram.cpp b/scripting/wasmprogram.cpp index d2f914cf0..1a1751732 100644 --- a/scripting/wasmprogram.cpp +++ b/scripting/wasmprogram.cpp @@ -25,8 +25,6 @@ http://mozilla.org/MPL/2.0/. #include #include #include -#include -#include #include #include #include @@ -117,7 +115,10 @@ std::int32_t to_int32(std::size_t const Value) class wasm_program final : public program { public: - wasm_program(std::string const &Script, script_screen_kind const Kind) : kind{Kind}, script{Script}, folder{substr_path(Script)} {} + wasm_program(std::string const &Script, script_screen_kind const Kind) + : kind{Kind}, script{Script}, folder{substr_path(Script)}, output{std::format("WASM screen \"{}\"", Script)} + { + } ~wasm_program() override { if (exec_env != nullptr) @@ -142,6 +143,7 @@ class wasm_program final : public program input_view const *input{nullptr}; render_call *call{nullptr}; bool commands_ignored{false}; // a screen outside the cab tried to send a command, and it was logged + output_limits output; private: bool call_i32(wasm_function_inst_t Function, std::string_view Name, std::int32_t &Result); @@ -300,17 +302,23 @@ void native_command(wasm_exec_env_t Env, char const *Name, std::uint32_t const L } return; } - screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + if (screen->output.take_command(*screen->call, std::string_view{Name, Length})) + { + screen->call->commands.emplace_back(std::string{Name, Length}, Param1, Param2, screen->call->vehicle); + } } void native_log(wasm_exec_env_t Env, char const *Text, std::uint32_t const Length) { - auto const *screen{program_of(Env)}; + auto *screen{program_of(Env)}; if (screen == nullptr || Text == nullptr) { return; } - WriteLog(std::format("WASM screen \"{}\": {}", screen->script, std::string_view{Text, Length})); + if (auto const line{screen->output.take_log(std::string_view{Text, Length})}; line.has_value()) + { + WriteLog(*line); + } } // reads a file from the screen's folder into the buffer. returns the size of the whole file, which may be more @@ -436,6 +444,7 @@ bool wasm_program::instantiate(wasm_module_t const Module) bool wasm_program::call_i32(wasm_function_inst_t Function, std::string_view const Name, std::int32_t &Result) { wasm_runtime_set_instruction_count_limit(exec_env, static_cast(instruction_limit)); + output.start_call(); std::array cells{}; if (false == wasm_runtime_call_wasm(exec_env, Function, 0, cells.data())) { @@ -514,9 +523,9 @@ class wasm_runtime_host final : public runtime { for (auto const &[script, entry] : m_modules) { - if (entry.module != nullptr) + if (entry.wasm_module != nullptr) { - wasm_runtime_unload(entry.module); + wasm_runtime_unload(entry.wasm_module); } } if (m_started) @@ -542,7 +551,7 @@ class wasm_runtime_host final : public runtime struct module_entry { std::vector bytes; // the runtime reads the module from here as long as it is loaded - wasm_module_t module{nullptr}; + wasm_module_t wasm_module{nullptr}; }; wasm_module_t load_module(std::string const &Script); @@ -575,40 +584,40 @@ wasm_module_t wasm_runtime_host::load_module(std::string const &Script) { if (auto const lookup{m_modules.find(Script)}; lookup != m_modules.end()) { - return lookup->second.module; + return lookup->second.wasm_module; } // a failure is kept as well, so the module isn't tried again for every screen using it auto &entry{m_modules[Script]}; - std::ifstream file{Script, std::ios::binary}; - if (false == file.is_open()) + auto const file{read_regular_file(Script)}; + if (false == file.has_value()) { - ErrorLog(std::format("WASM screen \"{}\": file not found", Script)); + ErrorLog(std::format("WASM screen \"{}\": file not found, or larger than {} bytes", Script, max_screen_file)); return nullptr; } - entry.bytes.assign(std::istreambuf_iterator{file}, std::istreambuf_iterator{}); + entry.bytes.assign(file->begin(), file->end()); if (entry.bytes.empty() || entry.bytes.size() > std::numeric_limits::max()) { ErrorLog(std::format("WASM screen \"{}\": invalid module size", Script)); return nullptr; } std::array error{}; - entry.module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); - if (entry.module == nullptr) + entry.wasm_module = wasm_runtime_load(entry.bytes.data(), static_cast(entry.bytes.size()), error.data(), static_cast(error.size())); + if (entry.wasm_module == nullptr) { ErrorLog(std::format("WASM screen \"{}\": failed to load the module: {}", Script, error.data())); } - return entry.module; + return entry.wasm_module; } std::unique_ptr wasm_runtime_host::load(std::string const &Script, script_screen_kind const Kind) { - auto *module{load_module(Script)}; - if (module == nullptr) + auto *wasm_module{load_module(Script)}; + if (wasm_module == nullptr) { return nullptr; } auto loaded{std::make_unique(Script, Kind)}; - if (false == loaded->instantiate(module)) + if (false == loaded->instantiate(wasm_module)) { return nullptr; } diff --git a/shaders/README.md b/shaders/README.md index 16cfbc2a8..34c7122f9 100644 --- a/shaders/README.md +++ b/shaders/README.md @@ -24,7 +24,8 @@ compiles every shader of `ogl46/` (with the variant `MODEL_DRAWS` of the vertex glslc --target-env=opengl4.5 -DMODEL_DRAWS=1 ogl46/vertex.vert -o ogl46bin/vertex.vert.MODEL_DRAWS.spv glslc --target-env=vulkan1.4 vk14/imgui.frag -o vk14bin/imgui.frag.spv -A binary made by hand isn't in the manifest, so it is taken without being compared with its source. After a change of a +A binary made by hand isn't in the manifest, so it is used only where its source isn't there (otherwise the source is compiled +and the log says so). After a change of a source, compile the binaries again (or delete them): a binary older than its source is not used, and the log says so. ## Writing shaders @@ -38,6 +39,15 @@ source, compile the binaries again (or delete them): a binary older than its sou * The settings of the game (`SHADOWMAP_ENABLED`, `ENVMAP_ENABLED`, `MOTIONBLUR_ENABLED`, `POSTFX_ENABLED`, `EXTRAEFFECTS_ENABLED`, `OUTPUT_GAMMA`) are `const bool` (specialization constants in the binaries, `ogl46/settings.glsl`): use them in `if`, not in `#if`. +* A material shader names its textures and parameters with `#pragma texture(name, unit, components)` and + `#pragma param(name, location, offset, size, default)`; a `.mat` file sets them as `texture_:` and `param_:`. + Every directive of a file and of its includes is read, whatever `#ifdef` it is in. A fourth argument of + `#pragma texture` (`black`, `white`, `red`, `yellow`) makes the texture one the material may leave out: the unit then + shows a single texel of that colour. +* The materials of the metallic and roughness workflow are `mat_pbr.frag` and its variants (`mat_pbr_detail.frag`, + `mat_pbr_parallax.frag`, `mat_pbr_coat.frag`): `mat_pbr.glsl` declares what they share and says what each texture and + parameter is, `mat_pbr_surface.glsl` is their fragment stage, the same file in `ogl46/` and `vk14/`. They define + `PBR_SURFACE` (and `PBR_COAT`), which `light_common.glsl` lights as the texturing tools show the surface. * The constants of the game (bindings, sizes) are written in `ogl46/common.glsl` and `vk14/common.glsl` for the binaries; the game puts its own values before the sources and checks at the start that the files have the same ones (the shader validator in `ci_shadervalidator` checks them too). diff --git a/shaders/compile_spirv.py b/shaders/compile_spirv.py index 061783c1a..da0aa3053 100644 --- a/shaders/compile_spirv.py +++ b/shaders/compile_spirv.py @@ -12,7 +12,7 @@ # glslc --target-env=opengl4.5 shaders/ogl46/mat_default.frag -o shaders/ogl46bin/mat_default.frag.spv # glslc --target-env=opengl4.5 -DMODEL_DRAWS=1 shaders/ogl46/vertex.vert -o shaders/ogl46bin/vertex.vert.MODEL_DRAWS.spv # glslc --target-env=vulkan1.4 shaders/vk14/imgui.frag -o shaders/vk14bin/imgui.frag.spv -# (a binary compiled by hand isn't in the manifest, so the game takes it without comparing it with its sources) +# (a binary compiled by hand isn't in the manifest, so the game takes it only where its source isn't there) import argparse import os @@ -115,6 +115,11 @@ def main(): if result.returncode != 0: failed.append('%s/%s' % (binarydir, binary)) sys.stderr.write(result.stderr) + # the binary of an earlier run would stay beside a source it no longer matches + stale = os.path.join(binaries, binary) + if os.path.isfile(stale): + os.remove(stale) # NOSONAR: a developer tool removing its own output beside the shaders it is given + print('removed the stale %s/%s' % (binarydir, binary), file=sys.stderr) continue if result.stderr.strip(): sys.stderr.write(result.stderr) diff --git a/shaders/mat_wire.frag b/shaders/mat_wire.frag deleted file mode 100644 index 030fddc62..000000000 --- a/shaders/mat_wire.frag +++ /dev/null @@ -1,57 +0,0 @@ -in vec3 f_normal; -in vec2 f_coord; -in vec4 f_pos; - -in vec4 f_clip_pos; -in vec4 f_clip_future_pos; - -#include - -// overhead line wires, ropes and fittings drawn as solids: untextured metal. -// param[0].rgb - metal colour (sRGB), param[0].a - opacity -// param[1].x - colour intensity, param[1].y - metalness, param[1].z - reflection, param[1].w - glossiness -#param (color, 0, 0, 4, diffuse) -#param (diffuse, 1, 0, 1, diffuse) -#param (specular, 1, 1, 1, specular) -#param (reflection, 1, 2, 1, zero) -#param (glossiness, 1, 3, 1, glossiness) - -layout(location = 0) out vec4 out_color; -#if MOTIONBLUR_ENABLED -layout(location = 1) out vec4 out_motion; -#endif - -#include -#include -#include - -void main() -{ - // no texture: the metal 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); - - vec3 fragcolor = ambient; - vec3 fragnormal = normalize(f_normal); - float reflectivity = param[1].z; - // bare metal: the colour tints the highlights instead of the diffuse term - metalic = clamp(param[1].y, 0.0, 1.0); - float specularity = dot(pow(param[0].rgb, vec3(2.2)), vec3(0.5)); - glossiness = abs(param[1].w); - - fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - - vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); -#if POSTFX_ENABLED - out_color = color; -#else - out_color = tonemap(color); -#endif -#if MOTIONBLUR_ENABLED - { - vec2 a = (f_clip_future_pos.xy / f_clip_future_pos.w) * 0.5 + 0.5;; - vec2 b = (f_clip_pos.xy / f_clip_pos.w) * 0.5 + 0.5;; - - out_motion = vec4(a - b, 0.0f, 0.0f); - } -#endif -} diff --git a/shaders/ogl46/cluster_cull.comp b/shaders/ogl46/cluster_cull.comp index 0545540f9..59d9a6bea 100644 --- a/shaders/ogl46/cluster_cull.comp +++ b/shaders/ogl46/cluster_cull.comp @@ -25,7 +25,8 @@ float light_peak(light_s light) if (light.type == LIGHT_HEADLIGHTS) // weights are the state of the individual lamps and the beam texture, which is not brighter than 1, picks from them return peak * max(light.headlight_weights.r, max(light.headlight_weights.g, light.headlight_weights.b)); - return peak * (1.0 + light.ambient); + // point and spot lights: ambient holds the signed radius of the sphere the light shines from, which brings no brightness + return peak; } // distance from the light at which its contribution falls under MIN_CONTRIBUTION, 0 for a light which has none diff --git a/shaders/ogl46/common.glsl b/shaders/ogl46/common.glsl index 9c0a2ada4..0e727e3a1 100644 --- a/shaders/ogl46/common.glsl +++ b/shaders/ogl46/common.glsl @@ -62,8 +62,13 @@ #define WATER_MAP 256 #define WATER_GROUP_SIZE 64 #define WATER_SSBO_BINDING 16 +#define RAIN_CELLS_SSBO_BINDING 18 #define WATER_UBO_BINDING 6 #define WATER_MASK_TEX 25 +#define WATER_LAYER_TEXELS 2097152 +#define WATER_LAYER_BANDS 8 +#define WATER_SNOW_ATLAS_TEX 32 +#define WATER_SNOW_NORMAL_TEX 33 #define INSTANCE_COUNTER_HEADER 8 #define INSTANCE_JOB_SLEEPERS 1U #define LIGHT_SSBO_BINDING 0 @@ -129,6 +134,12 @@ #define FOG_VOLUME_BIAS 10.000000 #endif +// the places along the sweep of a blade whose rain is kept (gl::WIPER_PASS_BUCKETS): the renderer defines it, an older one doesn't +#ifndef WIPER_PASS_BUCKETS +#define WIPER_PASS_BUCKETS 64 +#endif + + const uint LIGHT_SPOT = 0U; const uint LIGHT_POINT = 1U; const uint LIGHT_DIR = 2U; @@ -368,6 +379,17 @@ layout(std140, binding = SCENE_UBO_BINDING) uniform scene_ubo vec4 cab_probe_sun_color; vec4 cab_probe_sun_box; vec4 cab_probe_sun_world; + // the insects met when the blades were at the ends of their sweep (mat_bugs_windscreen), see gl::scene_ubs + vec4 wiper_bugs_out; + vec4 wiper_bugs_return; + // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs + vec4 camera_hi; + vec4 camera_lo; + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w 1 with the cells of the rain + // worked out in this frame (mat_rain_windscreen), see gl::scene_ubs + vec4 rain_state; + // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs + vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; #ifdef STAGE_VERTEX diff --git a/shaders/ogl46/gtao_main.comp b/shaders/ogl46/gtao_main.comp index bae03d6dc..152bb48d7 100644 --- a/shaders/ogl46/gtao_main.comp +++ b/shaders/ogl46/gtao_main.comp @@ -31,7 +31,7 @@ const float FALLOFF_RANGE = 0.615; float half_depth(ivec2 texel) { ivec2 full_size = textureSize(depth_tex, 0); - return texelFetch(depth_tex, min(texel * 2, full_size - 1), 0).r; + return texelFetch(depth_tex, clamp(texel * 2, ivec2(0), full_size - 1), 0).r; } vec3 view_position(ivec2 texel, float depth) @@ -42,6 +42,27 @@ vec3 view_position(ivec2 texel, float depth) return position.xyz / position.w; } +// the step to the neighbour on one axis which is closer in depth. a neighbour outside the target or in the sky has no +// position and is left out; with neither left, zero +vec3 neighbour_delta(ivec2 texel, ivec2 offset, vec3 position, ivec2 size) +{ + ivec2 before = texel - offset; + ivec2 after = texel + offset; + float depthbefore = all(greaterThanEqual(before, ivec2(0))) ? half_depth(before) : 0.0; + float depthafter = all(lessThan(after, size)) ? half_depth(after) : 0.0; + bool hasbefore = depthbefore > 0.0; + bool hasafter = depthafter > 0.0; + if (!hasbefore && !hasafter) + return vec3(0.0); + if (!hasbefore) + return view_position(after, depthafter) - position; + if (!hasafter) + return position - view_position(before, depthbefore); + vec3 deltabefore = position - view_position(before, depthbefore); + vec3 deltaafter = view_position(after, depthafter) - position; + return (abs(deltaafter.z) < abs(deltabefore.z)) ? deltaafter : deltabefore; +} + // 4x4 ordered pattern, values 0..15 const float BAYER[16] = float[](0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0); @@ -61,14 +82,12 @@ void main() vec3 position = view_position(texel, depth); vec3 view = normalize(-position); - // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it - vec3 left = view_position(texel - ivec2(1, 0), half_depth(texel - ivec2(1, 0))); - vec3 right = view_position(texel + ivec2(1, 0), half_depth(texel + ivec2(1, 0))); - vec3 down = view_position(texel - ivec2(0, 1), half_depth(texel - ivec2(0, 1))); - vec3 up = view_position(texel + ivec2(0, 1), half_depth(texel + ivec2(0, 1))); - vec3 dx = (abs(right.z - position.z) < abs(position.z - left.z)) ? right - position : position - left; - vec3 dy = (abs(up.z - position.z) < abs(position.z - down.z)) ? up - position : position - down; - vec3 normal = normalize(cross(dx, dy)); + // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it. with no + // neighbour on an axis (a thin wire against the sky, the edge of the image) the surface faces the camera + vec3 dx = neighbour_delta(texel, ivec2(1, 0), position, size); + vec3 dy = neighbour_delta(texel, ivec2(0, 1), position, size); + vec3 normal = cross(dx, dy); + normal = (dot(normal, normal) > 1e-24) ? normalize(normal) : view; if (dot(normal, view) < 0.0) normal = -normal; diff --git a/shaders/ogl46/light_common.glsl b/shaders/ogl46/light_common.glsl index c87658b46..a49006820 100644 --- a/shaders/ogl46/light_common.glsl +++ b/shaders/ogl46/light_common.glsl @@ -28,6 +28,30 @@ layout(std430, binding = CAB_PROBE_SSBO_BINDING) readonly buffer cab_probe_ssbo float glossiness = 1.0; float metalic = 0.0; + +// the materials of the metallic and roughness workflow (mat_pbr.glsl, which defines PBR_SURFACE) describe the surface the way the +// texturing tools do: the perceptual roughness itself in place of the glossiness, the occlusion of the ambient light baked into +// their textures, and the light the surface emits whatever falls on it. they are lit as those tools show them: the sun without +// the sharpened terminator, the highlights not scaled by the specular colour of the submodel, and with the light a rough +// surface reflects after more than one bounce between its facets +float pbr_roughness = 1.0; +float pbr_occlusion = 1.0; +vec3 pbr_emission = vec3(0.0); +// with PBR_COAT, the clear varnish over the surface: how much of it there is (0..1) and its perceptual roughness +float coat_weight = 0.0; +float coat_roughness = 0.0; +// the highlights of the lamps in the varnish, gathered by add_local_light() +vec3 coat_lampspecular = vec3(0.0); +// the reflectance of the varnish at normal incidence (a refractive index of 1.5) +const float COAT_F0 = 0.04; + +// what scales the highlights of the sun and the lamps: specular: of the material, the specular colour of the submodel without +// it. in the pbr materials that parameter is the specular level instead, which shade_surface() gets as Specularity +#ifdef PBR_SURFACE +#define HIGHLIGHT_SCALE 1.0 +#else +#define HIGHLIGHT_SCALE param[1].y +#endif layout(location = 7) in vec4 UserData; #pragma param(weathering, 2, 3, 1, zero) @@ -609,7 +633,18 @@ void add_local_light(light_s light, vec2 part, vec3 fragnormal, inout vec3 diffu float energy = 1.0; if ((light.type != LIGHT_HEADLIGHTS) && (light.ambient != 0.0)) tolight = sphere_light_specular(tolight, fragnormal, abs(light.ambient), spec_roughness, energy); - specular += color * (part.y * param[1].y * energy) * specular_light(normalize(tolight), fragnormal, spec_f0, spec_roughness, LOCAL_LIGHT_BRDF_LIMIT); + specular += color * (part.y * HIGHLIGHT_SCALE * energy) * specular_light(normalize(tolight), fragnormal, spec_f0, spec_roughness, LOCAL_LIGHT_BRDF_LIMIT); +#ifdef PBR_COAT + // the varnish reflects the lamp with a lobe of its own + if (coat_weight > 0.0) + { + vec3 tocoat = light.pos - f_pos.xyz; + float coatenergy = 1.0; + if ((light.type != LIGHT_HEADLIGHTS) && (light.ambient != 0.0)) + tocoat = sphere_light_specular(tocoat, fragnormal, abs(light.ambient), coat_roughness, coatenergy); + coat_lampspecular += color * (part.y * coatenergy) * specular_light(normalize(tocoat), fragnormal, vec3(COAT_F0), coat_roughness, LOCAL_LIGHT_BRDF_LIMIT); + } +#endif } // adds the light of the headlights and lamps which reach the fragment to its diffuse and specular light. these are the ones in @@ -737,7 +772,14 @@ vec3 reflection_surroundings(vec3 fragnormal, float roughness) { vec3 direction = normalize(envmap_direction(fragnormal)); vec3 sky = envmap_sample_rough(normalize(vec3(direction.x, max(direction.y, 0.0), direction.z)), roughness); +#ifdef PBR_SURFACE + // the lobe of a rough surface takes in the sky and the ground at once: the horizon spreads with the roughness, instead of + // drawing a line across the surface + float spread = roughness * roughness; + float below = smoothstep(-spread, 0.25 + spread, -direction.y); +#else float below = smoothstep(0.0, 0.25, -direction.y); +#endif if ((below <= 0.0) || (false == ENVMAP_ENABLED)) return sky; return mix(sky, reflection_ground(), below); @@ -746,10 +788,23 @@ vec3 reflection_surroundings(vec3 fragnormal, float roughness) // the least weight of the reflection of the surroundings (its specular colour times its share) a surface traces the scene for const float REFLECTION_SCENE_WEIGHT = 0.004; +#ifdef PBR_SURFACE +// the screen and the rays follow the mirror direction alone: the sharp image of a polished surface, where a rough one shows the +// surroundings blurred. the scene hands the reflection over to the environment map and the probe of the cab, which the +// roughness blurs, between these perceptual roughnesses +const float SCENE_REFLECTION_ROUGHNESS_START = 0.1; +const float SCENE_REFLECTION_ROUGHNESS_END = 0.3; +#endif + // the reflection of the scene in a surface of the given perceptual roughness: the colour times how much of the reflection the // scene gives (rgb), and that share (a), the rest is left to reflection_surroundings() vec4 reflection_scene(vec3 fragnormal, float roughness) { +#ifdef PBR_SURFACE + float sharpness = 1.0 - smoothstep(SCENE_REFLECTION_ROUGHNESS_START, SCENE_REFLECTION_ROUGHNESS_END, roughness); + if (sharpness <= 0.0) + return vec4(0.0); +#endif vec3 direction = normalize(reflect(f_pos.xyz, fragnormal)); vec4 result = ssr_trace(f_pos.xyz, normalize(f_normal), direction, roughness); #ifdef REFLECTION_RAYS_ACTIVE @@ -760,6 +815,9 @@ vec4 reflection_scene(vec3 fragnormal, float roughness) result.rgb += traced.rgb * (1.0 - result.a); result.a += traced.a * (1.0 - result.a); } +#endif +#ifdef PBR_SURFACE + result *= sharpness; #endif return result; } @@ -861,6 +919,17 @@ vec3 cab_probe_reflection(vec3 surroundings, vec3 fragnormal, float roughness, v return surroundings * (1.0 - albedo.a) + light.rgb + albedo.rgb * ambientlight; } +#ifdef PBR_COAT +// what the varnish of a material reflects of the surroundings, with Coatspec the share of them it reflects: the ambient light +// where the material doesn't ask for the cubemap (Shares.x), the scene and the environment map elsewhere (Shares.y; the map +// held back by the occlusion and by the shadow of the sun, as for the surface below) +vec3 coat_reflection(vec3 ambientlight, vec3 envcolor, vec4 scenecolor, vec3 coatspec, vec2 shares, float occlusion, float cubemapshadow) +{ + return ambientlight * coatspec * shares.x * occlusion + + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * cubemapshadow * occlusion)) * coatspec * shares.y; +} +#endif + // lights the surface: the ambient light, the sun (the moon), the headlights and lamps and the reflection of the surroundings. // the units are the ones of the ambient light, the irradiance over pi: a white lambertian surface lit by 1 of it shows 1. // Texturecolor is the albedo (the base colour of a metal), Specularity the specular level of a dielectric (0.5 is the @@ -881,6 +950,11 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref else { // the sky lights the faces turned up and towards the bright part of the sky more than the ones turned to the ground +#ifdef PBR_SURFACE + // inside a cab or an interior the roof and the walls hide the sky: the bright blue zenith doesn't light the faces turned up + // more than the rest, the cab around (its probe) lights them instead + if (cab_interior < 0.5) +#endif fragcolor = add_sky_ambient(fragcolor, fragnormal); #ifndef NO_WEATHERING float weathered = (param[2].w > 0.0 ? clamp(param[2].w * UserData.x, 0.0, 1.0) : 0.0); @@ -894,7 +968,11 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref texturecolor = (tinted > 0.0 ? texturecolor * mix(vec3(1.0), param[2].rgb, tinted) : texturecolor); specularity = mix(specularity, min(specularity, 0.03), smoothstep(0.0, 0.4, polished)); metalic = mix(metalic, 0.0, polished); +#ifdef PBR_SURFACE + pbr_roughness = mix(pbr_roughness, max(pbr_roughness, 0.94), polished); +#else glossiness = mix(glossiness, min(glossiness, 0.06 * abs(param[1].w)), polished); +#endif reflectivity = mix(reflectivity, min(reflectivity, 0.08 * param[1].z), smoothstep(0.0, 0.4, polished)); #endif // Scale ambient before it gets tinted by the texture. @@ -912,7 +990,11 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref float NdotV = max(dot(fragnormal, view_dir), 1e-4); // glossiness == param[1].w -> mirror, glossiness == 0 -> fully rough +#ifdef PBR_SURFACE + float roughness = clamp(pbr_roughness, 0.0, 1.0); +#else float roughness = clamp(1.0 - glossiness / max(abs(param[1].w), 1.0), 0.0, 1.0); +#endif roughness = max(specular_antialiasing(fragnormal, roughness), MIN_ROUGHNESS); // metals reflect with their base colour, dielectrics with the specular level (0.5 -> 0.04) vec3 f0 = mix(vec3(0.08 * specularity), texturecolor, metalic); @@ -932,6 +1014,10 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref // light a lot; they take a share of it (gfx.postfx.ao.cab), the light which bounces inside them comes from the probe or below if (cab_interior > 0.5) occlusion = mix(1.0, occlusion, ao_params.z); +#ifdef PBR_SURFACE + // the occlusion baked into the textures of the material holds the ambient light back too, whatever the view finds + occlusion = min(occlusion, pbr_occlusion); +#endif vec3 diffuse_occlusion = vec3(1.0); float specular_occlusion = 1.0; if (occlusion < 1.0) @@ -939,6 +1025,15 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref diffuse_occlusion = ao_multi_bounce(occlusion, texturecolor); specular_occlusion = ao_specular(occlusion, NdotV, roughness); } +#ifdef PBR_SURFACE + // a normal map can tilt the normal so far that the reflected ray goes into the surface the geometry has there: such a ray + // finds the surface itself, not the surroundings (the horizon occlusion of Lagarde and de Rousiers 2014) + vec3 surfacenormal = normalize(f_normal); + if (dot(surfacenormal, f_pos.xyz) > 0.0) + surfacenormal = -surfacenormal; + float horizon = clamp(1.0 + dot(reflect(-view_dir, fragnormal), surfacenormal), 0.0, 1.0); + specular_occlusion *= horizon * horizon; +#endif // Pre-integrated env BRDF: how much of the surroundings the surface reflects, for its F0, roughness and the view angle. // the surroundings are the cubemap where the material asks for it (reflectivity) and the ambient light elsewhere, so a @@ -955,6 +1050,15 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref } // what the diffuse layer is left with vec3 diffuse_albedo = texturecolor * (1.0 - metalic) * (1.0 - env_spec); +#ifdef PBR_SURFACE + // the single bounce of the brdf leaves out the light which leaves a rough surface after more bounces between its facets, so + // rough metals come out too dark: the highlights and the reflection are raised by what is missing (Fdez-Aguera, "A multiple + // scattering microfacet model for real-time image based lighting", 2019). a white surface reflects 1 - 0.55 * roughness in + // one bounce: what the two terms of EnvBRDFApprox() add up to + vec3 multibounce = 1.0 + f0 * (1.0 / (1.0 - 0.55 * roughness) - 1.0); + env_spec *= multibounce; + cubemap_spec = env_spec; +#endif if (legacy_coat) { // the varnish: a smooth dielectric layer reflecting the cubemap, worn off where the material is weathered @@ -963,6 +1067,17 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref ambient_share = 1.0; diffuse_albedo *= 1.0 - cubemap_spec * min(cubemap_share, 1.0); } +#ifdef PBR_COAT + // the varnish: a smooth dielectric layer over the surface. what it reflects doesn't reach the surface below (coat_through is + // what does), and it reflects the surroundings, the sun and the lamps with a lobe of its own + coat_weight = matte ? 0.0 : clamp(coat_weight, 0.0, 1.0); + coat_roughness = max(specular_antialiasing(fragnormal, clamp(coat_roughness, 0.0, 1.0)), MIN_ROUGHNESS); + vec3 coat_spec = EnvBRDFApprox(vec3(COAT_F0), coat_roughness, NdotV) * coat_weight; + float coat_through = 1.0 - coat_weight * (COAT_F0 + (1.0 - COAT_F0) * pow(1.0 - NdotV, 5.0)); + float coat_occlusion = ((occlusion < 1.0) ? ao_specular(occlusion, NdotV, coat_roughness) : 1.0) * horizon * horizon; + vec3 coat_envcolor = vec3(0.0); + vec4 coat_scenecolor = vec4(0.0); +#endif // the reflection of the surroundings: the scene where the screen (or the ray tracing) gives it, the sky and the ground of the // environment map elsewhere vec3 envcolor = vec3(0.0); @@ -974,22 +1089,54 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref // inside the cab the cab is what the surroundings are, where the probe holds it if (cabprobe && (cab_probe_params.y > 0.0)) envcolor = cab_probe_reflection(envcolor, fragnormal, env_roughness, cabambient); +#ifdef PBR_COAT + // the varnish reflects the surroundings as well. the scene is traced once, for the layer which shows more of it; the + // other one reflects the environment map alone + if (coat_weight > 0.0) + { + coat_envcolor = reflection_surroundings(fragnormal, coat_roughness) * skyoccl.x; + if (cabprobe && (cab_probe_params.y > 0.0)) + coat_envcolor = cab_probe_reflection(coat_envcolor, fragnormal, coat_roughness, cabambient); + } + float baseweight = cubemap_share * dot(cubemap_spec, vec3(1.0 / 3.0)) * coat_through; + float coatweight = cubemap_share * dot(coat_spec, vec3(1.0 / 3.0)); + bool tracing = (ssr_params.x > 0.0) || (ssr_params2.z > 0.0); + if (tracing && (coatweight >= baseweight) && (coatweight > REFLECTION_SCENE_WEIGHT)) + coat_scenecolor = reflection_scene(fragnormal, coat_roughness); + else if (tracing && (baseweight > REFLECTION_SCENE_WEIGHT)) + scenecolor = reflection_scene(fragnormal, env_roughness); +#else if (((ssr_params.x > 0.0) || (ssr_params2.z > 0.0)) && (cubemap_share * dot(cubemap_spec, vec3(1.0 / 3.0)) > REFLECTION_SCENE_WEIGHT)) scenecolor = reflection_scene(fragnormal, env_roughness); +#endif } if (lights_count == 0U) - return fragcolor * diffuse_occlusion * diffuse_albedo - + emissioncolor * texturecolor - + fragcolor * env_spec * ambient_share * specular_occlusion - + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * specular_occlusion)) * cubemap_spec * cubemap_share; + { + vec3 unlit = fragcolor * diffuse_occlusion * diffuse_albedo + + emissioncolor * texturecolor + + fragcolor * env_spec * ambient_share * specular_occlusion + + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * specular_occlusion)) * cubemap_spec * cubemap_share; +#ifdef PBR_SURFACE + unlit += pbr_emission; +#endif +#ifdef PBR_COAT + unlit = unlit * coat_through + + coat_reflection(fragcolor, coat_envcolor, coat_scenecolor, coat_spec, vec2(ambient_share, cubemap_share), coat_occlusion, 1.0); +#endif + return unlit; + } vec3 light_dir = normalize(-lights[0].dir); float NdotL = max(dot(fragnormal, light_dir), 0.0); // Sharpen sun N.L falloff so the lit-to-shaded terminator on cab // panels, vehicle bodies and terrain reads as a clear edge rather // than a soft Lambertian ramp. Tunable via SUN_NDOTL_SHARPNESS. +#ifdef PBR_SURFACE + float sun_NdotL = NdotL; +#else float sun_NdotL = pow(NdotL, SUN_NDOTL_SHARPNESS); +#endif // the clouds hold back the sun (the moon at night) where their shadow falls float cloudsun = cloud_shadow(mat3(inv_view) * f_pos.xyz); // Sun HDR scale -> SUN_DIFFUSE_SCALE, the same for the diffuse and the specular light @@ -1018,6 +1165,9 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref // the reflection of the surroundings, before the light of the sun and the lamps joins the ambient light vec3 env_reflection = fragcolor * env_spec * ambient_share * specular_occlusion + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * cubemap_shadow * specular_occlusion)) * cubemap_spec * cubemap_share; +#ifdef PBR_COAT + vec3 coat_light = coat_reflection(fragcolor, coat_envcolor, coat_scenecolor, coat_spec, vec2(ambient_share, cubemap_share), coat_occlusion, cubemap_shadow); +#endif // the sun coming in through the windows and bouncing around a low poly interior, or the cab without its probe (which gives that // light from where the sun falls in the cab): a share of the light of the sun outside joins the ambient light (gfx.interior.bounce) if ((cab_interior > 0.5) && (false == cabprobe)) @@ -1033,12 +1183,27 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref vec3 lampspecular = vec3(0.0); add_local_lights(fragnormal, fragcolor, lampspecular); +#ifdef PBR_SURFACE + specular *= multibounce; + lampspecular *= multibounce; +#endif - return fragcolor * diffuse_albedo // ambient, sun and lamps on the diffuse layer - + specular * param[1].y // highlight of the sun, fresnel coloured (metals take their base colour) - + lampspecular // highlights of the lamps, param[1].y already applied - + emissioncolor * texturecolor - + env_reflection; + vec3 lit = fragcolor * diffuse_albedo // ambient, sun and lamps on the diffuse layer + + specular * HIGHLIGHT_SCALE // highlight of the sun, fresnel coloured (metals take their base colour) + + lampspecular // highlights of the lamps, HIGHLIGHT_SCALE already applied + + emissioncolor * texturecolor + + env_reflection; +#ifdef PBR_SURFACE + lit += pbr_emission; +#endif +#ifdef PBR_COAT + // the highlights of the sun and the lamps in the varnish, over what comes through it from the surface below + if (coat_weight > 0.0) + coat_light += (sunlight * specular_light(light_dir, fragnormal, vec3(COAT_F0), coat_roughness, SUN_BRDF_LIMIT) * (1.0 - shadow) + + coat_lampspecular) * coat_weight; + lit = lit * coat_through + coat_light; +#endif + return lit; } vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) diff --git a/shaders/ogl46/mat_bugs_windscreen.frag b/shaders/ogl46/mat_bugs_windscreen.frag new file mode 100644 index 000000000..caeaa2f09 --- /dev/null +++ b/shaders/ogl46/mat_bugs_windscreen.frag @@ -0,0 +1,500 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// Windscreen bugs (spring / summer) - v3 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v2) +// v3: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param, the settings as constants); +// the tuning values are constants (a uniform can't have a default any more); the blur ring goes to the post-processing +// through the velocity target as the haze of rain_windscreen does (postfx_taa.frag / postfx_motionblur.frag with +// rain_windscreen_haze.glsl); the colour is written straight (not premultiplied), as rain_windscreen of the 4.6 renderers +// writes the glass; the gloss of the glass from legacy_gloss(); no lighting where the glass is clear (no bug, clear texture) +// v2: cells without a bug are skipped before the wiper mask is read (the mask used to be read for all +// 18 cells of both layers on every pixel); the fine specks are procedural (no texture reads, only the +// pixel's own cell); optional vertical bias of the dirt; quick splat instead of a 2 s growth; +// now and then a really big bug and rarely a huge one (own coarse grids, never cut off by the 3x3 search); +// smaller blur ring, scaled by the size of the bug on screen. +// +// Insects splat on the glass one by one, only while the vehicle goes faster than 20 km/h and the more the faster, and the glass +// gets dirtier until it is fully dirty after `bugs_fill_time` seconds of driving at 100 km/h (default 3600 = 1 h; at 160 km/h +// about 35 minutes, at 50 km/h 2.7 hours). The engine counts the insects met (rain_wind.w) and keeps the count of the moments +// the blades were at the ends of their sweep (wiper_bugs_out / wiper_bugs_return), next to their times. +// No sliding, no rain: every bug is placed once (hash of its grid cell) and just +// appears at its own random moment. Wipers (wipermask) wipe the bugs off in the area they +// sweep; the glass there then gets dirty again, with new bugs, over the next bugs_fill_time. +// +// .mat (shader name WITHOUT the "mat_" prefix, the engine adds it). +// The sampler is called "raindropsatlas" on purpose, exactly like in rain_windscreen: +// the engine collects ALL texture_* lines of a .mat and checks them against the final +// shader, so a key that only one of the two shaders knows ends in "unknown texture binding". +// With one shared key, a season / weather block just overrides the file: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// +// spring: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas <- 2x2 atlas (blender_bugs_atlas.py), colour + alpha +// texture_normalmap: textures/fx/bugs_normalmap <- same layout: rg = normal xy, b = height, a = mask +// param_raindrop_grid_size: 60 <- cells across the glass UV, see below +// } +// summer: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas +// texture_normalmap: textures/fx/bugs_normalmap +// param_raindrop_grid_size: 60 +// } +// +// rain: { <- rain weather beats the season (priority 2 > 1) +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// } +// +// NOTE: the wipers' memory of when the glass was last wiped lives only in the engine's +// wiper timers, and the renderer resets them to -1000 whenever the camera is not in +// a cab (F4 ...). The shader cannot recover what is gone, so after returning to the cab the +// parts of the glass the blades cover are dirty as if never wiped (capped by `bugs_unknown_level`) until they are +// wiped again. A one-line engine fix would keep the memory, see the note in the chat. +// +// One cell is about one bug, so a grid of ~40-80 gives bugs of a few cm on a ~1.5 m +// windscreen (150, as used for rain drops, would make them tiny). + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +#include "common.glsl" + +layout(location = 0) out vec4 out_color; +layout(location = 1) out vec4 out_motion; + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // splats: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" + +layout(binding = 0) uniform sampler2D diffuse; +layout(binding = 1) uniform sampler2D raindropsatlas; +layout(binding = 2) uniform sampler2D wipermask; +layout(binding = 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +const float bugs_fill_time = 3600.0; // seconds of driving at 100 km/h until the glass is fully dirty (none below 20 km/h) +const float bugs_start_time = 0.0; // simulation time at which the glass was clean +const float bugs_density = 0.15; // fraction of grid cells that end up with a big bug (0..1) +const float specks_density = 0.12; // same for the layer of tiny specks (0 = off) +const float bugs_opacity = 1.0; // overall opacity of the dirt +const float bugs_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched (e.g. 2.0 for a 1.4 x 0.7 m pane) +const float bugs_unknown_level = 1.0; // upper limit of the dirt where the wiper memory was lost: 1 = grows like everywhere else, 0.3 = never more than 30%, 0 = stays clean until a blade passes +const float bugs_wiper_clean = 1.0; // 1 = wipers wipe the bugs off (uses wipermask), 0 = wipers ignore them +const float bugs_gloss = 0.45; // shininess of the wet splats (sun / headlight glints on the bumps), 0 = matt +const float bugs_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float bugs_halo_blur = 0.8; // blur of the scene seen through the see-through parts of a bug (its texture half transparent: wings, + // the thin smear of the splat), none around it (0 = off, 1 = full); done in the post-processing +const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = only under the splat, max 1.6) +const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) +const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even +const float bugs_giant_density = 0.015; // share of the coarse cells that end up with a really big bug (0 = off) +const float bugs_giant_scale = 2.5; // how much bigger the big ones are (the coarse grid is this many times coarser) +const float bugs_huge_density = 0.02; // share of the very coarse cells with a huge bug: about one per pane when fully dirty (0 = off) +const float bugs_huge_scale = 5.0; // how much bigger the huge ones are than the normal bugs +const float specks_size = 0.30; // size of the fine specks, in speck cells (0.1 .. 0.45) +const float specks_opacity = 0.55; // how much a speck covers the glass + +const float BUG_SIZE_MIN = 0.6; // bug size in grid cells (keep max <= 1.2, the search covers 3x3 cells) +const float BUG_SIZE_MAX = 1.2; +const float BUG_FADE_TIME = 0.15; // seconds a splat takes to appear (a quick splat) +const float SPECK_SCALE = 2.5; // speck grid = raindrop_grid_size * this +const float WS_ENC = 64.0; // must match rain_windscreen_haze.glsl + +// Match the way rain_windscreen draws the glass itself (colour premultiplied by +// alpha, then alpha-blended), so the pane looks identical in summer and in rain. +// Set to 1 to see the shader's clock (`time`) as red digits on the glass, see bugs_start_time. +#ifndef BUGS_DEBUG_TIME +#define BUGS_DEBUG_TIME 0 +#endif + +#ifndef BUGS_MATCH_RAIN_GLASS +#define BUGS_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// Simulation time at which a wiper blade last swept over `co`. +// WIPER_NONE no blade covers this spot (it can never be wiped) +// WIPER_UNKNOWN a blade covers it, but the engine has lost its memory: while the camera is +// outside the cab (F4 ...) the renderer resets the stroke timers to -1000 +// Same blade/stroke logic as GetMixFactor in rain_windscreen: wipermask channel i is the +// area of blade i, its value says when during the stroke the blade reaches that spot, and +// wiper_pos is 0..1 on the way out and 1..2 on the way back. The timers hold the moment +// each stroke started, which is good enough (a stroke takes about a second). +const float WIPER_NONE = -1.0e9; +const float WIPER_UNKNOWN = -2.0e9; + +float lastCleanTime(vec2 co, out float bugsAt) +{ + vec4 m = textureLod(wipermask, co, 0.0); + float best = WIPER_NONE; + bugsAt = 0.0; + bool unknown = false; + for (int i = 0; i < 4; ++i) + { + if (m[i] <= 0.001) + continue; + float pos = wiper_pos[i]; + bool isOut = pos <= 1.0; + float phase = isOut ? pos : 2.0 - pos; + float maskVal = isOut ? m[i] : 1.0 - m[i]; + bool passed = maskVal <= phase; // blade is already past this spot + float sideV = isOut ? (passed ? 0.0 : 1.0) : (passed ? 1.0 : 0.0); + float t = mix(wiper_timer_out[i], wiper_timer_return[i], sideV); + if (!(t <= time)) // garbage or NaN: ignore + continue; + float b = mix(wiper_bugs_out[i], wiper_bugs_return[i], sideV); // the insects met at that moment + if ((t < -500.0) || (b < 0.0)) // the -1000 "memory lost" marker + { + unknown = true; + continue; + } + if (t > best) + { + best = t; + bugsAt = b; + } + } + if (best > WIPER_NONE) + return best; + return unknown ? WIPER_UNKNOWN : WIPER_NONE; +} + +// Fine specks: tiny dried drops of bug juice. Procedural (a soft irregular blob with a darker rim), +// one per speck cell and always inside it, so only the pixel's own cell is checked: no texture reads +// apart from the wiper state of this pixel, which main() passes in. +void speckLayer(float gridSize, float density, float tcPix, float bugsPix, vec2 aspect, float pixelUV, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accNA) +{ + vec2 g = f_coord * gridSize; + vec2 cell = floor(g); + float tBase, prog; + float met = max(rain_wind.w, 0.0); // the insects met so far + if (tcPix < -1.5e9) + { + tBase = -1000.0; + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tcPix < -0.5e9) + { + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); + } + else + { + tBase = tcPix; + prog = max(met - bugsPix, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + return; + uint pseed = Hash(uvec3(uvec2(ivec2(floor(cell / 8.0))), 107u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vertMul = clamp(1.0 + bugs_vertical * ((cell.y + 0.5) / gridSize - 0.5) * 2.0, 0.0, 2.0); + uint seed = Hash(uvec3(uvec2(ivec2(cell)), 7u ^ floatBitsToUint(tBase))); + if (RandF(seed) > density * patchMul * vertMul) + return; + float appearAt = RandF(seed); + if (prog < appearAt) + return; + float r = clamp(specks_size, 0.05, 0.45) * mix(0.5, 1.0, RandF(seed)); + vec2 c = vec2(r) + vec2(RandF(seed), RandF(seed)) * max(1.0 - 2.0 * r, 0.0); + float ang = RandF(seed) * 6.2831853; + float el = mix(0.6, 1.0, RandF(seed)); + vec2 p = (g - cell - c) / r; + p = vec2(cos(ang) * p.x + sin(ang) * p.y, (-sin(ang) * p.x + cos(ang) * p.y) / el); + // irregular outline: a few lobes + float th = atan(p.y, p.x); + float lob = 1.0 + 0.18 * sin(3.0 * th + RandF(seed) * 6.28) + 0.10 * sin(5.0 * th + RandF(seed) * 6.28); + float d = length(p) / lob; + if (d >= 1.0) + return; + float edgeW = clamp(pixelUV * gridSize / r * 1.5, 0.05, 0.6); // ~1.5 px soft edge + float m = 1.0 - smoothstep(1.0 - edgeW, 1.0, d); + float a = m * specks_opacity * bugs_opacity * (0.6 + 0.4 * smoothstep(0.5, 0.95, d)); // the dried rim covers more + vec3 col = vec3(0.42, 0.34, 0.16) * mix(0.8, 1.15, RandF(seed)) * mix(1.0, 0.75, smoothstep(0.6, 0.95, d)); + vec3 nT = normalize(vec3(p / max(lob, 0.5) * 0.25 * bugs_bump, 1.0)); + accRGB = col * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; +} + +// Adds one layer of bugs to the premultiplied accumulators (accRGB, accA). +void bugLayer(float gridSize, float density, uint layerSeed, + float pixelUV, vec2 aspect, float haloStrength, float opacityMul, float lightMix, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accNA) +{ + vec2 cell = floor(f_coord * gridSize); + float fadeSpan = BUG_FADE_TIME / max(bugs_fill_time, 1.0); + + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + + // Dirt is patchy: big areas get more bugs than others; optional bias towards the top / bottom + uint pseed = Hash(uvec3(uvec2(ivec2(floor(ncell / 8.0))), layerSeed + 100u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vy = (ncell.y + 0.5) / gridSize; // 0 = bottom of the UV, 1 = top + float vertMul = clamp(1.0 + bugs_vertical * (vy - 0.5) * 2.0, 0.0, 2.0); + float pCell = clamp(density * patchMul * vertMul, 0.0, 1.0); + + // 1st test, fixed per cell (cheap, no texture): can this cell hold a bug at all? + // Cells that fail it are skipped before the wiper mask is read. + float pMax = min(2.0 * pCell, 1.0); + uint cseed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed + 31u)); + if (RandF(cseed) > pMax) + continue; + + // When the wipers last swept over this cell. Whatever hit the glass before that + // moment is gone; the cell then gets a brand new set of bugs (the seed depends on + // that moment) that again take bugs_fill_time to build up. + float bugsAt = 0.0; + float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize, bugsAt) : WIPER_NONE; + + // the insects met since the glass here was clean (they come only above 20 km/h, see the head of the file) + float met = max(rain_wind.w, 0.0); + float tBase; + float prog; + if (tc < -1.5e9) + { + // The engine forgot when the wipers last swept here (another vehicle). We cannot know how dirty the glass was, + // so show the level of the glass never wiped, at most bugs_unknown_level, until a blade passes. + tBase = -1000.0; + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tc < -0.5e9) + { + // no blade reaches here: everything met so far + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); + } + else + { + tBase = tc; + prog = max(met - bugsAt, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + continue; + + uint seed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed ^ floatBitsToUint(tBase))); + + // 2nd test, new after every wipe: together with the 1st one the cell holds a bug with + // probability pCell, and a wiped cell gets a new set of bugs + float present = RandF(seed); + if (present * pMax > pCell) + continue; + + // Moment (0..1 of the fill time) when this bug hits the glass + float appearAt = RandF(seed); + if (prog < appearAt) + continue; + float appear = smoothstep(appearAt, appearAt + fadeSpan, prog); + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float size = mix(BUG_SIZE_MIN, BUG_SIZE_MAX, RandF(seed)) / gridSize * mix(0.7, 1.0, appear); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float choice = RandF(seed); + float tone = mix(0.8, 1.15, RandF(seed)); + + vec2 d = (f_coord - center) * aspect; + + // Blur ring around the splat (greasy smear): strongest next to the bug, fading out + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + + // mip level from the on-screen size of the bug (derivatives are not + // allowed inside this non-uniform branch, so pixelUV comes from main) + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec4 t = textureLod(raindropsatlas, tileOffset(choice) + local * 0.5, lod); + + // fine specks: fainter and lighter than the big bugs (the splat bodies are nearly black) + t.rgb = mix(t.rgb, vec3(0.42, 0.34, 0.16), lightMix); + float a = clamp(t.a * appear * bugs_opacity * opacityMul, 0.0, 1.0); + + // the scene blurred only where the bug is see-through (half transparent), not around it and not where it's opaque + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); + float seeThrough = smoothstep(0.03, 0.3, a) * (1.0 - smoothstep(0.75, 0.95, a)); + smear = max(smear, seeThrough * haloStrength * pxScale); + + // relief: tangent-space normal of the splat -> glass UV frame (undo the mirror, then the rotation) + vec4 nm = textureLod(normalmap, tileOffset(choice) + local * 0.5, lod); + vec2 nxy = (nm.rg * 2.0 - 1.0) * bugs_bump * appear; // a splat that is still settling is flatter + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // "over" compositing in premultiplied form + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; + } + } +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; // tangent frame of the glass (T along u, B along v) + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); + // No discard on a (nearly) clear glass texture: clean glass between patches of faint dirt would + // otherwise be "bald" - no bugs, no halo. + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); // uniform control flow here + vec2 aspect = (bugs_uv_aspect >= 1.0) ? vec2(bugs_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(bugs_uv_aspect, 0.01)); + + // 0 = never dirty yet; the real per-cell progress is computed in bugLayer (wipers reset it) + float progress = clamp(max(rain_wind.w, 0.0) / max(bugs_fill_time, 1.0), 0.0, 1.0); + + vec3 bugRGB = vec3(0.0); // premultiplied + float bugA = 0.0; + float smear = 0.0; // blur ring around the bugs + vec3 bugN = vec3(0.0); // normals of the splats, premultiplied like the colour + float bugNA = 0.0; + if (progress > 0.0) + { + // fine specks underneath (procedural, one wiper read for the pixel), big bugs on top + if (specks_density > 0.0) + { + float bugsPix = 0.0; + float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord, bugsPix) : WIPER_NONE; + speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, bugsPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); + } + bugLayer(gridSize, bugs_density, 3u, pixelUV, aspect, 1.0, 1.0, 0.0, bugRGB, bugA, smear, bugN, bugNA); + // now and then a really big one, on top (its own coarse grid: same 3x3 search, bigger cells) + if (bugs_giant_density > 0.0) + bugLayer(gridSize / max(bugs_giant_scale, 1.0), bugs_giant_density, 11u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + // and rarely a huge one (about one per pane when it is fully dirty) + if (bugs_huge_density > 0.0) + bugLayer(gridSize / max(bugs_huge_scale, 1.0), bugs_huge_density, 13u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + } + + // Bugs over the glass (premultiplied "over") + float glassA = tex_color.a * alpha_mult; + float finalA = bugA + glassA * (1.0 - bugA); + vec3 premult = bugRGB + tex_color.rgb * glassA * (1.0 - bugA); + vec3 albedo = premult / max(finalA, 1e-4); + + // Reflections / specular belong to the glass only, not to the bugs + float glassShare = glassA * (1.0 - bugA) / max(finalA, 1e-4); + + vec3 fragcolor = ambient; + // Relief of the splats: tilt the glass normal by the splat's slope (the tilt direction is physical, + // so it does not matter which way the mesh normal points); flat where there is no bug. + vec3 bugDir = bugN + vec3(0.0, 0.0, 1.0) * (1.0 - bugNA); + vec3 fragnormal = Ngl; + if (bugNA > 0.001) + fragnormal = normalize(Ngl * max(bugDir.z, 0.05) + Tgl * bugDir.x + Bgl * bugDir.y); + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + + bugs_gloss * bugA; // wet splats catch the sun and the headlights + legacy_gloss(); + + // Lit by sun, ambient and headlights like everything else (bugs glow in oncoming beams) + // most of the glass is clear (no bug, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + vec3 lit = apply_fog(fragcolor); + +#if BUGS_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + +#if BUGS_DEBUG_TIME + // Calibration: paints floor(time) as 8 red digits across the glass (the shader's own clock, in seconds). + // Read the number right after the scenario has loaded and put it into bugs_start_time. + { + const int SEG[10] = int[10](63, 6, 91, 79, 102, 109, 125, 7, 127, 111); + float dx = (f_coord.x - 0.10) / 0.10; + float dy = (f_coord.y - 0.42) / 0.08; + int idx = int(floor(dx)); + if (idx >= 0 && idx < 8 && dy >= 0.0 && dy <= 2.0) + { + float tt = floor(max(time, 0.0)); + float div = pow(10.0, float(7 - idx)); + int dig = int(mod(floor(tt / div), 10.0)); + vec2 q = vec2(fract(dx) / 0.8, dy); + int m = SEG[dig]; + bool on = false; + if ((m & 1) != 0 && q.y > 1.86 && q.x > 0.1 && q.x < 0.9) on = true; // a + if ((m & 2) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 1.0 && q.y < 1.9) on = true; // b + if ((m & 4) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 0.1 && q.y < 1.0) on = true; // c + if ((m & 8) != 0 && q.y < 0.14 && q.x > 0.1 && q.x < 0.9) on = true; // d + if ((m & 16) != 0 && q.x < 0.14 && q.y > 0.1 && q.y < 1.0) on = true; // e + if ((m & 32) != 0 && q.x < 0.14 && q.y > 1.0 && q.y < 1.9) on = true; // f + if ((m & 64) != 0 && q.y > 0.93 && q.y < 1.07 && q.x > 0.1 && q.x < 0.9) on = true; // g + if (on) + out_color = vec4(1.0, 0.05, 0.05, 1.0); + } + } +#endif + + if (MOTIONBLUR_ENABLED) + { + // alpha 0 = blending keeps the scene's own motion vectors + // only the see-through parts of the bugs (smear); no blur over opaque parts of the pane (1 - glassA) + float blurMask = clamp(smear * bugs_halo_blur * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + out_motion = (blurMask >= 0.01) ? vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0) : vec4(0.0); + } +} diff --git a/shaders/ogl46/mat_pbr.frag b/shaders/ogl46/mat_pbr.frag new file mode 100644 index 000000000..9d40e024e --- /dev/null +++ b/shaders/ogl46/mat_pbr.frag @@ -0,0 +1,3 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "mat_pbr.glsl" diff --git a/shaders/ogl46/mat_pbr.glsl b/shaders/ogl46/mat_pbr.glsl new file mode 100644 index 000000000..744fd2058 --- /dev/null +++ b/shaders/ogl46/mat_pbr.glsl @@ -0,0 +1,65 @@ +// the materials of the metallic and roughness workflow, which take the textures the way the texturing tools export them: +// diffuse the base colour (sRGB), the opacity in its alpha +// normalmap the normals of the tangent space in the red and green, with the green pointing up the texture (the opengl +// convention) +// orm the occlusion of the ambient light in the red, the roughness in the green and the metalness in the blue, the +// packing of unreal engine and gltf. without the texture: no occlusion, roughness: alone, no metal +// emissive the light the surface emits (sRGB), whatever falls on it. without the texture: none +// and the parameters +// specular the specular level of the parts which aren't metal, 1 for the reflectance of 4% (the level 0.5 of the tools) +// reflection how much of the reflected surroundings is the environment map and the scene, the rest the ambient light +// emissive scales the emissive texture +// roughness scales the roughness of the texture +// +// mat_pbr.frag and its variants are this file with what the variant adds, picked by a define before the include: +// PBR_DETAIL a second normal map (detailnormalmap) repeated detail_scale times over the first, of the strength +// detail_height_scale +// PBR_PARALLAX the height of the surface (height: white the highest) shifts the textures by height_scale +// PBR_COAT a clear varnish over the surface: coat scales how much of it there is (the red of coatmap), coat_roughness +// is added to its roughness (the green of coatmap). without the texture: varnish all over, as smooth as +// coat_roughness says +// the variant declares its own textures and parameters before the include: every #pragma texture and #pragma param in a +// file is read, whatever #ifdef it is in +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 8) in mat3 f_tbn; + +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; +#ifdef PBR_PARALLAX +layout(location = 6) in vec3 TangentFragPos; +#endif + +#include "common.glsl" + +layout(location = 0) out vec4 out_color; +layout(location = 1) out vec4 out_motion; + +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, one) +#pragma param(reflection, 1, 2, 1, one) +#pragma param(emissive, 1, 3, 1, one) +#pragma param(roughness, 2, 0, 1, one) + +#pragma texture(diffuse, 0, sRGB_A) +layout(binding = 0) uniform sampler2D diffuse; + +#pragma texture(normalmap, 1, RGBA) +layout(binding = 1) uniform sampler2D normalmap; + +#pragma texture(orm, 2, RGBA, yellow) +layout(binding = 2) uniform sampler2D orm; + +#pragma texture(emissive, 3, sRGB_A, black) +layout(binding = 3) uniform sampler2D emissive; + +// lit as the tools show the surface, see light_common.glsl +#define PBR_SURFACE +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" + +// the same file for both renderers +#include "mat_pbr_surface.glsl" diff --git a/shaders/ogl46/mat_pbr_coat.frag b/shaders/ogl46/mat_pbr_coat.frag new file mode 100644 index 000000000..2044827e6 --- /dev/null +++ b/shaders/ogl46/mat_pbr_coat.frag @@ -0,0 +1,12 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// a clear varnish over the surface, see mat_pbr.glsl +#define PBR_COAT +// param[2].w is the roughness of the varnish, not the weathering +#define NO_WEATHERING +#pragma param(coat, 2, 1, 1, one) +#pragma param(coat_roughness, 2, 3, 1, zero) + +#pragma texture(coatmap, 4, RGBA, red) +layout(binding = 4) uniform sampler2D coatmap; +#include "mat_pbr.glsl" diff --git a/shaders/ogl46/mat_pbr_detail.frag b/shaders/ogl46/mat_pbr_detail.frag new file mode 100644 index 000000000..ba5120166 --- /dev/null +++ b/shaders/ogl46/mat_pbr_detail.frag @@ -0,0 +1,10 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// a second normal map repeated over the first, see mat_pbr.glsl +#define PBR_DETAIL +#pragma param(detail_scale, 2, 1, 1, one) +#pragma param(detail_height_scale, 2, 2, 1, one) + +#pragma texture(detailnormalmap, 4, RGBA) +layout(binding = 4) uniform sampler2D detailnormalmap; +#include "mat_pbr.glsl" diff --git a/shaders/ogl46/mat_pbr_parallax.frag b/shaders/ogl46/mat_pbr_parallax.frag new file mode 100644 index 000000000..4133f3515 --- /dev/null +++ b/shaders/ogl46/mat_pbr_parallax.frag @@ -0,0 +1,9 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// the height of the surface shifts the textures, see mat_pbr.glsl +#define PBR_PARALLAX +#pragma param(height_scale, 2, 1, 1, zero) + +#pragma texture(heightmap, 4, R) +layout(binding = 4) uniform sampler2D heightmap; +#include "mat_pbr.glsl" diff --git a/shaders/ogl46/mat_pbr_surface.glsl b/shaders/ogl46/mat_pbr_surface.glsl new file mode 100644 index 000000000..a94293c77 --- /dev/null +++ b/shaders/ogl46/mat_pbr_surface.glsl @@ -0,0 +1,115 @@ +// the fragment stage of the pbr materials, see mat_pbr.glsl. the same file for the opengl and the vulkan renderer: the +// textures, the inputs and the outputs are declared by the files which include it + +#ifdef PBR_PARALLAX +// the depth of the surface below its highest points, 0..1: the height map holds the height, white the highest +float parallax_depth(vec2 coord, vec2 dcoorddx, vec2 dcoorddy) +{ + return 1.0 - textureGrad(heightmap, coord, dcoorddx, dcoorddy).r; +} + +// the texture coordinates of the point of the surface the view finds, with the surface sunk below the geometry by its depth +// (param[2].y: the depth of the black of the height map, as a share of the size of the texture). Viewdir: the direction +// to the eye in the tangent space +vec2 parallax_coord(vec2 coord, vec3 viewdir) +{ + float range = length(f_pos.xyz); + if (range > 100.0) + return coord; + // gradients of the coordinates taken here: inside the loop the fragments of a quad don't go the same way + vec2 dcoorddx = dFdx(coord); + vec2 dcoorddy = dFdy(coord); + // the shift fades out before the distance it stops at, so it doesn't switch off at once there + vec2 shift = viewdir.xy * (param[2].y * (1.0 - smoothstep(80.0, 100.0, range))); + + if (false == EXTRAEFFECTS_ENABLED) + { + // one step: the depth at the point seen, taken for the depth of the point found + return coord - shift * parallax_depth(coord, dcoorddx, dcoorddy); + } + + // the ray is followed down through layers of the depth, more of them at grazing angles and close by, until it gets below the + // surface; the point is then found between the last two steps + float layers = mix(32.0, 8.0, clamp(min(abs(viewdir.z), range / 20.0), 0.0, 1.0)); + float layerdepth = 1.0 / layers; + vec2 stride = shift / layers; + vec2 current = coord; + float found = parallax_depth(current, dcoorddx, dcoorddy); + float reached = 0.0; + while (reached < found) + { + current -= stride; + found = parallax_depth(current, dcoorddx, dcoorddy); + reached += layerdepth; + } + vec2 previous = current + stride; + float after = found - reached; + float before = parallax_depth(previous, dcoorddx, dcoorddy) - reached + layerdepth; + float weight = after / min(after - before, -1e-5); + return mix(current, previous, clamp(weight, 0.0, 1.0)); +} +#endif + +// the normal of the tangent space a normal map holds in its red and green +vec3 unpack_normal(vec2 texel) +{ + vec2 xy = texel * 2.0 - 1.0; + return vec3(xy, sqrt(1.0 - clamp(dot(xy, xy), 0.0, 1.0))); +} + +void main() +{ + vec2 coord = f_coord; +#ifdef PBR_PARALLAX + coord = parallax_coord(f_coord, normalize(-TangentFragPos)); +#endif + + vec4 tex_color = texture(diffuse, coord); + + bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + if(alphatestfail) + discard; + + vec3 fragcolor = ambient; + + vec3 normal = unpack_normal(texture(normalmap, coord).rg); +#ifdef PBR_DETAIL + // the detail tilts the normal further (the whiteout blend of the two) + vec3 detail = unpack_normal(texture(detailnormalmap, coord * param[2].y).rg); + normal = vec3(normal.xy + detail.xy * param[2].z, normal.z * detail.z); +#endif + vec3 fragnormal = normalize(f_tbn * normalize(normal)); + + vec3 surface = texture(orm, coord).rgb; + pbr_occlusion = surface.r; + pbr_roughness = surface.g * param[2].x; + metalic = surface.b; + pbr_emission = texture(emissive, coord).rgb * param[1].w; +#ifdef PBR_COAT + vec2 varnish = texture(coatmap, coord).rg; + coat_weight = varnish.r * param[2].y; + coat_roughness = varnish.g + param[2].w; +#endif + // the specular level of the tools: 0.5 is the reflectance of 4% + float specularity = 0.5 * param[1].y; + float reflectivity = param[1].z; + + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + + vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + if (POSTFX_ENABLED) + { + out_color = color; + } + else + { + out_color = tonemap(color); + } + if (MOTIONBLUR_ENABLED) + { + vec2 a = (f_clip_future_pos.xy / f_clip_future_pos.w) * 0.5 + 0.5; + vec2 b = (f_clip_pos.xy / f_clip_pos.w) * 0.5 + 0.5; + + out_motion = vec4(a - b, 0.0f, 0.0f); + } +} diff --git a/shaders/ogl46/mat_rain_windscreen.frag b/shaders/ogl46/mat_rain_windscreen.frag index 91ed0ad96..903b81f23 100644 --- a/shaders/ogl46/mat_rain_windscreen.frag +++ b/shaders/ogl46/mat_rain_windscreen.frag @@ -1,29 +1,48 @@ #version 460 core #define STAGE_FRAGMENT 1 -// Windshield rain and snow -// by @lcddisplay; wiper movement @MichauSto; water on the glass rewritten as a model of drops lying on it +// Windshield rain effects - v3 (rewrite) +// by @lcddisplay; wiper movement @MichauSto; rain v3: drop layers, drop life, rivulets that sweep drops // -// the material: the textures diffuse (the glass) and wipermask (a blade per channel, r g b a: 0 where it doesn't reach, elsewhere -// the place of the blade over its sweep, 0 at rest .. 1 at the far end, at which it goes over the place). raindropsatlas and -// raindrop_grid_size aren't used any more, they stay so the materials which name them still load. rain_scale (1 when not given) -// scales the drops and the flakes. water_slot is given by the renderer (1 + the glass of the simulation, 0 none), not by the -// material. the block of the scene: rain_params (x: how heavy the rain or snow is, z: 1 for snow, w: temperature of the air), -// wiper_pos, wiper_timer_out, wiper_timer_return (the blades of the vehicle of the camera) and rain_wind (the air against it). +// What is on the glass: +// 1. Micro droplets: a dense grid of tiny, static droplets. Procedural (no texture reads): a spherical cap +// per droplet. They make the glass look wet between the bigger drops. +// 2. Drops: one per grid cell (raindrop_grid_size), shape from the 2x2 drop tiles of the atlas +// (normalmap: rg = normal xy, b = height, a = mask). A drop lands (quick pop), sits still for +// drop_life_min..drop_life_max seconds, then makes room for a new one. Drops do NOT slide: all motion is +// done by the rivulets (a sliding drop used to leave its 3x3 neighbourhood and got cut off). +// Sizes are skewed (many medium, few big) and the tiles are randomly mirrored (8 shapes instead of 4). +// Where drops overlap, the higher one wins (no averaged "ghost" normals). +// 3. Rivulets: a drop runs down in stick-slip fashion and leaves a wet trail (4 sprites in the right half +// of the atlas, 256 x 1024: head in the bottom STREAK_HEAD_FRAC, trail above). The head sweeps up every +// drop and droplet on its way: the trail band is clean until the rivulet fades out. +// The trail right above the head is taken from the sprite part that touches the head, then it blends +// into the trail pattern that is fixed to the glass (beads stay where they were left). // -// the glasses of the cab of the train are simulated (gfx::windscreen_water, water_*.comp, water.glsl): the raindrops land as often -// as the rain hits the glass, splashing; the drops lie held by surface tension until gravity and the drag of the air pull them -// harder, then slide in stops and goes, wetting their paths (the next ones follow them into rivulets) and leaving droplets behind; -// the drops which touch flow together; the blades take the water along, gather it into a bead and leave it at the ends of their -// sweep, where it runs down; the flakes stick and melt. here the drops of the simulation are drawn where the fragment is, and the -// wetted paths as a thin film. elsewhere (the windows of other vehicles, a glass the simulation has no room for) the water is made -// up from the time alone: drops landing, growing and sliding along tracks, the blades pushing a ridge and leaving the water at the -// edge of their sweep. +// Speed: the hashes and the life cycles of the cells (which drop a cell holds now, where, how big; where the head of a rivulet is) +// are worked out once a frame for every cell by rain_cells.comp (rain_cells.glsl), not here for the 9 cells around every pixel; +// the wipers are asked only for the drops the pixel lies on. the look is the same. // -// the water is a field of soft kernels (metaballs): drops coming close flow together, and a drop is a few kernels, so the drops -// are of many shapes. a drop is a lens holding a sharp picture of the place around it turned over (the image of the last frame -// where the screen holds it, the sky and the ground elsewhere), its edge shows the light of the sky reflected inside it; the lamps -// and the headlights light the water up; the film the blades leave breaks up behind them and the lights seen through it are drawn -// into lines towards their pivot; the wet glass is a little milky +// Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the +// pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. +// +// Refraction / blur (OpenGL 4.6, the renderer with the screen space reflections): the glass reads the image of the last +// frame the renderer keeps for the reflections (ssr_history, with mipmaps) and the depth of the scene (scene_depth): +// - drops act as small lenses: the pixel shows the scene on the opposite side of the drop centre, so every drop holds a +// small, flipped picture (drop_lens); rivulets bend the view by Snell's law from their normal, +// - bright lights near a drop (signals, lamps, headlights) show up in it, +// Works standing still, with the motion blur off and with taa. Needs gfx.ssr (default: medium); without it the drops show +// the sky / ground only, faintly. +// The haze of the wet glass is blurred by the post-processing, from the picture of this frame: the glass writes a request +// into the velocity target (x = 64 * strength, y = 0) and postfx_taa.frag (with gfx.antialiasing taa: every frame) or +// postfx_motionblur.frag (without it: only while something moves) blur the picture there (rain_windscreen_haze.glsl). +// +// Speed: the air against the vehicle (rain_wind) drives the water: at speed a second layer of rivulets runs along its push +// (up a front glass, back along a side window) and sweeps the drops up on its way, the drops are stretched along the push, +// the haze grows. Standing still the rain is as it always was. +// +// OpenGL 4.6 renderer (feat/gl46-migration): headlights and lamps are clustered, calc_headlights takes the +// screen-space derivatives of f_pos, the sun glint follows the cloud shadow. Lamps (cab lamp, scenery) light up +// the drops too (drop_lamp_scatter). layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; @@ -37,1176 +56,1096 @@ layout(location = 1) out vec4 out_motion; #pragma texture(diffuse, 0, sRGB_A) #pragma texture(raindropsatlas, 1, sRGB_A) #pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; 2048 x 1024 (drops left, rivulets right), linear #pragma param(color, 0, 0, 4, diffuse) #pragma param(diffuse, 1, 0, 1, diffuse) #pragma param(specular, 1, 1, 1, specular) #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) #pragma param(raindrop_grid_size, 2, 0, 1, one) -#pragma param(rain_scale, 2, 1, 1, one) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" -#include "water.glsl" +#include "random.glsl" +#include "rain_cells.glsl" layout(binding = 0) uniform sampler2D diffuse; layout(binding = 1) uniform sampler2D raindropsatlas; layout(binding = 2) uniform sampler2D wipermask; +layout(binding = 3) uniform sampler2D normalmap; -const float RW_PI = 3.14159265; -// refractive index of water -const float RW_IOR = 1.333; -// the falling particles (particles_precipitation.comp, rendering/common/gpuparticles.cpp): the diameters of the flakes, metres, -// and how fast the rain and the snow fall, m/s -const vec2 RW_SNOW_DIAMETER = vec2(0.004, 0.012); -const float RW_RAIN_FALL = 7.0; -const float RW_SNOW_FALL = 1.1; -// a drop is a lens: it holds a sharp picture of the place around it, turned over through its middle, RW_LENS times as far out -// as the fragment is from the middle (and as much smaller), with this share of the bending of the view by the surface on top -const float RW_LENS = 2.0; -const float RW_LENS_BEND = 0.15; -// the drag of the air going along the glass: the speed at which it equals the weight of a drop, m/s; and the share of the air -// meeting the glass head on which turns up along it. so the water goes up a glass the sooner the more it leans back: on a -// vertical glass at about 250 km/h, leaning 20 degrees at about 130 km/h, 45 degrees at about 80 km/h -const float RW_DRAG_SPEED = 24.0; -const float RW_HEAD_ON = 0.35; -// the water is a field summed from soft kernels (metaballs) and its surface is where the field is RW_SURFACE: drops which come -// close flow together the way surface tension pulls them. a kernel alone reaches the surface at RW_EDGE of its radius -const float RW_SURFACE = 0.25; -const float RW_EDGE = 0.61; +// --- Haze of the wet glass (blur) ------------------------------------------------ +// The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). +const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds, more at speed) from nothing up to +// its full strength, in any rain (a lighter rain takes longer). where no wiper reaches it is full +const float haze_fill = 12.0; // rain fallen since the blade to mist the glass up fully: seconds of the heaviest + // rain standing still (2x as long at 1.5; the speed counted in by the game) +const float haze_curve = 1.0; // > 1: slow at first, then more and more +const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl -// the glass at the fragment: the view space steps along it for a step of the coordinates of the glass (metres along the axes -// of the model, see main()), and the size of a pixel on it, metres -vec3 rw_tu; -vec3 rw_tv; -float rw_pixel; +// --- How the water gathers on the glass ------------------------------------------------------------------ +// the game counts the rain the glass meets (rain_state, gl::scene_ubs; more at speed) and how wet the glass is (0 dry .. 1 as full +// of drops as it gets): the glass fills up to the full in any rain, a lighter one only takes longer, and dries when the rain stops. +// the times are in the game (fill_rate, fill_speed, dry_halflife in the setup of the scene block). where a blade went over the glass +// the drops come back with the rain fallen since -// how the water on the glass behaves here, set by main() -float rw_scale; // size of the drops (param rain_scale) -float rw_since; // seconds since a blade last cleaned the place -float rw_period; // seconds between the small drops landing on a place of one -float rw_grow; // seconds the drops need after a wipe to grow big enough to slide -float rw_rate; // how fast the glass gathers the rain against a standing vertical glass in the heaviest rain -float rw_push; // the force on a drop along the glass, in units of its weight -vec2 rw_down; // the way gravity pulls along the glass (coordinates of the glass, unit) -vec2 rw_flow; // the way the air goes along the glass (unit, 0 in still air) +// --- Drops (atlas tiles) ------------------------------------------------------ +// (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) -// the field of the water: the sum of the kernels, its gradient along the glass (view space) and the sums for the mean radius of -// the drops it is made of -float rw_field = 0.0; -vec3 rw_fgrad = vec3(0.0); -float rw_fsize = 0.0; -float rw_fweight = 0.0; +// --- Micro droplets ------------------------------------------------------------- +const float micro_density = 0.45; // share of micro cells holding a droplet on a full glass, 0 = off +const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale +const float micro_size_min = 0.12; // droplet radius in micro cells +const float micro_size_max = 0.40; +const float micro_bulge = 0.80; // slope of the droplet dome at its rim (0..0.95) +const float micro_life = 60.0; // average seconds a droplet lives -// the water at the fragment: the thickness of the highest water there (metres), its gradient (view space), the radius of the -// curvature of its surface (metres: how much it bends the view across a pixel) and how much of the pixel it covers -float rw_height = 0.0; -vec3 rw_slope = vec3(0.0); -float rw_curve = 1.0; -float rw_cover = 0.0; -// from the middle of the drop which gives the water to the fragment (view space, metres), 0 for spread water -vec3 rw_offset = vec3(0.0); -// the last time the water a blade pushes went over the fragment, taking the drops lying there with it -float rw_cleared = -1.0e9; +// --- Look of the drops (grey atlas for drops / rivulets, the same look computed for micro droplets) --------- +const float drop_rim_start = 0.30; // micro droplets: dome slope (1 - nz) where the bright rim starts +const float drop_rim_end = 0.80; // ... and where it is fully bright +const float drop_light_side = 0.25; // micro droplets: brighter on the upper-left side +const float drop_center_alpha = 0.25; // how much the dark middle of a drop covers the scene +const float drop_rim_alpha = 0.85; // how much the bright rim covers the scene +const float drop_shade_alpha = 0.30; // faint alpha over the whole dome (carries the glints) -uvec4 rw_pcg4d(uvec4 v) +// --- Light on the drops -------------------------------------------------------- +const float drop_ior = 1.33; // refraction index of water +const float drop_refract = 0.5; // rivulets: strength of the picture shift (Snell; 1 = physical) +const float drop_lens = 2.0; // drops: lens field, the drop shows (1 + drop_lens) x its own size, flipped +const float drop_lens_mix = 0.7; // drops: 1 = lens picture, 0 = Snell shift like the rivulets +const float drop_env = 0.6; // reflection of the environment on the dome (0 = off) +const float drop_glint_strength = 5.0; // sun / moon glint brightness +const float drop_glint_sharpness = 40.0; // sun / moon glint size (lower = a wider lobe, so more drops catch it) +const float drop_sheen = 0.3; // wide, soft sun sheen on the domes around the sharp glint +const float drop_headlight_scatter = 3.0; // how much drops light up in headlight beams +const float drop_lamp_scatter = 1.0; // GL 4.6: how much drops light up from lamps (station lamps, signals), 0 = off +const float drop_light_near = 4.0; // lights nearer than this (metres; the own vehicle) don't light the drops, full from 2x +const float drop_light_max = 3.0; +const float drop_dark_lum = 0.25; // average brightness of the screen (scene units) below which the drops darken with it // the most the lamps and headlights add to a drop (scene units, before tonemapping) + +// --- Rivulets (drops that run down and leave a wet trail) --------------------------------- +// Sizes are in "drop cells" (1 cell = 1 / raindrop_grid_size of the glass UV). +const float streak_density = 1.00; // share of cells carrying a rivulet (scaled by the rain intensity), 0 = off +const float streak_cell = 6.0; // width of a rivulet cell in drop cells +const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet +const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) +const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) +const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail +const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off +const float streak_uv_aspect = 1.0; // glass width / height in UV terms (1 = same stretch as the drops) +const float streak_sweep = 1.0; // 1 = the head sweeps up drops on its way (clean band behind it), 0 = off +const float streak_sweep_width = 0.9; // width of the swept band, in head widths +const float streak_link = 1.5; // head widths above the head where the trail is taken from the sprite part + // that touches the head (so the trail always leaves the head cleanly) + +// --- Speed: the air against the vehicle (rain_wind) drives the water on the glass -------------------- +// The force on the water along the glass: its weight (gravity) and the drag of the air going along the glass (and of the +// share of the air meeting it head on which turns up along it), as in the stock shader of the renderer. Standing still +// (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. +const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a + // vertical front glass the water would go up only at ~250 km/h) +const float wind_streaks = 1.5; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.5; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 1.2; // ... and their runs this long against those of gravity: few drops with long trails +const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) +const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) +const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s +const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it +const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a + // curved glass, where every triangle would turn them a little) + +// --- The rivulets of the air of different thickness: the width of every one is drawn from this range (x streak_head, x +// wind_head_scale), most of them thin, a few thick (never wider than their cell) ------------------------------------------------- +const float streak_thin = 0.5; // the thinnest +const float streak_thick = 2.0; // the thickest +const float streak_thick_bias = 2.0; // > 1: more thin ones +// --- What the blades leave: they don't take every drop (a few stay where they were): wiper_miss of rain_cells.glsl ----------------- + +#ifndef STREAK_FLIP_Y +#define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) +#endif +const float STREAK_TAIL_SCALE = 1.5; // the trail pattern of the sprite is drawn this much longer than native +const float STREAK_HEAD_FRAC = 0.22; // part of the sprite height used by the drop head (= HEAD_FRAC of the atlas generator) + +const float WS_INSIDE = 0.3; // metres beyond the glass nearer than which the image is taken for the inside of the cab + // (in the rain the cab isn't in the depth: the nose of the own vehicle is outside) +const float WS_REFR_MAXPX = 96.0; // largest picture shift of a drop, screen pixels +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) +const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it + +// measuring what costs what (the time of "colour, translucent and cab" with each): 0 everything (as in the game), 1 the drops not lit +// (no sun glint, lamps, reflection), 2 no rivulets (and nothing swept by them), 3 no micro droplets, 4 no drops of the atlas, +// 5 none of the rain (only the glass and the haze) +#ifndef WS_PROFILE +#define WS_PROFILE 0 +#endif + +const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) + +// the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, +// the ground below it, blurred by Lod (as in the stock mat_rain_windscreen.frag) +vec3 wsSurroundings(vec3 direction, float lod) { - v = v * 1664525u + 1013904223u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - v ^= v >> 16u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - return v; + vec3 world = mat3(inv_view) * direction; + vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); + float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); + if ((below <= 0.0) || (false == ENVMAP_ENABLED)) + return sky; + return mix(sky, reflection_ground(), below); } -// four numbers 0 .. 1 of a cell of a layer -vec4 rw_random(ivec2 cell, uint layer, uint index) +// what is seen through the glass in a view space direction: the image of the last frame where it holds the place, Distance +// away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. Fade: towards the edges of the +// image the surroundings take over. The inside of the cab (near the camera in the depth) is never taken: the surroundings +// stand for it (else the drops would show the dark walls of the cab) +vec3 wsBehind(vec3 direction, float lod, float distance, out float share, bool fade) { - return vec4(rw_pcg4d(uvec4(uvec2(cell), layer, index))) * (1.0 / 4294967296.0); + share = 0.0; + vec3 around = wsSurroundings(direction, lod); + if (ssr_params.x < 1.0) + return around; + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return around; + vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; + vec2 edges = min(coords, 1.0 - coords); + share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); + coords = clamp(coords, vec2(0.0), vec2(1.0)); + if (share <= 0.0) + return around; + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; + float near = projection[3][2]; + if ((depth > 0.0) && (near / depth < -f_pos.z + WS_INSIDE)) + { + share = 0.0; + return around; + } + vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; + if (any(isnan(color)) || any(isinf(color))) + { + share = 0.0; + return around; + } + return mix(around, max(color, vec3(0.0)), share); } -float rw_noise(float x, uint layer) +float wsLum(vec3 c) { - float i = floor(x); - float f = x - i; - float a = rw_random(ivec2(int(i), 0), layer, 7u).x; - float b = rw_random(ivec2(int(i) + 1, 0), layer, 7u).x; - return mix(a, b, f * f * (3.0 - 2.0 * f)); + return dot(c, vec3(0.2126, 0.7152, 0.0722)); } -// value noise 0 .. 1 (x) with its gradient (yz) -vec3 rw_noise2(vec2 p, uint layer) +// bright lights near a drop (signals, lamps, headlights): a drop is a wide-angle lens and picks them up. A light is where a +// fine mip level of the image (~11 px around) is much brighter than a coarse one (~90 px around) +vec3 wsLightGlow(vec3 direction, float distance) { - vec2 i = floor(p); - vec2 f = p - i; - vec2 u = f * f * (3.0 - 2.0 * f); - vec2 du = 6.0 * f * (1.0 - f); - ivec2 c = ivec2(i); - float a = rw_random(c, layer, 8u).x; - float b = rw_random(c + ivec2(1, 0), layer, 8u).x; - float d = rw_random(c + ivec2(0, 1), layer, 8u).x; - float e = rw_random(c + ivec2(1, 1), layer, 8u).x; - float k1 = b - a; - float k2 = d - a; - float k4 = a - b - d + e; - return vec3(a + k1 * u.x + k2 * u.y + k4 * u.x * u.y, du * vec2(k1 + k4 * u.y, k2 + k4 * u.x)); -} - -// P turned by A (radians). every set of drops is laid on its own grid, turned and shifted against the others, so the drops line -// up neither with each other nor along the glass -vec2 rw_turn(vec2 p, float a) -{ - float c = cos(a); - float s = sin(a); - return vec2(c * p.x - s * p.y, s * p.x + c * p.y); -} - -// a gradient given along the coordinates of the glass, view space -vec3 rw_along(vec2 gradient) -{ - return rw_tu * (gradient.x / dot(rw_tu, rw_tu)) + rw_tv * (gradient.y / dot(rw_tv, rw_tv)); -} - -// the gradient along the glass (view space) of a value of the fragments, from how it changes from pixel to pixel; Dpdx, Dpdy: -// the steps of the position, Normal: of the glass -vec3 rw_gradient(float value, vec3 dpdx, vec3 dpdy, vec3 normal) -{ - vec3 r1 = cross(dpdy, normal); - vec3 r2 = cross(normal, dpdx); - float det = dot(dpdx, r1); - float dx = dFdx(value); - float dy = dFdy(value); - return (abs(det) > 1e-14) ? (dx * r1 + dy * r2) / det : vec3(0.0); -} - -// a kernel of the water, Offset (view space) from its centre to the fragment: alone it makes water of the radius Visible, -// Weight 1 .. 0 as it goes. water smaller than a pixel would only flicker, it is left to the haze of the wet glass -void rw_kernel(vec3 offset, float visible, float weight) -{ - if ((weight <= 0.0) || (visible < 0.5 * rw_pixel)) - return; - // a drop a pixel or two across is grain rather than a lens: it fades into the haze of the wet glass - weight *= smoothstep(0.5 * rw_pixel, 2.0 * rw_pixel, visible); - float support = visible / RW_EDGE; - float q = dot(offset, offset) / (support * support); - if (q >= 1.0) - return; - float k = 1.0 - q; - float k3 = weight * k * k * k; - rw_field += k3; - rw_fgrad += offset * (-6.0 * weight * k * k / (support * support)); - rw_fsize += k3 * visible; - rw_fweight += k3; -} - -// a kernel at the Offset in the coordinates of the glass -void rw_blob(vec2 offset, float visible, float weight) -{ - rw_kernel(offset.x * rw_tu + offset.y * rw_tv, visible, weight); -} - -// a drop lying on the glass: a few kernels, sagging down the glass and lopsided as Shape (random 0 .. 1) says -void rw_drop(vec2 offset, float visible, float weight, vec4 shape) -{ - rw_blob(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec2 side = vec2(-rw_down.y, rw_down.x); - vec2 sag = (rw_down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_blob(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_blob(offset - vec2(cos(angle), sin(angle)) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// water spread over the glass (a film, a ridge): its thickness, the gradient of it (view space), the radius of the curvature of -// its surface and how much of the pixel it covers -void rw_sheet(float thickness, vec3 slope, float curve, float cover) -{ - if (cover <= 0.0) - return; - rw_cover = max(rw_cover, cover); - if (thickness > rw_height) - { - rw_height = thickness; - rw_slope = slope; - rw_curve = curve; - rw_offset = vec3(0.0); - } -} - -// the surface of the water of the field: a drop is a cap of a sphere, flat lens of the contact angle Contact (radians) the water -// makes with the glass. how far across a drop the fragment is follows from the field (inverting the kernel), the height and -// the slope of the cap from that: the slope rises slowly from the middle and steeply only close to the edge, where it reaches -// the contact angle; where drops flowed together the field is above that of a drop alone and the water is flat. the edge is -// antialiased by how fast the field changes across a pixel -void rw_settle(float contact) -{ - if (rw_field <= 0.5 * RW_SURFACE) - return; - float gradient = length(rw_fgrad); - float cover = clamp((rw_field - RW_SURFACE) / max(gradient * rw_pixel, 1e-3) + 0.5, 0.0, 1.0); - if (cover <= 0.0) - return; - float mean = rw_fsize / max(rw_fweight, 1e-12); - // 0 in the middle of a drop, 1 at its edge - float across = min(sqrt(max(1.0 - pow(min(rw_field, 1.0), 1.0 / 3.0), 0.0)) / RW_EDGE, 1.0); - float s = sin(contact); - float rs = across * s; - float root = sqrt(max(1.0 - rs * rs, 1e-4)); - float sphere = mean / s; - vec3 slope = (gradient > 1e-9) ? rw_fgrad * ((rs / root) / gradient) : vec3(0.0); - float height = max(sphere * (root - cos(contact)), 0.0); - bool top = height > rw_height; - rw_sheet(height, slope, sphere, cover); - // the field rises towards the middle of the drop - if (top && (gradient > 1e-9)) - rw_offset = rw_fgrad * (-across * mean / gradient); -} - -// the blades. a channel of the mask of the wipers is a blade: 0 where it doesn't reach, elsewhere the place of the blade over its -// sweep (0 at rest .. 1 at the far end) at which it goes over the place. wiper_pos: where the blade is (0 .. 1 on its way out, -// 1 + where it is on its way back), wiper_timer_out / _return: the last time it lay at its start / was at its far end -struct rw_wipe_s -{ - float since; // seconds since a blade last went over the place (large where none reaches) - float ahead; // 0 .. 1, how close in front of a moving blade the place is (the water the blade pushes) - float front; // how far in front of the nearest moving blade the place is, units of the mask (1 where none) - float swept; // 0 .. 1, how much of its way the blade in front did, the water it gathered on the way - float working; // 0 .. 1, the blades went lately -}; - -rw_wipe_s rw_wipe(vec4 mask) -{ - rw_wipe_s wipe = rw_wipe_s(1.0e4, 0.0, 1.0, 0.0, 0.0); - for (int i = 0; i < 4; ++i) - { - float m = mask[i]; - if (m < 0.001) - continue; - float pos = wiper_pos[i]; - bool back = pos > 1.0; - float blade = back ? pos - 1.0 : pos; - float t0 = wiper_timer_out[i]; - float t1 = wiper_timer_return[i]; - // when the blade went over the place last: on this stroke, the blade moving at an even pace from its end, or on the - // stroke before, which took as long as the time between the ends (if the blade lay at its end longer, two seconds) - float pass; - float front; // how far in front of the blade the place is (units of the mask), below 0 behind it - if (back) - { - pass = (m >= blade) ? t1 + (time - t1) * ((1.0 - m) / max(1.0 - blade, 1e-3)) : t0 + m * clamp(t1 - t0, 0.0, 2.0); - front = blade - m; - } - else - { - pass = (m <= blade) ? t0 + (time - t0) * (m / max(blade, 1e-3)) : t1 + (1.0 - m) * clamp(t0 - t1, 0.0, 2.0); - front = m - blade; - } - wipe.since = min(wipe.since, max(time - pass, 0.0)); - float moving = smoothstep(0.0, 0.03, blade) * smoothstep(1.0, 0.97, blade); - float ahead = (front > 0.0) ? (1.0 - smoothstep(0.0, 0.035, front)) * moving : 0.0; - wipe.ahead = max(wipe.ahead, ahead); - if ((front > 0.0) && (moving > 0.5)) - wipe.front = min(wipe.front, front); - wipe.swept = max(wipe.swept, ahead * (back ? 1.0 - blade : blade)); - float working = 1.0 - smoothstep(4.0, 30.0, time - t1); - wipe.working = max(wipe.working, working); - } - return wipe; -} - -// a place of the glass a blade reaches -bool rw_reached(vec2 coords) -{ - return any(greaterThanEqual(textureLod(wipermask, clamp(coords, vec2(0.0), vec2(1.0)), 0.0), vec4(0.001))); -} - -// the edge of the sweep of the blades, where they push the water out to: 0 where a blade reaches, else the share of the places -// around at Reach (metres along the glass) which a blade reaches. found from where the blades reach and not from the values of -// the mask, which may stay at the end of the sweep over a wide part of the glass. Maskstep: the coordinates of the mask for a -// step along the glass -float rw_rim(vec2 coords, float reach, mat2 maskstep) -{ - if (rw_reached(coords)) - return 0.0; - float inside = 0.0; - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - inside += rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) ? 1.0 : 0.0; - } - return inside / 6.0; -} - -// whether the edge of the sweep of the blades is within Reach of the place -bool rw_border(vec2 coords, float reach, mat2 maskstep) -{ - bool here = rw_reached(coords); - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - if (rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) != here) - return true; - } - return false; -} - -// how far along its way a sliding drop is at the share T of the time it takes: it stops and goes, the more smoothly the harder -// it is pushed -float rw_stickslip(float t, float seed) -{ - t = clamp(t, 0.0, 1.0); - float s = t * 3.0; - float i = floor(s); - float stuck = (i + smoothstep(0.25 + 0.4 * seed, 1.0, s - i)) / 3.0; - return mix(stuck, t, smoothstep(0.8, 2.0, rw_push)); -} - -// the track of the water down a column of the glass (Column: its index, Width: of a column, Y: metres up the way): where it -// is across, metres. the water keeps to the way wetted before, so every drop of a column goes the same way, wavy, with kinks -// where the glass held it -float rw_path(int column, float y, float width, uint layer) -{ - float slow = rw_noise(y / (0.05 * rw_scale) + float(column) * 7.31, layer) - 0.5; - float k = y / (0.008 * rw_scale); - float i = floor(k); - float a = rw_random(ivec2(column, int(i)), layer + 500u, 3u).x; - float b = rw_random(ivec2(column, int(i) + 1), layer + 500u, 3u).x; - float kinks = mix(a, b, smoothstep(0.15, 0.85, k - i)) - 0.5; - return (float(column) + 0.5 + 0.4 * slow + 0.2 * kinks) * width; -} - -// the drops which grew big enough to slide, and the streams they leave: Q the place across and up the way they go (Side, Down: -// those directions in the coordinates of the glass), Share of them going this way. a column of the glass carries the water of -// a track; a drop starts somewhere in a cell of the column now and then, slides down with stops, thinning, and leaves a stream -// which drains into beads and dries -void rw_sliders(vec2 q, vec2 side, vec2 down, uint layer, float share) -{ - float width = 0.04 * rw_scale; - float height = 0.15 * rw_scale; - int column = int(floor(q.x / width)); - int row = int(floor(q.y / height)); - vec4 a = rw_random(ivec2(column, 7), layer, 0u); - if (a.x > share * mix(0.35, 0.9, clamp(rw_rate / 3.0, 0.0, 1.0))) - return; - float speed = clamp(0.035 + 0.06 * (rw_push - 0.4) + 0.3 * max(rw_push - 1.5, 0.0), 0.01, 0.8); - float period = clamp(25.0 / rw_rate, 3.0, 60.0); - float trail = 0.0; - for (int r = 0; r < 3; ++r) - { - ivec2 cell = ivec2(column, row + r); - vec4 b = rw_random(cell, layer, 1u); - float span = period * mix(0.7, 1.3, b.x); - float now = floor(time / span + b.y); - for (int k = 0; k < 2; ++k) - { - float cycle = now - float(k); - float start = (cycle - b.y) * span; - float t = time - start; - // the drop gathered from the drops landed since the last wipe - if ((t < 0.0) || (rw_since - t < rw_grow)) - continue; - vec4 c = rw_random(cell, layer + 1000u, uint(int(cycle) + 1000000)); - float top = (float(cell.y) + 0.8 - 0.6 * c.x) * height; - float travel = mix(0.06, 0.28, c.y) * rw_scale; - float v = speed * mix(0.7, 1.3, c.z); - float gather = 0.6; - float moved = travel * rw_stickslip((t - gather) * v / travel, c.w); - float y = top - moved; - float radius = mix(0.003, 0.0042, c.w) * rw_scale * (1.0 - 0.35 * moved / travel) * mix(0.6, 1.0, smoothstep(0.0, gather, t)); - // at the end of its way what is left of it stays and flows out into the stream - float body = 1.0 - smoothstep(0.0, 1.5, t - gather - travel / v); - if ((body > 0.0) && (abs(q.y - y) < 3.5 * radius)) - { - vec2 o = vec2(q.x - rw_path(column, y, width, layer), q.y - y); - rw_blob(side * o.x - down * o.y, radius, body); - // its rear up the stream: a corner, drawn out into a cusp the faster it goes (the front stays round) - float drawn = clamp(v * 5.0, 0.0, 1.5); - for (int k = 1; k <= 2; ++k) - { - float yt = y + radius * (0.45 + 0.5 * drawn) * float(k); - vec2 ot = vec2(q.x - rw_path(column, yt, width, layer), q.y - yt); - rw_blob(side * ot.x - down * ot.y, radius * ((k == 1) ? 0.7 : 0.42), body); - } - } - if ((moved > 0.0) && (q.y > y) && (q.y < top)) - { - float age = t - gather - (top - q.y) / v; - if ((age >= 0.0) && (age < rw_since)) - { - // fresh, the stream is whole; draining, it breaks into beads, which dry - float beads = rw_noise(q.y / (0.004 * rw_scale), layer + 9u); - float wet = mix(1.15, 0.2 + 1.0 * beads, smoothstep(0.0, 15.0, age)) * (1.0 - smoothstep(30.0, 60.0, age)); - trail = max(trail, wet); - } - } - } - } - if (trail > 0.0) - { - float across = q.x - rw_path(column, q.y, width, layer); - float half_width = mix(0.0005, 0.0011, a.y) * rw_scale * (0.6 + 0.8 * rw_noise(q.y / (0.006 * rw_scale), layer + 11u)); - rw_blob(side * across, half_width, trail); - } -} - -// a drop lying on the glass, as rw_drop() with the directions along the glass given in the view space (Down: the way gravity -// pulls along the glass, Side across it) -void rw_drop_view(vec3 offset, float visible, float weight, vec4 shape, vec3 down, vec3 side) -{ - rw_kernel(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec3 sag = (down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_kernel(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_kernel(offset - (cos(angle) * side + sin(angle) * down) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// the water the simulation keeps on the glass (gfx::windscreen_water, water.glsl), where the material is a glass of the cab of the -// train: the drops listed by the cell of the grid the fragment is in. Slot: of the glass, Uv: the coordinates of the fragment, -// Puv: the view space step along the glass for a step of the uv; Down, Side: along the glass. a sliding drop is drawn out behind -// itself into a cusp, the faster the longer; one lying is lopsided and sags down the glass; a flake of snow is lace, grey and -// clear as it melts (Snowcover, Wet: as the flakes of rw_snow()) -void rw_simulated(uint slot, vec2 uv, mat2x3 puv, vec3 down, vec3 side, inout float snowcover, inout float wet) -{ - uint base = water_grid_base(slot); - uint cell = water_cell(uv); - uint count = min(water_cells[base + cell], uint(WATER_CELL_DROPS)); - for (uint k = 0u; k < count; ++k) - { - uint place = water_cells[base + uint(WATER_GRID * WATER_GRID) + cell * uint(WATER_CELL_DROPS) + k]; - water_drop_s drop = water_drops[slot * uint(WATER_DROPS) + place]; - float volume = drop.place.z; - if (volume <= 0.0) - continue; - vec3 offset = puv * (uv - drop.place.xy); - vec4 shape = vec4(rw_pcg4d(uvec4(place, slot, 41u, 0u))) * (1.0 / 4294967296.0); - if (drop.motion.w < 1.0) - { - // a flake: lobed lace, shrinking, grey and clear as it melts - float m = drop.motion.w; - vec2 flat2 = vec2(dot(offset, side), dot(offset, down)); - float radius = 0.5 * water_flake(volume); - float dist = length(flat2); - if (dist < radius + rw_pixel) - { - float angle = atan(flat2.y, flat2.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + shape.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + shape.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(flat2 / 0.0007 + shape.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - continue; - } - float radius = water_radius(volume); - vec3 velocity = puv * drop.motion.xy; - float speed = length(velocity); - if (speed > 0.002) - { - // its rear up the way it came: a corner, drawn out into a cusp the faster it goes (the front stays round) - vec3 way = velocity / speed; - rw_kernel(offset, radius, 1.0); - float drawn = clamp(speed * 5.0, 0.0, 1.5); - for (int t = 1; t <= 2; ++t) - rw_kernel(offset + way * (radius * (0.45 + 0.5 * drawn) * float(t)), radius * ((t == 1) ? 0.7 : 0.42), 1.0); - } - else - { - rw_drop_view(offset, radius, 1.0, shape, down, side); - } - } -} - -// how fresh the wetted paths of the simulation are at a place of the glass (x) and how that changes along u and v (yz): the -// texels of their map filtered by a cubic b-spline over 4 x 4 of them, so the edges of a path are smooth curves and its slopes -// change smoothly (a bilinear filter would leave steps at every texel in the bending of the view) -vec3 rw_trail(uint slot, vec2 uv, float now) -{ - // a path stays wet (and seen) longer than the drops keep to it - float lasting = 25.0; - vec2 p = uv * float(WATER_TRAIL) - 0.5; - vec2 i = floor(p); - vec2 f = p - i; - // the weights of the b-spline and their derivatives, for the texels i - 1 .. i + 2 - vec2 g = 1.0 - f; - vec4 wx = vec4(g.x * g.x * g.x, 3.0 * f.x * f.x * f.x - 6.0 * f.x * f.x + 4.0, -3.0 * f.x * f.x * f.x + 3.0 * f.x * f.x + 3.0 * f.x + 1.0, f.x * f.x * f.x) / 6.0; - vec4 wy = vec4(g.y * g.y * g.y, 3.0 * f.y * f.y * f.y - 6.0 * f.y * f.y + 4.0, -3.0 * f.y * f.y * f.y + 3.0 * f.y * f.y + 3.0 * f.y + 1.0, f.y * f.y * f.y) / 6.0; - vec4 dx = vec4(-g.x * g.x, 3.0 * f.x * f.x - 4.0 * f.x, -3.0 * f.x * f.x + 2.0 * f.x + 1.0, f.x * f.x) * 0.5; - vec4 dy = vec4(-g.y * g.y, 3.0 * f.y * f.y - 4.0 * f.y, -3.0 * f.y * f.y + 2.0 * f.y + 1.0, f.y * f.y) * 0.5; - vec3 result = vec3(0.0); - ivec2 base = ivec2(i) - 1; - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - float value = water_wetted(slot, base + ivec2(x, y), now, lasting); - result += value * vec3(wx[x] * wy[y], dx[x] * wy[y], wx[x] * dy[y]); - } - } - result.yz *= float(WATER_TRAIL); - return result; -} - -// the surroundings in a view space direction where the screen doesn't hold them: the environment map above the horizon (the sky -// and the clouds), the ground below it, blurred by Lod -vec3 rw_surroundings(vec3 direction, float lod) -{ - vec3 world = mat3(inv_view) * direction; - vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); - // the horizon as blurred as the view is - float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); - if ((below <= 0.0) || (false == ENVMAP_ENABLED)) - return sky; - return mix(sky, reflection_ground(), below); -} - -// what is seen through the glass in a view space direction: the image of the last frame (the screen space reflections keep it) -// where it holds the place, Distance away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. -// Fade: towards the edges of the image the surroundings take over (else the edges are stretched) -vec3 rw_behind_edges(vec3 direction, float lod, float distance, out float share, bool fade) -{ - share = 0.0; - vec3 around = rw_surroundings(direction, lod); - if (ssr_params.x < 1.0) - return around; - vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); - if (previous.w <= 1e-5) - return around; - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 edges = min(coords, 1.0 - coords); - share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); - coords = clamp(coords, vec2(0.0), vec2(1.0)); - if (share <= 0.0) - return around; - // the view out through the water goes on outside, where the image shows the inside of the cab around the windows the - // surroundings stand for it (else the drops show the dark walls and roof of the cab) - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; - float near = projection[3][2]; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - { - share = 0.0; - return around; - } - vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; - if (any(isnan(color)) || any(isinf(color))) - { - share = 0.0; - return around; - } - return mix(around, max(color, vec3(0.0)), share); -} - -vec3 rw_behind(vec3 direction, float lod, float distance, out float share) -{ - return rw_behind_edges(direction, lod, distance, share, true); + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return vec3(0.0); + vec2 coords = clamp((previous.xy / previous.w) * 0.5 + 0.5, vec2(0.0), vec2(1.0)); + vec3 near = textureLod(ssr_history, coords, min(3.5, ssr_params2.x)).rgb; + vec3 wide = textureLod(ssr_history, coords, min(6.5, ssr_params2.x)).rgb; + if (any(isnan(near)) || any(isinf(near)) || any(isnan(wide)) || any(isinf(wide))) + return vec3(0.0); + vec3 excess = max(near - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return min(excess, vec3(30.0)) * (2.0 * WS_LIGHT_GAIN); } // a layer Over put over Under, the colours not premultiplied -vec4 rw_over(vec4 over, vec4 under) +vec4 wsOver(vec4 over, vec4 under) { - float alpha = over.a + under.a * (1.0 - over.a); - if (alpha <= 1e-5) - return vec4(0.0); - return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); + float alpha = over.a + under.a * (1.0 - over.a); + if (alpha <= 1e-5) + return vec4(0.0); + return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); +} + +// =========================================================================== +float GetMixFactor(in vec2 co, out float side); + +// the rain fallen when each blade last went over the place of its sweep given by the wiper mask (-1: not known), see +// gl::scene_ubs::wiper_rain_pass +vec4 wsWipePass(vec4 mask) +{ + ivec4 b = min(ivec4(max(mask, vec4(0.0)) * float(WIPER_PASS_BUCKETS)), ivec4(WIPER_PASS_BUCKETS - 1)); + return vec4(wiper_rain_pass[b.x].x, wiper_rain_pass[b.y].y, wiper_rain_pass[b.z].z, wiper_rain_pass[b.w].w); +} + +uvec2 cellKey(vec2 c); + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// the 2x2 drop tiles live in the left half of the atlas: a tile is 0.25 wide and 0.5 high in atlas UV +vec2 dropAtlasUV(float choice, vec2 uv) +{ + vec2 off = tileOffset(choice); + return vec2((off.x + uv.x * 0.5) * 0.5, off.y + uv.y * 0.5); +} + +uvec2 cellKey(vec2 c) +{ + return uvec2(ivec2(c) + ivec2(65536)); +} + +// --- one rivulet cell ------------------------------------------------------------ +struct Riv +{ + bool on; + float life; // 0..1 (fade in / out) + float width; // sprite width = head width (glass UV) + float headH; // head height (glass UV) + float topY; // where the trail starts (fixed on the glass) + float bottom; // bottom of the head now + float left; // left edge of the sprite + float flip; + float col; // which of the 4 sprites + float wipe; + float wavK, wavPh, wavSp; +}; + +// the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v +// up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) +float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet +int wsLayerIndex = 0; // its cells in rain_cells (0 gravity, 1 .. 4 the air) +float wsLayerHead = 1.0; // x streak_head +float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) +float wsLayerSin = 0.0; +bool wsLayerVaried = false; // the widths of its rivulets from streak_thin .. streak_thick (the air) + +// glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) +vec2 wsToLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x + wsLayerSin * v.y, -wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsToLayer(vec2 g) +{ + return wsToLayerDir(g - 0.5) + 0.5; +} +vec2 wsFromLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x - wsLayerSin * v.y, wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsFromLayer(vec2 p) +{ + return wsFromLayerDir(p - 0.5) + 0.5; +} + +// the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn +// of the layer of the air +float wsWindShare = 0.0; +// the layer of the weight turned by a quarter turn at a time so that its rivulets run down the glass in the world, whichever +// way the texture lies on it (an island of the UV turned or upside down) +float wsGravCos = 1.0; +float wsGravSin = 0.0; +float wsWindCos = 1.0; +float wsWindSin = 0.0; +void wsSetLayer(int layer) +{ + if (layer == 0) + { + wsLayerDensity = 1.0 - wsWindShare; + wsLayerIndex = 0; + wsLayerHead = 1.0; + wsLayerCos = wsGravCos; + wsLayerSin = wsGravSin; + wsLayerVaried = false; + } + else + { + wsLayerDensity = wsWindShare * wind_streaks; + wsLayerIndex = layer; + wsLayerHead = wind_head_scale; + wsLayerCos = wsWindCos; + wsLayerSin = wsWindSin; + wsLayerVaried = true; + } +} + +// the rivulet of cell SCell of the layer set (wsSetLayer): the randoms and the life of the cell from rain_cells (rain_cells.comp +// worked them out as this did once from the hashes of the cell), the sizes and the places from them +Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) +{ + Riv r; + uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < streak_density * wsLayerDensity * rain_state.y); // as wet as the glass is + r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); + float wr = rain_byte(d.y, 16u); + r.width = streak_head * wsLayerHead / gridSize + * (wsLayerVaried ? mix(streak_thin, streak_thick, pow(wr, streak_thick_bias)) : mix(0.75, 1.25, wr)); + if (wsLayerVaried) + r.width = min(r.width, sCW / 2.6); // the trail with its swing (sMargin) stays in its cell + r.headH = r.width * 0.88 * streak_uv_aspect; + float sSpan = max(sCH * mix(0.35, 0.70, rain_byte(d.y, 24u)), r.headH * 3.0); + // stick-slip: how far down its run the head is now (rain_cells.comp) + float sRun = float(d.y & 65535u) * (1.0 / 65535.0); + r.topY = sCell.y * sCH + sSpan + rain_byte(d.z, 0u) * max(sCH - sSpan, 0.0); + r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); + const float sMargin = 0.8; + r.left = sCell.x * sCW + sMargin * r.width + rain_byte(d.z, 8u) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (((d.w >> 8) & 1u) != 0u) ? 1.0 : 0.0; + r.col = float((d.w >> 9) & 3u); + r.wipe = rain_byte(d.x, 24u); + r.wavK = 6.2831853 / mix(2.5, 5.0, rain_byte(d.z, 16u)); + r.wavPh = rain_byte(d.z, 24u) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, rain_byte(d.w, 0u)); + return r; +} + +// sideways offset of the path (in head widths) at distance dW (head widths) down from the start of the trail +float rivWob(Riv r, float dW, out float ramp, out float wobD) +{ + float rampT = clamp(dW / 2.5, 0.0, 1.0); + ramp = rampT * rampT * (3.0 - 2.0 * rampT); + float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; + float a1 = dW * r.wavK + r.wavPh; + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); + float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; + wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); + return streak_wiggle * ramp * w1; +} + +// how much a drop centred at p (glass UV, v up) with radius rad has been swept up by rivulet r (0..1) +float rivSwept(Riv r, vec2 p, float rad) +{ + if (!r.on || r.life <= 0.001) return 0.0; + if (p.y > r.topY || p.y < r.bottom - rad) return 0.0; + bool inHead = p.y < r.bottom + r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : p.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + float cx = r.left + (0.5 + wob) * r.width; + float halfW = 0.5 * streak_sweep_width * r.width; + return (1.0 - smoothstep(halfW, halfW + rad, abs(p.x - cx))) * r.life; +} + +// candidate on the glass that wins the pixel (the highest dome) +struct Hit +{ + float score; + float cov; // coverage of the dome (normal map alpha) + float colA; // coverage of the drawn drop (sharper) + vec3 n; // dome normal, tangent space of the glass + vec2 offUV; // pixel - centre (glass UV), for the lens + float radUV; // radius (glass UV) + float isDrop; // 1 = drop / droplet (lens), 0 = rivulet (Snell) + float vis; // life / sweep visibility + vec2 auv; // grey atlas lookup of the winner (drops, rivulets) + vec2 agx, agy; + float atlas; // 1 = shade from the grey atlas, 0 = analytic (micro droplets: shade in colA's place) + float shade; // analytic shade (micro droplets) +}; + +void consider(inout Hit h, float score, float cov, float colA, vec3 n, vec2 offUV, float radUV, float isDrop, + float vis, vec2 auv, vec2 agx, vec2 agy, float atlas, float shade) +{ + if (score > h.score) + { + h.score = score; h.cov = cov; h.colA = colA; h.n = n; + h.offUV = offUV; h.radUV = radUV; h.isDrop = isDrop; + h.vis = vis; h.auv = auv; h.agx = agx; h.agy = agy; h.atlas = atlas; h.shade = shade; + } +} + +// the rivulet R of the layer set (wsSetLayer) at the pixel, at SUVr in the coordinates of the layer; Rd1 / Rd2: their change +// per screen pixel +void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) +{ + if (!(r.on && r.life > 0.001)) + return; + const float sMargin = 0.8; + float sLen = r.topY - r.bottom; + float sx = (sUVr.x - r.left) / r.width; + float sy = sUVr.y - r.bottom; + if (sx >= -sMargin && sx <= 1.0 + sMargin && sy >= 0.0 && sy <= sLen) + { + bool inHead = sy < r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : sUVr.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + if (inHead) wobD = 0.0; + float sxw = sx - wob; + if (sxw >= 0.0 && sxw <= 1.0) + { + float sSide; + vec2 sWipeUV = f_coord; + if (inHead) + { + sWipeUV = wsFromLayer(vec2(r.left + 0.5 * r.width, r.bottom + 0.5 * r.headH)); + if (STREAK_FLIP_Y != 0) sWipeUV.y = 1.0 - sWipeUV.y; + } + if (GetMixFactor(sWipeUV, sSide) >= mix(0.5, 1.0, r.wipe)) + { + float sNative = 3.125 * r.width * streak_uv_aspect * STREAK_TAIL_SCALE; + float sxs = mix(sxw, 1.0 - sxw, r.flip); + float su = 0.5 + (r.col + sxs) * 0.125; + vec2 sgx = vec2(0.125 / r.width * rd1.x, 0.0); + vec2 sgy = vec2(0.125 / r.width * rd2.x, 0.0); + vec4 sNm; + vec2 sAuv; + float vtSign = 1.0; + if (inHead) + { + float kv = STREAK_HEAD_FRAC / r.headH; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + sAuv = vec2(su, sy / r.headH * STREAK_HEAD_FRAC); + sNm = textureGrad(normalmap, sAuv, sgx, sgy); + } + else + { + float kv = (1.0 - STREAK_HEAD_FRAC) / sNative; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + // a) trail pattern fixed to the glass, tiled by mirroring (beads stay where they were left) + float dd = max(r.topY - sUVr.y, 0.0) / sNative; + float vt = abs(mod(dd, 2.0) - 1.0); + vtSign = (mod(dd, 2.0) < 1.0) ? 1.0 : -1.0; + // b) right above the head: the sprite part that touches the head + float above = (sy - r.headH) / r.width; // head widths above the head + float link = 1.0 - smoothstep(0.5 * streak_link, streak_link, above); + vec4 nGlass = vec4(0.0); + vec4 nLink = vec4(0.0); + vec2 uvGlass = vec2(su, STREAK_HEAD_FRAC + vt * (1.0 - STREAK_HEAD_FRAC)); + vec2 uvLink = vec2(su, STREAK_HEAD_FRAC + min((sy - r.headH) / sNative, 1.0) * (1.0 - STREAK_HEAD_FRAC)); + if (link < 0.999) + nGlass = textureGrad(normalmap, uvGlass, sgx, sgy); + if (link > 0.001) + nLink = textureGrad(normalmap, uvLink, sgx, sgy); + sAuv = (link > 0.5) ? uvLink : uvGlass; + sNm = mix(nGlass, nLink, link); + vtSign = mix(vtSign, 1.0, link); + } + + float sFade = inHead ? 1.0 : smoothstep(0.0, 1.5, dW); // the start of the trail melts into the glass + float sVis = r.life * sFade; + float sCov = smoothstep(0.1, 0.6, sNm.a) * sVis; + if (sCov > 0.001) + { + vec2 nxy = sNm.rg * 2.0 - 1.0; + if (r.flip > 0.5) nxy.x = -nxy.x; + if (STREAK_FLIP_Y != 0) nxy.y = -nxy.y; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = -nxy / max(nz, 0.08); + if (!inHead) + slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + // the slope of the layer to the one of the glass + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + slope = wsFromLayerDir(slope); + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + vec3 n = normalize(vec3(-slope, 1.0)); + float h = sNm.b * r.width * 0.5; + consider(hit, sCov * (h + 1e-5), sCov, 0.0, n, vec2(0.0), r.width * 0.5, 0.0, + sVis, sAuv, sgx, sgy, 1.0, 0.0); + } + } + } + } +} + +// how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) +float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) +{ + wsSetLayer(0); + vec2 cl = wsToLayer(cg); + Riv rv = getRiv(floor(cl / vec2(sCW, sCH)), sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cl, rad); + if (wsWindShare > 0.001) + { + wsSetLayer(1); + vec2 cw = wsToLayer(cg); + vec2 wc = vec2(sCW * wind_cell_scale, sCH * wind_run_scale); + Riv rw = getRiv(floor(cw / wc), wc.x, wc.y, gridSize); + kept *= 1.0 - streak_sweep * rivSwept(rw, cw, rad); + wsSetLayer(0); + } + return kept; +} + +// the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known +float wsWipeRain(vec2 co) +{ + vec4 mask = textureLod(wipermask, co, 0.0); + vec4 at = wsWipePass(mask); + float fallen = -1.0; + for (int i = 0; i < 4; ++i) + if ((mask[i] > 0.001) && (at[i] >= 0.0)) + fallen = (fallen < 0.0) ? max(rain_state.x - at[i], 0.0) : min(fallen, max(rain_state.x - at[i], 0.0)); + return fallen; +} + +// the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv +void wsGlassFrame(vec3 Ngl, vec2 duv1, vec2 duv2, out vec3 Tgl, out vec3 Bgl) +{ + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; +} + +// the drop of a cell for one side of the blades (A, B: its half of the cell in rain_cells): where it lies, how big it is and its +// shape (the sag, the stretch by the air along PushT). true when P lies on it +bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float speed, vec2 pushT, vec2 p, + out vec2 center, out float sq, out float sag, out mat2 shapeM, out vec2 dl) +{ + center = (nc + vec2(rain_byte(a, 8u), rain_byte(a, 16u))) / gridSize; + float size = mix(drop_size_min, drop_size_max, rain_byte(a, 24u)) / gridSize; // the bias of the sizes: rain_cells.comp + sag = 1.0 + drop_sag * rain_byte(b, 0u); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * speed * rain_byte(b, 8u); + shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(pushT, pushT)); + sq = size * spreadF; // spreads out as it lands + dl = shapeM * (p - center); + return max(abs(dl.x), abs(dl.y)) < sq * 0.5; } void main() { - vec4 tex_color = texture(diffuse, f_coord); - vec4 mask = texture(wipermask, f_coord); + // ---- screen-space derivatives (before any non-uniform flow) ---- + // only what the drops, the droplets and the rivulets read is kept through their loops; the frame of the glass, the change of the + // view and the lens are worked out again for the shading after them (fewer registers in the loops: more pixels at once) + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + float uvPerPx = max(length(duv1), length(duv2)); + vec3 Ngl = normalize(f_normal); - // the coordinates of the glass: metres along the axes of the model, so the water stays where it lies on the glass whatever the - // vehicle and the camera do. the axis of the model nearest to the vertical is up, the glass is projected along the - // horizontal one it faces most (along the vertical one if it lies flat) - mat3 linear = mat3(modelview); - mat3 rot = mat3(normalize(linear[0]), normalize(linear[1]), normalize(linear[2])); - mat3 unrot = transpose(rot); - vec3 local = unrot * (f_pos.xyz - modelview[3].xyz); - vec3 viewnormal = normalize(f_normal); - // the water is on the side away from the camera, the outside of the cab - vec3 outward = (dot(viewnormal, f_pos.xyz) < 0.0) ? -viewnormal : viewnormal; - vec3 normal = unrot * outward; - vec3 up = unrot * (vec3(0.0, 1.0, 0.0) * mat3(inv_view)); - vec3 aup = abs(up); - int iu = (aup.x > aup.y) ? ((aup.x > aup.z) ? 0 : 2) : ((aup.y > aup.z) ? 1 : 2); - int ia = (iu + 1) % 3; - int ib = (iu + 2) % 3; - vec3 axis_up = vec3(0.0); - axis_up[iu] = (up[iu] < 0.0) ? -1.0 : 1.0; - vec3 axis_a = vec3(0.0); - axis_a[ia] = 1.0; - vec3 axis_b = vec3(0.0); - axis_b[ib] = 1.0; - vec3 an = abs(normal); - vec3 axis_u, axis_v, axis_n; - if (an[iu] > max(an[ia], an[ib])) - { - axis_n = axis_up; - axis_u = axis_a; - axis_v = axis_b; - } - else if (an[ia] >= an[ib]) - { - axis_n = axis_a; - axis_u = axis_b; - axis_v = axis_up; - } - else - { - axis_n = axis_b; - axis_u = axis_a; - axis_v = axis_up; - } - vec2 glass = vec2(dot(local, axis_u), dot(local, axis_v)); - float facing = dot(normal, axis_n); - facing = ((facing < 0.0) ? -1.0 : 1.0) * max(abs(facing), 0.35); - // a step of the coordinates is a step along the glass - rw_tu = rot * (axis_u - axis_n * (dot(normal, axis_u) / facing)); - rw_tv = rot * (axis_v - axis_n * (dot(normal, axis_v) / facing)); + vec4 tex_color = texture(diffuse, f_coord); + float glassA = tex_color.a * alpha_mult; - // the derivatives, before anything is discarded: the size of a pixel on the glass and in the view, and how the coordinates of - // the mask follow the ones of the glass - vec3 view = normalize(f_pos.xyz); - vec3 dpdx = dFdx(f_pos.xyz); - vec3 dpdy = dFdy(f_pos.xyz); - rw_pixel = max(max(length(dpdx), length(dpdy)), 1e-6); - float pixelangle = max(max(length(dFdx(view)), length(dFdy(view))), 1e-6); - vec2 gdx = dFdx(glass); - vec2 gdy = dFdy(glass); - mat2 steps = mat2(gdx, gdy); - float det = determinant(steps); - mat2 maskstep = (abs(det) > 1e-14) ? mat2(dFdx(f_coord), dFdy(f_coord)) * inverse(steps) : mat2(0.0); + float gridSize = ceil(param[2].x); + vec2 rainCoord = f_coord; - // the water the simulation keeps, where the material is a glass of the cab of the train (the param water_slot, given by the - // renderer: 1 + the glass): the view space step along the glass for a step of the uv, and how fresh the wetted path the water - // went along is, with how that changes along the glass (before anything is discarded) - int slot = int(param[2].z + 0.5) - 1; - mat2 uvsteps = mat2(dFdx(f_coord), dFdy(f_coord)); - float uvdet = determinant(uvsteps); - bool simulated = (slot >= 0) && (slot < WATER_SLOTS) && (abs(uvdet) > 1e-24); - simulated = simulated && (water_header[clamp(slot, 0, WATER_SLOTS - 1)].x > 0.5); - mat2x3 puv = (abs(uvdet) > 1e-24) ? mat2x3(dpdx, dpdy) * inverse(uvsteps) : mat2x3(0.0); - vec3 trailfield = simulated ? rw_trail(uint(slot), f_coord, water_header[clamp(slot, 0, WATER_SLOTS - 1)].y) : vec3(0.0); - float trail = trailfield.x; - // its gradient along the glass, view space: the uv gradient taken through the steps of the uv along the glass - vec3 trailslope = vec3(0.0); - { - mat2 metric = transpose(puv) * puv; - if (abs(determinant(metric)) > 1e-30) - trailslope = puv * (inverse(metric) * trailfield.yz); - } + float ambLum = clamp(dot(ambient, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + float dynBright = pow(clamp(ambLum * 6.0, 0.0, 1.0), 0.5); + // GL 4.6: the ambient light isn't a level of 0..1 any more (it is in the units of the scene, the light of the sky added), so + // at night the drops came out as bright as by day. how bright the picture around really is says it: the coarsest level of + // the image of the last frame, the average of the screen + float sceneLum = (ssr_params.x >= 1.0) ? wsLum(textureLod(ssr_history, vec2(0.5), ssr_params2.x).rgb) : 1.0; + float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight + dynBright *= wsNight; - if (tex_color.a < 0.01) - discard; + Hit hit; + hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); + hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; + hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - vec4 layer = vec4(0.0); - float heavy = clamp(rain_params.x, 0.0, 1.0); - bool snow = rain_params.z > 0.5; - if ((heavy > 0.0) || simulated) - { - rw_scale = max(param[2].y, 0.05); + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass) ---- + vec2 wsPushT; + float wsSpeed; + float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + { + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); + vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space + vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s + vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass + vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); + wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); + vec3 wsFlow = wsAir - wsN * dot(wsAir, wsN) + wsRise * (max(-dot(wsAir, wsN), 0.0) * WS_HEAD_ON); + float wsDrag = dot(wsFlow, wsFlow) / (WS_DRAG_SPEED * WS_DRAG_SPEED) * wind_drag_gain; // in units of the weight + vec3 wsFlowDir = (length(wsFlow) > 1e-3) ? normalize(wsFlow) : vec3(0.0); + vec3 wsPush = wsGrav + wsFlowDir * wsDrag; + // to the glass UV (v up) through the tangent frame of the texture + vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); + vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + if (dot(gravG, gravG) > 1e-8) + { + // down the glass in its UV, to the nearest quarter turn (a finer turn would break the rivulets at the seams where a curved + // glass bends); none on a glass lying flat + float turn = round(atan(gravG.x, -gravG.y) / 1.5707963) * 1.5707963; + wsGravCos = round(cos(turn)); + wsGravSin = round(sin(turn)); + } + wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets + if (wsWindShare > 0.0) + { + // the rivulets of the air run along the push of the air at twice the weight: the same way at any speed (they don't swing + // round as the train speeds up), up a front glass, back and down a side window + vec2 way = gravG + flowG * 2.0; + if (dot(way, way) > 1e-8) + { + way = normalize(way); + float turn = round(atan(way.x, -way.y) / WS_WIND_STEP) * WS_WIND_STEP; + wsWindCos = cos(turn); + wsWindSin = sin(turn); + } + else + wsWindShare = 0.0; + } + // the push of the air on the drops, texture UV (for stretching them) + wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + } - // what meets the glass. the air against the vehicle (rain_wind) drags the drops along the glass with what of it goes - // along the glass and with the share of what meets it head on which turns up it: the more the glass leans back the more - // of the air goes along it, and the less of their weight pulls the drops down it - vec3 air = unrot * (rain_wind.xyz * mat3(inv_view)); - float fall = snow ? RW_SNOW_FALL : RW_RAIN_FALL; - float hits = max(-dot(air - up * fall, normal), 0.0); - rw_rate = heavy * clamp(0.7 + hits / fall, 0.7, 6.0); - rw_period = clamp((snow ? 10.0 : 5.0) / rw_rate, 0.4, 300.0); - rw_grow = 2.0 * rw_period; - vec3 gravity = -up - normal * dot(-up, normal); - vec3 rise = up - normal * dot(up, normal); - rise = (length(rise) > 0.1) ? normalize(rise) : vec3(0.0); - vec3 flow = air - normal * dot(air, normal) + rise * (max(-dot(air, normal), 0.0) * RW_HEAD_ON); - vec3 push = gravity + flow * (length(flow) / (RW_DRAG_SPEED * RW_DRAG_SPEED)); - vec2 force = vec2(dot(push, axis_u), dot(push, axis_v)); - rw_push = length(force); - vec2 fallway = vec2(dot(gravity, axis_u), dot(gravity, axis_v)); - rw_down = (length(fallway) > 0.1) ? normalize(fallway) : vec2(0.0, -1.0); - vec2 flowway = vec2(dot(flow, axis_u), dot(flow, axis_v)); - rw_flow = (length(flowway) > 1.0) ? normalize(flowway) : vec2(0.0); + // the wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); + // the change of the glass UV (v up) per screen pixel, for the rivulets + vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); + vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); - rw_wipe_s wipe = rw_wipe(mask); - rw_since = wipe.since; - // the blades went lately (any of them, also where none of them reaches) - float working = 0.0; - for (int i = 0; i < 4; ++i) - working = max(working, 1.0 - smoothstep(4.0, 30.0, time - wiper_timer_return[i])); - // how much of the water the place gathers it has - float gathered = 1.0 - exp(-rw_since / (6.0 * rw_period)); - // the film a blade leaves is drawn into fine streaks along its arcs, each a thin cylindrical lens which draws a light seen - // through it into a line across the streaks, towards the pivot of the blade: the way across the streaks on the screen - vec2 streakway = vec2(0.0); - if ((working > 0.0) && (false == snow) && (abs(det) > 1e-14)) - { - int blade = 0; - for (int i = 1; i < 4; ++i) - blade = (mask[i] > mask[blade]) ? i : blade; - if (mask[blade] >= 0.001) - { - // the mask grows along the arcs; a step of a centimetre, so the steps of its values don't matter - float mu = textureLod(wipermask, f_coord + maskstep * vec2(0.01, 0.0), 0.0)[blade]; - float mv = textureLod(wipermask, f_coord + maskstep * vec2(0.0, 0.01), 0.0)[blade]; - vec2 arc = vec2(mu, mv) - mask[blade]; - vec2 onscreen = inverse(steps) * vec2(-arc.y, arc.x); - if ((length(arc) > 1e-4) && (length(onscreen) > 1e-9)) - streakway = normalize(onscreen); - } - } - vec3 ripple = rw_noise2(glass / (0.006 * rw_scale), 5u); + // ---- rivulet cell of this pixel (also used to sweep the drops) ---- + wsSetLayer(0); + float sCW = streak_cell / gridSize; + float sCH = streak_run / gridSize; + vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up + vec2 sUVl = wsToLayer(sUVg); // the same in the layer of the weight (down: -v) + vec2 sCell = floor(sUVl / vec2(sCW, sCH)); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - // the water a blade pushes: a bead in front of it while it moves, as wide as the water it gathered on its way, with a steep - // lumpy front (its edge shows dark, the view can't get out there). the drops the bead reaches flow into it - vec3 lumps = rw_noise2(glass / (0.009 * rw_scale), 7u); - float gatheredwater = snow ? 0.0 : min(gathered * 1.5, 1.0) * (0.35 + 0.65 * min(wipe.swept * 2.5, 1.0)); - float reach = 0.004 + 0.018 * gatheredwater + 0.008 * (ripple.x - 0.5); - float ridge = gatheredwater * smoothstep(0.0, 0.003, wipe.front) * (1.0 - smoothstep(reach - 0.004, reach, wipe.front)); - // the smooth shape from how it changes from pixel to pixel, the lumps on it as they are - float pooledbase = 0.004 * ridge; - float pooled = pooledbase * (0.75 + 0.5 * lumps.x); - vec3 pooledslope = rw_gradient(pooledbase, dpdx, dpdy, outward) * (0.75 + 0.5 * lumps.x) + rw_along(lumps.yz * (0.5 * pooledbase / (0.009 * rw_scale))); - if ((pooled > 0.0) && (false == simulated)) - { - rw_sheet(pooled, pooledslope, 0.03, smoothstep(0.0, 0.1, ridge)); - if (ridge > 0.05) - rw_cleared = time; - } + // the cells (rain_cells) are read only when worked out in this frame (rain_state.w): before the first rain, or without their + // storage, there is nothing in them + if ((rain_state.y > 0.001) && (rain_state.w > 0.5) && (WS_PROFILE != 5)) + { + // =================================================================== + // 1. drops from the atlas: this cell and its 8 neighbours + // =================================================================== + vec2 cellF = rainCoord * gridSize; + vec2 cell = floor(cellF); +#if WS_PROFILE != 4 + // the drops of the 9 cells around which reach the quarter of the cell the pixel lies in (worked out by rain_cells.comp, + // with the drops there are now): usually 1 .. 3 of them + uvec2 quarter = uvec2(greaterThanEqual(cellF - cell, vec2(0.5))); + uint reach = rain_cells[rain_mask_index(ivec2(cell))][quarter.y * 2u + quarter.x]; + while (reach != 0u) + { + int bit = findLSB(reach); + reach &= reach - 1u; + vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); + uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + // as many drops as the glass is wet (the cells were sorted out with a little more) + if (rain_byte(d.y, 24u) > min(rain_state.y * drop_density, 0.95)) + continue; + float vis = float(d.w >> 24) * (1.0 / 255.0); + float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); + // a drop the blades miss: the same drop before and after the stroke, left where it is + bool missed = ((d.w >> 19) & 1u) != 0u; + vec2 center0, center1, dl0, dl1; + float sq0, sq1, sag0, sag1; + mat2 shape0, shape1; + bool in0 = wsDropShape(d.x, d.y, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center0, sq0, sag0, shape0, dl0); + bool in1 = (!missed) && wsDropShape(d.z, d.w, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center1, sq1, sag1, shape1, dl1); + // the wipers asked only for the drops the pixel lies on + if (!(in0 || in1)) + continue; + float side = 0.0; + float mixF = missed ? 1.0 : GetMixFactor((nc + 0.5) / gridSize, side); + bool back = (side > 0.5); + if (!(back ? in1 : in0)) + continue; + if (mixF < rain_byte(back ? d.z : d.x, 0u)) + continue; + uint db = back ? d.w : d.y; + vec2 center = back ? center1 : center0; + float sq = back ? sq1 : sq0; + float sag = back ? sag1 : sag0; + mat2 shapeM = back ? shape1 : shape0; + vec2 dl = back ? dl1 : dl0; + float flipX = (((db >> 16) & 1u) != 0u) ? 1.0 : 0.0; + float choice = (float((db >> 17) & 3u) + 0.5) * 0.25; + vec2 diff = rainCoord - center; - float snowcover = 0.0; - float wet = 0.0; - if (simulated) - { - // the directions along the glass, view space - vec3 upview = vec3(0.0, 1.0, 0.0) * mat3(inv_view); - vec3 downview = -(upview - outward * dot(upview, outward)); - downview = (length(downview) > 0.05) ? normalize(downview) : normalize(cross(outward, normalize(rw_tu))); - vec3 sideview = cross(outward, downview); - rw_simulated(uint(slot), f_coord, puv, downview, sideview, snowcover, wet); - // the paths the water went along lately: a rivulet, a band of water rounded across (a cylinder lens: it holds a picture of - // the place around it turned over across the band, its edges dark as the edges of drops), thicker the fresher. the - // smoothed freshness falls off from the middle of a path to its edges - if (trail > 0.08) - { - float p = clamp((trail - 0.08) / 0.5, 0.0, 1.0); - float thickness = 0.0005 * (1.0 - (1.0 - p) * (1.0 - p)); - vec3 rise = trailslope * (0.0005 * 2.0 * (1.0 - p) / 0.5); - float steep = length(rise); - if (steep > 0.7) - rise *= 0.7 / steep; - bool top = thickness > rw_height; - rw_sheet(thickness, rise, 0.004, smoothstep(0.0, 0.15, p) * 0.95); - // from the middle of the band to the fragment - float across = length(trailslope) / 0.5; - if (top && (across > 1.0)) - rw_offset = -trailslope * ((1.0 - p) / (across * length(trailslope))); - } - } - else if (false == snow) - { - // the drops which grew big enough slide off, with gravity and the air: a set of tracks for each of the directions of the - // push nearest to the one now, each laid along its own way, so none of them moves when the push turns - float sliding = smoothstep(0.25, 0.6, rw_push); - if (sliding > 0.0) - { - float bin = atan(force.y, force.x) / (RW_PI / 6.0); - float lower = floor(bin); - for (int k = 0; k < 2; ++k) - { - float share = ((k == 0) ? 1.0 - (bin - lower) : bin - lower) * sliding; - if (share < 0.02) - continue; - float angle = (lower + float(k)) * (RW_PI / 6.0); - vec2 down = vec2(cos(angle), sin(angle)); - vec2 side = vec2(-down.y, down.x); - rw_sliders(vec2(dot(glass, side), -dot(glass, down)), side, down, uint(int(lower) + k + 64) * 2u + 16u, share); - } - } + if (sweepOn) + { + vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); + vis *= wsKept(cg, 0.35 * sq, sCW, sCH, gridSize); + } + if (vis <= 0.001) + continue; - // the drops as they land, each time somewhere else in its cell, as often as the rain hits the glass: the drops of the - // rain spread on the glass, thrown with a fine splash which runs back into them - // each drop anywhere in its cell, the cell as large as a drop with its splash reaches - float cell = 0.007 * rw_scale; - vec2 laid = rw_turn(glass, 0.61) + vec2(0.31, 0.17); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.08, 0.3, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 1u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 1u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.5, 0.9, b.y); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 2u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.61); - float visible = mix(0.0011, 0.0019, b.z) * rw_scale; - // a raindrop hits the glass far above the speed at which it splashes (Weber number in the hundreds and thousands): - // it spreads, throws a spray of droplets which stay on the glass around it, and draws back - float splash = exp(-age / 0.06); - float fade = 1.0 - smoothstep(life - min(0.4, 0.3 * life), life, age); - if (visible * 0.3 > 0.5 * rw_pixel) - { - int spray = 3 + int(p.z * 4.0); - for (int s = 0; s < spray; ++s) - { - vec4 e = rw_random(c, 3u, uint(cycle) * 8u + uint(s)); - vec2 way = normalize(vec2(cos(e.x * 6.2831853), sin(e.x * 6.2831853)) + rw_flow * 0.9); - rw_blob(offset - way * (visible * (1.4 + 1.6 * e.y)), visible * mix(0.18, 0.35, e.z), fade * (0.55 + 0.45 * splash)); - } - } - rw_drop(offset, visible * (1.0 + 0.3 * splash), fade, p.wzyx); - } - } - // the drops the landing ones gathered into, growing until they are big enough to slide (the air blows them off sooner) - cell = 0.011 * rw_scale; - laid = rw_turn(glass, 1.07) + vec2(0.53, 0.29); - home = ivec2(floor(laid / cell)); - density = mix(0.55, 1.0, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 4u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 4u, 1u); - float span = rw_period * mix(2.5, 4.0, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.75, 0.98, b.y) / (1.0 + 2.0 * max(rw_push - 1.0, 0.0)); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 5u, uint(cycle)); - // the big drops are much alike: they grow as they gather the small ones (the radius in step with the time) up to the - // size at which they slide off (on a vertical glass a footprint of about 9 mm, larger on a glass leaning back, smaller - // in a strong air flow), and go - float slides = min(0.0045 / sqrt(max(rw_push, 0.3)), 0.005); - float visible = slides * mix(0.6, 1.0, b.z) * rw_scale * mix(0.35, 1.0, clamp(age / (0.6 * life), 0.0, 1.0)); - rw_drop(rw_turn(laid - (vec2(c) + p.xy) * cell, -1.07), visible, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.zwxy); - } - } + vec2 luv = dl / sq + 0.5; + if (flipX > 0.5) luv.x = 1.0 - luv.x; + float atlasTexels = float(textureSize(normalmap, 0).x); + float quadPx = sq / max(uvPerPx, 1e-6); + float nlod = clamp(log2(max(0.25 * atlasTexels / max(quadPx, 1.0), 1.0)), 0.0, 6.0); + vec4 nm = textureLod(normalmap, dropAtlasUV(choice, luv), nlod); + float cov = smoothstep(0.1, 0.6, nm.a) * vis; + if (cov <= 0.001) + continue; + vec2 nxy = nm.rg * 2.0 - 1.0; + if (flipX > 0.5) nxy.x = -nxy.x; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = transpose(shapeM) * (-nxy / max(nz, 0.08)); + vec3 n = normalize(vec3(-slope, 1.0)); + // gradients of the tile UV (for the one atlas read after the loop) + vec2 gx = (shapeM * duv1) / sq * vec2(0.25, 0.5); + vec2 gy = (shapeM * duv2) / sq * vec2(0.25, 0.5); + consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, + vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); + } +#endif - // the water the blades push out of their sweep: a broken row of drops flowed together along its edge, just outside it - float leave = working * min(heavy * 1.5, 1.0); - if ((leave > 0.0) && rw_border(f_coord, 0.009 * rw_scale, maskstep)) - { - cell = 0.0065 * rw_scale; - laid = rw_turn(glass, 0.29) + vec2(0.11, 0.43); - home = ivec2(floor(laid / cell)); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 20u, 0u); - if (a.x > 0.85) - continue; - // from the fragment to the middle of the drop, along the glass - vec2 centre = rw_turn((vec2(c) + a.yz) * cell - laid, -0.29); - float rim = rw_rim(f_coord + maskstep * centre, 0.004 * rw_scale, maskstep) * leave; - if (rim <= 0.05) - continue; - rw_drop(-centre, mix(0.0016, 0.003, a.w) * rw_scale * mix(0.6, 1.0, rim), smoothstep(0.05, 0.35, rim), rw_random(c, 21u, 0u)); - } - } - } + // =================================================================== + // 2. micro droplets: procedural, one per micro cell, fully inside it + // =================================================================== + if ((micro_density > 0.0) && (WS_PROFILE != 3)) + { + float mg = gridSize * micro_scale; + vec2 mc = floor(rainCoord * mg); + uvec2 mk = cellKey(mc); + uint m0 = Hash(uvec3(mk, 51u)); + float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); + float mtt = time / mLife + RandF(m0); + float mph = fract(mtt); + uint mep = uint(mod(floor(mtt), 65521.0)); + uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); + if (RandF(m1) < min(micro_density * rain_state.y, 0.95)) + { + uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); + if (wipeVis >= RandF(m2)) + { + float r = mix(micro_size_min, micro_size_max, pow(RandF(m2), 1.5)); + vec2 c = mc + vec2(r) + vec2(RandF(m2), RandF(m2)) * max(1.0 - 2.0 * r, 0.0); + float ell = mix(0.85, 1.15, RandF(m2)); + vec2 p = (rainCoord * mg - c) / r; + p.x *= ell; + float d2 = dot(p, p); + if (d2 < 1.0) + { + float vis = smoothstep(0.0, 0.01, mph) * (1.0 - smoothstep(0.97, 1.0, mph)); + if (sweepOn) + { + vec2 cu = c / mg; + vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); + vis *= wsKept(cg, r / mg, sCW, sCH, gridSize); + } + float d = sqrt(d2); + float cov = smoothstep(1.0, 0.8, d) * vis; + if (cov > 0.001) + { + vec2 nxy = p * micro_bulge; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec3 n = normalize(vec3(nxy, nz)); + float h = sqrt(1.0 - d2) * micro_bulge * (r / mg); + float rim = smoothstep(drop_rim_start, drop_rim_end, 1.0 - n.z); + float lt = dot(n, DROP_LIGHT) * drop_light_side * 0.5 + (1.0 - drop_light_side * 0.5); + consider(hit, cov * (h + 1e-6), cov, smoothstep(1.0, 0.9, d) * vis, n, + rainCoord - c / mg, r / mg, 1.0, + vis, vec2(0.0), vec2(0.0), vec2(0.0), 0.0, clamp(rim * lt, 0.0, 1.0)); + } + } + } + } + } - // the streams running down from the water the blades leave at the ends of their sweep: a stream in some of the columns - // along the way down, where up the glass there is such water, as far down as the water had time to run since the blade - // went over the place - if ((working > 0.0) && (length(fallway) > 0.3)) - { - vec2 side = vec2(-rw_down.y, rw_down.x); - float width = 0.035 * rw_scale; - float across = dot(glass, side); - float along = -dot(glass, rw_down); - int column = int(floor(across / width)); - vec4 a = rw_random(ivec2(column, 0), 30u, 0u); - if (a.x < 0.6 * heavy * working) - { - float lateral = across - rw_path(column, along, width, 31u); - float half_width = mix(0.0006, 0.0012, a.z) * rw_scale * (0.6 + 0.8 * rw_noise(along / (0.006 * rw_scale), 32u)); - if (abs(lateral) < 2.0 * half_width + rw_pixel) - { - // up the glass, the first place where the reach of the blades begins or ends - const float reach[6] = float[](0.01, 0.025, 0.05, 0.1, 0.18, 0.3); - bool here = rw_reached(f_coord); - float source = -1.0; - for (int s = 0; s < 6; ++s) - { - if (rw_reached(f_coord + maskstep * (-rw_down * reach[s])) != here) - { - source = reach[s]; - break; - } - } - if ((source > 0.0) && (source < max(rw_since - 0.1, 0.0) * 0.2)) - { - float beads = rw_noise(along / (0.004 * rw_scale), 33u); - float flowing = working * (1.0 - 0.5 * smoothstep(0.15, 0.3, source)); - rw_blob(side * lateral, half_width, flowing * mix(0.6, 1.2, beads)); - } - } - } - } - } - else - { - // the flakes stick where they land and melt into drops: the glass is warmed by the cab, faster in the air above zero - float warm = rain_params.w; - float cell = 0.016 * rw_scale; - vec2 laid = rw_turn(glass, 0.83) + vec2(0.07, 0.61); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.5, 0.9, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 11u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 11u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.6, 0.95, b.y); - if ((age > life) || (age > rw_since)) - continue; - vec4 p = rw_random(c, 12u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.83); - float diameter = mix(RW_SNOW_DIAMETER.x, RW_SNOW_DIAMETER.y, b.z) * rw_scale; - float melt = ((warm > 0.5) ? mix(3.0, 10.0, b.w) / (1.0 + 0.25 * warm) : mix(15.0, 45.0, b.w)); - if (age < melt) - { - float m = age / melt; - float dist = length(offset.x * rw_tu + offset.y * rw_tv); - float radius = 0.5 * diameter; - if (dist < radius + rw_pixel) - { - float angle = atan(offset.y, offset.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + p.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + p.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(glass / (0.0007 * rw_scale) + p.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - } - else - { - // the water of the flake - rw_drop(offset, 0.0018 * pow(diameter / 0.008, 0.667) * rw_scale, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.wzyx); - } - } - } - // the snow the blades push in front of them and leave at the ends of their sweep - float pile = max(wipe.ahead * min(gathered * 2.0, 1.0) * (0.4 + 0.6 * min(wipe.swept * 2.5, 1.0)), rw_rim(f_coord, 0.006 * rw_scale, maskstep) * working * heavy); - float packed = rw_noise2(glass / (0.0015 * rw_scale), 15u).x; - snowcover = max(snowcover, smoothstep(0.15, 0.5, pile * 1.2 + 0.4 * (ripple.x - 0.5)) * mix(0.7, 1.0, packed)); - } - // untreated glass, weathered and a little dirty: flat drops (a rain repellent coating would give beads above 90 degrees) - rw_settle(radians(mix(30.0, 48.0, rw_noise2(glass / (0.005 * rw_scale), 16u).x))); + // =================================================================== + // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air + // =================================================================== +#if WS_PROFILE != 2 + wsSetLayer(0); + drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVl, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + if (wsWindShare > 0.001) + { + for (int wl = 1; wl <= wind_layers; ++wl) + { + vec2 wc = vec2(sCW * wind_cell_scale, sCH * ((wl == wind_layers) && (wl > 1) ? wind_long_run : wind_run_scale)); + wsSetLayer(wl); + // every further layer: its cells shifted aside, drops of its own + vec2 sUVw = wsToLayer(sUVg) + fract(vec2(0.5, 0.618) * float(wl - 1)) * wc; + Riv rivW = getRiv(floor(sUVw / wc), wc.x, wc.y, gridSize); + drawRivulet(hit, rivW, sUVw, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + } + wsSetLayer(0); + } +#endif + } - // the lamps (of the cab, of the scenery) and the headlights light the water up, from both sides of the glass (worked out - // here, where the fragments of a quad go together) - vec3 lamps = vec3(0.0); - vec3 lampgloss = vec3(0.0); - add_local_lights(outward, lamps, lampgloss); - add_local_lights(-outward, lamps, lampgloss); + // ---- the frame of the glass, the change of the view and the lens, for the shading (uniform flow again) ---- + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); - // the film just behind a blade, breaking up - float film = snow ? 0.0 : heavy * exp(-rw_since / 0.8) * smoothstep(0.02, 0.08, rw_since); - if (film > 0.01) - { - vec3 fine = rw_noise2(glass / (0.0021 * rw_scale), 6u); - vec2 tilt = fine.yz * (0.004 * film); - rw_sheet(0.00005 * film, rw_along(tilt), 0.3, 0.8 * film); - } + // ----------------------------------------------------------------------- + // Shading of the winning dome + // ----------------------------------------------------------------------- + float coverA = clamp(hit.cov, 0.0, 1.0); + vec3 dropLayer = vec3(0.0); + float alphaOut = 0.0; + vec3 dropGlint = vec3(0.0); + vec2 lensBend = vec2(0.0); + float lensK = 0.0; // drops: how much the lens shrinks the picture + float lensRadPx = 1.0e4; // drops: radius on screen, pixels + if (coverA > 0.001) + { + vec3 Nt = hit.n; + // look of the drop: grey atlas (bright rim, dark middle) for drops and rivulets, analytic for droplets + vec3 rgb; + float colA; + if (hit.atlas > 0.5) + { + vec4 at = textureGrad(raindropsatlas, hit.auv, hit.agx, hit.agy); + rgb = at.rgb; + colA = smoothstep(0.3, 0.9, at.a) * hit.vis; + } + else + { + rgb = vec3(hit.shade); + colA = hit.colA; + } + float a = colA * mix(drop_center_alpha, drop_rim_alpha, smoothstep(0.1, 0.3, length(rgb))); + dropLayer = rgb * dynBright * a; + alphaOut = clamp(a, 0.0, 1.0); - // what the water shows: the view goes through the glass (a plate: only the way from the air into the water counts) and out - // through the surface of the water, bent as much as it is curved. it is the world turned upside down in a drop, and the - // edges of a drop, where the view can't get out (total internal reflection), show the inside of the cab - float background = 0.0; - bool image = ssr_params.x >= 1.0; - if (image) - { - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; - if (depth > 0.0) - background = (projection[3][2] / depth) / max(-view.z, 0.05); - } - vec3 inside = ambient * (AMBIENT_SCALE * 0.5); - vec4 water = vec4(0.0); - if (rw_cover > 0.0) - { - vec3 surface = normalize(outward - rw_slope); - vec3 inwater = refract(view, -outward, 1.0 / RW_IOR); - vec3 through = refract(inwater, -surface, RW_IOR); - // what the surface reflects back inside the water: the light which came in at the other side of the drop, from the sky, - // and the inside of the cab. where the view can't get out (the edge of a drop) that is all it shows: a bright edge - vec3 bounced = reflect(inwater, surface); - if (dot(bounced, outward) < 0.0) - bounced = reflect(bounced, outward); - vec3 inner = mix(inside, rw_surroundings(normalize(bounced), 5.0), 0.3); - vec3 color = inner; - if (dot(through, through) > 0.5) - { - float fresnel = 0.02 + 0.98 * pow(1.0 - abs(dot(through, surface)), 5.0); - // the view through the water spreads over this much of the world across a pixel (radians) - float spread = (RW_IOR - 1.0) * rw_pixel / max(rw_curve, 1e-4); - // the picture the drop holds as a lens, and a share of the bending by the surface - vec3 lens = normalize(f_pos.xyz - (1.0 + RW_LENS) * rw_offset) + (through - view) * RW_LENS_BEND; - float lod = mix(log2(1.0 + RW_LENS) - 0.5, log2(max(spread / pixelangle, 1.0)), RW_LENS_BEND); - // a drop a few pixels across would hold a picture of single pixels, a grain: blurred more the smaller it looks - lod += clamp(2.5 - log2(max(rw_curve / rw_pixel, 1.0)), 0.0, 1.5); - float share; - vec3 seen = rw_behind(normalize(lens), lod, background, share); - // the sun through the drop, where the image doesn't hold it: as bright as the drop gathers its light. in heavier rain - // the sun is behind the clouds, its disc is not there to be focused - float sunshare = (1.0 - heavy) * (1.0 - heavy); - if ((lights_count > 0U) && (share < 1.0) && (sunshare > 0.01)) - { - vec3 sun = normalize(-lights[0].dir); - float width = max(spread, 0.03); - float off = acos(clamp(dot(through, sun), -1.0, 1.0)); - if (off < 4.0 * width) - { - float lit = 1.0 - clamp(calc_shadow(), 0.0, 1.0); - vec3 sunlight = lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * cloud_shadow(mat3(inv_view) * f_pos.xyz)); - // the light of the sun over the spread of the view: a pixel shows pi * irradiance * the share of a steradian - seen += sunlight * (sunshare * lit * (1.0 - share) * exp(-0.5 * off * off / (width * width)) / (2.0 * width * width)); - } - } - color = mix(seen, inner, fresnel); - } - color += lamps * 0.6; - // without the image of the last frame the surroundings stand for what the water bends the view to; nearly flat water - // would show them in place of the scene behind it, so it is left mostly clear - float opaque = image ? 1.0 : mix(0.3, 1.0, smoothstep(0.02, 0.15, 1.0 - dot(through, view))); - water = vec4(color, rw_cover * opaque); - } - // the wet glass where the rain gathers is a little hazy: the tiniest drops spread the light - if (image && (false == snow)) - { - float mist = heavy * gathered * (simulated ? 0.18 : 0.3); - if (mist > 0.01) - { - float share; - vec3 hazy = rw_behind_edges(view, 3.5, background, share, false); - // the tiniest drops spread the light of the sky coming through the glass - hazy = mix(hazy, rw_surroundings(outward, 7.0), 0.1); - layer = vec4(hazy, mist * max(share, 0.5)); - } - } - layer = rw_over(water, layer); - // the lights seen through the streaks of the film the blades leave, drawn into lines towards their pivot - if (image && (length(streakway) > 0.5)) - { - vec4 previous = ssr_reprojection * ((background > 0.0) ? vec4(view * background, 1.0) : vec4(view, 0.0)); - if (previous.w > 1e-5) - { - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 texel = 1.0 / vec2(textureSize(ssr_history, 0)); - ivec2 size = textureSize(scene_depth, 0); - float near = projection[3][2]; - // a light: much brighter than the place around it (the bright sky is not) - vec3 around = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 6.0).rgb; - float threshold = max(1.0, 3.0 * max(around.r, max(around.g, around.b))); - vec3 glare = vec3(0.0); - float total = 0.0; - for (int k = -8; k <= 8; ++k) - { - if (k == 0) - continue; - float w = 1.0 - abs(float(k)) / 9.0; - total += w; - vec2 tap = coords + streakway * texel * (float(k) * 5.0); - if (any(lessThan(tap, vec2(0.0))) || any(greaterThan(tap, vec2(1.0)))) - continue; - // only what is outside: the lamps of the cab are not behind the glass - float depth = texelFetch(scene_depth, clamp(ivec2(tap * vec2(size)), ivec2(0), size - 1), 0).r; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - continue; - vec3 c = textureLod(ssr_history, tap, 1.5).rgb; - if (any(isnan(c)) || any(isinf(c))) - continue; - glare += max(c - vec3(threshold), vec3(0.0)) * w; - } - glare *= 0.6 * heavy * working / total; - if (any(greaterThan(glare, vec3(1e-4)))) - { - // the scene itself under the water carries the light added (it changes nothing seen) - vec3 scene = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 0.0).rgb; - layer = rw_over(layer, vec4(max(scene, vec3(0.0)), 0.2)); - layer.rgb += glare / layer.a; - } - } - } - if (snowcover > 0.0) - { - // the flakes are lit through from the outside, by the sky and the sun, and from the inside of the cab; melting they turn - // grey and clear - vec3 outside = rw_surroundings(outward, 6.0); - if (lights_count > 0U) - { - vec3 sun = normalize(-lights[0].dir); - outside += lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * max(dot(outward, sun), 0.0) * (1.0 - clamp(calc_shadow(), 0.0, 1.0))); - } - vec3 flake = mix(vec3(0.92), vec3(0.62, 0.66, 0.7), wet); - vec3 color = flake * (outside * (0.35 * (1.0 - 0.5 * wet)) + ambient * (AMBIENT_SCALE * 0.7)); - layer = rw_over(vec4(color, snowcover * mix(0.97, 0.6, wet)), layer); - } - } - out_color = layer; + // refraction: Snell for rivulets (and as a fallback), lens picture for drops + vec3 I = normalize(f_pos.xyz); + vec3 No = (dot(Ngl, I) > 0.0) ? Ngl : -Ngl; + vec3 Nd = normalize(Tgl * Nt.x + Bgl * Nt.y + No * Nt.z); + vec3 R = refract(I, -Nd, drop_ior); + if (dot(R, R) < 1e-4) + R = refract(I, -Nd, 1.0 + 0.5 * (drop_ior - 1.0)); + vec2 dSlope = vec2(0.0); + if (dot(R, R) > 1e-4 && R.z < -0.05) + dSlope = R.xy / (-R.z) - I.xy / (-I.z); + vec2 snellBend = clamp(-(dSlope * pxPerSlope * drop_refract) / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = snellBend; + if (hit.isDrop > 0.5 && drop_lens_mix > 0.0) + { + vec2 offPx = Jinv * hit.offUV; // pixel - drop centre, in screen pixels + float radPx = hit.radUV / max(uvPerPx, 1e-6); + float k = clamp(min(drop_lens, 0.95 * WS_REFR_MAXPX / max(radPx, 1.0) - 1.0), 0.0, drop_lens); + vec2 lb = clamp((1.0 + k) * offPx / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = mix(snellBend, lb, drop_lens_mix); + lensK = k; + lensRadPx = radPx; + } - { // Overlay windshield texture with alpha - vec3 fragcolor = ambient; - vec3 fragnormal = normalize(f_normal); - float reflectivity = param[1].z; - float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; - legacy_gloss(); + vec3 Rd = (dot(R, R) > 1e-4) ? normalize(R) : I; + vec3 glint = vec3(0.0); + if (lights_count > 0U) + { + float cosS = max(dot(Rd, normalize(-lights[0].dir)), 0.0); + float lobe = pow(cosS, drop_glint_sharpness) * drop_glint_strength + + pow(cosS, 0.2 * drop_glint_sharpness) * drop_sheen; + // the shadow (shadow map + GL 4.6 contact shadow ray) only where the sun shows in the drop at all + if (lobe > 1e-4) + { + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + // GL 4.6: the clouds hold the sun back where their shadow falls (as in apply_lights) + float cloudSun = cloud_shadow(mat3(inv_view) * f_pos.xyz); + glint += lights[0].color * lights[0].intensity * lobe * (1.0 - shadowSun) * cloudSun * wsNight; + } + } + // GL 4.6: headlights and lamps come from the light cluster of the fragment (lights_clustered), or are the + // first lights_count - 1 headlights otherwise. calc_headlights takes the screen-space change of f_pos + // (worked out at the top of main, in uniform flow). The drop scatters light from both sides of the glass, + // so the glass normal is turned towards the light. + // only the lights outside the glass and a few metres away light the drops up (signals, lamps of the station, the + // headlights of other trains): the lamps and the headlights of the own vehicle, a metre or two from the glass, would + // make every drop glow white + vec3 lamps = vec3(0.0); + if (lights_clustered != 0U) + { + cluster_range_s range = cluster_ranges[fragment_cluster()]; + for (uint i = 0U; i < range.count; i++) + { + light_s lt = lights[cluster_light_indices[range.offset + i]]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + if (lt.type == LIGHT_HEADLIGHTS) + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + else if (drop_lamp_scatter > 0.0) + lamps += lt.color * calc_local_light(lt, nl).x * lt.intensity * drop_lamp_scatter * away; + } + } + else + { + for (uint i = 1U; i < lights_count; i++) + { + light_s lt = lights[i]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + } + } + glint += min(lamps, vec3(drop_light_max)); + // reflection of the surroundings on the dome: straight from the environment map. (It used to go through a + // second apply_lights, which in GL 4.6 also runs the shadow map, the contact shadows and the whole light + // cluster again for every drop pixel; the sun and the lamps are done above already.) + if (drop_env > 0.0) + { + vec3 Nv = -Nd; // dome normal towards the viewer + float NoV = clamp(dot(Nv, -I), 0.0, 1.0); + glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; + } +#if WS_PROFILE == 1 + glint = vec3(0.0); +#endif + dropGlint = glint; + if (!POSTFX_ENABLED) + dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped + } - fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(fragcolor, tex_color.a * alpha_mult); + // ----------------------------------------------------------------------- + // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops + // ----------------------------------------------------------------------- + // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) + float wipeRain = wsWipeRain(f_coord); + float hazeBack = (wipeRain < 0.0) ? rain_state.y + : min(rain_state.y, pow(clamp(wipeRain / haze_fill, 0.0, 1.0), haze_curve)); + // up to the full haze in any rain, as the glass gets wet (a lighter rain only mists it up more slowly), less as it dries + float hazeWeight = hazeBack * (1.0 - max(alphaOut, coverA)); + float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); + bool image = ssr_params.x >= 1.0; + float background = 0.0; // distance to the scene behind, along the view (0: far / not known) + if (image) + { + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; + if (depth > 0.0) + background = (projection[3][2] / depth) / max(-wsView.z, 0.05); + } + vec4 under = vec4(0.0); // the blurred view under the drops (not premultiplied) + vec4 bent = vec4(0.0); // the view bent by the drops, laid over everything (as the old postfx did) - out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); - out_color.a = mix(out_color.a, 1., color.a); - } - if (false == POSTFX_ENABLED) - { - out_color = tonemap(out_color); - } + // the haze is blurred by the post-processing (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): the + // picture of this frame can't be read here, and one of the last frame laid over it only shows a milky ghost of the scene + float blurAmt = clamp(hazeWeight * blur_amount, 0.0, 1.0); - if (MOTIONBLUR_ENABLED) - { - out_motion = vec4(0.0); - } + // the drops: the view bent (the picture shift worked out above), and the lights near them. with the motion vectors the + // post-processing bends the picture of this frame (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): it has + // the depth of the cab and never pulls the dashboard or the roof into a drop. the image of the last frame is only the fallback + float refrA = smoothstep(0.05, 0.35, coverA) * glassClear * step(glassA, 0.5); + if ((false == MOTIONBLUR_ENABLED) && (refrA > 0.001)) + { + vec2 shiftPx = -lensBend * WS_REFR_MAXPX; // where the drop looks, screen pixels + vec3 dir = normalize(wsView + shiftPx.x * wsDvx + shiftPx.y * wsDvy); + // a drop shows a minified picture: read it from a coarser level (no grain); tiny drops a little blurrier still + float lod = clamp(log2(1.0 + lensK * drop_lens_mix) - 0.5, 0.0, 3.0) + + clamp(2.5 - log2(max(lensRadPx, 1.0)), 0.0, 1.5); + float share; + vec3 seen = wsBehind(dir, lod, background, share, true); + if (image && (WS_LIGHT_GAIN > 0.0)) + seen += wsLightGlow(wsView, background); + // without the image the surroundings stand in: only faintly, they aren't the scene behind + bent = vec4(seen, refrA * WS_REFR_MIX * (image ? 1.0 : 0.3)); + } + + // the drop shading over it + float shadeA = coverA * drop_shade_alpha; + float outA = alphaOut + shadeA * (1.0 - alphaOut); + vec4 drops = vec4(dropLayer, outA); + drops.rgb += dropGlint * coverA / max(outA, 0.05); // the blend multiplies by alpha once more + out_color = wsOver(drops, under); + + { // windshield texture over the rain + vec3 fragcolor = ambient; + // where the glass texture is clear, its lighting is multiplied by ~0 below: skip apply_lights there + if (glassA > 0.002) + { + vec3 fragnormal = normalize(f_normal); + float reflectivity = param[1].z; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; + legacy_gloss(); + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + } + vec4 color = vec4(fragcolor, glassA); + out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); + out_color.a = mix(out_color.a, 1., color.a); + } + // the picture in the drops goes over the drop shading and the glass, as the old postfx replaced the pixel with it: the dark + // middle of the atlas only shows through faintly, the rim and the glints a little more + out_color = wsOver(bent, out_color); + if (!POSTFX_ENABLED) + out_color = tonemap(out_color); + + // the velocity target: on the drops the picture shift (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), on the hazy glass the request + // for the haze (x = WS_ENC * strength, y = 0); elsewhere the velocity of the scene behind the glass stays as it is (alpha 0) + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + bool drop = (coverA > 0.05 || alphaOut > 0.05) && (glassA < 0.5); + float blurMask = blurAmt * glassClear; + if (drop) + { + vec2 bend = lensBend * smoothstep(0.05, 0.35, coverA); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", raindrops gradually returning after wiper pass: + // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is + // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) + vec4 at = wsWipePass(mask); + vec4 fallen = vec4(rain_state.x) - at; + vec4 known = step(vec4(0.), at); + vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); + vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + // out_factor: the blade that clears the cell the most wins. side: which wiper stroke the drops of this + // cell belong to (part of their random seed, so it must not depend on out_factor). + for (int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + have_side = true; + } + } + return out_factor; } diff --git a/shaders/ogl46/mat_snow_windscreen.frag b/shaders/ogl46/mat_snow_windscreen.frag new file mode 100644 index 000000000..e4772cb01 --- /dev/null +++ b/shaders/ogl46/mat_snow_windscreen.frag @@ -0,0 +1,196 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// Windscreen snow: replaces rain_windscreen when it snows - v3 (OpenGL 4.6 / Vulkan 1.4) +// +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it SNOWS at 1 deg C and below, and the .mat +// block "snow:" is picked. +// +// What lies on the glass comes from the simulation (water_snow.comp, water.glsl): the map of the glass keeps the snow, the water, +// how packed the snow is and the shape of its flakes from frame to frame. The flakes land and stay where they landed, pile up, +// the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives +// the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. +// +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid at each pixel +// sharp from the atlas (snow_sprites.glsl). water_snowlayer.comp lists, for each texel of a layer of the glass (~1 mm), the +// sprites coming within it when the snow under them changes, so the glass lays only those instead of looking through every cell: +// - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come +// one after the other as the snow piles up (mostly icy fleece, more and bigger; now and then a lump of packed or wet snow), +// each on the ones before, so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the +// scene behind them blurred). In a heap they come sooner +// - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) +// A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. +// +// Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): +// 0 a dot 1 dots 2, 3 small puffs 4, 5 puffs 6, 7 crumbs +// 8, 9 wet lumps 10, 11 clumps 12, 13 packed snow 14 slush 15 drop +// An older 2 x 2 atlas (1024 x 1024: fluffy flake, wet lump, crumbs, melted spot) still works, its tiles stand in for these. +// +// .mat: +// +// snow: { +// shader: snow_windscreen +// texture_raindropsatlas: textures/fx/snow-atlas +// texture_normalmap: textures/fx/snow_normalmap +// } + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; + +layout(location = 0) out vec4 out_color; +layout(location = 1) out vec4 out_motion; +#include "common.glsl" + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) // the renderer bakes it into the map of the glass (the blades); not read here +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; the layout of raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) // not used any more (the map of the glass sets the size of the flakes) +// snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none +#pragma param(snow_slot, 2, 2, 1, zero) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" +#include "water.glsl" + +layout(binding = 0) uniform sampler2D diffuse; +layout(binding = 1) uniform sampler2D raindropsatlas; +layout(binding = 2) uniform sampler2D wipermask; +layout(binding = 3) uniform sampler2D normalmap; + +#include "snow_sprites.glsl" + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + // the snow laid together from the sprites (listed by water_snowlayer.comp, a band of its rows every step and wherever a blade + // goes) + vec3 snowRGB = vec3(0.0); + float snowA = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; + float wet = 0.0; + snSlot = int(param[2].z + 0.5) - 1; + if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) + { + // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the + // atlas; a second glass of the snow in the cab (the layer goes to the first one) looks through all the cells around the + // pixel, as it was before the layer, slower but the same + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + float pixelUV = max(length(duv1), length(duv2)); + snow_layer_s laid; + uvec4 refs; + vec2 centreUV; + vec2 span; + if (water_layer_refs(uint(snSlot), f_coord, refs, centreUV)) + { + snSpan(uint(snSlot), centreUV, span); + laid = snComposeRefs(f_coord, centreUV, span, pixelUV, refs); + } + else + { + snSpan(uint(snSlot), f_coord, span); + laid = snCompose(f_coord, span, pixelUV); + } + vec4 layerColour = vec4(laid.rgb, laid.a); + vec4 layerNormal = vec4(laid.n, laid.tr); + vec4 layerBend = vec4(laid.bend, laid.bendA, laid.haze); + snowRGB = layerColour.rgb; + snowA = layerColour.a; + snowN = layerNormal.xyz; + snowTr = layerNormal.w; + snBend = layerBend.xy; + snBendA = layerBend.z; + vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); + wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + // the picture behind thin flakes and a wet film is blurred + snHaze = max(layerBend.w, wet * snow_wet_blur); + snHaze = max(snHaze, smoothstep(snow_blur_mm.x, snow_blur_mm.y, q.x)); + } + + float glassA = tex_color.a * alpha_mult; + float finalA = snowA + glassA * (1.0 - snowA); + vec3 premult = snowRGB + tex_color.rgb * glassA * (1.0 - snowA); + vec3 albedo = premult / max(finalA, 1e-4); + float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); + + // relief: tilt the glass normal by the normals of the sprites (flat where there are none) + vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); + vec3 fragnormal = Ngl; + if (snowA > 0.001) + fragnormal = normalize(Ngl * max(nDir.z, 0.05) + Tgl * nDir.x + Bgl * nDir.y); + + vec3 fragcolor = ambient; + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; + legacy_gloss(); + + // most of the glass is clear: the lighting of the 4.6 renderers is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + + // thin snow glows when you look towards the sun / a lamp + if ((finalA > 0.002) && (snowA > 0.001) && (snow_translucency > 0.0) && (lights_count > 0U)) + { + vec3 I = normalize(f_pos.xyz); + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); + float glow = pow(towards, 3.0) * (1.0 - shadowSun); + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * (snowTr / max(snowA, 1e-3)) * albedo * snowA; + } + vec3 lit = apply_fog(fragcolor); + vec4 color = vec4(lit, finalA); // straight, as rain_windscreen of the 4.6 renderers writes the glass + + out_color = POSTFX_ENABLED ? color : tonemap(color); + + // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as + // rain_windscreen asks: the drops bend it (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), thin snow and a wet film blur it + // (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: the blending keeps the motion of the scene behind + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + float clear = 1.0 - smoothstep(0.5, 0.95, glassA); + if ((snBendA > 0.1) && (glassA < 0.5)) + { + // the post-processing puts the picture from the bent place in place of this pixel, snow and all (85% of it): through + // snow it hides, the snow itself would be replaced by the picture from a place up to 96 px away, a gap of the snow + // there showing here, so an opaque cover would never close. bent only as much as the snow lets the light through + float through = 1.0 - smoothstep(0.6, 0.98, snowA); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA) * through; + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else + { + float blurMask = clamp(snHaze * snow_haze * (1.0 - smoothstep(0.3, 0.8, snowA)) * clear, 0.0, 1.0); + if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + } + out_motion = req; + } +} diff --git a/shaders/ogl46/mat_vat.frag b/shaders/ogl46/mat_vat.frag new file mode 100644 index 000000000..9081789a5 --- /dev/null +++ b/shaders/ogl46/mat_vat.frag @@ -0,0 +1,4 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// people animated by textures (mat_vat.vert moves the vertices): drawn as mat_default +#include "mat_default.glsl" diff --git a/shaders/ogl46/mat_vat.vert b/shaders/ogl46/mat_vat.vert new file mode 100644 index 000000000..aacf58bdd --- /dev/null +++ b/shaders/ogl46/mat_vat.vert @@ -0,0 +1,209 @@ +#version 460 core +#define STAGE_VERTEX 1 +// an animation baked into textures (vertex animation texture, VAT): people walking, standing, waiting. the vertices are moved +// here by the frames of the animation the textures hold, the material is drawn by mat_vat.frag (as mat_default). made by +// vat_bake.py from an animated mesh in blender; the model (t3d) carries in the userdata of every vertex (x) its column of the +// textures. the same shader draws the sun shadows (MATERIAL_SHADOW) and the multi draws (MODEL_DRAWS, opengl46_renderer) +// +// the textures (linear, never compressed or downscaled: at most gfx maxtexturesize, 2048 by default): +// vatpos_hi, vatpos_lo: the position of a vertex in a frame, 16 bits per axis over the box of the animation (rgb: the high and +// the low bytes), the normal in vatnormal (rgb, 0.5 + 0.5 n) +// the frames lie one under another, each in RowsPerFrame rows of Width vertices; the first row of vatpos_hi holds the header, +// the last one the same header with another mark (so the shader sees whether the image came upside down): +// pixel 0: 'V' 'A' 'T' 1 in the first row, 'V' 'A' 'T' 2 in the last +// pixel 1: min x, min y (16 bits each: hi, lo; millimetres + 32768) pixel 2: min z, size x (size: millimetres) +// pixel 3: size y, size z pixel 4: vertices, frames +// pixel 5: rows per frame, frames a second x 100 +// pixel 6: clips (0 or 1: one animation); with more the frames are that many animations of equal length one after another, +// and every one of the models plays one of them, picked as its moment is; then flags: 1 the frames packed one +// right after another (vertex Frame * Vertices + Vertex of the whole image, row by row), else each in its own rows +// the textures go with the trait r (texture_vatpos_hi: name:r), which keeps them as they are (never scaled down nor compressed) +// param vat_speed (1 if not given): how fast the animation plays +// param vat_random (1 if not given): 1 every model its own moment from its place; 0 the moment of the clock alone, for a model the game +// moves (its place changes the whole time, the moment taken from it would jump); -1 the game picks the clip and the moment, by the +// fraction of ten times the turn of the model about the vertical in degrees: (clip + 0.25 + 0.5 * moment) / clips (world/deer.cpp) +layout(location = 0) in vec3 v_vert; +layout(location = 1) in vec3 v_normal; +layout(location = 2) in vec2 v_coord; +layout(location = 3) in vec4 v_tangent; +layout(location = 4) in vec4 v_userdata; + +#include "common.glsl" + +#pragma texture(vatpos_hi, 1, RGBA) +#pragma texture(vatpos_lo, 2, RGBA) +#pragma texture(vatnormal, 3, RGBA) +#pragma param(vat_speed, 2, 0, 1, one) +#pragma param(vat_random, 2, 1, 1, one) +layout(binding = 1) uniform sampler2D vatpos_hi; +layout(binding = 2) uniform sampler2D vatpos_lo; +layout(binding = 3) uniform sampler2D vatnormal; + +#ifdef MATERIAL_SHADOW +layout(location = 2) out vec2 f_coord; +#else +invariant gl_Position; + +layout(location = 0) out vec3 f_normal; +layout(location = 1) flat out vec3 f_normal_raw; +layout(location = 2) out vec2 f_coord; +layout(location = 3) out vec4 f_pos; +layout(location = 8) out mat3 f_tbn; + +layout(location = 4) out vec4 f_clip_pos; +layout(location = 5) out vec4 f_clip_future_pos; + +layout(location = 6) out vec3 TangentFragPos; +layout(location = 7) out vec4 UserData; +#endif + +// the header: Flipped when the image came upside down +struct vat_header +{ + bool valid; + bool flipped; + int height; + vec3 lower; + vec3 size; + int vertices; + int frames; + int rows; + float fps; + int clips; + bool dense; +}; + +ivec4 vat_bytes(ivec2 texel) +{ + return ivec4(round(texelFetch(vatpos_hi, texel, 0) * 255.0)); +} + +vat_header vat_read_header() +{ + vat_header h; + ivec2 size = textureSize(vatpos_hi, 0); + h.height = size.y; + ivec4 mark = vat_bytes(ivec2(0, 0)); + h.valid = (mark.x == 86) && (mark.y == 65) && (mark.z == 84) && ((mark.w == 1) || (mark.w == 2)); + h.flipped = (mark.w == 2); + int row = 0; + ivec4 p1 = vat_bytes(ivec2(1, row)); + ivec4 p2 = vat_bytes(ivec2(2, row)); + ivec4 p3 = vat_bytes(ivec2(3, row)); + ivec4 p4 = vat_bytes(ivec2(4, row)); + ivec4 p5 = vat_bytes(ivec2(5, row)); + ivec4 p6 = vat_bytes(ivec2(6, row)); + h.lower = (vec3(p1.x * 256 + p1.y, p1.z * 256 + p1.w, p2.x * 256 + p2.y) - 32768.0) * 0.001; + h.size = vec3(p2.z * 256 + p2.w, p3.x * 256 + p3.y, p3.z * 256 + p3.w) * 0.001; + h.vertices = p4.x * 256 + p4.y; + h.frames = max(p4.z * 256 + p4.w, 1); + h.rows = max(p5.x * 256 + p5.y, 1); + h.fps = float(p5.z * 256 + p5.w) * 0.01; + h.clips = clamp(p6.x * 256 + p6.y, 1, h.frames); + h.dense = (p6.z & 1) != 0; + return h; +} + +// the texel of vertex Vertex in frame Frame +ivec2 vat_texel(vat_header h, int vertex, int frame, int width) +{ + int ix = h.dense ? frame * h.vertices + vertex : frame * h.rows * width + vertex; + int row = 1 + ix / width; + if (h.flipped) + row = h.height - 1 - row; + return ivec2(ix % width, row); +} + +vec3 vat_position(vat_header h, ivec2 texel) +{ + vec3 high = round(texelFetch(vatpos_hi, texel, 0).rgb * 255.0); + vec3 low = round(texelFetch(vatpos_lo, texel, 0).rgb * 255.0); + return h.lower + h.size * ((high * 256.0 + low) / 65535.0); +} + +vec3 vat_normal(ivec2 texel) +{ + return texelFetch(vatnormal, texel, 0).rgb * 2.0 - 1.0; +} + +// the place and the normal of the vertex now (the rest pose of the model where the textures don't fit it) +void vat_animate(mat4 mv, out vec3 position, out vec3 normal) +{ + position = v_vert; + normal = v_normal; + vat_header h = vat_read_header(); + int vertex = int(v_userdata.x + 0.5); + if ((false == h.valid) || (vertex < 0) || (vertex >= h.vertices)) + return; + int width = textureSize(vatpos_hi, 0).x; + // every one of the models a moment (and a clip) of its own: from its place in the world, whole metres, and its turn about the + // vertical, whole 2 degrees. the place is the one of the camera of the pass (camera_hi exact, camera_lo the rest) and the model + // relative to it (mv, turned back to the world with inv_view), so it's the same in every pass and with every move of the camera; + // the edges of the cells and of the bins away from the round values models are set at + mat3 world = mat3(inv_view) * mat3(mv); + vec3 rel = camera_lo.xyz + mat3(inv_view) * mv[3].xyz; + ivec3 cell = ivec3(camera_hi.xyz) + ivec3(floor(rel + 0.37)); + float yaw = degrees(atan(world[0].z, world[0].x)); + int bin = int(mod(floor(yaw * 0.5 + 0.315), 180.0)); + uint seed = uint(cell.x) * 73856093u ^ uint(cell.y) * 19349663u ^ uint(cell.z) * 83492791u ^ uint(bin) * 2654435761u; + seed ^= seed >> 16; seed *= 0x7feb352du; seed ^= seed >> 15; seed *= 0x846ca68bu; seed ^= seed >> 16; + float random = clamp(param[2].y, 0.0, 1.0); + float phase = random * float(seed & 0xffffu) / 65536.0; + float pick = random * float(seed >> 16) / 65536.0; + if (param[2].y < -0.5) + { + // picked by the game: the fraction of the turn in tenths of a degree (the turn is -yaw), a quarter of a clip's span kept + // clear of its edges + float spin = fract(-yaw * 10.0) * float(h.clips); + float slot = floor(spin); + pick = (slot + 0.5) / float(h.clips); + phase = clamp((spin - slot - 0.25) * 2.0, 0.0, 1.0); + } + int clipframes = max(h.frames / h.clips, 1); + int clip = min(int(pick * float(h.clips)), h.clips - 1); + float t = (time * h.fps * max(param[2].x, 0.0)) + phase * float(clipframes); + float f = mod(t, float(clipframes)); + int f0 = clip * clipframes + int(floor(f)) % clipframes; + int f1 = clip * clipframes + (int(floor(f)) + 1) % clipframes; + float a = fract(f); + ivec2 t0 = vat_texel(h, vertex, f0, width); + ivec2 t1 = vat_texel(h, vertex, f1, width); + position = mix(vat_position(h, t0), vat_position(h, t1), a); + vec3 n = mix(vat_normal(t0), vat_normal(t1), a); + normal = (dot(n, n) > 1e-6) ? normalize(n) : v_normal; +} + +void main() +{ + mat4 mv = effective_modelview(); + vec3 position; + vec3 normal; + vat_animate(mv, position, normal); +#ifdef MATERIAL_SHADOW + gl_Position = (projection * mv) * vec4(position, 1.0); + f_coord = v_coord; +#else + mat3 mvn = effective_modelviewnormal(); + + f_normal = normalize(mvn * normal); + f_normal_raw = normal; + f_coord = v_coord; + f_pos = mv * vec4(position, 1.0); + f_clip_pos = projection * f_pos; + f_clip_future_pos = (projection * future) * f_pos; + + gl_Position = f_clip_pos; + gl_PointSize = param[1].x; + + vec3 N = f_normal; + vec3 T = mvn * v_tangent.xyz; + T = normalize(T - N * dot(N, T)); + vec3 B = cross(N, T) * (v_tangent.w < 0.0 ? -1.0 : 1.0); + f_tbn = mat3(T, B, N); + TangentFragPos = transpose(f_tbn) * f_pos.xyz; + UserData = v_userdata; +#endif +#ifdef MODEL_DRAWS + f_model_draw = uint(gl_DrawID); +#endif +} diff --git a/shaders/ogl46/postfx_motionblur.frag b/shaders/ogl46/postfx_motionblur.frag index e28953ebb..66ce2ed43 100644 --- a/shaders/ogl46/postfx_motionblur.frag +++ b/shaders/ogl46/postfx_motionblur.frag @@ -13,13 +13,34 @@ layout(binding = 1) uniform sampler2D velocity_tex; layout(binding = 2) uniform sampler2D depth_tex; #include "common.glsl" +#include "rain_windscreen_haze.glsl" void main() { + // the hazy wet windscreen (mat_rain_windscreen.frag): blurred here without the taa, left as it is when the taa blurred it + vec2 rawv = texture(velocity_tex, f_coords).xy; + if (wsIsDrop(rawv)) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb + : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); + return; + } + float blurAmt = wsBlur(rawv); + if (blurAmt > 0.0) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + return; + } + float ori_depth = texture(depth_tex, f_coords).x; vec2 texelSize = 1.0 / vec2(textureSize(color_tex, 0)); - vec2 velocity = texture(velocity_tex, f_coords).xy * param[0].x; + vec2 velocity = rawv * param[0].x; + // edge pixels of the windscreen can carry a fraction of a blur request: never use that as motion + if (any(greaterThan(abs(rawv), vec2(WS_FLOOR * WS_ENC)))) + velocity = vec2(0.0); float speed = length(velocity / texelSize); int nSamples = clamp(int(speed), 1, 32); diff --git a/shaders/ogl46/postfx_taa.frag b/shaders/ogl46/postfx_taa.frag index 294325e71..c06a03fcb 100644 --- a/shaders/ogl46/postfx_taa.frag +++ b/shaders/ogl46/postfx_taa.frag @@ -22,4 +22,53 @@ layout(binding = 3) uniform sampler2D history_tex; #define TAA_HISTORY_VALID (param[0].x > 0.5) #define TAA_REPROJECTION future #define TAA_NEAR param[0].y +#include "rain_windscreen_haze.glsl" + +// the resolve of the taa under another name: main() below gives the hazy windscreen its blur first +#define main taa_resolve_main #include "taa_resolve.glsl" +#undef main + +// the drops and the haze are made from the frame alone (the history of the taa would smear them over the frames): drawn with the +// offsets of the taa they shimmer from frame to frame. they stay where they are on the screen, so the result of the last frame at +// the same pixel is blended in: fully while the view stands still, half while it moves, kept near this frame's result (no ghosts +// of a wiper or of drops gone) +const float WS_TEMPORAL_SHARE = 0.2; // the share of this frame while the view stands still +const float WS_TEMPORAL_MOVING = 0.5; // ... and while it moves +const float WS_TEMPORAL_RANGE = 0.12; // the last frame kept within this of this frame (colours squeezed into 0..1) + +vec3 wsStabilize(vec3 current, ivec2 pixel) +{ + if (false == TAA_HISTORY_VALID) + return current; + vec4 last = texelFetch(history_tex, pixel, 0); + if (any(isnan(last)) || (false == wsWasHazed(last.a))) // not a drop or haze pixel in the last frame + return current; + vec2 size = vec2(textureSize(color_tex, 0)); + float depth = texelFetch(depth_tex, pixel, 0).r; + vec4 world = TAA_REPROJECTION * vec4(f_coords * 2.0 - 1.0, depth, 1.0); + bool still = (world.w > 0.0) && (length((world.xy / world.w * 0.5 + 0.5 - f_coords) * size) < 0.5); + vec3 c = taa_compress(current); + vec3 h = clamp(taa_compress(taa_clean(last.rgb)), c - WS_TEMPORAL_RANGE, c + WS_TEMPORAL_RANGE); + return taa_decompress(clamp(mix(h, c, still ? WS_TEMPORAL_SHARE : WS_TEMPORAL_MOVING), vec3(0.0), vec3(1.0 - 1.0 / TAA_HALF_MAX))); +} + +void main() +{ + // the hazy wet windscreen (mat_rain_windscreen.frag): the picture of this frame blurred over the hazy glass, without the + // history (else it would blur on frame after frame); marked for the motion blur after + ivec2 pixel = ivec2(f_coords * vec2(textureSize(velocity_tex, 0))); + vec2 raw = texelFetch(velocity_tex, pixel, 0).xy; + if (wsIsDrop(raw)) + { + out_color = vec4(wsStabilize(taa_clean(wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, raw)), pixel), WS_HAZED); + return; + } + float blurAmt = wsBlur(raw); + if (blurAmt > 0.0) + { + out_color = vec4(wsStabilize(taa_clean(wsHaze(color_tex, velocity_tex, f_coords, blurAmt)), pixel), WS_HAZED); + return; + } + taa_resolve_main(); +} diff --git a/shaders/ogl46/rain_cells.comp b/shaders/ogl46/rain_cells.comp new file mode 100644 index 000000000..43ab26a60 --- /dev/null +++ b/shaders/ogl46/rain_cells.comp @@ -0,0 +1,189 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the cells of the glasses with rain (rain_cells.glsl): the drops and the rivulets of every cell worked out for the time of the +// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them). two passes: the +// cells (rain_pass 0), then which drops reach the quarters of each drop cell (rain_pass 1, it reads the first) + +#include "common.glsl" + +layout(location = 0) uniform float rain_time; // the time of the block of the scene (scene_ubs.time) +layout(location = 1) uniform float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) +layout(location = 2) uniform int rain_pass; // 0 the cells, 1 the reach of the drops + +#include "random.glsl" +#include "rain_cells.glsl" + +layout(local_size_x = RAIN_CELLS_GROUP_SIZE) in; + +uvec2 rain_key(ivec2 Cell) +{ + return uvec2(Cell + ivec2(65536)); +} + +// a random kept to 8 bits (rain_byte() takes it back) +uint q8(float Value) +{ + return min(uint(Value * 256.0), 255u); +} + +// a share 0 .. 1 kept to Steps + 1 levels, 0 and 1 exact +uint qn(float Value, float Steps) +{ + return uint(round(clamp(Value, 0.0, 1.0) * Steps)); +} + +// a drop cell: its life now, the activation, and the drop of either side of the blades (the sequence of the randoms is the +// one mat_rain_windscreen.frag had) +uvec4 drop_cell(ivec2 Cell) +{ + uvec2 key = rain_key(Cell); + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = rain_time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + float landing = RandF(s1); + bool missed = RandF(s1) < wiper_miss; + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float spread = smoothstep(0.0, 2.0 * appearF, ph); + uvec4 result; + for (uint side = 0u; side < 2u; ++side) + { + uint s2 = Hash(uvec3(key, ep * 4u + 2u + side * 2u)); + float thr = RandF(s2); + float cx = RandF(s2); + float cy = RandF(s2); + float size = RandF(s2); + float sag = RandF(s2); + float flip = RandF(s2); + float choice = RandF(s2); + float stretch = RandF(s2); + uint tile = min(uint(choice * 4.0), 3u); + uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(pow(size, drop_size_bias)) << 24); + uint b = q8(sag) | (q8(stretch) << 8) | ((flip < 0.5) ? (1u << 16) : 0u) | (tile << 17); + if (side == 0u) + { + b |= (qn(spread, 31.0) << 19) | (q8(landing) << 24); + result.x = a; + result.y = b; + } + else + { + b |= (missed ? (1u << 19) : 0u) | (qn(vis, 255.0) << 24); + result.z = a; + result.w = b; + } + } + return result; +} + +// a rivulet cell of layer Layer (0 gravity, 1 .. 4 the air), as getRiv of mat_rain_windscreen.frag drew it +uvec4 rivulet_cell(int Layer, ivec2 Cell) +{ + uint salt = 91u + 2u * uint(Layer); + uint sSeed = Hash(uvec3(rain_key(Cell), salt)); + float on = RandF(sSeed); + float sPeriod = ((Layer == 0) ? streak_period : wind_streak_period) * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(rain_time / sPeriod + RandF(sSeed)); + float life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + float wr = RandF(sSeed); + float span = RandF(sSeed); + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + float top = RandF(sSeed); + float left = RandF(sSeed); + float flip = RandF(sSeed); + float col = RandF(sSeed); + float wipe = RandF(sSeed); + float wavK = RandF(sSeed); + float wavPh = RandF(sSeed); + float wavSp = RandF(sSeed); + uvec4 result; + result.x = min(uint(on * 65536.0), 65535u) | (qn(life, 255.0) << 16) | (q8(wipe) << 24); + result.y = qn(sRun, 65535.0) | (q8(wr) << 16) | (q8(span) << 24); + result.z = q8(top) | (q8(left) << 8) | (q8(wavK) << 16) | (q8(wavPh) << 24); + result.w = q8(wavSp) | ((flip < 0.5) ? (1u << 8) : 0u) | (min(uint(col * 4.0), 3u) << 9); + return result; +} + +// how far from the centre (in cells) the drop of side half A, B of a cell can reach at most: half its size, the sag, the stretch of the +// air at its strongest, any way it is turned +float drop_reach(uint A, uint B, float Spread) +{ + float half_size = 0.5 * mix(drop_size_min, drop_size_max, rain_byte(A, 24u)) * Spread; + float sag = 1.0 + drop_sag * rain_byte(B, 0u); + float stretch = 1.0 + drop_wind_stretch * rain_byte(B, 8u); + return half_size * sqrt(1.0 + sag * sag) * stretch * 1.01; +} + +// the reach of the drops around a drop cell into its quarters (rain_cells.glsl), from the cells worked out by the first pass +uvec4 drop_masks(ivec2 Cell) +{ + uvec4 result = uvec4(0u); + // as many drops as the glass is wet (rain_amount: the wetness of the glass, scene_ubs.rain_state.y) + float most = min(rain_amount * drop_density, 0.95); + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + { + uvec4 d = rain_cells[rain_drop_index(Cell + ivec2(dx, dy))]; + if ((rain_byte(d.y, 24u) > most) || ((d.w >> 24) == 0u)) + continue; + float spread = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); + bool missed = ((d.w >> 19) & 1u) != 0u; + uint bit = 1u << uint((dy + 1) * 3 + dx + 1); + for (uint side = 0u; side < 2u; ++side) + { + if ((side == 1u) && missed) + break; + uint a = (side == 0u) ? d.x : d.z; + uint b = (side == 0u) ? d.y : d.w; + vec2 centre = vec2(dx, dy) + vec2(rain_byte(a, 8u), rain_byte(a, 16u)); + float reach = drop_reach(a, b, spread); + for (uint q = 0u; q < 4u; ++q) + { + vec2 low = vec2(float(q & 1u), float(q >> 1)) * 0.5; + vec2 away = max(max(low - centre, centre - (low + 0.5)), vec2(0.0)); + if (dot(away, away) < reach * reach) + result[q] |= bit; + } + } + } + return result; +} + +void main() +{ + uint index = gl_GlobalInvocationID.x; + if (rain_pass == 1) + { + // the second pass: the reach of the drops, a thread a drop cell + if (index >= uint(RAIN_DROP_CELLS * RAIN_DROP_CELLS)) + return; + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[uint(RAIN_MASK_BASE) + index] = drop_masks(cell); + return; + } + if (index >= uint(RAIN_MASK_BASE)) + return; + if (index < uint(RAIN_RIV_BASE)) + { + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + // the last column and row stand for the cells -1 (the neighbours of the first ones) + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[index] = drop_cell(cell); + return; + } + uint rest = index - uint(RAIN_RIV_BASE); + int layer = int(rest / uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS)); + uint place = rest % uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS); + ivec2 texel = ivec2(int(place % uint(RAIN_RIV_CELLS)), int(place / uint(RAIN_RIV_CELLS))); + // the cells -32 .. 95: the upper quarter stands for the cells below 0 + ivec2 cell = ivec2(texel.x >= 96 ? texel.x - RAIN_RIV_CELLS : texel.x, texel.y >= 96 ? texel.y - RAIN_RIV_CELLS : texel.y); + rain_cells[index] = rivulet_cell(layer, cell); +} diff --git a/shaders/ogl46/rain_cells.glsl b/shaders/ogl46/rain_cells.glsl new file mode 100644 index 000000000..5fa8569dd --- /dev/null +++ b/shaders/ogl46/rain_cells.glsl @@ -0,0 +1,82 @@ +// the cells of the glasses with rain (mat_rain_windscreen.frag): the drops of the grid of drops and the rivulets of the layers of +// rivulets, worked out once a frame for every cell by rain_cells.comp (a thread a cell) instead of in every pixel of a glass for +// its 9 neighbouring cells. a cell holds the random values of its drop or rivulet as they are now (the hashes of the cell and of +// its epoch, the life cycle at the time of the frame); the glass takes the sizes and the places from them with its own settings. +// so the glass looks the same as when it worked them out itself (the hashes are the same; the values are kept to 8 or 16 bits) +// +// a cell is one uvec4. the drops: RAIN_DROP_CELLS x RAIN_DROP_CELLS cells, cell c of the grid in element (c.y & 511) * 512 + +// (c.x & 511), whole for the cells -1 .. 510 (grids up to 510 cells; finer ones repeat their drops every 512 cells): +// x side 0 (the drop of a cell the blades went over on their way out): bits 0-7 the threshold the wipers have to be past for +// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 its size (0 .. 1 from drop_size_min to drop_size_max) +// y side 0: bits 0-7 the random of its sag, 8-15 of its stretch by the air, 16 mirrored, 17-18 the tile of the atlas, +// 19-23 how far it spread out landing (0 .. 31), 24-31 the random a cell holds a drop by (a drop when below the share) +// z side 1 (the blades on their way back): as x +// w side 1: as y, bit 19 set when the blades miss the drop, bits 24-31 its visibility in its life (0 .. 255) +// the reach of the drops: for every drop cell (element RAIN_MASK_BASE + the index of the drop cell) the drops of the 9 cells around +// it (bit (dy + 1) * 3 + dx + 1) which reach into each quarter of it (x the lower left, y the lower right, z the upper left, w the +// upper right), with the drops the cells hold now in the rain there is now (a glass only looks at those) +// the rivulets: RAIN_RIV_LAYERS layers (0 gravity, 1 .. 4 the air) of RAIN_RIV_CELLS x RAIN_RIV_CELLS cells, cell c in element +// RAIN_RIV_BASE + layer * 128 * 128 + (c.y & 127) * 128 + (c.x & 127), whole for the cells -32 .. 95: +// x bits 0-15 the random the cell holds a rivulet by, 16-23 its life (0 .. 255), 24-31 the random of the wipers it stays under +// y bits 0-15 how far down its run the head is (0 .. 65535), 16-23 the random of its width, 24-31 of its span +// z the randoms of its top, its left edge, the length and the phase of its waves (a byte each) +// w bits 0-7 the random of the speed of its waves, 8 mirrored, 9-10 the sprite of the atlas + +#ifndef RAIN_CELLS_GLSL +#define RAIN_CELLS_GLSL + +#define RAIN_DROP_CELLS 512 +#define RAIN_RIV_CELLS 128 +#define RAIN_RIV_LAYERS 5 +#define RAIN_RIV_BASE (RAIN_DROP_CELLS * RAIN_DROP_CELLS) +#define RAIN_MASK_BASE (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_CELLS_COUNT (RAIN_MASK_BASE + RAIN_DROP_CELLS * RAIN_DROP_CELLS) +#define RAIN_CELLS_GROUP_SIZE 64 + +#if defined(STAGE_COMPUTE) +layout(std430, binding = RAIN_CELLS_SSBO_BINDING) buffer rain_cells_ssbo +#else +layout(std430, binding = RAIN_CELLS_SSBO_BINDING) readonly buffer rain_cells_ssbo +#endif +{ + uvec4 rain_cells[]; +}; + +// the drops and the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) +const float drop_life_min = 14.0; // seconds a drop sits on the glass +const float drop_life_max = 45.0; +const float drop_appear = 0.18; // seconds of the landing "pop" +const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life +const float wiper_miss = 0.005; // share of the drops a blade goes over without taking them (a tenth of the 0.05 it was) +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) + +// a random kept to 8 bits, back to 0 .. 1 (the middle of its step) +float rain_byte(uint Value, uint Shift) +{ + return (float((Value >> Shift) & 255u) + 0.5) * (1.0 / 256.0); +} + +uint rain_drop_index(ivec2 Cell) +{ + return uint(Cell.y & (RAIN_DROP_CELLS - 1)) * uint(RAIN_DROP_CELLS) + uint(Cell.x & (RAIN_DROP_CELLS - 1)); +} + +uint rain_mask_index(ivec2 Cell) +{ + return uint(RAIN_MASK_BASE) + rain_drop_index(Cell); +} + +uint rain_riv_index(int Layer, ivec2 Cell) +{ + return uint(RAIN_RIV_BASE) + uint(Layer) * uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS) + uint(Cell.y & (RAIN_RIV_CELLS - 1)) * uint(RAIN_RIV_CELLS) + + uint(Cell.x & (RAIN_RIV_CELLS - 1)); +} + +#endif diff --git a/shaders/ogl46/rain_windscreen_haze.glsl b/shaders/ogl46/rain_windscreen_haze.glsl new file mode 100644 index 000000000..73be4b573 --- /dev/null +++ b/shaders/ogl46/rain_windscreen_haze.glsl @@ -0,0 +1,270 @@ +// the haze of the wet windscreen (mat_rain_windscreen.frag), drawn by the post-processing: the glass asks for it in the velocity +// target (x = WS_ENC * strength, y = 0, see mat_rain_windscreen.frag), and the picture there is blurred over the hazy glass only. +// postfx_taa.frag does it with the temporal anti-aliasing (every frame, also standing still), postfx_motionblur.frag without it +// (it runs only while something moves). the picture blurred by the taa is marked in its alpha (WS_HAZED), so the motion blur +// after it leaves it as it is. +// +// real motion vectors are tiny (<< 0.25 per frame), so the large values can only come from the windscreen +#ifndef RAIN_WINDSCREEN_HAZE_GLSL +#define RAIN_WINDSCREEN_HAZE_GLSL + +const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag +const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion +const float WS_HAZED = -4.0; // alpha of the picture the taa already blurred: below anything a scene writes (additive + // particles took the alpha of the image above 1.5, and the motion blur then left the haze of a + // bug or of the glass out on some frames: a flicker). negative, so the lock of the taa takes 0 + +// whether the picture was blurred by the taa already (WS_HAZED in its alpha) +bool wsWasHazed(float alpha) +{ + return alpha < -3.0; +} + +// blur of hazy glass +const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height +const int WS_TAPS = 16; +const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze around it (brightness, scene units) + +// strength of the blur request, 0 for pixels that are not blur pixels +float wsBlur(vec2 raw) +{ + // a blended edge with something else: not a blur pixel. the haze is asked with y = 0; with msaa the samples of a pixel are + // averaged, and the edge of a drop (y half of a drop's) came out as a full haze request: a ring blurred around the drop which + // flickered as the edges moved over the samples + if (raw.x > 100.0 || raw.y > 1.0) + return 0.0; + float m = clamp(raw.x / WS_ENC, 0.0, 1.0); + return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); +} + +// a colour of the picture made safe: a very bright light can be an infinity in the half float image (and a broken pixel a nan); +// in an average that gave nan for the whole result, which the taa turns black: black dotted blobs around the lights +vec3 wsSafe(vec3 c) +{ + return any(isnan(c)) ? vec3(0.0) : clamp(c, vec3(0.0), vec3(65000.0)); +} + +vec3 wsFetch(sampler2D tex, vec2 uv) +{ + return wsSafe(textureLod(tex, uv, 0.0).rgb); +} + +// the weight of a colour in an average that a single very bright pixel must not take over +float wsKaris(vec3 c) +{ + return 1.0 / (1.0 + dot(c, vec3(0.2126, 0.7152, 0.0722))); +} + +// the picture at Uv blurred over the hazy glass, for a request of BlurAmt (> 0) +vec3 wsHaze(sampler2D colortex, sampler2D velocitytex, vec2 uv, float blurAmt) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 sharp = wsFetch(colortex, uv); + + float radius = WS_RADIUS * blurAmt; + + // interleaved gradient noise rotates the disc per pixel -> no banding + float rot = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + + float wsum = wsKaris(sharp); + vec3 sum = sharp * wsum; + float psum_w = 1.0; // the plain average beside it + vec3 psum = sharp; + + for (int i = 0; i < WS_TAPS; ++i) + { + float r = sqrt((float(i) + 0.5) / float(WS_TAPS)); + float a = float(i) * 2.3999632 + rot; // golden angle + vec2 o = vec2(cos(a), sin(a)) * r * radius; + o.x *= aspect; + + vec2 tap = uv + o; + + // take only hazy-glass pixels (not the cab frame, not clear glass, not drops) + // weighed by 1 / (1 + brightness) (karis average): an ordinary picture blurs the same, but a very bright light + // (a lamp close by, headlights) is not smeared over the whole disc at full strength, which the bloom then turned + // into a large flat blob shaped like a clover + float w = step(0.01, wsBlur(textureLod(velocitytex, tap, 0.0).xy)); + vec3 c = wsFetch(colortex, tap); + psum += c * w; + psum_w += w; + w *= wsKaris(c); + sum += c * w; + wsum += w; + } + + // the karis average alone almost wipes small bright lights out of the haze (signals at night went faint): the light the + // plain average has above it comes back, up to WS_HAZE_LIGHT_CAP, so a light stays a soft glow of its colour and only a + // very bright one (a lamp close by) isn't smeared at full strength + vec3 blurred = sum / wsum; + vec3 extra = max(psum / psum_w - blurred, vec3(0.0)); + float extraL = dot(extra, vec3(0.2126, 0.7152, 0.0722)); + blurred += extra * min(1.0, WS_HAZE_LIGHT_CAP / max(extraL, 1e-4)); + return mix(sharp, blurred, min(blurAmt * 4.0, 1.0)); +} + +// --------------------------------------------------------------------------------------------------------------------------- +// refraction in the drops: the glass sends the picture shift of the drop (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend, bend -1..1 +// = WS_REFR_MAXPX pixels), and the picture of this frame is bent here. the depth of the whole frame (with the cab) is known here, +// so the dashboard, the frame and the roof of the cab are never pulled into a drop (the image of the last frame used by the +// glass shader can't tell them apart: white drops at night at the edges and under the wipers) +// --------------------------------------------------------------------------------------------------------------------------- +const float WS_BEND_ENC = 60.0; // must match mat_rain_windscreen.frag +const float WS_DROP_BIAS = 192.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MAXPX = 96.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LENS_AA = 0.75; // above this spread of the picture between neighbouring pixels, a 4x4 footprint is averaged + +// the lights in the drops: a drop is a wide-angle lens and lights up near a bright light (signals, lamps, headlights). taken from +// the mipmaps of the image the screen reflections keep (ssr_history: the last frame, or this one in the motion blur), so the glow +// is smooth: point samples of the full image caught a headlight of one pixel only at fixed offsets and drew it as grids of dots +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights in the drops (0 = off) +const float WS_LIGHT_CAP = 8.0; // the most the glow adds to a drop (brightness, scene units) +const float WS_LIGHT_MIN_LUM = 1.0; // a light: the fine level at least this bright (scene units) above the place around it ... +const float WS_LIGHT_CONTRAST = 3.0; // ... and this many times brighter than it +const float WS_LIGHT_FINE = 3.5; // mip levels: the drop's own neighbourhood (~11 px), a wider one (~32 px), the place around +const float WS_LIGHT_MID = 5.0; +const float WS_LIGHT_WIDE = 7.0; +const float WS_LIGHT_MID_SHARE = 0.5; // how much the lights a little further away count + +// the vulkan renderer gives the post-processing only its own images (LAYOUT_POST): no history of the reflections, no glow there +#ifndef LAYOUT_POST +layout(binding = SSR_HISTORY_TEX) uniform sampler2D ws_light_history; +#endif + +// reverse z, infinite far: depth = znear / distance. a sample is "the cab" when it is much nearer than the centre and closer than ~5 m +const float WS_NEAR_RATIO = 1.6; +const float WS_NEAR_DEPTH = 0.02; + +bool wsSameLayer(float d, float d0) +{ + return d <= max(d0 * WS_NEAR_RATIO, WS_NEAR_DEPTH); +} + +float wsLum(vec3 c) +{ + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +// a drop pixel (drop, rivulet): both values in 132..252 +bool wsIsDrop(vec2 raw) +{ + // 132 .. 252 exactly: with msaa the edge of a drop averaged with the scene behind (half the values, up to 126) isn't a drop, + // else its decoded bend was nonsense, pulling the picture from far away for a frame (a drop flashing) + return raw.x > 131.5 && raw.y > 131.5; +} + +vec2 wsBend(vec2 raw) +{ + return clamp((raw - WS_DROP_BIAS) / WS_BEND_ENC, -1.0, 1.0); +} + +#ifndef LAYOUT_POST +// the image of the reflections around Uv as blurred as its mip level Lod, but round: a level of the mipmaps is a grid of squares +// (2^Lod pixels each), and a light read from it alone lit the drops in a square around it. a ring of taps of the finer level +// around the place, weighed as a soft disc, gives the same blur without the squares +vec3 wsHistoryRound(vec2 uv, float lod) +{ + float level = min(lod, ssr_params2.x); + float finer = max(level - 1.0, 0.0); + vec2 pixel = 1.0 / vec2(textureSize(ws_light_history, 0)); + float radius = 0.6 * exp2(level); // pixels of the image + vec3 sum = wsSafe(textureLod(ws_light_history, uv, finer).rgb) * 0.2; + for (int i = 0; i < 8; ++i) + { + float a = (float(i) + 0.5) * 0.7853982; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a), sin(a)) * radius * pixel, finer).rgb) * 0.06; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a + 0.3927), sin(a + 0.3927)) * (2.0 * radius) * pixel, finer).rgb) * 0.04; + } + return sum; +} + +vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) +{ + vec3 c = wsHistoryRound(uv, lod); + vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + // no threshold with an edge: a light dims away from it (the drops right by a lamp the brightest, then less and less); full + // from twice WS_LIGHT_MIN_LUM above the place around, as much as before there + return excess * clamp(wsLum(excess) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); +} + +vec3 wsLightGlow(vec2 uv) +{ + if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) + return vec3(0.0); + vec3 wide = wsHistoryRound(uv, WS_LIGHT_WIDE); + // the near light in full, the one a little further away fading with it squared: the farther the drop, the less + vec3 mid = wsLightExcess(uv, WS_LIGHT_MID, wide); + float midF = clamp(wsLum(mid) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * mid * midF; + glow *= WS_LIGHT_GAIN; + // a light close by is kept to the brightness of one light + return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); +} +#else +vec3 wsLightGlow(vec2 uv) +{ + return vec3(0.0); +} +#endif + +// the picture at Uv seen through the drop, for a drop pixel with the request Raw +vec3 wsDropRefraction(sampler2D colortex, sampler2D velocitytex, sampler2D depthtex, vec2 uv, vec2 raw) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 center = wsFetch(colortex, uv); + + vec2 bend = wsBend(raw); + vec2 uv2 = uv - bend * WS_REFR_MAXPX * texelSize; + + // the spread of the picture between neighbouring pixels (the jacobian of the shift): a drop shows a minified, flipped copy + // of the scene, single samples would alias into a hatch there + vec2 rx = textureLod(velocitytex, uv + vec2(texelSize.x, 0.0), 0.0).xy; + vec2 ry = textureLod(velocitytex, uv + vec2(0.0, texelSize.y), 0.0).xy; + vec2 jx = (wsIsDrop(rx) ? wsBend(rx) - bend : vec2(0.0)) * WS_REFR_MAXPX; + vec2 jy = (wsIsDrop(ry) ? wsBend(ry) - bend : vec2(0.0)) * WS_REFR_MAXPX; + float lens = length(jx) + length(jy); + + // never pull in what is much nearer than the scene behind the glass (the cab) + vec3 refr = center; + float d0 = textureLod(depthtex, uv, 0.0).x; + float d1 = textureLod(depthtex, uv2, 0.0).x; + if (wsSameLayer(d1, d0)) + { + if (lens < WS_LENS_AA) + { + refr = wsFetch(colortex, uv2); + } + else + { + vec2 fx = clamp(vec2(1.0, 0.0) - jx, vec2(-10.0), vec2(10.0)); + vec2 fy = clamp(vec2(0.0, 1.0) - jy, vec2(-10.0), vec2(10.0)); + vec3 acc = vec3(0.0); + float wacc = 0.0; + for (int j = 0; j < 4; ++j) + { + for (int i = 0; i < 4; ++i) + { + vec2 t = (vec2(float(i), float(j)) + 0.5) / 4.0 - 0.5; + vec3 c = wsFetch(colortex, uv2 + (fx * t.x + fy * t.y) * texelSize); + float w = wsKaris(c); + acc += c * w; + wacc += w; + } + } + refr = acc / wacc; + } + } + + vec3 outc = mix(center, refr, WS_REFR_MIX); + // the glow only in the drops themselves, strongest in their middle, where the lens bends most: the water film and the + // rivulets between them (no bend) would show it as flat squares around the headlights of an oncoming train + float glowW = smoothstep(0.03, 0.2, length(bend)); + if ((WS_LIGHT_GAIN > 0.0) && (glowW > 0.0)) + outc += wsLightGlow(uv) * glowW; + return outc; +} + +#endif diff --git a/shaders/ogl46/settings.glsl b/shaders/ogl46/settings.glsl index 65c441991..cda2ecf39 100644 --- a/shaders/ogl46/settings.glsl +++ b/shaders/ogl46/settings.glsl @@ -4,7 +4,8 @@ #ifndef SETTINGS_GLSL #define SETTINGS_GLSL -#ifdef GL_SPIRV +// (some drivers, AMD's among them, define GL_SPIRV also when they compile the source: the game always puts the values before it) +#if defined(GL_SPIRV) && !defined(SHADOWMAP_ENABLED_VALUE) layout(constant_id = 0) const bool SHADOWMAP_ENABLED = true; layout(constant_id = 1) const bool ENVMAP_ENABLED = true; layout(constant_id = 2) const bool MOTIONBLUR_ENABLED = true; diff --git a/shaders/ogl46/snow_sprites.glsl b/shaders/ogl46/snow_sprites.glsl new file mode 100644 index 000000000..897ae70b9 --- /dev/null +++ b/shaders/ogl46/snow_sprites.glsl @@ -0,0 +1,462 @@ +// the snow on the windscreens laid together from the sprites of the atlas (mat_snow_windscreen.frag, water_snowlayer.comp): the +// tuning of the look of the snow and the laying of the lumps, the dots and the drops. the including file declares the samplers +// raindropsatlas and normalmap (the atlas of the snow and its normal map) and includes random.glsl and water.glsl before + +#ifndef SNOW_SPRITES_GLSL +#define SNOW_SPRITES_GLSL + +// --- tuning ------------------------------------------------------------------------------------------------------------------ +const float snow_flake_cell = 0.010; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff +const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) +const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow +const float snow_lump_cell = 0.0225; // a lump at most every this many metres of the glass (its size: up to two of them) +const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) +const float snow_heap_cells = 2.85; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) +const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_ice = 0.75; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow +const float snow_thin = 0.5; // opacity of the most glassy flake; each flake is at random from it to fully white +const float snow_glassy = 0.45; // opacity of the most glassy lump until the snow gets thick; each lump from it to fully white +const float snow_lump_white = 0.88; // opacity of the whitest lump until the snow gets thick (the flakes under it show through) +const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat +const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt +const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off +const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them +const float snow_wet_blur = 0.6; // blur of the scene behind a wet film +const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain + // mists the glass up: the gaps between the lumps too, clear again behind a blade) + +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl + +const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) +const float SNOW_PACKED = 0.4; // and of packed snow + +// tiles of the atlas +const int TILE_DROP = 15; + +vec2 snUV = vec2(0.0); // the place on the glass laid, uv +int snSlot = 0; +uint snMap = 0u; +bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) +float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) +vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) +float snBendA = 0.0; + +struct sprite_acc +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied +}; + +// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the +// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) +vec2 snTile(int tile) +{ + if (snBig) + return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; + int old = 0; // a fluffy flake + if ((tile == 6) || (tile == 7)) + old = 2; // crumbs + else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) + old = 1; // a wet lump + else if (tile == TILE_DROP) + old = 3; // a melted spot + return vec2(float(old % 2), float(1 - old / 2)) * 0.5; +} + +float snTileSize() +{ + return snBig ? 0.25 : 0.5; +} + +// the snow under the middle of a sprite: the texel of the map there, not filtered between four (a sprite reads it once for all +// of its pixels, so it changes nothing of its shape; two reads of the storage instead of eight, for each sprite of each pixel) +vec4 snSnowAt(vec2 uv) +{ + return water_snow_texel(uint(snSlot), snMap, ivec2(floor(uv * float(WATER_MAP)))); +} + +// how white a sprite is (0 glassy, stuck and half melted, 1 dry powder), at random from its Random, whiter where the snow is +// Thick (0 .. 1); another number than Random, so it goes its own way of the tone +float snWhite(float random, float thick) +{ + float r = fract(random * 13.731 + 0.377); + return smoothstep(0.0, 1.0, clamp(r + (thick - 0.5) * 0.7, 0.0, 1.0)); +} + +// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) +{ + vec2 uv = snTile(tile) + local * snTileSize(); + vec4 t = textureLod(raindropsatlas, uv, lod); + vec4 n = textureLod(normalmap, uv, lod); + float a = clamp(t.a * alpha, 0.0, 1.0); + if (a <= 0.002) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + // front to back: the sprites come from the top one down (the same picture as laying them back to front), so the pixel stops + // looking once the snow over it covers it + float w = a * (1.0 - acc.a); + acc.rgb += t.rgb * tone * w; + acc.n += nT * w; + acc.tr += (1.0 - t.a * 0.55) * w; + acc.a += w; + // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush + // the most + float bends = snow_ice_bend * bend; // the atlas holds icy snow only + float wb = a * (1.0 - snBendA); + snBend += nuv * bends * wb; + snBendA += wb; +} + +// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite +// in them), Aspect the cells as they lie on the glass; false outside the sprite +bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) +{ + vec2 d = (p - c) * aspect; + vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); + r.x *= flip / aniso; + local = r / size + 0.5; + return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); +} + +float snLod(float pixelUV, float sizeUV) +{ + float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); + return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); +} + +// how wet the snow of a state of the map is (0 dry .. 1 slush) +float snWetness(vec4 q) +{ + return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); +} + +// the tone of the snow: grey and darker when wet (slush), a little grey when packed +vec3 snTone(vec4 q, float random) +{ + vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; + tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); + return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); +} + +// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with +// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) +float snHeap(ivec2 cell) +{ + vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; + ivec2 i = ivec2(floor(c - 0.5)); + vec2 f = c - 0.5 - vec2(i); + f = f * f * (3.0 - 2.0 * f); + uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); + uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); + uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); + uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); + return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); +} + +// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its +// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around +// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns +// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last +// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner +struct lump_grid +{ + vec2 shift; // the grid shifted, cells + uint salt; + vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) + vec2 size; // the size of its lumps, cells: from .. to (random per cell) + int tiles; // its tiles, in sn_lump_tiles: the first one and how many + int count; + float share; // the share of its cells having a lump at all (1: all of them) +}; + +// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15) +const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); + +// the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid +// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing +// the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) +const int SN_GRIDS = 5; +const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), + lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0)); +// (nine grids before: each grid alone covers the glass a few times over, so five close it as well, with fewer sprites one on +// another at a pixel) + +const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at + +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake. the flake of a Cell at P +// (the place in cells): true when it is there and comes within Reach (cells) of P; laid over Acc where it covers P +bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, inout sprite_acc acc) +{ + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly part, so + // it is read only for a flake which, as big as it gets, covers the pixel + float chance = RandF(seed); + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float sizeDraw = mix(0.6, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + vec4 q = snSnowAt(centre / perUV); + // only the dry snow has its flakes: no drops of the melted ones (the round drops and the wet lumps with their film, tiles 8, 9, + // 14, 15, aren't used) + bool drop = false; + bool crystal = (q.x >= 0.05); + if (false == crystal) + return false; + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + return false; + float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) + return true; + int tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) + tile += (tile < 2) ? 0 : 4; + float white = snWhite(random, smoothstep(0.05, snow_cover * 3.0, q.x)); + float alpha = mix(snow_thin, 1.0, white); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - white, acc); + return true; +} + +// the lump of a Cell of a Grid at P (the place in the cells of the grid, shifted): true when it is there and comes within Reach +// (cells) of P; laid over Acc where it covers P +bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, float reach, inout sprite_acc acc) +{ + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly part, so it + // is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) + float needsDraw = RandF(seed); + if (RandF(seed) >= grid.share) + return false; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + int tile = sn_lump_tiles[grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)]; + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = snSnowAt((centre - grid.shift) / perUV); + if (q.x <= needs) + return false; + float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) + return true; + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float white = snWhite(random, smoothstep(snow_cover, snow_deep, q.x)); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, snow_lump_white, white), 1.0, deep); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), (1.0 - deep) * (1.0 - white), acc); + return true; +} + +// the snow of the glass laid together: the flakes over the lumps, as water_snowlayer.comp lists them for the texels of the layer +// and mat_snow_windscreen.frag lays them at its pixels (or, for a glass without the layer, all of them at its pixels) +struct snow_layer_s +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied + vec2 bend; // the bend of the picture behind, weighted + float bendA; // its weight + float haze; // the blur of the picture behind the thin snow +}; + +snow_layer_s snFinish(sprite_acc flakes, sprite_acc layer) +{ + snow_layer_s s; + // the flakes over the layer + s.rgb = flakes.rgb + layer.rgb * (1.0 - flakes.a); + s.a = flakes.a + layer.a * (1.0 - flakes.a); + s.n = flakes.n + layer.n * (1.0 - flakes.a); + s.tr = flakes.tr + layer.tr * (1.0 - flakes.a); + s.bend = snBend; + s.bendA = snBendA; + // the picture behind thin flakes is blurred + s.haze = smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6; + return s; +} + +// the snow of the glass laid together at UV from all the cells around it. Span: metres of the glass in a unit of its uv; +// PixelUV: the uv a pixel covers (the level of the atlas). snSlot, snMap and snBig set before +snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // laid front to back: the flakes, then the grids from the top one down, so a pixel stops looking once the snow over it covers + // it + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + for (int oy = 1; oy >= -1; --oy) + for (int ox = 1; ox >= -1; --ox) + snFlakeCell(pF, hereF + ivec2(ox, oy), perF, pixelUV, 0.0, flakes); + vec2 perL = span / snow_lump_cell; + for (int g = 0; g < SN_GRIDS; ++g) + { + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (layer.a >= SN_COVERED) + return snFinish(flakes, layer); // the grids over this one cover the pixel + snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, 0.0, layer); + } + } + return snFinish(flakes, layer); +} + +// the layer of the snow of a glass (water_snowlayer.comp writes it, mat_snow_windscreen.frag reads it) holds for each of its +// texels (~1 mm of the glass) the sprites coming within it, in the order they are laid: up to SN_REFS bytes in four uint, each +// 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column +// offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at +// its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost +const int SN_REFS = 6; // the top ones, the listing stops when full (sixteen fit in the four uint; 8 if thick snow shows gaps) +// the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out +const float SN_LIST_COVERED = 0.97; + +void snRef(uint ref, inout uvec4 refs, inout int count) +{ + if (count >= SN_REFS) + return; + uint shift = 8u * uint(count & 3); + refs[count >> 2] = (refs[count >> 2] & ~(255u << shift)) | ((ref + 1u) << shift); + ++count; +} + +// the sprites of the texel of the layer centred at UV (PixelUV its size in the uv), as the layer holds them +uvec4 snList(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + uvec4 refs = uvec4(0u); + int count = 0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the sprites coming within the corners of the texel (cells of the list), as big as they grow before it is listed anew + float half_diagonal = 0.75 * pixelUV; + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; + for (int k = 0; k < 9; ++k) + { + if (count >= 2) + break; // two flakes at most, the rest of the list for the lumps + if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); + } + vec2 perL = span / snow_lump_cell; + float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; + for (int g = 0; g < SN_GRIDS; ++g) + { + if ((layer.a >= SN_LIST_COVERED) || (count >= SN_REFS)) + break; // the grids over this one cover the texel, or the list is full + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (count >= SN_REFS) + break; // the list is full: nothing more worked out, and the cover counts only the sprites the glass lays + if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) + snRef(uint(16 * (g + 1) + k), refs, count); + } + } + return refs; +} + +// the snow of the glass laid together at UV from the sprites Refs of the texel of the layer centred at CentreUV (the cells +// counted around that). Span: metres of the glass in a unit of its uv at the texel; PixelUV: the uv a pixel covers +snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uvec4 refs) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + vec2 perF = span / snow_flake_cell; + vec2 perL = span / snow_lump_cell; + for (int r = 0; r < SN_REFS; ++r) + { + uint ref = (refs[r >> 2] >> (8u * uint(r & 3))) & 255u; + if (ref == 0u) + break; + --ref; + int list = int(ref >> 4u); + int k = int(ref & 15u); + ivec2 offset = ivec2(1 - k % 3, 1 - k / 3); + if ((list == 0) && (k < 9)) + { + snFlakeCell(uv * perF, ivec2(floor(centreUV * perF)) + offset, perF, pixelUV, 0.0, flakes); + continue; + } + if ((list > SN_GRIDS) || (k >= 9) || (layer.a >= SN_COVERED)) + continue; // nothing laid, or the grids over this one cover the pixel + lump_grid grid = sn_grids[list - 1]; + ivec2 here = ivec2(floor(centreUV * perL + grid.shift)); + snLumpCell(uv * perL + grid.shift, here + offset, perL, grid, pixelUV, 0.0, layer); + } + return snFinish(flakes, layer); +} + +// the metres of the glass in a unit of its uv at UV, from the texel of its map there or, at the edge of the glass, the nearest +// one next to it the glass is on; false when there is none +bool snSpan(uint slot, vec2 uv, out vec2 span) +{ + span = vec2(0.05); + ivec2 at = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + // the texel itself first, then the ones beside it, then the corners + const ivec2 near[9] = ivec2[9](ivec2(0), ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1), ivec2(1), ivec2(-1, 1), ivec2(1, -1), ivec2(-1)); + for (int k = 0; k < 9; ++k) + { + ivec2 t = clamp(at + near[k], ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (slot * uint(WATER_MAP * WATER_MAP) + uint(t.y * WATER_MAP + t.x)) * 2u; + if (water_axes[axis].w > 0.0) + { + span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + return true; + } + } + return false; +} + +#endif diff --git a/shaders/ogl46/tonemapping.glsl b/shaders/ogl46/tonemapping.glsl index 4dd648457..ae08bada8 100644 --- a/shaders/ogl46/tonemapping.glsl +++ b/shaders/ogl46/tonemapping.glsl @@ -162,7 +162,8 @@ vec4 tonemap(vec4 x) // 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)))); + // the bvec3 overload selects instead of blending, so a NaN does not get through 0 * NaN + hdr = mix(hdr, vec3(0.0), bvec3(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)); diff --git a/shaders/ogl46/water.glsl b/shaders/ogl46/water.glsl index 6c3dcbfba..418f3455b 100644 --- a/shaders/ogl46/water.glsl +++ b/shaders/ogl46/water.glsl @@ -53,6 +53,91 @@ layout(std430, binding = WATER_SSBO_BINDING) readonly buffer water_ssbo uint water_cells[]; }; +// the snow on a glass of the snow (water_snow.comp, mat_snow_windscreen.frag): two maps of WATER_MAP x WATER_MAP texels after the +// wetted paths in water_cells, two uint a texel (halves: x the snow, mm, y the water, mm, z how packed the snow is 0 .. 1, w random +// 0 .. 1, the shape of its flakes); a step reads one and writes the other, the header of the glass says which one is the latest +// (z 1 when there's a map of the snow, w the map) +uint water_snow_base(uint slot, uint map) +{ + return uint(WATER_SLOTS * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS)) + uint(WATER_SLOTS * WATER_TRAIL * WATER_TRAIL) + (map * uint(WATER_SLOTS) + slot) * uint(WATER_MAP * WATER_MAP * 2); +} + +// a texel of a map of the snow, nothing outside the map +vec4 water_snow_texel(uint slot, uint map, ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return vec4(0.0); + uint index = water_snow_base(slot, map) + 2u * uint(texel.y * WATER_MAP + texel.x); + return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); +} + +// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag), after the maps of the snow: eight +// uint of every glass (the rectangle of its uv the layer takes: the corner and the size, floats; the texels of the layer across +// and down, 0 when the glass has no layer: the cab has one, for its first glass of the snow), then the layer, WATER_LAYER_TEXELS +// texels of four uint each: the sprites of the snow coming within the texel, in the order they are laid (snow_sprites.glsl, +// snList) +void water_layer_rect(uint slot, out vec4 rect, out uvec2 size) +{ + uint info = water_snow_base(0u, 2u) + slot * 8u; + rect = uintBitsToFloat(uvec4(water_cells[info], water_cells[info + 1u], water_cells[info + 2u], water_cells[info + 3u])); + size = uvec2(water_cells[info + 4u], water_cells[info + 5u]); +} + +uint water_layer_base() +{ + return water_snow_base(0u, 2u) + uint(WATER_SLOTS) * 8u; +} + +// whether the glass has the layer of the snow +bool water_layer_of(uint slot) +{ + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + return (size.x > 0u) && (size.y > 0u) && all(greaterThan(rect.zw, vec2(0.0))); +} + +// the sprites of the snow of a glass at UV, as its layer holds them for the texel there (Refs, see snow_sprites.glsl), and the +// centre of that texel (CentreUV); false outside the layer +bool water_layer_refs(uint slot, vec2 uv, out uvec4 refs, out vec2 centreUV) +{ + refs = uvec4(0u); + centreUV = uv; + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (size.y == 0u) || any(lessThanEqual(rect.zw, vec2(0.0)))) + return false; + ivec2 t = ivec2(floor((uv - rect.xy) / rect.zw * vec2(size))); + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) + return false; + centreUV = rect.xy + (vec2(t) + 0.5) / vec2(size) * rect.zw; + uint index = water_layer_base() + 4u * (uint(t.y) * size.x + uint(t.x)); + refs = uvec4(water_cells[index], water_cells[index + 1u], water_cells[index + 2u], water_cells[index + 3u]); + return true; +} + +// the latest map of the snow of a glass; false when there's none yet +bool water_snow_map(uint slot, out uint map) +{ + vec4 header = water_header[slot]; + map = (header.w > 0.5) ? 1u : 0u; + return header.z > 0.5; +} + +// the latest map of the snow filtered between the texels at a place of the glass +vec4 water_snow_at(uint slot, uint map, vec2 uv) +{ + vec2 p = uv * float(WATER_MAP) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + vec4 a = water_snow_texel(slot, map, i); + vec4 b = water_snow_texel(slot, map, i + ivec2(1, 0)); + vec4 c = water_snow_texel(slot, map, i + ivec2(0, 1)); + vec4 d = water_snow_texel(slot, map, i + ivec2(1, 1)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); +} + // the radius of the footprint of a drop holding Volume mm3 of water, metres: a cap of a sphere meeting the glass at 40 degrees float water_radius(float volume) { diff --git a/shaders/ogl46/water_sim.glsl b/shaders/ogl46/water_sim.glsl index 75919c9e9..d611b6c0e 100644 --- a/shaders/ogl46/water_sim.glsl +++ b/shaders/ogl46/water_sim.glsl @@ -41,6 +41,11 @@ layout(std140, binding = WATER_UBO_BINDING) uniform water_ubo // every glass: x the landings tried in the step, y 1 / the most metres squared a unit of its uv holds, z 1 when it's simulated, // w the size of its drops (rain_scale of its material) vec4 water_slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the air + // the glass is, degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + vec4 water_snow; + // every glass: 1 when its snow is simulated + vec4 water_snow_slots; }; const float WATER_GRAVITY = 9.81; diff --git a/shaders/ogl46/water_snow.comp b/shaders/ogl46/water_snow.comp new file mode 100644 index 000000000..96b6fbfc5 --- /dev/null +++ b/shaders/ogl46/water_snow.comp @@ -0,0 +1,357 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl): a step of the snow of the glasses of the snow, a thread per texel of +// the map of a glass, a row of groups per glass. the step reads one map of the snow and writes the other (water_snow.w says which +// one it reads), so a texel sees its neighbours as they were before the step +// +// what a texel holds: the snow, mm (as it lies, fluffy or packed), the water, mm (the melted snow, a film on the glass and soaked +// into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its +// flakes (mat_snow_windscreen.frag). in a step, in this order: +// - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, +// the water runs down as a film and is pushed by the air. what goes over the edge of the glass falls off. snow doesn't spread +// onto its neighbours by itself: it sticks to the glass, so the edge of a wiped area stays where the blade left it +// - the blades wipe, as they wipe the rain: a blade going over a texel in the step takes its snow (a little stays, and a wet +// trace of the water); what it takes is gone +// - now and then the thick snow lets go of the glass in a slab and slides off it, the glass bare behind it +// - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off. +// near zero the flakes are wet: they bring some water with them (wet snow, lumps of slush) +// - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the +// snow melts at the glass into its water, the water dries slowly + +#include "common.glsl" +#include "water_sim.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// how dense the snow is: fresh flakes and snow pressed by a blade (the water in a mm of it, mm) +const float SNOW_FRESH = 0.1; +const float SNOW_PACKED = 0.4; +// the snow of a flake, mm3 of water (0.3 .. 2.5 as the flakes of the water passes, water_spawn.comp) +const float SNOW_FLAKE_LEAST = 0.3; +const float SNOW_FLAKE_MOST = 2.5; +// the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it +const float SNOW_EDDIES = 0.6; +// the most snow a texel holds, mm +const float SNOW_MOST = 40.0; +// the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and +// of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) +const float SNOW_WIPE_MISS = 0.03; +const float SNOW_WIPE_LEFT = 0.03; +const float SNOW_WIPE_WATER = 0.1; +const float SNOW_WIPE_TRACE = 0.08; +const float SNOW_WIPE_WET = 0.015; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm (the heat the glass passes on, +// ~70 W/m2 a degree, melts 0.0002 mm of water a second) +const float SNOW_MELT = 0.0002; +// the share of the snowfall the flakes of water_snow.x make (the renderer counts a quarter of them, as for the particles of the +// drop passes): the snow of the map gets a bit more of it (all of it built up too fast) +const float SNOW_FALL_SHARE = 1.5; +// the most of the speed of the snow against the glass counting for the snow landing, m/s: at speed most of the flakes go past or +// bounce off, so a front glass builds up its snow a few times as fast as a standing one, not a hundred +const float SNOW_FACING_MOST = 6.0; +// how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) +const float SNOW_WARMTH = 1.0; +// the share of a flake landing near zero already water (wet snow) +const float SNOW_WET_FLAKES = 0.5; +// the water freezing a second on a glass below zero, mm +const float SNOW_FREEZE = 0.02; +// the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) +const float SNOW_DRY = 0.0004; +const float SNOW_FILM_DRY = 0.15; +// how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the +// glass), how fast the film of water runs down a vertical glass and goes with the air, m/s +const float SNOW_SLIDE = 0.03; +const float SNOW_BLOW = 0.0005; +const float SNOW_RUN = 0.02; +const float SNOW_RUN_AIR = 0.002; + +// the slabs: where the snow is thick, now and then a slab of it lets go and slides off the glass (on a glass plastered over a slab +// every SNOW_SLAB_EVERY seconds, on a frozen glass less often). its upper edge goes down the slab in SNOW_SLAB_SLIDE seconds and +// the glass behind it is bare, but for a little of the snow +// (the snow in the middle of the slab decides: the whole slab goes, a wiped glass as one never wiped, where the snow is as thick). +// every slab lets go from snow of its own, random: the more snow, the more of them go +const vec2 SNOW_SLAB_DEEP = vec2(0.4, 2.5); // mm of snow from which a slab lets go: from .. to (the glass is closed by 2-3 mm) +const float SNOW_SLAB_CELL = 24.0; // texels: at most a slab in a cell this big, about as big as the cell +const float SNOW_SLAB_EVERY = 3.0; // s +const float SNOW_SLAB_PERIOD = 10.0; // s: a cell draws for its slab once in this time +const float SNOW_SLAB_SLIDE = 1.2; // s +const float SNOW_SLAB_LEFT = 0.05; // the share of the snow a slab leaves + +struct snow_slab_s +{ + vec2 centre; // texels + float radius; // texels + float start; // s into the period + float deep; // mm of snow in its middle from which it lets go +}; + +uint snow_slot; +uint snow_from; +uint snow_axes_base; + +bool snow_on_glass(ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return false; + return water_axes[(snow_axes_base + uint(texel.y * WATER_MAP + texel.x)) * 2u].w > 0.75; +} + +vec4 snow_get(ivec2 texel) +{ + return snow_on_glass(texel) ? water_snow_texel(snow_slot, snow_from, texel) : vec4(0.0); +} + +float snow_blade(ivec2 texel, int blade) +{ + texel = clamp(texel, ivec2(0), ivec2(WATER_MAP - 1)); + return water_blades[snow_axes_base + uint(texel.y * WATER_MAP + texel.x)][blade]; +} + +// whether the blade went over the texel in the step (it reaches it, and the place of the texel along its sweep is between where +// the blade was and where it is, the place it was at belonging to the step before) +bool snow_crossed(ivec2 texel, int blade) +{ + float before = water_blades_before[blade]; + float now = water_blades_now[blade]; + if ((before < 0.0) || (now < 0.0) || (now == before) || (false == snow_on_glass(texel))) + return false; + float place = snow_blade(texel, blade); + if (place <= 0.001) + return false; + return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); +} + +// the slab of a cell in a period, if the cell has one; the more often the warmer the glass (wet snow lets go sooner) +bool snow_slab_of(ivec2 cell, uint period, float glass, out snow_slab_s slab) +{ + vec4 draw = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51abu); + vec4 shape = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51acu); + slab = snow_slab_s((vec2(cell) + 0.2 + 0.6 * shape.xy) * SNOW_SLAB_CELL, mix(0.5, 0.9, shape.z) * SNOW_SLAB_CELL, + shape.w * (SNOW_SLAB_PERIOD - SNOW_SLAB_SLIDE), mix(SNOW_SLAB_DEEP.x, SNOW_SLAB_DEEP.y, draw.y)); + float cells = float(WATER_MAP * WATER_MAP) / (SNOW_SLAB_CELL * SNOW_SLAB_CELL); + float chance = SNOW_SLAB_PERIOD / SNOW_SLAB_EVERY / cells * mix(0.4, 1.0, smoothstep(-6.0, 0.0, glass)); + return draw.x < chance; +} + +// whether the upper edge of the slab is past the place (texels) now, t seconds into the period: the place in the slab (its edge +// ragged) and above the edge going down it, faster and faster +bool snow_in_slab(vec2 p, vec2 down, float t, snow_slab_s slab) +{ + float progress = (t - slab.start) / SNOW_SLAB_SLIDE; + if ((progress < 0.0) || (progress > 1.0)) + return false; + vec2 off = p - slab.centre; + float ragged = slab.radius * mix(0.7, 1.15, water_noise(p / 5.0, 0x5a1bu + snow_slot)); + if (dot(off, off) > ragged * ragged) + return false; + return dot(off, down) < mix(-1.2, 1.2, progress * progress) * slab.radius; +} + +// whether a slab slides off the texel now; down: down the glass, texels (normalized) +bool snow_slid(ivec2 texel, vec2 down, float glass) +{ + float now = water_step.y; + uint period = uint(floor(now / SNOW_SLAB_PERIOD)); + float t = now - float(period) * SNOW_SLAB_PERIOD; + ivec2 here = ivec2(floor(vec2(texel) / SNOW_SLAB_CELL)); + vec2 p = vec2(texel) + 0.5; + for (int k = 0; k < 9; ++k) + { + snow_slab_s slab; + if ((false == snow_slab_of(here + ivec2(k % 3 - 1, k / 3 - 1), period, glass, slab)) || (false == snow_in_slab(p, down, t, slab))) + continue; + if (snow_get(ivec2(floor(slab.centre))).x >= slab.deep) + return true; + } + return false; +} + +// the frame of the glass at a texel, unfiltered +water_frame_s snow_frame(ivec2 texel) +{ + uint index = snow_axes_base + uint(texel.y * WATER_MAP + texel.x); + vec4 a = water_axes[index * 2u]; + vec4 b = water_axes[index * 2u + 1u]; + water_frame_s frame = water_frame_s(a.xyz, b.xyz, vec3(0.0, 0.0, 1.0), a.w); + vec3 n = cross(a.xyz, b.xyz); + if (dot(n, n) > 1e-24) + frame.normal = normalize(n) * ((b.w < 0.0) ? -1.0 : 1.0); + return frame; +} + +// how the snow (xy) and the water (zw) of a texel move, texels a second +vec4 snow_motion(ivec2 texel, vec4 state) +{ + if ((state.x <= 0.001) && (state.y <= 0.001)) + return vec4(0.0); + water_frame_s frame = snow_frame(texel); + vec3 n = frame.normal; + vec3 down = -water_up.xyz; + vec3 slope = down - n * dot(down, n); + vec3 air = water_air.xyz - n * dot(water_air.xyz, n); + float wind = length(air); + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown + float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.08, 0.25, state.x)); + vec3 snow = slope * slide + air * blow; + // the film of water runs where there's enough of it, not the water soaked into the snow + float film = (1.0 - smoothstep(0.5, 3.0, state.x)); + vec3 water = (slope * SNOW_RUN * smoothstep(0.03, 0.15, state.y) + air * SNOW_RUN_AIR * smoothstep(0.03, 0.1, state.y)) * film; + return vec4(water_to_uv(frame, snow), water_to_uv(frame, water)) * float(WATER_MAP); +} + +// the shares of a texel going to its neighbours along x and along y in the step, for a motion in texels a second +vec2 snow_out(vec2 motion, float seconds) +{ + return min(abs(motion) * seconds, vec2(0.45)); +} + +// the snow and the water of the texel after they moved in the step: what leaves it, what comes from its neighbours; the +// packing and the shape go with the snow +vec4 snow_move(ivec2 texel, vec4 state, float seconds) +{ + vec4 motion = snow_motion(texel, state); + vec2 snowout = snow_out(motion.xy, seconds); + vec2 waterout = snow_out(motion.zw, seconds); + float snow = state.x * (1.0 - snowout.x - snowout.y); + float water = state.y * (1.0 - waterout.x - waterout.y); + float packing = state.z * snow; // (not "packed": a reserved word of GLSL, the NVIDIA OpenGL compiler refuses it) + const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); + for (int k = 0; k < 4; ++k) + { + ivec2 side = sides[k]; + ivec2 other = texel + side; + bool glass = snow_on_glass(other); + if (false == glass) + continue; + vec4 neighbour = water_snow_texel(snow_slot, snow_from, other); + float coming = 0.0; + // what the motion of the neighbour brings: it goes this way along the axis of the side + vec4 itsmotion = snow_motion(other, neighbour); + vec2 itssnow = snow_out(itsmotion.xy, seconds); + vec2 itswater = snow_out(itsmotion.zw, seconds); + if (side.x != 0) + { + coming += (itsmotion.x * float(side.x) < 0.0) ? neighbour.x * itssnow.x : 0.0; + water += (itsmotion.z * float(side.x) < 0.0) ? neighbour.y * itswater.x : 0.0; + } + else + { + coming += (itsmotion.y * float(side.y) < 0.0) ? neighbour.x * itssnow.y : 0.0; + water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; + } + snow += coming; + packing += coming * neighbour.z; + } + snow = max(snow, 0.0); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packing / snow, 0.0, 1.0) : 0.0, state.w); +} + +void main() +{ + snow_slot = gl_WorkGroupID.y; + uint place = gl_GlobalInvocationID.x; + if ((water_snow_slots[snow_slot] < 0.5) || (place >= uint(WATER_MAP * WATER_MAP))) + return; + snow_from = (water_snow.w > 0.5) ? 1u : 0u; + uint to = 1u - snow_from; + snow_axes_base = snow_slot * uint(WATER_MAP * WATER_MAP); + if (place == 0u) + water_header[snow_slot].zw = vec2(1.0, float(to)); + ivec2 texel = ivec2(int(place % uint(WATER_MAP)), int(place / uint(WATER_MAP))); + uint index = water_snow_base(snow_slot, to) + 2u * place; + if (false == snow_on_glass(texel)) + { + water_cells[index] = 0u; + water_cells[index + 1u] = 0u; + return; + } + float seconds = water_step.x; + vec4 before = water_snow_texel(snow_slot, snow_from, texel); + vec4 state = snow_move(texel, before, seconds); + + // how warm the glass is: warmer than the air (the cab heats it), the less so the faster the vehicle goes + float speed = water_snow.z; + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 10.0); + + // the blades: they take the snow where they went over; a wet trace only on a glass above zero (on a frozen one the blade + // leaves it dry, so the snow landing on the wiped glass is the same dry snow as around) + bool crossed = false; + for (int blade = 0; blade < 4; ++blade) + crossed = crossed || snow_crossed(texel, blade); + if (crossed) + { + float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); + float taken = state.x - left; + state.x = left; + float trace = min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET) * smoothstep(-1.0, 1.0, glass); + state.y = state.y * SNOW_WIPE_WATER + trace; + } + + // a slab sliding off (not on a glass lying flat) + water_frame_s frame = snow_frame(texel); + vec3 down = -water_up.xyz; + vec2 downmap = water_to_uv(frame, down - frame.normal * dot(down, frame.normal)) * float(WATER_MAP); + if ((state.x > 0.0) && (dot(downmap, downmap) > 0.25) && snow_slid(texel, normalize(downmap), glass)) + state.x *= SNOW_SLAB_LEFT; + + // the flakes landing + float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 + vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s + // the snow coming at the glass along its normal. the side of the glass the snow comes from isn't told: the outward side of + // the frames of the map (from the middle of the box around the cab model) and the air against the cab (from the matrix of + // the vehicle and its velocity) don't agree for every cab, and with them disagreeing a front glass at speed got the snow of + // the eddies only, plastered no faster than a standing one. the glass the driver looks through leads, so the snow comes at + // it from the outside + float facing = min(abs(dot(coming, frame.normal)), SNOW_FACING_MOST) + SNOW_EDDIES; + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or + // water stay + // (only on a bare glass: a flake sticks to the snow already there) + float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)) * (1.0 - smoothstep(0.05, 0.3, state.x)); + float sticking = 1.0 - 0.15 * smoothstep(5.0, 25.0, speed) * dry; + float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; + vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); + float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); + if (count > 0.0) + { + float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 + // the share of a wet flake already water (near zero) + float melting = SNOW_WET_FLAKES * smoothstep(-4.0, 0.5, water_up.w); + float added = water * (1.0 - melting) / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + state.y += water * melting / max(area * 1e6, 1e-3); + float snow = state.x + added; + state.z = state.z * state.x / snow; + // a flake on the bare glass has a shape of its own + state.w = (state.x < 0.3) ? random.z : state.w; + state.x = snow; + } + + // the melting at the warm glass, the freezing at a frozen one (the water turns to ice, packed snow) and the drying + float frozen = min(state.y, SNOW_FREEZE * smoothstep(0.0, -2.0, glass) * seconds); + if (frozen > 0.0) + { + float ice = frozen / SNOW_PACKED; + state.z = (state.z * state.x + ice) / max(state.x + ice, 1e-4); + state.x += ice; + state.y -= frozen; + } + float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); + state.x -= melted / max(density, 1e-3); + float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow + state.y = max(state.y + melted - (SNOW_DRY + SNOW_FILM_DRY * film) * seconds, 0.0); + + state.x = clamp(state.x, 0.0, SNOW_MOST); + state.y = min(state.y, 4.0); + if (state.x < 0.002) + { + state.x = 0.0; + state.z = 0.0; + } + water_cells[index] = packHalf2x16(state.xy); + water_cells[index + 1u] = packHalf2x16(state.zw); +} diff --git a/shaders/ogl46/water_snowlayer.comp b/shaders/ogl46/water_snowlayer.comp new file mode 100644 index 000000000..a27a884dc --- /dev/null +++ b/shaders/ogl46/water_snowlayer.comp @@ -0,0 +1,80 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the sprites of the snow of a glass coming within +// each texel of its layer listed, which mat_snow_windscreen.frag lays at its pixels, sharp from the atlas (looking through the +// nine cells of the ten lists at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per +// texel of the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under +// a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is listed anew in a step (water_counts.w the step), and at +// once wherever a blade went over the glass in the step + +#include "common.glsl" +#include "water_sim.glsl" +#include "random.glsl" + +// the atlas of the snow of the glass and its normal map (raindropsatlas, normalmap of its material) +layout(binding = WATER_SNOW_ATLAS_TEX) uniform sampler2D raindropsatlas; +layout(binding = WATER_SNOW_NORMAL_TEX) uniform sampler2D normalmap; + +#include "snow_sprites.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its +// middle, up to two of its cells (~3 cm) away from a texel it covers +const float SNOW_LAYER_BLADE_MARGIN = 0.06; + +// whether a blade went over the texel of the map, or near it, in the step +bool snow_layer_swept(uint mapTexel) +{ + vec4 place = water_blades[mapTexel]; + for (int blade = 0; blade < 4; ++blade) + { + float now = water_blades_now[blade]; + float before = water_blades_before[blade]; + if ((now < 0.0) || (now == before) || (place[blade] <= 0.001)) + continue; + if ((place[blade] >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place[blade] <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) + return true; + } + return false; +} + +void main() +{ + uint slot = water_counts.z; + uint texel = gl_GlobalInvocationID.x; + if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER_TEXELS)) || (water_snow_slots[slot] < 0.5)) + return; + uint map; + if (false == water_snow_map(slot, map)) + return; + // the layer over the rectangle of the uv the glass takes + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (texel >= size.x * size.y)) + return; + ivec2 at = ivec2(int(texel % size.x), int(texel / size.x)); + vec2 uv = rect.xy + (vec2(at) + 0.5) / vec2(size) * rect.zw; + ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); + // a band of the rows in a step (the snow builds up and melts slowly), and wherever a blade went + bool due = ((uint(at.y) % uint(WATER_LAYER_BANDS)) == (water_counts.w % uint(WATER_LAYER_BANDS))) || snow_layer_swept(mapTexel); + if (false == due) + return; + uint index = water_layer_base() + 4u * texel; + // nothing of the glass there or next to it (a texel on the edge of the glass takes the size of the glass beside it) + vec2 span; + uvec4 refs = uvec4(0u); + if (snSpan(slot, uv, span)) + { + snSlot = int(slot); + snMap = map; + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + refs = snList(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); + } + water_cells[index] = refs.x; + water_cells[index + 1u] = refs.y; + water_cells[index + 2u] = refs.z; + water_cells[index + 3u] = refs.w; +} diff --git a/shaders/vk14/cluster_cull.comp b/shaders/vk14/cluster_cull.comp index 141f9eaf5..3f5792280 100644 --- a/shaders/vk14/cluster_cull.comp +++ b/shaders/vk14/cluster_cull.comp @@ -25,7 +25,8 @@ float light_peak(light_s light) if (light.type == LIGHT_HEADLIGHTS) // weights are the state of the individual lamps and the beam texture, which is not brighter than 1, picks from them return peak * max(light.headlight_weights.r, max(light.headlight_weights.g, light.headlight_weights.b)); - return peak * (1.0 + light.ambient); + // point and spot lights: ambient holds the signed radius of the sphere the light shines from, which brings no brightness + return peak; } // distance from the light at which its contribution falls under MIN_CONTRIBUTION, 0 for a light which has none diff --git a/shaders/vk14/common.glsl b/shaders/vk14/common.glsl index 3dc8df4b8..6c0884dc1 100644 --- a/shaders/vk14/common.glsl +++ b/shaders/vk14/common.glsl @@ -68,7 +68,8 @@ #define SKY_OCCLUSION_HEIGHT_TEX 31 #define SKY_OCCLUSION_TEX 32 #define CAB_PROBE_MASK_TEX 33 -#define PASS_BINDING_COUNT 34 +#define RAIN_CELLS_SSBO 34 +#define PASS_BINDING_COUNT 35 #define MATERIAL_TEXTURE_FIRST 0 #define CL_CLUSTER_UBO 0 #define CL_AABB_SSBO 1 @@ -137,10 +138,18 @@ #define WATER_TRAIL 1024 #define WATER_MAP 256 #define WATER_GROUP_SIZE 64 +#define WATER_LAYER_TEXELS 2097152 +#define WATER_LAYER_BANDS 8 #define CAB_PROBE_SH_SIZE 16 #define CAB_PROBE_SH_GROUP_SIZE 64 #endif +// the places along the sweep of a blade whose rain is kept (gl::WIPER_PASS_BUCKETS): the renderer defines it, an older one doesn't +#ifndef WIPER_PASS_BUCKETS +#define WIPER_PASS_BUCKETS 64 +#endif + + #include "settings.glsl" #if !defined(LAYOUT_UI) && !defined(LAYOUT_COMPUTE) @@ -330,6 +339,17 @@ layout(std140, set = PASS_SET, binding = SCENE_UBO) uniform scene_ubo vec4 cab_probe_sun_color; vec4 cab_probe_sun_box; vec4 cab_probe_sun_world; + // the insects met when the blades were at the ends of their sweep (mat_bugs_windscreen), see gl::scene_ubs + vec4 wiper_bugs_out; + vec4 wiper_bugs_return; + // the place of the camera of the pass in the world (whole 64 m, the rest), see gl::scene_ubs + vec4 camera_hi; + vec4 camera_lo; + // the rain the glass meets: x fallen so far, y how wet the glass is, z how fast it fills, w 1 with the cells of the rain + // worked out in this frame (mat_rain_windscreen), see gl::scene_ubs + vec4 rain_state; + // the rain fallen when a blade last went over a place of its sweep (the wiper mask / 64), see gl::scene_ubs + vec4 wiper_rain_pass[WIPER_PASS_BUCKETS]; }; #ifndef LAYOUT_COMPUTE diff --git a/shaders/vk14/gtao_main.comp b/shaders/vk14/gtao_main.comp index 14f74ef41..f50205223 100644 --- a/shaders/vk14/gtao_main.comp +++ b/shaders/vk14/gtao_main.comp @@ -37,7 +37,7 @@ const float FALLOFF_RANGE = 0.615; float half_depth(ivec2 texel) { ivec2 full_size = textureSize(depth_tex, 0); - return texelFetch(depth_tex, min(texel * 2, full_size - 1), 0).r; + return texelFetch(depth_tex, clamp(texel * 2, ivec2(0), full_size - 1), 0).r; } vec3 view_position(ivec2 texel, float depth) @@ -48,6 +48,27 @@ vec3 view_position(ivec2 texel, float depth) return position.xyz / position.w; } +// the step to the neighbour on one axis which is closer in depth. a neighbour outside the target or in the sky has no +// position and is left out; with neither left, zero +vec3 neighbour_delta(ivec2 texel, ivec2 offset, vec3 position, ivec2 size) +{ + ivec2 before = texel - offset; + ivec2 after = texel + offset; + float depthbefore = all(greaterThanEqual(before, ivec2(0))) ? half_depth(before) : 0.0; + float depthafter = all(lessThan(after, size)) ? half_depth(after) : 0.0; + bool hasbefore = depthbefore > 0.0; + bool hasafter = depthafter > 0.0; + if (!hasbefore && !hasafter) + return vec3(0.0); + if (!hasbefore) + return view_position(after, depthafter) - position; + if (!hasafter) + return position - view_position(before, depthbefore); + vec3 deltabefore = position - view_position(before, depthbefore); + vec3 deltaafter = view_position(after, depthafter) - position; + return (abs(deltaafter.z) < abs(deltabefore.z)) ? deltaafter : deltabefore; +} + // 4x4 ordered pattern, values 0..15 const float BAYER[16] = float[](0.0, 8.0, 2.0, 10.0, 12.0, 4.0, 14.0, 6.0, 3.0, 11.0, 1.0, 9.0, 15.0, 7.0, 13.0, 5.0); @@ -67,14 +88,12 @@ void main() vec3 position = view_position(texel, depth); vec3 view = normalize(-position); - // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it - vec3 left = view_position(texel - ivec2(1, 0), half_depth(texel - ivec2(1, 0))); - vec3 right = view_position(texel + ivec2(1, 0), half_depth(texel + ivec2(1, 0))); - vec3 down = view_position(texel - ivec2(0, 1), half_depth(texel - ivec2(0, 1))); - vec3 up = view_position(texel + ivec2(0, 1), half_depth(texel + ivec2(0, 1))); - vec3 dx = (abs(right.z - position.z) < abs(position.z - left.z)) ? right - position : position - left; - vec3 dy = (abs(up.z - position.z) < abs(position.z - down.z)) ? up - position : position - down; - vec3 normal = normalize(cross(dx, dy)); + // normal from the neighbours: on each axis the one closer in depth, so edges of objects do not bend it. with no + // neighbour on an axis (a thin wire against the sky, the edge of the image) the surface faces the camera + vec3 dx = neighbour_delta(texel, ivec2(1, 0), position, size); + vec3 dy = neighbour_delta(texel, ivec2(0, 1), position, size); + vec3 normal = cross(dx, dy); + normal = (dot(normal, normal) > 1e-24) ? normalize(normal) : view; if (dot(normal, view) < 0.0) normal = -normal; diff --git a/shaders/vk14/light_common.glsl b/shaders/vk14/light_common.glsl index a83b1babd..77e607fd8 100644 --- a/shaders/vk14/light_common.glsl +++ b/shaders/vk14/light_common.glsl @@ -32,6 +32,30 @@ layout(std430, set = PASS_SET, binding = CAB_PROBE_SSBO) readonly buffer cab_pro float glossiness = 1.0; float metalic = 0.0; + +// the materials of the metallic and roughness workflow (mat_pbr.glsl, which defines PBR_SURFACE) describe the surface the way the +// texturing tools do: the perceptual roughness itself in place of the glossiness, the occlusion of the ambient light baked into +// their textures, and the light the surface emits whatever falls on it. they are lit as those tools show them: the sun without +// the sharpened terminator, the highlights not scaled by the specular colour of the submodel, and with the light a rough +// surface reflects after more than one bounce between its facets +float pbr_roughness = 1.0; +float pbr_occlusion = 1.0; +vec3 pbr_emission = vec3(0.0); +// with PBR_COAT, the clear varnish over the surface: how much of it there is (0..1) and its perceptual roughness +float coat_weight = 0.0; +float coat_roughness = 0.0; +// the highlights of the lamps in the varnish, gathered by add_local_light() +vec3 coat_lampspecular = vec3(0.0); +// the reflectance of the varnish at normal incidence (a refractive index of 1.5) +const float COAT_F0 = 0.04; + +// what scales the highlights of the sun and the lamps: specular: of the material, the specular colour of the submodel without +// it. in the pbr materials that parameter is the specular level instead, which shade_surface() gets as Specularity +#ifdef PBR_SURFACE +#define HIGHLIGHT_SCALE 1.0 +#else +#define HIGHLIGHT_SCALE param[1].y +#endif layout(location = 7) in vec4 UserData; #pragma param(weathering, 2, 3, 1, zero) @@ -613,7 +637,18 @@ void add_local_light(light_s light, vec2 part, vec3 fragnormal, inout vec3 diffu float energy = 1.0; if ((light.type != LIGHT_HEADLIGHTS) && (light.ambient != 0.0)) tolight = sphere_light_specular(tolight, fragnormal, abs(light.ambient), spec_roughness, energy); - specular += color * (part.y * param[1].y * energy) * specular_light(normalize(tolight), fragnormal, spec_f0, spec_roughness, LOCAL_LIGHT_BRDF_LIMIT); + specular += color * (part.y * HIGHLIGHT_SCALE * energy) * specular_light(normalize(tolight), fragnormal, spec_f0, spec_roughness, LOCAL_LIGHT_BRDF_LIMIT); +#ifdef PBR_COAT + // the varnish reflects the lamp with a lobe of its own + if (coat_weight > 0.0) + { + vec3 tocoat = light.pos - f_pos.xyz; + float coatenergy = 1.0; + if ((light.type != LIGHT_HEADLIGHTS) && (light.ambient != 0.0)) + tocoat = sphere_light_specular(tocoat, fragnormal, abs(light.ambient), coat_roughness, coatenergy); + coat_lampspecular += color * (part.y * coatenergy) * specular_light(normalize(tocoat), fragnormal, vec3(COAT_F0), coat_roughness, LOCAL_LIGHT_BRDF_LIMIT); + } +#endif } // adds the light of the headlights and lamps which reach the fragment to its diffuse and specular light. these are the ones in @@ -741,7 +776,14 @@ vec3 reflection_surroundings(vec3 fragnormal, float roughness) { vec3 direction = normalize(envmap_direction(fragnormal)); vec3 sky = envmap_sample_rough(normalize(vec3(direction.x, max(direction.y, 0.0), direction.z)), roughness); +#ifdef PBR_SURFACE + // the lobe of a rough surface takes in the sky and the ground at once: the horizon spreads with the roughness, instead of + // drawing a line across the surface + float spread = roughness * roughness; + float below = smoothstep(-spread, 0.25 + spread, -direction.y); +#else float below = smoothstep(0.0, 0.25, -direction.y); +#endif if ((below <= 0.0) || (false == ENVMAP_ENABLED)) return sky; return mix(sky, reflection_ground(), below); @@ -759,10 +801,24 @@ vec3 reflection_surroundings(vec3 fragnormal, float roughness) const float REFLECTION_SCENE_WEIGHT = 0.004; const float REFLECTION_RAY_WEIGHT = 0.012; +#ifdef PBR_SURFACE +// the screen and the rays follow the mirror direction alone: the sharp image of a polished surface, where a rough one shows the +// surroundings blurred. the scene hands the reflection over to the environment map and the probe of the cab, which the +// roughness blurs, between these perceptual roughnesses +const float SCENE_REFLECTION_ROUGHNESS_START = 0.1; +const float SCENE_REFLECTION_ROUGHNESS_END = 0.3; +#endif + // the reflection of the scene in a surface of the given perceptual roughness: the colour times how much of the reflection the // scene gives (rgb), and that share (a), the rest is left to reflection_surroundings() vec4 reflection_scene(vec3 fragnormal, float roughness, float weight) { +#ifdef PBR_SURFACE + float sharpness = 1.0 - smoothstep(SCENE_REFLECTION_ROUGHNESS_START, SCENE_REFLECTION_ROUGHNESS_END, roughness); + if (sharpness <= 0.0) + return vec4(0.0); + weight *= sharpness; +#endif vec3 direction = normalize(reflect(f_pos.xyz, fragnormal)); vec4 result = ssr_trace(f_pos.xyz, normalize(f_normal), direction, roughness); #ifdef REFLECTION_RAYS_ACTIVE @@ -773,6 +829,9 @@ vec4 reflection_scene(vec3 fragnormal, float roughness, float weight) result.rgb += traced.rgb * (1.0 - result.a); result.a += traced.a * (1.0 - result.a); } +#endif +#ifdef PBR_SURFACE + result *= sharpness; #endif return result; } @@ -874,6 +933,17 @@ vec3 cab_probe_reflection(vec3 surroundings, vec3 fragnormal, float roughness, v return surroundings * (1.0 - albedo.a) + light.rgb + albedo.rgb * ambientlight; } +#ifdef PBR_COAT +// what the varnish of a material reflects of the surroundings, with Coatspec the share of them it reflects: the ambient light +// where the material doesn't ask for the cubemap (Shares.x), the scene and the environment map elsewhere (Shares.y; the map +// held back by the occlusion and by the shadow of the sun, as for the surface below) +vec3 coat_reflection(vec3 ambientlight, vec3 envcolor, vec4 scenecolor, vec3 coatspec, vec2 shares, float occlusion, float cubemapshadow) +{ + return ambientlight * coatspec * shares.x * occlusion + + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * cubemapshadow * occlusion)) * coatspec * shares.y; +} +#endif + // lights the surface: the ambient light, the sun (the moon), the headlights and lamps and the reflection of the surroundings. // the units are the ones of the ambient light, the irradiance over pi: a white lambertian surface lit by 1 of it shows 1. // Texturecolor is the albedo (the base colour of a metal), Specularity the specular level of a dielectric (0.5 is the @@ -894,6 +964,11 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref else { // the sky lights the faces turned up and towards the bright part of the sky more than the ones turned to the ground +#ifdef PBR_SURFACE + // inside a cab or an interior the roof and the walls hide the sky: the bright blue zenith doesn't light the faces turned up + // more than the rest, the cab around (its probe) lights them instead + if (cab_interior < 0.5) +#endif fragcolor = add_sky_ambient(fragcolor, fragnormal); #ifndef NO_WEATHERING float weathered = (param[2].w > 0.0 ? clamp(param[2].w * UserData.x, 0.0, 1.0) : 0.0); @@ -907,7 +982,11 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref texturecolor = (tinted > 0.0 ? texturecolor * mix(vec3(1.0), param[2].rgb, tinted) : texturecolor); specularity = mix(specularity, min(specularity, 0.03), smoothstep(0.0, 0.4, polished)); metalic = mix(metalic, 0.0, polished); +#ifdef PBR_SURFACE + pbr_roughness = mix(pbr_roughness, max(pbr_roughness, 0.94), polished); +#else glossiness = mix(glossiness, min(glossiness, 0.06 * abs(param[1].w)), polished); +#endif reflectivity = mix(reflectivity, min(reflectivity, 0.08 * param[1].z), smoothstep(0.0, 0.4, polished)); #endif // Scale ambient before it gets tinted by the texture. @@ -925,7 +1004,11 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref float NdotV = max(dot(fragnormal, view_dir), 1e-4); // glossiness == param[1].w -> mirror, glossiness == 0 -> fully rough +#ifdef PBR_SURFACE + float roughness = clamp(pbr_roughness, 0.0, 1.0); +#else float roughness = clamp(1.0 - glossiness / max(abs(param[1].w), 1.0), 0.0, 1.0); +#endif roughness = max(specular_antialiasing(fragnormal, roughness), MIN_ROUGHNESS); // metals reflect with their base colour, dielectrics with the specular level (0.5 -> 0.04) vec3 f0 = mix(vec3(0.08 * specularity), texturecolor, metalic); @@ -945,6 +1028,10 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref // light a lot; they take a share of it (gfx.postfx.ao.cab), the light which bounces inside them comes from the probe or below if (cab_interior > 0.5) occlusion = mix(1.0, occlusion, ao_params.z); +#ifdef PBR_SURFACE + // the occlusion baked into the textures of the material holds the ambient light back too, whatever the view finds + occlusion = min(occlusion, pbr_occlusion); +#endif vec3 diffuse_occlusion = vec3(1.0); float specular_occlusion = 1.0; if (occlusion < 1.0) @@ -952,6 +1039,15 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref diffuse_occlusion = ao_multi_bounce(occlusion, texturecolor); specular_occlusion = ao_specular(occlusion, NdotV, roughness); } +#ifdef PBR_SURFACE + // a normal map can tilt the normal so far that the reflected ray goes into the surface the geometry has there: such a ray + // finds the surface itself, not the surroundings (the horizon occlusion of Lagarde and de Rousiers 2014) + vec3 surfacenormal = normalize(f_normal); + if (dot(surfacenormal, f_pos.xyz) > 0.0) + surfacenormal = -surfacenormal; + float horizon = clamp(1.0 + dot(reflect(-view_dir, fragnormal), surfacenormal), 0.0, 1.0); + specular_occlusion *= horizon * horizon; +#endif // Pre-integrated env BRDF: how much of the surroundings the surface reflects, for its F0, roughness and the view angle. // the surroundings are the cubemap where the material asks for it (reflectivity) and the ambient light elsewhere, so a @@ -968,6 +1064,15 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref } // what the diffuse layer is left with vec3 diffuse_albedo = texturecolor * (1.0 - metalic) * (1.0 - env_spec); +#ifdef PBR_SURFACE + // the single bounce of the brdf leaves out the light which leaves a rough surface after more bounces between its facets, so + // rough metals come out too dark: the highlights and the reflection are raised by what is missing (Fdez-Aguera, "A multiple + // scattering microfacet model for real-time image based lighting", 2019). a white surface reflects 1 - 0.55 * roughness in + // one bounce: what the two terms of EnvBRDFApprox() add up to + vec3 multibounce = 1.0 + f0 * (1.0 / (1.0 - 0.55 * roughness) - 1.0); + env_spec *= multibounce; + cubemap_spec = env_spec; +#endif if (legacy_coat) { // the varnish: a smooth dielectric layer reflecting the cubemap, worn off where the material is weathered @@ -976,6 +1081,17 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref ambient_share = 1.0; diffuse_albedo *= 1.0 - cubemap_spec * min(cubemap_share, 1.0); } +#ifdef PBR_COAT + // the varnish: a smooth dielectric layer over the surface. what it reflects doesn't reach the surface below (coat_through is + // what does), and it reflects the surroundings, the sun and the lamps with a lobe of its own + coat_weight = matte ? 0.0 : clamp(coat_weight, 0.0, 1.0); + coat_roughness = max(specular_antialiasing(fragnormal, clamp(coat_roughness, 0.0, 1.0)), MIN_ROUGHNESS); + vec3 coat_spec = EnvBRDFApprox(vec3(COAT_F0), coat_roughness, NdotV) * coat_weight; + float coat_through = 1.0 - coat_weight * (COAT_F0 + (1.0 - COAT_F0) * pow(1.0 - NdotV, 5.0)); + float coat_occlusion = ((occlusion < 1.0) ? ao_specular(occlusion, NdotV, coat_roughness) : 1.0) * horizon * horizon; + vec3 coat_envcolor = vec3(0.0); + vec4 coat_scenecolor = vec4(0.0); +#endif // the reflection of the surroundings: the scene where the screen (or the ray tracing) gives it, the sky and the ground of the // environment map elsewhere vec3 envcolor = vec3(0.0); @@ -987,23 +1103,55 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref // inside the cab the cab is what the surroundings are, where the probe holds it if (cabprobe && (cab_probe_params.y > 0.0)) envcolor = cab_probe_reflection(envcolor, fragnormal, env_roughness, cabambient); +#ifdef PBR_COAT + // the varnish reflects the surroundings as well. the scene is traced once, for the layer which shows more of it; the + // other one reflects the environment map alone + if (coat_weight > 0.0) + { + coat_envcolor = reflection_surroundings(fragnormal, coat_roughness) * skyoccl.x; + if (cabprobe && (cab_probe_params.y > 0.0)) + coat_envcolor = cab_probe_reflection(coat_envcolor, fragnormal, coat_roughness, cabambient); + } + float baseweight = cubemap_share * dot(cubemap_spec, vec3(1.0 / 3.0)) * coat_through; + float coatweight = cubemap_share * dot(coat_spec, vec3(1.0 / 3.0)); + bool tracing = (ssr_params.x > 0.0) || (ssr_params2.z > 0.0); + if (tracing && (coatweight >= baseweight) && (coatweight > REFLECTION_SCENE_WEIGHT)) + coat_scenecolor = reflection_scene(fragnormal, coat_roughness, coatweight); + else if (tracing && (baseweight > REFLECTION_SCENE_WEIGHT)) + scenecolor = reflection_scene(fragnormal, env_roughness, baseweight); +#else float sceneweight = cubemap_share * dot(cubemap_spec, vec3(1.0 / 3.0)); if (((ssr_params.x > 0.0) || (ssr_params2.z > 0.0)) && (sceneweight > REFLECTION_SCENE_WEIGHT)) scenecolor = reflection_scene(fragnormal, env_roughness, sceneweight); +#endif } if (lights_count == 0U) - return fragcolor * diffuse_occlusion * diffuse_albedo - + emissioncolor * texturecolor - + fragcolor * env_spec * ambient_share * specular_occlusion - + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * specular_occlusion)) * cubemap_spec * cubemap_share; + { + vec3 unlit = fragcolor * diffuse_occlusion * diffuse_albedo + + emissioncolor * texturecolor + + fragcolor * env_spec * ambient_share * specular_occlusion + + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * specular_occlusion)) * cubemap_spec * cubemap_share; +#ifdef PBR_SURFACE + unlit += pbr_emission; +#endif +#ifdef PBR_COAT + unlit = unlit * coat_through + + coat_reflection(fragcolor, coat_envcolor, coat_scenecolor, coat_spec, vec2(ambient_share, cubemap_share), coat_occlusion, 1.0); +#endif + return unlit; + } vec3 light_dir = normalize(-lights[0].dir); float NdotL = max(dot(fragnormal, light_dir), 0.0); // Sharpen sun N.L falloff so the lit-to-shaded terminator on cab // panels, vehicle bodies and terrain reads as a clear edge rather // than a soft Lambertian ramp. Tunable via SUN_NDOTL_SHARPNESS. +#ifdef PBR_SURFACE + float sun_NdotL = NdotL; +#else float sun_NdotL = pow(NdotL, SUN_NDOTL_SHARPNESS); +#endif // the clouds hold back the sun (the moon at night) where their shadow falls float cloudsun = cloud_shadow(mat3(inv_view) * f_pos.xyz); // Sun HDR scale -> SUN_DIFFUSE_SCALE, the same for the diffuse and the specular light @@ -1032,6 +1180,9 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref // the reflection of the surroundings, before the light of the sun and the lamps joins the ambient light vec3 env_reflection = fragcolor * env_spec * ambient_share * specular_occlusion + (scenecolor.rgb + envcolor * ((1.0 - scenecolor.a) * cubemap_shadow * specular_occlusion)) * cubemap_spec * cubemap_share; +#ifdef PBR_COAT + vec3 coat_light = coat_reflection(fragcolor, coat_envcolor, coat_scenecolor, coat_spec, vec2(ambient_share, cubemap_share), coat_occlusion, cubemap_shadow); +#endif // the sun coming in through the windows and bouncing around a low poly interior, or the cab without its probe (which gives that // light from where the sun falls in the cab): a share of the light of the sun outside joins the ambient light (gfx.interior.bounce) if ((cab_interior > 0.5) && (false == cabprobe)) @@ -1047,12 +1198,27 @@ vec3 shade_surface(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float ref vec3 lampspecular = vec3(0.0); add_local_lights(fragnormal, fragcolor, lampspecular); +#ifdef PBR_SURFACE + specular *= multibounce; + lampspecular *= multibounce; +#endif - return fragcolor * diffuse_albedo // ambient, sun and lamps on the diffuse layer - + specular * param[1].y // highlight of the sun, fresnel coloured (metals take their base colour) - + lampspecular // highlights of the lamps, param[1].y already applied - + emissioncolor * texturecolor - + env_reflection; + vec3 lit = fragcolor * diffuse_albedo // ambient, sun and lamps on the diffuse layer + + specular * HIGHLIGHT_SCALE // highlight of the sun, fresnel coloured (metals take their base colour) + + lampspecular // highlights of the lamps, HIGHLIGHT_SCALE already applied + + emissioncolor * texturecolor + + env_reflection; +#ifdef PBR_SURFACE + lit += pbr_emission; +#endif +#ifdef PBR_COAT + // the highlights of the sun and the lamps in the varnish, over what comes through it from the surface below + if (coat_weight > 0.0) + coat_light += (sunlight * specular_light(light_dir, fragnormal, vec3(COAT_F0), coat_roughness, SUN_BRDF_LIMIT) * (1.0 - shadow) + + coat_lampspecular) * coat_weight; + lit = lit * coat_through + coat_light; +#endif + return lit; } vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone) diff --git a/shaders/vk14/mat_bugs_windscreen.frag b/shaders/vk14/mat_bugs_windscreen.frag new file mode 100644 index 000000000..c3b7470de --- /dev/null +++ b/shaders/vk14/mat_bugs_windscreen.frag @@ -0,0 +1,505 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// Windscreen bugs (spring / summer) - v3 (OpenGL 4.6 / Vulkan 1.4 port of the OpenGL 3.3 v2) +// v3: the syntax of the 4.6 renderers (explicit locations and bindings, #pragma texture / param, the settings as constants); +// the tuning values are constants (a uniform can't have a default any more); the blur ring goes to the post-processing +// through the velocity target as the haze of rain_windscreen does (postfx_taa.frag / postfx_motionblur.frag with +// rain_windscreen_haze.glsl); the colour is written straight (not premultiplied), as rain_windscreen of the 4.6 renderers +// writes the glass; the gloss of the glass from legacy_gloss(); no lighting where the glass is clear (no bug, clear texture) +// v2: cells without a bug are skipped before the wiper mask is read (the mask used to be read for all +// 18 cells of both layers on every pixel); the fine specks are procedural (no texture reads, only the +// pixel's own cell); optional vertical bias of the dirt; quick splat instead of a 2 s growth; +// now and then a really big bug and rarely a huge one (own coarse grids, never cut off by the 3x3 search); +// smaller blur ring, scaled by the size of the bug on screen. +// +// Insects splat on the glass one by one, only while the vehicle goes faster than 20 km/h and the more the faster, and the glass +// gets dirtier until it is fully dirty after `bugs_fill_time` seconds of driving at 100 km/h (default 3600 = 1 h; at 160 km/h +// about 35 minutes, at 50 km/h 2.7 hours). The engine counts the insects met (rain_wind.w) and keeps the count of the moments +// the blades were at the ends of their sweep (wiper_bugs_out / wiper_bugs_return), next to their times. +// No sliding, no rain: every bug is placed once (hash of its grid cell) and just +// appears at its own random moment. Wipers (wipermask) wipe the bugs off in the area they +// sweep; the glass there then gets dirty again, with new bugs, over the next bugs_fill_time. +// +// .mat (shader name WITHOUT the "mat_" prefix, the engine adds it). +// The sampler is called "raindropsatlas" on purpose, exactly like in rain_windscreen: +// the engine collects ALL texture_* lines of a .mat and checks them against the final +// shader, so a key that only one of the two shaders knows ends in "unknown texture binding". +// With one shared key, a season / weather block just overrides the file: +// +// texture_diffuse: dynamic/pkp/vectron_v1/cab/szyby +// texture_wipermask: dynamic/pkp/vectron_v1/cab/szyby_wipermask +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// +// spring: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas <- 2x2 atlas (blender_bugs_atlas.py), colour + alpha +// texture_normalmap: textures/fx/bugs_normalmap <- same layout: rg = normal xy, b = height, a = mask +// param_raindrop_grid_size: 60 <- cells across the glass UV, see below +// } +// summer: { +// shader: bugs_windscreen +// texture_raindropsatlas: textures/fx/bugs-atlas +// texture_normalmap: textures/fx/bugs_normalmap +// param_raindrop_grid_size: 60 +// } +// +// rain: { <- rain weather beats the season (priority 2 > 1) +// shader: rain_windscreen +// texture_raindropsatlas: textures/fx/raindrops-atlas +// texture_normalmap: textures/fx/raindrops_normalmap +// param_raindrop_grid_size: 150 +// } +// +// NOTE: the wipers' memory of when the glass was last wiped lives only in the engine's +// wiper timers, and the renderer resets them to -1000 whenever the camera is not in +// a cab (F4 ...). The shader cannot recover what is gone, so after returning to the cab the +// parts of the glass the blades cover are dirty as if never wiped (capped by `bugs_unknown_level`) until they are +// wiped again. A one-line engine fix would keep the memory, see the note in the chat. +// +// One cell is about one bug, so a grid of ~40-80 gives bugs of a few cm on a ~1.5 m +// windscreen (150, as used for rain drops, would make them tiny). + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; + +layout(location = 0) out vec4 out_color; +#ifdef NO_MOTION_OUTPUT +// a pass without the velocity target: the writes go nowhere +vec4 out_motion; +#else +layout(location = 1) out vec4 out_motion; +#endif + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // splats: rg = normal xy, b = height, a = mask; same 2x2 layout as raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" + +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; + +// --- Tuning ----------------------------------------------------------------- +const float bugs_fill_time = 3600.0; // seconds of driving at 100 km/h until the glass is fully dirty (none below 20 km/h) +const float bugs_start_time = 0.0; // simulation time at which the glass was clean +const float bugs_density = 0.15; // fraction of grid cells that end up with a big bug (0..1) +const float specks_density = 0.12; // same for the layer of tiny specks (0 = off) +const float bugs_opacity = 1.0; // overall opacity of the dirt +const float bugs_uv_aspect = 1.0; // glass width / height in the world if the UV is stretched (e.g. 2.0 for a 1.4 x 0.7 m pane) +const float bugs_unknown_level = 1.0; // upper limit of the dirt where the wiper memory was lost: 1 = grows like everywhere else, 0.3 = never more than 30%, 0 = stays clean until a blade passes +const float bugs_wiper_clean = 1.0; // 1 = wipers wipe the bugs off (uses wipermask), 0 = wipers ignore them +const float bugs_gloss = 0.45; // shininess of the wet splats (sun / headlight glints on the bumps), 0 = matt +const float bugs_bump = 1.0; // strength of the 3D relief from the normal map, 0 = flat +const float bugs_halo_blur = 0.8; // blur of the scene seen through the see-through parts of a bug (its texture half transparent: wings, + // the thin smear of the splat), none around it (0 = off, 1 = full); done in the post-processing +const float bugs_halo_size = 1.15; // ring radius = bug half-size * this (1 = only under the splat, max 1.6) +const float bugs_halo_px = 60.0; // a bug this many pixels wide on screen gets the full blur, smaller ones less (the blur radius is fixed in pixels) +const float bugs_vertical = 0.0; // -1..1: more dirt at the bottom (<0) or at the top (>0) of the pane, 0 = even +const float bugs_giant_density = 0.015; // share of the coarse cells that end up with a really big bug (0 = off) +const float bugs_giant_scale = 2.5; // how much bigger the big ones are (the coarse grid is this many times coarser) +const float bugs_huge_density = 0.02; // share of the very coarse cells with a huge bug: about one per pane when fully dirty (0 = off) +const float bugs_huge_scale = 5.0; // how much bigger the huge ones are than the normal bugs +const float specks_size = 0.30; // size of the fine specks, in speck cells (0.1 .. 0.45) +const float specks_opacity = 0.55; // how much a speck covers the glass + +const float BUG_SIZE_MIN = 0.6; // bug size in grid cells (keep max <= 1.2, the search covers 3x3 cells) +const float BUG_SIZE_MAX = 1.2; +const float BUG_FADE_TIME = 0.15; // seconds a splat takes to appear (a quick splat) +const float SPECK_SCALE = 2.5; // speck grid = raindrop_grid_size * this +const float WS_ENC = 64.0; // must match rain_windscreen_haze.glsl + +// Match the way rain_windscreen draws the glass itself (colour premultiplied by +// alpha, then alpha-blended), so the pane looks identical in summer and in rain. +// Set to 1 to see the shader's clock (`time`) as red digits on the glass, see bugs_start_time. +#ifndef BUGS_DEBUG_TIME +#define BUGS_DEBUG_TIME 0 +#endif + +#ifndef BUGS_MATCH_RAIN_GLASS +#define BUGS_MATCH_RAIN_GLASS 0 // 4.6: rain_windscreen writes the glass straight, not premultiplied +#endif + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// Simulation time at which a wiper blade last swept over `co`. +// WIPER_NONE no blade covers this spot (it can never be wiped) +// WIPER_UNKNOWN a blade covers it, but the engine has lost its memory: while the camera is +// outside the cab (F4 ...) the renderer resets the stroke timers to -1000 +// Same blade/stroke logic as GetMixFactor in rain_windscreen: wipermask channel i is the +// area of blade i, its value says when during the stroke the blade reaches that spot, and +// wiper_pos is 0..1 on the way out and 1..2 on the way back. The timers hold the moment +// each stroke started, which is good enough (a stroke takes about a second). +const float WIPER_NONE = -1.0e9; +const float WIPER_UNKNOWN = -2.0e9; + +float lastCleanTime(vec2 co, out float bugsAt) +{ + vec4 m = textureLod(wipermask, co, 0.0); + float best = WIPER_NONE; + bugsAt = 0.0; + bool unknown = false; + for (int i = 0; i < 4; ++i) + { + if (m[i] <= 0.001) + continue; + float pos = wiper_pos[i]; + bool isOut = pos <= 1.0; + float phase = isOut ? pos : 2.0 - pos; + float maskVal = isOut ? m[i] : 1.0 - m[i]; + bool passed = maskVal <= phase; // blade is already past this spot + float sideV = isOut ? (passed ? 0.0 : 1.0) : (passed ? 1.0 : 0.0); + float t = mix(wiper_timer_out[i], wiper_timer_return[i], sideV); + if (!(t <= time)) // garbage or NaN: ignore + continue; + float b = mix(wiper_bugs_out[i], wiper_bugs_return[i], sideV); // the insects met at that moment + if ((t < -500.0) || (b < 0.0)) // the -1000 "memory lost" marker + { + unknown = true; + continue; + } + if (t > best) + { + best = t; + bugsAt = b; + } + } + if (best > WIPER_NONE) + return best; + return unknown ? WIPER_UNKNOWN : WIPER_NONE; +} + +// Fine specks: tiny dried drops of bug juice. Procedural (a soft irregular blob with a darker rim), +// one per speck cell and always inside it, so only the pixel's own cell is checked: no texture reads +// apart from the wiper state of this pixel, which main() passes in. +void speckLayer(float gridSize, float density, float tcPix, float bugsPix, vec2 aspect, float pixelUV, + inout vec3 accRGB, inout float accA, inout vec3 accN, inout float accNA) +{ + vec2 g = f_coord * gridSize; + vec2 cell = floor(g); + float tBase, prog; + float met = max(rain_wind.w, 0.0); // the insects met so far + if (tcPix < -1.5e9) + { + tBase = -1000.0; + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tcPix < -0.5e9) + { + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); + } + else + { + tBase = tcPix; + prog = max(met - bugsPix, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + return; + uint pseed = Hash(uvec3(uvec2(ivec2(floor(cell / 8.0))), 107u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vertMul = clamp(1.0 + bugs_vertical * ((cell.y + 0.5) / gridSize - 0.5) * 2.0, 0.0, 2.0); + uint seed = Hash(uvec3(uvec2(ivec2(cell)), 7u ^ floatBitsToUint(tBase))); + if (RandF(seed) > density * patchMul * vertMul) + return; + float appearAt = RandF(seed); + if (prog < appearAt) + return; + float r = clamp(specks_size, 0.05, 0.45) * mix(0.5, 1.0, RandF(seed)); + vec2 c = vec2(r) + vec2(RandF(seed), RandF(seed)) * max(1.0 - 2.0 * r, 0.0); + float ang = RandF(seed) * 6.2831853; + float el = mix(0.6, 1.0, RandF(seed)); + vec2 p = (g - cell - c) / r; + p = vec2(cos(ang) * p.x + sin(ang) * p.y, (-sin(ang) * p.x + cos(ang) * p.y) / el); + // irregular outline: a few lobes + float th = atan(p.y, p.x); + float lob = 1.0 + 0.18 * sin(3.0 * th + RandF(seed) * 6.28) + 0.10 * sin(5.0 * th + RandF(seed) * 6.28); + float d = length(p) / lob; + if (d >= 1.0) + return; + float edgeW = clamp(pixelUV * gridSize / r * 1.5, 0.05, 0.6); // ~1.5 px soft edge + float m = 1.0 - smoothstep(1.0 - edgeW, 1.0, d); + float a = m * specks_opacity * bugs_opacity * (0.6 + 0.4 * smoothstep(0.5, 0.95, d)); // the dried rim covers more + vec3 col = vec3(0.42, 0.34, 0.16) * mix(0.8, 1.15, RandF(seed)) * mix(1.0, 0.75, smoothstep(0.6, 0.95, d)); + vec3 nT = normalize(vec3(p / max(lob, 0.5) * 0.25 * bugs_bump, 1.0)); + accRGB = col * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; +} + +// Adds one layer of bugs to the premultiplied accumulators (accRGB, accA). +void bugLayer(float gridSize, float density, uint layerSeed, + float pixelUV, vec2 aspect, float haloStrength, float opacityMul, float lightMix, + inout vec3 accRGB, inout float accA, inout float smear, + inout vec3 accN, inout float accNA) +{ + vec2 cell = floor(f_coord * gridSize); + float fadeSpan = BUG_FADE_TIME / max(bugs_fill_time, 1.0); + + for (int oy = -1; oy <= 1; oy++) { + for (int ox = -1; ox <= 1; ox++) { + + vec2 ncell = cell + vec2(float(ox), float(oy)); + + // Dirt is patchy: big areas get more bugs than others; optional bias towards the top / bottom + uint pseed = Hash(uvec3(uvec2(ivec2(floor(ncell / 8.0))), layerSeed + 100u)); + float patchMul = mix(0.4, 1.6, RandF(pseed)); + float vy = (ncell.y + 0.5) / gridSize; // 0 = bottom of the UV, 1 = top + float vertMul = clamp(1.0 + bugs_vertical * (vy - 0.5) * 2.0, 0.0, 2.0); + float pCell = clamp(density * patchMul * vertMul, 0.0, 1.0); + + // 1st test, fixed per cell (cheap, no texture): can this cell hold a bug at all? + // Cells that fail it are skipped before the wiper mask is read. + float pMax = min(2.0 * pCell, 1.0); + uint cseed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed + 31u)); + if (RandF(cseed) > pMax) + continue; + + // When the wipers last swept over this cell. Whatever hit the glass before that + // moment is gone; the cell then gets a brand new set of bugs (the seed depends on + // that moment) that again take bugs_fill_time to build up. + float bugsAt = 0.0; + float tc = (bugs_wiper_clean > 0.5) ? lastCleanTime((ncell + 0.5) / gridSize, bugsAt) : WIPER_NONE; + + // the insects met since the glass here was clean (they come only above 20 km/h, see the head of the file) + float met = max(rain_wind.w, 0.0); + float tBase; + float prog; + if (tc < -1.5e9) + { + // The engine forgot when the wipers last swept here (another vehicle). We cannot know how dirty the glass was, + // so show the level of the glass never wiped, at most bugs_unknown_level, until a blade passes. + tBase = -1000.0; + prog = min(met / max(bugs_fill_time, 1.0), bugs_unknown_level); + } + else if (tc < -0.5e9) + { + // no blade reaches here: everything met so far + tBase = bugs_start_time; + prog = met / max(bugs_fill_time, 1.0); + } + else + { + tBase = tc; + prog = max(met - bugsAt, 0.0) / max(bugs_fill_time, 1.0); + } + if (prog <= 0.0) + continue; + + uint seed = Hash(uvec3(uvec2(ivec2(ncell)), layerSeed ^ floatBitsToUint(tBase))); + + // 2nd test, new after every wipe: together with the 1st one the cell holds a bug with + // probability pCell, and a wiped cell gets a new set of bugs + float present = RandF(seed); + if (present * pMax > pCell) + continue; + + // Moment (0..1 of the fill time) when this bug hits the glass + float appearAt = RandF(seed); + if (prog < appearAt) + continue; + float appear = smoothstep(appearAt, appearAt + fadeSpan, prog); + + float jx = RandF(seed); + float jy = RandF(seed); + vec2 center = (ncell + vec2(jx, jy)) / gridSize; + + float size = mix(BUG_SIZE_MIN, BUG_SIZE_MAX, RandF(seed)) / gridSize * mix(0.7, 1.0, appear); + float ang = RandF(seed) * 6.2831853; + float flipX = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float choice = RandF(seed); + float tone = mix(0.8, 1.15, RandF(seed)); + + vec2 d = (f_coord - center) * aspect; + + // Blur ring around the splat (greasy smear): strongest next to the bug, fading out + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + + float c = cos(ang); + float s = sin(ang); + vec2 r = vec2(c * d.x + s * d.y, -s * d.x + c * d.y); + r.x *= flipX; + + vec2 local = r / size + 0.5; + if (any(lessThan(local, vec2(0.0))) || any(greaterThan(local, vec2(1.0)))) + continue; + + // mip level from the on-screen size of the bug (derivatives are not + // allowed inside this non-uniform branch, so pixelUV comes from main) + float lod = clamp(log2(max(pixelUV / size * 0.5 * float(textureSize(raindropsatlas, 0).x), 1.0)), 0.0, 4.0); + vec4 t = textureLod(raindropsatlas, tileOffset(choice) + local * 0.5, lod); + + // fine specks: fainter and lighter than the big bugs (the splat bodies are nearly black) + t.rgb = mix(t.rgb, vec3(0.42, 0.34, 0.16), lightMix); + float a = clamp(t.a * appear * bugs_opacity * opacityMul, 0.0, 1.0); + + // the scene blurred only where the bug is see-through (half transparent), not around it and not where it's opaque + // (the post pass blurs with a fixed radius in pixels, so a bug that is small on screen gets less of it) + float pxScale = clamp(size / max(pixelUV, 1e-6) / max(bugs_halo_px, 1.0), 0.15, 1.0); + float seeThrough = smoothstep(0.03, 0.3, a) * (1.0 - smoothstep(0.75, 0.95, a)); + smear = max(smear, seeThrough * haloStrength * pxScale); + + // relief: tangent-space normal of the splat -> glass UV frame (undo the mirror, then the rotation) + vec4 nm = textureLod(normalmap, tileOffset(choice) + local * 0.5, lod); + vec2 nxy = (nm.rg * 2.0 - 1.0) * bugs_bump * appear; // a splat that is still settling is flatter + nxy.x *= flipX; + vec2 nuv = vec2(c * nxy.x - s * nxy.y, s * nxy.x + c * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + + // "over" compositing in premultiplied form + accRGB = t.rgb * tone * a + accRGB * (1.0 - a); + accN = nT * a + accN * (1.0 - a); + accA = a + accA * (1.0 - a); + accNA = accA; + } + } +} + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; // tangent frame of the glass (T along u, B along v) + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); + // No discard on a (nearly) clear glass texture: clean glass between patches of faint dirt would + // otherwise be "bald" - no bugs, no halo. + + float gridSize = max(ceil(param[2].x), 1.0); + float pixelUV = max(length(dFdx(f_coord)), length(dFdy(f_coord))); // uniform control flow here + vec2 aspect = (bugs_uv_aspect >= 1.0) ? vec2(bugs_uv_aspect, 1.0) : vec2(1.0, 1.0 / max(bugs_uv_aspect, 0.01)); + + // 0 = never dirty yet; the real per-cell progress is computed in bugLayer (wipers reset it) + float progress = clamp(max(rain_wind.w, 0.0) / max(bugs_fill_time, 1.0), 0.0, 1.0); + + vec3 bugRGB = vec3(0.0); // premultiplied + float bugA = 0.0; + float smear = 0.0; // blur ring around the bugs + vec3 bugN = vec3(0.0); // normals of the splats, premultiplied like the colour + float bugNA = 0.0; + if (progress > 0.0) + { + // fine specks underneath (procedural, one wiper read for the pixel), big bugs on top + if (specks_density > 0.0) + { + float bugsPix = 0.0; + float tcPix = (bugs_wiper_clean > 0.5) ? lastCleanTime(f_coord, bugsPix) : WIPER_NONE; + speckLayer(gridSize * SPECK_SCALE, specks_density, tcPix, bugsPix, aspect, pixelUV, bugRGB, bugA, bugN, bugNA); + } + bugLayer(gridSize, bugs_density, 3u, pixelUV, aspect, 1.0, 1.0, 0.0, bugRGB, bugA, smear, bugN, bugNA); + // now and then a really big one, on top (its own coarse grid: same 3x3 search, bigger cells) + if (bugs_giant_density > 0.0) + bugLayer(gridSize / max(bugs_giant_scale, 1.0), bugs_giant_density, 11u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + // and rarely a huge one (about one per pane when it is fully dirty) + if (bugs_huge_density > 0.0) + bugLayer(gridSize / max(bugs_huge_scale, 1.0), bugs_huge_density, 13u, pixelUV, aspect, 1.0, 1.0, 0.0, + bugRGB, bugA, smear, bugN, bugNA); + } + + // Bugs over the glass (premultiplied "over") + float glassA = tex_color.a * alpha_mult; + float finalA = bugA + glassA * (1.0 - bugA); + vec3 premult = bugRGB + tex_color.rgb * glassA * (1.0 - bugA); + vec3 albedo = premult / max(finalA, 1e-4); + + // Reflections / specular belong to the glass only, not to the bugs + float glassShare = glassA * (1.0 - bugA) / max(finalA, 1e-4); + + vec3 fragcolor = ambient; + // Relief of the splats: tilt the glass normal by the splat's slope (the tilt direction is physical, + // so it does not matter which way the mesh normal points); flat where there is no bug. + vec3 bugDir = bugN + vec3(0.0, 0.0, 1.0) * (1.0 - bugNA); + vec3 fragnormal = Ngl; + if (bugNA > 0.001) + fragnormal = normalize(Ngl * max(bugDir.z, 0.05) + Tgl * bugDir.x + Bgl * bugDir.y); + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + + bugs_gloss * bugA; // wet splats catch the sun and the headlights + legacy_gloss(); + + // Lit by sun, ambient and headlights like everything else (bugs glow in oncoming beams) + // most of the glass is clear (no bug, a clear glass texture): the lighting of the 4.6 renderers (the clusters of lamps, the + // shadows, the reflections) is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + vec3 lit = apply_fog(fragcolor); + +#if BUGS_MATCH_RAIN_GLASS + vec4 color = vec4(lit * finalA, finalA); +#else + vec4 color = vec4(lit, finalA); +#endif + + out_color = POSTFX_ENABLED ? color : tonemap(color); + +#if BUGS_DEBUG_TIME + // Calibration: paints floor(time) as 8 red digits across the glass (the shader's own clock, in seconds). + // Read the number right after the scenario has loaded and put it into bugs_start_time. + { + const int SEG[10] = int[10](63, 6, 91, 79, 102, 109, 125, 7, 127, 111); + float dx = (f_coord.x - 0.10) / 0.10; + float dy = (f_coord.y - 0.42) / 0.08; + int idx = int(floor(dx)); + if (idx >= 0 && idx < 8 && dy >= 0.0 && dy <= 2.0) + { + float tt = floor(max(time, 0.0)); + float div = pow(10.0, float(7 - idx)); + int dig = int(mod(floor(tt / div), 10.0)); + vec2 q = vec2(fract(dx) / 0.8, dy); + int m = SEG[dig]; + bool on = false; + if ((m & 1) != 0 && q.y > 1.86 && q.x > 0.1 && q.x < 0.9) on = true; // a + if ((m & 2) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 1.0 && q.y < 1.9) on = true; // b + if ((m & 4) != 0 && q.x > 0.86 && q.x < 1.0 && q.y > 0.1 && q.y < 1.0) on = true; // c + if ((m & 8) != 0 && q.y < 0.14 && q.x > 0.1 && q.x < 0.9) on = true; // d + if ((m & 16) != 0 && q.x < 0.14 && q.y > 0.1 && q.y < 1.0) on = true; // e + if ((m & 32) != 0 && q.x < 0.14 && q.y > 1.0 && q.y < 1.9) on = true; // f + if ((m & 64) != 0 && q.y > 0.93 && q.y < 1.07 && q.x > 0.1 && q.x < 0.9) on = true; // g + if (on) + out_color = vec4(1.0, 0.05, 0.05, 1.0); + } + } +#endif + + if (MOTIONBLUR_ENABLED) + { + // alpha 0 = blending keeps the scene's own motion vectors + // only the see-through parts of the bugs (smear); no blur over opaque parts of the pane (1 - glassA) + float blurMask = clamp(smear * bugs_halo_blur * (1.0 - smoothstep(0.5, 0.95, glassA)), 0.0, 1.0); + out_motion = (blurMask >= 0.01) ? vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0) : vec4(0.0); + } +} diff --git a/shaders/vk14/mat_pbr.frag b/shaders/vk14/mat_pbr.frag new file mode 100644 index 000000000..16edd13e7 --- /dev/null +++ b/shaders/vk14/mat_pbr.frag @@ -0,0 +1,4 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +#include "mat_pbr.glsl" diff --git a/shaders/vk14/mat_pbr.glsl b/shaders/vk14/mat_pbr.glsl new file mode 100644 index 000000000..c809db722 --- /dev/null +++ b/shaders/vk14/mat_pbr.glsl @@ -0,0 +1,71 @@ +// the materials of the metallic and roughness workflow, which take the textures the way the texturing tools export them: +// diffuse the base colour (sRGB), the opacity in its alpha +// normalmap the normals of the tangent space in the red and green, with the green pointing up the texture (the opengl +// convention) +// orm the occlusion of the ambient light in the red, the roughness in the green and the metalness in the blue, the +// packing of unreal engine and gltf. without the texture: no occlusion, roughness: alone, no metal +// emissive the light the surface emits (sRGB), whatever falls on it. without the texture: none +// and the parameters +// specular the specular level of the parts which aren't metal, 1 for the reflectance of 4% (the level 0.5 of the tools) +// reflection how much of the reflected surroundings is the environment map and the scene, the rest the ambient light +// emissive scales the emissive texture +// roughness scales the roughness of the texture +// +// mat_pbr.frag and its variants are this file with what the variant adds, picked by a define before the include: +// PBR_DETAIL a second normal map (detailnormalmap) repeated detail_scale times over the first, of the strength +// detail_height_scale +// PBR_PARALLAX the height of the surface (height: white the highest) shifts the textures by height_scale +// PBR_COAT a clear varnish over the surface: coat scales how much of it there is (the red of coatmap), coat_roughness +// is added to its roughness (the green of coatmap). without the texture: varnish all over, as smooth as +// coat_roughness says +// the variant declares its own textures and parameters before the include (and after the one of common.glsl, which has the +// set and the bindings of the textures): every #pragma texture and #pragma param in a file is read, whatever #ifdef it is in. +// shaders/ogl46/mat_pbr.glsl with the bindings of the vulkan renderer +#include "common.glsl" +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 8) in mat3 f_tbn; + +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; +#ifdef PBR_PARALLAX +layout(location = 6) in vec3 TangentFragPos; +#endif + + +layout(location = 0) out vec4 out_color; +#ifdef NO_MOTION_OUTPUT +// a pass without the velocity target: the writes go nowhere +vec4 out_motion; +#else +layout(location = 1) out vec4 out_motion; +#endif + +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, one) +#pragma param(reflection, 1, 2, 1, one) +#pragma param(emissive, 1, 3, 1, one) +#pragma param(roughness, 2, 0, 1, one) + +#pragma texture(diffuse, 0, sRGB_A) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; + +#pragma texture(normalmap, 1, RGBA) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D normalmap; + +#pragma texture(orm, 2, RGBA, yellow) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D orm; + +#pragma texture(emissive, 3, sRGB_A, black) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D emissive; + +// lit as the tools show the surface, see light_common.glsl +#define PBR_SURFACE +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" + +// the same file for both renderers +#include "mat_pbr_surface.glsl" diff --git a/shaders/vk14/mat_pbr_coat.frag b/shaders/vk14/mat_pbr_coat.frag new file mode 100644 index 000000000..0989e3f68 --- /dev/null +++ b/shaders/vk14/mat_pbr_coat.frag @@ -0,0 +1,13 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// a clear varnish over the surface, see mat_pbr.glsl +#define PBR_COAT +// param[2].w is the roughness of the varnish, not the weathering +#define NO_WEATHERING +#pragma param(coat, 2, 1, 1, one) +#pragma param(coat_roughness, 2, 3, 1, zero) + +#pragma texture(coatmap, 4, RGBA, red) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 4) uniform sampler2D coatmap; +#include "mat_pbr.glsl" diff --git a/shaders/vk14/mat_pbr_detail.frag b/shaders/vk14/mat_pbr_detail.frag new file mode 100644 index 000000000..9409ebca6 --- /dev/null +++ b/shaders/vk14/mat_pbr_detail.frag @@ -0,0 +1,11 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// a second normal map repeated over the first, see mat_pbr.glsl +#define PBR_DETAIL +#pragma param(detail_scale, 2, 1, 1, one) +#pragma param(detail_height_scale, 2, 2, 1, one) + +#pragma texture(detailnormalmap, 4, RGBA) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 4) uniform sampler2D detailnormalmap; +#include "mat_pbr.glsl" diff --git a/shaders/vk14/mat_pbr_parallax.frag b/shaders/vk14/mat_pbr_parallax.frag new file mode 100644 index 000000000..87f105ad1 --- /dev/null +++ b/shaders/vk14/mat_pbr_parallax.frag @@ -0,0 +1,10 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// the height of the surface shifts the textures, see mat_pbr.glsl +#define PBR_PARALLAX +#pragma param(height_scale, 2, 1, 1, zero) + +#pragma texture(heightmap, 4, R) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 4) uniform sampler2D heightmap; +#include "mat_pbr.glsl" diff --git a/shaders/vk14/mat_pbr_surface.glsl b/shaders/vk14/mat_pbr_surface.glsl new file mode 100644 index 000000000..a94293c77 --- /dev/null +++ b/shaders/vk14/mat_pbr_surface.glsl @@ -0,0 +1,115 @@ +// the fragment stage of the pbr materials, see mat_pbr.glsl. the same file for the opengl and the vulkan renderer: the +// textures, the inputs and the outputs are declared by the files which include it + +#ifdef PBR_PARALLAX +// the depth of the surface below its highest points, 0..1: the height map holds the height, white the highest +float parallax_depth(vec2 coord, vec2 dcoorddx, vec2 dcoorddy) +{ + return 1.0 - textureGrad(heightmap, coord, dcoorddx, dcoorddy).r; +} + +// the texture coordinates of the point of the surface the view finds, with the surface sunk below the geometry by its depth +// (param[2].y: the depth of the black of the height map, as a share of the size of the texture). Viewdir: the direction +// to the eye in the tangent space +vec2 parallax_coord(vec2 coord, vec3 viewdir) +{ + float range = length(f_pos.xyz); + if (range > 100.0) + return coord; + // gradients of the coordinates taken here: inside the loop the fragments of a quad don't go the same way + vec2 dcoorddx = dFdx(coord); + vec2 dcoorddy = dFdy(coord); + // the shift fades out before the distance it stops at, so it doesn't switch off at once there + vec2 shift = viewdir.xy * (param[2].y * (1.0 - smoothstep(80.0, 100.0, range))); + + if (false == EXTRAEFFECTS_ENABLED) + { + // one step: the depth at the point seen, taken for the depth of the point found + return coord - shift * parallax_depth(coord, dcoorddx, dcoorddy); + } + + // the ray is followed down through layers of the depth, more of them at grazing angles and close by, until it gets below the + // surface; the point is then found between the last two steps + float layers = mix(32.0, 8.0, clamp(min(abs(viewdir.z), range / 20.0), 0.0, 1.0)); + float layerdepth = 1.0 / layers; + vec2 stride = shift / layers; + vec2 current = coord; + float found = parallax_depth(current, dcoorddx, dcoorddy); + float reached = 0.0; + while (reached < found) + { + current -= stride; + found = parallax_depth(current, dcoorddx, dcoorddy); + reached += layerdepth; + } + vec2 previous = current + stride; + float after = found - reached; + float before = parallax_depth(previous, dcoorddx, dcoorddy) - reached + layerdepth; + float weight = after / min(after - before, -1e-5); + return mix(current, previous, clamp(weight, 0.0, 1.0)); +} +#endif + +// the normal of the tangent space a normal map holds in its red and green +vec3 unpack_normal(vec2 texel) +{ + vec2 xy = texel * 2.0 - 1.0; + return vec3(xy, sqrt(1.0 - clamp(dot(xy, xy), 0.0, 1.0))); +} + +void main() +{ + vec2 coord = f_coord; +#ifdef PBR_PARALLAX + coord = parallax_coord(f_coord, normalize(-TangentFragPos)); +#endif + + vec4 tex_color = texture(diffuse, coord); + + bool alphatestfail = ( opacity >= 0.0 ? (tex_color.a < opacity) : (tex_color.a >= -opacity) ); + if(alphatestfail) + discard; + + vec3 fragcolor = ambient; + + vec3 normal = unpack_normal(texture(normalmap, coord).rg); +#ifdef PBR_DETAIL + // the detail tilts the normal further (the whiteout blend of the two) + vec3 detail = unpack_normal(texture(detailnormalmap, coord * param[2].y).rg); + normal = vec3(normal.xy + detail.xy * param[2].z, normal.z * detail.z); +#endif + vec3 fragnormal = normalize(f_tbn * normalize(normal)); + + vec3 surface = texture(orm, coord).rgb; + pbr_occlusion = surface.r; + pbr_roughness = surface.g * param[2].x; + metalic = surface.b; + pbr_emission = texture(emissive, coord).rgb * param[1].w; +#ifdef PBR_COAT + vec2 varnish = texture(coatmap, coord).rg; + coat_weight = varnish.r * param[2].y; + coat_roughness = varnish.g + param[2].w; +#endif + // the specular level of the tools: 0.5 is the reflectance of 4% + float specularity = 0.5 * param[1].y; + float reflectivity = param[1].z; + + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + + vec4 color = vec4(apply_fog(fragcolor), tex_color.a * alpha_mult); + if (POSTFX_ENABLED) + { + out_color = color; + } + else + { + out_color = tonemap(color); + } + if (MOTIONBLUR_ENABLED) + { + vec2 a = (f_clip_future_pos.xy / f_clip_future_pos.w) * 0.5 + 0.5; + vec2 b = (f_clip_pos.xy / f_clip_pos.w) * 0.5 + 0.5; + + out_motion = vec4(a - b, 0.0f, 0.0f); + } +} diff --git a/shaders/vk14/mat_rain_windscreen.frag b/shaders/vk14/mat_rain_windscreen.frag index 4cc783f2a..78e20679d 100644 --- a/shaders/vk14/mat_rain_windscreen.frag +++ b/shaders/vk14/mat_rain_windscreen.frag @@ -1,30 +1,49 @@ #version 460 core #define STAGE_FRAGMENT 1 #include "common.glsl" -// Windshield rain and snow -// by @lcddisplay; wiper movement @MichauSto; water on the glass rewritten as a model of drops lying on it +// Windshield rain effects - v3 (rewrite) +// by @lcddisplay; wiper movement @MichauSto; rain v3: drop layers, drop life, rivulets that sweep drops // -// the material: the textures diffuse (the glass) and wipermask (a blade per channel, r g b a: 0 where it doesn't reach, elsewhere -// the place of the blade over its sweep, 0 at rest .. 1 at the far end, at which it goes over the place). raindropsatlas and -// raindrop_grid_size aren't used any more, they stay so the materials which name them still load. rain_scale (1 when not given) -// scales the drops and the flakes. water_slot is given by the renderer (1 + the glass of the simulation, 0 none), not by the -// material. the block of the scene: rain_params (x: how heavy the rain or snow is, z: 1 for snow, w: temperature of the air), -// wiper_pos, wiper_timer_out, wiper_timer_return (the blades of the vehicle of the camera) and rain_wind (the air against it). +// What is on the glass: +// 1. Micro droplets: a dense grid of tiny, static droplets. Procedural (no texture reads): a spherical cap +// per droplet. They make the glass look wet between the bigger drops. +// 2. Drops: one per grid cell (raindrop_grid_size), shape from the 2x2 drop tiles of the atlas +// (normalmap: rg = normal xy, b = height, a = mask). A drop lands (quick pop), sits still for +// drop_life_min..drop_life_max seconds, then makes room for a new one. Drops do NOT slide: all motion is +// done by the rivulets (a sliding drop used to leave its 3x3 neighbourhood and got cut off). +// Sizes are skewed (many medium, few big) and the tiles are randomly mirrored (8 shapes instead of 4). +// Where drops overlap, the higher one wins (no averaged "ghost" normals). +// 3. Rivulets: a drop runs down in stick-slip fashion and leaves a wet trail (4 sprites in the right half +// of the atlas, 256 x 1024: head in the bottom STREAK_HEAD_FRAC, trail above). The head sweeps up every +// drop and droplet on its way: the trail band is clean until the rivulet fades out. +// The trail right above the head is taken from the sprite part that touches the head, then it blends +// into the trail pattern that is fixed to the glass (beads stay where they were left). // -// the glasses of the cab of the train are simulated (gfx::windscreen_water, water_*.comp, water.glsl): the raindrops land as often -// as the rain hits the glass, splashing; the drops lie held by surface tension until gravity and the drag of the air pull them -// harder, then slide in stops and goes, wetting their paths (the next ones follow them into rivulets) and leaving droplets behind; -// the drops which touch flow together; the blades take the water along, gather it into a bead and leave it at the ends of their -// sweep, where it runs down; the flakes stick and melt. here the drops of the simulation are drawn where the fragment is, and the -// wetted paths as a thin film. elsewhere (the windows of other vehicles, a glass the simulation has no room for) the water is made -// up from the time alone: drops landing, growing and sliding along tracks, the blades pushing a ridge and leaving the water at the -// edge of their sweep. +// Speed: the hashes and the life cycles of the cells (which drop a cell holds now, where, how big; where the head of a rivulet is) +// are worked out once a frame for every cell by rain_cells.comp (rain_cells.glsl), not here for the 9 cells around every pixel; +// the wipers are asked only for the drops the pixel lies on. the look is the same. // -// the water is a field of soft kernels (metaballs): drops coming close flow together, and a drop is a few kernels, so the drops -// are of many shapes. a drop is a lens holding a sharp picture of the place around it turned over (the image of the last frame -// where the screen holds it, the sky and the ground elsewhere), its edge shows the light of the sky reflected inside it; the lamps -// and the headlights light the water up; the film the blades leave breaks up behind them and the lights seen through it are drawn -// into lines towards their pivot; the wet glass is a little milky +// Shading: the grey atlas (bright rim, dark middle) is read once per pixel, only for the drop that wins the +// pixel (it used to be read for all 9 neighbours). Micro droplets are shaded analytically. +// +// Refraction / blur (OpenGL 4.6, the renderer with the screen space reflections): the glass reads the image of the last +// frame the renderer keeps for the reflections (ssr_history, with mipmaps) and the depth of the scene (scene_depth): +// - drops act as small lenses: the pixel shows the scene on the opposite side of the drop centre, so every drop holds a +// small, flipped picture (drop_lens); rivulets bend the view by Snell's law from their normal, +// - bright lights near a drop (signals, lamps, headlights) show up in it, +// Works standing still, with the motion blur off and with taa. Needs gfx.ssr (default: medium); without it the drops show +// the sky / ground only, faintly. +// The haze of the wet glass is blurred by the post-processing, from the picture of this frame: the glass writes a request +// into the velocity target (x = 64 * strength, y = 0) and postfx_taa.frag (with gfx.antialiasing taa: every frame) or +// postfx_motionblur.frag (without it: only while something moves) blur the picture there (rain_windscreen_haze.glsl). +// +// Speed: the air against the vehicle (rain_wind) drives the water: at speed a second layer of rivulets runs along its push +// (up a front glass, back along a side window) and sweeps the drops up on its way, the drops are stretched along the push, +// the haze grows. Standing still the rain is as it always was. +// +// OpenGL 4.6 renderer (feat/gl46-migration): headlights and lamps are clustered, calc_headlights takes the +// screen-space derivatives of f_pos, the sun glint follows the cloud shadow. Lamps (cab lamp, scenery) light up +// the drops too (drop_lamp_scatter). layout(location = 0) in vec3 f_normal; layout(location = 2) in vec2 f_coord; @@ -42,1176 +61,1096 @@ layout(location = 1) out vec4 out_motion; #pragma texture(diffuse, 0, sRGB_A) #pragma texture(raindropsatlas, 1, sRGB_A) #pragma texture(wipermask, 2, sRGB_A) +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; 2048 x 1024 (drops left, rivulets right), linear #pragma param(color, 0, 0, 4, diffuse) #pragma param(diffuse, 1, 0, 1, diffuse) #pragma param(specular, 1, 1, 1, specular) #pragma param(reflection, 1, 2, 1, zero) #pragma param(glossiness, 1, 3, 1, glossiness) #pragma param(raindrop_grid_size, 2, 0, 1, one) -#pragma param(rain_scale, 2, 1, 1, one) #include "light_common.glsl" #include "apply_fog.glsl" #include "tonemapping.glsl" -#include "water.glsl" +#include "random.glsl" +#include "rain_cells.glsl" layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; -const float RW_PI = 3.14159265; -// refractive index of water -const float RW_IOR = 1.333; -// the falling particles (particles_precipitation.comp, rendering/common/gpuparticles.cpp): the diameters of the flakes, metres, -// and how fast the rain and the snow fall, m/s -const vec2 RW_SNOW_DIAMETER = vec2(0.004, 0.012); -const float RW_RAIN_FALL = 7.0; -const float RW_SNOW_FALL = 1.1; -// a drop is a lens: it holds a sharp picture of the place around it, turned over through its middle, RW_LENS times as far out -// as the fragment is from the middle (and as much smaller), with this share of the bending of the view by the surface on top -const float RW_LENS = 2.0; -const float RW_LENS_BEND = 0.15; -// the drag of the air going along the glass: the speed at which it equals the weight of a drop, m/s; and the share of the air -// meeting the glass head on which turns up along it. so the water goes up a glass the sooner the more it leans back: on a -// vertical glass at about 250 km/h, leaning 20 degrees at about 130 km/h, 45 degrees at about 80 km/h -const float RW_DRAG_SPEED = 24.0; -const float RW_HEAD_ON = 0.35; -// the water is a field summed from soft kernels (metaballs) and its surface is where the field is RW_SURFACE: drops which come -// close flow together the way surface tension pulls them. a kernel alone reaches the surface at RW_EDGE of its radius -const float RW_SURFACE = 0.25; -const float RW_EDGE = 0.61; +// --- Haze of the wet glass (blur) ------------------------------------------------ +// The haze follows the rain and is wiped away by the wipers, as before (fully blurred from a quarter of the haze on). +const float blur_amount = 1.0; // strength of the haze: 0 = off, 1 = full +// after the wiper the haze grows with the rain fallen on the glass since (intensity x seconds, more at speed) from nothing up to +// its full strength, in any rain (a lighter rain takes longer). where no wiper reaches it is full +const float haze_fill = 12.0; // rain fallen since the blade to mist the glass up fully: seconds of the heaviest + // rain standing still (2x as long at 1.5; the speed counted in by the game) +const float haze_curve = 1.0; // > 1: slow at first, then more and more +const float WS_BEND_ENC = 60.0; // the drop request in the velocity target; must match rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; must match rain_windscreen_haze.glsl -// the glass at the fragment: the view space steps along it for a step of the coordinates of the glass (metres along the axes -// of the model, see main()), and the size of a pixel on it, metres -vec3 rw_tu; -vec3 rw_tv; -float rw_pixel; +// --- How the water gathers on the glass ------------------------------------------------------------------ +// the game counts the rain the glass meets (rain_state, gl::scene_ubs; more at speed) and how wet the glass is (0 dry .. 1 as full +// of drops as it gets): the glass fills up to the full in any rain, a lighter one only takes longer, and dries when the rain stops. +// the times are in the game (fill_rate, fill_speed, dry_halflife in the setup of the scene block). where a blade went over the glass +// the drops come back with the rain fallen since -// how the water on the glass behaves here, set by main() -float rw_scale; // size of the drops (param rain_scale) -float rw_since; // seconds since a blade last cleaned the place -float rw_period; // seconds between the small drops landing on a place of one -float rw_grow; // seconds the drops need after a wipe to grow big enough to slide -float rw_rate; // how fast the glass gathers the rain against a standing vertical glass in the heaviest rain -float rw_push; // the force on a drop along the glass, in units of its weight -vec2 rw_down; // the way gravity pulls along the glass (coordinates of the glass, unit) -vec2 rw_flow; // the way the air goes along the glass (unit, 0 in still air) +// --- Drops (atlas tiles) ------------------------------------------------------ +// (how long they live: rain_cells.glsl; the cells of the drops and of the rivulets are worked out once a frame by rain_cells.comp) -// the field of the water: the sum of the kernels, its gradient along the glass (view space) and the sums for the mean radius of -// the drops it is made of -float rw_field = 0.0; -vec3 rw_fgrad = vec3(0.0); -float rw_fsize = 0.0; -float rw_fweight = 0.0; +// --- Micro droplets ------------------------------------------------------------- +const float micro_density = 0.45; // share of micro cells holding a droplet on a full glass, 0 = off +const float micro_scale = 3.0; // micro grid = raindrop_grid_size * micro_scale +const float micro_size_min = 0.12; // droplet radius in micro cells +const float micro_size_max = 0.40; +const float micro_bulge = 0.80; // slope of the droplet dome at its rim (0..0.95) +const float micro_life = 60.0; // average seconds a droplet lives -// the water at the fragment: the thickness of the highest water there (metres), its gradient (view space), the radius of the -// curvature of its surface (metres: how much it bends the view across a pixel) and how much of the pixel it covers -float rw_height = 0.0; -vec3 rw_slope = vec3(0.0); -float rw_curve = 1.0; -float rw_cover = 0.0; -// from the middle of the drop which gives the water to the fragment (view space, metres), 0 for spread water -vec3 rw_offset = vec3(0.0); -// the last time the water a blade pushes went over the fragment, taking the drops lying there with it -float rw_cleared = -1.0e9; +// --- Look of the drops (grey atlas for drops / rivulets, the same look computed for micro droplets) --------- +const float drop_rim_start = 0.30; // micro droplets: dome slope (1 - nz) where the bright rim starts +const float drop_rim_end = 0.80; // ... and where it is fully bright +const float drop_light_side = 0.25; // micro droplets: brighter on the upper-left side +const float drop_center_alpha = 0.25; // how much the dark middle of a drop covers the scene +const float drop_rim_alpha = 0.85; // how much the bright rim covers the scene +const float drop_shade_alpha = 0.30; // faint alpha over the whole dome (carries the glints) -uvec4 rw_pcg4d(uvec4 v) +// --- Light on the drops -------------------------------------------------------- +const float drop_ior = 1.33; // refraction index of water +const float drop_refract = 0.5; // rivulets: strength of the picture shift (Snell; 1 = physical) +const float drop_lens = 2.0; // drops: lens field, the drop shows (1 + drop_lens) x its own size, flipped +const float drop_lens_mix = 0.7; // drops: 1 = lens picture, 0 = Snell shift like the rivulets +const float drop_env = 0.6; // reflection of the environment on the dome (0 = off) +const float drop_glint_strength = 5.0; // sun / moon glint brightness +const float drop_glint_sharpness = 40.0; // sun / moon glint size (lower = a wider lobe, so more drops catch it) +const float drop_sheen = 0.3; // wide, soft sun sheen on the domes around the sharp glint +const float drop_headlight_scatter = 3.0; // how much drops light up in headlight beams +const float drop_lamp_scatter = 1.0; // GL 4.6: how much drops light up from lamps (station lamps, signals), 0 = off +const float drop_light_near = 4.0; // lights nearer than this (metres; the own vehicle) don't light the drops, full from 2x +const float drop_light_max = 3.0; +const float drop_dark_lum = 0.25; // average brightness of the screen (scene units) below which the drops darken with it // the most the lamps and headlights add to a drop (scene units, before tonemapping) + +// --- Rivulets (drops that run down and leave a wet trail) --------------------------------- +// Sizes are in "drop cells" (1 cell = 1 / raindrop_grid_size of the glass UV). +const float streak_density = 1.00; // share of cells carrying a rivulet (scaled by the rain intensity), 0 = off +const float streak_cell = 6.0; // width of a rivulet cell in drop cells +const float streak_run = 20.0; // height of a rivulet cell in drop cells = the longest run of one rivulet +const float streak_head = 1.7; // mean width of the drop head, in drop cells (randomised 0.75x .. 1.25x) +const float streak_wiggle = 0.35; // how far the path swings sideways, in head widths (0 = straight) +const float streak_wiggle_speed = 0.5; // speed of the little waves that flow down the trail +const float streak_flow = 0.15; // ripples flowing down inside the trail (shows in refraction and glints), 0 = off +const float streak_uv_aspect = 1.0; // glass width / height in UV terms (1 = same stretch as the drops) +const float streak_sweep = 1.0; // 1 = the head sweeps up drops on its way (clean band behind it), 0 = off +const float streak_sweep_width = 0.9; // width of the swept band, in head widths +const float streak_link = 1.5; // head widths above the head where the trail is taken from the sprite part + // that touches the head (so the trail always leaves the head cleanly) + +// --- Speed: the air against the vehicle (rain_wind) drives the water on the glass -------------------- +// The force on the water along the glass: its weight (gravity) and the drag of the air going along the glass (and of the +// share of the air meeting it head on which turns up along it), as in the stock shader of the renderer. Standing still +// (or in a light wind) nothing of it shows: the rain lands, grows and runs down as it always did. +const float wind_drag_gain = 4.0; // how strongly the air drives the water (1 = the drag of the stock shader: on a + // vertical front glass the water would go up only at ~250 km/h) +const float wind_streaks = 1.5; // density of the rivulets driven by the air, at full drag (x streak_density) +const float wind_cell_scale = 0.5; // the rivulets of the air: their cells this much narrower ... +const float wind_run_scale = 1.2; // ... and their runs this long against those of gravity: few drops with long trails +const float wind_head_scale = 0.4; // their heads this much smaller (a small bead at the front of a long trail) +const int wind_layers = 4; // layers of them, each with drops of its own (1 .. 4) +const float wind_long_run = 3.0; // the last layer: its trails this much longer than those of gravity (the long ones, a part of all) +const float WS_DRAG_SPEED = 24.0; // speed of the air along the glass at which its drag equals the weight of a drop, m/s +const float WS_HEAD_ON = 0.35; // share of the air meeting the glass head on which turns up along it +const float WS_WIND_STEP = 0.1309; // the direction of the rivulets of the air in steps of 7.5 degrees (no seams on a + // curved glass, where every triangle would turn them a little) + +// --- The rivulets of the air of different thickness: the width of every one is drawn from this range (x streak_head, x +// wind_head_scale), most of them thin, a few thick (never wider than their cell) ------------------------------------------------- +const float streak_thin = 0.5; // the thinnest +const float streak_thick = 2.0; // the thickest +const float streak_thick_bias = 2.0; // > 1: more thin ones +// --- What the blades leave: they don't take every drop (a few stay where they were): wiper_miss of rain_cells.glsl ----------------- + +#ifndef STREAK_FLIP_Y +#define STREAK_FLIP_Y 0 // set to 1 if the rivulets run UP the glass (head on top) +#endif +const float STREAK_TAIL_SCALE = 1.5; // the trail pattern of the sprite is drawn this much longer than native +const float STREAK_HEAD_FRAC = 0.22; // part of the sprite height used by the drop head (= HEAD_FRAC of the atlas generator) + +const float WS_INSIDE = 0.3; // metres beyond the glass nearer than which the image is taken for the inside of the cab + // (in the rain the cab isn't in the depth: the nose of the own vehicle is outside) +const float WS_REFR_MAXPX = 96.0; // largest picture shift of a drop, screen pixels +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights near a drop shown in it (0 = off) +const float WS_LIGHT_CONTRAST = 3.0; // a light: this many times brighter than the place around it + +// measuring what costs what (the time of "colour, translucent and cab" with each): 0 everything (as in the game), 1 the drops not lit +// (no sun glint, lamps, reflection), 2 no rivulets (and nothing swept by them), 3 no micro droplets, 4 no drops of the atlas, +// 5 none of the rain (only the glass and the haze) +#ifndef WS_PROFILE +#define WS_PROFILE 0 +#endif + +const vec3 DROP_LIGHT = vec3(-0.5527, 0.6532, 0.5226); // same light as the atlas generator (upper left) + +// the surroundings in a view space direction where the image doesn't hold them: the environment map above the horizon, +// the ground below it, blurred by Lod (as in the stock mat_rain_windscreen.frag) +vec3 wsSurroundings(vec3 direction, float lod) { - v = v * 1664525u + 1013904223u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - v ^= v >> 16u; - v.x += v.y * v.w; - v.y += v.z * v.x; - v.z += v.x * v.y; - v.w += v.y * v.z; - return v; + vec3 world = mat3(inv_view) * direction; + vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); + float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); + if ((below <= 0.0) || (false == ENVMAP_ENABLED)) + return sky; + return mix(sky, reflection_ground(), below); } -// four numbers 0 .. 1 of a cell of a layer -vec4 rw_random(ivec2 cell, uint layer, uint index) +// what is seen through the glass in a view space direction: the image of the last frame where it holds the place, Distance +// away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. Fade: towards the edges of the +// image the surroundings take over. The inside of the cab (near the camera in the depth) is never taken: the surroundings +// stand for it (else the drops would show the dark walls of the cab) +vec3 wsBehind(vec3 direction, float lod, float distance, out float share, bool fade) { - return vec4(rw_pcg4d(uvec4(uvec2(cell), layer, index))) * (1.0 / 4294967296.0); + share = 0.0; + vec3 around = wsSurroundings(direction, lod); + if (ssr_params.x < 1.0) + return around; + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return around; + vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; + vec2 edges = min(coords, 1.0 - coords); + share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); + coords = clamp(coords, vec2(0.0), vec2(1.0)); + if (share <= 0.0) + return around; + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; + float near = projection[3][2]; + if ((depth > 0.0) && (near / depth < -f_pos.z + WS_INSIDE)) + { + share = 0.0; + return around; + } + vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; + if (any(isnan(color)) || any(isinf(color))) + { + share = 0.0; + return around; + } + return mix(around, max(color, vec3(0.0)), share); } -float rw_noise(float x, uint layer) +float wsLum(vec3 c) { - float i = floor(x); - float f = x - i; - float a = rw_random(ivec2(int(i), 0), layer, 7u).x; - float b = rw_random(ivec2(int(i) + 1, 0), layer, 7u).x; - return mix(a, b, f * f * (3.0 - 2.0 * f)); + return dot(c, vec3(0.2126, 0.7152, 0.0722)); } -// value noise 0 .. 1 (x) with its gradient (yz) -vec3 rw_noise2(vec2 p, uint layer) +// bright lights near a drop (signals, lamps, headlights): a drop is a wide-angle lens and picks them up. A light is where a +// fine mip level of the image (~11 px around) is much brighter than a coarse one (~90 px around) +vec3 wsLightGlow(vec3 direction, float distance) { - vec2 i = floor(p); - vec2 f = p - i; - vec2 u = f * f * (3.0 - 2.0 * f); - vec2 du = 6.0 * f * (1.0 - f); - ivec2 c = ivec2(i); - float a = rw_random(c, layer, 8u).x; - float b = rw_random(c + ivec2(1, 0), layer, 8u).x; - float d = rw_random(c + ivec2(0, 1), layer, 8u).x; - float e = rw_random(c + ivec2(1, 1), layer, 8u).x; - float k1 = b - a; - float k2 = d - a; - float k4 = a - b - d + e; - return vec3(a + k1 * u.x + k2 * u.y + k4 * u.x * u.y, du * vec2(k1 + k4 * u.y, k2 + k4 * u.x)); -} - -// P turned by A (radians). every set of drops is laid on its own grid, turned and shifted against the others, so the drops line -// up neither with each other nor along the glass -vec2 rw_turn(vec2 p, float a) -{ - float c = cos(a); - float s = sin(a); - return vec2(c * p.x - s * p.y, s * p.x + c * p.y); -} - -// a gradient given along the coordinates of the glass, view space -vec3 rw_along(vec2 gradient) -{ - return rw_tu * (gradient.x / dot(rw_tu, rw_tu)) + rw_tv * (gradient.y / dot(rw_tv, rw_tv)); -} - -// the gradient along the glass (view space) of a value of the fragments, from how it changes from pixel to pixel; Dpdx, Dpdy: -// the steps of the position, Normal: of the glass -vec3 rw_gradient(float value, vec3 dpdx, vec3 dpdy, vec3 normal) -{ - vec3 r1 = cross(dpdy, normal); - vec3 r2 = cross(normal, dpdx); - float det = dot(dpdx, r1); - float dx = dFdx(value); - float dy = dFdy(value); - return (abs(det) > 1e-14) ? (dx * r1 + dy * r2) / det : vec3(0.0); -} - -// a kernel of the water, Offset (view space) from its centre to the fragment: alone it makes water of the radius Visible, -// Weight 1 .. 0 as it goes. water smaller than a pixel would only flicker, it is left to the haze of the wet glass -void rw_kernel(vec3 offset, float visible, float weight) -{ - if ((weight <= 0.0) || (visible < 0.5 * rw_pixel)) - return; - // a drop a pixel or two across is grain rather than a lens: it fades into the haze of the wet glass - weight *= smoothstep(0.5 * rw_pixel, 2.0 * rw_pixel, visible); - float support = visible / RW_EDGE; - float q = dot(offset, offset) / (support * support); - if (q >= 1.0) - return; - float k = 1.0 - q; - float k3 = weight * k * k * k; - rw_field += k3; - rw_fgrad += offset * (-6.0 * weight * k * k / (support * support)); - rw_fsize += k3 * visible; - rw_fweight += k3; -} - -// a kernel at the Offset in the coordinates of the glass -void rw_blob(vec2 offset, float visible, float weight) -{ - rw_kernel(offset.x * rw_tu + offset.y * rw_tv, visible, weight); -} - -// a drop lying on the glass: a few kernels, sagging down the glass and lopsided as Shape (random 0 .. 1) says -void rw_drop(vec2 offset, float visible, float weight, vec4 shape) -{ - rw_blob(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec2 side = vec2(-rw_down.y, rw_down.x); - vec2 sag = (rw_down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_blob(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_blob(offset - vec2(cos(angle), sin(angle)) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// water spread over the glass (a film, a ridge): its thickness, the gradient of it (view space), the radius of the curvature of -// its surface and how much of the pixel it covers -void rw_sheet(float thickness, vec3 slope, float curve, float cover) -{ - if (cover <= 0.0) - return; - rw_cover = max(rw_cover, cover); - if (thickness > rw_height) - { - rw_height = thickness; - rw_slope = slope; - rw_curve = curve; - rw_offset = vec3(0.0); - } -} - -// the surface of the water of the field: a drop is a cap of a sphere, flat lens of the contact angle Contact (radians) the water -// makes with the glass. how far across a drop the fragment is follows from the field (inverting the kernel), the height and -// the slope of the cap from that: the slope rises slowly from the middle and steeply only close to the edge, where it reaches -// the contact angle; where drops flowed together the field is above that of a drop alone and the water is flat. the edge is -// antialiased by how fast the field changes across a pixel -void rw_settle(float contact) -{ - if (rw_field <= 0.5 * RW_SURFACE) - return; - float gradient = length(rw_fgrad); - float cover = clamp((rw_field - RW_SURFACE) / max(gradient * rw_pixel, 1e-3) + 0.5, 0.0, 1.0); - if (cover <= 0.0) - return; - float mean = rw_fsize / max(rw_fweight, 1e-12); - // 0 in the middle of a drop, 1 at its edge - float across = min(sqrt(max(1.0 - pow(min(rw_field, 1.0), 1.0 / 3.0), 0.0)) / RW_EDGE, 1.0); - float s = sin(contact); - float rs = across * s; - float root = sqrt(max(1.0 - rs * rs, 1e-4)); - float sphere = mean / s; - vec3 slope = (gradient > 1e-9) ? rw_fgrad * ((rs / root) / gradient) : vec3(0.0); - float height = max(sphere * (root - cos(contact)), 0.0); - bool top = height > rw_height; - rw_sheet(height, slope, sphere, cover); - // the field rises towards the middle of the drop - if (top && (gradient > 1e-9)) - rw_offset = rw_fgrad * (-across * mean / gradient); -} - -// the blades. a channel of the mask of the wipers is a blade: 0 where it doesn't reach, elsewhere the place of the blade over its -// sweep (0 at rest .. 1 at the far end) at which it goes over the place. wiper_pos: where the blade is (0 .. 1 on its way out, -// 1 + where it is on its way back), wiper_timer_out / _return: the last time it lay at its start / was at its far end -struct rw_wipe_s -{ - float since; // seconds since a blade last went over the place (large where none reaches) - float ahead; // 0 .. 1, how close in front of a moving blade the place is (the water the blade pushes) - float front; // how far in front of the nearest moving blade the place is, units of the mask (1 where none) - float swept; // 0 .. 1, how much of its way the blade in front did, the water it gathered on the way - float working; // 0 .. 1, the blades went lately -}; - -rw_wipe_s rw_wipe(vec4 mask) -{ - rw_wipe_s wipe = rw_wipe_s(1.0e4, 0.0, 1.0, 0.0, 0.0); - for (int i = 0; i < 4; ++i) - { - float m = mask[i]; - if (m < 0.001) - continue; - float pos = wiper_pos[i]; - bool back = pos > 1.0; - float blade = back ? pos - 1.0 : pos; - float t0 = wiper_timer_out[i]; - float t1 = wiper_timer_return[i]; - // when the blade went over the place last: on this stroke, the blade moving at an even pace from its end, or on the - // stroke before, which took as long as the time between the ends (if the blade lay at its end longer, two seconds) - float pass; - float front; // how far in front of the blade the place is (units of the mask), below 0 behind it - if (back) - { - pass = (m >= blade) ? t1 + (time - t1) * ((1.0 - m) / max(1.0 - blade, 1e-3)) : t0 + m * clamp(t1 - t0, 0.0, 2.0); - front = blade - m; - } - else - { - pass = (m <= blade) ? t0 + (time - t0) * (m / max(blade, 1e-3)) : t1 + (1.0 - m) * clamp(t0 - t1, 0.0, 2.0); - front = m - blade; - } - wipe.since = min(wipe.since, max(time - pass, 0.0)); - float moving = smoothstep(0.0, 0.03, blade) * smoothstep(1.0, 0.97, blade); - float ahead = (front > 0.0) ? (1.0 - smoothstep(0.0, 0.035, front)) * moving : 0.0; - wipe.ahead = max(wipe.ahead, ahead); - if ((front > 0.0) && (moving > 0.5)) - wipe.front = min(wipe.front, front); - wipe.swept = max(wipe.swept, ahead * (back ? 1.0 - blade : blade)); - float working = 1.0 - smoothstep(4.0, 30.0, time - t1); - wipe.working = max(wipe.working, working); - } - return wipe; -} - -// a place of the glass a blade reaches -bool rw_reached(vec2 coords) -{ - return any(greaterThanEqual(textureLod(wipermask, clamp(coords, vec2(0.0), vec2(1.0)), 0.0), vec4(0.001))); -} - -// the edge of the sweep of the blades, where they push the water out to: 0 where a blade reaches, else the share of the places -// around at Reach (metres along the glass) which a blade reaches. found from where the blades reach and not from the values of -// the mask, which may stay at the end of the sweep over a wide part of the glass. Maskstep: the coordinates of the mask for a -// step along the glass -float rw_rim(vec2 coords, float reach, mat2 maskstep) -{ - if (rw_reached(coords)) - return 0.0; - float inside = 0.0; - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - inside += rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) ? 1.0 : 0.0; - } - return inside / 6.0; -} - -// whether the edge of the sweep of the blades is within Reach of the place -bool rw_border(vec2 coords, float reach, mat2 maskstep) -{ - bool here = rw_reached(coords); - for (int k = 0; k < 6; ++k) - { - float angle = float(k) * (RW_PI / 3.0); - if (rw_reached(coords + maskstep * (vec2(cos(angle), sin(angle)) * reach)) != here) - return true; - } - return false; -} - -// how far along its way a sliding drop is at the share T of the time it takes: it stops and goes, the more smoothly the harder -// it is pushed -float rw_stickslip(float t, float seed) -{ - t = clamp(t, 0.0, 1.0); - float s = t * 3.0; - float i = floor(s); - float stuck = (i + smoothstep(0.25 + 0.4 * seed, 1.0, s - i)) / 3.0; - return mix(stuck, t, smoothstep(0.8, 2.0, rw_push)); -} - -// the track of the water down a column of the glass (Column: its index, Width: of a column, Y: metres up the way): where it -// is across, metres. the water keeps to the way wetted before, so every drop of a column goes the same way, wavy, with kinks -// where the glass held it -float rw_path(int column, float y, float width, uint layer) -{ - float slow = rw_noise(y / (0.05 * rw_scale) + float(column) * 7.31, layer) - 0.5; - float k = y / (0.008 * rw_scale); - float i = floor(k); - float a = rw_random(ivec2(column, int(i)), layer + 500u, 3u).x; - float b = rw_random(ivec2(column, int(i) + 1), layer + 500u, 3u).x; - float kinks = mix(a, b, smoothstep(0.15, 0.85, k - i)) - 0.5; - return (float(column) + 0.5 + 0.4 * slow + 0.2 * kinks) * width; -} - -// the drops which grew big enough to slide, and the streams they leave: Q the place across and up the way they go (Side, Down: -// those directions in the coordinates of the glass), Share of them going this way. a column of the glass carries the water of -// a track; a drop starts somewhere in a cell of the column now and then, slides down with stops, thinning, and leaves a stream -// which drains into beads and dries -void rw_sliders(vec2 q, vec2 side, vec2 down, uint layer, float share) -{ - float width = 0.04 * rw_scale; - float height = 0.15 * rw_scale; - int column = int(floor(q.x / width)); - int row = int(floor(q.y / height)); - vec4 a = rw_random(ivec2(column, 7), layer, 0u); - if (a.x > share * mix(0.35, 0.9, clamp(rw_rate / 3.0, 0.0, 1.0))) - return; - float speed = clamp(0.035 + 0.06 * (rw_push - 0.4) + 0.3 * max(rw_push - 1.5, 0.0), 0.01, 0.8); - float period = clamp(25.0 / rw_rate, 3.0, 60.0); - float trail = 0.0; - for (int r = 0; r < 3; ++r) - { - ivec2 cell = ivec2(column, row + r); - vec4 b = rw_random(cell, layer, 1u); - float span = period * mix(0.7, 1.3, b.x); - float now = floor(time / span + b.y); - for (int k = 0; k < 2; ++k) - { - float cycle = now - float(k); - float start = (cycle - b.y) * span; - float t = time - start; - // the drop gathered from the drops landed since the last wipe - if ((t < 0.0) || (rw_since - t < rw_grow)) - continue; - vec4 c = rw_random(cell, layer + 1000u, uint(int(cycle) + 1000000)); - float top = (float(cell.y) + 0.8 - 0.6 * c.x) * height; - float travel = mix(0.06, 0.28, c.y) * rw_scale; - float v = speed * mix(0.7, 1.3, c.z); - float gather = 0.6; - float moved = travel * rw_stickslip((t - gather) * v / travel, c.w); - float y = top - moved; - float radius = mix(0.003, 0.0042, c.w) * rw_scale * (1.0 - 0.35 * moved / travel) * mix(0.6, 1.0, smoothstep(0.0, gather, t)); - // at the end of its way what is left of it stays and flows out into the stream - float body = 1.0 - smoothstep(0.0, 1.5, t - gather - travel / v); - if ((body > 0.0) && (abs(q.y - y) < 3.5 * radius)) - { - vec2 o = vec2(q.x - rw_path(column, y, width, layer), q.y - y); - rw_blob(side * o.x - down * o.y, radius, body); - // its rear up the stream: a corner, drawn out into a cusp the faster it goes (the front stays round) - float drawn = clamp(v * 5.0, 0.0, 1.5); - for (int k = 1; k <= 2; ++k) - { - float yt = y + radius * (0.45 + 0.5 * drawn) * float(k); - vec2 ot = vec2(q.x - rw_path(column, yt, width, layer), q.y - yt); - rw_blob(side * ot.x - down * ot.y, radius * ((k == 1) ? 0.7 : 0.42), body); - } - } - if ((moved > 0.0) && (q.y > y) && (q.y < top)) - { - float age = t - gather - (top - q.y) / v; - if ((age >= 0.0) && (age < rw_since)) - { - // fresh, the stream is whole; draining, it breaks into beads, which dry - float beads = rw_noise(q.y / (0.004 * rw_scale), layer + 9u); - float wet = mix(1.15, 0.2 + 1.0 * beads, smoothstep(0.0, 15.0, age)) * (1.0 - smoothstep(30.0, 60.0, age)); - trail = max(trail, wet); - } - } - } - } - if (trail > 0.0) - { - float across = q.x - rw_path(column, q.y, width, layer); - float half_width = mix(0.0005, 0.0011, a.y) * rw_scale * (0.6 + 0.8 * rw_noise(q.y / (0.006 * rw_scale), layer + 11u)); - rw_blob(side * across, half_width, trail); - } -} - -// a drop lying on the glass, as rw_drop() with the directions along the glass given in the view space (Down: the way gravity -// pulls along the glass, Side across it) -void rw_drop_view(vec3 offset, float visible, float weight, vec4 shape, vec3 down, vec3 side) -{ - rw_kernel(offset, visible, weight); - if (visible < 1.5 * rw_pixel) - return; - vec3 sag = (down * (0.2 + 0.35 * shape.x) + side * ((shape.y - 0.5) * 0.7)) * visible; - rw_kernel(offset - sag, visible * mix(0.6, 0.85, shape.z), weight); - if (shape.w > 0.4) - { - float angle = shape.w * 40.0; - rw_kernel(offset - (cos(angle) * side + sin(angle) * down) * (0.6 * visible), visible * mix(0.4, 0.6, shape.x), weight); - } -} - -// the water the simulation keeps on the glass (gfx::windscreen_water, water.glsl), where the material is a glass of the cab of the -// train: the drops listed by the cell of the grid the fragment is in. Slot: of the glass, Uv: the coordinates of the fragment, -// Puv: the view space step along the glass for a step of the uv; Down, Side: along the glass. a sliding drop is drawn out behind -// itself into a cusp, the faster the longer; one lying is lopsided and sags down the glass; a flake of snow is lace, grey and -// clear as it melts (Snowcover, Wet: as the flakes of rw_snow()) -void rw_simulated(uint slot, vec2 uv, mat2x3 puv, vec3 down, vec3 side, inout float snowcover, inout float wet) -{ - uint base = water_grid_base(slot); - uint cell = water_cell(uv); - uint count = min(water_cells[base + cell], uint(WATER_CELL_DROPS)); - for (uint k = 0u; k < count; ++k) - { - uint place = water_cells[base + uint(WATER_GRID * WATER_GRID) + cell * uint(WATER_CELL_DROPS) + k]; - water_drop_s drop = water_drops[slot * uint(WATER_DROPS) + place]; - float volume = drop.place.z; - if (volume <= 0.0) - continue; - vec3 offset = puv * (uv - drop.place.xy); - vec4 shape = vec4(rw_pcg4d(uvec4(place, slot, 41u, 0u))) * (1.0 / 4294967296.0); - if (drop.motion.w < 1.0) - { - // a flake: lobed lace, shrinking, grey and clear as it melts - float m = drop.motion.w; - vec2 flat2 = vec2(dot(offset, side), dot(offset, down)); - float radius = 0.5 * water_flake(volume); - float dist = length(flat2); - if (dist < radius + rw_pixel) - { - float angle = atan(flat2.y, flat2.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + shape.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + shape.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(flat2 / 0.0007 + shape.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - continue; - } - float radius = water_radius(volume); - vec3 velocity = puv * drop.motion.xy; - float speed = length(velocity); - if (speed > 0.002) - { - // its rear up the way it came: a corner, drawn out into a cusp the faster it goes (the front stays round) - vec3 way = velocity / speed; - rw_kernel(offset, radius, 1.0); - float drawn = clamp(speed * 5.0, 0.0, 1.5); - for (int t = 1; t <= 2; ++t) - rw_kernel(offset + way * (radius * (0.45 + 0.5 * drawn) * float(t)), radius * ((t == 1) ? 0.7 : 0.42), 1.0); - } - else - { - rw_drop_view(offset, radius, 1.0, shape, down, side); - } - } -} - -// how fresh the wetted paths of the simulation are at a place of the glass (x) and how that changes along u and v (yz): the -// texels of their map filtered by a cubic b-spline over 4 x 4 of them, so the edges of a path are smooth curves and its slopes -// change smoothly (a bilinear filter would leave steps at every texel in the bending of the view) -vec3 rw_trail(uint slot, vec2 uv, float now) -{ - // a path stays wet (and seen) longer than the drops keep to it - float lasting = 25.0; - vec2 p = uv * float(WATER_TRAIL) - 0.5; - vec2 i = floor(p); - vec2 f = p - i; - // the weights of the b-spline and their derivatives, for the texels i - 1 .. i + 2 - vec2 g = 1.0 - f; - vec4 wx = vec4(g.x * g.x * g.x, 3.0 * f.x * f.x * f.x - 6.0 * f.x * f.x + 4.0, -3.0 * f.x * f.x * f.x + 3.0 * f.x * f.x + 3.0 * f.x + 1.0, f.x * f.x * f.x) / 6.0; - vec4 wy = vec4(g.y * g.y * g.y, 3.0 * f.y * f.y * f.y - 6.0 * f.y * f.y + 4.0, -3.0 * f.y * f.y * f.y + 3.0 * f.y * f.y + 3.0 * f.y + 1.0, f.y * f.y * f.y) / 6.0; - vec4 dx = vec4(-g.x * g.x, 3.0 * f.x * f.x - 4.0 * f.x, -3.0 * f.x * f.x + 2.0 * f.x + 1.0, f.x * f.x) * 0.5; - vec4 dy = vec4(-g.y * g.y, 3.0 * f.y * f.y - 4.0 * f.y, -3.0 * f.y * f.y + 2.0 * f.y + 1.0, f.y * f.y) * 0.5; - vec3 result = vec3(0.0); - ivec2 base = ivec2(i) - 1; - for (int y = 0; y < 4; ++y) - { - for (int x = 0; x < 4; ++x) - { - float value = water_wetted(slot, base + ivec2(x, y), now, lasting); - result += value * vec3(wx[x] * wy[y], dx[x] * wy[y], wx[x] * dy[y]); - } - } - result.yz *= float(WATER_TRAIL); - return result; -} - -// the surroundings in a view space direction where the screen doesn't hold them: the environment map above the horizon (the sky -// and the clouds), the ground below it, blurred by Lod -vec3 rw_surroundings(vec3 direction, float lod) -{ - vec3 world = mat3(inv_view) * direction; - vec3 sky = envmap_sample_rough(normalize(vec3(world.x, max(world.y, 0.0), world.z)), clamp(lod / 8.0, 0.0, 1.0)); - // the horizon as blurred as the view is - float below = smoothstep(-0.03 - 0.05 * lod, 0.25 + 0.05 * lod, -world.y); - if ((below <= 0.0) || (false == ENVMAP_ENABLED)) - return sky; - return mix(sky, reflection_ground(), below); -} - -// what is seen through the glass in a view space direction: the image of the last frame (the screen space reflections keep it) -// where it holds the place, Distance away along the direction (0: far), blurred by Lod; Share: how much of it the image gave. -// Fade: towards the edges of the image the surroundings take over (else the edges are stretched) -vec3 rw_behind_edges(vec3 direction, float lod, float distance, out float share, bool fade) -{ - share = 0.0; - vec3 around = rw_surroundings(direction, lod); - if (ssr_params.x < 1.0) - return around; - vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); - if (previous.w <= 1e-5) - return around; - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 edges = min(coords, 1.0 - coords); - share = fade ? smoothstep(0.0, 0.04, min(edges.x, edges.y)) : step(-0.02, min(edges.x, edges.y)); - coords = clamp(coords, vec2(0.0), vec2(1.0)); - if (share <= 0.0) - return around; - // the view out through the water goes on outside, where the image shows the inside of the cab around the windows the - // surroundings stand for it (else the drops show the dark walls and roof of the cab) - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(coords * vec2(size)), ivec2(0), size - 1), 0).r; - float near = projection[3][2]; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - { - share = 0.0; - return around; - } - vec3 color = textureLod(ssr_history, coords, clamp(lod, 0.0, ssr_params2.x)).rgb; - if (any(isnan(color)) || any(isinf(color))) - { - share = 0.0; - return around; - } - return mix(around, max(color, vec3(0.0)), share); -} - -vec3 rw_behind(vec3 direction, float lod, float distance, out float share) -{ - return rw_behind_edges(direction, lod, distance, share, true); + vec4 previous = ssr_reprojection * ((distance > 0.0) ? vec4(direction * distance, 1.0) : vec4(direction, 0.0)); + if (previous.w <= 1e-5) + return vec3(0.0); + vec2 coords = clamp((previous.xy / previous.w) * 0.5 + 0.5, vec2(0.0), vec2(1.0)); + vec3 near = textureLod(ssr_history, coords, min(3.5, ssr_params2.x)).rgb; + vec3 wide = textureLod(ssr_history, coords, min(6.5, ssr_params2.x)).rgb; + if (any(isnan(near)) || any(isinf(near)) || any(isnan(wide)) || any(isinf(wide))) + return vec3(0.0); + vec3 excess = max(near - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + return min(excess, vec3(30.0)) * (2.0 * WS_LIGHT_GAIN); } // a layer Over put over Under, the colours not premultiplied -vec4 rw_over(vec4 over, vec4 under) +vec4 wsOver(vec4 over, vec4 under) { - float alpha = over.a + under.a * (1.0 - over.a); - if (alpha <= 1e-5) - return vec4(0.0); - return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); + float alpha = over.a + under.a * (1.0 - over.a); + if (alpha <= 1e-5) + return vec4(0.0); + return vec4((over.rgb * over.a + under.rgb * under.a * (1.0 - over.a)) / alpha, alpha); +} + +// =========================================================================== +float GetMixFactor(in vec2 co, out float side); + +// the rain fallen when each blade last went over the place of its sweep given by the wiper mask (-1: not known), see +// gl::scene_ubs::wiper_rain_pass +vec4 wsWipePass(vec4 mask) +{ + ivec4 b = min(ivec4(max(mask, vec4(0.0)) * float(WIPER_PASS_BUCKETS)), ivec4(WIPER_PASS_BUCKETS - 1)); + return vec4(wiper_rain_pass[b.x].x, wiper_rain_pass[b.y].y, wiper_rain_pass[b.z].z, wiper_rain_pass[b.w].w); +} + +uvec2 cellKey(vec2 c); + +vec2 tileOffset(float choice) +{ + if (choice < 0.25) return vec2(0.0, 0.0); + else if (choice < 0.5) return vec2(0.5, 0.0); + else if (choice < 0.75) return vec2(0.0, 0.5); + return vec2(0.5, 0.5); +} + +// the 2x2 drop tiles live in the left half of the atlas: a tile is 0.25 wide and 0.5 high in atlas UV +vec2 dropAtlasUV(float choice, vec2 uv) +{ + vec2 off = tileOffset(choice); + return vec2((off.x + uv.x * 0.5) * 0.5, off.y + uv.y * 0.5); +} + +uvec2 cellKey(vec2 c) +{ + return uvec2(ivec2(c) + ivec2(65536)); +} + +// --- one rivulet cell ------------------------------------------------------------ +struct Riv +{ + bool on; + float life; // 0..1 (fade in / out) + float width; // sprite width = head width (glass UV) + float headH; // head height (glass UV) + float topY; // where the trail starts (fixed on the glass) + float bottom; // bottom of the head now + float left; // left edge of the sprite + float flip; + float col; // which of the 4 sprites + float wipe; + float wavK, wavPh, wavSp; +}; + +// the layer of rivulets being worked on: the one of gravity (the rivulets as they always were, coordinates = glass UV with v +// up) or the one of the air (its own cells and seeds, turned so that its rivulets run along the push of the air) +float wsLayerDensity = 1.0; // x rain x streak_density: share of the cells holding a rivulet +int wsLayerIndex = 0; // its cells in rain_cells (0 gravity, 1 .. 4 the air) +float wsLayerHead = 1.0; // x streak_head +float wsLayerCos = 1.0; // the layer is turned by this angle (its "down" is the way its water runs on the glass) +float wsLayerSin = 0.0; +bool wsLayerVaried = false; // the widths of its rivulets from streak_thin .. streak_thick (the air) + +// glass UV (v up) -> coordinates of the layer, where the rivulets run down (-v) +vec2 wsToLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x + wsLayerSin * v.y, -wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsToLayer(vec2 g) +{ + return wsToLayerDir(g - 0.5) + 0.5; +} +vec2 wsFromLayerDir(vec2 v) +{ + return vec2(wsLayerCos * v.x - wsLayerSin * v.y, wsLayerSin * v.x + wsLayerCos * v.y); +} +vec2 wsFromLayer(vec2 p) +{ + return wsFromLayerDir(p - 0.5) + 0.5; +} + +// the layers: 0 gravity, 1 air. WindShare: how much the air drives the water (0 standing still), WindCos / WindSin: the turn +// of the layer of the air +float wsWindShare = 0.0; +// the layer of the weight turned by a quarter turn at a time so that its rivulets run down the glass in the world, whichever +// way the texture lies on it (an island of the UV turned or upside down) +float wsGravCos = 1.0; +float wsGravSin = 0.0; +float wsWindCos = 1.0; +float wsWindSin = 0.0; +void wsSetLayer(int layer) +{ + if (layer == 0) + { + wsLayerDensity = 1.0 - wsWindShare; + wsLayerIndex = 0; + wsLayerHead = 1.0; + wsLayerCos = wsGravCos; + wsLayerSin = wsGravSin; + wsLayerVaried = false; + } + else + { + wsLayerDensity = wsWindShare * wind_streaks; + wsLayerIndex = layer; + wsLayerHead = wind_head_scale; + wsLayerCos = wsWindCos; + wsLayerSin = wsWindSin; + wsLayerVaried = true; + } +} + +// the rivulet of cell SCell of the layer set (wsSetLayer): the randoms and the life of the cell from rain_cells (rain_cells.comp +// worked them out as this did once from the hashes of the cell), the sizes and the places from them +Riv getRiv(vec2 sCell, float sCW, float sCH, float gridSize) +{ + Riv r; + uvec4 d = rain_cells[rain_riv_index(wsLayerIndex, ivec2(sCell))]; + r.on = ((float(d.x & 65535u) + 0.5) * (1.0 / 65536.0) < streak_density * wsLayerDensity * rain_state.y); // as wet as the glass is + r.life = float((d.x >> 16) & 255u) * (1.0 / 255.0); + float wr = rain_byte(d.y, 16u); + r.width = streak_head * wsLayerHead / gridSize + * (wsLayerVaried ? mix(streak_thin, streak_thick, pow(wr, streak_thick_bias)) : mix(0.75, 1.25, wr)); + if (wsLayerVaried) + r.width = min(r.width, sCW / 2.6); // the trail with its swing (sMargin) stays in its cell + r.headH = r.width * 0.88 * streak_uv_aspect; + float sSpan = max(sCH * mix(0.35, 0.70, rain_byte(d.y, 24u)), r.headH * 3.0); + // stick-slip: how far down its run the head is now (rain_cells.comp) + float sRun = float(d.y & 65535u) * (1.0 / 65535.0); + r.topY = sCell.y * sCH + sSpan + rain_byte(d.z, 0u) * max(sCH - sSpan, 0.0); + r.bottom = r.topY - r.headH * 1.2 - sRun * (sSpan - r.headH * 1.2); + const float sMargin = 0.8; + r.left = sCell.x * sCW + sMargin * r.width + rain_byte(d.z, 8u) * max(sCW - r.width * (1.0 + 2.0 * sMargin), 0.0); + r.flip = (((d.w >> 8) & 1u) != 0u) ? 1.0 : 0.0; + r.col = float((d.w >> 9) & 3u); + r.wipe = rain_byte(d.x, 24u); + r.wavK = 6.2831853 / mix(2.5, 5.0, rain_byte(d.z, 16u)); + r.wavPh = rain_byte(d.z, 24u) * 6.2831853; + r.wavSp = streak_wiggle_speed * mix(0.6, 1.4, rain_byte(d.w, 0u)); + return r; +} + +// sideways offset of the path (in head widths) at distance dW (head widths) down from the start of the trail +float rivWob(Riv r, float dW, out float ramp, out float wobD) +{ + float rampT = clamp(dW / 2.5, 0.0, 1.0); + ramp = rampT * rampT * (3.0 - 2.0 * rampT); + float rampD = 3.0 * rampT * (1.0 - rampT) / 2.5; + float a1 = dW * r.wavK + r.wavPh; + float a2 = dW * r.wavK * 1.7 - time * r.wavSp * 1.0472 + r.wavPh * 2.0; // the wave runs DOWN + float w1 = 0.7 * sin(a1) + 0.3 * sin(a2); + float w1D = 0.7 * cos(a1) * r.wavK + 0.3 * cos(a2) * r.wavK * 1.7; + wobD = -streak_wiggle * (rampD * w1 + ramp * w1D); + return streak_wiggle * ramp * w1; +} + +// how much a drop centred at p (glass UV, v up) with radius rad has been swept up by rivulet r (0..1) +float rivSwept(Riv r, vec2 p, float rad) +{ + if (!r.on || r.life <= 0.001) return 0.0; + if (p.y > r.topY || p.y < r.bottom - rad) return 0.0; + bool inHead = p.y < r.bottom + r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : p.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + float cx = r.left + (0.5 + wob) * r.width; + float halfW = 0.5 * streak_sweep_width * r.width; + return (1.0 - smoothstep(halfW, halfW + rad, abs(p.x - cx))) * r.life; +} + +// candidate on the glass that wins the pixel (the highest dome) +struct Hit +{ + float score; + float cov; // coverage of the dome (normal map alpha) + float colA; // coverage of the drawn drop (sharper) + vec3 n; // dome normal, tangent space of the glass + vec2 offUV; // pixel - centre (glass UV), for the lens + float radUV; // radius (glass UV) + float isDrop; // 1 = drop / droplet (lens), 0 = rivulet (Snell) + float vis; // life / sweep visibility + vec2 auv; // grey atlas lookup of the winner (drops, rivulets) + vec2 agx, agy; + float atlas; // 1 = shade from the grey atlas, 0 = analytic (micro droplets: shade in colA's place) + float shade; // analytic shade (micro droplets) +}; + +void consider(inout Hit h, float score, float cov, float colA, vec3 n, vec2 offUV, float radUV, float isDrop, + float vis, vec2 auv, vec2 agx, vec2 agy, float atlas, float shade) +{ + if (score > h.score) + { + h.score = score; h.cov = cov; h.colA = colA; h.n = n; + h.offUV = offUV; h.radUV = radUV; h.isDrop = isDrop; + h.vis = vis; h.auv = auv; h.agx = agx; h.agy = agy; h.atlas = atlas; h.shade = shade; + } +} + +// the rivulet R of the layer set (wsSetLayer) at the pixel, at SUVr in the coordinates of the layer; Rd1 / Rd2: their change +// per screen pixel +void drawRivulet(inout Hit hit, Riv r, vec2 sUVr, vec2 rd1, vec2 rd2) +{ + if (!(r.on && r.life > 0.001)) + return; + const float sMargin = 0.8; + float sLen = r.topY - r.bottom; + float sx = (sUVr.x - r.left) / r.width; + float sy = sUVr.y - r.bottom; + if (sx >= -sMargin && sx <= 1.0 + sMargin && sy >= 0.0 && sy <= sLen) + { + bool inHead = sy < r.headH; + float dW = (r.topY - (inHead ? r.bottom + 0.5 * r.headH : sUVr.y)) / r.width; + float ramp, wobD; + float wob = rivWob(r, dW, ramp, wobD); + if (inHead) wobD = 0.0; + float sxw = sx - wob; + if (sxw >= 0.0 && sxw <= 1.0) + { + float sSide; + vec2 sWipeUV = f_coord; + if (inHead) + { + sWipeUV = wsFromLayer(vec2(r.left + 0.5 * r.width, r.bottom + 0.5 * r.headH)); + if (STREAK_FLIP_Y != 0) sWipeUV.y = 1.0 - sWipeUV.y; + } + if (GetMixFactor(sWipeUV, sSide) >= mix(0.5, 1.0, r.wipe)) + { + float sNative = 3.125 * r.width * streak_uv_aspect * STREAK_TAIL_SCALE; + float sxs = mix(sxw, 1.0 - sxw, r.flip); + float su = 0.5 + (r.col + sxs) * 0.125; + vec2 sgx = vec2(0.125 / r.width * rd1.x, 0.0); + vec2 sgy = vec2(0.125 / r.width * rd2.x, 0.0); + vec4 sNm; + vec2 sAuv; + float vtSign = 1.0; + if (inHead) + { + float kv = STREAK_HEAD_FRAC / r.headH; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + sAuv = vec2(su, sy / r.headH * STREAK_HEAD_FRAC); + sNm = textureGrad(normalmap, sAuv, sgx, sgy); + } + else + { + float kv = (1.0 - STREAK_HEAD_FRAC) / sNative; + sgx.y = kv * rd1.y; sgy.y = kv * rd2.y; + // a) trail pattern fixed to the glass, tiled by mirroring (beads stay where they were left) + float dd = max(r.topY - sUVr.y, 0.0) / sNative; + float vt = abs(mod(dd, 2.0) - 1.0); + vtSign = (mod(dd, 2.0) < 1.0) ? 1.0 : -1.0; + // b) right above the head: the sprite part that touches the head + float above = (sy - r.headH) / r.width; // head widths above the head + float link = 1.0 - smoothstep(0.5 * streak_link, streak_link, above); + vec4 nGlass = vec4(0.0); + vec4 nLink = vec4(0.0); + vec2 uvGlass = vec2(su, STREAK_HEAD_FRAC + vt * (1.0 - STREAK_HEAD_FRAC)); + vec2 uvLink = vec2(su, STREAK_HEAD_FRAC + min((sy - r.headH) / sNative, 1.0) * (1.0 - STREAK_HEAD_FRAC)); + if (link < 0.999) + nGlass = textureGrad(normalmap, uvGlass, sgx, sgy); + if (link > 0.001) + nLink = textureGrad(normalmap, uvLink, sgx, sgy); + sAuv = (link > 0.5) ? uvLink : uvGlass; + sNm = mix(nGlass, nLink, link); + vtSign = mix(vtSign, 1.0, link); + } + + float sFade = inHead ? 1.0 : smoothstep(0.0, 1.5, dW); // the start of the trail melts into the glass + float sVis = r.life * sFade; + float sCov = smoothstep(0.1, 0.6, sNm.a) * sVis; + if (sCov > 0.001) + { + vec2 nxy = sNm.rg * 2.0 - 1.0; + if (r.flip > 0.5) nxy.x = -nxy.x; + if (STREAK_FLIP_Y != 0) nxy.y = -nxy.y; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = -nxy / max(nz, 0.08); + if (!inHead) + slope.y = slope.y * vtSign / STREAK_TAIL_SCALE - slope.x * wobD + + streak_flow * ramp * sin(dW * 4.8 - time * 4.0); + // the slope of the layer to the one of the glass + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + slope = wsFromLayerDir(slope); + if (STREAK_FLIP_Y != 0) slope.y = -slope.y; + vec3 n = normalize(vec3(-slope, 1.0)); + float h = sNm.b * r.width * 0.5; + consider(hit, sCov * (h + 1e-5), sCov, 0.0, n, vec2(0.0), r.width * 0.5, 0.0, + sVis, sAuv, sgx, sgy, 1.0, 0.0); + } + } + } + } +} + +// how much of a drop centred at Cg (glass UV, v up) with radius Rad the rivulets of both layers have swept up (0..1 kept) +float wsKept(vec2 cg, float rad, float sCW, float sCH, float gridSize) +{ + wsSetLayer(0); + vec2 cl = wsToLayer(cg); + Riv rv = getRiv(floor(cl / vec2(sCW, sCH)), sCW, sCH, gridSize); + float kept = 1.0 - streak_sweep * rivSwept(rv, cl, rad); + if (wsWindShare > 0.001) + { + wsSetLayer(1); + vec2 cw = wsToLayer(cg); + vec2 wc = vec2(sCW * wind_cell_scale, sCH * wind_run_scale); + Riv rw = getRiv(floor(cw / wc), wc.x, wc.y, gridSize); + kept *= 1.0 - streak_sweep * rivSwept(rw, cw, rad); + wsSetLayer(0); + } + return kept; +} + +// the rain fallen (rain_state.x) since a blade last went over this place (texture UV); -1 where no blade goes or not known +float wsWipeRain(vec2 co) +{ + vec4 mask = textureLod(wipermask, co, 0.0); + vec4 at = wsWipePass(mask); + float fallen = -1.0; + for (int i = 0; i < 4; ++i) + if ((mask[i] > 0.001) && (at[i] >= 0.0)) + fallen = (fallen < 0.0) ? max(rain_state.x - at[i], 0.0) : min(fallen, max(rain_state.x - at[i], 0.0)); + return fallen; +} + +// the tangent frame of the glass (the directions of u and v on it, view space) from the screen-space change of the place and the uv +void wsGlassFrame(vec3 Ngl, vec2 duv1, vec2 duv2, out vec3 Tgl, out vec3 Bgl) +{ + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; +} + +// the drop of a cell for one side of the blades (A, B: its half of the cell in rain_cells): where it lies, how big it is and its +// shape (the sag, the stretch by the air along PushT). true when P lies on it +bool wsDropShape(uint a, uint b, vec2 nc, float gridSize, float spreadF, float speed, vec2 pushT, vec2 p, + out vec2 center, out float sq, out float sag, out mat2 shapeM, out vec2 dl) +{ + center = (nc + vec2(rain_byte(a, 8u), rain_byte(a, 16u))) / gridSize; + float size = mix(drop_size_min, drop_size_max, rain_byte(a, 24u)) / gridSize; // the bias of the sizes: rain_cells.comp + sag = 1.0 + drop_sag * rain_byte(b, 0u); + // at speed the air stretches the drop along its push (1 standing still: the drop as it always was) + float stretch = 1.0 + drop_wind_stretch * speed * rain_byte(b, 8u); + shapeM = mat2(1.0, 0.0, 0.0, 1.0 / sag) * (mat2(1.0) + (1.0 / stretch - 1.0) * outerProduct(pushT, pushT)); + sq = size * spreadF; // spreads out as it lands + dl = shapeM * (p - center); + return max(abs(dl.x), abs(dl.y)) < sq * 0.5; } void main() { - vec4 tex_color = texture(diffuse, f_coord); - vec4 mask = texture(wipermask, f_coord); + // ---- screen-space derivatives (before any non-uniform flow) ---- + // only what the drops, the droplets and the rivulets read is kept through their loops; the frame of the glass, the change of the + // view and the lens are worked out again for the shading after them (fewer registers in the loops: more pixels at once) + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + float uvPerPx = max(length(duv1), length(duv2)); + vec3 Ngl = normalize(f_normal); - // the coordinates of the glass: metres along the axes of the model, so the water stays where it lies on the glass whatever the - // vehicle and the camera do. the axis of the model nearest to the vertical is up, the glass is projected along the - // horizontal one it faces most (along the vertical one if it lies flat) - mat3 linear = mat3(modelview); - mat3 rot = mat3(normalize(linear[0]), normalize(linear[1]), normalize(linear[2])); - mat3 unrot = transpose(rot); - vec3 local = unrot * (f_pos.xyz - modelview[3].xyz); - vec3 viewnormal = normalize(f_normal); - // the water is on the side away from the camera, the outside of the cab - vec3 outward = (dot(viewnormal, f_pos.xyz) < 0.0) ? -viewnormal : viewnormal; - vec3 normal = unrot * outward; - vec3 up = unrot * (vec3(0.0, 1.0, 0.0) * mat3(inv_view)); - vec3 aup = abs(up); - int iu = (aup.x > aup.y) ? ((aup.x > aup.z) ? 0 : 2) : ((aup.y > aup.z) ? 1 : 2); - int ia = (iu + 1) % 3; - int ib = (iu + 2) % 3; - vec3 axis_up = vec3(0.0); - axis_up[iu] = (up[iu] < 0.0) ? -1.0 : 1.0; - vec3 axis_a = vec3(0.0); - axis_a[ia] = 1.0; - vec3 axis_b = vec3(0.0); - axis_b[ib] = 1.0; - vec3 an = abs(normal); - vec3 axis_u, axis_v, axis_n; - if (an[iu] > max(an[ia], an[ib])) - { - axis_n = axis_up; - axis_u = axis_a; - axis_v = axis_b; - } - else if (an[ia] >= an[ib]) - { - axis_n = axis_a; - axis_u = axis_b; - axis_v = axis_up; - } - else - { - axis_n = axis_b; - axis_u = axis_a; - axis_v = axis_up; - } - vec2 glass = vec2(dot(local, axis_u), dot(local, axis_v)); - float facing = dot(normal, axis_n); - facing = ((facing < 0.0) ? -1.0 : 1.0) * max(abs(facing), 0.35); - // a step of the coordinates is a step along the glass - rw_tu = rot * (axis_u - axis_n * (dot(normal, axis_u) / facing)); - rw_tv = rot * (axis_v - axis_n * (dot(normal, axis_v) / facing)); + vec4 tex_color = texture(diffuse, f_coord); + float glassA = tex_color.a * alpha_mult; - // the derivatives, before anything is discarded: the size of a pixel on the glass and in the view, and how the coordinates of - // the mask follow the ones of the glass - vec3 view = normalize(f_pos.xyz); - vec3 dpdx = dFdx(f_pos.xyz); - vec3 dpdy = dFdy(f_pos.xyz); - rw_pixel = max(max(length(dpdx), length(dpdy)), 1e-6); - float pixelangle = max(max(length(dFdx(view)), length(dFdy(view))), 1e-6); - vec2 gdx = dFdx(glass); - vec2 gdy = dFdy(glass); - mat2 steps = mat2(gdx, gdy); - float det = determinant(steps); - mat2 maskstep = (abs(det) > 1e-14) ? mat2(dFdx(f_coord), dFdy(f_coord)) * inverse(steps) : mat2(0.0); + float gridSize = ceil(param[2].x); + vec2 rainCoord = f_coord; - // the water the simulation keeps, where the material is a glass of the cab of the train (the param water_slot, given by the - // renderer: 1 + the glass): the view space step along the glass for a step of the uv, and how fresh the wetted path the water - // went along is, with how that changes along the glass (before anything is discarded) - int slot = int(param[2].z + 0.5) - 1; - mat2 uvsteps = mat2(dFdx(f_coord), dFdy(f_coord)); - float uvdet = determinant(uvsteps); - bool simulated = (slot >= 0) && (slot < WATER_SLOTS) && (abs(uvdet) > 1e-24); - simulated = simulated && (water_header[clamp(slot, 0, WATER_SLOTS - 1)].x > 0.5); - mat2x3 puv = (abs(uvdet) > 1e-24) ? mat2x3(dpdx, dpdy) * inverse(uvsteps) : mat2x3(0.0); - vec3 trailfield = simulated ? rw_trail(uint(slot), f_coord, water_header[clamp(slot, 0, WATER_SLOTS - 1)].y) : vec3(0.0); - float trail = trailfield.x; - // its gradient along the glass, view space: the uv gradient taken through the steps of the uv along the glass - vec3 trailslope = vec3(0.0); - { - mat2 metric = transpose(puv) * puv; - if (abs(determinant(metric)) > 1e-30) - trailslope = puv * (inverse(metric) * trailfield.yz); - } + float ambLum = clamp(dot(ambient, vec3(0.2126, 0.7152, 0.0722)), 0.0, 1.0); + float dynBright = pow(clamp(ambLum * 6.0, 0.0, 1.0), 0.5); + // GL 4.6: the ambient light isn't a level of 0..1 any more (it is in the units of the scene, the light of the sky added), so + // at night the drops came out as bright as by day. how bright the picture around really is says it: the coarsest level of + // the image of the last frame, the average of the screen + float sceneLum = (ssr_params.x >= 1.0) ? wsLum(textureLod(ssr_history, vec2(0.5), ssr_params2.x).rgb) : 1.0; + float wsNight = smoothstep(0.0, drop_dark_lum, sceneLum); // 0 dark night .. 1 daylight + dynBright *= wsNight; - if (tex_color.a < 0.01) - discard; + Hit hit; + hit.score = 0.0; hit.cov = 0.0; hit.colA = 0.0; hit.n = vec3(0.0, 0.0, 1.0); + hit.offUV = vec2(0.0); hit.radUV = 1.0; hit.isDrop = 1.0; + hit.vis = 0.0; hit.auv = vec2(0.0); hit.agx = vec2(0.0); hit.agy = vec2(0.0); hit.atlas = 0.0; hit.shade = 0.0; - vec4 layer = vec4(0.0); - float heavy = clamp(rain_params.x, 0.0, 1.0); - bool snow = rain_params.z > 0.5; - if ((heavy > 0.0) || simulated) - { - rw_scale = max(param[2].y, 0.05); + // ---- the air against the vehicle on the glass (uniform flow: the derivatives of the glass) ---- + vec2 wsPushT; + float wsSpeed; + float flipS = (STREAK_FLIP_Y != 0) ? -1.0 : 1.0; // texture v -> glass v (up) + vec3 wsN = (dot(Ngl, f_pos.xyz) < 0.0) ? -Ngl : Ngl; // the outside of the glass + { + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); + vec3 wsUp = vec3(0.0, 1.0, 0.0) * mat3(inv_view); // world up, view space + vec3 wsAir = rain_wind.xyz * mat3(inv_view); // the air against the vehicle, view space, m/s + vec3 wsGrav = -wsUp - wsN * dot(-wsUp, wsN); // the weight along the glass + vec3 wsRise = wsUp - wsN * dot(wsUp, wsN); + wsRise = (length(wsRise) > 0.1) ? normalize(wsRise) : vec3(0.0); + vec3 wsFlow = wsAir - wsN * dot(wsAir, wsN) + wsRise * (max(-dot(wsAir, wsN), 0.0) * WS_HEAD_ON); + float wsDrag = dot(wsFlow, wsFlow) / (WS_DRAG_SPEED * WS_DRAG_SPEED) * wind_drag_gain; // in units of the weight + vec3 wsFlowDir = (length(wsFlow) > 1e-3) ? normalize(wsFlow) : vec3(0.0); + vec3 wsPush = wsGrav + wsFlowDir * wsDrag; + // to the glass UV (v up) through the tangent frame of the texture + vec2 gravG = vec2(dot(wsGrav, Tgl), dot(wsGrav, Bgl) * flipS); + vec2 flowG = vec2(dot(wsFlowDir, Tgl), dot(wsFlowDir, Bgl) * flipS); + if (dot(gravG, gravG) > 1e-8) + { + // down the glass in its UV, to the nearest quarter turn (a finer turn would break the rivulets at the seams where a curved + // glass bends); none on a glass lying flat + float turn = round(atan(gravG.x, -gravG.y) / 1.5707963) * 1.5707963; + wsGravCos = round(cos(turn)); + wsGravSin = round(sin(turn)); + } + wsSpeed = smoothstep(0.3, 1.2, wsDrag); // 0 standing still .. 1 at speed (haze, drops) + wsWindShare = smoothstep(0.5, 1.3, wsDrag); // how much the air drives the rivulets + if (wsWindShare > 0.0) + { + // the rivulets of the air run along the push of the air at twice the weight: the same way at any speed (they don't swing + // round as the train speeds up), up a front glass, back and down a side window + vec2 way = gravG + flowG * 2.0; + if (dot(way, way) > 1e-8) + { + way = normalize(way); + float turn = round(atan(way.x, -way.y) / WS_WIND_STEP) * WS_WIND_STEP; + wsWindCos = cos(turn); + wsWindSin = sin(turn); + } + else + wsWindShare = 0.0; + } + // the push of the air on the drops, texture UV (for stretching them) + wsPushT = vec2(dot(wsPush, Tgl), dot(wsPush, Bgl)); + wsPushT = (dot(wsPushT, wsPushT) > 1e-10) ? normalize(wsPushT) : vec2(0.0, -1.0); + } - // what meets the glass. the air against the vehicle (rain_wind) drags the drops along the glass with what of it goes - // along the glass and with the share of what meets it head on which turns up it: the more the glass leans back the more - // of the air goes along it, and the less of their weight pulls the drops down it - vec3 air = unrot * (rain_wind.xyz * mat3(inv_view)); - float fall = snow ? RW_SNOW_FALL : RW_RAIN_FALL; - float hits = max(-dot(air - up * fall, normal), 0.0); - rw_rate = heavy * clamp(0.7 + hits / fall, 0.7, 6.0); - rw_period = clamp((snow ? 10.0 : 5.0) / rw_rate, 0.4, 300.0); - rw_grow = 2.0 * rw_period; - vec3 gravity = -up - normal * dot(-up, normal); - vec3 rise = up - normal * dot(up, normal); - rise = (length(rise) > 0.1) ? normalize(rise) : vec3(0.0); - vec3 flow = air - normal * dot(air, normal) + rise * (max(-dot(air, normal), 0.0) * RW_HEAD_ON); - vec3 push = gravity + flow * (length(flow) / (RW_DRAG_SPEED * RW_DRAG_SPEED)); - vec2 force = vec2(dot(push, axis_u), dot(push, axis_v)); - rw_push = length(force); - vec2 fallway = vec2(dot(gravity, axis_u), dot(gravity, axis_v)); - rw_down = (length(fallway) > 0.1) ? normalize(fallway) : vec2(0.0, -1.0); - vec2 flowway = vec2(dot(flow, axis_u), dot(flow, axis_v)); - rw_flow = (length(flowway) > 1.0) ? normalize(flowway) : vec2(0.0); + // the wiper state of this pixel (blur, micro droplets) + float hazeSide; + float wipeVis = GetMixFactor(f_coord, hazeSide); + // the change of the glass UV (v up) per screen pixel, for the rivulets + vec2 wsRd1 = vec2(duv1.x, flipS * duv1.y); + vec2 wsRd2 = vec2(duv2.x, flipS * duv2.y); - rw_wipe_s wipe = rw_wipe(mask); - rw_since = wipe.since; - // the blades went lately (any of them, also where none of them reaches) - float working = 0.0; - for (int i = 0; i < 4; ++i) - working = max(working, 1.0 - smoothstep(4.0, 30.0, time - wiper_timer_return[i])); - // how much of the water the place gathers it has - float gathered = 1.0 - exp(-rw_since / (6.0 * rw_period)); - // the film a blade leaves is drawn into fine streaks along its arcs, each a thin cylindrical lens which draws a light seen - // through it into a line across the streaks, towards the pivot of the blade: the way across the streaks on the screen - vec2 streakway = vec2(0.0); - if ((working > 0.0) && (false == snow) && (abs(det) > 1e-14)) - { - int blade = 0; - for (int i = 1; i < 4; ++i) - blade = (mask[i] > mask[blade]) ? i : blade; - if (mask[blade] >= 0.001) - { - // the mask grows along the arcs; a step of a centimetre, so the steps of its values don't matter - float mu = textureLod(wipermask, f_coord + maskstep * vec2(0.01, 0.0), 0.0)[blade]; - float mv = textureLod(wipermask, f_coord + maskstep * vec2(0.0, 0.01), 0.0)[blade]; - vec2 arc = vec2(mu, mv) - mask[blade]; - vec2 onscreen = inverse(steps) * vec2(-arc.y, arc.x); - if ((length(arc) > 1e-4) && (length(onscreen) > 1e-9)) - streakway = normalize(onscreen); - } - } - vec3 ripple = rw_noise2(glass / (0.006 * rw_scale), 5u); + // ---- rivulet cell of this pixel (also used to sweep the drops) ---- + wsSetLayer(0); + float sCW = streak_cell / gridSize; + float sCH = streak_run / gridSize; + vec2 sUVg = vec2(f_coord.x, (STREAK_FLIP_Y != 0) ? 1.0 - f_coord.y : f_coord.y); // glass UV, v up + vec2 sUVl = wsToLayer(sUVg); // the same in the layer of the weight (down: -v) + vec2 sCell = floor(sUVl / vec2(sCW, sCH)); + bool sweepOn = streak_sweep > 0.0 && streak_density > 0.0 && (wind_streaks > 0.0 || wsWindShare < 1.0) && (WS_PROFILE != 2); - // the water a blade pushes: a bead in front of it while it moves, as wide as the water it gathered on its way, with a steep - // lumpy front (its edge shows dark, the view can't get out there). the drops the bead reaches flow into it - vec3 lumps = rw_noise2(glass / (0.009 * rw_scale), 7u); - float gatheredwater = snow ? 0.0 : min(gathered * 1.5, 1.0) * (0.35 + 0.65 * min(wipe.swept * 2.5, 1.0)); - float reach = 0.004 + 0.018 * gatheredwater + 0.008 * (ripple.x - 0.5); - float ridge = gatheredwater * smoothstep(0.0, 0.003, wipe.front) * (1.0 - smoothstep(reach - 0.004, reach, wipe.front)); - // the smooth shape from how it changes from pixel to pixel, the lumps on it as they are - float pooledbase = 0.004 * ridge; - float pooled = pooledbase * (0.75 + 0.5 * lumps.x); - vec3 pooledslope = rw_gradient(pooledbase, dpdx, dpdy, outward) * (0.75 + 0.5 * lumps.x) + rw_along(lumps.yz * (0.5 * pooledbase / (0.009 * rw_scale))); - if ((pooled > 0.0) && (false == simulated)) - { - rw_sheet(pooled, pooledslope, 0.03, smoothstep(0.0, 0.1, ridge)); - if (ridge > 0.05) - rw_cleared = time; - } + // the cells (rain_cells) are read only when worked out in this frame (rain_state.w): before the first rain, or without their + // storage, there is nothing in them + if ((rain_state.y > 0.001) && (rain_state.w > 0.5) && (WS_PROFILE != 5)) + { + // =================================================================== + // 1. drops from the atlas: this cell and its 8 neighbours + // =================================================================== + vec2 cellF = rainCoord * gridSize; + vec2 cell = floor(cellF); +#if WS_PROFILE != 4 + // the drops of the 9 cells around which reach the quarter of the cell the pixel lies in (worked out by rain_cells.comp, + // with the drops there are now): usually 1 .. 3 of them + uvec2 quarter = uvec2(greaterThanEqual(cellF - cell, vec2(0.5))); + uint reach = rain_cells[rain_mask_index(ivec2(cell))][quarter.y * 2u + quarter.x]; + while (reach != 0u) + { + int bit = findLSB(reach); + reach &= reach - 1u; + vec2 nc = cell + vec2(float(bit % 3 - 1), float(bit / 3 - 1)); + uvec4 d = rain_cells[rain_drop_index(ivec2(nc))]; + // as many drops as the glass is wet (the cells were sorted out with a little more) + if (rain_byte(d.y, 24u) > min(rain_state.y * drop_density, 0.95)) + continue; + float vis = float(d.w >> 24) * (1.0 / 255.0); + float spreadF = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); + // a drop the blades miss: the same drop before and after the stroke, left where it is + bool missed = ((d.w >> 19) & 1u) != 0u; + vec2 center0, center1, dl0, dl1; + float sq0, sq1, sag0, sag1; + mat2 shape0, shape1; + bool in0 = wsDropShape(d.x, d.y, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center0, sq0, sag0, shape0, dl0); + bool in1 = (!missed) && wsDropShape(d.z, d.w, nc, gridSize, spreadF, wsSpeed, wsPushT, rainCoord, center1, sq1, sag1, shape1, dl1); + // the wipers asked only for the drops the pixel lies on + if (!(in0 || in1)) + continue; + float side = 0.0; + float mixF = missed ? 1.0 : GetMixFactor((nc + 0.5) / gridSize, side); + bool back = (side > 0.5); + if (!(back ? in1 : in0)) + continue; + if (mixF < rain_byte(back ? d.z : d.x, 0u)) + continue; + uint db = back ? d.w : d.y; + vec2 center = back ? center1 : center0; + float sq = back ? sq1 : sq0; + float sag = back ? sag1 : sag0; + mat2 shapeM = back ? shape1 : shape0; + vec2 dl = back ? dl1 : dl0; + float flipX = (((db >> 16) & 1u) != 0u) ? 1.0 : 0.0; + float choice = (float((db >> 17) & 3u) + 0.5) * 0.25; + vec2 diff = rainCoord - center; - float snowcover = 0.0; - float wet = 0.0; - if (simulated) - { - // the directions along the glass, view space - vec3 upview = vec3(0.0, 1.0, 0.0) * mat3(inv_view); - vec3 downview = -(upview - outward * dot(upview, outward)); - downview = (length(downview) > 0.05) ? normalize(downview) : normalize(cross(outward, normalize(rw_tu))); - vec3 sideview = cross(outward, downview); - rw_simulated(uint(slot), f_coord, puv, downview, sideview, snowcover, wet); - // the paths the water went along lately: a rivulet, a band of water rounded across (a cylinder lens: it holds a picture of - // the place around it turned over across the band, its edges dark as the edges of drops), thicker the fresher. the - // smoothed freshness falls off from the middle of a path to its edges - if (trail > 0.08) - { - float p = clamp((trail - 0.08) / 0.5, 0.0, 1.0); - float thickness = 0.0005 * (1.0 - (1.0 - p) * (1.0 - p)); - vec3 rise = trailslope * (0.0005 * 2.0 * (1.0 - p) / 0.5); - float steep = length(rise); - if (steep > 0.7) - rise *= 0.7 / steep; - bool top = thickness > rw_height; - rw_sheet(thickness, rise, 0.004, smoothstep(0.0, 0.15, p) * 0.95); - // from the middle of the band to the fragment - float across = length(trailslope) / 0.5; - if (top && (across > 1.0)) - rw_offset = -trailslope * ((1.0 - p) / (across * length(trailslope))); - } - } - else if (false == snow) - { - // the drops which grew big enough slide off, with gravity and the air: a set of tracks for each of the directions of the - // push nearest to the one now, each laid along its own way, so none of them moves when the push turns - float sliding = smoothstep(0.25, 0.6, rw_push); - if (sliding > 0.0) - { - float bin = atan(force.y, force.x) / (RW_PI / 6.0); - float lower = floor(bin); - for (int k = 0; k < 2; ++k) - { - float share = ((k == 0) ? 1.0 - (bin - lower) : bin - lower) * sliding; - if (share < 0.02) - continue; - float angle = (lower + float(k)) * (RW_PI / 6.0); - vec2 down = vec2(cos(angle), sin(angle)); - vec2 side = vec2(-down.y, down.x); - rw_sliders(vec2(dot(glass, side), -dot(glass, down)), side, down, uint(int(lower) + k + 64) * 2u + 16u, share); - } - } + if (sweepOn) + { + vec2 cg = vec2(center.x, (STREAK_FLIP_Y != 0) ? 1.0 - center.y : center.y); + vis *= wsKept(cg, 0.35 * sq, sCW, sCH, gridSize); + } + if (vis <= 0.001) + continue; - // the drops as they land, each time somewhere else in its cell, as often as the rain hits the glass: the drops of the - // rain spread on the glass, thrown with a fine splash which runs back into them - // each drop anywhere in its cell, the cell as large as a drop with its splash reaches - float cell = 0.007 * rw_scale; - vec2 laid = rw_turn(glass, 0.61) + vec2(0.31, 0.17); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.08, 0.3, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 1u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 1u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.5, 0.9, b.y); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 2u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.61); - float visible = mix(0.0011, 0.0019, b.z) * rw_scale; - // a raindrop hits the glass far above the speed at which it splashes (Weber number in the hundreds and thousands): - // it spreads, throws a spray of droplets which stay on the glass around it, and draws back - float splash = exp(-age / 0.06); - float fade = 1.0 - smoothstep(life - min(0.4, 0.3 * life), life, age); - if (visible * 0.3 > 0.5 * rw_pixel) - { - int spray = 3 + int(p.z * 4.0); - for (int s = 0; s < spray; ++s) - { - vec4 e = rw_random(c, 3u, uint(cycle) * 8u + uint(s)); - vec2 way = normalize(vec2(cos(e.x * 6.2831853), sin(e.x * 6.2831853)) + rw_flow * 0.9); - rw_blob(offset - way * (visible * (1.4 + 1.6 * e.y)), visible * mix(0.18, 0.35, e.z), fade * (0.55 + 0.45 * splash)); - } - } - rw_drop(offset, visible * (1.0 + 0.3 * splash), fade, p.wzyx); - } - } - // the drops the landing ones gathered into, growing until they are big enough to slide (the air blows them off sooner) - cell = 0.011 * rw_scale; - laid = rw_turn(glass, 1.07) + vec2(0.53, 0.29); - home = ivec2(floor(laid / cell)); - density = mix(0.55, 1.0, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 4u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 4u, 1u); - float span = rw_period * mix(2.5, 4.0, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.75, 0.98, b.y) / (1.0 + 2.0 * max(rw_push - 1.0, 0.0)); - if ((age > life) || (age > rw_since) || (time - age < rw_cleared)) - continue; - vec4 p = rw_random(c, 5u, uint(cycle)); - // the big drops are much alike: they grow as they gather the small ones (the radius in step with the time) up to the - // size at which they slide off (on a vertical glass a footprint of about 9 mm, larger on a glass leaning back, smaller - // in a strong air flow), and go - float slides = min(0.0045 / sqrt(max(rw_push, 0.3)), 0.005); - float visible = slides * mix(0.6, 1.0, b.z) * rw_scale * mix(0.35, 1.0, clamp(age / (0.6 * life), 0.0, 1.0)); - rw_drop(rw_turn(laid - (vec2(c) + p.xy) * cell, -1.07), visible, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.zwxy); - } - } + vec2 luv = dl / sq + 0.5; + if (flipX > 0.5) luv.x = 1.0 - luv.x; + float atlasTexels = float(textureSize(normalmap, 0).x); + float quadPx = sq / max(uvPerPx, 1e-6); + float nlod = clamp(log2(max(0.25 * atlasTexels / max(quadPx, 1.0), 1.0)), 0.0, 6.0); + vec4 nm = textureLod(normalmap, dropAtlasUV(choice, luv), nlod); + float cov = smoothstep(0.1, 0.6, nm.a) * vis; + if (cov <= 0.001) + continue; + vec2 nxy = nm.rg * 2.0 - 1.0; + if (flipX > 0.5) nxy.x = -nxy.x; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec2 slope = transpose(shapeM) * (-nxy / max(nz, 0.08)); + vec3 n = normalize(vec3(-slope, 1.0)); + // gradients of the tile UV (for the one atlas read after the loop) + vec2 gx = (shapeM * duv1) / sq * vec2(0.25, 0.5); + vec2 gy = (shapeM * duv2) / sq * vec2(0.25, 0.5); + consider(hit, cov * (nm.b * sq * sag + 1e-5), cov, 0.0, n, diff, 0.5 * sq, 1.0, + vis, dropAtlasUV(choice, luv), gx, gy, 1.0, 0.0); + } +#endif - // the water the blades push out of their sweep: a broken row of drops flowed together along its edge, just outside it - float leave = working * min(heavy * 1.5, 1.0); - if ((leave > 0.0) && rw_border(f_coord, 0.009 * rw_scale, maskstep)) - { - cell = 0.0065 * rw_scale; - laid = rw_turn(glass, 0.29) + vec2(0.11, 0.43); - home = ivec2(floor(laid / cell)); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 20u, 0u); - if (a.x > 0.85) - continue; - // from the fragment to the middle of the drop, along the glass - vec2 centre = rw_turn((vec2(c) + a.yz) * cell - laid, -0.29); - float rim = rw_rim(f_coord + maskstep * centre, 0.004 * rw_scale, maskstep) * leave; - if (rim <= 0.05) - continue; - rw_drop(-centre, mix(0.0016, 0.003, a.w) * rw_scale * mix(0.6, 1.0, rim), smoothstep(0.05, 0.35, rim), rw_random(c, 21u, 0u)); - } - } - } + // =================================================================== + // 2. micro droplets: procedural, one per micro cell, fully inside it + // =================================================================== + if ((micro_density > 0.0) && (WS_PROFILE != 3)) + { + float mg = gridSize * micro_scale; + vec2 mc = floor(rainCoord * mg); + uvec2 mk = cellKey(mc); + uint m0 = Hash(uvec3(mk, 51u)); + float mLife = micro_life * mix(0.6, 1.6, RandF(m0)); + float mtt = time / mLife + RandF(m0); + float mph = fract(mtt); + uint mep = uint(mod(floor(mtt), 65521.0)); + uint m1 = Hash(uvec3(mk, mep * 4u + 1u)); + if (RandF(m1) < min(micro_density * rain_state.y, 0.95)) + { + uint m2 = Hash(uvec3(mk, mep * 4u + 2u + uint(hazeSide) * 2u)); + if (wipeVis >= RandF(m2)) + { + float r = mix(micro_size_min, micro_size_max, pow(RandF(m2), 1.5)); + vec2 c = mc + vec2(r) + vec2(RandF(m2), RandF(m2)) * max(1.0 - 2.0 * r, 0.0); + float ell = mix(0.85, 1.15, RandF(m2)); + vec2 p = (rainCoord * mg - c) / r; + p.x *= ell; + float d2 = dot(p, p); + if (d2 < 1.0) + { + float vis = smoothstep(0.0, 0.01, mph) * (1.0 - smoothstep(0.97, 1.0, mph)); + if (sweepOn) + { + vec2 cu = c / mg; + vec2 cg = vec2(cu.x, (STREAK_FLIP_Y != 0) ? 1.0 - cu.y : cu.y); + vis *= wsKept(cg, r / mg, sCW, sCH, gridSize); + } + float d = sqrt(d2); + float cov = smoothstep(1.0, 0.8, d) * vis; + if (cov > 0.001) + { + vec2 nxy = p * micro_bulge; + float nz = sqrt(1.0 - clamp(dot(nxy, nxy), 0.0, 1.0)); + vec3 n = normalize(vec3(nxy, nz)); + float h = sqrt(1.0 - d2) * micro_bulge * (r / mg); + float rim = smoothstep(drop_rim_start, drop_rim_end, 1.0 - n.z); + float lt = dot(n, DROP_LIGHT) * drop_light_side * 0.5 + (1.0 - drop_light_side * 0.5); + consider(hit, cov * (h + 1e-6), cov, smoothstep(1.0, 0.9, d) * vis, n, + rainCoord - c / mg, r / mg, 1.0, + vis, vec2(0.0), vec2(0.0), vec2(0.0), 0.0, clamp(rim * lt, 0.0, 1.0)); + } + } + } + } + } - // the streams running down from the water the blades leave at the ends of their sweep: a stream in some of the columns - // along the way down, where up the glass there is such water, as far down as the water had time to run since the blade - // went over the place - if ((working > 0.0) && (length(fallway) > 0.3)) - { - vec2 side = vec2(-rw_down.y, rw_down.x); - float width = 0.035 * rw_scale; - float across = dot(glass, side); - float along = -dot(glass, rw_down); - int column = int(floor(across / width)); - vec4 a = rw_random(ivec2(column, 0), 30u, 0u); - if (a.x < 0.6 * heavy * working) - { - float lateral = across - rw_path(column, along, width, 31u); - float half_width = mix(0.0006, 0.0012, a.z) * rw_scale * (0.6 + 0.8 * rw_noise(along / (0.006 * rw_scale), 32u)); - if (abs(lateral) < 2.0 * half_width + rw_pixel) - { - // up the glass, the first place where the reach of the blades begins or ends - const float reach[6] = float[](0.01, 0.025, 0.05, 0.1, 0.18, 0.3); - bool here = rw_reached(f_coord); - float source = -1.0; - for (int s = 0; s < 6; ++s) - { - if (rw_reached(f_coord + maskstep * (-rw_down * reach[s])) != here) - { - source = reach[s]; - break; - } - } - if ((source > 0.0) && (source < max(rw_since - 0.1, 0.0) * 0.2)) - { - float beads = rw_noise(along / (0.004 * rw_scale), 33u); - float flowing = working * (1.0 - 0.5 * smoothstep(0.15, 0.3, source)); - rw_blob(side * lateral, half_width, flowing * mix(0.6, 1.2, beads)); - } - } - } - } - } - else - { - // the flakes stick where they land and melt into drops: the glass is warmed by the cab, faster in the air above zero - float warm = rain_params.w; - float cell = 0.016 * rw_scale; - vec2 laid = rw_turn(glass, 0.83) + vec2(0.07, 0.61); - ivec2 home = ivec2(floor(laid / cell)); - float density = mix(0.5, 0.9, heavy); - for (int y = -1; y <= 1; ++y) - { - for (int x = -1; x <= 1; ++x) - { - ivec2 c = home + ivec2(x, y); - vec4 a = rw_random(c, 11u, 0u); - if (a.x > density) - continue; - vec4 b = rw_random(c, 11u, 1u); - float span = rw_period * mix(0.7, 1.3, a.w); - float cycle = floor(time / span + b.x); - float age = time - (cycle - b.x) * span; - float life = span * mix(0.6, 0.95, b.y); - if ((age > life) || (age > rw_since)) - continue; - vec4 p = rw_random(c, 12u, uint(cycle)); - vec2 offset = rw_turn(laid - (vec2(c) + p.xy) * cell, -0.83); - float diameter = mix(RW_SNOW_DIAMETER.x, RW_SNOW_DIAMETER.y, b.z) * rw_scale; - float melt = ((warm > 0.5) ? mix(3.0, 10.0, b.w) / (1.0 + 0.25 * warm) : mix(15.0, 45.0, b.w)); - if (age < melt) - { - float m = age / melt; - float dist = length(offset.x * rw_tu + offset.y * rw_tv); - float radius = 0.5 * diameter; - if (dist < radius + rw_pixel) - { - float angle = atan(offset.y, offset.x); - float lobes = 0.55 + 0.45 * (0.6 * rw_noise(angle * 1.9 + p.z * 40.0, 13u) + 0.4 * abs(cos(3.0 * angle + p.w * 6.2831853))); - float rim = radius * lobes * (1.0 - 0.45 * m); - float body = smoothstep(rim + rw_pixel, 0.55 * rim - rw_pixel, dist); - float lace = rw_noise2(glass / (0.0007 * rw_scale) + p.zw * 100.0, 14u).x; - float flake = body * mix(0.55, 1.0, lace) * (1.0 - 0.7 * m * m); - snowcover = 1.0 - (1.0 - snowcover) * (1.0 - flake); - wet = max(wet, m * body); - } - } - else - { - // the water of the flake - rw_drop(offset, 0.0018 * pow(diameter / 0.008, 0.667) * rw_scale, 1.0 - smoothstep(life - min(0.5, 0.3 * life), life, age), p.wzyx); - } - } - } - // the snow the blades push in front of them and leave at the ends of their sweep - float pile = max(wipe.ahead * min(gathered * 2.0, 1.0) * (0.4 + 0.6 * min(wipe.swept * 2.5, 1.0)), rw_rim(f_coord, 0.006 * rw_scale, maskstep) * working * heavy); - float packed = rw_noise2(glass / (0.0015 * rw_scale), 15u).x; - snowcover = max(snowcover, smoothstep(0.15, 0.5, pile * 1.2 + 0.4 * (ripple.x - 0.5)) * mix(0.7, 1.0, packed)); - } - // untreated glass, weathered and a little dirty: flat drops (a rain repellent coating would give beads above 90 degrees) - rw_settle(radians(mix(30.0, 48.0, rw_noise2(glass / (0.005 * rw_scale), 16u).x))); + // =================================================================== + // 3. rivulets of this pixel's cells: the layer of gravity and, at speed, the one of the air + // =================================================================== +#if WS_PROFILE != 2 + wsSetLayer(0); + drawRivulet(hit, getRiv(sCell, sCW, sCH, gridSize), sUVl, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + if (wsWindShare > 0.001) + { + for (int wl = 1; wl <= wind_layers; ++wl) + { + vec2 wc = vec2(sCW * wind_cell_scale, sCH * ((wl == wind_layers) && (wl > 1) ? wind_long_run : wind_run_scale)); + wsSetLayer(wl); + // every further layer: its cells shifted aside, drops of its own + vec2 sUVw = wsToLayer(sUVg) + fract(vec2(0.5, 0.618) * float(wl - 1)) * wc; + Riv rivW = getRiv(floor(sUVw / wc), wc.x, wc.y, gridSize); + drawRivulet(hit, rivW, sUVw, wsToLayerDir(wsRd1), wsToLayerDir(wsRd2)); + } + wsSetLayer(0); + } +#endif + } - // the lamps (of the cab, of the scenery) and the headlights light the water up, from both sides of the glass (worked out - // here, where the fragments of a quad go together) - vec3 lamps = vec3(0.0); - vec3 lampgloss = vec3(0.0); - add_local_lights(outward, lamps, lampgloss); - add_local_lights(-outward, lamps, lampgloss); + // ---- the frame of the glass, the change of the view and the lens, for the shading (uniform flow again) ---- + vec2 sxy = f_pos.xy / max(-f_pos.z, 1e-3); + float pxPerSlope = 1.0 / max(max(length(dFdx(sxy)), length(dFdy(sxy))), 1e-6); + vec3 wsView = normalize(f_pos.xyz); // the view through the glass and its change per pixel (for the bent view) + vec3 wsDvx = dFdx(wsView); + vec3 wsDvy = dFdy(wsView); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec3 Tgl, Bgl; + wsGlassFrame(Ngl, duv1, duv2, Tgl, Bgl); + // glass UV offset -> screen pixels (inverse of the UV Jacobian), for the drop lens + mat2 Juv = mat2(duv1, duv2); + float detJ = determinant(Juv); + mat2 Jinv = (abs(detJ) > 1e-20) ? inverse(Juv) : mat2(0.0); - // the film just behind a blade, breaking up - float film = snow ? 0.0 : heavy * exp(-rw_since / 0.8) * smoothstep(0.02, 0.08, rw_since); - if (film > 0.01) - { - vec3 fine = rw_noise2(glass / (0.0021 * rw_scale), 6u); - vec2 tilt = fine.yz * (0.004 * film); - rw_sheet(0.00005 * film, rw_along(tilt), 0.3, 0.8 * film); - } + // ----------------------------------------------------------------------- + // Shading of the winning dome + // ----------------------------------------------------------------------- + float coverA = clamp(hit.cov, 0.0, 1.0); + vec3 dropLayer = vec3(0.0); + float alphaOut = 0.0; + vec3 dropGlint = vec3(0.0); + vec2 lensBend = vec2(0.0); + float lensK = 0.0; // drops: how much the lens shrinks the picture + float lensRadPx = 1.0e4; // drops: radius on screen, pixels + if (coverA > 0.001) + { + vec3 Nt = hit.n; + // look of the drop: grey atlas (bright rim, dark middle) for drops and rivulets, analytic for droplets + vec3 rgb; + float colA; + if (hit.atlas > 0.5) + { + vec4 at = textureGrad(raindropsatlas, hit.auv, hit.agx, hit.agy); + rgb = at.rgb; + colA = smoothstep(0.3, 0.9, at.a) * hit.vis; + } + else + { + rgb = vec3(hit.shade); + colA = hit.colA; + } + float a = colA * mix(drop_center_alpha, drop_rim_alpha, smoothstep(0.1, 0.3, length(rgb))); + dropLayer = rgb * dynBright * a; + alphaOut = clamp(a, 0.0, 1.0); - // what the water shows: the view goes through the glass (a plate: only the way from the air into the water counts) and out - // through the surface of the water, bent as much as it is curved. it is the world turned upside down in a drop, and the - // edges of a drop, where the view can't get out (total internal reflection), show the inside of the cab - float background = 0.0; - bool image = ssr_params.x >= 1.0; - if (image) - { - ivec2 size = textureSize(scene_depth, 0); - float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; - if (depth > 0.0) - background = (projection[3][2] / depth) / max(-view.z, 0.05); - } - vec3 inside = ambient * (AMBIENT_SCALE * 0.5); - vec4 water = vec4(0.0); - if (rw_cover > 0.0) - { - vec3 surface = normalize(outward - rw_slope); - vec3 inwater = refract(view, -outward, 1.0 / RW_IOR); - vec3 through = refract(inwater, -surface, RW_IOR); - // what the surface reflects back inside the water: the light which came in at the other side of the drop, from the sky, - // and the inside of the cab. where the view can't get out (the edge of a drop) that is all it shows: a bright edge - vec3 bounced = reflect(inwater, surface); - if (dot(bounced, outward) < 0.0) - bounced = reflect(bounced, outward); - vec3 inner = mix(inside, rw_surroundings(normalize(bounced), 5.0), 0.3); - vec3 color = inner; - if (dot(through, through) > 0.5) - { - float fresnel = 0.02 + 0.98 * pow(1.0 - abs(dot(through, surface)), 5.0); - // the view through the water spreads over this much of the world across a pixel (radians) - float spread = (RW_IOR - 1.0) * rw_pixel / max(rw_curve, 1e-4); - // the picture the drop holds as a lens, and a share of the bending by the surface - vec3 lens = normalize(f_pos.xyz - (1.0 + RW_LENS) * rw_offset) + (through - view) * RW_LENS_BEND; - float lod = mix(log2(1.0 + RW_LENS) - 0.5, log2(max(spread / pixelangle, 1.0)), RW_LENS_BEND); - // a drop a few pixels across would hold a picture of single pixels, a grain: blurred more the smaller it looks - lod += clamp(2.5 - log2(max(rw_curve / rw_pixel, 1.0)), 0.0, 1.5); - float share; - vec3 seen = rw_behind(normalize(lens), lod, background, share); - // the sun through the drop, where the image doesn't hold it: as bright as the drop gathers its light. in heavier rain - // the sun is behind the clouds, its disc is not there to be focused - float sunshare = (1.0 - heavy) * (1.0 - heavy); - if ((lights_count > 0U) && (share < 1.0) && (sunshare > 0.01)) - { - vec3 sun = normalize(-lights[0].dir); - float width = max(spread, 0.03); - float off = acos(clamp(dot(through, sun), -1.0, 1.0)); - if (off < 4.0 * width) - { - float lit = 1.0 - clamp(calc_shadow(), 0.0, 1.0); - vec3 sunlight = lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * cloud_shadow(mat3(inv_view) * f_pos.xyz)); - // the light of the sun over the spread of the view: a pixel shows pi * irradiance * the share of a steradian - seen += sunlight * (sunshare * lit * (1.0 - share) * exp(-0.5 * off * off / (width * width)) / (2.0 * width * width)); - } - } - color = mix(seen, inner, fresnel); - } - color += lamps * 0.6; - // without the image of the last frame the surroundings stand for what the water bends the view to; nearly flat water - // would show them in place of the scene behind it, so it is left mostly clear - float opaque = image ? 1.0 : mix(0.3, 1.0, smoothstep(0.02, 0.15, 1.0 - dot(through, view))); - water = vec4(color, rw_cover * opaque); - } - // the wet glass where the rain gathers is a little hazy: the tiniest drops spread the light - if (image && (false == snow)) - { - float mist = heavy * gathered * (simulated ? 0.18 : 0.3); - if (mist > 0.01) - { - float share; - vec3 hazy = rw_behind_edges(view, 3.5, background, share, false); - // the tiniest drops spread the light of the sky coming through the glass - hazy = mix(hazy, rw_surroundings(outward, 7.0), 0.1); - layer = vec4(hazy, mist * max(share, 0.5)); - } - } - layer = rw_over(water, layer); - // the lights seen through the streaks of the film the blades leave, drawn into lines towards their pivot - if (image && (length(streakway) > 0.5)) - { - vec4 previous = ssr_reprojection * ((background > 0.0) ? vec4(view * background, 1.0) : vec4(view, 0.0)); - if (previous.w > 1e-5) - { - vec2 coords = (previous.xy / previous.w) * 0.5 + 0.5; - vec2 texel = 1.0 / vec2(textureSize(ssr_history, 0)); - ivec2 size = textureSize(scene_depth, 0); - float near = projection[3][2]; - // a light: much brighter than the place around it (the bright sky is not) - vec3 around = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 6.0).rgb; - float threshold = max(1.0, 3.0 * max(around.r, max(around.g, around.b))); - vec3 glare = vec3(0.0); - float total = 0.0; - for (int k = -8; k <= 8; ++k) - { - if (k == 0) - continue; - float w = 1.0 - abs(float(k)) / 9.0; - total += w; - vec2 tap = coords + streakway * texel * (float(k) * 5.0); - if (any(lessThan(tap, vec2(0.0))) || any(greaterThan(tap, vec2(1.0)))) - continue; - // only what is outside: the lamps of the cab are not behind the glass - float depth = texelFetch(scene_depth, clamp(ivec2(tap * vec2(size)), ivec2(0), size - 1), 0).r; - if ((depth > 0.0) && (near / depth < -f_pos.z + 2.5)) - continue; - vec3 c = textureLod(ssr_history, tap, 1.5).rgb; - if (any(isnan(c)) || any(isinf(c))) - continue; - glare += max(c - vec3(threshold), vec3(0.0)) * w; - } - glare *= 0.6 * heavy * working / total; - if (any(greaterThan(glare, vec3(1e-4)))) - { - // the scene itself under the water carries the light added (it changes nothing seen) - vec3 scene = textureLod(ssr_history, clamp(coords, vec2(0.0), vec2(1.0)), 0.0).rgb; - layer = rw_over(layer, vec4(max(scene, vec3(0.0)), 0.2)); - layer.rgb += glare / layer.a; - } - } - } - if (snowcover > 0.0) - { - // the flakes are lit through from the outside, by the sky and the sun, and from the inside of the cab; melting they turn - // grey and clear - vec3 outside = rw_surroundings(outward, 6.0); - if (lights_count > 0U) - { - vec3 sun = normalize(-lights[0].dir); - outside += lights[0].color * (SUN_DIFFUSE_SCALE * lights[0].intensity * max(dot(outward, sun), 0.0) * (1.0 - clamp(calc_shadow(), 0.0, 1.0))); - } - vec3 flake = mix(vec3(0.92), vec3(0.62, 0.66, 0.7), wet); - vec3 color = flake * (outside * (0.35 * (1.0 - 0.5 * wet)) + ambient * (AMBIENT_SCALE * 0.7)); - layer = rw_over(vec4(color, snowcover * mix(0.97, 0.6, wet)), layer); - } - } - out_color = layer; + // refraction: Snell for rivulets (and as a fallback), lens picture for drops + vec3 I = normalize(f_pos.xyz); + vec3 No = (dot(Ngl, I) > 0.0) ? Ngl : -Ngl; + vec3 Nd = normalize(Tgl * Nt.x + Bgl * Nt.y + No * Nt.z); + vec3 R = refract(I, -Nd, drop_ior); + if (dot(R, R) < 1e-4) + R = refract(I, -Nd, 1.0 + 0.5 * (drop_ior - 1.0)); + vec2 dSlope = vec2(0.0); + if (dot(R, R) > 1e-4 && R.z < -0.05) + dSlope = R.xy / (-R.z) - I.xy / (-I.z); + vec2 snellBend = clamp(-(dSlope * pxPerSlope * drop_refract) / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = snellBend; + if (hit.isDrop > 0.5 && drop_lens_mix > 0.0) + { + vec2 offPx = Jinv * hit.offUV; // pixel - drop centre, in screen pixels + float radPx = hit.radUV / max(uvPerPx, 1e-6); + float k = clamp(min(drop_lens, 0.95 * WS_REFR_MAXPX / max(radPx, 1.0) - 1.0), 0.0, drop_lens); + vec2 lb = clamp((1.0 + k) * offPx / WS_REFR_MAXPX, vec2(-1.0), vec2(1.0)); + lensBend = mix(snellBend, lb, drop_lens_mix); + lensK = k; + lensRadPx = radPx; + } - { // Overlay windshield texture with alpha - vec3 fragcolor = ambient; - vec3 fragnormal = normalize(f_normal); - float reflectivity = param[1].z; - float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; - legacy_gloss(); + vec3 Rd = (dot(R, R) > 1e-4) ? normalize(R) : I; + vec3 glint = vec3(0.0); + if (lights_count > 0U) + { + float cosS = max(dot(Rd, normalize(-lights[0].dir)), 0.0); + float lobe = pow(cosS, drop_glint_sharpness) * drop_glint_strength + + pow(cosS, 0.2 * drop_glint_sharpness) * drop_sheen; + // the shadow (shadow map + GL 4.6 contact shadow ray) only where the sun shows in the drop at all + if (lobe > 1e-4) + { + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + // GL 4.6: the clouds hold the sun back where their shadow falls (as in apply_lights) + float cloudSun = cloud_shadow(mat3(inv_view) * f_pos.xyz); + glint += lights[0].color * lights[0].intensity * lobe * (1.0 - shadowSun) * cloudSun * wsNight; + } + } + // GL 4.6: headlights and lamps come from the light cluster of the fragment (lights_clustered), or are the + // first lights_count - 1 headlights otherwise. calc_headlights takes the screen-space change of f_pos + // (worked out at the top of main, in uniform flow). The drop scatters light from both sides of the glass, + // so the glass normal is turned towards the light. + // only the lights outside the glass and a few metres away light the drops up (signals, lamps of the station, the + // headlights of other trains): the lamps and the headlights of the own vehicle, a metre or two from the glass, would + // make every drop glow white + vec3 lamps = vec3(0.0); + if (lights_clustered != 0U) + { + cluster_range_s range = cluster_ranges[fragment_cluster()]; + for (uint i = 0U; i < range.count; i++) + { + light_s lt = lights[cluster_light_indices[range.offset + i]]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + if (lt.type == LIGHT_HEADLIGHTS) + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + else if (drop_lamp_scatter > 0.0) + lamps += lt.color * calc_local_light(lt, nl).x * lt.intensity * drop_lamp_scatter * away; + } + } + else + { + for (uint i = 1U; i < lights_count; i++) + { + light_s lt = lights[i]; + vec3 toL = lt.pos - f_pos.xyz; + float away = smoothstep(0.0, 0.2, dot(toL, wsN) / max(length(toL), 1e-4)) + * smoothstep(drop_light_near, 2.0 * drop_light_near, length(toL)); + if (away <= 0.0) + continue; + vec3 nl = (dot(Ngl, toL) > 0.0) ? Ngl : -Ngl; + lamps += lt.color * calc_headlights(lt, nl, dp1, dp2).x * lt.intensity * drop_headlight_scatter * away; + } + } + glint += min(lamps, vec3(drop_light_max)); + // reflection of the surroundings on the dome: straight from the environment map. (It used to go through a + // second apply_lights, which in GL 4.6 also runs the shadow map, the contact shadows and the whole light + // cluster again for every drop pixel; the sun and the lamps are done above already.) + if (drop_env > 0.0) + { + vec3 Nv = -Nd; // dome normal towards the viewer + float NoV = clamp(dot(Nv, -I), 0.0, 1.0); + glint += envmap_color_lod(Nv, 0.8) * EnvBRDFApprox(vec3(0.04), 0.1, NoV) * drop_env * wsNight; + } +#if WS_PROFILE == 1 + glint = vec3(0.0); +#endif + dropGlint = glint; + if (!POSTFX_ENABLED) + dropGlint = min(dropGlint, vec3(1.0)); // this path is not tonemapped + } - fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); - vec4 color = vec4(fragcolor, tex_color.a * alpha_mult); + // ----------------------------------------------------------------------- + // What is seen through the wet glass: the image of the last frame, blurred by the haze, bent by the drops + // ----------------------------------------------------------------------- + // the haze after the wiper: grows with the rain fallen since, up to the intensity of the rain (as it always was where no wiper reaches) + float wipeRain = wsWipeRain(f_coord); + float hazeBack = (wipeRain < 0.0) ? rain_state.y + : min(rain_state.y, pow(clamp(wipeRain / haze_fill, 0.0, 1.0), haze_curve)); + // up to the full haze in any rain, as the glass gets wet (a lighter rain only mists it up more slowly), less as it dries + float hazeWeight = hazeBack * (1.0 - max(alphaOut, coverA)); + float glassClear = 1.0 - smoothstep(0.5, 0.95, glassA); + bool image = ssr_params.x >= 1.0; + float background = 0.0; // distance to the scene behind, along the view (0: far / not known) + if (image) + { + ivec2 size = textureSize(scene_depth, 0); + float depth = texelFetch(scene_depth, clamp(ivec2(gl_FragCoord.xy), ivec2(0), size - 1), 0).r; + if (depth > 0.0) + background = (projection[3][2] / depth) / max(-wsView.z, 0.05); + } + vec4 under = vec4(0.0); // the blurred view under the drops (not premultiplied) + vec4 bent = vec4(0.0); // the view bent by the drops, laid over everything (as the old postfx did) - out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); - out_color.a = mix(out_color.a, 1., color.a); - } - if (false == POSTFX_ENABLED) - { - out_color = tonemap(out_color); - } + // the haze is blurred by the post-processing (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): the + // picture of this frame can't be read here, and one of the last frame laid over it only shows a milky ghost of the scene + float blurAmt = clamp(hazeWeight * blur_amount, 0.0, 1.0); - if (MOTIONBLUR_ENABLED) - { - out_motion = vec4(0.0); - } + // the drops: the view bent (the picture shift worked out above), and the lights near them. with the motion vectors the + // post-processing bends the picture of this frame (postfx_taa.frag / postfx_motionblur.frag, rain_windscreen_haze.glsl): it has + // the depth of the cab and never pulls the dashboard or the roof into a drop. the image of the last frame is only the fallback + float refrA = smoothstep(0.05, 0.35, coverA) * glassClear * step(glassA, 0.5); + if ((false == MOTIONBLUR_ENABLED) && (refrA > 0.001)) + { + vec2 shiftPx = -lensBend * WS_REFR_MAXPX; // where the drop looks, screen pixels + vec3 dir = normalize(wsView + shiftPx.x * wsDvx + shiftPx.y * wsDvy); + // a drop shows a minified picture: read it from a coarser level (no grain); tiny drops a little blurrier still + float lod = clamp(log2(1.0 + lensK * drop_lens_mix) - 0.5, 0.0, 3.0) + + clamp(2.5 - log2(max(lensRadPx, 1.0)), 0.0, 1.5); + float share; + vec3 seen = wsBehind(dir, lod, background, share, true); + if (image && (WS_LIGHT_GAIN > 0.0)) + seen += wsLightGlow(wsView, background); + // without the image the surroundings stand in: only faintly, they aren't the scene behind + bent = vec4(seen, refrA * WS_REFR_MIX * (image ? 1.0 : 0.3)); + } + + // the drop shading over it + float shadeA = coverA * drop_shade_alpha; + float outA = alphaOut + shadeA * (1.0 - alphaOut); + vec4 drops = vec4(dropLayer, outA); + drops.rgb += dropGlint * coverA / max(outA, 0.05); // the blend multiplies by alpha once more + out_color = wsOver(drops, under); + + { // windshield texture over the rain + vec3 fragcolor = ambient; + // where the glass texture is clear, its lighting is multiplied by ~0 below: skip apply_lights there + if (glassA > 0.002) + { + vec3 fragnormal = normalize(f_normal); + float reflectivity = param[1].z; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5; + legacy_gloss(); + fragcolor = apply_lights(fragcolor, fragnormal, tex_color.rgb, reflectivity, specularity, shadow_tone); + } + vec4 color = vec4(fragcolor, glassA); + out_color.xyz = apply_fog(mix(out_color.xyz, color.xyz, color.a)); + out_color.a = mix(out_color.a, 1., color.a); + } + // the picture in the drops goes over the drop shading and the glass, as the old postfx replaced the pixel with it: the dark + // middle of the atlas only shows through faintly, the rim and the glints a little more + out_color = wsOver(bent, out_color); + if (!POSTFX_ENABLED) + out_color = tonemap(out_color); + + // the velocity target: on the drops the picture shift (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), on the hazy glass the request + // for the haze (x = WS_ENC * strength, y = 0); elsewhere the velocity of the scene behind the glass stays as it is (alpha 0) + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + bool drop = (coverA > 0.05 || alphaOut > 0.05) && (glassA < 0.5); + float blurMask = blurAmt * glassClear; + if (drop) + { + vec2 bend = lensBend * smoothstep(0.05, 0.35, coverA); + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + out_motion = req; + } +} + +float GetMixFactor(in vec2 co, out float side) { + vec4 movePhase = wiper_pos; + bvec4 is_out = lessThanEqual(movePhase, vec4(1.)); + movePhase = mix(vec4(2.) - movePhase, movePhase, is_out); + + vec4 mask = textureLod(wipermask, co, 0.0); // called from non-uniform flow: no implicit derivatives + + vec4 areaMask = step(.001, mask); + + vec4 maskVal = mix(1. - mask, mask, is_out); + vec4 wipeWidth = smoothstep(1., .9, movePhase) * .25; + vec4 cleaned = smoothstep(movePhase - wipeWidth, movePhase, maskVal) * areaMask; + vec4 side_v = step(maskVal, movePhase); + cleaned *= side_v; + side_v = mix(side_v, vec4(1.) - side_v, is_out); + + // "regeneration", raindrops gradually returning after wiper pass: + // the share of the drops back: the glass fills with the rain fallen since the blade (rain_state), up to as wet as the glass is + // where no blade goes (the drops of a cell are there only up to that share, so the share of those back is the fill over it) + vec4 at = wsWipePass(mask); + vec4 fallen = vec4(rain_state.x) - at; + vec4 known = step(vec4(0.), at); + vec4 filled = mix(vec4(1.), vec4(1.) - exp(-max(fallen, vec4(0.)) * rain_state.z), known); + vec4 regenPhase = clamp(filled / max(rain_state.y, 1e-4), vec4(0.), vec4(1.)); + + side_v = mix(vec4(0.), vec4(1.) - side_v, areaMask); + + vec4 factor_v = mix(vec4(1.), regenPhase * (vec4(1.) - cleaned), areaMask); + + side = 0.; + float out_factor = 1.; + bool have_side = false; + // out_factor: the blade that clears the cell the most wins. side: which wiper stroke the drops of this + // cell belong to (part of their random seed, so it must not depend on out_factor). + for (int i = 0; i < 4; ++i) + { + out_factor = min(out_factor, factor_v[i]); + if (!have_side && areaMask[i] > 0.) + { + side = side_v[i]; + have_side = true; + } + } + return out_factor; } diff --git a/shaders/vk14/mat_snow_windscreen.frag b/shaders/vk14/mat_snow_windscreen.frag new file mode 100644 index 000000000..43f0c455f --- /dev/null +++ b/shaders/vk14/mat_snow_windscreen.frag @@ -0,0 +1,201 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +#include "common.glsl" +// Windscreen snow: replaces rain_windscreen when it snows - v3 (OpenGL 4.6 / Vulkan 1.4) +// +// MaSzyna switches the weather itself (simulationenvironment.cpp): with Overcast > 1 it SNOWS at 1 deg C and below, and the .mat +// block "snow:" is picked. +// +// What lies on the glass comes from the simulation (water_snow.comp, water.glsl): the map of the glass keeps the snow, the water, +// how packed the snow is and the shape of its flakes from frame to frame. The flakes land and stay where they landed, pile up, +// the blades wipe it as they wipe the rain (a wet trace stays), it melts at the warm glass, slush slides down. The renderer gives +// the glass its map through the param snow_slot (1 + its slot); a glass without a map has no snow. +// +// The look is only sprites from the atlas, as the drops of rain_windscreen and the splats of bugs_windscreen, laid at each pixel +// sharp from the atlas (snow_sprites.glsl). water_snowlayer.comp lists, for each texel of a layer of the glass (~1 mm), the +// sprites coming within it when the snow under them changes, so the glass lays only those instead of looking through every cell: +// - the lumps, in nine grids of ~1.6 cm cells shifted against each other: each cell has its lump fixed once (tile, place, +// size, the snow it takes); it comes when the snow around reaches that and stays as it is until the snow goes. The grids come +// one after the other as the snow piles up (mostly icy fleece, more and bigger; now and then a lump of packed or wet snow), +// each on the ones before, so the snow accumulates rather than changes, and covers the glass by 2-3 mm, small gaps left (the +// scene behind them blurred). In a heap they come sooner +// - dots and small puffs of dry snow between them, and drops where a flake has melted (they bend the picture behind, as rain does) +// A thin flake lets the light through (ice crystals): the picture behind it is blurred, not hidden. +// +// Atlas / normalmap (snieg_atlas_maszyna.py), 4 x 4 tiles of 512 x 512 (2048 x 2048): +// 0 a dot 1 dots 2, 3 small puffs 4, 5 puffs 6, 7 crumbs +// 8, 9 wet lumps 10, 11 clumps 12, 13 packed snow 14 slush 15 drop +// An older 2 x 2 atlas (1024 x 1024: fluffy flake, wet lump, crumbs, melted spot) still works, its tiles stand in for these. +// +// .mat: +// +// snow: { +// shader: snow_windscreen +// texture_raindropsatlas: textures/fx/snow-atlas +// texture_normalmap: textures/fx/snow_normalmap +// } + +layout(location = 0) in vec3 f_normal; +layout(location = 2) in vec2 f_coord; +layout(location = 3) in vec4 f_pos; +layout(location = 4) in vec4 f_clip_pos; +layout(location = 5) in vec4 f_clip_future_pos; + +layout(location = 0) out vec4 out_color; +#ifdef NO_MOTION_OUTPUT +// a pass without the velocity target: the writes go nowhere +vec4 out_motion; +#else +layout(location = 1) out vec4 out_motion; +#endif + +#pragma texture(diffuse, 0, sRGB_A) +#pragma texture(raindropsatlas, 1, sRGB_A) +#pragma texture(wipermask, 2, sRGB_A) // the renderer bakes it into the map of the glass (the blades); not read here +#pragma texture(normalmap, 3, RGBA) // rg = normal xy, b = height, a = mask; the layout of raindropsatlas (linear) +#pragma param(color, 0, 0, 4, diffuse) +#pragma param(diffuse, 1, 0, 1, diffuse) +#pragma param(specular, 1, 1, 1, specular) +#pragma param(reflection, 1, 2, 1, zero) +#pragma param(glossiness, 1, 3, 1, glossiness) +#pragma param(raindrop_grid_size, 2, 0, 1, one) // not used any more (the map of the glass sets the size of the flakes) +// snow_slot: 1 + the slot of the glass in the simulation of the snow (the renderer sets it), 0: none +#pragma param(snow_slot, 2, 2, 1, zero) + +#include "light_common.glsl" +#include "apply_fog.glsl" +#include "tonemapping.glsl" +#include "random.glsl" +#include "water.glsl" + +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 0) uniform sampler2D diffuse; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D raindropsatlas; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D wipermask; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D normalmap; + +#include "snow_sprites.glsl" + +void main() +{ + // Derivatives first, in uniform control flow (no discard before them). + vec3 Ngl = normalize(f_normal); + vec3 dp1 = dFdx(f_pos.xyz); + vec3 dp2 = dFdy(f_pos.xyz); + vec2 duv1 = dFdx(f_coord); + vec2 duv2 = dFdy(f_coord); + vec3 dp2perp = cross(dp2, Ngl); + vec3 dp1perp = cross(Ngl, dp1); + vec3 Tgl = dp2perp * duv1.x + dp1perp * duv2.x; + vec3 Bgl = dp2perp * duv1.y + dp1perp * duv2.y; + float invmax = inversesqrt(max(max(dot(Tgl, Tgl), dot(Bgl, Bgl)), 1e-20)); + Tgl *= invmax; + Bgl *= invmax; + + vec4 tex_color = texture(diffuse, f_coord); // no discard: clean glass between faint dirt must still get snow and blur + // the snow laid together from the sprites (listed by water_snowlayer.comp, a band of its rows every step and wherever a blade + // goes) + vec3 snowRGB = vec3(0.0); + float snowA = 0.0; + vec3 snowN = vec3(0.0); + float snowTr = 0.0; + float wet = 0.0; + snSlot = int(param[2].z + 0.5) - 1; + if ((snSlot >= 0) && (snSlot < WATER_SLOTS) && water_snow_map(uint(snSlot), snMap)) + { + // the sprites coming within the texel of the layer at the pixel (water_snowlayer.comp) laid at the pixel, sharp from the + // atlas; a second glass of the snow in the cab (the layer goes to the first one) looks through all the cells around the + // pixel, as it was before the layer, slower but the same + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + float pixelUV = max(length(duv1), length(duv2)); + snow_layer_s laid; + uvec4 refs; + vec2 centreUV; + vec2 span; + if (water_layer_refs(uint(snSlot), f_coord, refs, centreUV)) + { + snSpan(uint(snSlot), centreUV, span); + laid = snComposeRefs(f_coord, centreUV, span, pixelUV, refs); + } + else + { + snSpan(uint(snSlot), f_coord, span); + laid = snCompose(f_coord, span, pixelUV); + } + vec4 layerColour = vec4(laid.rgb, laid.a); + vec4 layerNormal = vec4(laid.n, laid.tr); + vec4 layerBend = vec4(laid.bend, laid.bendA, laid.haze); + snowRGB = layerColour.rgb; + snowA = layerColour.a; + snowN = layerNormal.xyz; + snowTr = layerNormal.w; + snBend = layerBend.xy; + snBendA = layerBend.z; + vec4 q = water_snow_at(uint(snSlot), snMap, f_coord); + wet = smoothstep(0.05, 0.3, q.y) * (1.0 - smoothstep(0.5, 2.0, q.x)); + // the picture behind thin flakes and a wet film is blurred + snHaze = max(layerBend.w, wet * snow_wet_blur); + snHaze = max(snHaze, smoothstep(snow_blur_mm.x, snow_blur_mm.y, q.x)); + } + + float glassA = tex_color.a * alpha_mult; + float finalA = snowA + glassA * (1.0 - snowA); + vec3 premult = snowRGB + tex_color.rgb * glassA * (1.0 - snowA); + vec3 albedo = premult / max(finalA, 1e-4); + float glassShare = glassA * (1.0 - snowA) / max(finalA, 1e-4); + + // relief: tilt the glass normal by the normals of the sprites (flat where there are none) + vec3 nDir = snowN + vec3(0.0, 0.0, 1.0) * (1.0 - snowA); + vec3 fragnormal = Ngl; + if (snowA > 0.001) + fragnormal = normalize(Ngl * max(nDir.z, 0.05) + Tgl * nDir.x + Bgl * nDir.y); + + vec3 fragcolor = ambient; + float reflectivity = param[1].z * glassShare; + float specularity = (tex_color.r + tex_color.g + tex_color.b) * 0.5 * glassShare + snow_gloss * snowA; + legacy_gloss(); + + // most of the glass is clear: the lighting of the 4.6 renderers is skipped there, it would be multiplied by an alpha of ~0 + if (finalA > 0.002) + fragcolor = apply_lights(fragcolor, fragnormal, albedo, reflectivity, specularity, shadow_tone); + + // thin snow glows when you look towards the sun / a lamp + if ((finalA > 0.002) && (snowA > 0.001) && (snow_translucency > 0.0) && (lights_count > 0U)) + { + vec3 I = normalize(f_pos.xyz); + float shadowSun = 0.0; + if (shadow_tone < 1.0) + shadowSun = (1.0 - shadow_tone) * clamp(calc_shadow(), 0.0, 1.0); + float towards = max(dot(I, normalize(-lights[0].dir)), 0.0); + float glow = pow(towards, 3.0) * (1.0 - shadowSun); + fragcolor += lights[0].color * lights[0].intensity * glow * snow_translucency * (snowTr / max(snowA, 1e-3)) * albedo * snowA; + } + vec3 lit = apply_fog(fragcolor); + vec4 color = vec4(lit, finalA); // straight, as rain_windscreen of the 4.6 renderers writes the glass + + out_color = POSTFX_ENABLED ? color : tonemap(color); + + // the scene seen through the snow, drawn by the post-processing (rain_windscreen_haze.glsl), asked for in the velocity target as + // rain_windscreen asks: the drops bend it (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend), thin snow and a wet film blur it + // (x = WS_ENC * strength, y = 0); the snow itself stays sharp. alpha 0 elsewhere: the blending keeps the motion of the scene behind + if (MOTIONBLUR_ENABLED) + { + vec4 req = vec4(0.0); + float clear = 1.0 - smoothstep(0.5, 0.95, glassA); + if ((snBendA > 0.1) && (glassA < 0.5)) + { + // the post-processing puts the picture from the bent place in place of this pixel, snow and all (85% of it): through + // snow it hides, the snow itself would be replaced by the picture from a place up to 96 px away, a gap of the snow + // there showing here, so an opaque cover would never close. bent only as much as the snow lets the light through + float through = 1.0 - smoothstep(0.6, 0.98, snowA); + vec2 bend = clamp(-snBend / max(snBendA, 1e-3) * snow_drop_bend, vec2(-1.0), vec2(1.0)) * smoothstep(0.1, 0.4, snBendA) * through; + req = vec4(WS_DROP_BIAS + WS_BEND_ENC * bend.x, WS_DROP_BIAS + WS_BEND_ENC * bend.y, 0.0, 1.0); + } + else + { + float blurMask = clamp(snHaze * snow_haze * (1.0 - smoothstep(0.3, 0.8, snowA)) * clear, 0.0, 1.0); + if (blurMask >= 0.01) + req = vec4(WS_ENC * blurMask, 0.0, 0.0, 1.0); + } + out_motion = req; + } +} diff --git a/shaders/vk14/mat_vat.frag b/shaders/vk14/mat_vat.frag new file mode 100644 index 000000000..2ce2b3690 --- /dev/null +++ b/shaders/vk14/mat_vat.frag @@ -0,0 +1,9 @@ +#version 460 core +#define STAGE_FRAGMENT 1 +// animals and people animated by textures (mat_vat.vert moves the vertices): drawn as mat_default. the textures and the param of +// the animation are declared here too, as in the vertex shader +#pragma texture(vatpos_hi, 1, RGBA) +#pragma texture(vatpos_lo, 2, RGBA) +#pragma texture(vatnormal, 3, RGBA) +#pragma param(vat_speed, 2, 0, 1, one) +#include "mat_default.glsl" diff --git a/shaders/vk14/mat_vat.vert b/shaders/vk14/mat_vat.vert new file mode 100644 index 000000000..e3e2fd662 --- /dev/null +++ b/shaders/vk14/mat_vat.vert @@ -0,0 +1,210 @@ +#version 460 core +#define STAGE_VERTEX 1 +#include "common.glsl" +// an animation baked into textures (vertex animation texture, VAT): people walking, standing, waiting. the vertices are moved +// here by the frames of the animation the textures hold, the material is drawn by mat_vat.frag (as mat_default). made by +// vat_bake.py from an animated mesh in blender; the model (t3d) carries in the userdata of every vertex (x) its column of the +// textures. the same shader draws the sun shadows (MATERIAL_SHADOW) and the multi draws (MODEL_DRAWS) of vulkan14_renderer: +// the vulkan version of shaders/ogl46/mat_vat.vert, with the bindings of the material set +// +// the textures (linear, never compressed or downscaled: at most gfx maxtexturesize, 2048 by default): +// vatpos_hi, vatpos_lo: the position of a vertex in a frame, 16 bits per axis over the box of the animation (rgb: the high and +// the low bytes), the normal in vatnormal (rgb, 0.5 + 0.5 n) +// the frames lie one under another, each in RowsPerFrame rows of Width vertices; the first row of vatpos_hi holds the header, +// the last one the same header with another mark (so the shader sees whether the image came upside down): +// pixel 0: 'V' 'A' 'T' 1 in the first row, 'V' 'A' 'T' 2 in the last +// pixel 1: min x, min y (16 bits each: hi, lo; millimetres + 32768) pixel 2: min z, size x (size: millimetres) +// pixel 3: size y, size z pixel 4: vertices, frames +// pixel 5: rows per frame, frames a second x 100 +// pixel 6: clips (0 or 1: one animation); with more the frames are that many animations of equal length one after another, +// and every one of the models plays one of them, picked as its moment is; then flags: 1 the frames packed one +// right after another (vertex Frame * Vertices + Vertex of the whole image, row by row), else each in its own rows +// the textures go with the trait r (texture_vatpos_hi: name:r), which keeps them as they are (never scaled down nor compressed) +// param vat_speed (1 if not given): how fast the animation plays +// param vat_random (1 if not given): 1 every model its own moment from its place; 0 the moment of the clock alone, for a model the game +// moves (its place changes the whole time, the moment taken from it would jump); -1 the game picks the clip and the moment, by the +// fraction of ten times the turn of the model about the vertical in degrees: (clip + 0.25 + 0.5 * moment) / clips (world/deer.cpp) +layout(location = 0) in vec3 v_vert; +layout(location = 1) in vec3 v_normal; +layout(location = 2) in vec2 v_coord; +layout(location = 3) in vec4 v_tangent; +layout(location = 4) in vec4 v_userdata; + +#pragma texture(vatpos_hi, 1, RGBA) +#pragma texture(vatpos_lo, 2, RGBA) +#pragma texture(vatnormal, 3, RGBA) +#pragma param(vat_speed, 2, 0, 1, one) +#pragma param(vat_random, 2, 1, 1, one) +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 1) uniform sampler2D vatpos_hi; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 2) uniform sampler2D vatpos_lo; +layout(set = MATERIAL_SET, binding = MATERIAL_TEXTURE_FIRST + 3) uniform sampler2D vatnormal; + +#ifdef MATERIAL_SHADOW +layout(location = 2) out vec2 f_coord; +#else +invariant gl_Position; + +layout(location = 0) out vec3 f_normal; +layout(location = 1) flat out vec3 f_normal_raw; +layout(location = 2) out vec2 f_coord; +layout(location = 3) out vec4 f_pos; +layout(location = 8) out mat3 f_tbn; + +layout(location = 4) out vec4 f_clip_pos; +layout(location = 5) out vec4 f_clip_future_pos; + +layout(location = 6) out vec3 TangentFragPos; +layout(location = 7) out vec4 UserData; +#endif + +// the header: Flipped when the image came upside down +struct vat_header +{ + bool valid; + bool flipped; + int height; + vec3 lower; + vec3 size; + int vertices; + int frames; + int rows; + float fps; + int clips; + bool dense; +}; + +ivec4 vat_bytes(ivec2 texel) +{ + return ivec4(round(texelFetch(vatpos_hi, texel, 0) * 255.0)); +} + +vat_header vat_read_header() +{ + vat_header h; + ivec2 size = textureSize(vatpos_hi, 0); + h.height = size.y; + ivec4 mark = vat_bytes(ivec2(0, 0)); + h.valid = (mark.x == 86) && (mark.y == 65) && (mark.z == 84) && ((mark.w == 1) || (mark.w == 2)); + h.flipped = (mark.w == 2); + int row = 0; + ivec4 p1 = vat_bytes(ivec2(1, row)); + ivec4 p2 = vat_bytes(ivec2(2, row)); + ivec4 p3 = vat_bytes(ivec2(3, row)); + ivec4 p4 = vat_bytes(ivec2(4, row)); + ivec4 p5 = vat_bytes(ivec2(5, row)); + ivec4 p6 = vat_bytes(ivec2(6, row)); + h.lower = (vec3(p1.x * 256 + p1.y, p1.z * 256 + p1.w, p2.x * 256 + p2.y) - 32768.0) * 0.001; + h.size = vec3(p2.z * 256 + p2.w, p3.x * 256 + p3.y, p3.z * 256 + p3.w) * 0.001; + h.vertices = p4.x * 256 + p4.y; + h.frames = max(p4.z * 256 + p4.w, 1); + h.rows = max(p5.x * 256 + p5.y, 1); + h.fps = float(p5.z * 256 + p5.w) * 0.01; + h.clips = clamp(p6.x * 256 + p6.y, 1, h.frames); + h.dense = (p6.z & 1) != 0; + return h; +} + +// the texel of vertex Vertex in frame Frame +ivec2 vat_texel(vat_header h, int vertex, int frame, int width) +{ + int ix = h.dense ? frame * h.vertices + vertex : frame * h.rows * width + vertex; + int row = 1 + ix / width; + if (h.flipped) + row = h.height - 1 - row; + return ivec2(ix % width, row); +} + +vec3 vat_position(vat_header h, ivec2 texel) +{ + vec3 high = round(texelFetch(vatpos_hi, texel, 0).rgb * 255.0); + vec3 low = round(texelFetch(vatpos_lo, texel, 0).rgb * 255.0); + return h.lower + h.size * ((high * 256.0 + low) / 65535.0); +} + +vec3 vat_normal(ivec2 texel) +{ + return texelFetch(vatnormal, texel, 0).rgb * 2.0 - 1.0; +} + +// the place and the normal of the vertex now (the rest pose of the model where the textures don't fit it) +void vat_animate(mat4 mv, out vec3 position, out vec3 normal) +{ + position = v_vert; + normal = v_normal; + vat_header h = vat_read_header(); + int vertex = int(v_userdata.x + 0.5); + if ((false == h.valid) || (vertex < 0) || (vertex >= h.vertices)) + return; + int width = textureSize(vatpos_hi, 0).x; + // every one of the models a moment (and a clip) of its own: from its place in the world, whole metres, and its turn about the + // vertical, whole 2 degrees. the place is the one of the camera of the pass (camera_hi exact, camera_lo the rest) and the model + // relative to it (mv, turned back to the world with inv_view), so it's the same in every pass and with every move of the camera; + // the edges of the cells and of the bins away from the round values models are set at + mat3 world = mat3(inv_view) * mat3(mv); + vec3 rel = camera_lo.xyz + mat3(inv_view) * mv[3].xyz; + ivec3 cell = ivec3(camera_hi.xyz) + ivec3(floor(rel + 0.37)); + float yaw = degrees(atan(world[0].z, world[0].x)); + int bin = int(mod(floor(yaw * 0.5 + 0.315), 180.0)); + uint seed = uint(cell.x) * 73856093u ^ uint(cell.y) * 19349663u ^ uint(cell.z) * 83492791u ^ uint(bin) * 2654435761u; + seed ^= seed >> 16; seed *= 0x7feb352du; seed ^= seed >> 15; seed *= 0x846ca68bu; seed ^= seed >> 16; + float random = clamp(param[2].y, 0.0, 1.0); + float phase = random * float(seed & 0xffffu) / 65536.0; + float pick = random * float(seed >> 16) / 65536.0; + if (param[2].y < -0.5) + { + // picked by the game: the fraction of the turn in tenths of a degree (the turn is -yaw), a quarter of a clip's span kept + // clear of its edges + float spin = fract(-yaw * 10.0) * float(h.clips); + float slot = floor(spin); + pick = (slot + 0.5) / float(h.clips); + phase = clamp((spin - slot - 0.25) * 2.0, 0.0, 1.0); + } + int clipframes = max(h.frames / h.clips, 1); + int clip = min(int(pick * float(h.clips)), h.clips - 1); + float t = (time * h.fps * max(param[2].x, 0.0)) + phase * float(clipframes); + float f = mod(t, float(clipframes)); + int f0 = clip * clipframes + int(floor(f)) % clipframes; + int f1 = clip * clipframes + (int(floor(f)) + 1) % clipframes; + float a = fract(f); + ivec2 t0 = vat_texel(h, vertex, f0, width); + ivec2 t1 = vat_texel(h, vertex, f1, width); + position = mix(vat_position(h, t0), vat_position(h, t1), a); + vec3 n = mix(vat_normal(t0), vat_normal(t1), a); + normal = (dot(n, n) > 1e-6) ? normalize(n) : v_normal; +} + +void main() +{ + mat4 mv = effective_modelview(); + vec3 position; + vec3 normal; + vat_animate(mv, position, normal); +#ifdef MATERIAL_SHADOW + gl_Position = (projection * mv) * vec4(position, 1.0); + f_coord = v_coord; +#else + mat3 mvn = effective_modelviewnormal(); + + f_normal = normalize(mvn * normal); + f_normal_raw = normal; + f_coord = v_coord; + f_pos = mv * vec4(position, 1.0); + f_clip_pos = projection * f_pos; + f_clip_future_pos = (projection * future) * f_pos; + + gl_Position = f_clip_pos; + gl_PointSize = param[1].x; + + vec3 N = f_normal; + vec3 T = mvn * v_tangent.xyz; + T = normalize(T - N * dot(N, T)); + vec3 B = cross(N, T) * (v_tangent.w < 0.0 ? -1.0 : 1.0); + f_tbn = mat3(T, B, N); + TangentFragPos = transpose(f_tbn) * f_pos.xyz; + UserData = v_userdata; +#endif +#ifdef MODEL_DRAWS + // which block of the multi draw the fragments read (common.glsl) + f_model_draw = MODEL_DRAW; +#endif +} diff --git a/shaders/vk14/postfx_dlss_motion.frag b/shaders/vk14/postfx_dlss_motion.frag index dcb91e498..e94ed8d20 100644 --- a/shaders/vk14/postfx_dlss_motion.frag +++ b/shaders/vk14/postfx_dlss_motion.frag @@ -20,6 +20,12 @@ void main() ivec2 pixel = ivec2(gl_FragCoord.xy); vec2 velocity = texelFetch(velocity_tex, pixel, 0).xy; float depth = texelFetch(depth_tex, pixel, 0).r; + // the windscreens (mat_rain_windscreen, mat_bugs_windscreen) send the post-processing their drops and haze as large values + // (real motion is far below a quarter of the screen per frame): no motion for dlss there, the glass goes with the camera + if (any(greaterThan(abs(velocity), vec2(0.25)))) + { + velocity = vec2(0.0); + } if (depth <= 0.0) { vec4 world = mat4(param[2], param[3], param[4], param[5]) * vec4(f_coords * 2.0 - 1.0, depth, 1.0); diff --git a/shaders/vk14/postfx_motionblur.frag b/shaders/vk14/postfx_motionblur.frag index 12d788008..2677cc6c6 100644 --- a/shaders/vk14/postfx_motionblur.frag +++ b/shaders/vk14/postfx_motionblur.frag @@ -16,12 +16,35 @@ layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 1) uniform sampler2D veloc layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 2) uniform sampler2D depth_tex; +#include "rain_windscreen_haze.glsl" + void main() { + // the wet windscreen (mat_rain_windscreen.frag): its drops and haze done here without the taa, left as they are when the taa + // did them (marked in the alpha) + vec2 rawv = texture(velocity_tex, f_coords).xy; + if (wsIsDrop(rawv)) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb + : wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, rawv), 1.0); + return; + } + float blurAmt = wsBlur(rawv); + if (blurAmt > 0.0) + { + vec4 picture = texture(color_tex, f_coords); + out_color = vec4(wsWasHazed(picture.a) ? picture.rgb : wsHaze(color_tex, velocity_tex, f_coords, blurAmt), 1.0); + return; + } + float ori_depth = texture(depth_tex, f_coords).x; vec2 texelSize = 1.0 / vec2(textureSize(color_tex, 0)); - vec2 velocity = texture(velocity_tex, f_coords).xy * param[0].x; + vec2 velocity = rawv * param[0].x; + // edge pixels of the windscreen can carry a fraction of a request: never use that as motion + if (any(greaterThan(abs(rawv), vec2(WS_FLOOR * WS_ENC)))) + velocity = vec2(0.0); float speed = length(velocity / texelSize); int nSamples = clamp(int(speed), 1, 32); diff --git a/shaders/vk14/postfx_taa.frag b/shaders/vk14/postfx_taa.frag index dd48c0203..281c6b07b 100644 --- a/shaders/vk14/postfx_taa.frag +++ b/shaders/vk14/postfx_taa.frag @@ -23,4 +23,54 @@ layout(set = POST_SET, binding = POST_TEXTURE_FIRST + 3) uniform sampler2D histo #define TAA_HISTORY_VALID (param[0].x > 0.5) #define TAA_REPROJECTION mat4(param[2], param[3], param[4], param[5]) #define TAA_NEAR param[0].y +#include "rain_windscreen_haze.glsl" + +// the resolve of the taa under another name: main() below gives the wet windscreen (mat_rain_windscreen.frag) its haze and the +// picture in its drops first +#define main taa_resolve_main #include "taa_resolve.glsl" +#undef main + +// the drops and the haze are made from the frame alone (the history of the taa would smear them over the frames): drawn with the +// offsets of the taa they shimmer from frame to frame. they stay where they are on the screen, so the result of the last frame at +// the same pixel is blended in: fully while the view stands still, half while it moves, kept near this frame's result (no ghosts +// of a wiper or of drops gone) +const float WS_TEMPORAL_SHARE = 0.2; // the share of this frame while the view stands still +const float WS_TEMPORAL_MOVING = 0.5; // ... and while it moves +const float WS_TEMPORAL_RANGE = 0.12; // the last frame kept within this of this frame (colours squeezed into 0..1) + +vec3 wsStabilize(vec3 current, ivec2 pixel) +{ + if (false == TAA_HISTORY_VALID) + return current; + vec4 last = texelFetch(history_tex, pixel, 0); + if (any(isnan(last)) || (false == wsWasHazed(last.a))) // not a drop or haze pixel in the last frame + return current; + vec2 size = vec2(textureSize(color_tex, 0)); + float depth = texelFetch(depth_tex, pixel, 0).r; + vec4 world = TAA_REPROJECTION * vec4(f_coords * 2.0 - 1.0, depth, 1.0); + bool still = (world.w > 0.0) && (length((world.xy / world.w * 0.5 + 0.5 - f_coords) * size) < 0.5); + vec3 c = taa_compress(current); + vec3 h = clamp(taa_compress(taa_clean(last.rgb)), c - WS_TEMPORAL_RANGE, c + WS_TEMPORAL_RANGE); + return taa_decompress(clamp(mix(h, c, still ? WS_TEMPORAL_SHARE : WS_TEMPORAL_MOVING), vec3(0.0), vec3(1.0 - 1.0 / TAA_HALF_MAX))); +} + +void main() +{ + // the drops: the picture of this frame bent by them; the hazy glass: the picture of this frame blurred over it. both without + // the history (else they would smear on frame after frame), marked for the motion blur after + ivec2 pixel = ivec2(f_coords * vec2(textureSize(velocity_tex, 0))); + vec2 raw = texelFetch(velocity_tex, pixel, 0).xy; + if (wsIsDrop(raw)) + { + out_color = vec4(wsStabilize(taa_clean(wsDropRefraction(color_tex, velocity_tex, depth_tex, f_coords, raw)), pixel), WS_HAZED); + return; + } + float blurAmt = wsBlur(raw); + if (blurAmt > 0.0) + { + out_color = vec4(wsStabilize(taa_clean(wsHaze(color_tex, velocity_tex, f_coords, blurAmt)), pixel), WS_HAZED); + return; + } + taa_resolve_main(); +} diff --git a/shaders/vk14/rain_cells.comp b/shaders/vk14/rain_cells.comp new file mode 100644 index 000000000..9b6848a2b --- /dev/null +++ b/shaders/vk14/rain_cells.comp @@ -0,0 +1,194 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the cells of the glasses with rain (rain_cells.glsl): the drops and the rivulets of every cell worked out for the time of the +// frame, a thread a cell, before the passes which draw the glasses (mat_rain_windscreen.frag only reads them). two passes: the +// cells (rain_pass 0), then which drops reach the quarters of each drop cell (rain_pass 1, it reads the first) + +// none of the pass set: the cells pushed with the dispatch (set COMPUTE_SET), the time and the pass in the push constants +#define LAYOUT_UI 1 +#include "common.glsl" + +layout(push_constant) uniform kernel_constants +{ + float rain_time; // the time of the block of the scene (scene_ubs.time) + float rain_amount; // how wet the glass is (scene_ubs.rain_state.y, a little more) + int rain_pass; // 0 the cells, 1 the reach of the drops +}; + +#include "random.glsl" +#include "rain_cells.glsl" + +layout(local_size_x = RAIN_CELLS_GROUP_SIZE) in; + +uvec2 rain_key(ivec2 Cell) +{ + return uvec2(Cell + ivec2(65536)); +} + +// a random kept to 8 bits (rain_byte() takes it back) +uint q8(float Value) +{ + return min(uint(Value * 256.0), 255u); +} + +// a share 0 .. 1 kept to Steps + 1 levels, 0 and 1 exact +uint qn(float Value, float Steps) +{ + return uint(round(clamp(Value, 0.0, 1.0) * Steps)); +} + +// a drop cell: its life now, the activation, and the drop of either side of the blades (the sequence of the randoms is the +// one mat_rain_windscreen.frag had) +uvec4 drop_cell(ivec2 Cell) +{ + uvec2 key = rain_key(Cell); + uint s0 = Hash(uvec3(key, 23u)); + float lifeLen = mix(drop_life_min, drop_life_max, RandF(s0)); + float tt = rain_time / lifeLen + RandF(s0); + float epoch = floor(tt); + float ph = tt - epoch; + uint ep = uint(mod(epoch, 65521.0)); + uint s1 = Hash(uvec3(key, ep * 4u + 1u)); + float landing = RandF(s1); + bool missed = RandF(s1) < wiper_miss; + float appearF = drop_appear / lifeLen; + float fadeF = drop_fade / lifeLen; + float vis = smoothstep(0.0, appearF, ph) * (1.0 - smoothstep(1.0 - fadeF, 1.0, ph)); + float spread = smoothstep(0.0, 2.0 * appearF, ph); + uvec4 result; + for (uint side = 0u; side < 2u; ++side) + { + uint s2 = Hash(uvec3(key, ep * 4u + 2u + side * 2u)); + float thr = RandF(s2); + float cx = RandF(s2); + float cy = RandF(s2); + float size = RandF(s2); + float sag = RandF(s2); + float flip = RandF(s2); + float choice = RandF(s2); + float stretch = RandF(s2); + uint tile = min(uint(choice * 4.0), 3u); + uint a = q8(thr) | (q8(cx) << 8) | (q8(cy) << 16) | (q8(pow(size, drop_size_bias)) << 24); + uint b = q8(sag) | (q8(stretch) << 8) | ((flip < 0.5) ? (1u << 16) : 0u) | (tile << 17); + if (side == 0u) + { + b |= (qn(spread, 31.0) << 19) | (q8(landing) << 24); + result.x = a; + result.y = b; + } + else + { + b |= (missed ? (1u << 19) : 0u) | (qn(vis, 255.0) << 24); + result.z = a; + result.w = b; + } + } + return result; +} + +// a rivulet cell of layer Layer (0 gravity, 1 .. 4 the air), as getRiv of mat_rain_windscreen.frag drew it +uvec4 rivulet_cell(int Layer, ivec2 Cell) +{ + uint salt = 91u + 2u * uint(Layer); + uint sSeed = Hash(uvec3(rain_key(Cell), salt)); + float on = RandF(sSeed); + float sPeriod = ((Layer == 0) ? streak_period : wind_streak_period) * mix(0.6, 1.6, RandF(sSeed)); + float sPhase = fract(rain_time / sPeriod + RandF(sSeed)); + float life = smoothstep(0.0, 0.05, sPhase) * (1.0 - smoothstep(0.86, 1.0, sPhase)); + float wr = RandF(sSeed); + float span = RandF(sSeed); + float sSteps = floor(mix(3.0, 8.0, RandF(sSeed))); + float sXs = clamp(sPhase / 0.88, 0.0, 1.0) * sSteps; + float sRun = clamp((floor(sXs) + smoothstep(0.55, 1.0, fract(sXs))) / sSteps, 0.0, 1.0); + float top = RandF(sSeed); + float left = RandF(sSeed); + float flip = RandF(sSeed); + float col = RandF(sSeed); + float wipe = RandF(sSeed); + float wavK = RandF(sSeed); + float wavPh = RandF(sSeed); + float wavSp = RandF(sSeed); + uvec4 result; + result.x = min(uint(on * 65536.0), 65535u) | (qn(life, 255.0) << 16) | (q8(wipe) << 24); + result.y = qn(sRun, 65535.0) | (q8(wr) << 16) | (q8(span) << 24); + result.z = q8(top) | (q8(left) << 8) | (q8(wavK) << 16) | (q8(wavPh) << 24); + result.w = q8(wavSp) | ((flip < 0.5) ? (1u << 8) : 0u) | (min(uint(col * 4.0), 3u) << 9); + return result; +} + +// how far from the centre (in cells) the drop of side half A, B of a cell can reach at most: half its size, the sag, the stretch of the +// air at its strongest, any way it is turned +float drop_reach(uint A, uint B, float Spread) +{ + float half_size = 0.5 * mix(drop_size_min, drop_size_max, rain_byte(A, 24u)) * Spread; + float sag = 1.0 + drop_sag * rain_byte(B, 0u); + float stretch = 1.0 + drop_wind_stretch * rain_byte(B, 8u); + return half_size * sqrt(1.0 + sag * sag) * stretch * 1.01; +} + +// the reach of the drops around a drop cell into its quarters (rain_cells.glsl), from the cells worked out by the first pass +uvec4 drop_masks(ivec2 Cell) +{ + uvec4 result = uvec4(0u); + // as many drops as the glass is wet (rain_amount: the wetness of the glass, scene_ubs.rain_state.y) + float most = min(rain_amount * drop_density, 0.95); + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + { + uvec4 d = rain_cells[rain_drop_index(Cell + ivec2(dx, dy))]; + if ((rain_byte(d.y, 24u) > most) || ((d.w >> 24) == 0u)) + continue; + float spread = mix(0.8, 1.0, float((d.y >> 19) & 31u) * (1.0 / 31.0)); + bool missed = ((d.w >> 19) & 1u) != 0u; + uint bit = 1u << uint((dy + 1) * 3 + dx + 1); + for (uint side = 0u; side < 2u; ++side) + { + if ((side == 1u) && missed) + break; + uint a = (side == 0u) ? d.x : d.z; + uint b = (side == 0u) ? d.y : d.w; + vec2 centre = vec2(dx, dy) + vec2(rain_byte(a, 8u), rain_byte(a, 16u)); + float reach = drop_reach(a, b, spread); + for (uint q = 0u; q < 4u; ++q) + { + vec2 low = vec2(float(q & 1u), float(q >> 1)) * 0.5; + vec2 away = max(max(low - centre, centre - (low + 0.5)), vec2(0.0)); + if (dot(away, away) < reach * reach) + result[q] |= bit; + } + } + } + return result; +} + +void main() +{ + uint index = gl_GlobalInvocationID.x; + if (rain_pass == 1) + { + // the second pass: the reach of the drops, a thread a drop cell + if (index >= uint(RAIN_DROP_CELLS * RAIN_DROP_CELLS)) + return; + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[uint(RAIN_MASK_BASE) + index] = drop_masks(cell); + return; + } + if (index >= uint(RAIN_MASK_BASE)) + return; + if (index < uint(RAIN_RIV_BASE)) + { + ivec2 texel = ivec2(int(index % uint(RAIN_DROP_CELLS)), int(index / uint(RAIN_DROP_CELLS))); + // the last column and row stand for the cells -1 (the neighbours of the first ones) + ivec2 cell = ivec2(texel.x == RAIN_DROP_CELLS - 1 ? -1 : texel.x, texel.y == RAIN_DROP_CELLS - 1 ? -1 : texel.y); + rain_cells[index] = drop_cell(cell); + return; + } + uint rest = index - uint(RAIN_RIV_BASE); + int layer = int(rest / uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS)); + uint place = rest % uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS); + ivec2 texel = ivec2(int(place % uint(RAIN_RIV_CELLS)), int(place / uint(RAIN_RIV_CELLS))); + // the cells -32 .. 95: the upper quarter stands for the cells below 0 + ivec2 cell = ivec2(texel.x >= 96 ? texel.x - RAIN_RIV_CELLS : texel.x, texel.y >= 96 ? texel.y - RAIN_RIV_CELLS : texel.y); + rain_cells[index] = rivulet_cell(layer, cell); +} diff --git a/shaders/vk14/rain_cells.glsl b/shaders/vk14/rain_cells.glsl new file mode 100644 index 000000000..6a5a69945 --- /dev/null +++ b/shaders/vk14/rain_cells.glsl @@ -0,0 +1,82 @@ +// the cells of the glasses with rain (mat_rain_windscreen.frag): the drops of the grid of drops and the rivulets of the layers of +// rivulets, worked out once a frame for every cell by rain_cells.comp (a thread a cell) instead of in every pixel of a glass for +// its 9 neighbouring cells. a cell holds the random values of its drop or rivulet as they are now (the hashes of the cell and of +// its epoch, the life cycle at the time of the frame); the glass takes the sizes and the places from them with its own settings. +// so the glass looks the same as when it worked them out itself (the hashes are the same; the values are kept to 8 or 16 bits) +// +// a cell is one uvec4. the drops: RAIN_DROP_CELLS x RAIN_DROP_CELLS cells, cell c of the grid in element (c.y & 511) * 512 + +// (c.x & 511), whole for the cells -1 .. 510 (grids up to 510 cells; finer ones repeat their drops every 512 cells): +// x side 0 (the drop of a cell the blades went over on their way out): bits 0-7 the threshold the wipers have to be past for +// it, 8-15 / 16-23 the place in the cell (x, y), 24-31 its size (0 .. 1 from drop_size_min to drop_size_max) +// y side 0: bits 0-7 the random of its sag, 8-15 of its stretch by the air, 16 mirrored, 17-18 the tile of the atlas, +// 19-23 how far it spread out landing (0 .. 31), 24-31 the random a cell holds a drop by (a drop when below the share) +// z side 1 (the blades on their way back): as x +// w side 1: as y, bit 19 set when the blades miss the drop, bits 24-31 its visibility in its life (0 .. 255) +// the reach of the drops: for every drop cell (element RAIN_MASK_BASE + the index of the drop cell) the drops of the 9 cells around +// it (bit (dy + 1) * 3 + dx + 1) which reach into each quarter of it (x the lower left, y the lower right, z the upper left, w the +// upper right), with the drops the cells hold now in the rain there is now (a glass only looks at those) +// the rivulets: RAIN_RIV_LAYERS layers (0 gravity, 1 .. 4 the air) of RAIN_RIV_CELLS x RAIN_RIV_CELLS cells, cell c in element +// RAIN_RIV_BASE + layer * 128 * 128 + (c.y & 127) * 128 + (c.x & 127), whole for the cells -32 .. 95: +// x bits 0-15 the random the cell holds a rivulet by, 16-23 its life (0 .. 255), 24-31 the random of the wipers it stays under +// y bits 0-15 how far down its run the head is (0 .. 65535), 16-23 the random of its width, 24-31 of its span +// z the randoms of its top, its left edge, the length and the phase of its waves (a byte each) +// w bits 0-7 the random of the speed of its waves, 8 mirrored, 9-10 the sprite of the atlas + +#ifndef RAIN_CELLS_GLSL +#define RAIN_CELLS_GLSL + +#define RAIN_DROP_CELLS 512 +#define RAIN_RIV_CELLS 128 +#define RAIN_RIV_LAYERS 5 +#define RAIN_RIV_BASE (RAIN_DROP_CELLS * RAIN_DROP_CELLS) +#define RAIN_MASK_BASE (RAIN_RIV_BASE + RAIN_RIV_LAYERS * RAIN_RIV_CELLS * RAIN_RIV_CELLS) +#define RAIN_CELLS_COUNT (RAIN_MASK_BASE + RAIN_DROP_CELLS * RAIN_DROP_CELLS) +#define RAIN_CELLS_GROUP_SIZE 64 + +#if defined(STAGE_COMPUTE) +layout(std430, set = COMPUTE_SET, binding = 0) buffer rain_cells_ssbo +#else +layout(std430, set = PASS_SET, binding = RAIN_CELLS_SSBO) readonly buffer rain_cells_ssbo +#endif +{ + uvec4 rain_cells[]; +}; + +// the drops and the rivulets (the settings of mat_rain_windscreen.frag which the cells are worked out with) +const float drop_density = 0.6; // share of grid cells holding a drop at full rain (scaled by rain intensity) +const float drop_size_min = 0.45; // drop size in grid cells +const float drop_size_max = 1.15; +const float drop_size_bias = 1.8; // >1 = more small/medium drops, fewer big ones +const float drop_sag = 0.12; // max vertical stretch of a resting drop (gravity) +const float drop_wind_stretch = 0.4; // drops are stretched up to this much along the push of the air (0 = off) +const float drop_life_min = 14.0; // seconds a drop sits on the glass +const float drop_life_max = 45.0; +const float drop_appear = 0.18; // seconds of the landing "pop" +const float drop_fade = 1.5; // seconds a drop takes to vanish at the end of its life +const float wiper_miss = 0.005; // share of the drops a blade goes over without taking them (a tenth of the 0.05 it was) +const float streak_period = 40.0; // seconds a rivulet lives (it runs for ~90% of that and then fades out), average +const float wind_streak_period = 18.0; // seconds a rivulet driven by the air lives (they run faster than the ones of gravity) + +// a random kept to 8 bits, back to 0 .. 1 (the middle of its step) +float rain_byte(uint Value, uint Shift) +{ + return (float((Value >> Shift) & 255u) + 0.5) * (1.0 / 256.0); +} + +uint rain_drop_index(ivec2 Cell) +{ + return uint(Cell.y & (RAIN_DROP_CELLS - 1)) * uint(RAIN_DROP_CELLS) + uint(Cell.x & (RAIN_DROP_CELLS - 1)); +} + +uint rain_mask_index(ivec2 Cell) +{ + return uint(RAIN_MASK_BASE) + rain_drop_index(Cell); +} + +uint rain_riv_index(int Layer, ivec2 Cell) +{ + return uint(RAIN_RIV_BASE) + uint(Layer) * uint(RAIN_RIV_CELLS * RAIN_RIV_CELLS) + uint(Cell.y & (RAIN_RIV_CELLS - 1)) * uint(RAIN_RIV_CELLS) + + uint(Cell.x & (RAIN_RIV_CELLS - 1)); +} + +#endif diff --git a/shaders/vk14/rain_windscreen_haze.glsl b/shaders/vk14/rain_windscreen_haze.glsl new file mode 100644 index 000000000..73be4b573 --- /dev/null +++ b/shaders/vk14/rain_windscreen_haze.glsl @@ -0,0 +1,270 @@ +// the haze of the wet windscreen (mat_rain_windscreen.frag), drawn by the post-processing: the glass asks for it in the velocity +// target (x = WS_ENC * strength, y = 0, see mat_rain_windscreen.frag), and the picture there is blurred over the hazy glass only. +// postfx_taa.frag does it with the temporal anti-aliasing (every frame, also standing still), postfx_motionblur.frag without it +// (it runs only while something moves). the picture blurred by the taa is marked in its alpha (WS_HAZED), so the motion blur +// after it leaves it as it is. +// +// real motion vectors are tiny (<< 0.25 per frame), so the large values can only come from the windscreen +#ifndef RAIN_WINDSCREEN_HAZE_GLSL +#define RAIN_WINDSCREEN_HAZE_GLSL + +const float WS_ENC = 64.0; // must match mat_rain_windscreen.frag +const float WS_FLOOR = 0.004; // = 0.256 in raw velocity units: everything below is real motion +const float WS_HAZED = -4.0; // alpha of the picture the taa already blurred: below anything a scene writes (additive + // particles took the alpha of the image above 1.5, and the motion blur then left the haze of a + // bug or of the glass out on some frames: a flicker). negative, so the lock of the taa takes 0 + +// whether the picture was blurred by the taa already (WS_HAZED in its alpha) +bool wsWasHazed(float alpha) +{ + return alpha < -3.0; +} + +// blur of hazy glass +const float WS_RADIUS = 0.014; // max blur radius, fraction of screen height +const int WS_TAPS = 16; +const float WS_HAZE_LIGHT_CAP = 12.0; // the most a light adds to the haze around it (brightness, scene units) + +// strength of the blur request, 0 for pixels that are not blur pixels +float wsBlur(vec2 raw) +{ + // a blended edge with something else: not a blur pixel. the haze is asked with y = 0; with msaa the samples of a pixel are + // averaged, and the edge of a drop (y half of a drop's) came out as a full haze request: a ring blurred around the drop which + // flickered as the edges moved over the samples + if (raw.x > 100.0 || raw.y > 1.0) + return 0.0; + float m = clamp(raw.x / WS_ENC, 0.0, 1.0); + return clamp((m - WS_FLOOR) / (1.0 - WS_FLOOR), 0.0, 1.0); +} + +// a colour of the picture made safe: a very bright light can be an infinity in the half float image (and a broken pixel a nan); +// in an average that gave nan for the whole result, which the taa turns black: black dotted blobs around the lights +vec3 wsSafe(vec3 c) +{ + return any(isnan(c)) ? vec3(0.0) : clamp(c, vec3(0.0), vec3(65000.0)); +} + +vec3 wsFetch(sampler2D tex, vec2 uv) +{ + return wsSafe(textureLod(tex, uv, 0.0).rgb); +} + +// the weight of a colour in an average that a single very bright pixel must not take over +float wsKaris(vec3 c) +{ + return 1.0 / (1.0 + dot(c, vec3(0.2126, 0.7152, 0.0722))); +} + +// the picture at Uv blurred over the hazy glass, for a request of BlurAmt (> 0) +vec3 wsHaze(sampler2D colortex, sampler2D velocitytex, vec2 uv, float blurAmt) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 sharp = wsFetch(colortex, uv); + + float radius = WS_RADIUS * blurAmt; + + // interleaved gradient noise rotates the disc per pixel -> no banding + float rot = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715)))); + + float wsum = wsKaris(sharp); + vec3 sum = sharp * wsum; + float psum_w = 1.0; // the plain average beside it + vec3 psum = sharp; + + for (int i = 0; i < WS_TAPS; ++i) + { + float r = sqrt((float(i) + 0.5) / float(WS_TAPS)); + float a = float(i) * 2.3999632 + rot; // golden angle + vec2 o = vec2(cos(a), sin(a)) * r * radius; + o.x *= aspect; + + vec2 tap = uv + o; + + // take only hazy-glass pixels (not the cab frame, not clear glass, not drops) + // weighed by 1 / (1 + brightness) (karis average): an ordinary picture blurs the same, but a very bright light + // (a lamp close by, headlights) is not smeared over the whole disc at full strength, which the bloom then turned + // into a large flat blob shaped like a clover + float w = step(0.01, wsBlur(textureLod(velocitytex, tap, 0.0).xy)); + vec3 c = wsFetch(colortex, tap); + psum += c * w; + psum_w += w; + w *= wsKaris(c); + sum += c * w; + wsum += w; + } + + // the karis average alone almost wipes small bright lights out of the haze (signals at night went faint): the light the + // plain average has above it comes back, up to WS_HAZE_LIGHT_CAP, so a light stays a soft glow of its colour and only a + // very bright one (a lamp close by) isn't smeared at full strength + vec3 blurred = sum / wsum; + vec3 extra = max(psum / psum_w - blurred, vec3(0.0)); + float extraL = dot(extra, vec3(0.2126, 0.7152, 0.0722)); + blurred += extra * min(1.0, WS_HAZE_LIGHT_CAP / max(extraL, 1e-4)); + return mix(sharp, blurred, min(blurAmt * 4.0, 1.0)); +} + +// --------------------------------------------------------------------------------------------------------------------------- +// refraction in the drops: the glass sends the picture shift of the drop (x, y = WS_DROP_BIAS + WS_BEND_ENC * bend, bend -1..1 +// = WS_REFR_MAXPX pixels), and the picture of this frame is bent here. the depth of the whole frame (with the cab) is known here, +// so the dashboard, the frame and the roof of the cab are never pulled into a drop (the image of the last frame used by the +// glass shader can't tell them apart: white drops at night at the edges and under the wipers) +// --------------------------------------------------------------------------------------------------------------------------- +const float WS_BEND_ENC = 60.0; // must match mat_rain_windscreen.frag +const float WS_DROP_BIAS = 192.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MAXPX = 96.0; // must match mat_rain_windscreen.frag +const float WS_REFR_MIX = 0.85; // 0 = no refraction, 1 = only the refracted picture +const float WS_LENS_AA = 0.75; // above this spread of the picture between neighbouring pixels, a 4x4 footprint is averaged + +// the lights in the drops: a drop is a wide-angle lens and lights up near a bright light (signals, lamps, headlights). taken from +// the mipmaps of the image the screen reflections keep (ssr_history: the last frame, or this one in the motion blur), so the glow +// is smooth: point samples of the full image caught a headlight of one pixel only at fixed offsets and drew it as grids of dots +const float WS_LIGHT_GAIN = 1.0; // brightness of the lights in the drops (0 = off) +const float WS_LIGHT_CAP = 8.0; // the most the glow adds to a drop (brightness, scene units) +const float WS_LIGHT_MIN_LUM = 1.0; // a light: the fine level at least this bright (scene units) above the place around it ... +const float WS_LIGHT_CONTRAST = 3.0; // ... and this many times brighter than it +const float WS_LIGHT_FINE = 3.5; // mip levels: the drop's own neighbourhood (~11 px), a wider one (~32 px), the place around +const float WS_LIGHT_MID = 5.0; +const float WS_LIGHT_WIDE = 7.0; +const float WS_LIGHT_MID_SHARE = 0.5; // how much the lights a little further away count + +// the vulkan renderer gives the post-processing only its own images (LAYOUT_POST): no history of the reflections, no glow there +#ifndef LAYOUT_POST +layout(binding = SSR_HISTORY_TEX) uniform sampler2D ws_light_history; +#endif + +// reverse z, infinite far: depth = znear / distance. a sample is "the cab" when it is much nearer than the centre and closer than ~5 m +const float WS_NEAR_RATIO = 1.6; +const float WS_NEAR_DEPTH = 0.02; + +bool wsSameLayer(float d, float d0) +{ + return d <= max(d0 * WS_NEAR_RATIO, WS_NEAR_DEPTH); +} + +float wsLum(vec3 c) +{ + return dot(c, vec3(0.2126, 0.7152, 0.0722)); +} + +// a drop pixel (drop, rivulet): both values in 132..252 +bool wsIsDrop(vec2 raw) +{ + // 132 .. 252 exactly: with msaa the edge of a drop averaged with the scene behind (half the values, up to 126) isn't a drop, + // else its decoded bend was nonsense, pulling the picture from far away for a frame (a drop flashing) + return raw.x > 131.5 && raw.y > 131.5; +} + +vec2 wsBend(vec2 raw) +{ + return clamp((raw - WS_DROP_BIAS) / WS_BEND_ENC, -1.0, 1.0); +} + +#ifndef LAYOUT_POST +// the image of the reflections around Uv as blurred as its mip level Lod, but round: a level of the mipmaps is a grid of squares +// (2^Lod pixels each), and a light read from it alone lit the drops in a square around it. a ring of taps of the finer level +// around the place, weighed as a soft disc, gives the same blur without the squares +vec3 wsHistoryRound(vec2 uv, float lod) +{ + float level = min(lod, ssr_params2.x); + float finer = max(level - 1.0, 0.0); + vec2 pixel = 1.0 / vec2(textureSize(ws_light_history, 0)); + float radius = 0.6 * exp2(level); // pixels of the image + vec3 sum = wsSafe(textureLod(ws_light_history, uv, finer).rgb) * 0.2; + for (int i = 0; i < 8; ++i) + { + float a = (float(i) + 0.5) * 0.7853982; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a), sin(a)) * radius * pixel, finer).rgb) * 0.06; + sum += wsSafe(textureLod(ws_light_history, uv + vec2(cos(a + 0.3927), sin(a + 0.3927)) * (2.0 * radius) * pixel, finer).rgb) * 0.04; + } + return sum; +} + +vec3 wsLightExcess(vec2 uv, float lod, vec3 wide) +{ + vec3 c = wsHistoryRound(uv, lod); + vec3 excess = max(c - wide * WS_LIGHT_CONTRAST, vec3(0.0)); + // no threshold with an edge: a light dims away from it (the drops right by a lamp the brightest, then less and less); full + // from twice WS_LIGHT_MIN_LUM above the place around, as much as before there + return excess * clamp(wsLum(excess) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); +} + +vec3 wsLightGlow(vec2 uv) +{ + if ((ssr_params.x < 1.0) || (textureSize(ws_light_history, 0).x < 16)) + return vec3(0.0); + vec3 wide = wsHistoryRound(uv, WS_LIGHT_WIDE); + // the near light in full, the one a little further away fading with it squared: the farther the drop, the less + vec3 mid = wsLightExcess(uv, WS_LIGHT_MID, wide); + float midF = clamp(wsLum(mid) / (2.0 * WS_LIGHT_MIN_LUM), 0.0, 1.0); + vec3 glow = wsLightExcess(uv, WS_LIGHT_FINE, wide) + WS_LIGHT_MID_SHARE * mid * midF; + glow *= WS_LIGHT_GAIN; + // a light close by is kept to the brightness of one light + return glow * min(1.0, WS_LIGHT_CAP / max(wsLum(glow), 1e-4)); +} +#else +vec3 wsLightGlow(vec2 uv) +{ + return vec3(0.0); +} +#endif + +// the picture at Uv seen through the drop, for a drop pixel with the request Raw +vec3 wsDropRefraction(sampler2D colortex, sampler2D velocitytex, sampler2D depthtex, vec2 uv, vec2 raw) +{ + vec2 texelSize = 1.0 / vec2(textureSize(colortex, 0)); + float aspect = texelSize.x / texelSize.y; // height / width + vec3 center = wsFetch(colortex, uv); + + vec2 bend = wsBend(raw); + vec2 uv2 = uv - bend * WS_REFR_MAXPX * texelSize; + + // the spread of the picture between neighbouring pixels (the jacobian of the shift): a drop shows a minified, flipped copy + // of the scene, single samples would alias into a hatch there + vec2 rx = textureLod(velocitytex, uv + vec2(texelSize.x, 0.0), 0.0).xy; + vec2 ry = textureLod(velocitytex, uv + vec2(0.0, texelSize.y), 0.0).xy; + vec2 jx = (wsIsDrop(rx) ? wsBend(rx) - bend : vec2(0.0)) * WS_REFR_MAXPX; + vec2 jy = (wsIsDrop(ry) ? wsBend(ry) - bend : vec2(0.0)) * WS_REFR_MAXPX; + float lens = length(jx) + length(jy); + + // never pull in what is much nearer than the scene behind the glass (the cab) + vec3 refr = center; + float d0 = textureLod(depthtex, uv, 0.0).x; + float d1 = textureLod(depthtex, uv2, 0.0).x; + if (wsSameLayer(d1, d0)) + { + if (lens < WS_LENS_AA) + { + refr = wsFetch(colortex, uv2); + } + else + { + vec2 fx = clamp(vec2(1.0, 0.0) - jx, vec2(-10.0), vec2(10.0)); + vec2 fy = clamp(vec2(0.0, 1.0) - jy, vec2(-10.0), vec2(10.0)); + vec3 acc = vec3(0.0); + float wacc = 0.0; + for (int j = 0; j < 4; ++j) + { + for (int i = 0; i < 4; ++i) + { + vec2 t = (vec2(float(i), float(j)) + 0.5) / 4.0 - 0.5; + vec3 c = wsFetch(colortex, uv2 + (fx * t.x + fy * t.y) * texelSize); + float w = wsKaris(c); + acc += c * w; + wacc += w; + } + } + refr = acc / wacc; + } + } + + vec3 outc = mix(center, refr, WS_REFR_MIX); + // the glow only in the drops themselves, strongest in their middle, where the lens bends most: the water film and the + // rivulets between them (no bend) would show it as flat squares around the headlights of an oncoming train + float glowW = smoothstep(0.03, 0.2, length(bend)); + if ((WS_LIGHT_GAIN > 0.0) && (glowW > 0.0)) + outc += wsLightGlow(uv) * glowW; + return outc; +} + +#endif diff --git a/shaders/vk14/snow_sprites.glsl b/shaders/vk14/snow_sprites.glsl new file mode 100644 index 000000000..897ae70b9 --- /dev/null +++ b/shaders/vk14/snow_sprites.glsl @@ -0,0 +1,462 @@ +// the snow on the windscreens laid together from the sprites of the atlas (mat_snow_windscreen.frag, water_snowlayer.comp): the +// tuning of the look of the snow and the laying of the lumps, the dots and the drops. the including file declares the samplers +// raindropsatlas and normalmap (the atlas of the snow and its normal map) and includes random.glsl and water.glsl before + +#ifndef SNOW_SPRITES_GLSL +#define SNOW_SPRITES_GLSL + +// --- tuning ------------------------------------------------------------------------------------------------------------------ +const float snow_flake_cell = 0.010; // a dot, a small puff or a drop at most every this many metres of the glass (its size) +const float snow_crystals = 0.35; // share of the cells with a little dry snow showing a dot or a small puff +const float snow_drops = 0.05; // share of the texels with the water of a melted flake showing a drop (more with more water) +const float snow_deep = 2.5; // mm of snow from which the cover is opaque (no picture behind it) +const float snow_cover = 0.25; // the lumps get opaque from three times this many mm of snow +const float snow_lump_cell = 0.0225; // a lump at most every this many metres of the glass (its size: up to two of them) +const vec2 snow_lump_grow = vec2(0.75, 0.88); // a lump's size as it comes .. on thick snow, of its size (small gaps stay open) +const float snow_heap_cells = 2.85; // the heaps the lumps come in, cells of the lumps (bigger: bigger heaps) +const float snow_opaque = 1.8; // mm of fresh snow letting 1/e of the light through (packed: half of it) +const float snow_ice = 0.75; // opacity of a lump until the snow gets thick (icy: the picture shows through, bent) +const vec3 snow_ice_tint = vec3(0.93, 0.97, 1.0); // the colour of the icy snow +const float snow_thin = 0.5; // opacity of the most glassy flake; each flake is at random from it to fully white +const float snow_glassy = 0.45; // opacity of the most glassy lump until the snow gets thick; each lump from it to fully white +const float snow_lump_white = 0.88; // opacity of the whitest lump until the snow gets thick (the flakes under it show through) +const float snow_bump = 1.0; // strength of the relief from the normal map, 0 = flat +const float snow_gloss = 0.8; // glints of the sun / headlights on the wet snow, 0 = matt +const float snow_ice_bend = 1.0; // how strongly the icy snow bends the picture behind it, of the bend of a drop +const float snow_translucency = 0.8; // glow of thin snow when you look towards the sun / a lamp, 0 = off +const float snow_haze = 1.0; // blur of the scene behind thin snow (frosted glass), 0 = off +const float snow_drop_bend = 1.0; // how strongly the drops bend the picture behind them +const float snow_wet_blur = 0.6; // blur of the scene behind a wet film +const vec2 snow_blur_mm = vec2(0.05, 0.6); // the scene behind the snow blurred from .. fully at this many mm of it (as the rain + // mists the glass up: the gaps between the lumps too, clear again behind a blade) + +const float WS_REFR_MAXPX = 96.0; // the largest picture shift the post-processing makes, screen pixels; as rain_windscreen_haze.glsl +const float WS_BEND_ENC = 60.0; // the bend request in the velocity target; as rain_windscreen_haze.glsl +const float WS_DROP_BIAS = 192.0; +const float WS_ENC = 64.0; // the haze request in the velocity target; as rain_windscreen_haze.glsl + +const float SNOW_FRESH = 0.1; // water in a mm of fresh snow, mm (as water_snow.comp) +const float SNOW_PACKED = 0.4; // and of packed snow + +// tiles of the atlas +const int TILE_DROP = 15; + +vec2 snUV = vec2(0.0); // the place on the glass laid, uv +int snSlot = 0; +uint snMap = 0u; +bool snBig = true; // a 4 x 4 atlas (else the older 2 x 2) +float snHaze = 0.0; // the picture behind is blurred (thin snow, a wet film) +vec2 snBend = vec2(0.0); // the drops bend the picture behind (their normals, weighted) +float snBendA = 0.0; + +struct sprite_acc +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied +}; + +// the corner of a tile in the atlas; an older 2 x 2 atlas stands its four tiles in for the sixteen +// the rows of the tiles counted from the top of the picture of the atlas (as snieg_atlas_maszyna.py makes it), the v of the +// texture from its bottom: the first row is at the top of the texture (the tiles of the old 2 x 2 atlas the same way) +vec2 snTile(int tile) +{ + if (snBig) + return vec2(float(tile % 4), float(3 - tile / 4)) * 0.25; + int old = 0; // a fluffy flake + if ((tile == 6) || (tile == 7)) + old = 2; // crumbs + else if ((tile >= 8) && (tile != 10) && (tile != 11) && (tile != TILE_DROP)) + old = 1; // a wet lump + else if (tile == TILE_DROP) + old = 3; // a melted spot + return vec2(float(old % 2), float(1 - old / 2)) * 0.5; +} + +float snTileSize() +{ + return snBig ? 0.25 : 0.5; +} + +// the snow under the middle of a sprite: the texel of the map there, not filtered between four (a sprite reads it once for all +// of its pixels, so it changes nothing of its shape; two reads of the storage instead of eight, for each sprite of each pixel) +vec4 snSnowAt(vec2 uv) +{ + return water_snow_texel(uint(snSlot), snMap, ivec2(floor(uv * float(WATER_MAP)))); +} + +// how white a sprite is (0 glassy, stuck and half melted, 1 dry powder), at random from its Random, whiter where the snow is +// Thick (0 .. 1); another number than Random, so it goes its own way of the tone +float snWhite(float random, float thick) +{ + float r = fract(random * 13.731 + 0.377); + return smoothstep(0.0, 1.0, clamp(r + (thick - 0.5) * 0.7, 0.0, 1.0)); +} + +// a sprite over the accumulator: Local the place in it (0 .. 1), Rot its rotation (cos, sin), Tone its colour +void snSprite(vec2 local, int tile, float alpha, vec3 tone, vec2 rot, float flip, float lod, float bend, inout sprite_acc acc) +{ + vec2 uv = snTile(tile) + local * snTileSize(); + vec4 t = textureLod(raindropsatlas, uv, lod); + vec4 n = textureLod(normalmap, uv, lod); + float a = clamp(t.a * alpha, 0.0, 1.0); + if (a <= 0.002) + return; + vec2 nxy = (n.rg * 2.0 - 1.0) * snow_bump; + nxy.x *= flip; + vec2 nuv = vec2(rot.x * nxy.x - rot.y * nxy.y, rot.y * nxy.x + rot.x * nxy.y); + vec3 nT = vec3(nuv, sqrt(max(1.0 - dot(nuv, nuv), 0.02))); + // front to back: the sprites come from the top one down (the same picture as laying them back to front), so the pixel stops + // looking once the snow over it covers it + float w = a * (1.0 - acc.a); + acc.rgb += t.rgb * tone * w; + acc.n += nT * w; + acc.tr += (1.0 - t.a * 0.55) * w; + acc.a += w; + // all the snow bends the picture behind it (wet icy snow, slush, drops), as the drops of the rain; the drops and the slush + // the most + float bends = snow_ice_bend * bend; // the atlas holds icy snow only + float wb = a * (1.0 - snBendA); + snBend += nuv * bends * wb; + snBendA += wb; +} + +// where in a sprite the pixel is: P the pixel and C the centre of the sprite, in the units of its grid (the size of the sprite +// in them), Aspect the cells as they lie on the glass; false outside the sprite +bool snLocal(vec2 p, vec2 c, float size, vec2 aspect, vec2 rot, float flip, float aniso, out vec2 local) +{ + vec2 d = (p - c) * aspect; + vec2 r = vec2(rot.x * d.x + rot.y * d.y, -rot.y * d.x + rot.x * d.y); + r.x *= flip / aniso; + local = r / size + 0.5; + return all(greaterThanEqual(local, vec2(0.0))) && all(lessThanEqual(local, vec2(1.0))); +} + +float snLod(float pixelUV, float sizeUV) +{ + float tilePx = float(textureSize(raindropsatlas, 0).x) * snTileSize(); + return clamp(log2(max(pixelUV / sizeUV * tilePx, 1.0)), 0.0, 6.0); +} + +// how wet the snow of a state of the map is (0 dry .. 1 slush) +float snWetness(vec4 q) +{ + return q.y / (q.y + q.x * mix(SNOW_FRESH, SNOW_PACKED, q.z) + 1e-4); +} + +// the tone of the snow: grey and darker when wet (slush), a little grey when packed +vec3 snTone(vec4 q, float random) +{ + vec3 tone = vec3(mix(0.94, 1.04, random)) * snow_ice_tint; + tone *= mix(vec3(1.0), vec3(0.95, 0.96, 0.98), q.z); + return tone * mix(vec3(1.0), vec3(0.88, 0.91, 0.94), smoothstep(0.3, 0.8, snWetness(q))); +} + +// how much a cell of the lumps lies in a heap: the snow landing side by side runs together, so the lumps come in heaps with +// barer glass between them; a random number for every few cells, blended between them (the same for every pixel of the cell) +float snHeap(ivec2 cell) +{ + vec2 c = (vec2(cell) + 0.5) / snow_heap_cells; + ivec2 i = ivec2(floor(c - 0.5)); + vec2 f = c - 0.5 - vec2(i); + f = f * f * (3.0 - 2.0 * f); + uint s00 = Hash(uvec3(uvec2(i + 8192), 53u)); + uint s10 = Hash(uvec3(uvec2(i + ivec2(1, 0) + 8192), 53u)); + uint s01 = Hash(uvec3(uvec2(i + ivec2(0, 1) + 8192), 53u)); + uint s11 = Hash(uvec3(uvec2(i + ivec2(1, 1) + 8192), 53u)); + return mix(mix(RandF(s00), RandF(s10), f.x), mix(RandF(s01), RandF(s11), f.x), f.y); +} + +// the lumps, in grids of cells of snow_lump_cell metres of the glass, shifted against each other. every cell of a grid has its +// lump fixed once (its tile, place, turn, size and the snow it takes to be there): the lump comes when the snow of the map around +// it reaches that, grows a little with more snow, and stays as it is until the snow goes (a blade, the melting); it never turns +// into another lump. the grids come one after the other as the snow piles up: dots and crumbs first, then puffs, clumps, and last +// the big lumps of packed snow which close the glass. in a heap (the snow landing side by side runs together) they come sooner +struct lump_grid +{ + vec2 shift; // the grid shifted, cells + uint salt; + vec2 snow; // the snow it takes for a lump of the grid to come, mm: from .. to (random per cell) + vec2 size; // the size of its lumps, cells: from .. to (random per cell) + int tiles; // its tiles, in sn_lump_tiles: the first one and how many + int count; + float share; // the share of its cells having a lump at all (1: all of them) +}; + +// the tiles of the lumps, as the grids take them: the fleece (2-5, and the clumps made of it, 8, 9) and the packed snow (10-15) +const int sn_lump_tiles[12] = int[12](2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15); + +// the grids of the lumps, coming one after the other as the snow piles up, each on the ones before, in the order they are laid +// (front to back, the top one first): all of them icy fleece (the dense puffs and clumps, tiles 2-5, 8, 9), more and bigger, closing +// the glass by 2-3 mm; now and then a single lump of packed snow on top (tiles 10-15) +const int SN_GRIDS = 5; +const lump_grid sn_grids[SN_GRIDS] = lump_grid[SN_GRIDS]( + lump_grid(vec2(0.4, 0.6), 271u, vec2(0.6, 2.0), vec2(1.2, 1.6), 6, 6, 0.03), + lump_grid(vec2(0.75), 251u, vec2(1.0, 2.6), vec2(2.0, 3.0), 2, 4, 1.0), + lump_grid(vec2(0.0, 0.5), 233u, vec2(0.6, 1.8), vec2(2.0, 3.0), 0, 6, 1.0), + lump_grid(vec2(0.75, 0.25), 151u, vec2(0.2, 1.0), vec2(1.8, 2.8), 2, 4, 1.0), + lump_grid(vec2(0.0), 31u, vec2(0.02, 0.5), vec2(1.4, 2.4), 2, 4, 1.0)); +// (nine grids before: each grid alone covers the glass a few times over, so five close it as well, with fewer sprites one on +// another at a pixel) + +const float SN_COVERED = 0.998; // the snow over the pixel covering it: the sprites under it are not looked at + +// the dots and the drops, in cells of snow_flake_cell metres of the glass: in many of the cells holding a little dry snow a dot +// or a small puff sits between the lumps, in some of those holding only water a drop of a melted flake. the flake of a Cell at P +// (the place in cells): true when it is there and comes within Reach (cells) of P; laid over Acc where it covers P +bool snFlakeCell(vec2 p, ivec2 cell, vec2 perUV, float pixelUV, float reach, inout sprite_acc acc) +{ + uint seed = Hash(uvec3(uvec2(cell + 8192), 17u + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.15 + 0.7 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the flake doesn't change: the map is the costly part, so + // it is read only for a flake which, as big as it gets, covers the pixel + float chance = RandF(seed); + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + float kind = RandF(seed); + float random = RandF(seed); + float sizeDraw = mix(0.6, 1.0, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * 1.4 + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + vec4 q = snSnowAt(centre / perUV); + // only the dry snow has its flakes: no drops of the melted ones (the round drops and the wet lumps with their film, tiles 8, 9, + // 14, 15, aren't used) + bool drop = false; + bool crystal = (q.x >= 0.05); + if (false == crystal) + return false; + if (chance > (drop ? snow_drops * smoothstep(0.03, 0.2, q.y) : snow_crystals)) + return false; + float size = sizeDraw * (drop ? mix(0.7, 1.4, smoothstep(0.03, 0.3, q.y)) : 1.0); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, 1.0, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, 1.0, local)) + return true; + int tile = min(int(kind * 4.0), 3); // the small clump, the dots and the scattered crystals (tiles 0, 1, 6, 7) + tile += (tile < 2) ? 0 : 4; + float white = snWhite(random, smoothstep(0.05, snow_cover * 3.0, q.x)); + float alpha = mix(snow_thin, 1.0, white); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), 1.0 - white, acc); + return true; +} + +// the lump of a Cell of a Grid at P (the place in the cells of the grid, shifted): true when it is there and comes within Reach +// (cells) of P; laid over Acc where it covers P +bool snLumpCell(vec2 p, ivec2 cell, vec2 perUV, lump_grid grid, float pixelUV, float reach, inout sprite_acc acc) +{ + uint seed = Hash(uvec3(uvec2(cell + 4096), grid.salt + 7u * uint(snSlot))); + vec2 centre = vec2(cell) + 0.1 + 0.8 * vec2(RandF(seed), RandF(seed)); + // every draw of the cell first, in the order they always came, so the lump doesn't change: the map is the costly part, so it + // is read only for a lump which, as big as it grows, covers the pixel (most of the nine cells don't) + float needsDraw = RandF(seed); + if (RandF(seed) >= grid.share) + return false; + float ang = RandF(seed) * 6.2831853; + vec2 rot = vec2(cos(ang), sin(ang)); + float flip = (RandF(seed) < 0.5) ? -1.0 : 1.0; + int tile = sn_lump_tiles[grid.tiles + min(int(RandF(seed) * float(grid.count)), grid.count - 1)]; + float random = RandF(seed); + float aniso = mix(0.8, 1.0, RandF(seed)); + float sizeDraw = mix(grid.size.x, grid.size.y, RandF(seed)); + vec2 local; + if (false == snLocal(p, centre, sizeDraw * snow_lump_grow.y + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + // the snow it takes, sooner in a heap + float needs = mix(grid.snow.x, grid.snow.y, needsDraw) * mix(1.4, 0.6, snHeap(cell)); + vec4 q = snSnowAt((centre - grid.shift) / perUV); + if (q.x <= needs) + return false; + float size = sizeDraw * mix(snow_lump_grow.x, snow_lump_grow.y, smoothstep(needs, needs * 2.0 + 0.2, q.x)); + if (false == snLocal(p, centre, size + 2.0 * reach, vec2(1.0), rot, flip, aniso, local)) + return false; + if (false == snLocal(p, centre, size, vec2(1.0), rot, flip, aniso, local)) + return true; + // fading in over the first snow (no flicker on the edge), opaque when thick; the thick snow bends nothing + float deep = smoothstep(snow_cover * 3.0, snow_deep, q.x); + float white = snWhite(random, smoothstep(snow_cover, snow_deep, q.x)); + float alpha = smoothstep(needs, needs + 0.04, q.x) * mix(mix(snow_glassy, snow_lump_white, white), 1.0, deep); + vec3 tone = mix(snTone(q, random), vec3(1.0), white * 0.6); + snSprite(local, tile, alpha, tone, rot, flip, snLod(pixelUV, size / max(perUV.x, perUV.y)), (1.0 - deep) * (1.0 - white), acc); + return true; +} + +// the snow of the glass laid together: the flakes over the lumps, as water_snowlayer.comp lists them for the texels of the layer +// and mat_snow_windscreen.frag lays them at its pixels (or, for a glass without the layer, all of them at its pixels) +struct snow_layer_s +{ + vec3 rgb; // premultiplied + float a; + vec3 n; // premultiplied, tangent space + float tr; // translucency, premultiplied + vec2 bend; // the bend of the picture behind, weighted + float bendA; // its weight + float haze; // the blur of the picture behind the thin snow +}; + +snow_layer_s snFinish(sprite_acc flakes, sprite_acc layer) +{ + snow_layer_s s; + // the flakes over the layer + s.rgb = flakes.rgb + layer.rgb * (1.0 - flakes.a); + s.a = flakes.a + layer.a * (1.0 - flakes.a); + s.n = flakes.n + layer.n * (1.0 - flakes.a); + s.tr = flakes.tr + layer.tr * (1.0 - flakes.a); + s.bend = snBend; + s.bendA = snBendA; + // the picture behind thin flakes is blurred + s.haze = smoothstep(0.0, 0.3, flakes.a + layer.a) * (1.0 - smoothstep(0.5, 0.9, layer.a)) * 0.6; + return s; +} + +// the snow of the glass laid together at UV from all the cells around it. Span: metres of the glass in a unit of its uv; +// PixelUV: the uv a pixel covers (the level of the atlas). snSlot, snMap and snBig set before +snow_layer_s snCompose(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // laid front to back: the flakes, then the grids from the top one down, so a pixel stops looking once the snow over it covers + // it + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + for (int oy = 1; oy >= -1; --oy) + for (int ox = 1; ox >= -1; --ox) + snFlakeCell(pF, hereF + ivec2(ox, oy), perF, pixelUV, 0.0, flakes); + vec2 perL = span / snow_lump_cell; + for (int g = 0; g < SN_GRIDS; ++g) + { + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (layer.a >= SN_COVERED) + return snFinish(flakes, layer); // the grids over this one cover the pixel + snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, 0.0, layer); + } + } + return snFinish(flakes, layer); +} + +// the layer of the snow of a glass (water_snowlayer.comp writes it, mat_snow_windscreen.frag reads it) holds for each of its +// texels (~1 mm of the glass) the sprites coming within it, in the order they are laid: up to SN_REFS bytes in four uint, each +// 1 + the list (0 the flakes, 1 .. SN_GRIDS the grids of the lumps) times 16 + the cell around the texel (0 .. 8: 1 - the column +// offset + 3 * (1 - the row offset)), 0 after the last one (a layer cleared to zeros lists nothing). the glass lays only those at +// its pixels, sharp from the atlas as when it laid all of the cells around itself, at a fraction of the cost +const int SN_REFS = 6; // the top ones, the listing stops when full (sixteen fit in the four uint; 8 if thick snow shows gaps) +// the sprites over a texel covering it on the whole (the level of the atlas the size of the texel): those under it are left out +const float SN_LIST_COVERED = 0.97; + +void snRef(uint ref, inout uvec4 refs, inout int count) +{ + if (count >= SN_REFS) + return; + uint shift = 8u * uint(count & 3); + refs[count >> 2] = (refs[count >> 2] & ~(255u << shift)) | ((ref + 1u) << shift); + ++count; +} + +// the sprites of the texel of the layer centred at UV (PixelUV its size in the uv), as the layer holds them +uvec4 snList(vec2 uv, vec2 span, float pixelUV) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + uvec4 refs = uvec4(0u); + int count = 0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + // the sprites coming within the corners of the texel (cells of the list), as big as they grow before it is listed anew + float half_diagonal = 0.75 * pixelUV; + vec2 perF = span / snow_flake_cell; + vec2 pF = uv * perF; + ivec2 hereF = ivec2(floor(pF)); + float reachF = half_diagonal * max(perF.x, perF.y) * 1.25; + for (int k = 0; k < 9; ++k) + { + if (count >= 2) + break; // two flakes at most, the rest of the list for the lumps + if (snFlakeCell(pF, hereF + ivec2(1 - k % 3, 1 - k / 3), perF, pixelUV, reachF, flakes)) + snRef(uint(k), refs, count); + } + vec2 perL = span / snow_lump_cell; + float reachL = half_diagonal * max(perL.x, perL.y) * 1.25 + 0.05; + for (int g = 0; g < SN_GRIDS; ++g) + { + if ((layer.a >= SN_LIST_COVERED) || (count >= SN_REFS)) + break; // the grids over this one cover the texel, or the list is full + vec2 pL = uv * perL + sn_grids[g].shift; + ivec2 hereL = ivec2(floor(pL)); + for (int k = 0; k < 9; ++k) + { + if (count >= SN_REFS) + break; // the list is full: nothing more worked out, and the cover counts only the sprites the glass lays + if (snLumpCell(pL, hereL + ivec2(1 - k % 3, 1 - k / 3), perL, sn_grids[g], pixelUV, reachL, layer)) + snRef(uint(16 * (g + 1) + k), refs, count); + } + } + return refs; +} + +// the snow of the glass laid together at UV from the sprites Refs of the texel of the layer centred at CentreUV (the cells +// counted around that). Span: metres of the glass in a unit of its uv at the texel; PixelUV: the uv a pixel covers +snow_layer_s snComposeRefs(vec2 uv, vec2 centreUV, vec2 span, float pixelUV, uvec4 refs) +{ + snUV = uv; + snBend = vec2(0.0); + snBendA = 0.0; + sprite_acc layer = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + sprite_acc flakes = sprite_acc(vec3(0.0), 0.0, vec3(0.0), 0.0); + vec2 perF = span / snow_flake_cell; + vec2 perL = span / snow_lump_cell; + for (int r = 0; r < SN_REFS; ++r) + { + uint ref = (refs[r >> 2] >> (8u * uint(r & 3))) & 255u; + if (ref == 0u) + break; + --ref; + int list = int(ref >> 4u); + int k = int(ref & 15u); + ivec2 offset = ivec2(1 - k % 3, 1 - k / 3); + if ((list == 0) && (k < 9)) + { + snFlakeCell(uv * perF, ivec2(floor(centreUV * perF)) + offset, perF, pixelUV, 0.0, flakes); + continue; + } + if ((list > SN_GRIDS) || (k >= 9) || (layer.a >= SN_COVERED)) + continue; // nothing laid, or the grids over this one cover the pixel + lump_grid grid = sn_grids[list - 1]; + ivec2 here = ivec2(floor(centreUV * perL + grid.shift)); + snLumpCell(uv * perL + grid.shift, here + offset, perL, grid, pixelUV, 0.0, layer); + } + return snFinish(flakes, layer); +} + +// the metres of the glass in a unit of its uv at UV, from the texel of its map there or, at the edge of the glass, the nearest +// one next to it the glass is on; false when there is none +bool snSpan(uint slot, vec2 uv, out vec2 span) +{ + span = vec2(0.05); + ivec2 at = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + // the texel itself first, then the ones beside it, then the corners + const ivec2 near[9] = ivec2[9](ivec2(0), ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1), ivec2(1), ivec2(-1, 1), ivec2(1, -1), ivec2(-1)); + for (int k = 0; k < 9; ++k) + { + ivec2 t = clamp(at + near[k], ivec2(0), ivec2(WATER_MAP - 1)); + uint axis = (slot * uint(WATER_MAP * WATER_MAP) + uint(t.y * WATER_MAP + t.x)) * 2u; + if (water_axes[axis].w > 0.0) + { + span = max(vec2(length(water_axes[axis].xyz), length(water_axes[axis + 1u].xyz)), vec2(0.05)); + return true; + } + } + return false; +} + +#endif diff --git a/shaders/vk14/tonemapping.glsl b/shaders/vk14/tonemapping.glsl index cee58e5df..bb9e15f21 100644 --- a/shaders/vk14/tonemapping.glsl +++ b/shaders/vk14/tonemapping.glsl @@ -162,7 +162,8 @@ vec4 tonemap(vec4 x) // 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)))); + // the bvec3 overload selects instead of blending, so a NaN does not get through 0 * NaN + hdr = mix(hdr, vec3(0.0), bvec3(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)); diff --git a/shaders/vk14/water.glsl b/shaders/vk14/water.glsl index 41d672d60..2bfe62a6a 100644 --- a/shaders/vk14/water.glsl +++ b/shaders/vk14/water.glsl @@ -54,6 +54,91 @@ layout(std430, set = PASS_SET, binding = WATER_SSBO) readonly buffer water_ssbo uint water_cells[]; }; +// the snow on a glass of the snow (water_snow.comp, mat_snow_windscreen.frag): two maps of WATER_MAP x WATER_MAP texels after the +// wetted paths in water_cells, two uint a texel (halves: x the snow, mm, y the water, mm, z how packed the snow is 0 .. 1, w random +// 0 .. 1, the shape of its flakes); a step reads one and writes the other, the header of the glass says which one is the latest +// (z 1 when there's a map of the snow, w the map) +uint water_snow_base(uint slot, uint map) +{ + return uint(WATER_SLOTS * WATER_GRID * WATER_GRID * (1 + WATER_CELL_DROPS)) + uint(WATER_SLOTS * WATER_TRAIL * WATER_TRAIL) + (map * uint(WATER_SLOTS) + slot) * uint(WATER_MAP * WATER_MAP * 2); +} + +// a texel of a map of the snow, nothing outside the map +vec4 water_snow_texel(uint slot, uint map, ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return vec4(0.0); + uint index = water_snow_base(slot, map) + 2u * uint(texel.y * WATER_MAP + texel.x); + return vec4(unpackHalf2x16(water_cells[index]), unpackHalf2x16(water_cells[index + 1u])); +} + +// the snow of a glass laid together (water_snowlayer.comp, read by mat_snow_windscreen.frag), after the maps of the snow: eight +// uint of every glass (the rectangle of its uv the layer takes: the corner and the size, floats; the texels of the layer across +// and down, 0 when the glass has no layer: the cab has one, for its first glass of the snow), then the layer, WATER_LAYER_TEXELS +// texels of four uint each: the sprites of the snow coming within the texel, in the order they are laid (snow_sprites.glsl, +// snList) +void water_layer_rect(uint slot, out vec4 rect, out uvec2 size) +{ + uint info = water_snow_base(0u, 2u) + slot * 8u; + rect = uintBitsToFloat(uvec4(water_cells[info], water_cells[info + 1u], water_cells[info + 2u], water_cells[info + 3u])); + size = uvec2(water_cells[info + 4u], water_cells[info + 5u]); +} + +uint water_layer_base() +{ + return water_snow_base(0u, 2u) + uint(WATER_SLOTS) * 8u; +} + +// whether the glass has the layer of the snow +bool water_layer_of(uint slot) +{ + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + return (size.x > 0u) && (size.y > 0u) && all(greaterThan(rect.zw, vec2(0.0))); +} + +// the sprites of the snow of a glass at UV, as its layer holds them for the texel there (Refs, see snow_sprites.glsl), and the +// centre of that texel (CentreUV); false outside the layer +bool water_layer_refs(uint slot, vec2 uv, out uvec4 refs, out vec2 centreUV) +{ + refs = uvec4(0u); + centreUV = uv; + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (size.y == 0u) || any(lessThanEqual(rect.zw, vec2(0.0)))) + return false; + ivec2 t = ivec2(floor((uv - rect.xy) / rect.zw * vec2(size))); + if (any(lessThan(t, ivec2(0))) || any(greaterThanEqual(t, ivec2(size)))) + return false; + centreUV = rect.xy + (vec2(t) + 0.5) / vec2(size) * rect.zw; + uint index = water_layer_base() + 4u * (uint(t.y) * size.x + uint(t.x)); + refs = uvec4(water_cells[index], water_cells[index + 1u], water_cells[index + 2u], water_cells[index + 3u]); + return true; +} + +// the latest map of the snow of a glass; false when there's none yet +bool water_snow_map(uint slot, out uint map) +{ + vec4 header = water_header[slot]; + map = (header.w > 0.5) ? 1u : 0u; + return header.z > 0.5; +} + +// the latest map of the snow filtered between the texels at a place of the glass +vec4 water_snow_at(uint slot, uint map, vec2 uv) +{ + vec2 p = uv * float(WATER_MAP) - 0.5; + ivec2 i = ivec2(floor(p)); + vec2 f = p - vec2(i); + vec4 a = water_snow_texel(slot, map, i); + vec4 b = water_snow_texel(slot, map, i + ivec2(1, 0)); + vec4 c = water_snow_texel(slot, map, i + ivec2(0, 1)); + vec4 d = water_snow_texel(slot, map, i + ivec2(1, 1)); + return mix(mix(a, b, f.x), mix(c, d, f.x), f.y); +} + // the radius of the footprint of a drop holding Volume mm3 of water, metres: a cap of a sphere meeting the glass at 40 degrees float water_radius(float volume) { diff --git a/shaders/vk14/water_sim.glsl b/shaders/vk14/water_sim.glsl index 82710150a..d1794ca64 100644 --- a/shaders/vk14/water_sim.glsl +++ b/shaders/vk14/water_sim.glsl @@ -41,6 +41,11 @@ layout(std140, set = COMPUTE_SET, binding = 1) uniform water_ubo // every glass: x the landings tried in the step, y 1 / the most metres squared a unit of its uv holds, z 1 when it's simulated, // w the size of its drops (rain_scale of its material) vec4 water_slots[WATER_SLOTS]; + // the snow (water_snow.comp): x the flakes coming to a square metre of the ground in a second, y how much warmer than the air + // the glass is, degrees, z the speed of the vehicle, m/s, w the map of the snow the step reads (0, 1) + vec4 water_snow; + // every glass: 1 when its snow is simulated + vec4 water_snow_slots; }; const float WATER_GRAVITY = 9.81; diff --git a/shaders/vk14/water_snow.comp b/shaders/vk14/water_snow.comp new file mode 100644 index 000000000..e4497b2e6 --- /dev/null +++ b/shaders/vk14/water_snow.comp @@ -0,0 +1,360 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl): a step of the snow of the glasses of the snow, a thread per texel of +// the map of a glass, a row of groups per glass. the step reads one map of the snow and writes the other (water_snow.w says which +// one it reads), so a texel sees its neighbours as they were before the step +// +// what a texel holds: the snow, mm (as it lies, fluffy or packed), the water, mm (the melted snow, a film on the glass and soaked +// into the snow), how packed the snow is (0 fresh flakes .. 1 snow pressed by a blade) and a random number, the shape of its +// flakes (mat_snow_windscreen.frag). in a step, in this order: +// - the snow and the water move: wet heavy snow (slush) slides down the glass, dry powder is blown along it by the air at speed, +// the water runs down as a film and is pushed by the air. what goes over the edge of the glass falls off. snow doesn't spread +// onto its neighbours by itself: it sticks to the glass, so the edge of a wiped area stays where the blade left it +// - the blades wipe, as they wipe the rain: a blade going over a texel in the step takes its snow (a little stays, and a wet +// trace of the water); what it takes is gone +// - now and then the thick snow lets go of the glass in a slab and slides off it, the glass bare behind it +// - the flakes land: as many as come to the glass facing the snow coming at it against the cab (and a few in the eddies of the +// air where it doesn't face it), each bringing its snow to the texel; the faster the vehicle the more of the dry ones bounce off. +// near zero the flakes are wet: they bring some water with them (wet snow, lumps of slush) +// - the snow melts: the glass is warmer than the air (the cab is heated), the less so the faster the vehicle goes; above zero the +// snow melts at the glass into its water, the water dries slowly + +// none of the pass set: everything the kernel reads is pushed with its dispatch (set COMPUTE_SET, water_sim.glsl), so it runs +// before the passes of the frame set theirs up +#define LAYOUT_UI 1 +#include "common.glsl" +#include "water_sim.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// how dense the snow is: fresh flakes and snow pressed by a blade (the water in a mm of it, mm) +const float SNOW_FRESH = 0.1; +const float SNOW_PACKED = 0.4; +// the snow of a flake, mm3 of water (0.3 .. 2.5 as the flakes of the water passes, water_spawn.comp) +const float SNOW_FLAKE_LEAST = 0.3; +const float SNOW_FLAKE_MOST = 2.5; +// the speed of the snow coming at the glass in the eddies of the air, m/s: a glass not facing the snow gets a little of it +const float SNOW_EDDIES = 0.6; +// the most snow a texel holds, mm +const float SNOW_MOST = 40.0; +// the share of the snow a blade leaves (at most SNOW_WIPE_LEFT mm: the snow it pushes along goes with it), of the water, and +// of the water of the snow it takes which it leaves as a wet trace (at most SNOW_WIPE_WET mm) +const float SNOW_WIPE_MISS = 0.03; +const float SNOW_WIPE_LEFT = 0.03; +const float SNOW_WIPE_WATER = 0.1; +const float SNOW_WIPE_TRACE = 0.08; +const float SNOW_WIPE_WET = 0.015; +// the water the snow melts into at the glass a second for each degree the glass is above zero, mm (the heat the glass passes on, +// ~70 W/m2 a degree, melts 0.0002 mm of water a second) +const float SNOW_MELT = 0.0002; +// the share of the snowfall the flakes of water_snow.x make (the renderer counts a quarter of them, as for the particles of the +// drop passes): the snow of the map gets a bit more of it (all of it built up too fast) +const float SNOW_FALL_SHARE = 1.5; +// the most of the speed of the snow against the glass counting for the snow landing, m/s: at speed most of the flakes go past or +// bounce off, so a front glass builds up its snow a few times as fast as a standing one, not a hundred +const float SNOW_FACING_MOST = 6.0; +// how much warmer than the air the glass is, the share of the warmth given (water_snow.y, the cab heats it) +const float SNOW_WARMTH = 1.0; +// the share of a flake landing near zero already water (wet snow) +const float SNOW_WET_FLAKES = 0.5; +// the water freezing a second on a glass below zero, mm +const float SNOW_FREEZE = 0.02; +// the water drying a second, mm, and the share of a thin film going in a second (it dries and runs off as droplets) +const float SNOW_DRY = 0.0004; +const float SNOW_FILM_DRY = 0.15; +// how fast slush slides down a vertical glass, how fast dry powder goes with the air (a share of the speed of the air along the +// glass), how fast the film of water runs down a vertical glass and goes with the air, m/s +const float SNOW_SLIDE = 0.03; +const float SNOW_BLOW = 0.0005; +const float SNOW_RUN = 0.02; +const float SNOW_RUN_AIR = 0.002; + +// the slabs: where the snow is thick, now and then a slab of it lets go and slides off the glass (on a glass plastered over a slab +// every SNOW_SLAB_EVERY seconds, on a frozen glass less often). its upper edge goes down the slab in SNOW_SLAB_SLIDE seconds and +// the glass behind it is bare, but for a little of the snow +// (the snow in the middle of the slab decides: the whole slab goes, a wiped glass as one never wiped, where the snow is as thick). +// every slab lets go from snow of its own, random: the more snow, the more of them go +const vec2 SNOW_SLAB_DEEP = vec2(0.4, 2.5); // mm of snow from which a slab lets go: from .. to (the glass is closed by 2-3 mm) +const float SNOW_SLAB_CELL = 24.0; // texels: at most a slab in a cell this big, about as big as the cell +const float SNOW_SLAB_EVERY = 3.0; // s +const float SNOW_SLAB_PERIOD = 10.0; // s: a cell draws for its slab once in this time +const float SNOW_SLAB_SLIDE = 1.2; // s +const float SNOW_SLAB_LEFT = 0.05; // the share of the snow a slab leaves + +struct snow_slab_s +{ + vec2 centre; // texels + float radius; // texels + float start; // s into the period + float deep; // mm of snow in its middle from which it lets go +}; + +uint snow_slot; +uint snow_from; +uint snow_axes_base; + +bool snow_on_glass(ivec2 texel) +{ + if (any(lessThan(texel, ivec2(0))) || any(greaterThanEqual(texel, ivec2(WATER_MAP)))) + return false; + return water_axes[(snow_axes_base + uint(texel.y * WATER_MAP + texel.x)) * 2u].w > 0.75; +} + +vec4 snow_get(ivec2 texel) +{ + return snow_on_glass(texel) ? water_snow_texel(snow_slot, snow_from, texel) : vec4(0.0); +} + +float snow_blade(ivec2 texel, int blade) +{ + texel = clamp(texel, ivec2(0), ivec2(WATER_MAP - 1)); + return water_blades[snow_axes_base + uint(texel.y * WATER_MAP + texel.x)][blade]; +} + +// whether the blade went over the texel in the step (it reaches it, and the place of the texel along its sweep is between where +// the blade was and where it is, the place it was at belonging to the step before) +bool snow_crossed(ivec2 texel, int blade) +{ + float before = water_blades_before[blade]; + float now = water_blades_now[blade]; + if ((before < 0.0) || (now < 0.0) || (now == before) || (false == snow_on_glass(texel))) + return false; + float place = snow_blade(texel, blade); + if (place <= 0.001) + return false; + return (now > before) ? ((place > before) && (place <= now)) : ((place < before) && (place >= now)); +} + +// the slab of a cell in a period, if the cell has one; the more often the warmer the glass (wet snow lets go sooner) +bool snow_slab_of(ivec2 cell, uint period, float glass, out snow_slab_s slab) +{ + vec4 draw = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51abu); + vec4 shape = water_random(uint(cell.x + 64), uint(cell.y + 64) + 977u * snow_slot, period, 0x51acu); + slab = snow_slab_s((vec2(cell) + 0.2 + 0.6 * shape.xy) * SNOW_SLAB_CELL, mix(0.5, 0.9, shape.z) * SNOW_SLAB_CELL, + shape.w * (SNOW_SLAB_PERIOD - SNOW_SLAB_SLIDE), mix(SNOW_SLAB_DEEP.x, SNOW_SLAB_DEEP.y, draw.y)); + float cells = float(WATER_MAP * WATER_MAP) / (SNOW_SLAB_CELL * SNOW_SLAB_CELL); + float chance = SNOW_SLAB_PERIOD / SNOW_SLAB_EVERY / cells * mix(0.4, 1.0, smoothstep(-6.0, 0.0, glass)); + return draw.x < chance; +} + +// whether the upper edge of the slab is past the place (texels) now, t seconds into the period: the place in the slab (its edge +// ragged) and above the edge going down it, faster and faster +bool snow_in_slab(vec2 p, vec2 down, float t, snow_slab_s slab) +{ + float progress = (t - slab.start) / SNOW_SLAB_SLIDE; + if ((progress < 0.0) || (progress > 1.0)) + return false; + vec2 off = p - slab.centre; + float ragged = slab.radius * mix(0.7, 1.15, water_noise(p / 5.0, 0x5a1bu + snow_slot)); + if (dot(off, off) > ragged * ragged) + return false; + return dot(off, down) < mix(-1.2, 1.2, progress * progress) * slab.radius; +} + +// whether a slab slides off the texel now; down: down the glass, texels (normalized) +bool snow_slid(ivec2 texel, vec2 down, float glass) +{ + float now = water_step.y; + uint period = uint(floor(now / SNOW_SLAB_PERIOD)); + float t = now - float(period) * SNOW_SLAB_PERIOD; + ivec2 here = ivec2(floor(vec2(texel) / SNOW_SLAB_CELL)); + vec2 p = vec2(texel) + 0.5; + for (int k = 0; k < 9; ++k) + { + snow_slab_s slab; + if ((false == snow_slab_of(here + ivec2(k % 3 - 1, k / 3 - 1), period, glass, slab)) || (false == snow_in_slab(p, down, t, slab))) + continue; + if (snow_get(ivec2(floor(slab.centre))).x >= slab.deep) + return true; + } + return false; +} + +// the frame of the glass at a texel, unfiltered +water_frame_s snow_frame(ivec2 texel) +{ + uint index = snow_axes_base + uint(texel.y * WATER_MAP + texel.x); + vec4 a = water_axes[index * 2u]; + vec4 b = water_axes[index * 2u + 1u]; + water_frame_s frame = water_frame_s(a.xyz, b.xyz, vec3(0.0, 0.0, 1.0), a.w); + vec3 n = cross(a.xyz, b.xyz); + if (dot(n, n) > 1e-24) + frame.normal = normalize(n) * ((b.w < 0.0) ? -1.0 : 1.0); + return frame; +} + +// how the snow (xy) and the water (zw) of a texel move, texels a second +vec4 snow_motion(ivec2 texel, vec4 state) +{ + if ((state.x <= 0.001) && (state.y <= 0.001)) + return vec4(0.0); + water_frame_s frame = snow_frame(texel); + vec3 n = frame.normal; + vec3 down = -water_up.xyz; + vec3 slope = down - n * dot(down, n); + vec3 air = water_air.xyz - n * dot(water_air.xyz, n); + float wind = length(air); + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // slush: wet and heavy enough to go; dry powder: loose and thin enough to be blown + float slide = SNOW_SLIDE * smoothstep(0.25, 0.7, wet) * smoothstep(2.0, 8.0, state.x); + float blow = SNOW_BLOW * smoothstep(10.0, 25.0, wind) * (1.0 - state.z) * (1.0 - smoothstep(0.1, 0.3, wet)) * (1.0 - smoothstep(0.08, 0.25, state.x)); + vec3 snow = slope * slide + air * blow; + // the film of water runs where there's enough of it, not the water soaked into the snow + float film = (1.0 - smoothstep(0.5, 3.0, state.x)); + vec3 water = (slope * SNOW_RUN * smoothstep(0.03, 0.15, state.y) + air * SNOW_RUN_AIR * smoothstep(0.03, 0.1, state.y)) * film; + return vec4(water_to_uv(frame, snow), water_to_uv(frame, water)) * float(WATER_MAP); +} + +// the shares of a texel going to its neighbours along x and along y in the step, for a motion in texels a second +vec2 snow_out(vec2 motion, float seconds) +{ + return min(abs(motion) * seconds, vec2(0.45)); +} + +// the snow and the water of the texel after they moved in the step: what leaves it, what comes from its neighbours; the +// packing and the shape go with the snow +vec4 snow_move(ivec2 texel, vec4 state, float seconds) +{ + vec4 motion = snow_motion(texel, state); + vec2 snowout = snow_out(motion.xy, seconds); + vec2 waterout = snow_out(motion.zw, seconds); + float snow = state.x * (1.0 - snowout.x - snowout.y); + float water = state.y * (1.0 - waterout.x - waterout.y); + float packing = state.z * snow; // (not "packed": a reserved word of GLSL, the NVIDIA OpenGL compiler refuses it) + const ivec2 sides[4] = ivec2[4](ivec2(1, 0), ivec2(-1, 0), ivec2(0, 1), ivec2(0, -1)); + for (int k = 0; k < 4; ++k) + { + ivec2 side = sides[k]; + ivec2 other = texel + side; + bool glass = snow_on_glass(other); + if (false == glass) + continue; + vec4 neighbour = water_snow_texel(snow_slot, snow_from, other); + float coming = 0.0; + // what the motion of the neighbour brings: it goes this way along the axis of the side + vec4 itsmotion = snow_motion(other, neighbour); + vec2 itssnow = snow_out(itsmotion.xy, seconds); + vec2 itswater = snow_out(itsmotion.zw, seconds); + if (side.x != 0) + { + coming += (itsmotion.x * float(side.x) < 0.0) ? neighbour.x * itssnow.x : 0.0; + water += (itsmotion.z * float(side.x) < 0.0) ? neighbour.y * itswater.x : 0.0; + } + else + { + coming += (itsmotion.y * float(side.y) < 0.0) ? neighbour.x * itssnow.y : 0.0; + water += (itsmotion.w * float(side.y) < 0.0) ? neighbour.y * itswater.y : 0.0; + } + snow += coming; + packing += coming * neighbour.z; + } + snow = max(snow, 0.0); + return vec4(snow, max(water, 0.0), (snow > 1e-4) ? clamp(packing / snow, 0.0, 1.0) : 0.0, state.w); +} + +void main() +{ + snow_slot = gl_WorkGroupID.y; + uint place = gl_GlobalInvocationID.x; + if ((water_snow_slots[snow_slot] < 0.5) || (place >= uint(WATER_MAP * WATER_MAP))) + return; + snow_from = (water_snow.w > 0.5) ? 1u : 0u; + uint to = 1u - snow_from; + snow_axes_base = snow_slot * uint(WATER_MAP * WATER_MAP); + if (place == 0u) + water_header[snow_slot].zw = vec2(1.0, float(to)); + ivec2 texel = ivec2(int(place % uint(WATER_MAP)), int(place / uint(WATER_MAP))); + uint index = water_snow_base(snow_slot, to) + 2u * place; + if (false == snow_on_glass(texel)) + { + water_cells[index] = 0u; + water_cells[index + 1u] = 0u; + return; + } + float seconds = water_step.x; + vec4 before = water_snow_texel(snow_slot, snow_from, texel); + vec4 state = snow_move(texel, before, seconds); + + // how warm the glass is: warmer than the air (the cab heats it), the less so the faster the vehicle goes + float speed = water_snow.z; + float glass = water_up.w + water_snow.y * SNOW_WARMTH / (1.0 + speed / 10.0); + + // the blades: they take the snow where they went over; a wet trace only on a glass above zero (on a frozen one the blade + // leaves it dry, so the snow landing on the wiped glass is the same dry snow as around) + bool crossed = false; + for (int blade = 0; blade < 4; ++blade) + crossed = crossed || snow_crossed(texel, blade); + if (crossed) + { + float left = min(state.x * SNOW_WIPE_MISS, SNOW_WIPE_LEFT); + float taken = state.x - left; + state.x = left; + float trace = min(taken * mix(SNOW_FRESH, SNOW_PACKED, state.z) * SNOW_WIPE_TRACE, SNOW_WIPE_WET) * smoothstep(-1.0, 1.0, glass); + state.y = state.y * SNOW_WIPE_WATER + trace; + } + + // a slab sliding off (not on a glass lying flat) + water_frame_s frame = snow_frame(texel); + vec3 down = -water_up.xyz; + vec2 downmap = water_to_uv(frame, down - frame.normal * dot(down, frame.normal)) * float(WATER_MAP); + if ((state.x > 0.0) && (dot(downmap, downmap) > 0.25) && snow_slid(texel, normalize(downmap), glass)) + state.x *= SNOW_SLAB_LEFT; + + // the flakes landing + float area = length(cross(frame.tu, frame.tv)) / float(WATER_MAP * WATER_MAP); // m2 + vec3 coming = water_air.xyz - water_up.xyz * water_air.w; // the snow against the cab, m/s + // the snow coming at the glass along its normal. the side of the glass the snow comes from isn't told: the outward side of + // the frames of the map (from the middle of the box around the cab model) and the air against the cab (from the matrix of + // the vehicle and its velocity) don't agree for every cab, and with them disagreeing a front glass at speed got the snow of + // the eddies only, plastered no faster than a standing one. the glass the driver looks through leads, so the snow comes at + // it from the outside + float facing = min(abs(dot(coming, frame.normal)), SNOW_FACING_MOST) + SNOW_EDDIES; + float density = mix(SNOW_FRESH, SNOW_PACKED, state.z); + float wet = state.y / (state.y + state.x * density + 1e-4); + // the dry flakes bounce off a moving glass (powder is blown away), the wet ones (near zero) and those landing on wet snow or + // water stay + // (only on a bare glass: a flake sticks to the snow already there) + float dry = (1.0 - smoothstep(0.1, 0.4, wet)) * (1.0 - smoothstep(-3.0, 0.0, water_up.w)) * (1.0 - smoothstep(0.05, 0.3, state.x)); + float sticking = 1.0 - 0.15 * smoothstep(5.0, 25.0, speed) * dry; + float landings = water_snow.x * SNOW_FALL_SHARE / max(water_air.w, 0.1) * facing * area * seconds * sticking; + vec4 random = water_random(place, snow_slot, water_counts.x, 0x5e0du); + float count = min(floor(landings) + ((random.x < fract(landings)) ? 1.0 : 0.0), 4.0); + if (count > 0.0) + { + float water = count * mix(SNOW_FLAKE_LEAST, SNOW_FLAKE_MOST, random.y * random.y); // mm3 + // the share of a wet flake already water (near zero) + float melting = SNOW_WET_FLAKES * smoothstep(-4.0, 0.5, water_up.w); + float added = water * (1.0 - melting) / SNOW_FRESH / max(area * 1e6, 1e-3); // mm of fresh snow over the texel + state.y += water * melting / max(area * 1e6, 1e-3); + float snow = state.x + added; + state.z = state.z * state.x / snow; + // a flake on the bare glass has a shape of its own + state.w = (state.x < 0.3) ? random.z : state.w; + state.x = snow; + } + + // the melting at the warm glass, the freezing at a frozen one (the water turns to ice, packed snow) and the drying + float frozen = min(state.y, SNOW_FREEZE * smoothstep(0.0, -2.0, glass) * seconds); + if (frozen > 0.0) + { + float ice = frozen / SNOW_PACKED; + state.z = (state.z * state.x + ice) / max(state.x + ice, 1e-4); + state.x += ice; + state.y -= frozen; + } + float melted = min(SNOW_MELT * max(glass, 0.0) * seconds, state.x * density); + state.x -= melted / max(density, 1e-3); + float film = state.y * (1.0 - smoothstep(0.5, 3.0, state.x)); // the water not soaked into the snow + state.y = max(state.y + melted - (SNOW_DRY + SNOW_FILM_DRY * film) * seconds, 0.0); + + state.x = clamp(state.x, 0.0, SNOW_MOST); + state.y = min(state.y, 4.0); + if (state.x < 0.002) + { + state.x = 0.0; + state.z = 0.0; + } + water_cells[index] = packHalf2x16(state.xy); + water_cells[index + 1u] = packHalf2x16(state.zw); +} diff --git a/shaders/vk14/water_snowlayer.comp b/shaders/vk14/water_snowlayer.comp new file mode 100644 index 000000000..264e5881f --- /dev/null +++ b/shaders/vk14/water_snowlayer.comp @@ -0,0 +1,82 @@ +#version 460 core +#define STAGE_COMPUTE 1 +// the snow on the windscreens (water_sim.glsl, water.glsl, snow_sprites.glsl): the sprites of the snow of a glass coming within +// each texel of its layer listed, which mat_snow_windscreen.frag lays at its pixels, sharp from the atlas (looking through the +// nine cells of the ten lists at every pixel of the glass in every frame cost as much as the rest of the frame). a thread per +// texel of the layer (over the rectangle of the uv the glass takes, ~1 mm a texel), the glass is water_counts.z. the snow under +// a lump changes slowly, so a band of every WATER_LAYER_BANDS-th row is listed anew in a step (water_counts.w the step), and at +// once wherever a blade went over the glass in the step + +// none of the pass set: everything the kernel reads is pushed with its dispatch (set COMPUTE_SET, water_sim.glsl) +#define LAYOUT_UI 1 +#include "common.glsl" +#include "water_sim.glsl" +#include "random.glsl" + +// the atlas of the snow of the glass and its normal map (raindropsatlas, normalmap of its material) +layout(set = COMPUTE_SET, binding = 2) uniform sampler2D raindropsatlas; +layout(set = COMPUTE_SET, binding = 3) uniform sampler2D normalmap; + +#include "snow_sprites.glsl" + +layout(local_size_x = WATER_GROUP_SIZE) in; + +// the share of the sweep of a blade around where it went in the step whose snow is laid anew: a lump is laid by the snow at its +// middle, up to two of its cells (~3 cm) away from a texel it covers +const float SNOW_LAYER_BLADE_MARGIN = 0.06; + +// whether a blade went over the texel of the map, or near it, in the step +bool snow_layer_swept(uint mapTexel) +{ + vec4 place = water_blades[mapTexel]; + for (int blade = 0; blade < 4; ++blade) + { + float now = water_blades_now[blade]; + float before = water_blades_before[blade]; + if ((now < 0.0) || (now == before) || (place[blade] <= 0.001)) + continue; + if ((place[blade] >= min(now, before) - SNOW_LAYER_BLADE_MARGIN) && (place[blade] <= max(now, before) + SNOW_LAYER_BLADE_MARGIN)) + return true; + } + return false; +} + +void main() +{ + uint slot = water_counts.z; + uint texel = gl_GlobalInvocationID.x; + if ((slot >= uint(WATER_SLOTS)) || (texel >= uint(WATER_LAYER_TEXELS)) || (water_snow_slots[slot] < 0.5)) + return; + uint map; + if (false == water_snow_map(slot, map)) + return; + // the layer over the rectangle of the uv the glass takes + vec4 rect; + uvec2 size; + water_layer_rect(slot, rect, size); + if ((size.x == 0u) || (texel >= size.x * size.y)) + return; + ivec2 at = ivec2(int(texel % size.x), int(texel / size.x)); + vec2 uv = rect.xy + (vec2(at) + 0.5) / vec2(size) * rect.zw; + ivec2 mapAt = clamp(ivec2(floor(uv * float(WATER_MAP))), ivec2(0), ivec2(WATER_MAP - 1)); + uint mapTexel = slot * uint(WATER_MAP * WATER_MAP) + uint(mapAt.y * WATER_MAP + mapAt.x); + // a band of the rows in a step (the snow builds up and melts slowly), and wherever a blade went + bool due = ((uint(at.y) % uint(WATER_LAYER_BANDS)) == (water_counts.w % uint(WATER_LAYER_BANDS))) || snow_layer_swept(mapTexel); + if (false == due) + return; + uint index = water_layer_base() + 4u * texel; + // nothing of the glass there or next to it (a texel on the edge of the glass takes the size of the glass beside it) + vec2 span; + uvec4 refs = uvec4(0u); + if (snSpan(slot, uv, span)) + { + snSlot = int(slot); + snMap = map; + snBig = (textureSize(raindropsatlas, 0).x >= 2048); + refs = snList(uv, span, max(rect.z / float(size.x), rect.w / float(size.y))); + } + water_cells[index] = refs.x; + water_cells[index + 1u] = refs.y; + water_cells[index + 2u] = refs.z; + water_cells[index + 3u] = refs.w; +} diff --git a/simulation/blackboxrecorder.cpp b/simulation/blackboxrecorder.cpp index b30d8a6c7..15c326a49 100644 --- a/simulation/blackboxrecorder.cpp +++ b/simulation/blackboxrecorder.cpp @@ -25,6 +25,8 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/physicslog.h" #include "utilities/utilities.h" +#include "world/stationnames.h" +#include "physics/vehicle.h" #include #include @@ -64,32 +66,32 @@ std::string text_of(std::string_view const Win1250) { blackbox::driver driver_of(TDynamicObject const &Vehicle) { if (Vehicle.Mechanik == nullptr) return blackbox::driver::none; - return Vehicle.Mechanik->AIControllFlag ? blackbox::driver::ai : blackbox::driver::human; + return Vehicle.Mechanik->AIControllFlag() ? blackbox::driver::ai : blackbox::driver::human; } // the switches of the user's train: those of its own vehicle, and those of the one with the motors it drives -std::uint32_t devices_of(TMoverParameters const &Occupied, TMoverParameters const &Controlling) { +std::uint32_t devices_of(physics::Vehicle const &Occupied, physics::Vehicle const &Controlling) { namespace device = blackbox::cab_devices; auto const on{[](bool const State, std::uint32_t const Bit) { return State ? Bit : 0u; }}; - return on(Occupied.Battery || Controlling.Battery, device::battery) | on(Controlling.Mains, device::main_breaker) | - on(Controlling.Pantographs[end::front].is_active, device::pantograph_front) | on(Controlling.Pantographs[end::rear].is_active, device::pantograph_rear) | - on(Controlling.ConverterFlag, device::converter) | on(Controlling.CompressorFlag, device::compressor) | on(Controlling.StLinFlag, device::line_contactors) | - on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose, device::sanding) | on(Occupied.WarningSignal != 0, device::horn) | - on(false == Occupied.Doors.instances[side::left].is_closed, device::doors_left) | - on(false == Occupied.Doors.instances[side::right].is_closed, device::doors_right) | on(Occupied.Radio, device::radio) | - on(Controlling.Heating, device::heating) | on(Occupied.SpringBrake.IsActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | + return on(Occupied.lowVoltage.IsBatteryOn() || Controlling.lowVoltage.IsBatteryOn(), device::battery) | on(Controlling.lineBreaker.IsClosed(), device::main_breaker) | + on(Controlling.pantographs[VehicleEnd::front].is_active, device::pantograph_front) | on(Controlling.pantographs[VehicleEnd::rear].is_active, device::pantograph_rear) | + on(Controlling.converter.IsRunning(), device::converter) | on(Controlling.air.compressor.IsRunning(), device::compressor) | on(Controlling.lineContactors.IsClosed(), device::line_contactors) | + on(Controlling.FuseFlag, device::overload_relay) | on(Controlling.SandDose(), device::sanding) | on(Occupied.WarningSignal() != 0, device::horn) | + on(false == Occupied.Doors.instances[VehicleSide::left].is_closed, device::doors_left) | + on(false == Occupied.Doors.instances[VehicleSide::right].is_closed, device::doors_right) | on(Occupied.Radio(), device::radio) | + on(Controlling.trainHeating.IsOn(), device::heating) | on(Occupied.brakes.spring.isActive, device::spring_brake) | on(Controlling.ShuntMode, device::shunt_mode) | // the doors as the cab works them: the permits, the departure signal, the steps and the lock - on(Occupied.DepartureSignal, device::departure_signal) | on(Occupied.Doors.instances[side::left].open_permit, device::door_permit_left) | - on(Occupied.Doors.instances[side::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | + on(Occupied.DepartureSignal(), device::departure_signal) | on(Occupied.Doors.instances[VehicleSide::left].open_permit, device::door_permit_left) | + on(Occupied.Doors.instances[VehicleSide::right].open_permit, device::door_permit_right) | on(Occupied.Doors.step_enabled, device::door_step) | on(Occupied.Doors.lock_enabled, device::door_lock) | on(Occupied.Doors.is_locked, device::doors_locked) | - on(Occupied.Hamulec != nullptr && Occupied.Hamulec->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | + on(Occupied.brakes.distributor != nullptr && Occupied.brakes.distributor->Releaser(), device::brake_releaser) | on(Controlling.FuelPump.is_active, device::fuel_pump) | on(Controlling.OilPump.is_active, device::oil_pump) | - on(Controlling.MotorBlowers[end::front].is_active || Controlling.MotorBlowers[end::rear].is_active, device::motor_blowers) | - on(Controlling.dizel_heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); + on(Controlling.MotorBlowers[VehicleEnd::front].is_active || Controlling.MotorBlowers[VehicleEnd::rear].is_active, device::motor_blowers) | + on(Controlling.diesel.heat.engine_is_hot, device::engine_hot) | on(Controlling.SpeedCtrl() && Controlling.SpeedCtrlUnit.IsActive, device::speed_control); } -std::uint8_t engine_of(TMoverParameters const &Mover) { - switch (Mover.EngineType) { +std::uint8_t engine_of(physics::Vehicle const &Physics) { + switch (Physics.EngineType) { case TEngineType::ElectricSeriesMotor: return blackbox::engines::electric; case TEngineType::ElectricInductionMotor: @@ -107,10 +109,10 @@ std::uint8_t engine_of(TMoverParameters const &Mover) { // the lights at an end of the train: of its head or of its tail, at the end of that vehicle turned away from the rest std::uint16_t outward_lights(TDynamicObject const *Vehicle, bool const Head) { - if (Vehicle == nullptr || Vehicle->MoverParameters == nullptr) + if (Vehicle == nullptr || Vehicle->physics == nullptr) return 0; auto const along{Vehicle->iDirection > 0}; - return static_cast(Vehicle->MoverParameters->iLights[Head == along ? end::front : end::rear]); + return static_cast(Vehicle->physics->LitLights()[Head == along ? VehicleEnd::front : VehicleEnd::rear]); } // the lamps the vehicle has at that end: the driver checks a pattern against those of it there are @@ -118,7 +120,7 @@ std::uint16_t outward_lamps(TDynamicObject const *Vehicle, bool const Head) { if (Vehicle == nullptr) return 0; auto const along{Vehicle->iDirection > 0}; - return static_cast(Vehicle->LightList(Head == along ? end::front : end::rear)); + return static_cast(Vehicle->LightList(Head == along ? VehicleEnd::front : VehicleEnd::rear)); } // the scenario file without the starter's $, the folders and the extension, safe for a file name @@ -204,9 +206,9 @@ bool coupled(TDynamicObject const *From, TDynamicObject const *To) { auto side{start}; // going on away from the first vehicle: through the coupler opposite the one each was reached by for (int step = 0; step < 1000 && vehicle != nullptr; ++step) { - auto const *mover{vehicle->MoverParameters}; - auto const &neighbour{mover->Neighbours[side]}; - if (mover->Couplers[side].CouplingFlag == 0 || neighbour.vehicle == nullptr) + auto const *physics{vehicle->physics}; + auto const &neighbour{physics->Neighbours[side]}; + if (physics->Couplers[side].CouplingFlag.Empty() || neighbour.vehicle == nullptr) break; if (neighbour.vehicle == To) return true; @@ -223,7 +225,7 @@ blackbox::vehicle_state state_of(TDynamicObject const &Vehicle, std::uint32_t co state.position = glm::vec3{Vehicle.GetPosition()}; auto const front{Vehicle.VectorFront()}; state.heading = static_cast(std::atan2(front.x, front.z)); - state.speed_kmh = static_cast(Vehicle.MoverParameters->V * 3.6); + state.speed_kmh = static_cast(Vehicle.physics->V() * 3.6); state.driving = driver_of(Vehicle); return state; } @@ -392,8 +394,9 @@ void blackbox_recorder::write_map() { if (values == nullptr) continue; auto const &text{values->input_text()}; + // the name in the form the station records and the rows of the timetable have theirs, as it always was if (text.starts_with(stoppoint)) - m_writer->stop_point(stoppoints++, text_of(std::string_view{text}.substr(stoppoint.size())), values->input_location(), + m_writer->stop_point(stoppoints++, text_of(timetable::station_ascii(text.substr(stoppoint.size()))), values->input_location(), static_cast(values->input_value(1)), static_cast(values->input_value(2)), heading_of(values->input_location())); else if (text == "Warning_signal") m_writer->horn_point(hornpoints++, text_of(values->name()), values->input_location(), static_cast(values->input_value(1)), @@ -412,7 +415,7 @@ void blackbox_recorder::write_cab() { if (train == nullptr || train->Dynamic() == nullptr) return; auto const *vehicle{train->Dynamic()}; - auto const *occupied{vehicle->MoverParameters}; + auto const *occupied{vehicle->physics}; // the one which drives the consist, as the driving aid tells it auto const *owner{vehicle->ctOwner != nullptr ? vehicle->ctOwner : vehicle->Mechanik}; auto const *controlling{owner != nullptr ? owner->Controlling() : occupied}; @@ -421,78 +424,78 @@ void blackbox_recorder::write_cab() { sample.time = m_time; sample.vehicle = vehicle_id(vehicle); sample.position = vehicle->GetPosition(); - sample.speed_kmh = static_cast(occupied->V * 3.6); + sample.speed_kmh = static_cast(occupied->V() * 3.6); // of the wheels as they turn, which the speedometer shows: apart from that of the vehicle when they slip or skid. // those of the powered vehicle, as the speedometer has it (TTrain::DynamicSet), which in a unit driven from an // unpowered car is another one, maybe facing the other way: signed as the occupied one's speed // the vehicle itself, if none in the unit is powered auto const *powered{train->Dynamic()->FindPowered()}; auto const facing{powered->DirectionGet() * vehicle->DirectionGet()}; - sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->MoverParameters->WheelDiameter * powered->MoverParameters->nrot * 3.6); - sample.acceleration = static_cast(controlling->AccS); - sample.lateral_acceleration = static_cast(occupied->AccN); + sample.wheel_speed_kmh = static_cast(facing * M_PI * powered->physics->WheelDiameter() * powered->physics->nrot() * 3.6); + sample.acceleration = static_cast(controlling->AccS()); + sample.lateral_acceleration = static_cast(occupied->AccN()); if (owner != nullptr && owner->is_train()) { auto const order{owner->order_current()}; - sample.movement = (order & Obey_train) != 0 ? blackbox::movements::train : - (order & (Shunt | Loose_shunt | Connect)) != 0 ? blackbox::movements::shunting : blackbox::movements::other; - sample.light_hint_head = static_cast(owner->light_hint(end::front)); - sample.light_hint_tail = static_cast(owner->light_hint(end::rear)); + sample.movement = order.HasAny(DriverOrder::obeyTrain) ? blackbox::movements::train : + order.HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) ? blackbox::movements::shunting : blackbox::movements::other; + sample.light_hint_head = static_cast(owner->light_hint(VehicleEnd::front)); + sample.light_hint_tail = static_cast(owner->light_hint(VehicleEnd::rear)); } - sample.odometer_km = static_cast(occupied->DistCounter); + sample.odometer_km = static_cast(occupied->DistCounter()); sample.driving = driver_of(*vehicle); sample.flags = (FreeFlyModeFlag ? 0 : blackbox::cab_flags::in_cab) | (owner != nullptr && owner->is_active() ? blackbox::cab_flags::ai_valid : 0) | (controlling->SecuritySystem.is_blinking() ? blackbox::cab_flags::alerter_blinking : 0) | - (controlling->SecuritySystem.is_beeping() ? blackbox::cab_flags::alerter_beeping : 0) | (controlling->SlippingWheels ? blackbox::cab_flags::wheel_slip : 0) | - (occupied->RadioStopFlag ? blackbox::cab_flags::radio_stop : 0) | (occupied->AlarmChainFlag ? blackbox::cab_flags::alarm_chain : 0); - sample.main_controller = static_cast(controlling->MainCtrlPos); - sample.scnd_controller = static_cast(controlling->ScndCtrlPos); + (controlling->SecuritySystem.is_beeping() ? blackbox::cab_flags::alerter_beeping : 0) | (controlling->SlippingWheels() ? blackbox::cab_flags::wheel_slip : 0) | + (occupied->RadioStopFlag() ? blackbox::cab_flags::radio_stop : 0) | (occupied->brakes.alarmChain ? blackbox::cab_flags::alarm_chain : 0); + sample.main_controller = static_cast(controlling->MainCtrlPos()); + sample.scnd_controller = static_cast(controlling->ScndCtrlPos()); sample.reverser = static_cast(controlling->DirActive); - sample.train_brake = static_cast(occupied->fBrakeCtrlPos); - sample.local_brake = static_cast(occupied->LocalBrakePosA); - sample.brake_cylinder = static_cast(occupied->BrakePress); - sample.brake_pipe = static_cast(occupied->PipePress); + sample.train_brake = static_cast(occupied->brakes.HandlePositionSmooth()); + sample.local_brake = static_cast(occupied->brakes.IndependentPosition()); + sample.brake_cylinder = static_cast(occupied->brakes.cylinderPressure); + sample.brake_pipe = static_cast(occupied->brakePipe.Pressure()); sample.motor_current = static_cast(controlling->Im); if (owner != nullptr && owner->is_active()) sample.ai = owner->ai_reference(); sample.devices = devices_of(*occupied, *controlling); - sample.main_reservoir = static_cast(controlling->Compressor); + sample.main_reservoir = static_cast(controlling->air.MainReservoirPressure()); sample.voltage = static_cast(controlling->EngineVoltage); sample.engine_rpm = static_cast(std::abs(controlling->enrot) * 60.0); // the lights at the ends of the train: of the vehicles at its ends, at their ends turned away from the rest - sample.lights_head = outward_lights(owner != nullptr ? owner->Vehicle(end::front) : vehicle, true); - sample.lights_tail = outward_lights(owner != nullptr ? owner->Vehicle(end::rear) : vehicle, false); - sample.equipped_head = outward_lamps(owner != nullptr ? owner->Vehicle(end::front) : vehicle, true); - sample.equipped_tail = outward_lamps(owner != nullptr ? owner->Vehicle(end::rear) : vehicle, false); + sample.lights_head = outward_lights(owner != nullptr ? owner->Vehicle(VehicleEnd::front) : vehicle, true); + sample.lights_tail = outward_lights(owner != nullptr ? owner->Vehicle(VehicleEnd::rear) : vehicle, false); + sample.equipped_head = outward_lamps(owner != nullptr ? owner->Vehicle(VehicleEnd::front) : vehicle, true); + sample.equipped_tail = outward_lamps(owner != nullptr ? owner->Vehicle(VehicleEnd::rear) : vehicle, false); auto const &security{controlling->SecuritySystem}; namespace flag = blackbox::security_flags; sample.security = static_cast((security.is_vigilance_blinking() ? flag::vigilance : 0) | (security.is_cabsignal_blinking() ? flag::cabsignal : 0) | (security.is_beeping() ? flag::vigilance_beeping : 0) | (security.is_cabsignal_beeping() ? flag::cabsignal_beeping : 0) | (security.is_braking() ? flag::braking : 0)); - sample.cab = static_cast(occupied->CabOccupied); + sample.cab = static_cast(occupied->CabOccupied()); // what drives the train, the setting of the brakes, the radio, the engine's oil and temperatures sample.engine = engine_of(*controlling); - sample.brake_delay = static_cast(occupied->BrakeDelayFlag); + sample.brake_delay = static_cast(occupied->brakes.delaySetting); // the const one: with no driver the first channel sample.radio_channel = static_cast(std::clamp(std::as_const(*train).RadioChannel(), 0, 255)); - sample.driver_valve = occupied->Handle != nullptr ? static_cast(occupied->Handle->GetCP()) : 0.0f; - sample.feed_pipe = static_cast(occupied->ScndPipePress); + sample.driver_valve = occupied->brakes.driverValve != nullptr ? static_cast(occupied->brakes.driverValve->GetCP()) : 0.0f; + sample.feed_pipe = static_cast(occupied->mainPipe.Pressure()); sample.oil_pressure = controlling->OilPump.pressure; - sample.water_temperature = controlling->dizel_heat.Twy; - sample.oil_temperature = controlling->dizel_heat.To; - sample.engine_temperature = controlling->dizel_heat.Ts; - sample.speed_control_kmh = controlling->SpeedCtrl ? static_cast(controlling->SpeedCtrlUnit.DesiredVelocity) : 0.0f; + sample.water_temperature = controlling->diesel.heat.Twy; + sample.oil_temperature = controlling->diesel.heat.To; + sample.engine_temperature = controlling->diesel.heat.Ts; + sample.speed_control_kmh = controlling->SpeedCtrl() ? static_cast(controlling->SpeedCtrlUnit.DesiredVelocity) : 0.0f; sample.engine_power = static_cast(controlling->EnginePower); - sample.hand_brake = static_cast(std::clamp(occupied->ManualBrakePos, -128, 127)); - sample.brake_mode = static_cast(occupied->BrakeOpModeFlag); - sample.horn = static_cast(occupied->WarningSignal); + sample.hand_brake = static_cast(std::clamp(occupied->brakes.HandBrakePosition(), -128, 127)); + sample.brake_mode = static_cast(occupied->brakes.operatingMode); + sample.horn = static_cast(occupied->WarningSignal()); sample.integrated_controller = static_cast(controlling->eimic); - sample.clutch = static_cast(controlling->dizel_engagestate); - sample.converter_fill = static_cast(controlling->hydro_TC_Fill); + sample.clutch = static_cast(controlling->diesel.clutchState); + sample.converter_fill = static_cast(controlling->torqueConverter.fill); // the brakes of the whole train: the highest of its cylinders, from the head to the tail - auto brakes{occupied->BrakePress}; - for (auto const *each{owner != nullptr ? owner->Vehicle(end::front) : nullptr}; each != nullptr; each = each->Next()) - if (each->MoverParameters != nullptr) - brakes = std::max(brakes, each->MoverParameters->BrakePress); + auto brakes{occupied->brakes.cylinderPressure}; + for (auto const *each{owner != nullptr ? owner->Vehicle(VehicleEnd::front) : nullptr}; each != nullptr; each = each->Next()) + if (each->physics != nullptr) + brakes = std::max(brakes, each->physics->brakes.cylinderPressure); sample.consist_brake_cylinder = static_cast(brakes); m_writer->cab(sample); } @@ -525,7 +528,7 @@ void blackbox_recorder::look_around(bool const Keyframe) { auto *train{simulation::Train}; auto const uservehicle{train != nullptr && train->Dynamic() != nullptr ? vehicle_id(train->Dynamic()) : blackbox::no_vehicle}; auto const userincab{uservehicle != blackbox::no_vehicle && false == FreeFlyModeFlag}; - auto const usercab{uservehicle != blackbox::no_vehicle ? static_cast(train->Dynamic()->MoverParameters->CabOccupied) : std::int8_t{0}}; + auto const usercab{uservehicle != blackbox::no_vehicle ? static_cast(train->Dynamic()->physics->CabOccupied()) : std::int8_t{0}}; if (false == m_userknown || uservehicle != m_uservehicle || userincab != m_userincab || usercab != m_usercab) { m_writer->user_vehicle(m_time, uservehicle, userincab, usercab); m_uservehicle = uservehicle; @@ -542,6 +545,7 @@ void blackbox_recorder::look_around(bool const Keyframe) { look_at_vehicles(Keyframe); auto const vehicles{clock::now()}; look_at_couplers(); + look_at_derailments(); auto const couplers{clock::now()}; look_at_switches(); auto const switches{clock::now()}; @@ -555,17 +559,70 @@ void blackbox_recorder::look_around(bool const Keyframe) { } } +namespace { + +std::uint8_t cause_of(derail_motion::cause const Cause) { + switch (Cause) { + case derail_motion::cause::overturned: + return blackbox::derailment_causes::overturned; + case derail_motion::cause::end_of_track: + return blackbox::derailment_causes::end_of_track; + case derail_motion::cause::pulled_off: + return blackbox::derailment_causes::pulled_off; + case derail_motion::cause::collision: + return blackbox::derailment_causes::collision; + default: + return blackbox::derailment_causes::flange_climbed; + } +} + +} // namespace + +void blackbox_recorder::look_at_derailments() { + for (auto *vehicle : simulation::Vehicles.sequence()) { + if (false == vehicle->bEnabled) + continue; + auto const &motion{vehicle->physics->OffTrack}; + auto const id{vehicle_id(vehicle)}; + auto &entry{m_vehicles[vehicle]}; + if (false == motion.active()) { + entry.derailment = 0; + continue; + } + auto const phase{motion.at_rest() ? 2 : 1}; + if (entry.derailment >= phase) + continue; + blackbox::derailment_state state; + state.time = m_time; + state.vehicle = id; + state.cause = cause_of(motion.reason()); + state.position = vehicle->GetPosition(); + state.heading = static_cast(std::atan2(vehicle->VectorFront().x, vehicle->VectorFront().z)); + state.speed_kmh = static_cast(vehicle->physics->V() * 3.6); + state.offset = static_cast(vehicle->off_track_offset()); + state.roll = static_cast(motion.roll()); + state.travelled = static_cast(motion.travelled()); + state.lying = motion.lying(); + // seen first at rest, it left the track before + for (auto written = entry.derailment + 1; written <= phase; ++written) { + state.phase = (written == 1 ? blackbox::derailment_phases::left_track : blackbox::derailment_phases::at_rest); + m_writer->derailment(state); + } + entry.derailment = phase; + } +} + void blackbox_recorder::look_at_couplers() { for (auto *vehicle : simulation::Vehicles.sequence()) { if (false == vehicle->bEnabled) continue; auto &entry{m_vehicles[vehicle]}; - auto const *mover{vehicle->MoverParameters}; + auto const *physics{vehicle->physics}; for (int side = 0; side < 2; ++side) { - auto const flags{mover->Couplers[side].CouplingFlag}; + auto const flags{physics->Couplers[side].CouplingFlag}; // a neighbour not coupled is only seen on the same track - auto const *other{flags != 0 ? mover->Neighbours[side].vehicle : nullptr}; - coupler_entry const now{other, other != nullptr ? mover->Neighbours[side].vehicle_end : 0, other != nullptr ? flags : 0}; + auto const *other{false == flags.Empty() ? physics->Neighbours[side].vehicle : nullptr}; + coupler_entry const now{other, other != nullptr ? physics->Neighbours[side].vehicle_end : 0, other != nullptr ? flags.Bits() : 0}; auto &last{entry.couplers[side]}; auto const changed{now.other != last.other || now.other_side != last.other_side || now.flags != last.flags}; auto const before{last}; @@ -589,7 +646,7 @@ void blackbox_recorder::look_at_couplers() { change.flags = static_cast(now.flags); change.previous_flags = static_cast(entry.couplers_known ? before.flags : 0); change.previous_other = entry.couplers_known ? known_id(before.other) : blackbox::no_vehicle; - change.position = vehicle->CouplerPosition(static_cast(side)); + change.position = vehicle->CouplerPosition(static_cast(side)); m_writer->coupling(change); } entry.couplers_known = true; @@ -707,11 +764,11 @@ std::uint32_t blackbox_recorder::vehicle_id(TDynamicObject const *Vehicle) { auto &entry{m_vehicles[Vehicle]}; entry.id = m_nextvehicle++; - auto const *mover{Vehicle->MoverParameters}; + auto const *physics{Vehicle->physics}; auto const *driver{Vehicle->Mechanik}; auto const train{driver != nullptr && driver->TrainName() != "none" ? driver->TrainName() : std::string{}}; - m_writer->vehicle({entry.id, text_of(Vehicle->name()), text_of(mover->TypeName), text_of(train), static_cast(mover->Dim.L), static_cast(mover->Dim.W), - static_cast(mover->CategoryFlag)}); + m_writer->vehicle({entry.id, text_of(Vehicle->name()), text_of(physics->TypeName), text_of(train), static_cast(physics->Dim.L), static_cast(physics->Dim.W), + static_cast(physics->CategoryFlag)}); return entry.id; } @@ -720,8 +777,9 @@ std::uint32_t blackbox_recorder::known_id(TDynamicObject const *Vehicle) { return Vehicle != nullptr && Vehicle->bEnabled ? vehicle_id(Vehicle) : blackbox::no_vehicle; } -std::uint32_t blackbox_recorder::signal_at(glm::dvec3 const &Location) const { - auto const found{std::ranges::find_if(m_signals, [&Location](signal_entry const &Signal) { return glm::distance(Signal.location, Location) < 0.01; })}; +std::uint32_t blackbox_recorder::signal_of(TMemCell const *Cell) const { + // by the memory cell, not by its position: two signals can have their cells at one point + auto const found{std::ranges::find(m_signals, Cell, &signal_entry::cell)}; if (found == m_signals.end()) return blackbox::no_signal; return static_cast(std::distance(m_signals.begin(), found)); @@ -750,7 +808,7 @@ void blackbox_recorder::signal_passed(TDynamicObject const *Vehicle, basic_event if (m_writer == nullptr || Vehicle == nullptr) return; auto const location{Event.input_location()}; - m_writer->signal_passed({m_time, vehicle_id(Vehicle), signal_at(location), text_of(Event.name()), location, static_cast(Speed1), static_cast(Speed2), + m_writer->signal_passed({m_time, vehicle_id(Vehicle), signal_of(Event.input_cell()), text_of(Event.name()), location, static_cast(Speed1), static_cast(Speed2), static_cast(Trainspeed), static_cast(Overrun), Flags}); } diff --git a/simulation/blackboxrecorder.h b/simulation/blackboxrecorder.h index a3aaf5d0f..cdc61da61 100644 --- a/simulation/blackboxrecorder.h +++ b/simulation/blackboxrecorder.h @@ -69,6 +69,8 @@ private: bool listed{false}; std::array couplers; // as seen last bool couplers_known{false}; + // off the track: 0 not, 1 written as leaving it, 2 written as at rest + int derailment{0}; }; struct switch_entry { TTrack *track{nullptr}; @@ -99,6 +101,8 @@ private: void look_at_signals(); // the couplers of every vehicle against the last look: those coupled at the first look, then the changes void look_at_couplers(); + // the vehicles leaving the track and coming to rest off it (physics.derailment new) + void look_at_derailments(); void write_camera(); // the timetable of the train the user is in, written again when it is another one; none isn't written void look_at_timetable(TDynamicObject const &Vehicle, std::uint32_t Id); @@ -106,7 +110,8 @@ private: std::uint32_t vehicle_id(TDynamicObject const *Vehicle); // the number of a vehicle still on the scenery, no_vehicle for none or one taken off it std::uint32_t known_id(TDynamicObject const *Vehicle); - std::uint32_t signal_at(glm::dvec3 const &Location) const; + // the number of the signal whose aspect the memory cell tells, no_signal for one which isn't on the map + std::uint32_t signal_of(TMemCell const *Cell) const; std::mutex m_mutex; std::array m_filebuffer{}; diff --git a/simulation/simulation.cpp b/simulation/simulation.cpp index 25c5cf29a..360f2544f 100644 --- a/simulation/simulation.cpp +++ b/simulation/simulation.cpp @@ -37,6 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "world/catenary_scene.h" +#include "physics/vehicle.h" namespace simulation { @@ -148,6 +149,8 @@ state_manager::update( double const Deltatime, int Iterationcount ) { simulation::Roadpoints.update( totaltime ); Timer::subsystem.sim_roads.stop(); simulation::Vehicles.update( Deltatime, Iterationcount ); + // the tracks the heat buckles, by itself or under the trains just moved + TTrack::update_buckling( totaltime ); } void @@ -241,13 +244,13 @@ void state_manager::process_commands() { TDynamicObject *vehicle = found_vehicle; while (vehicle) { - vehicle->MoverParameters->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); + vehicle->physics->brakes.distributor->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); vehicle = vehicle->Next(); } vehicle = found_vehicle; while (vehicle) { - vehicle->MoverParameters->Hamulec->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); + vehicle->physics->brakes.distributor->Releaser(commanddata.action != GLFW_RELEASE ? 1 : 0); vehicle = vehicle->Prev(); } } @@ -312,7 +315,7 @@ void state_manager::process_commands() { targetvehicle->ctOwner == currentvehicle->Mechanik || targetvehicle->ctOwner == currentvehicle->ctOwner }; auto const isincharge{ currentvehicle->Mechanik->primary() }; - auto const aidriveractive{ currentvehicle->Mechanik->AIControllFlag }; + auto const aidriveractive{ currentvehicle->Mechanik->AIControllFlag() }; // TODO: support for primary mode request passed as commanddata.param1 if( !sameconsist && isincharge ) { // oddajemy dotychczasowy AI @@ -435,14 +438,12 @@ void state_manager::process_commands() { } while (vehicle) { - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; - vehicle->MoverParameters->V = 0.000001; // HACK: force vehicle position re-calculation - vehicle->MoverParameters->DistCounter = 0.0; - vehicle->MoverParameters->WheelFlat = 0.0; - vehicle->MoverParameters->AlarmChainFlag = false; - vehicle->MoverParameters->OffsetTrackH = 0.0; - vehicle->MoverParameters->OffsetTrackV = 0.0; + // no damage, back on the rails with the state of the derailment cleared + vehicle->physics->repair_damage(); + vehicle->physics->SetV(0.000001); // HACK: force vehicle position re-calculation + vehicle->physics->SetDistCounter(0.0); + vehicle->physics->SetOffsetTrackH(0.0); + vehicle->physics->SetOffsetTrackV(0.0); // pantographs for( auto idx = 0; idx < vehicle->iAnimType[ ANIM_PANTS ]; ++idx ) { @@ -463,13 +464,13 @@ void state_manager::process_commands() { if (commanddata.command == user_command::repaircoupler) { if (auto *vehicle{simulation::Vehicles.find(commanddata.payload)}; vehicle != nullptr) { - vehicle->MoverParameters->repair_coupler(static_cast(commanddata.param1) == end::rear ? end::rear : end::front); + vehicle->physics->repair_coupler(EndOf(static_cast(commanddata.param1)) == VehicleEnd::rear ? VehicleEnd::rear : VehicleEnd::front); } } if (commanddata.command == user_command::fillcompressor) { TDynamicObject *vehicle = simulation::Vehicles.find(commanddata.payload); - vehicle->MoverParameters->CompressedVolume = 8.0f * vehicle->MoverParameters->VeselVolume; + vehicle->physics->air.Fill(8.0f * vehicle->physics->air.config.mainReservoirVolume); } if (commanddata.command == user_command::dynamicmove) { @@ -499,7 +500,7 @@ void state_manager::process_commands() { double offset = 0.0; while (vehicle) { - offset += vehicle->MoverParameters->Dim.L; + offset += vehicle->physics->Dim.L; vehicle->place_on_track(track, offset, false); vehicle = vehicle->Prev(); } @@ -512,7 +513,7 @@ void state_manager::process_commands() { if (commanddata.command == user_command::pullalarmchain) { TDynamicObject *vehicle = simulation::Vehicles.find(commanddata.payload); if (vehicle) - vehicle->MoverParameters->AlarmChainSwitch(true); + vehicle->physics->AlarmChainSwitch(true); } if (commanddata.command == user_command::sendaicommand) { diff --git a/simulation/simulationstateserializer.cpp b/simulation/simulationstateserializer.cpp index 2d8541d7f..848e1d655 100644 --- a/simulation/simulationstateserializer.cpp +++ b/simulation/simulationstateserializer.cpp @@ -37,6 +37,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/utilities.h" #include "editor/editorTerrainStreamer.hpp" +#include "physics/vehicle.h" #include @@ -46,7 +47,7 @@ namespace { double vehicle_length( std::string const &Folder, std::string const &Type ) { - TMoverParameters probe( 0.0, Type, Type, 0 ); + physics::Vehicle probe( 0.0, Type, Type, 0 ); return probe.LoadFIZ( paths::dynamic + Folder + "/" ) ? probe.Dim.L : 0.0; } @@ -272,8 +273,8 @@ state_serializer::deserialize_assignment( cParser &Input, scene::scratch_data &S while( false == token.empty() && token != "endassignment" ) { // assignment is expected to come as string pairs: language id and the actual assignment enclosed in quotes to form a single token - auto assignment{ Input.getToken() }; - win1250_to_ascii( assignment ); + // the assignment is only shown to the player, so it's kept with its letters, in utf-8 as the user interface takes it + auto const assignment{ data_text_to_utf8( Input.getToken() ) }; Scratchpad.trainset.assignment.emplace( token, assignment ); token = Input.getToken(); } @@ -384,8 +385,9 @@ state_serializer::deserialize_camera( cParser &Input, scene::scratch_data &Scrat void state_serializer::deserialize_config( cParser &Input, scene::scratch_data &Scratchpad ) { - // config parameters (re)definition - Global.ConfigParse( Input ); + // config parameters (re)definition, but for what only eu07.ini sets: programs to run, connections, the sandbox of + // the scripts (utilities/inionlysettings.h) + Global.ConfigParse( Input, config_source::scenery ); if( Global.test.enabled ) { // a scenery doesn't get to turn on what a test keeps off simulation::apply_test_mode_settings(); @@ -427,7 +429,8 @@ void state_serializer::deserialize_lua( cParser &Input, scene::scratch_data &Scr std::string file; Input >> file; #ifdef WITH_LUA - simulation::Lua.interpret(Global.asCurrentSceneryPath + file); + // the file is relative to the scenery folder, and stays inside it + simulation::Lua.interpret(Global.asCurrentSceneryPath, file); #else ErrorLog(file + ": lua scripts not supported in this build."); #endif @@ -446,7 +449,13 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc // TBD: postpone loading furter and only load required blocks during the simulation? if (false == Scratchpad.binary.terrain_included) { - Region->deserialize(Scratchpad.name); + if (false == Region->deserialize(Scratchpad.name)) + { + // the file looked whole to is_scene() but its content is damaged. the geometry it holds is missing from this + // session, as the text definitions were skipped already. the file is the game's own copy of the text, so it + // goes, and the next start loads the text and writes it anew + Region->discard_scene(Scratchpad.name); + } } else { @@ -467,6 +476,9 @@ state_serializer::deserialize_firstinit( cParser &Input, scene::scratch_data &Sc Scratchpad.binary.terrain_binaryfiles.clear(); simulation::Paths.InitTracks(); + if( Global.track_check ) { + simulation::Paths.CheckTracks(); + } // the roads tie up their own lanes where they gain or lose some, the junctions tie the lanes of the roads together, // what's left loose after that gets closed by the roads simulation::Roads.InitLanes(); @@ -567,9 +579,9 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch ErrorLog( "Bad scenario: duplicate vehicle name \"" + vehicle->name() + "\" defined in file \"" + Input.Name() + "\" (line " + std::to_string( inputline ) + ")" ); } - if( vehicle->MoverParameters->CategoryFlag == 1 // trains only - && ( (vehicle->LightList(end::front) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 - || (vehicle->LightList(end::rear) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 ) ) { + if( vehicle->physics->CategoryFlag == 1 // trains only + && ( (vehicle->LightList(VehicleEnd::front) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 + || (vehicle->LightList(VehicleEnd::rear) & (light::headlight_left | light::headlight_right | light::headlight_upper)) != 0 ) ) { simulation::Lights.insert( vehicle ); } } @@ -598,7 +610,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "road" ) { auto *road { new road_node( nodedata ) }; - road->import( + road->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -637,7 +649,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "sweep" ) { auto *sweep { new sweep_node( nodedata ) }; - sweep->import( + sweep->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -651,7 +663,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( nodedata.type == "junction" ) { auto *junction { new junction_node( nodedata ) }; - junction->import( + junction->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -683,7 +695,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch else if( roadpoint_node::is_keyword( nodedata.type ) ) { // level crossing, or a point where road vehicles appear or are taken away auto *point { new roadpoint_node( nodedata ) }; - point->import( + point->import_from( Input, ( Scratchpad.location.offset.empty() ? glm::dvec3 { 0.0 } : @@ -784,7 +796,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch if( false == skip ) { ++Scratchpad.binary.geometry_imported; - auto shape { scene::shape_node().import( Input, nodedata ) }; + auto shape { scene::shape_node().import_from( Input, nodedata ) }; material = shape.data().material; if( true == Global.editor_session ) { shape.source_file( scene::terrain_file::reference_of( Input.Name() ) ); @@ -822,7 +834,7 @@ state_serializer::deserialize_node( cParser &Input, scene::scratch_data &Scratch ++Scratchpad.binary.geometry_imported; simulation::Region->insert( - scene::lines_node().import( + scene::lines_node().import_from( Input, nodedata ), Scratchpad ); } @@ -1466,7 +1478,7 @@ state_serializer::deserialize_endtrainset( cParser &Input, scene::scratch_data & 0, nullptr ); } - if( Scratchpad.trainset.couplings.back() == coupling::faux ) { + if( Scratchpad.trainset.couplings.back() == 0 ) { // no coupling // jeśli ostatni pojazd ma sprzęg 0 to założymy mu końcówki blaszane (jak AI się odpali, to sobie poprawi) // place end signals only on trains without a driver, activate markers otherwise Scratchpad.trainset.vehicles.back()->RaLightsSet( @@ -1613,12 +1625,12 @@ state_serializer::deserialize_dynamic( cParser &Input, scene::scratch_data &Scra auto coupling = couplingdatawithparams != std::string::npos ? std::atoi(couplingdata.substr(0, couplingdatawithparams).c_str()) : std::atoi(couplingdata.c_str()); if( coupling < 0 ) { // sprzęg zablokowany (pojazdy nierozłączalne przy manewrach) - coupling = -coupling | coupling::permanent; + coupling = ( CouplingSet::FromBits( -coupling ) | Coupling::permanent ).Bits(); } if( offset != -1.0 && std::abs(offset) > 0.5 ) { // maksymalna odległość między sprzęgami - do przemyślenia // likwidacja sprzęgu, jeśli odległość zbyt duża - to powinno być uwzględniane w fizyce sprzęgów... - coupling = coupling::faux; + coupling = 0; // no coupling } auto const params = couplingdatawithparams != std::string::npos ? couplingdata.substr(couplingdatawithparams + 1) : ""; // load amount and type @@ -1680,8 +1692,8 @@ state_serializer::deserialize_dynamic( cParser &Input, scene::scratch_data &Scra } // automatically establish permanent connections for couplers which specify them in their definitions if( coupling != 0 - && vehicle->MoverParameters->Couplers[(offset == -1.0 ? end::front : end::rear)].AllowedFlag & coupling::permanent ) { - coupling |= coupling::permanent; + && vehicle->physics->Couplers[(offset == -1.0 ? VehicleEnd::front : VehicleEnd::rear)].AllowedFlag & Coupling::permanent ) { + coupling = ( CouplingSet::FromBits( coupling ) | Coupling::permanent ).Bits(); } if( true == Scratchpad.trainset.is_open ) { Scratchpad.trainset.vehicles.emplace_back( vehicle ); diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index 1c6c90535..a247918aa 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -90,8 +90,10 @@ void apply_test_mode_settings() Global.iMultiplayer = 0; Global.exec_on_exit.clear(); // and the same way every time, unless given another seed (-seed, or randomseed in the settings) - if (!Global.random_seed) + if (false == Global.random_seed_given) { Global.random_seed = seed_of("test"); + Global.random_seed_given = true; + } // the real time limit, which the scenery may set too test().watch_wall_clock(wall_clock_limit(Global.test.wall_timeout, Global.test.timeout)); } @@ -186,7 +188,7 @@ bool test_manager::tested_trains_at_rest() const // the consists as they are now: a train the tested one couples to joins it, one it leaves behind doesn't return std::ranges::none_of(Global.test.vehicles, [](std::string const &Name) { auto *vehicle { simulation::Vehicles.find(Name) }; - return vehicle != nullptr && vehicle->find_vehicle(coupling::coupler, is_moving) != nullptr; + return vehicle != nullptr && vehicle->find_vehicle(Coupling::coupler, is_moving) != nullptr; }); } diff --git a/starter/eu07_starter.cpp b/starter/eu07_starter.cpp index c756b51ac..b52c167b3 100644 --- a/starter/eu07_starter.cpp +++ b/starter/eu07_starter.cpp @@ -69,18 +69,42 @@ bool file_exists(std::wstring const &Path) return (attributes != INVALID_FILE_ATTRIBUTES) && ((attributes & FILE_ATTRIBUTE_DIRECTORY) == 0); } +// a path a function of the system writes to the buffer it's given (Get(buffer, size) returns the length written, or the size needed when +// the buffer is too small, or the size itself when it cut the path short), in a buffer grown until the path fits: a path longer than +// MAX_PATH (a folder with long paths enabled) isn't cut off nor taken for none. empty when there's none +template +std::wstring sized_path(Fill const &Get) +{ + std::wstring buffer(MAX_PATH, L'\0'); + while (true) + { + auto const length{static_cast(Get(buffer.data(), static_cast(buffer.size())))}; + if (length == 0) + { + return {}; + } + if (length < buffer.size()) + { + buffer.resize(length); + return buffer; + } + if (buffer.size() >= 32768) + { + // the longest path windows has + return {}; + } + buffer.resize(std::max(length + 1, buffer.size() * 2)); + } +} + std::wstring system_directory() { - wchar_t path[MAX_PATH]; - auto const length{::GetSystemDirectoryW(path, MAX_PATH)}; - return (length > 0) && (length < MAX_PATH) ? std::wstring(path, length) : std::wstring(); + return sized_path([](wchar_t *Buffer, DWORD const Size) { return ::GetSystemDirectoryW(Buffer, Size); }); } std::wstring windows_directory() { - wchar_t path[MAX_PATH]; - auto const length{::GetWindowsDirectoryW(path, MAX_PATH)}; - return (length > 0) && (length < MAX_PATH) ? std::wstring(path, length) : std::wstring(); + return sized_path([](wchar_t *Buffer, DWORD const Size) { return ::GetWindowsDirectoryW(Buffer, Size); }); } int show(std::wstring const &Text, UINT const Type) @@ -205,9 +229,7 @@ std::wstring locate(library_check const &Check, std::wstring const &Name, bool & return path; } } - wchar_t found[MAX_PATH]; - auto const length{::SearchPathW(nullptr, Name.c_str(), nullptr, MAX_PATH, found, nullptr)}; - return (length > 0) && (length < MAX_PATH) ? std::wstring(found, length) : std::wstring(); + return sized_path([&Name](wchar_t *Buffer, DWORD const Size) { return ::SearchPathW(nullptr, Name.c_str(), nullptr, Size, Buffer, nullptr); }); } // the libraries of the image and of the libraries next to the simulator, which the installation brings. the system ones are taken as they are @@ -347,16 +369,22 @@ bool check_system(std::wstring const &Simulator, std::wstring const &Directory) { runtime = runtime || is_runtime_library(lowercase(library)); } - std::wstring const text{L"The simulator can't start, these libraries are missing:" + join(check.missing)}; + // the check reads the imports itself and looks for them as the loader does, which it may not match in every case: the player can + // start the simulator anyway, and the loader has the last word + std::wstring const text{L"The simulator may not start, these libraries are missing:" + join(check.missing)}; if (runtime) { - offer_redistributable(text + L"\n\nThey belong to the Microsoft Visual C++ Redistributable.", false); + if (offer_redistributable(text + L"\n\nThey belong to the Microsoft Visual C++ Redistributable.", true)) + { + return false; + } } - else + else if (show(text + L"\n\nThe installation is incomplete: on Steam, verify the integrity of the game files, otherwise install the simulator again." + L"\n\nStart the simulator anyway?", + MB_YESNO | MB_ICONERROR | MB_DEFBUTTON2) != IDYES) { - show(text + L"\n\nThe installation is incomplete: on Steam, verify the integrity of the game files, otherwise install the simulator again.", MB_OK | MB_ICONERROR); + return false; } - return false; } #if defined(_MSC_VER) && (_MSC_VER >= 1940) @@ -443,13 +471,11 @@ wchar_t const *arguments() int WINAPI wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { - wchar_t path[MAX_PATH * 2]; - auto const length{::GetModuleFileNameW(nullptr, path, MAX_PATH * 2)}; - if ((length == 0) || (length >= MAX_PATH * 2)) + auto directory{sized_path([](wchar_t *Buffer, DWORD const Size) { return ::GetModuleFileNameW(nullptr, Buffer, Size); })}; + if (directory.empty()) { return 1; } - std::wstring directory(path, length); directory.erase(directory.find_last_of(L"\\/")); auto const simulator{directory + L"\\" + widen(EU07_SIMULATOR_EXE)}; 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/scenarios/README.md b/tests/scenarios/README.md index ea5ebc89b..9712b2f46 100644 --- a/tests/scenarios/README.md +++ b/tests/scenarios/README.md @@ -37,8 +37,10 @@ With `--test` the simulator: test mode are applied again after it, - runs the simulation as fast as it can in fixed steps of 0.03 s of simulation time per frame (three 10 ms physics steps), whatever the real time, the time speed or the machine, -- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so two - runs of a scenery come out the same (the physicslogs of two runs are byte for byte equal), +- seeds its random numbers with a fixed seed unless `-seed` or `randomseed` gives one, so, + with the fixed step above, two runs of a scenery come out the same (the physicslogs of two + runs are byte for byte equal; a seed without the fixed step isn't enough, see + [A seed alone doesn't make a run repeatable](#a-seed-alone-doesnt-make-a-run-repeatable)), - quits when the test ends, and says how it ended in the exit code and in a `test: ...` line on stdout and in the log. A command line it can't take, a start that fails, or an exception thrown by the simulator (of any type, on Linux too) ends the same way, with the @@ -135,13 +137,46 @@ Python 3.10+, no extra packages. Options: `cmake-build-*/bin/Release/eu07*.exe`. The build needs the `--test` and `-ini` command line options. - name one or more cases to run only those, e.g. `run.py ... eu07_td_timetable`. -- `-j N` runs N cases at once. Each case prints its results when it is done. All 19 cases - take about 30 s with `-j 4`, loading included. +- `-j N` runs N cases at once. Each case prints its results when it is done. The 42 cases + that aren't `slow` take about 30 s with `-j 4` and 2 minutes one at a time, loading included. - `--watch` runs a case the old way, in a visible window in real time (or faster with `--timespeed N`), closed after the case's `duration`; the exit code isn't checked then. For watching what a case does. +- `--slow` runs the cases marked `slow` too. Without it, and with no cases named, they are + skipped (and listed): each is a whole mission on a big scenery and takes many minutes. A + slow case named on the command line always runs. Run them one at a time (`-j 1`): each + simulator loads a whole scenery. A case on a mission of the base scenery with physicslog on + (`vehicle` given) removes every physicslog written in the game dir meanwhile, so with `-j N` + it runs alone, after the others. +- `--seed N` (a number or a word) runs the cases with another seed of the simulator's random + numbers (`randomseed`) than the fixed one of the test mode, for a bug that shows up only + sometimes: run the case with a few seeds. A seed repeats a run only in the test mode, see + below. -Exit code is 0 when every case passed. Logs of each run (`log.txt`, `errors.txt`, +### A seed alone doesn't make a run repeatable + +The same seed gives the same run only when every frame lasts the same simulation time. Each +frame the simulator splits the time since the last one into physics steps of at most 10 ms +(`driver_mode::update()`); outside the test mode that time comes from the wall clock (times +`timespeed`), so the number and the length of the steps follow the frame rate, and with them +the speeds, the pressures and the moments the AI decides things. Two runs of one scenery with +one seed then drift apart, the more so on a busy machine. + +- The test mode (`--test`, what `run.py` runs by default) sets a fixed step itself: 0.03 s of + simulation time per frame, three 10 ms steps, whatever the wall clock + (`Timer::set_fixed_step()` in `driver_mode::enter()`). A case run twice with the same + `--seed`, or with none, comes out the same. This is the way to repeat a run. +- `--watch` doesn't use the test mode: it runs on the wall clock, so a watched run isn't + repeatable, seed or not. Use it to look at a case, not to repeat one. +- Outside the test mode (`--watch`, or the simulator started by hand with `-seed`) the setting + `deltaoverride N` makes every frame last 1/N s of simulation time, whatever the wall clock + and `timespeed` (`Timer::set_delta_override()`). It goes in `eu07.ini`, a `-ini` file or a + case's `ini` list. In the test mode it takes the place of the 0.03 s step. Whether a watched + run with it repeats byte for byte hasn't been checked. + +Exit code is 0 when every case passed, or failed as its `xfail` mark says it does (`XFAIL` in +the summary); a case marked `xfail` that passes (`XPASS`) fails the run, so that the mark gets +removed. Logs of each run (`log.txt`, `errors.txt`, `stdout.txt`, the physicslogs of the vehicle and of other trains of the case, the black box as `autotest_.blackbox`) are moved to `tests/scenarios/out//`. @@ -171,7 +206,17 @@ The lead vehicle is named `autotest_`, so every case has its own physicslo files and cases can run in parallel. The `autotest_*` sceneries (and the simulator's `.sbt` geometry cache of them) stay in the game's `scenery/` dir; the cache is dropped when the base scenery is newer, and after a run cut short (`wall_timeout`, `error`, a crash, or killed by run.py), -which could have been writing it. +which could have been writing it. A case with `file.binary.terrain no` in its `ini` has no cache +written, and one left by an earlier run is removed. + +A case with `vehicle` runs a train of the base scenery under its own name: its physicslog is +`physicslog/.dat` (one of that name already in the game dir is replaced), and with the +physicslogs on, every train of the scenery writes one, over any of the same name; those written +during the run are deleted after it. Don't run such a case along with another one in the same game dir. + +Apart from these the game dir loses its `log.txt` and `errors.txt`, those of the last game +session: the simulator deletes them at every start, before it knows that the run's log goes +to `logs/`. ## Writing a case @@ -180,14 +225,21 @@ which could have been writing it. | key | meaning | | --- | --- | | `base_scenery` | scenery file in the game's `scenery/` dir | -| `strip_trainsets` | drop the base scenery's trainsets (default `true`) | +| `strip_trainsets` | drop the base scenery's trainsets (default `true`); `false` keeps them, for a case on one of the scenery's own missions (below) | +| `vehicle` | the train under test is this vehicle of the base scenery (its node name), instead of the `autotest_` one of the fragment: `test.vehicle`, the physicslog checked and `{{vehicle}}` are this one. With `strip_trainsets` `false` | +| `replace` | literal replacements in the text of the base scenery, a list of `[old, new]`, e.g. to put another locomotive on a mission; an `old` the scenery doesn't have is an error | +| `physicslog` | `false` turns the physicslogs (and the black box) off for the run: on a scenery with dozens of AI trains each of them would write 3-4 kB per second of simulation into the game dir. Such a case has the result of the test mode and the log checks only (default `true`) | +| `slow` | `true` marks a case that takes many minutes: skipped unless named or run with `--slow` | +| `xfail` | marks a case that fails because of a known, reported bug, with the reference and the reason as its text, e.g. `"eu07/maszyna#524: the AI never couples"`. Its failure is reported as `XFAIL` and doesn't fail the run; when it passes (`XPASS`) the run fails until the mark is removed | | `time` | replace the scenery start time, `HH:MM` | | `track_friction` | set the friction of every track of the base scenery (default in the sceneries is 0.15), e.g. for slippery rail | | `track_events` | lines added to tracks of the base scenery, by track name, e.g. `{ "tor1k": "event0 test_pass" }`; only tracks in the scenery file itself, not in its includes | | `test_config` | lines of a `config` block added to the scenery, e.g. `["test.timeout 90"]`; the block always has `test.vehicle` with the case's lead vehicle, so only its train counts for the pass and the standstill | | `ini` | extra `eu07.ini` lines for the run, after the common ones of the runner's `-ini` file, e.g. `["crashdamage yes"]` | -| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire) | +| `fragment` | `.scn` file in `cases/` added to the scenery: trainsets after `FirstInit` (before it they derail on unlinked track), the rest before it (launchers read after it never fire). Optional when the case keeps the scenery's trainsets | | `vars` | values for `{{name}}` in the fragment; a list becomes one line per item | +| `timetable` | a timetable file in `cases/` for a trainset of the fragment, for a train whose timetable no scenery of the game has: copied to the game's `scenery/` dir as `autotest_.txt` for the run and removed after it; the fragment names it `{{timetable}}` | +| `vehicle_variants` | vehicles of the case's own, made from those of the game, e.g. with a `.fiz` key the game's data doesn't have yet: a list of `{ "name": ..., "from": "/", "replace": [[old, new], ...] }`. For the run the vehicle's `.fiz`, with the literal replacements (an `old` it doesn't have is an error), and its `.mmd` are copied beside it in the game's `dynamic/` dir as `autotest__` and removed after it; the fragment names the type `{{variant_}}`, e.g. `dynamic pkp/et42_v2 112e-014-a {{variant_a}} ...`. The copy of the `.mmd` has the name of the vehicle it is made from in place of `(p2)`, the type name the simulator hands it, which some pass on to the include that names the model. An optional `"fiz_from": "/"` copies that file instead of the vehicle's own `.fiz`, named in full, e.g. `pkp/e6act_v2/e6acta.fiz.inc` for a vehicle whose `.fiz` only includes it (`e6actad.fiz`); the `.mmd` still comes from `from`. Keys for a section of the included file can't go after the include on a line of their own: a second `Power:` line loads the power source anew | | `expect` | the result the test mode should end with: `pass`, `fail`, `signal_passed_at_danger`, `timeout`, `standstill` or `error`, or `wall_timeout` for the timeout of the real time watchdog (the timeout code with a verdict saying it was the real time; a case expecting `timeout` fails on it). Default `timeout` for a case with `duration`, else `pass` | | `duration` | seconds of simulation to record: the test timeout of the run (`--test-timeout`) | | `timeout` | wall-clock seconds before giving up, loading included: the simulator's `--test-wall-timeout` (default 600) | @@ -209,6 +261,91 @@ starting at `vars.velocity` km/h; with `track_friction` 0.03 it locks the wheels and slides past the signal, so those cases set `test.fail_if_stop_overran no`. `td_red_signal_pass.scn` adds the `test_pass` event, which `test_mode_pass` puts as `event0` on `tor1k`, the track in front of the signal. +`td_shunt_red_signal.scn` is the same with no timetable, so the AI shunts (Shunt) towards the signal at +stop, starting `vars.offset` m into `tdo_n1734`: `eu07_td_shunt_red_signal` alone and +`eu07_td_shunt_push_red_signal` pushing three coaches, both from 30 km/h, have to stop before the signal, +151 m from the start (the shunting AI used to coast up to it and pass it at about 28 km/h, fixed +by #409). They stop after 145 m and 141 m. + +The `traxx_*` cases run a Traxx (E186, `p160dc`), whose driver's brake handle (MHZ_6P) has a time +chamber, like the MHZ_K5P, M394, Knorr, St113, FVel6 and FVE408 handles, which no other case has: the +AI getting such a locomotive ready has a rule of its own for releasing the train brake (5775493b2, +#444). `traxx_td_timetable` is the timetable run from a trainset ready to depart, +`traxx_td_timetable_cold` the same from a cold start (`td_cold_timetable.scn`, the handle in its +holding position, the brake pipe low), and `traxx_td_crew_add` the locomotive standing ready to depart +with nobody in it, the handle in its holding position and the brake pipe charged, until a driver is +put in (`td_crew.scn`, as `eu07_td_crew_add`). In all three the driver puts the handle to running +within a second of starting and leaves. + +`eu07_td_departure_station_capitals` runs an EU07 from where `td_timetable.scn` puts it, with the W4 of Stacja1 about +35 m ahead, on a timetable of its own (`td_departure_station_capitals.txt`, fragment `td_departure_station.scn`): +its first row, the station of departure, gives no arrival time and is written in capitals (`STACJA1`), the relation +says `Stacja1`, as in some timetables of the game (`Os33733` of linia_107_poludnie.scn starts at `ZAGORZ`). The +train has to stop there and leave at its departure time, 10:35, which the log shows as `as TEST24: at 10:35 next +Przystanek`; taking Stacja1 for a station it passes through, the driver logs `passed STACJA1` at once and leaves as +soon as the route is set at 10:34, and the train manager gives no departure signal. `eu07_td_departure_station` is the +same with the row written as in the relation. `eu07_td_timetable_past_w4` (fragment `td_timetable_past_w4.scn`) puts +the td/rozklad train, an EU07 with three coaches, with its head 80 m past the W4 of Stacja1, on `tor1k`: the W4 stays +under the consist, behind the head, and the driver still counts Stacja1 and leaves at 10:35, since the scan of the +route begins at the last vehicle and keeps a W4 behind the head. + +`eu07_coaches_td_timetable` is the timetable case with the EU07 and three coaches, a train that brakes with the train +brake, beside the light EU07 and the SN61 alone, which brake with the independent brake. The `*_td_downgrade_w4_signal` +cases (fragment `td_downgrade_w4_signal.scn`, timetable `td_downgrade.txt`) run on a line the fragment adds beside the +tracks of td.scn, at x = -3000: 300 m level, then 3000 m down a gradient of 20 per mille, under an overhead wire fed +by a substation of its own (`gr_pwr`; the wire on the section `pwr01` of td.scn gave the EU07 no voltage). The train +starts on the level at the W4 of Gora, stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before +`gr_sem`, a signal at stop 1100 m further down (a memory cell with `SetVelocity 0 0` and the event that reads it, no +model), about 1590 m and 2690 m from the start. The three trains are the light EU07, the SN61 alone and the EU07 with +three coaches. + +`e6actad_genset_td_timetable` (fragment `td_timetable_genset.scn`) is the timetable run of a dual-mode vehicle on its +genset (eu07/maszyna#536): an E6ACTad, the Dragon 2 "last mile" with a 520 kW diesel generator set. The game data has no +genset for it yet, so the case makes its own E6ACTad (`vehicle_variants`, `{{variant_g6}}`): the `.mmd` of `e6actad`, and +as its `.fiz` the `e6acta.fiz.inc` that `e6actad.fiz` includes (`fiz_from`), with `GensetStart=Manual` added to the +`Cntrl.` line and `GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 +GensetSpinUpTime=3 GensetPmaxRatio=0.85` to the `Power:` line. `event0` of the start track gives the standing vehicle, once, +`PutValues` `MainSwitch 0`, `TractionMode 1` (the selector on the genset) and `GensetSwitch 1`, a second apart, as the +vehicle holds one command at a time. The AI knows nothing of the genset: it closes the line breaker once the genset runs +and drives the timetable on it, at most 520 kW x 0.85 = 442 kW at the wheels (`traction_power`). +`e6actad_catenary_td_timetable` is the same variant without the events: it stays on the catenary and takes several +times that, which shows the check tells the two apart. + +### Heavy trains + +The heavy train cases (#187, #199, #263, #265) run on lines of their own beside the tracks of td.scn, at x = -3000, as +the `*_td_downgrade_w4_signal` cases of #479 do: 100 m tracks, an overhead wire fed by a substation of its own (none for +the diesel case) and signals at stop that are a memory cell with `SetVelocity 0 0` and the event that reads it, with no +model. Each train starts on a level stretch long enough for the whole consist, with its head 10 m before the W4 of Gora, +which is where the distances in the checks start from. A freight train leaves a station of its timetable as soon as it +stands there (`IsCargoTrain` in `TController`), so the freight trains leave Gora at once, not at 10:35. The checks that +look for a train that comes to a stand use the vehicle speed (`keeps_moving`), as the wheels of a heavy train starting +on poor rails spin while it stands; `starts_again` checks a start from a signal that clears at a given time, and how far +the train rolls back meanwhile. + +| case | fragment | train | what it shows | +| --- | --- | --- | --- | +| `et41_coal_td_downgrade_restriction` | `td_downgrade_restriction.scn`: 600 m level, 3500 m down 20 per mille, 20 km/h from 1500 to 1900 m down, the signal 3000 m down | ET41, 25 coal wagons 412W with 40 t each, G (about 1670 t) | passes: through the restriction at 10.5 km/h at the lowest, stops at the signal (3078 m) | +| `et22_764_td_downgrade_restriction` | the same | ET22, 20 heavy wagons 764 with 84 t each (about 2650 t) | `xfail`: dips to 8.5 km/h in the 20 km/h restriction (below the 10 km/h #263 counts as a defect); it doesn't stop | +| `st43_steel_td_downgrade12_long` | `td_downgrade12_long.scn`: 900 m level, 6500 m down 12 per mille, no wire, the signal 6000 m down | ST43, 45 coil wagons 425S, G | passes: holds 35-37.5 km/h of the 40 all the way down, never below 20 km/h, stops at the signal | +| `et41_coal_td_upgrade_start` | `td_upgrade_signal_start.scn`: 600 m level, 2500 m up 10 per mille, a signal 1000 m up that clears at 10:42, another 2300 m up | the ET41 with 25 coal wagons | passes: stops at the first signal with the whole train on the gradient, moves off 4.7 s after it clears, 10 km/h after 52 s, rolls back 0.04 m | +| `eu07a_coaches_td_upgrade_long` | `td_upgrade_long.scn`: 600 m level, 5500 m up 10 per mille, the signal 5300 m up | EU07A (303E), 8 coaches (about 360 t), passenger timetable at 80 km/h | passes: 80 km/h at 1430 m, never below 73.8 km/h on the climb | +| `et41_coal_td_slippery_start` | `td_level_signal.scn`: 2100 m level, the signal 1000 m ahead | ET41, 25 coal wagons with 60 t each (about 2170 t), `friction 0.3` | passes with the fix of this branch: gets going and stops at the signal (1082 m, at 392 s); before it, 395 slips in 1500 s and 75 m | + +What the AI still does with heavy trains, without a case that fails on it: + +- On a steep descent into a restriction a heavy G train holds the speed by applying and releasing the train brake in + turn. Its brake takes 10-15 s to release, so it falls well below the limit before the brake lets go: 10.5-12 km/h + for the ET41 with coal wagons, 8.5 km/h for the ET22 with the 764 wagons (the `xfail` above), in a 20 km/h + restriction. #263 reported this train stopping before the restriction in 10 of 12 runs; on staging it no longer + does, also with `friction 0.5` and with the wagons fully loaded. +- Starting uphill, a heavy train pulls against its train brake while the brake releases (#265): in + `et41_coal_td_upgrade_start` about 13 s at about 200 kN with the head moving by the slack of the couplers alone. It + starts at full power, without taking up the slack first. +- The AI doesn't know the adhesion of the rails: it plans braking with `Global.FrictionWeatherFactor` alone, and the + result of its running brake test (`adjust_desired_speed_for_braking_test`) is shown in the debug panel only. It sands + ahead of a slip only at a high motor current, and, since the fix of `et41_coal_td_slippery_start`, through the rest of + a start that has slipped (`control_wheelslip()`); not before a hard brake, nor before the first slip of a start. The `test_mode_*` cases show the ends of the test mode: `test_mode_pass` (exit 0, the pass event), `test_mode_signal_passed_at_danger` (exit 11), `test_mode_timeout` (exit 12, from @@ -220,6 +357,13 @@ standstill of 100 s ends the test although the traffic runs on (counting every v into the test timeout). `test_mode_pass_while_moving` reports the pass from `event2` of `tor1k` (the direction the train runs), as the train runs onto it, with `test.no_movement_before_pass no`, so the test ends with the train still moving. +`test_mode_standing_1m_past_signal` and `test_mode_standing_4m_past_signal` (fragment `td_past_red_signal.scn`) set +the td/rozklad train at a stand with its head 1 m and 4 m past the exit signal at stop (the memory cell of the +signal is 51 m into `tor1k`). The driver finds the signal behind the head at its first look ahead, 13.6 s in, and a +standing train passes nothing, so both run into their timeout. When a signal found up to 5 m behind the head +still counted as one the head had ahead, standing or not, both ended as signals passed at danger at 13.6 s (a +train set 6 m or 20 m past didn't). Starting at 0 km/h the driver doesn't wake up within the case, so they start at +0.1 km/h, as `td_red_signal.scn` does. The `en57_2000_automatic_coupler_*` cases (issue #86) share `td_automatic_coupler_hit.scn`: an EN57-2000 unit without a driver runs at `vars.velocity` km/h into a standing one, from @@ -230,18 +374,283 @@ couple and neither shows up: the black box has to have the last car of the stand writes nothing to the log when couplers catch). Nothing reports a result, so both end on the 60 s test timeout. +`et21_td_no_wire_reports` (issue #421, fragment `td_no_wire.scn`) adds a 200 m track of its own, +with no overhead wire, 400 m off the line of td.scn (every track of td.scn is under the wire), with +an ET21 and its AI driver on it. The pantographs go up and find no wire, so the locomotive can't +start: the driver has to say so in the log, once, naming the locomotive and where it stands, and +not mistake it for a wire without voltage. It ends on the standstill. + +The `eu07_td_off_track_*` cases run with `physics.derailment new`, where a derailed vehicle leaves the track and +moves on the ground by itself (`vehicle/derailmotion.h`); they check what the black box records of it with +`leaves_track`, and the log has a line of each vehicle off the track every second (`derailment: ... off the track`). +`td_off_track.scn` keeps an EU07 with an AI driver standing on track 1 of Stacja1 to log its physics, and has the train +of the case, without a driver, run at `vars.velocity` km/h from `vars.offset` m past point 1 of `vars.track`: +`eu07_td_off_track_buckle_fast` (133 km/h, `tdo_n222` buckled 600 mm over 8 m from the start with the `buckle` +keyword of the track) and `eu07_td_off_track_overturn` (190 km/h, over the overturning speed of the R 600 m curve) +from `tdo_n157`, `eu07_td_off_track_end` off the end of a track of its own (`vars.track_nodes`). +`eu07_td_off_track_buckle` is `td_buckle_event.scn` with an EU07 and three coaches on the timetable, at the 46 km/h +of the AI. The `eu07_td_off_track_curve_*` cases have an EU07 overturn at 150 km/h on a track of R 300 m of their own, +on level ground, on an embankment 4 m high and in a cutting, made of triangle strips in the fragment +(`td_off_track_curve_*.scn`, written by `make_off_track_curves.py`: a curve of R 300 m from (-300, 400) about the +centre (-600, 400), the cross section swept along it every 0.03 rad; the banks of the cutting rise 4 m at 1:1.5, then +on at 1:5). + +The `eu07_td_overspeed_bad_limit*` cases (fragment `td_overspeed_bad_limit.scn`) have that curve with a speed limit of +140 km/h, which it doesn't take (the EU07 overturns in it at about 108 km/h), and a straight track of 900 m on from it: +a defect of the data, as `physics.trackcheck` finds on some tracks of the bundled sceneries. With +`physics.derailment.trustlimits` (the default `yes`) the limit is trusted up to 1.1 times it and 5 km/h, +159 km/h: an EU07 without a driver at 140 km/h stays on the rails and the log names the track once +(`derailment monitor: data: ...`) in `eu07_td_overspeed_bad_limit`; at 175 km/h it overturns +(`eu07_td_overspeed_bad_limit_fast`), and so it does at 140 km/h with `physics.derailment.trustlimits no` +(`eu07_td_overspeed_bad_limit_untrusted`). + +`eu07_td_cold_connect` (fragment `td_cold_connect.scn`) has an EU07 with a hand brake +(`4E-ZEZ_GREY`; the plain `4e` has none) standing cold on track 1 of Stacja1 (trainset velocity 0, +so it starts with the hand brake on) and two coaches standing 45 m ahead of it. Its driver sleeps +until `event0` of its track gives it, once, `Shunt -1 3`: start the engine, couple to the consist +ahead (Connect, the first order it drives under), go on shunting. It passes when the first coach, +pushed, runs onto `tor1k` (`eventall2`), with the train still moving, and the black box has the +locomotive coupled to the coaches (it couples about 70 s after the start). A driver that leaves its +hand brake on under Connect pulls against it for good and the case ends as a standstill after 300 s. + +The `eu07_td_buckle_*` cases (fragment `td_buckle_event.scn`) run the timetable train of +`td_timetable.scn` and buckle the curve `tdo_n222`, about 950 m ahead of it, with a `trackbuckle` +event of `vars.amplitude` at 10:35. Both have `physics.derailment new` in `ini`: the default, +`monitor`, leaves the decision to the legacy draw and only logs what the criteria would do +(`derailment monitor: ... overturned at 46 km/h on track tdo_n222`), so the train runs on to +Przystanek whatever the buckle. With 600 mm over a main lobe of 8 m the locomotive overturns on +the buckle at 46 km/h, 1036 m from the start (`Bad driving: ... derailed on buckled track`); with +30 mm it keeps on the rails and stops at Przystanek after 1400 m. + +`sm42_td_uncouple_past_signal` (fragment `td_uncouple_past_signal.scn`) is the uncoupling of the SM42 at Debica on +L053 poranek (step 10 of `deb_sm42_stat`) on td.scn. An SM42 with no timetable stands turned at the far end of `tor1k`, +three wagons loaded with gravel (51 m of train) behind it towards the exit signal `stacja1_j`, which stays at stop (no +route). `tdo_n1734`, the track behind `tor1k`, is closed (`trackvel 0`) from the start. `event0` of `tor1k` gives the +driver `Shunt -1 0`: it pulls the wagons back for 47 m and stops in front of the closed track, with the far end of the +last wagon 2 m past the signal's memory cell (the `distance` check keeps it 0-4 m past). The pull leaves the screw +coupler stretched, 0.019 m apart at the buffers, and a screw coupler is let go only with the buffers pressed together +(under 0.01 m). At the first stand `event0` gives `Shunt 0 0`: brake the wagons, change direction, push the buffers in, +uncouple. After the direction change the driver counts `stacja1_j` as passed at its first move, so its speed is capped +at 0. The driver used to work the brake releaser only while it wanted to speed up, so the locomotive stayed braked by +the wagons' brake application and never closed the gap: no `uncoupled` in the log, and the case ran into its timeout. +Now the locomotive is released, eases into the wagons and uncouples within a second. The wagons are loaded so that the +stop leaves the gap above 0.01 m: with a coach and an empty wagon the buffers came to rest 0.009 m apart and the +coupler let go at once. + +The `*_td_crew_*` cases (eu07/maszyna#510, fragment `td_crew.scn`) are about the crew command of a +`putvalues` event, `Crew: `: cab 1 or -1 puts an AI driver in cab A or B of +the vehicle named, 0 takes its AI driver off. The vehicle is named in the text, so the events are +set off by event launchers, at an hour or with a delay; `vars.trainsets` are the vehicles and +`vars.crew` the events of the case: + +- `eu07_td_crew_add`: an EU07 standing cold with nobody in it gets a driver in cab A 20 s after + the start. A driver put in a standing vehicle waits for orders, as the one of a standing + trainset does, so `event0` of its track gives the order to go (`Shunt -1 0`), once: the driver + starts the locomotive and leaves through the exit signal, whose aspect makes it a train run. + `eu07_td_crew_add_rear` is the same with cab B: the locomotive leaves the other way, its rear + end leading (`moves`, from the black box). +- `eu07_td_crew_remove`: the EU07 of `eu07_td_timetable` loses its driver at 10:36, on the run at + 59 km/h. It is left with the power off and the brake valve in the emergency position: it + stands 16 s and 168 m later and doesn't move in the 164 s to the end (`stops_driverless`; the + physicslog ends when the driver goes). `en57_td_crew_remove` (driven from the head car, the + motors in the middle one), `vectron_td_crew_remove` (induction motors and an integrated handle) + and `sm42_td_crew_remove` (diesel) are the same with other vehicles. +- `eu07_td_crew_swap`: the driver waiting at Stacja1 is taken off after 20 s, which leaves the + locomotive braked, and a new one put in 20 s later, who gets the order to go, releases the + brakes and leaves. +- `golf_td_crew_swap`: a car running along the road `d3` at 50 km/h loses its driver, which + leaves it with its own brake applied in full: it stands 3 s and 17 m later. A road vehicle has + no cab to tell by and takes a driver all the same: the new one, put in 40 s later, drives on + along the road, at up to 100 km/h, having no timetable to cap the speed as the first one had + (the trainset's `50`). +- `eu07_td_crew_refused`: the run of `eu07_td_timetable` with crew events which must be refused, + at the start and again on the run: a second driver for the locomotive, a driver for a coach + (no cab), a cab which is none of 1, -1, 0, a driver taken off a coach which has none, and a + vehicle the scenery lacks. Each leaves its line in the log and the train runs its timetable to + the stop at Przystanek as it does without them. +- `en57_td_crew_parted`: an EN57-2000 unit with an AI driver and no timetable stands on track 1, + another one with nobody in it runs into its rear at 100 km/h (`crashdamage yes`). The hit + breaks the coupler between the middle and the rear car (`parts`, at 2 s), which leaves the rear + car with the driver in charge of it. The driver taken off at 10:35 had all three cars in charge, + the parted one too, and none of them keeps it (the log line `the driver was in charge of 3 + vehicles`; the cars still coupled to the head car are two). + +A vehicle with a user in it is left alone by the command, which the test mode can't show: nobody +sits in a vehicle there. + +`eu07_td_hauls_dead_vectron` is the timetable run with a dead locomotive in the train: behind the EU07 a +Vectron with nobody in it, coupled with the hook and the brake hose alone (the EU07's coupling `3`) and +prepared for hauling, the parameter `H` after its own coupling (`0.H`: the pullee mode of +MaSzyna-EU07/maszyna#64). The checks are those of the timetable cases; the train takes 300 s to +Przystanek and on (20 km/h after 79 s, the stop after 220 s and 1405 m). Without the `H` the Vectron, +which applies the emergency brake while none of its cabs is active, empties the brake pipe of the train +in two seconds, both locomotives stand with their brake cylinders full and the train never moves. +`eu07_td_hauls_dead_vectron_cold` (fragment `td_cold_timetable.scn`) is the same train from a cold start: +trainset velocity 0, so both locomotives stand braked (brake pipe at 3.5 bar, batteries off, the spring +brake of the Vectron switched on), and `event0` of the track gives the driver `Obey_train`, once. The EU07 +starts up, charges the brake pipe and leaves on time (the stop after 209 s and 1393 m); without the `H` +the pipe stays below 1 bar and the case ends as a standstill after 300 s. + +`eu07_td_reinspect_brakes_after_coupling` (fragment `td_reinspect_brakes.scn`, eu07/maszyna#350 and #282) is about the +wagon inspector of the AI (`TController::AutoRewident()`) on a train formed by coupling. An EU07 stands cold on the line +from Stacja1 (`koniec`) and a cut stands 45 m ahead of it, braked, with nobody in it: 16 coaches with P alone (BDhpumn) +and next to the locomotive 8 empty wagons with G and P (401W), 541 m of wagons. `event0` of the locomotive's track gives +the driver `Shunt -3 3`, once: couple to the cut with the coupler and the brake hose and run it on as a train +(`Obey_train`), waiting for the way, which `event2` of `tdo_n231`, in front of the cut, gives as a `SetVelocity 40 40` +(no signal of the line is in sight). Over 500 m of wagons make it a train on G (Cw-1 §19.1), where the brake of a wagon +without G is cut out (§19.9). The inspector looks at the train as the AI couples, at 4 km/h (t=69 s), too fast for it to +cut a brake out, and leaves that for the next standstill: `reinspect_brakes()` cuts the 16 coaches out as the train stands +a moment later, its brakes applied by the empty pipe of the cut. Neither the physicslog nor the black box has the brakes +of the wagons, so the case tells by how the train brakes: `event2` of `tdo_n240` takes the driver off at 38 km/h, which +leaves the brake valve in the emergency position, and braked by the locomotive and the 8 wagons alone the train stops 29 s +and 211 m later, a mean deceleration of 0.27 m/s² (`stops_driverless` with `max_deceleration` 0.40). With every brake +working it stops at 0.57 m/s², 99 m: that is `eu07_td_reinspect_brakes_legacy_inspector`, the same run with the inspector +of the earlier releases (`ai.brakesetting.cw1 no`), which cuts no brake out, and also what a build whose +`reinspect_brakes()` does nothing gives for the first case, which then fails. The test passes 150 s after the driver goes. + +The `*_section*` and `*_converter_interlock*` cases are about the line breaker closed ahead of the pantographs +(`PantRequiresMain=Yes` in `Cntrl.`, MaSzyna-EU07/maszyna#272) and the line contactors that wait for the +converter of their own vehicle (`LineContactorsInterlock=Converter`, #276), driven by the AI on the timetable +run of td.scn. The overhead wire of td.scn is changed with `replace`: one span of it, 61 m some 400 m from +the start (`0.7764 5.845 1561.2417` onwards, over the way out of Stacja1, which the train runs under power at +50-55 km/h), gets no supply and 0 V (`traction none 0`), and in `ep05_td_section_insulator` the span before +it is split around a section insulator 1 m long (`traction * 0`, as sceneries hang insulators). The EP05 has +`PantRequiresMain=Yes` in the game's data; the ET42 has no `LineContactorsInterlock` yet (SVN data of #276), +so those cases run variants of the vehicles made for the run (`vehicle_variants`). + +- `ep05_td_timetable`: the EP05 on the plain timetable run, the reference: 20 km/h after 73 s, the stop + after 205 s and 1400 m. +- `ep05_td_dead_section`: the EP05 runs into the span without voltage under power, nothing on the track + telling its driver to coast. The traction force drops to nothing at once and the AI puts the master + controller to 0; the line breaker stays closed (the log + says the vehicle lost power for 4.05 s, which it says only while the line breaker is closed). Behind the + section the AI takes power again (535 m, 36 kN by 595 m) and stops at Przystanek (1399 m). +- `ep05_td_neutral_section`: the same with the track under that span, `koniec`, marked as one to coast + through (`overhead 0`, which `track_events` adds as it adds events): the AI puts the master controller to + 0 as the locomotive runs onto it, 25 m ahead of the dead wire, and takes power again behind it. +- `eu07_td_dead_section`: the old behaviour for reference, an EU07 (pantographs first) into the same span: + its line breaker opens after 0.2 s (`lost power for 0.21 sec`, no longer), and behind the section the AI + closes it again and takes power (493 m). +- `ep05_td_section_insulator`: the EP05 runs under the insulator under power at 50 km/h. The pantograph is + without voltage for some 0.07 s, which the vehicle bridges by holding the last voltage for 0.2 s + (`TDynamicObject::Update`): the traction force stays between 50 and 58 kN past it and nothing is logged. + Without the hold the undervoltage relay of a `PantRequiresMain` vehicle would open the line contactors, + which close again only with the master controller back at its first position. With the insulator 15 m long + instead (a trial run) the vehicle does lose power there (logged, the force drops to 0), which shows the + pantograph runs under the piece of wire. +- `et42_td_converter_interlock_cold`: an ET42 with `LineContactorsInterlock=Converter` in both sections + stands cold (`td_cold_timetable.scn`) and is ordered to run the timetable: the AI starts the converters, + leaves (20 km/h after 74 s) and stops at Przystanek (1393 m). It and `et42_td_converter_interlock`, the + same from the timetable start, check that the AI gets such a train going; a plain ET42 passes them too. +- `et42_td_converter_interlock_slow_converter`: the check that the interlock takes effect. The same cold ET42 + with a converter that starts 60 s after it is switched on (`ConverterStartDelay=60`): the line contactors + wait for it, and the train reaches 20 km/h at 80.0 s; `starts` with `after: 77` fails it earlier. With the + same converter and no interlock it gets there at 73.8 s, as fast as without the slow converter (a copy of + the case without the key, run once, not kept). +- `ep05_td_interlock_dead_section_cold`: #272 and #276 together, an EP05 with `LineContactorsInterlock=Converter` + added, standing cold, with the span without voltage on its way: the pantographs can go up only through the + closed line breaker, so the AI has to close it first, then start the converter; it leaves (20 km/h after + 77 s). Under the dead wire the converter stops with the main circuit, behind it the converter starts again + and the AI takes power (573 m, 4 s later than the EP05 without the interlock) and stops at Przystanek + (1393 m). + +What these can't reach: the local converter switch of the ET42 (`converterlocal_sw:`), which the AI has to put +back on (`LineContactorsHeldByLocalConverterSwitch()`, the part of #276 in `determine_consist_state()` and +the `converteron` hint), is in the cab only: no command of a scenery or of the train's cables sets +`ConverterAllowLocal`, and nobody sits in a cab in the test mode, so the switch is always on in a case. + +The `eu07_td_switch_*` cases (fragment `td_switch_thrown.scn`, the review of #289, point 2b) throw a switch of +Stacja1 by an event under an EU07 with three coaches and check that the train keeps to the rails (`on_track`) and that +the AI keeps to the route it is really on. Both switches of the station have their points towards the line and the +way to track 2 straight (position 0), to track 1 curved (position 1); the ends of the two ways are 1.9 m apart, the +tracks 4.6 m. `zwr01` at the west end is run through facing by a train running into the station, `zwr02` at the east +end trailing by one leaving it. The throw is an event set off once, by the rear axle of the locomotive running onto a +track (`event1`/`event2` of it, which only the vehicle with the driver sets off) or by a launcher 5 s after the start; +a driver that stands cold gets its order (`vars.order`) from `event0` of its track, after the throw where the train +stands over the switch. On track 1 a signal at stop of the case's own stands at z 1100: the train has to stop before +it (`event0` of `tdo_n1725` passes the test, running onto `tdo_n1734` fails it); on track 2 the exit signal `stacja1_k` +at stop. What they showed on `staging` of 2026-11-22 (f15ea405), where an axle on a switch keeps the way it ran onto +(the segment it took when it got onto the switch) but leaves the switch by the way it is set to now, and the AI does +not scan its route again for a switch that changed behind the head of the train: + +| case | throw | result | +| --- | --- | --- | +| `eu07_td_switch_facing_control` | none, set to track 1 from the start | passes: stops before the signal of track 1 | +| `eu07_td_switch_thrown_facing_head` | `zwr01` to track 1 with the locomotive on the switch | `xfail`: the locomotive jumps sideways at the end of the switch (0.78 m off the track in the black box), the whole train goes to track 1, and the AI, still on the route of track 2, runs past the signal of track 1 at 40 km/h | +| `eu07_td_switch_thrown_facing_behind` | `zwr01` to track 1 with the locomotive just past it | `xfail`: the locomotive runs on along track 2 and the coaches coupled to it along track 1, side by side, for 900 m | +| `eu07_td_switch_thrown_standing_facing` | `zwr01` to track 1 under the standing train, which then leaves facing | `xfail`: the second coach runs with a bogie on each track, its body 2.3 m off both; the AI, which scans from the last vehicle, reads the signals of track 1 while it runs on track 2 (a signal passed at danger, `stacja1_j`) | +| `eu07_td_switch_thrown_standing_trailing` | `zwr02` to track 1 under the standing train, which then leaves trailing | passes: the first wheels coming from track 2 push the switch back (as through any switch set against them from the frog end) | +| `eu07_td_switch_thrown_trailing` | `zwr02` to track 2 under the coaches of the timetable train leaving track 1 | passes: the switch is pushed back, the train stops at Przystanek after 1402 m | + +Nothing derails in any of them with `physics.derailment monitor` (the default; the monitor reported nothing either), +and the three `xfail` cases run with `physics.derailment new` came out the same to the metre: the criteria of +derailment look at the curve, the cant and the speed of a vehicle, not at its bogies being on two tracks. Nor does the +coupler between a locomotive and a coach 4.6 m beside it break. + +### Cases on a mission of a scenery + +The cases made from players' reports (eu07/maszyna#421, #506, #524, #525) run a whole mission +of a scenery of the game, among its own traffic: `strip_trainsets` `false`, `vehicle` the +mission's own locomotive or unit, every train driven by AI as always in the test mode. They are +`slow`, have `physicslog` `false` unless a check needs the black box, and `file.binary.terrain no` +in `ini`, so that no geometry cache of the copied scenery (hundreds of MB for these) is written +into the game dir. What they add to the scenery: + +- nothing, when standing too long is the bug: `test.standstill` is set above the longest wait + the mission has, and the run ends with `duration` (`baltyk_skm1_*`), +- `mission_state_probe.scn`: these sceneries steer each station with a state cell per train + (text and two values, e.g. `deb_tme222158_stat` = `a 6 *`: the route of step 6 is set). The + probe is a loop of two events that looks at the cell `vars.cell` every 5 s and reports the + pass once it holds `vars.state` (a `memcompare`: `* 6 *`, `d * *`), with `vars.reason` as the + text. No fail event: a train that never gets there ends the test with the standstill or the + timeout. A periodic event launcher wouldn't do, the simulator polls those near the camera only, +- events named `:event0`, `:event1`, `:event2` or `:eventall1`...: the simulator binds an + event with such a name to the track by itself, so a fragment can hang events on tracks that + live in the scenery's includes, where `track_events` doesn't reach (`wrzosy_pxe336080_couple.scn`). + The name must not be one the scenery has already: a second event of the same name replaces the first. + +A train whose trainset has velocity 0 has a driver that sleeps in `Wait_for_orders` when nobody +is in the cab: the player would drive it, so the fragment has to give the orders the player's +hands stand for, with `PutValues` from an event the vehicle itself sets off (`event0` of the +track it stands on). The first of them may be the one to couple (`Shunt -2 -3`): a driver whose +first order is `Connect` releases the hand brake a cold locomotive starts with +(`eu07_td_cold_connect`). The mission trains of velocity 0.1 wait for their signal and need nothing. + +The cases and what they showed on master of 2026-11-11 (the two L053 poranek rows also on +staging f15ea405 of 2026-11-23): + +| case | report | result | +| --- | --- | --- | +| `wrzosy_pxe336080_couples` | #524 | passes: ordered to, the locomotive couples to the rake (`couples`, 262 s) and takes it out of the depot (696 s). The scenery itself gives no such order | +| `baltyk_skm1_roj55324_shunting_signal` | #525 | passes, with four seeds: the unit on the siding is let into the platforms 4 minutes after the start, once the shunter beside it has done its first moves, and leaves at 10:42. Since SVN r9644 (2026-11-15) the mission's unit is ED78-019A instead of EN90-009A; with it the case passes on staging b7f2186a1 (one seed) | +| `baltyk_skm1_roj55321_departure` | #525 | passes, with three seeds: the unit in the platform leaves at 10:34. Since SVN r9644 (2026-11-15) the mission's unit is EN57AL-1230ra instead of EN71-014ra; with it the case passes on staging b7f2186a1 (one seed) | +| `l053_poranek_tme222158_debica` | #421 | passes: TME222158 gets the exit signal to Sandomierz (step 6 of `deb_tme222158_stat`) after 4086.2 s. On master of 2026-11-11 the station jammed 4 minutes after the start, the AI of EP07-338'16 passed the shunting signal Tm4 at stop at 29 km/h; #409 fixed that. On staging f15ea405 (2026-11-23) the station's SM42-1096 jammed it next: ordered to uncouple at step 10 of `deb_sm42_stat`, with its cut standing across `debica_k_sem_info` at stop, it stayed braked and never got the coupler off (standstill after 4347 s), until the AI kept the locomotive released while it pushes the buffers in to uncouple (`sm42_td_uncouple_past_signal`) | +| `l053_poranek_tme222158_debica_et21` | #421 | passes after 4131.6 s. On master of 2026-11-11, with an ET21 as in the report, the locomotive stopped for good at Debica Towarowa, on the headshunt 20 m past the end of the overhead wire, and its driver never got out of `Prepare_engine`. Since #409 the ET21 gets through Debica Towarowa (steps 1-5 of `dt_tme222158_stat`) to Debica; there it waited for the SM42 as `l053_poranek_tme222158_debica` did, until the same fix | +| `l053_poludnie_roj32134_debica` | #506 | passes: both trains run and the unit ends at Debica after 6134 s; no train in its way | + +In the L053 sceneries the test mode logs a signal passed at danger for several shunting +locomotives within minutes, so these cases have `test.fail_if_stop_overran no`. + +The simulation ran at 15 times real time on Baltyk and at 5-8 times on L053 (with another +build going on on the machine) with the physicslogs off, and at 3-4 times on Wrzosy with them +on (250 drivers, the road vehicles included: 740 MB of physicslogs in 900 s), after 30-150 s of +loading. + Checks (speeds in km/h, times in seconds of physicslog time, distances in metres). Most use the physicslog Velocity column, which is the wheel speed: it stays at 0 while the wheels are locked in a skid. The ones marked *vehicle speed* use the vehicle speed column at the end of the row instead, logged by builds from this branch on. -- `starts` `min_speed`, `within`: reaches `min_speed` within `within` seconds. +- `starts` `min_speed`, `within` (`after`): reaches `min_speed` within `within` seconds (and not before `after` seconds, + when given). - `max_speed` `limit`, `tolerance`: never goes faster than `limit + tolerance`. - `brakes` `min_pressure`: after moving off, brake cylinder pressure reaches `min_pressure` bar (physicslog pressures are in bar whatever its header says; the brake pipe runs at 5.0). -- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`: after - reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the distances, - that stop has to be between them (metres travelled, as in `distance`). +- `stops` `moving_speed`, `stop_speed`, `hold`, optional `min_distance`, `max_distance`, `max_time`, + `nth`: after reaching `moving_speed`, stays at or below `stop_speed` for `hold` seconds; with the + distances, that stop has to be between them (metres travelled, as in `distance`), with `max_time` + it has to begin by then (seconds of the physicslog). `nth` (default 1) takes a later stop: each + stop after the first counts once the train has reached `moving_speed` again. - `stays_stopped` `moving_speed`, `stop_speed`: after moving off and stopping, never goes above `stop_speed` again. - `distance` `min`, `max`: total distance travelled. The physicslog has no position, so the @@ -255,6 +664,16 @@ the row instead, logged by builds from this branch on. after moving off, moves no more than `max_distance` metres, e.g. no creeping on locked wheels. - `ends_moving` `min_speed`: the last row of the physicslog is at `min_speed` or faster, e.g. the test ended without waiting for the train to stop. +- `traction_power` `max_kw`, optional `min_peak_kw` (*vehicle speed*): the power at the wheels, the + traction force times the vehicle speed, never goes above `max_kw` and, given `min_peak_kw`, reaches + it at least once; e.g. a dual-mode vehicle running on the power of its genset. The traction force + column is in N, whatever the header says. +- `keeps_moving` `moving_speed`, `min_speed`, `until_distance`, optional `from_distance` (*vehicle speed*): once at + `moving_speed`, the speed stays at or above `min_speed` between the two distances (metres travelled, from the vehicle + speed), e.g. a heavy train doesn't come to a stand on a descent before a restriction. Reports the lowest speed. +- `starts_again` `after`, `min_speed`, `within`, optional `max_rollback` (*vehicle speed* for the rollback): standing + at the time `after` (a signal that clears then), the train reaches `min_speed` within `within` seconds, and rolls back + no more than `max_rollback` metres meanwhile. - `log_contains` `pattern`: a line of the run's `log.txt` matches the regex, e.g. the `Bad driving: ... collided` message of a collision. - `log_lacks` `pattern`: no line of the run's `log.txt` matches the regex. @@ -264,10 +683,64 @@ the row instead, logged by builds from this branch on. filled in as in the fragment, e.g. `{{vehicle}}_rb`. Fails when the two were coupled from the start, came apart again, or the run left no black box. The black box is looked at once a second, so the time given is that of the first look after the couplers caught. +- `parts` `vehicle`, `other`, optional `before`: the black box has the two vehicles, coupled to + each other, come apart (the coupler itself let go: broken, or uncoupled), by the time `before` + of the recording when given. +- `driver_changes` `vehicle`, `to`, optional `after`, `before`: the black box has the vehicle get + the driver `to` (`none`, `ai` or `user`) at a time of the recording between the two, having had + another one before, and keep it to the end. +- `stops_driverless` `vehicle`, `min_speed`, `within`, optional `stop_speed` (0.5), `max_creep` + (1 m), `hold` (60 s): the black box has the vehicle lose its driver at `min_speed` or faster, + stand `within` seconds later and stay within `max_creep` of where it stopped for the rest of + the recording, or until it gets a driver again, at least `hold` seconds. The physicslog can't + tell: the driver writes it, so it ends when the driver goes. Optional `min_deceleration`, + `max_deceleration` (m/s²): the mean deceleration of that stop, from the speed the driver left at + and the way to the stop (v²/2s), has to be within them, e.g. a train some of whose brakes are + cut out stops slower. +- `moves` `vehicle`, `min_speed`, optional `direction` (`front`, or `rear`): the black box has the + vehicle reach `min_speed` with that end leading (the physicslog speed has no direction). +- `traction` `from_distance`, `to_distance`, and one or more of `reaches`, `at_most`, `at_least`: the + traction force in kN (the physicslog has it in N, whatever its header says) while the vehicle runs between + the two distances (metres travelled, as in `distance`): its highest there reaches `reaches`, e.g. the power + taken again behind a section without voltage; it stays at or below `at_most`, e.g. none under a dead wire; + it stays at or above `at_least`, e.g. no power lost under an insulator. +- `master_controller` `from_distance`, `to_distance`, `at_most`: the master controller stays at or below the + position between the two distances, e.g. at 0 where the scenery tells the driver to coast. +- `leaves_track` `vehicle`, optional `cause` (`flange climbed`, `overturned`, `end of track`, `pulled off`, + `collision`), `min_offset`, `max_offset`, `min_distance`, `max_distance`, `lying`: with + `physics.derailment new` the black box has the vehicle leave the track and come to rest off it; at rest its + distance from the axis of the track (either side) and the distance it went on the ground are within the + bounds, and it lies on its side, or not, as `lying` says. +- `consist_folds` `vehicles` (the names of the train front to back, comma separated), `min_bend`, optional + `min_folds` (1), `alternate`, `both_sides`: with `physics.derailment new` the train came to rest folded up off + the track: at least `min_folds` of the bends between neighbours at rest (the angle between their headings in the + black box, either way along) are `min_bend` degrees or more; with `alternate` neighbouring bends of that size turn + opposite ways (a zigzag), with `both_sides` some of the vehicles rest on either side of the track. A vehicle that + stayed on the rails has no bend with its neighbours. +- `no_overlap` `max_transient`, `max_at_rest` (a check on the log): with `physics.derailment new` the bodies of the + vehicles off the track and of those near them don't go into each other. The simulator logs every second the most + any two of them overlapped by (`derailment: the bodies overlap by up to ... m (which two, how they are related) + over the last second, ... m now`), and once more when all vehicles off the track are at rest (`, all at rest`); the + most on the way is at most `max_transient` m, the overlap at rest at most `max_at_rest` m. + +- `on_track` `vehicles`, optional `max_offset` (0.75 m), `max_detour` (5 m): every vehicle whose name starts with + `vehicles` (e.g. `{{vehicle}}`, the train of the case) keeps to the rails in the black box, in each of its states: + its middle is within `max_offset` of the line of a track (level distance, the map of the tracks of the black box), + and of two vehicles coupled to each other the way along the tracks from one to the other (through the ends of the + tracks that meet) is no more than `max_detour` longer than the straight line between them. A vehicle with its + bogies on two tracks that part, or thrown sideways, is off the line; a coach running on beside the locomotive it is + coupled to, on the next track, has a way to it hundreds of metres long. A coach on a curve of 300 m, through the + S of a switch, was up to 0.38 m off. The middle of a vehicle is the middle of the chord between its pivots, so on + a curve of radius R a vehicle running right is a^2 / 8R off the track, a being the distance of the pivots: a 19.5 m + coach 0.59 m at R 80, 0.79 m at R 60. The default suits curves down to about R 65 for such a coach; a case with + tighter curves sets more. The black box lists a vehicle once a second, so a jump between two lists shows up only + as it is at the next one. New check types go in `CHECKS` in `run.py`; each gets the physicslog rows and the check's parameters and returns `(passed, detail)`. Checks on the log go in `LOG_CHECKS` and get the text of `log.txt` instead of the rows. Checks on the black box (`blackbox_doc.md` in the root of the repo; the simulator writes it along with the physicslogs) go in `BLACKBOX_CHECKS` and get -what `read_blackbox()` read of it: the names of the vehicles and the coupling records. A check +what `read_blackbox()` read of it: the names of the vehicles, the coupling records, and the +states of each vehicle from the `vehicles` records (position, speed, driver; a vehicle is listed +when it moved, changed speed or got another driver, and all of them every 60 s). A check on another kind of record has to add it there. diff --git a/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json new file mode 100644 index 000000000..3a820f17a --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55321_departure.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts in the platform of Baltyk Glowny (EN57AL-1230ra, ROJ55321, departure 10:34; the EN71 of this mission became an EN57AL in SVN r9644): the exit signal has to clear and the unit has to leave. Standing for 10 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "EN57AL-1230ra", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 600", + "test.fail_if_stop_overran no" + ], + "duration": 900, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json new file mode 100644 index 000000000..343b431d4 --- /dev/null +++ b/tests/scenarios/cases/baltyk_skm1_roj55324_shunting_signal.json @@ -0,0 +1,18 @@ +{ + "description": "eu07/maszyna#525, Baltyk skm1, the mission that starts on the siding of Baltyk Towarowy next to the shunter (ED78-019A, ROJ55324; the EN90 of this mission became an ED78 in SVN r9644): the station lets the unit into the platforms once its shunter 6Dg-1244, on the track beside it, has done its first moves (4 minutes after the start), and out to Alakowice at 10:42. A shunter that gets stuck leaves the unit at the shunting signal for good: standing for 15 minutes ends the test as standstill.", + "base_scenery": "baltyk_skm1.scn", + "strip_trainsets": false, + "vehicle": "ED78-019A", + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.standstill 900", + "test.fail_if_stop_overran no" + ], + "duration": 1800, + "expect": "timeout", + "timeout": 900 +} diff --git a/tests/scenarios/cases/e6actad_catenary_td_timetable.json b/tests/scenarios/cases/e6actad_catenary_td_timetable.json new file mode 100644 index 000000000..9e8ff5f72 --- /dev/null +++ b/tests/scenarios/cases/e6actad_catenary_td_timetable.json @@ -0,0 +1,25 @@ +{ + "description": "GE#536 stage 1, the twin of e6actad_genset_td_timetable without the switching events: the same E6ACTad variant stays on its catenary position and runs the td/rozklad timetable as the plain E6ACT does, on far more than the genset's 442 kW at the wheels, which shows the traction_power check tells the two apart. The same variant g6 as the genset case.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vehicle_variants": [ + { "name": "g6", "from": "pkp/e6act_v2/e6actad", "fiz_from": "pkp/e6act_v2/e6acta.fiz.inc", "replace": [ + ["InactiveCabFlag=15", "InactiveCabFlag=15 GensetStart=Manual"], + ["PhysicalLayout=3", "PhysicalLayout=3 GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 GensetSpinUpTime=3 GensetPmaxRatio=0.85"] + ] } + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\e6act_v2 e6actad-017 {{variant_g6}} 0 headdriver 0 0 enddynamic" + }, + "ini": ["gfxrenderer null"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_lacks", "pattern": "Genset of" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "traction_power", "max_kw": 6000, "min_peak_kw": 1000 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/e6actad_genset_td_timetable.json b/tests/scenarios/cases/e6actad_genset_td_timetable.json new file mode 100644 index 000000000..92338d49d --- /dev/null +++ b/tests/scenarios/cases/e6actad_genset_td_timetable.json @@ -0,0 +1,28 @@ +{ + "description": "GE#536 stage 1: an E6ACTad (Dragon 2 last mile) on the td/rozklad timetable of td.scn, switched to its genset by the scenery before it leaves: PutValues MainSwitch 0, TractionMode 1, GensetSwitch 1 from event0 of its track, 1 s apart. The AI, which knows nothing of the genset, closes the line breaker once the genset runs and drives to Przystanek on at most 442 kW at the wheels (520 kW x 0.85). Makes its own E6ACTad for the run (vehicle_variants g6: e6acta.fiz.inc with the genset keys, the .mmd of e6actad).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable_genset.scn", + "vehicle_variants": [ + { "name": "g6", "from": "pkp/e6act_v2/e6actad", "fiz_from": "pkp/e6act_v2/e6acta.fiz.inc", "replace": [ + ["InactiveCabFlag=15", "InactiveCabFlag=15 GensetStart=Manual"], + ["PhysicalLayout=3", "PhysicalLayout=3 GensetPower=520 GensetVoltage=3000 GensetIdleRPM=700 GensetMaxRPM=1800 GensetStartTime=8 GensetSpinUpTime=3 GensetPmaxRatio=0.85"] + ] } + ], + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\e6act_v2 e6actad-017 {{variant_g6}} 0 headdriver 0 0 enddynamic" + }, + "ini": ["gfxrenderer null"], + "track_events": { + "tdo_n1734": "event0 autotest_genset" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Genset of autotest_e6actad_genset_td_timetable: running" }, + { "type": "starts", "min_speed": 20, "within": 180 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "traction_power", "max_kw": 451, "min_peak_kw": 380 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/en57_2000_crush_new.json b/tests/scenarios/cases/en57_2000_crush_new.json new file mode 100644 index 000000000..9de8c1688 --- /dev/null +++ b/tests/scenarios/cases/en57_2000_crush_new.json @@ -0,0 +1,17 @@ +{ + "description": "G14 stage 2: an EN57-2000 unit without a driver runs at 20 km/h into a standing one on td.scn, with physics.collisions new. Too fast for the automatic couplers to catch: past the buffers the cab ends crush, a few decimetres, too little for either unit to climb onto the other, so both stay on the rails; the run ends on the 60 s test timeout.", + "base_scenery": "td.scn", + "ini": ["crashdamage yes", "physics.collisions new"], + "fragment": "td_automatic_coupler_hit.scn", + "vars": { + "velocity": "20", + "offset": "0" + }, + "expect": "timeout", + "duration": 60, + "timeout": 300, + "checks": [ + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ and autotest_\\S+ collided at \\d+ km/h, the \\w+ end of autotest_\\S+ crushed" }, + { "type": "log_lacks", "pattern": "Bad driving: autotest_\\S+ derailed" } + ] +} diff --git a/tests/scenarios/cases/en57_td_crew_parted.json b/tests/scenarios/cases/en57_td_crew_parted.json new file mode 100644 index 000000000..f75a99179 --- /dev/null +++ b/tests/scenarios/cases/en57_td_crew_parted.json @@ -0,0 +1,34 @@ +{ + "description": "Crew event on a train parted by a broken coupler (eu07/maszyna#510, review of #422): an EN57-2000 unit with an AI driver and no timetable stands on track 1 of Stacja1 on td.scn, and another one with nobody in it runs into its rear at 100 km/h. The hit breaks the coupler between the middle and the rear car of the standing unit (TMoverParameters::damage_coupler()), which parts the unit and leaves the rear car with the driver in charge of it, as uncoupling doesn't. At 10:35 a putvalues event, Crew: 0 0, takes the driver off: all three vehicles of the unit had it in charge, the parted ones too, and none of them keeps it.", + "base_scenery": "td.scn", + "ini": ["crashdamage yes"], + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\en57-2000_v1 en57-2040_ra 6ba 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_s dynamic pkp\\en57-2000_v1 en57-2040_s 6bs 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_rb dynamic pkp\\en57-2000_v1 en57-2040_rb 6bb 0 nobody 0 0 enddynamic", + "endtrainset", + "trainset none tdo_n1725 0.0 100", + "node -1 0 {{vehicle}}_hit_ra dynamic pkp\\en57-2000_v1 en57-2040_ra 6ba 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_hit_s dynamic pkp\\en57-2000_v1 en57-2040_s 6bs 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_hit_rb dynamic pkp\\en57-2000_v1 en57-2040_rb 6bb 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1035 autotest_crew_off end" + ] + }, + "duration": 120, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ broke a coupler" }, + { "type": "parts", "vehicle": "{{vehicle}}_s", "other": "{{vehicle}}_rb", "before": 30 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_parted\\] the AI driver leaves" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_parted\\] the driver was in charge of 3 vehicles" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 50, "before": 70 } + ] +} diff --git a/tests/scenarios/cases/en57_td_crew_remove.json b/tests/scenarios/cases/en57_td_crew_remove.json new file mode 100644 index 000000000..4ca053a47 --- /dev/null +++ b/tests/scenarios/cases/en57_td_crew_remove.json @@ -0,0 +1,29 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with an EN57 unit of three cars, driven from its head car while the motors are in the middle one, which loses its AI driver on the run at 10:36, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\en57_v2 EN57-1000ra EN57RA_GSO_WKM1_KM_NS_N 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_s dynamic pkp\\en57_v2 EN57-1000s EN57S_WKM1_KM_NS_S 0 nobody 255 0 enddynamic", + "node -1 0 {{vehicle}}_rb dynamic pkp\\en57_v2 EN57-1000rb EN57RB_GSO_WKM1_KM_NS 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_en57_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/ep05_td_dead_section.json b/tests/scenarios/cases/ep05_td_dead_section.json new file mode 100644 index 000000000..d6bfe2c49 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_dead_section.json @@ -0,0 +1,22 @@ +{ + "description": "#272: an EP05 (PantRequiresMain=Yes: its line breaker closes ahead of the pantographs and holds without voltage) runs the td/rozklad timetable of td.scn with one span of the overhead wire on its way, 61 m some 400 m from the start, left without voltage, and nothing on the track to tell the driver to coast. The AI runs into it under power: the line breaker stays closed (the log keeps saying the vehicle lost power, which it says only while the line breaker is closed), the traction force drops to nothing and the AI puts the master controller to 0; behind the section the AI takes power again and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 420, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 460, "to_distance": 620, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json b/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json new file mode 100644 index 000000000..4cccc94f5 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_interlock_dead_section_cold.json @@ -0,0 +1,28 @@ +{ + "description": "#272 with #276: an EP05 whose line breaker closes ahead of the pantographs (PantRequiresMain=Yes) and whose line contactors close only with its own converter running (LineContactorsInterlock=Converter, a variant of the .fiz made for the run) stands cold on track 1 of Stacja1 and gets the order to run the td/rozklad timetable, with the span without voltage of ep05_td_dead_section on its way. The pantographs go up only through the closed line breaker, so the AI has to close it first, then start the converter, and leave; under the dead wire the main circuit, and with it the converter, has no voltage; behind it the AI takes power again and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 {{variant_ep05}} 0 headdriver 0 0 enddynamic" + }, + "vehicle_variants": [ + {"name": "ep05", "from": "pkp/ep05_v2/ep05", "replace": [["Camshaft=Yes PantRequiresMain=Yes", "Camshaft=Yes PantRequiresMain=Yes LineContactorsInterlock=Converter"]]} + ], + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 420, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 460, "to_distance": 620, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_neutral_section.json b/tests/scenarios/cases/ep05_td_neutral_section.json new file mode 100644 index 000000000..ea261b0b7 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_neutral_section.json @@ -0,0 +1,26 @@ +{ + "description": "#272: as ep05_td_dead_section, with the track under the span without voltage (koniec, 371-466 m) marked as a section to coast through (overhead 0), as a scenery marks a neutral section: the AI puts the master controller to zero when the locomotive runs onto that track, coasts under the dead wire with the line breaker closed, and takes power again behind it.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "track_events": { + "koniec": "overhead 0" + }, + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "master_controller", "from_distance": 395, "to_distance": 455, "at_most": 0}, + {"type": "traction", "from_distance": 415, "to_distance": 455, "at_most": 1}, + {"type": "traction", "from_distance": 470, "to_distance": 640, "reaches": 25}, + {"type": "log_contains", "pattern": "lost power for [3-9]\\.\\d\\d sec"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_section_insulator.json b/tests/scenarios/cases/ep05_td_section_insulator.json new file mode 100644 index 000000000..2490bcf9b --- /dev/null +++ b/tests/scenarios/cases/ep05_td_section_insulator.json @@ -0,0 +1,21 @@ +{ + "description": "#272: the EP05 of ep05_td_timetable runs under power under a section insulator: a piece of the overhead wire 1 m long with no supply (\"*\", 0 V), some 375 m from the start. The pantograph is without voltage for a few hundredths of a second, which the vehicle bridges by holding the last voltage for 0.2 s (TDynamicObject::Update). Without the hold the undervoltage relay would open the line contactors, which on a PantRequiresMain vehicle close again only with the master controller back at its first position: the traction force stays up all the way past the insulator.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.687223 5.8 1500.25\r\n0.7764 5.845 1561.2417\r\n0.687223 7.5 1500.25\r\n0.7764 7.545 1561.2417\r\n0.4 4.0 3 0.04 vis\r\nendtraction", "node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.687223 5.8 1500.25\r\n0.7457 5.8295 1540.2499\r\n0.687223 7.5 1500.25\r\n0.7457 7.5295 1540.2499\r\n0.4 4.0 3 0.04 vis\r\nendtraction\r\nnode -1 0 none traction * 0 4500 0.01 cu 3.0 1\r\n0.7457 5.8295 1540.2499\r\n0.7472 5.8302 1541.2499\r\n0.7457 7.5295 1540.2499\r\n0.7472 7.5302 1541.2499\r\n0.4 4.0 3 0.04 vis\r\nendtraction\r\nnode -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7472 5.8302 1541.2499\r\n0.7764 5.845 1561.2417\r\n0.7472 7.5302 1541.2499\r\n0.7764 7.545 1561.2417\r\n0.4 4.0 3 0.04 vis\r\nendtraction"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "traction", "from_distance": 345, "to_distance": 395, "at_least": 30}, + {"type": "log_lacks", "pattern": "lost power"}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/ep05_td_timetable.json b/tests/scenarios/cases/ep05_td_timetable.json new file mode 100644 index 000000000..4291cdb72 --- /dev/null +++ b/tests/scenarios/cases/ep05_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "EP05 (PantRequiresMain=Yes) on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek. The reference run of the ep05_td_*_section cases, with the overhead wire live all the way.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/ep05_v2 ep05-23 ep05 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et21_td_no_wire_reports.json b/tests/scenarios/cases/et21_td_no_wire_reports.json new file mode 100644 index 000000000..3aeaeecde --- /dev/null +++ b/tests/scenarios/cases/et21_td_no_wire_reports.json @@ -0,0 +1,27 @@ +{ + "description": "ET21 with an AI driver on a track of td.scn's own with no overhead wire: it raises the pantographs, finds no wire and can't start; the driver tells of it in the log, once, and keeps waiting for the voltage (eu07/maszyna#421). The test ends on the standstill.", + "base_scenery": "td.scn", + "fragment": "td_no_wire.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\et21_v2 ET21-367 3e2 0 headdriver 0 0 enddynamic" + }, + "test_config": [ + "test.standstill 300" + ], + "expect": "standstill", + "timeout": 900, + "checks": [ + { + "type": "log_contains", + "pattern": "AI \\[autotest_et21_td_no_wire_reports\\]: can't start, no overhead wire above its raised pantographs \\(at -?[\\d.]+, -?[\\d.]+, -?[\\d.]+\\)" + }, + { + "type": "log_lacks", + "pattern": "no voltage in the overhead wire at its raised pantographs" + }, + { + "type": "distance", + "max": 1 + } + ] +} diff --git a/tests/scenarios/cases/et22_764_td_downgrade_restriction.json b/tests/scenarios/cases/et22_764_td_downgrade_restriction.json new file mode 100644 index 000000000..b53a23411 --- /dev/null +++ b/tests/scenarios/cases/et22_764_td_downgrade_restriction.json @@ -0,0 +1,62 @@ +{ + "description": "An ET22 with 20 loaded heavy wagons 764 (Uaai, 84 t of machinery each, KE, G; about 2650 t) on the line of et41_coal_td_downgrade_restriction: down 20 per mille into a 20 km/h restriction 400 m long, then to the signal at stop. The train is to keep above 10 km/h through the restriction (#187: it almost stops).", + "xfail": "#187, #263: down 20 per mille the AI holds the 20 km/h restriction by applying and releasing the train brake in turn (handle 0, then 1.25-2.75, then 0 again); the release of this G train takes 10-15 s, so each one comes late and the train dips to 8.5 km/h, below the 10 km/h #263 counts as a defect. It doesn't stop. Known limitation of the AI, not fixed here", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_restriction.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et22_v3 201E-1150 201E 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic db\\uaaikks_v1 993_6_221-5 764 0 nobody 3 84 hmachinnery1 enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 10, + "until_distance": 2450 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2950, + "max_distance": 3110 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json b/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json new file mode 100644 index 000000000..966c6b0a8 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_downgrade_restriction.json @@ -0,0 +1,67 @@ +{ + "description": "An ET41 with 25 loaded coal wagons (412W, 60 t each, cast-iron blocks, G; about 1670 t) on a line of its own beside td.scn: from the level down a gradient of 20 per mille at the 60 km/h of its timetable, into a 20 km/h restriction 400 m long 1500 m down the gradient, then to the signal at stop 3000 m down. The train is to pass through the restriction without coming to a stand, and stop at the signal (#263, #187).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_restriction.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 10, + "until_distance": 2400 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2950, + "max_distance": 3110 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_slippery_start.json b/tests/scenarios/cases/et41_coal_td_slippery_start.json new file mode 100644 index 000000000..34696d422 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_slippery_start.json @@ -0,0 +1,66 @@ +{ + "description": "An ET41 with 25 fully loaded coal wagons (412W, 80 t each, G; about 2170 t) starts on level track with the rail friction at 0.3 of its normal (eu07.ini friction 0.3, as on wet leaves), and runs to the signal at stop 1000 m ahead. The train is to get going, keep moving and stop at the signal (#187: heavy trains slip, grip and snatch over and over and often don't get going).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_level_signal.scn", + "timetable": "td_freight_downgrade.txt", + "ini": [ + "friction 0.3" + ], + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 60 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "moves", + "vehicle": "{{vehicle}}", + "min_speed": 10 + }, + { + "type": "keeps_moving", + "moving_speed": 5, + "min_speed": 3, + "from_distance": 100, + "until_distance": 900 + }, + { + "type": "stops", + "moving_speed": 10, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1040, + "max_distance": 1150 + } + ] +} diff --git a/tests/scenarios/cases/et41_coal_td_upgrade_start.json b/tests/scenarios/cases/et41_coal_td_upgrade_start.json new file mode 100644 index 000000000..05d005919 --- /dev/null +++ b/tests/scenarios/cases/et41_coal_td_upgrade_start.json @@ -0,0 +1,73 @@ +{ + "description": "An ET41 with 25 loaded coal wagons (412W, 60 t each, G; about 1670 t) on a line of its own beside td.scn: up a gradient of 10 per mille to the signal hu_sem1 1000 m up, at stop until 10:42, where it stops with the whole train on the gradient; when the signal clears, it is to start without rolling back and get away, to the signal at stop 2300 m up (#265, #187).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_upgrade_signal_start.scn", + "timetable": "td_freight_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\et41_v2 41-045-a 203e-a 0 headdriver 55 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp\\et41_v2 41-045-b 203e-b 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\412w_v2 31515362022-6 412W 0 nobody 3 40 coal enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 300 + }, + { + "type": "max_speed", + "limit": 60, + "tolerance": 5 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 60, + "min_distance": 1040, + "max_distance": 1110 + }, + { + "type": "starts_again", + "after": 480, + "min_speed": 10, + "within": 120, + "max_rollback": 1.0 + }, + { + "type": "distance", + "min": 2340, + "max": 2410 + } + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock.json b/tests/scenarios/cases/et42_td_converter_interlock.json new file mode 100644 index 000000000..35d78a4f4 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock.json @@ -0,0 +1,24 @@ +{ + "description": "#276: as et42_td_converter_interlock_cold, from the timetable start (trainset velocity 0.1, the locomotive ready to go).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]} + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock_cold.json b/tests/scenarios/cases/et42_td_converter_interlock_cold.json new file mode 100644 index 000000000..f8dfdff56 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock_cold.json @@ -0,0 +1,27 @@ +{ + "description": "#276: an ET42 whose sections take power only with their own converter running (LineContactorsInterlock=Converter in Cntrl., the .fiz key the shipped et42_v2 doesn't have yet: a variant of both sections made for the run) stands cold on track 1 of Stacja1 on td.scn and gets the order to run the td/rozklad timetable. The AI has to start the converters before the line contactors close: it leaves, keeps to the speed limit and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter"]]} + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json b/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json new file mode 100644 index 000000000..d492aa671 --- /dev/null +++ b/tests/scenarios/cases/et42_td_converter_interlock_slow_converter.json @@ -0,0 +1,27 @@ +{ + "description": "#276, the check that the interlock takes effect: the ET42 of et42_td_converter_interlock_cold, with ConverterStartDelay=60 added to both sections, so the converters need a minute to start. With LineContactorsInterlock=Converter the line contactors wait for them and the train leaves later than it does with the same converter delay and no interlock (20 km/h at 80.0 s with it, at 73.8 s without it, measured with this case and a copy without the interlock key). Then it runs the timetable to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/et42_v2 112e-014-a {{variant_a}} 0 headdriver 255 0 enddynamic", + "node -1 0 {{vehicle}}_b dynamic pkp/et42_v2 112e-014-b {{variant_b}} 0 nobody 3 0 enddynamic" + ] + }, + "vehicle_variants": [ + {"name": "a", "from": "pkp/et42_v2/112e-a", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter ConverterStartDelay=60"]]}, + {"name": "b", "from": "pkp/et42_v2/112e-b", "replace": [["IniCDelay=0.5 SCDelay=0.1", "IniCDelay=0.5 SCDelay=0.1 LineContactorsInterlock=Converter ConverterStartDelay=60"]]} + ], + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "after": 77, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "brakes", "min_pressure": 0.5}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json new file mode 100644 index 000000000..1faae73ff --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_downgrade_w4_signal.json @@ -0,0 +1,42 @@ +{ + "description": "An EU07 with three coaches on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. A train braking with the train brake, the control of the light EU07 and SN61 cases.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/eu07_coaches_td_timetable.json b/tests/scenarios/cases/eu07_coaches_td_timetable.json new file mode 100644 index 000000000..c8621c3b0 --- /dev/null +++ b/tests/scenarios/cases/eu07_coaches_td_timetable.json @@ -0,0 +1,40 @@ +{ + "description": "EU07 with three coaches on td.scn, AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek with the train brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 90, + "tolerance": 3 + }, + { + "type": "brakes", + "min_pressure": 0.5 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_buckle_derails.json b/tests/scenarios/cases/eu07_td_buckle_derails.json new file mode 100644 index 000000000..8506736a5 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_derails.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event: 600 mm out of the curve over a main lobe of 8 m (an equivalent radius of 9 m, about 30 m for the body on axles 11 m apart). The AI doesn't see it and runs into it at the 46 km/h it has there: with physics.derailment new (the default, monitor, only logs what the criteria would do and the train runs on) the locomotive leaves the rails on the buckle and stops short of Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "600 8" + }, + "ini": ["gfxrenderer null", "physics.derailment new"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 600 mm to the (left|right) at [0-9.]+ m, main lobe 8.0 m" }, + { "type": "log_contains", "pattern": "Bad driving: autotest_\\S+ derailed on buckled track" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "distance", "max": 1100 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_buckle_event.json b/tests/scenarios/cases/eu07_td_buckle_event.json new file mode 100644 index 000000000..13e0da7bc --- /dev/null +++ b/tests/scenarios/cases/eu07_td_buckle_event.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles with a trackbuckle event (30 mm out of the curve, as the heat does: an equivalent radius of 330 m, too little to derail it). The track is laid again during the game and the train keeps on it to Przystanek, with physics.derailment new: the criteria decide, as in eu07_td_buckle_derails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "amplitude": "30" + }, + "ini": ["gfxrenderer null", "physics.derailment new"], + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Track \"tdo_n222\" buckled \\(event autotest_buckle\\): 30 mm to the (left|right)" }, + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }, + { "type": "log_lacks", "pattern": "Bad driving" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_cold_connect.json b/tests/scenarios/cases/eu07_td_cold_connect.json new file mode 100644 index 000000000..26c975861 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_cold_connect.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with a hand brake (4E-ZEZ_GREY) on td.scn, standing cold with the hand brake on, gets the order to couple to the two coaches standing 45 m ahead (Shunt -1 3): after starting the engine it has to release its hand brake, run up to the coaches, couple and push them on. Connect is the first order the AI drives under.", + "base_scenery": "td.scn", + "fragment": "td_cold_connect.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4E-ZEZ-234 4E-ZEZ_GREY", + "rake": [ + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "tdo_n1725": "event0 autotest_wake", + "tor1k": "eventall2 autotest_pass" + }, + "test_config": [ + "test.timeout 900", + "test.standstill 300", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 900, + "checks": [ + { "type": "couples", "vehicle": "{{vehicle}}", "other": "{{vehicle}}_c2" }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_add.json b/tests/scenarios/cases/eu07_td_crew_add.json new file mode 100644 index 000000000..eb3c3637c --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_add.json @@ -0,0 +1,31 @@ +{ + "description": "Crew event, a driver appears (eu07/maszyna#510): an EU07 stands cold on track 1 of Stacja1 on td.scn with nobody in it. 20 s after the start a putvalues event, Crew: 1 0, puts an AI driver in its cab A; the scenery then gives the driver the order to go (Shunt -1 0 from event0 of the track), and the driver starts the locomotive and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_add\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "starts", "min_speed": 20, "within": 240 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_add_rear.json b/tests/scenarios/cases/eu07_td_crew_add_rear.json new file mode 100644 index 000000000..a4a677807 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_add_rear.json @@ -0,0 +1,33 @@ +{ + "description": "Crew event, a driver appears in cab B (eu07/maszyna#510): as eu07_td_crew_add, with Crew: -1 0. The driver takes the rear cab, so the order to go sends the locomotive the other way, its rear end leading.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} -1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "test_config": [ + "test.fail_if_stop_overran no" + ], + "duration": 200, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_add_rear\\] an AI driver takes cab B" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "rear", "min_speed": 5 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_refused.json b/tests/scenarios/cases/eu07_td_crew_refused.json new file mode 100644 index 000000000..4dc273e03 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_refused.json @@ -0,0 +1,40 @@ +{ + "description": "Crew events which must change nothing (eu07/maszyna#510): the run of eu07_td_timetable, with a coach standing on track 2, and crew events set off at the start and again at 10:36, on the run: a second driver for the locomotive (it has one), a driver for the coach (no cab), a cab which is none of 1, -1, 0, a driver taken off the coach (it has none) and a vehicle the scenery lacks. Each is refused in the log and the train runs its timetable to the stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset", + "trainset none tor2k 30.0 0.0", + "node -1 0 {{vehicle}}_coach dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_second putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_coach putvalues 0 none 0 0 0 Crew:{{vehicle}}_coach 1 0 endevent", + "event autotest_crew_cab putvalues 0 none 0 0 0 Crew:{{vehicle}} 2 0 endevent", + "event autotest_crew_nobody putvalues 0 none 0 0 0 Crew:{{vehicle}}_coach 0 0 endevent", + "event autotest_crew_unknown putvalues 0 none 0 0 0 Crew:autotest_no_such_vehicle 0 0 endevent", + "event autotest_crew_all multiple 0 none autotest_crew_second autotest_crew_coach autotest_crew_cab autotest_crew_nobody autotest_crew_unknown endevent", + "node -1 0 autotest_crew_launcher1 eventlauncher 0 0 0 -1 none 1034 autotest_crew_all end", + "node -1 0 autotest_crew_launcher2 eventlauncher 0 0 0 -1 none 1036 autotest_crew_all end" + ] + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused\\] refused, the vehicle has a driver already" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused_coach\\] refused, the vehicle has no cab" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused\\] refused, the cab has to be 1, -1 or 0" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_refused_coach\\] no driver to take off" }, + { "type": "log_contains", "pattern": "PutValues - \\[Crew:autotest_no_such_vehicle\\]" }, + { "type": "log_lacks", "pattern": "Crew: .* (takes cab|leaves)" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_remove.json b/tests/scenarios/cases/eu07_td_crew_remove.json new file mode 100644 index 000000000..8f1968eaa --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_remove.json @@ -0,0 +1,27 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): an EU07 with an AI driver leaves Stacja1 on td.scn on the td/rozklad timetable at 10:35. At 10:36, on the run, a putvalues event, Crew: 0 0, takes the driver off: the locomotive is left with the power off and the brake valve in the emergency position, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_crew_swap.json b/tests/scenarios/cases/eu07_td_crew_swap.json new file mode 100644 index 000000000..4614c4622 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_crew_swap.json @@ -0,0 +1,34 @@ +{ + "description": "Crew events, the driver is replaced (eu07/maszyna#510): an EU07 with an AI driver waits on track 1 of Stacja1 on td.scn. 20 s after the start Crew: 0 0 takes the driver off, which leaves the locomotive braked; 20 s later Crew: 1 0 puts a new one in cab A, who gets the order to go (Shunt -1 0 from event0 of the track), releases the brakes and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 20 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_off end", + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 40 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_swap\\] the AI driver leaves" }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_eu07_td_crew_swap\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 35, "before": 50 }, + { "type": "starts", "min_speed": 20, "within": 200 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/eu07_td_dead_section.json b/tests/scenarios/cases/eu07_td_dead_section.json new file mode 100644 index 000000000..44c4c38f5 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_dead_section.json @@ -0,0 +1,22 @@ +{ + "description": "The reference of ep05_td_dead_section: an EU07, whose pantographs come first and whose line breaker opens without voltage (no PantRequiresMain), runs into the same span without voltage under power. Its line breaker opens 0.2 s into the section (the log says it lost power for 0.2x s, no longer: it says so only while the line breaker is closed), and behind it the AI closes the line breaker again, takes power and stops at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "replace": [ + ["node -1 0 none traction pwr01 3500 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417", "node -1 0 none traction none 0 4500 0.01 cu 3.0 1\r\n0.7764 5.845 1561.2417"] + ], + "duration": 240, + "timeout": 600, + "checks": [ + {"type": "starts", "min_speed": 20, "within": 150}, + {"type": "max_speed", "limit": 90, "tolerance": 3}, + {"type": "log_contains", "pattern": "lost power for 0\\.2\\d sec"}, + {"type": "log_lacks", "pattern": "lost power for (0\\.[3-9]|[1-9])"}, + {"type": "traction", "from_distance": 460, "to_distance": 700, "reaches": 25}, + {"type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420} + ] +} diff --git a/tests/scenarios/cases/eu07_td_departure_station.json b/tests/scenarios/cases/eu07_td_departure_station.json new file mode 100644 index 000000000..eb97b708c --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station.json @@ -0,0 +1,35 @@ +{ + "description": "Control for eu07_td_departure_station_capitals: the same timetable with the first row written as in the relation (Stacja1). The train stops at Stacja1 and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST25: at \\d+:\\d+ passed Stacja1" + }, + { + "type": "log_contains", + "pattern": "as TEST25: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_departure_station_capitals.json b/tests/scenarios/cases/eu07_td_departure_station_capitals.json new file mode 100644 index 000000000..cf1cbe2bd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_departure_station_capitals.json @@ -0,0 +1,35 @@ +{ + "description": "EU07 on td.scn on a timetable whose first row, the station of departure, is written in capitals (STACJA1) and gives no arrival time, while the relation says Stacja1. The train is to stop there and wait for its departure at 10:35, not take Stacja1 for a station it passes through and leave as soon as the route is set at 10:34 (linia_107_poludnie.scn, Os33733 at ZAGORZ).", + "base_scenery": "td.scn", + "time": "10:33", + "fragment": "td_departure_station.scn", + "timetable": "td_departure_station_capitals.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 360, + "timeout": 600, + "checks": [ + { + "type": "log_lacks", + "pattern": "as TEST24: at \\d+:\\d+ passed STACJA1" + }, + { + "type": "log_contains", + "pattern": "as TEST24: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json new file mode 100644 index 000000000..e26f6180d --- /dev/null +++ b/tests/scenarios/cases/eu07_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "A light EU07 on a line of its own beside td.scn, down a gradient of 20 per mille on a timetable: stops at the W4 of Dol 1500 m down the gradient, leaves at 10:38 and stops before the signal gr_sem at stop 1100 m further down. The EU07 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 355, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json b/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json new file mode 100644 index 000000000..8c06596c8 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_hauls_dead_vectron.json @@ -0,0 +1,20 @@ +{ + "description": "EU07 on td.scn hauls a dead Vectron prepared for hauling (coupling 3, parameter H: the pullee mode of MaSzyna-EU07/maszyna#64), AI driver on the td/rozklad timetable: starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek. Without the H the Vectron vents the brake pipe and the train never moves.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 dead_{{vehicle}} dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 0.H 0 enddynamic" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json b/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json new file mode 100644 index 000000000..ed43f3c98 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_hauls_dead_vectron_cold.json @@ -0,0 +1,23 @@ +{ + "description": "As eu07_td_hauls_dead_vectron, from a cold start: the trainset stands with velocity 0, so both locomotives start braked (brake pipe at 3.5 bar, batteries off, the Vectron's spring brake on). The EU07's driver gets the order to run as a train, starts the engine, charges the brake pipe and hauls the Vectron, prepared for hauling (parameter H), to Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp/4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 dead_{{vehicle}} dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 0.H 0 enddynamic" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_buckle.json b/tests/scenarios/cases/eu07_td_off_track_buckle.json new file mode 100644 index 000000000..29768b643 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_buckle.json @@ -0,0 +1,56 @@ +{ + "description": "physics.derailment new: EU07 with three coaches on td.scn on the td/rozklad timetable; at 10:35, as it leaves, the curve tdo_n222 about 950 m ahead buckles hard with a trackbuckle event (600 mm out of the curve over a main lobe of 8 m). The AI runs into it at the 33-35 km/h it has there with the coaches (46 km/h alone): the locomotive overturns on the buckle, goes off the track towards the bulge, falls on its side and stops on the ground some 30 m on; the coupling pulls the first coach off the rails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_buckle_event.scn", + "vars": { + "amplitude": "600 8", + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 240, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "Track \\\"tdo_n222\\\" buckled \\(event autotest_buckle\\): 600 mm" + }, + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+ leaves the track" + }, + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}", + "min_offset": 3, + "max_distance": 45, + "min_distance": 15, + "lying": true + }, + { + "type": "consist_folds", + "vehicles": "{{vehicle}},{{vehicle}}_w1", + "min_bend": 15 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json new file mode 100644 index 000000000..6b7154396 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_buckle_fast.json @@ -0,0 +1,55 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 133 km/h into the curve tdo_n222 of td.scn (R 600 m, cant 65 mm), buckled hard 600 mm over a main lobe of 8 m from the start (the buckle keyword of the track). The locomotive overturns on the buckle: it leaves the track, falls on its side within a second and slides on the ground to a stop some 170 m on, 30 m off the track; the coaches behind it go off and over as well, and the train comes to rest folded, the vehicles turned against each other by 10 to 20 degrees.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "tdo_n157", + "offset": "60", + "velocity": "133", + "track_nodes": "", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 20, + "min_distance": 120, + "max_distance": 230, + "lying": true + }, + { + "type": "consist_folds", + "vehicles": "{{vehicle}}_off,{{vehicle}}_off_w1,{{vehicle}}_off_w2,{{vehicle}}_off_w3", + "min_bend": 8, + "min_folds": 2 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ], + "track_events": { + "tdo_n222": "buckle 600;8" + } +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json b/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json new file mode 100644 index 000000000..8b930e541 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_cutting.json @@ -0,0 +1,36 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5 (triangles of the fragment). Over its overturning speed (about 120 km/h) it overturns out of the curve: it runs into the bank on the outside of the curve, climbs it and stops sooner than on level ground.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_cutting.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 230 + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json b/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json new file mode 100644 index 000000000..6db8b4ed8 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_embankment.json @@ -0,0 +1,37 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), on an embankment 4 m high with slopes of 1:1.5 (triangles of the fragment). Over its overturning speed (about 120 km/h) it overturns out of the curve: it falls on its side over the edge of the embankment, slides down its slope and on over the level ground at its foot, 4 m lower.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_embankment.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 280, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_curve_flat.json b/tests/scenarios/cases/eu07_td_off_track_curve_flat.json new file mode 100644 index 000000000..df4103e81 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_curve_flat.json @@ -0,0 +1,37 @@ +{ + "description": "physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), on level ground (the grass of td.scn). Over its overturning speed (about 120 km/h) it overturns out of the curve: it slides on the grass out of the curve, falls on its side and stops.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track_curve_flat.scn", + "vars": { + "velocity": "150" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 40, + "min_distance": 150, + "max_distance": 260, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_end.json b/tests/scenarios/cases/eu07_td_off_track_end.json new file mode 100644 index 000000000..5a37cb2d0 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_end.json @@ -0,0 +1,46 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 60 km/h off the end of a track of 150 m laid on its own in the fields of td.scn (autotest_stub): it runs straight on, upright, on the ground, and stops some 30 m on (the friction of 0.3 against the 39 km/h left of its 60 km/h as it drops off the end of the rails, the coaches pushing it); the first coach follows it off the end.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "autotest_stub", + "offset": "100", + "velocity": "60", + "track_nodes": "node -1 0 autotest_stub track normal 150.0 1.435 0.15 25.0 20 0 flat vis\n rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1\n-150.0 0.2 600.0 0.0 //point 1\n0.0 0.0 0.0 //control vector 1\n0.0 0.0 0.0 //control vector 2\n-150.0 0.2 750.0 0.0 //point 2\n0\nendtrack", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "end of track", + "max_offset": 0.5, + "min_distance": 5, + "max_distance": 60, + "lying": false + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_off_track_overturn.json b/tests/scenarios/cases/eu07_td_off_track_overturn.json new file mode 100644 index 000000000..c1bff7403 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_off_track_overturn.json @@ -0,0 +1,46 @@ +{ + "description": "physics.derailment new: an EU07 with three coaches and no driver runs at 190 km/h into the curve of R 600 m of td.scn (tdo_n213, tdo_n222), cant 65 mm: over the overturning speed (about 165 km/h) it overturns out of the curve, falls on its side and slides off the track to a stop; the coaches go over as well.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_off_track.scn", + "vars": { + "track": "tdo_n157", + "offset": "60", + "velocity": "190", + "track_nodes": "", + "consist": [ + "node -1 0 {{vehicle}}_off dynamic pkp\\4e_v1 4e-004 4e 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_off_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_off_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic" + ] + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 50, + "min_distance": 250, + "max_distance": 420, + "lying": true + }, + { + "type": "no_overlap", + "max_transient": 0.2, + "max_at_rest": 0.05 + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_overspeed_bad_limit.json b/tests/scenarios/cases/eu07_td_overspeed_bad_limit.json new file mode 100644 index 000000000..95882c765 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_overspeed_bad_limit.json @@ -0,0 +1,35 @@ +{ + "description": "physics.derailment new with physics.derailment.trustlimits (the default yes): an EU07 without a driver runs at 140 km/h into a curve of R 300 m without cant with a speed limit of 140 km/h, a track laid on its own in the fields of td.scn (autotest_curve) and a straight one on from it. The limit is a defect of the data (EU07 overturns in that curve at about 108 km/h), and 140 km/h is under its trusted speed of 159 km/h (the limit * 1.1 + 5 km/h): the criteria would overturn it, but it stays on the rails and runs on, and the log names the track once as a defect of the scenery.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_overspeed_bad_limit.scn", + "vars": { + "velocity": "140" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 20, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment monitor: data: autotest_\\S+_off held on the rails on track autotest_curve under its trusted speed of 159 km/h \\(speed limit 140 km/h" + }, + { + "type": "log_lacks", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "log_lacks", + "pattern": "Bad driving: autotest_\\S+_off" + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}_off" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_overspeed_bad_limit_fast.json b/tests/scenarios/cases/eu07_td_overspeed_bad_limit_fast.json new file mode 100644 index 000000000..28ecd8c0a --- /dev/null +++ b/tests/scenarios/cases/eu07_td_overspeed_bad_limit_fast.json @@ -0,0 +1,34 @@ +{ + "description": "physics.derailment new with physics.derailment.trustlimits: the curve of eu07_td_overspeed_bad_limit (R 300 m without cant, a speed limit of 140 km/h trusted up to 159 km/h) taken at 175 km/h, well over the trusted speed: the driver went too fast, the criteria decide, and the EU07 overturns out of the curve and slides on the grass to a stop on its side, as on the curve without a limit (eu07_td_off_track_curve_flat).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_overspeed_bad_limit.scn", + "vars": { + "velocity": "175" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "log_lacks", + "pattern": "derailment monitor: data:" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 10, + "lying": true + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_overspeed_bad_limit_untrusted.json b/tests/scenarios/cases/eu07_td_overspeed_bad_limit_untrusted.json new file mode 100644 index 000000000..b409cf9b5 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_overspeed_bad_limit_untrusted.json @@ -0,0 +1,35 @@ +{ + "description": "eu07_td_overspeed_bad_limit with physics.derailment.trustlimits no: the criteria decide at any speed, as before the key, so the EU07 at the limit of 140 km/h overturns out of the curve of R 300 m it takes at 108 km/h.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_overspeed_bad_limit.scn", + "vars": { + "velocity": "140" + }, + "ini": [ + "gfxrenderer null", + "physics.derailment new", + "couplerphysics all", + "physics.derailment.trustlimits no" + ], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "derailment: autotest_\\S+_off leaves the track" + }, + { + "type": "log_lacks", + "pattern": "derailment monitor: data:" + }, + { + "type": "leaves_track", + "vehicle": "{{vehicle}}_off", + "cause": "overturned", + "min_offset": 10, + "lying": true + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json new file mode 100644 index 000000000..be4b96feb --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_after_coupling.json @@ -0,0 +1,69 @@ +{ + "description": "eu07/maszyna#350, #282: an EU07 on td.scn couples on the run (Shunt -3 3) to a cut standing on the line, 16 coaches with P alone and 8 empty wagons with G and P, 541 m of wagons, and runs it on as a train (Obey_train): a train on G (Cw-1 19.1), so the brakes of the coaches are to be cut out (19.9). The inspector looks at the train as it couples, at 4 km/h, and leaves the cut-outs for the standstill; reinspect_brakes() makes them as the train stands just after. The driver taken off at 38 km/h leaves the brake valve in the emergency position: braked by the locomotive and the 8 wagons alone the train stops at some 0.27 m/s2, over 210 m (with every brake working, 0.57 m/s2 over 99 m).", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 90, + "hold": 60, + "min_deceleration": 0.15, + "max_deceleration": 0.4 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json new file mode 100644 index 000000000..e3a03c2da --- /dev/null +++ b/tests/scenarios/cases/eu07_td_reinspect_brakes_legacy_inspector.json @@ -0,0 +1,71 @@ +{ + "description": "The train of eu07_td_reinspect_brakes_after_coupling with the inspector of the releases before eu07/maszyna#350 (ai.brakesetting.cw1 no), which cuts no brake out: every brake of the train works, and the emergency stop after the driver is taken off at 38 km/h comes at some 0.57 m/s2, over 99 m. It shows what the deceleration check of that case tells apart.", + "base_scenery": "td.scn", + "fragment": "td_reinspect_brakes.scn", + "vars": { + "locomotive": "pkp\\4e_v1 4e-004 4e", + "cut": [ + "node -1 0 {{vehicle}}_c01 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c02 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c03 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c04 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c05 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c06 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c07 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c08 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c09 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c10 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c11 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c12 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c13 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c14 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c15 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c16 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w4 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w5 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w6 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w7 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_w8 dynamic pkp\\401w_v2 82515314470-4 401w_w_d 0 nobody 0 0 enddynamic" + ] + }, + "track_events": { + "koniec": "event0 autotest_wake", + "tdo_n231": "event2 autotest_way", + "tdo_n240": "event2 autotest_crew_off" + }, + "test_config": [ + "test.timeout 1200", + "test.standstill 600" + ], + "expect": "pass", + "timeout": 600, + "checks": [ + { + "type": "couples", + "vehicle": "{{vehicle}}", + "other": "{{vehicle}}_w8" + }, + { + "type": "stops_driverless", + "vehicle": "{{vehicle}}", + "min_speed": 30, + "within": 60, + "hold": 60, + "min_deceleration": 0.45 + }, + { + "type": "log_lacks", + "pattern": "derailed" + }, + { + "type": "log_lacks", + "pattern": "collided" + } + ], + "ini": [ + "ai.brakesetting.cw1 no" + ] +} diff --git a/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json new file mode 100644 index 000000000..243d37641 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_push_red_signal.json @@ -0,0 +1,24 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt), pushing three coaches with no route set, the first coach starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "velocity": "30", + "consist": [ + "node -1 0 {{vehicle}}_w1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608011-6 BDHPUMN_NG_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}}_w3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 115 0 enddynamic", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + ] + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 40 }, + { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 }, + { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 }, + { "type": "distance", "max": 150 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_shunt_red_signal.json b/tests/scenarios/cases/eu07_td_shunt_red_signal.json new file mode 100644 index 000000000..bc23046cd --- /dev/null +++ b/tests/scenarios/cases/eu07_td_shunt_red_signal.json @@ -0,0 +1,19 @@ +{ + "description": "EU07 shunting on td.scn (no timetable, so its AI drives under Shunt) with no route set, starting at 30 km/h about 150 m before the exit signal stacja1_j at stop: stops before the signal and stays there.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_shunt_red_signal.scn", + "vars": { + "offset": "0.0", + "velocity": "30", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 40 }, + { "type": "stops", "moving_speed": 5, "stop_speed": 0.5, "hold": 5 }, + { "type": "stays_stopped", "moving_speed": 5, "stop_speed": 0.5 }, + { "type": "distance", "max": 150 } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_facing_control.json b/tests/scenarios/cases/eu07_td_switch_facing_control.json new file mode 100644 index 000000000..e512703d7 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_facing_control.json @@ -0,0 +1,52 @@ +{ + "description": "Switch under a train, the control of the facing cases (#289 review 2b): an EU07 with three coaches runs from the west line into Stacja1 on td.scn, facing through switch zwr01, which is set to track 1 from the start (keyctrl02, with the entry signal at 40). Nothing is thrown. The train has to stop before a signal at stop on track 1 and stay on the rails.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl02 end", + "throw": "zwr01_1", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "tdo_n1725": [ + "event2 autotest_signal1_info", + "event0 autotest_pass" + ], + "tdo_n1734": [ + "eventall1 autotest_fail", + "eventall2 autotest_fail" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json b/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json new file mode 100644 index 000000000..7798cef47 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_facing_behind.json @@ -0,0 +1,50 @@ +{ + "description": "Switch thrown under a train running facing through it (#289 review 2b): as eu07_td_switch_thrown_facing_head, but zwr01 is thrown to track 1 when the locomotive has left the switch for track 2 (event of tor2p, set off by its rear axle), with the coaches still before and on the switch. A train cannot run on two tracks at once: every vehicle has to keep to the line of a track, whatever the throw does to them.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl01 end", + "throw": "zwr01_1 zwr01_V40", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "tor2p": [ + "event1 autotest_throw", + "event2 autotest_throw" + ], + "tdo_n109": "event0 autotest_pass" + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): the axles still on the switch leave it by the way it is set to now, those behind it take that way too, so the coaches go to track 1 and the locomotive they are coupled to runs on along track 2, 4.6 m beside them, with nothing derailed or broken" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json b/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json new file mode 100644 index 000000000..c02cad4d7 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_facing_head.json @@ -0,0 +1,57 @@ +{ + "description": "Switch thrown under a train running facing through it (#289 review 2b): as eu07_td_switch_facing_control, but the way is set to track 2 (keyctrl01) and zwr01 is thrown to track 1 when the locomotive has run onto the switch with both its bogies (event of the switch track, set off by its rear axle). The locomotive and the train behind it have to go on to track 1 and stay on the rails, and the AI has to stop before the signal at stop on track 1.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none start 80.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl01 end", + "throw": "zwr01_1 zwr01_V40", + "trigger": "", + "order": "Shunt -1 0" + }, + "track_events": { + "start": "event0 autotest_wake", + "zwr01": [ + "event1 autotest_throw", + "event2 autotest_throw" + ], + "tdo_n1725": [ + "event2 autotest_signal1_info", + "event0 autotest_pass" + ], + "tdo_n1734": [ + "eventall1 autotest_fail", + "eventall2 autotest_fail" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 30, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): an axle keeps the way of the switch it ran onto but leaves by the way the switch is set to now, so the locomotive jumps 1.9 m sideways at the end of the switch, an axle at a time; and the AI keeps the route it scanned before the throw (a switch behind the head of the train is not scanned again), so on track 1 it brakes for the exit signal of track 2 and runs past the signal at stop of track 1 at 40 km/h" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json b/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json new file mode 100644 index 000000000..fb3694906 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_standing_facing.json @@ -0,0 +1,49 @@ +{ + "description": "Switch thrown under a standing train, which then leaves facing through it (#289 review 2b): an EU07 with three coaches stands cold across zwr01 on td.scn, the locomotive on track 2, the last coaches over the switch, which is set to track 2. 5 s after the start the switch is thrown to track 1; then the driver gets the order to go, into the station, facing through the switch. Every vehicle has to keep to the line of a track.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tor2p 50.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "", + "throw": "zwr01_1 zwr01_V40", + "trigger": [ + "event autotest_throw_later multiple 5 none autotest_throw endevent", + "node -1 0 autotest_throw_launcher eventlauncher 0 0 0 -1 none 1034 autotest_throw_later end" + ], + "order": "Shunt -1 0" + }, + "track_events": { + "tor2p": "event0 autotest_wake_after_throw", + "tdo_n109": "event0 autotest_pass" + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ], + "xfail": "#289 review 2b, as before the stack (TrkFoll reverted in c268673c): the axles that stood on the switch leave it by the way it is set to now, so the second coach runs with one bogie on track 2 and the other on track 1, 4.6 m apart, its body 2.3 m off both, with nothing derailed or broken; and the AI scans its route from the last vehicle through the switch as now set, reads the signals of track 1 while it runs on track 2, and its head is counted past the exit signal of track 1 at stop" +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json b/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json new file mode 100644 index 000000000..321806476 --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_standing_trailing.json @@ -0,0 +1,52 @@ +{ + "description": "Switch thrown under a standing train, which then leaves trailing through it (#289 review 2b): an EU07 with three coaches stands cold across zwr02 on td.scn, the locomotive on the line, the coaches behind it over the switch and on track 2, the switch set to track 2. 5 s after the start it is thrown to track 1; then the driver gets the order to go, out to the line. The wheels coming from track 2 push the switch back over (as through any switch set against them from the frog end); every vehicle has to keep to the line of a track. Passes once the locomotive runs onto tdo_n176, with the train clear of the switch.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n145 40.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "", + "throw": "zwr02_1 zwr02_v40", + "trigger": [ + "event autotest_throw_later multiple 5 none autotest_throw endevent", + "node -1 0 autotest_throw_launcher eventlauncher 0 0 0 -1 none 1034 autotest_throw_later end" + ], + "order": "Obey_train 0 0" + }, + "track_events": { + "tdo_n145": "event0 autotest_wake_after_throw", + "tdo_n176": [ + "event1 autotest_pass_running", + "event2 autotest_pass_running" + ] + }, + "test_config": [ + "test.timeout 400", + "test.standstill 120", + "test.no_movement_before_pass no" + ], + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 10, + "within": 200 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json b/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json new file mode 100644 index 000000000..21d0d7bac --- /dev/null +++ b/tests/scenarios/cases/eu07_td_switch_thrown_trailing.json @@ -0,0 +1,56 @@ +{ + "description": "Switch thrown under a train running trailing through it (#289 review 2b): the td/rozklad timetable train, an EU07 with three coaches, leaves track 1 of Stacja1 on td.scn through zwr02 from its frog end; when the locomotive has run onto the line (event of tdo_n145, set off by its rear axle) the switch is thrown to track 2 under the coaches. The wheels coming from track 1 push it back over; the train has to stay on the rails and run its timetable to the stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_switch_thrown.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "route": "node -1 0 autotest_route_launcher eventlauncher 0 0 0 -1 none 1034 keyctrl04 end", + "throw": "zwr02_0 zwr02_vmax", + "trigger": "", + "order": "Obey_train 0 0" + }, + "track_events": { + "tdo_n145": [ + "event1 autotest_throw", + "event2 autotest_throw" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 240 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 0, + "min_distance": 1380, + "max_distance": 1420 + }, + { + "type": "on_track", + "vehicles": "{{vehicle}}", + "max_offset": 0.6 + }, + { + "type": "log_lacks", + "pattern": "Bad driving" + }, + { + "type": "log_contains", + "pattern": "EVENT LAUNCHED.*: autotest_throw_done$" + } + ] +} diff --git a/tests/scenarios/cases/eu07_td_timetable_past_w4.json b/tests/scenarios/cases/eu07_td_timetable_past_w4.json new file mode 100644 index 000000000..c60effbed --- /dev/null +++ b/tests/scenarios/cases/eu07_td_timetable_past_w4.json @@ -0,0 +1,28 @@ +{ + "description": "EU07 with three coaches on td.scn on the td/rozklad timetable, placed with its head 80 m past the W4 of Stacja1, the first station of the timetable, which stays under the consist. The driver counts Stacja1 as the stop it stands at and leaves at 10:35.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable_past_w4.scn", + "vars": { + "offset": 15, + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 0 0 enddynamic" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { + "type": "log_contains", + "pattern": "as ROJ65113: at 10:35 next Przystanek" + }, + { + "type": "starts", + "min_speed": 20, + "within": 240 + } + ] +} diff --git a/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json b/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json new file mode 100644 index 000000000..aa6fb0f86 --- /dev/null +++ b/tests/scenarios/cases/eu07a_coaches_td_upgrade_long.json @@ -0,0 +1,50 @@ +{ + "description": "An EU07A (303E) with 8 coaches (about 360 t) on a line of its own beside td.scn: up a gradient of 10 per mille, 5.5 km long, at the 80 km/h of its timetable, to the signal at stop 5300 m up. The train is to keep above 70 km/h on the climb (#187: an EU07A hung at 55-58 km/h on 10 per mille).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_upgrade_long.scn", + "timetable": "td_passenger_upgrade.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\303e_v1 303E-336'20 303E 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_c1 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c2 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c3 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c4 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c5 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c6 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c7 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic", + "node -1 0 {{vehicle}}_c8 dynamic pkp\\bdhpumn_v3 bdhpumn_50512608068-6 BDHPUMN_TAPICERKA_1 0 nobody 3 0 enddynamic" + ] + }, + "expect": "standstill", + "duration": 1200, + "timeout": 1500, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 70, + "from_distance": 2500, + "until_distance": 4800 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 5330, + "max_distance": 5410 + } + ] +} diff --git a/tests/scenarios/cases/golf_td_crew_swap.json b/tests/scenarios/cases/golf_td_crew_swap.json new file mode 100644 index 000000000..9eca8c05c --- /dev/null +++ b/tests/scenarios/cases/golf_td_crew_swap.json @@ -0,0 +1,30 @@ +{ + "description": "Crew events on a road vehicle (eu07/maszyna#510): a car with an AI driver runs along the road d3 of td.scn, at 50 km/h, the top speed its trainset gives it. 20 s after the start Crew: 0 0 takes the driver off: the car is left with its own brake applied in full, stops and stands. 40 s later Crew: 1 0 puts a driver in again (a road vehicle has no cab to tell by, and takes one all the same), who drives on along the road, with no timetable to cap the speed.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset 50 d3 0.0 30", + "node -1 0 {{vehicle}} dynamic road\\golf none golf 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 20 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_off end", + "event autotest_crew_on putvalues 60 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "duration": 120, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_golf_td_crew_swap\\] the AI driver leaves" }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 10, "within": 30, "hold": 30 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_golf_td_crew_swap\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 55, "before": 70 }, + { "type": "starts", "min_speed": 20, "within": 60 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/l053_poludnie_roj32134_debica.json b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json new file mode 100644 index 000000000..7ed64bf96 --- /dev/null +++ b/tests/scenarios/cases/l053_poludnie_roj32134_debica.json @@ -0,0 +1,24 @@ +{ + "description": "eu07/maszyna#506, L053 poludnie, ROJ23133 Debica - Rudawa and ROJ32134 back (EN57-1797ra): the unit runs both trains among the scenery's traffic and ends at Debica (the station's state cell of ROJ32134 says done).", + "base_scenery": "l053_poludnie.scn", + "strip_trainsets": false, + "vehicle": "EN57-1797ra", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_roj32134_stat", + "state": "d * *", + "reason": "roj32134_ended_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 7200", + "test.standstill 1500", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600 +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica.json b/tests/scenarios/cases/l053_poranek_tme222158_debica.json new file mode 100644 index 000000000..dde90e86a --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica.json @@ -0,0 +1,30 @@ +{ + "description": "eu07/maszyna#421, L053 poranek, TME222158: the locomotive brings the wagons with steel coils from Debica Towarowa to Debica, uncouples (Shunt 0 0 from the scenery), shunts on the Ms2 signals while the station's SM42 takes the wagons away, couples to its next train and gets the exit signal to Sandomierz (step 6 of the station's state cell).", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "vehicle": "ET22-654", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[et22-654\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json new file mode 100644 index 000000000..7ad5a1a78 --- /dev/null +++ b/tests/scenarios/cases/l053_poranek_tme222158_debica_et21.json @@ -0,0 +1,36 @@ +{ + "description": "eu07/maszyna#421 as reported in 2021, with an ET21 on TME222158 (the scenery has an ET22 there now): the same run as l053_poranek_tme222158_debica, the locomotive of the mission replaced.", + "base_scenery": "l053_poranek.scn", + "strip_trainsets": false, + "replace": [ + [ + "node -1 0 ET22-654 dynamic pkp\\et22_v3 201E-654 201E -1 headdriver 3 0 enddynamic", + "node -1 0 ET21-367 dynamic pkp\\et21_v2 ET21-367 3e2 -1 headdriver 3 0 enddynamic" + ] + ], + "vehicle": "ET21-367", + "fragment": "mission_state_probe.scn", + "vars": { + "cell": "deb_tme222158_stat", + "state": "* 6 *", + "reason": "tme222158_got_the_exit_signal_at_debica" + }, + "slow": true, + "physicslog": false, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 6000", + "test.standstill 2100", + "test.fail_if_stop_overran no" + ], + "expect": "pass", + "timeout": 3600, + "checks": [ + { + "type": "log_contains", + "pattern": "Uncoupling \\[et21-367\\]: uncoupled" + } + ] +} diff --git a/tests/scenarios/cases/mission_state_probe.scn b/tests/scenarios/cases/mission_state_probe.scn new file mode 100644 index 000000000..fd158dab3 --- /dev/null +++ b/tests/scenarios/cases/mission_state_probe.scn @@ -0,0 +1,13 @@ +// added by tests/scenarios/run.py to a scenery that keeps its own trainsets (strip_trainsets false): the +// case tests one of the scenery's missions, with every train driven by AI. +// the sceneries of this kind steer their stations with state cells, one per train (text and two values, +// e.g. "a 6 *": the route of step 6 is set for the train, "d * *": the train is done at this station). +// the probe looks at the cell {{cell}} every 5 s from the start on and reports the pass once it holds +// {{state}}. no fail event: a train that never gets there ends the test with the standstill or the +// timeout of the test mode. +// the two events calling each other are the loop these sceneries use themselves (e.g. bal_obsluga_stacji); +// an event with "onstart" in its name is queued when the scenery starts. +event onstart_autotest_probe multiple 30 none autotest_probe endevent +event autotest_probe multiple 0 {{cell}} autotest_pass else autotest_probe_wait condition memcompare {{state}} endevent +event autotest_probe_wait multiple 5 none autotest_probe endevent +event autotest_pass UpdateValues 0 __test.result {{reason}} 1 * endevent diff --git a/tests/scenarios/cases/sm42_td_crew_remove.json b/tests/scenarios/cases/sm42_td_crew_remove.json new file mode 100644 index 000000000..42e55d9d1 --- /dev/null +++ b/tests/scenarios/cases/sm42_td_crew_remove.json @@ -0,0 +1,27 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with an SM42 diesel shunter which loses its AI driver on the run at 10:36, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\sm42_v1 6D-468 6D 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_sm42_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/sm42_td_uncouple_past_signal.json b/tests/scenarios/cases/sm42_td_uncouple_past_signal.json new file mode 100644 index 000000000..f1ae7b835 --- /dev/null +++ b/tests/scenarios/cases/sm42_td_uncouple_past_signal.json @@ -0,0 +1,25 @@ +{ + "description": "SM42 shunter on td.scn pulls three loaded wagons back along tor1k and stops with the far end of the last one a few metres past the exit signal stacja1_j at stop, then gets Shunt 0 0 (uncouple): after the direction change the signal lies at stop over that wagon, behind the new head, and the AI has to push the buffers in all the same and let the coupler go.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_uncouple_past_signal.scn", + "vars": { + "wagons": [ + "node -1 0 {{vehicle}}_w3 dynamic pkp\\401z_v2 82515940087-8 401zp_2 0 nobody 3 60 gravel enddynamic", + "node -1 0 {{vehicle}}_w2 dynamic pkp\\401z_v2 82515942691-5 401zp_1 0 nobody 3 60 gravel enddynamic", + "node -1 0 {{vehicle}}_w1 dynamic pkp\\401z_v2 82515993043-7 401zl_2 0 nobody 3 60 gravel enddynamic" + ] + }, + "track_events": { + "tor1k": "event0 autotest_wake" + }, + "test_config": [ + "test.fail_if_stop_overran no" + ], + "duration": 180, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Uncoupling \\[autotest_sm42_td_uncouple_past_signal\\]: uncoupled" }, + { "type": "distance", "min": 45, "max": 49 } + ] +} diff --git a/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json new file mode 100644 index 000000000..033313dc0 --- /dev/null +++ b/tests/scenarios/cases/sn61_td_downgrade_w4_signal.json @@ -0,0 +1,47 @@ +{ + "description": "An SN61 railcar alone on the line of eu07_td_downgrade_w4_signal, down a gradient of 20 per mille: stops at the W4 of Dol, then before the signal at stop. The SN61 alone brakes with its independent brake.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade_w4_signal.scn", + "timetable": "td_downgrade.txt", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp\\sn61_v2 SN61-13 SN61_v1 0 headdriver 0 0 enddynamic" + }, + "duration": 540, + "timeout": 900, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 150 + }, + { + "type": "max_speed", + "limit": 80, + "tolerance": 3 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 1500, + "max_distance": 1700 + }, + { + "type": "stops", + "moving_speed": 20, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 2550, + "max_distance": 2750, + "max_time": 366, + "nth": 2 + }, + { + "type": "distance", + "min": 2550, + "max": 2750 + } + ] +} diff --git a/tests/scenarios/cases/st43_steel_td_downgrade12_long.json b/tests/scenarios/cases/st43_steel_td_downgrade12_long.json new file mode 100644 index 000000000..371faa23c --- /dev/null +++ b/tests/scenarios/cases/st43_steel_td_downgrade12_long.json @@ -0,0 +1,86 @@ +{ + "description": "An ST43 with 45 loaded steel coil wagons (425S, G) on a line of its own beside td.scn: from the level down a gradient of 12 per mille, 6 km long, at the 40 km/h of its timetable, to the signal at stop 6000 m down. The train is not to come to a stand on the way down (#199).", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_downgrade12_long.scn", + "timetable": "td_freight_downgrade12.txt", + "vars": { + "consist": [ + "node -1 0 {{vehicle}} dynamic pkp\\st43_v1 st43-195 060Da 0 headdriver 3 0 enddynamic", + "node -1 0 {{vehicle}}_w01 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w02 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w03 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w04 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w05 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w06 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w07 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w08 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w09 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w10 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w11 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w12 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w13 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w14 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w15 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w16 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w17 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w18 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w19 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w20 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w21 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w22 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w23 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w24 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w25 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w26 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w27 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w28 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w29 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w30 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w31 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w32 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w33 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w34 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w35 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w36 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w37 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w38 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w39 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w40 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w41 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w42 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w43 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w44 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic", + "node -1 0 {{vehicle}}_w45 dynamic pkp\\425s_v1 31514644357-9 425S_1 0 nobody 3 3 steel_coils enddynamic" + ] + }, + "expect": "standstill", + "duration": 1500, + "timeout": 1800, + "checks": [ + { + "type": "starts", + "min_speed": 20, + "within": 400 + }, + { + "type": "max_speed", + "limit": 40, + "tolerance": 5 + }, + { + "type": "keeps_moving", + "moving_speed": 20, + "min_speed": 5, + "until_distance": 5800 + }, + { + "type": "stops", + "moving_speed": 15, + "stop_speed": 1.0, + "hold": 20, + "min_distance": 5950, + "max_distance": 6110 + } + ] +} diff --git a/tests/scenarios/cases/td_buckle_event.scn b/tests/scenarios/cases/td_buckle_event.scn new file mode 100644 index 000000000..b9d47d434 --- /dev/null +++ b/tests/scenarios/cases/td_buckle_event.scn @@ -0,0 +1,11 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// td_timetable.scn (the timetable train from track 1 of Stacja1 to Przystanek), and at 10:35, as the train leaves, +// the curve tdo_n222 (R 600 m, about 950 m ahead of it) buckles in the heat out of the curve with the +// trackbuckle event of {{amplitude}} mm (see world/TrackBuckle.h) +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end +event autotest_buckle trackbuckle 0 tdo_n222 {{amplitude}} endevent +node -1 0 autotest_buckle_launcher eventlauncher 0 0 0 -1 none 1035 autotest_buckle end diff --git a/tests/scenarios/cases/td_cold_connect.scn b/tests/scenarios/cases/td_cold_connect.scn new file mode 100644 index 000000000..3ea9306c6 --- /dev/null +++ b/tests/scenarios/cases/td_cold_connect.scn @@ -0,0 +1,28 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the straight track 1 of Stacja1: a locomotive with an AI driver stands cold (trainset velocity 0, so +// it starts "Braked": hand brake on, battery off, pantographs down) on tdo_n1725, its front 60 m past +// point 1 of the track, facing point 2; the rake (vars.rake) stands, braked as well and with nobody in it, +// on tdo_n1734 ahead of it, its front 60 m past point 1 of that track, some 45 m in front of the +// locomotive (two coaches of 26.4 m). +trainset none tdo_n1725 60.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n1734 60.0 0.0 +{{rake}} +endtrainset + +// a driver of a standing trainset sleeps on Wait_for_orders until something wakes it. event0 of the +// locomotive's track (the case's track_events) runs while it stands there and gives it, once (the memory +// cell), the order a scenery gives a shunter to couple: Shunt -1 3, couple to the consist standing ahead +// with the coupler and the brake hose and go on shunting. the engine is cold, so the AI starts it +// first: its orders are Prepare_engine, Connect, Shunt, and Connect is the first one it drives under. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the rake, pushed by the locomotive, runs onto tor1k (40 m ahead of its first coach) towards its +// point 2: eventall2 of tor1k (the case's track_events) passes the test, which ends there with the train +// still moving (test.no_movement_before_pass no), 100 m short of the exit signal at the end of tor1k. +event autotest_pass UpdateValues 0 __test.result the_rake_was_coupled_and_pushed 1 * endevent diff --git a/tests/scenarios/cases/td_cold_timetable.scn b/tests/scenarios/cases/td_cold_timetable.scn new file mode 100644 index 000000000..b11c4825a --- /dev/null +++ b/tests/scenarios/cases/td_cold_timetable.scn @@ -0,0 +1,19 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed: +// the trainset goes after FirstInit, the launcher and the events before it. +// the case's consist stands cold where td.scn keeps its timetable train (track 1 of Stacja1): trainset +// velocity 0, so every vehicle starts "Braked": brake pipe at 3.5 bar, battery off, hand and spring brakes on. +// it has the same timetable: Stacja1 10:35 -> Przystanek -> Stacja2. +trainset td/rozklad tdo_n1734 0.0 0.0 +{{consist}} +endtrainset + +// the way out of track 1, as in td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +// a driver of a standing trainset sleeps on Wait_for_orders until something wakes it. event0 of the train's +// track (the case's track_events) runs while it stands there and gives it, once (the memory cell), the order +// to run as a train: Obey_train. the engine is cold, so the AI starts it first (Prepare_engine). +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Obey_train 0 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent diff --git a/tests/scenarios/cases/td_crew.scn b/tests/scenarios/cases/td_crew.scn new file mode 100644 index 000000000..33def0f24 --- /dev/null +++ b/tests/scenarios/cases/td_crew.scn @@ -0,0 +1,22 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the vehicles of the case (vars.trainsets), the lead one on track 1 of Stacja1 (tdo_n1734), where td.scn keeps +// its timetable train, and the crew events of the case (vars.crew, eu07/maszyna#510): a putvalues event with +// "Crew: " puts an AI driver in cab A (1) or cab B (-1) of the vehicle named, or takes its +// AI driver off (0). the vehicle is named in the text, so the events run from event launchers, with no vehicle +// setting them off. +{{trainsets}} + +// the way out of track 1, see td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +{{crew}} + +// a driver put in a standing vehicle waits for orders, as the driver of a standing trainset does, and the scenery +// has to give them. event0 of the track the locomotive stands on (the track_events of the case) runs while a +// vehicle with a driver in charge stands there; once the cell says a new driver waits (autotest_crew_waits, run +// along with the crew event), it gives the order to go, Shunt -1 0, one time. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_crew_waits UpdateValues 0 autotest_ordered * 1 * endevent +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 1 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 2 * endevent diff --git a/tests/scenarios/cases/td_departure_station.scn b/tests/scenarios/cases/td_departure_station.scn new file mode 100644 index 000000000..b005516c4 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the same start as td_timetable.scn, the W4 of Stacja1 about 35 m ahead of the train, but on the case's own +// timetable: {{timetable}}, a copy of the case's "timetable" file, Stacja1 10:35 -> Przystanek -> Stacja2 whose +// first row gives no arrival time, only the departure. the route out of track 1 is set at 10:34 +trainset {{timetable}} tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/td_departure_station.txt b/tests/scenarios/cases/td_departure_station.txt new file mode 100644 index 000000000..cd4851228 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST25 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Stacja1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_departure_station_capitals.txt b/tests/scenarios/cases/td_departure_station_capitals.txt new file mode 100644 index 000000000..8d727d5d0 --- /dev/null +++ b/tests/scenarios/cases/td_departure_station_capitals.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST24 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Stacja1 ] +[ Relacja pociagu | Stacja2 ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | STACJA1 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Przystanek 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP,pt 1 10.37.3 | ] +[ | 90 |----------------------------------1----------|---] +[ | | Stacja2 1 10.39 | 1 ] +[ | | R1 1 10.40 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_downgrade.txt b/tests/scenarios/cases/td_downgrade.txt new file mode 100644 index 000000000..ddc50d031 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade.txt @@ -0,0 +1,20 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST26 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 210 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 80 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Dol 1 10.37 | 4 ] +[ |_____| R1,+,L,H,PP 1 10.38 | ] +[ | 80 |----------------------------------1----------|---] +[ | | Koniec 1 10.45 | 7 ] +[ | | R1 1 10.46 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_downgrade12_long.scn b/tests/scenarios/cases/td_downgrade12_long.scn new file mode 100644 index 000000000..37cf1eff3 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade12_long.scn @@ -0,0 +1,608 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 900 m level, then 6500 m down a gradient of 12 per mille, +// with no overhead wire (diesel trains). the train starts on the level with its head 10 m before the W4 of Gora and runs on +// the timetable {{timetable}} (no stop; a freight train leaves Gora at once) at its line limit, down to the signal hl_sem +// at stop 6000 m down the gradient. the line goes on 500 m past the signal +node -1 0 hl_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -800.0 0.0 +0 +endtrack +node -1 0 hl_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -700.0 0.0 +0 +endtrack +node -1 0 hl_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -600.0 0.0 +0 +endtrack +node -1 0 hl_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hl_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hl_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hl_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hl_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hl_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hl_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.80 100.0 0.0 +0 +endtrack +node -1 0 hl_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.80 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 57.60 200.0 0.0 +0 +endtrack +node -1 0 hl_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 57.60 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.40 300.0 0.0 +0 +endtrack +node -1 0 hl_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.40 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 55.20 400.0 0.0 +0 +endtrack +node -1 0 hl_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 55.20 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 500.0 0.0 +0 +endtrack +node -1 0 hl_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.80 600.0 0.0 +0 +endtrack +node -1 0 hl_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.80 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 51.60 700.0 0.0 +0 +endtrack +node -1 0 hl_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 51.60 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.40 800.0 0.0 +0 +endtrack +node -1 0 hl_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.40 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 49.20 900.0 0.0 +0 +endtrack +node -1 0 hl_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 49.20 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 1000.0 0.0 +0 +endtrack +node -1 0 hl_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.80 1100.0 0.0 +0 +endtrack +node -1 0 hl_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.80 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 45.60 1200.0 0.0 +0 +endtrack +node -1 0 hl_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 45.60 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.40 1300.0 0.0 +0 +endtrack +node -1 0 hl_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.40 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 43.20 1400.0 0.0 +0 +endtrack +node -1 0 hl_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 43.20 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 1500.0 0.0 +0 +endtrack +node -1 0 hl_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.80 1600.0 0.0 +0 +endtrack +node -1 0 hl_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.80 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 39.60 1700.0 0.0 +0 +endtrack +node -1 0 hl_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 39.60 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.40 1800.0 0.0 +0 +endtrack +node -1 0 hl_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.40 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 37.20 1900.0 0.0 +0 +endtrack +node -1 0 hl_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 37.20 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 2000.0 0.0 +0 +endtrack +node -1 0 hl_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.80 2100.0 0.0 +0 +endtrack +node -1 0 hl_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.80 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 33.60 2200.0 0.0 +0 +endtrack +node -1 0 hl_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 33.60 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.40 2300.0 0.0 +0 +endtrack +node -1 0 hl_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.40 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 31.20 2400.0 0.0 +0 +endtrack +node -1 0 hl_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 31.20 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 2500.0 0.0 +0 +endtrack +node -1 0 hl_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.80 2600.0 0.0 +0 +endtrack +node -1 0 hl_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.80 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 27.60 2700.0 0.0 +0 +endtrack +node -1 0 hl_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 27.60 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.40 2800.0 0.0 +0 +endtrack +node -1 0 hl_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.40 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 25.20 2900.0 0.0 +0 +endtrack +node -1 0 hl_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 25.20 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 3000.0 0.0 +0 +endtrack +node -1 0 hl_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.80 3100.0 0.0 +0 +endtrack +node -1 0 hl_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.80 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 21.60 3200.0 0.0 +0 +endtrack +node -1 0 hl_41 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 21.60 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.40 3300.0 0.0 +0 +endtrack +node -1 0 hl_42 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.40 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 19.20 3400.0 0.0 +0 +endtrack +node -1 0 hl_43 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 19.20 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 3500.0 0.0 +0 +endtrack +node -1 0 hl_44 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 3500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.80 3600.0 0.0 +0 +endtrack +node -1 0 hl_45 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.80 3600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 15.60 3700.0 0.0 +0 +endtrack +node -1 0 hl_46 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 15.60 3700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.40 3800.0 0.0 +0 +endtrack +node -1 0 hl_47 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.40 3800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 13.20 3900.0 0.0 +0 +endtrack +node -1 0 hl_48 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 13.20 3900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 4000.0 0.0 +0 +endtrack +node -1 0 hl_49 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 4000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.80 4100.0 0.0 +0 +endtrack +node -1 0 hl_50 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.80 4100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 9.60 4200.0 0.0 +0 +endtrack +node -1 0 hl_51 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 9.60 4200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.40 4300.0 0.0 +0 +endtrack +node -1 0 hl_52 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.40 4300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 7.20 4400.0 0.0 +0 +endtrack +node -1 0 hl_53 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 7.20 4400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 4500.0 0.0 +0 +endtrack +node -1 0 hl_54 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 4500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.80 4600.0 0.0 +0 +endtrack +node -1 0 hl_55 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.80 4600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 3.60 4700.0 0.0 +0 +endtrack +node -1 0 hl_56 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 3.60 4700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.40 4800.0 0.0 +0 +endtrack +node -1 0 hl_57 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.40 4800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 1.20 4900.0 0.0 +0 +endtrack +node -1 0 hl_58 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 1.20 4900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -0.00 5000.0 0.0 +0 +endtrack +node -1 0 hl_59 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -0.00 5000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -1.20 5100.0 0.0 +0 +endtrack +node -1 0 hl_60 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -1.20 5100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -2.40 5200.0 0.0 +0 +endtrack +node -1 0 hl_61 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -2.40 5200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -3.60 5300.0 0.0 +0 +endtrack +node -1 0 hl_62 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -3.60 5300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -4.80 5400.0 0.0 +0 +endtrack +node -1 0 hl_63 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -4.80 5400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -6.00 5500.0 0.0 +0 +endtrack +node -1 0 hl_64 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -6.00 5500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -7.20 5600.0 0.0 +0 +endtrack +node -1 0 hl_65 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -7.20 5600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -8.40 5700.0 0.0 +0 +endtrack +node -1 0 hl_66 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -8.40 5700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -9.60 5800.0 0.0 +0 +endtrack +node -1 0 hl_67 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -9.60 5800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -10.80 5900.0 0.0 +0 +endtrack +node -1 0 hl_68 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -10.80 5900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -12.00 6000.0 0.0 +0 +event2 hl_sem_info +endtrack +node -1 0 hl_69 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -12.00 6000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -13.20 6100.0 0.0 +0 +endtrack +node -1 0 hl_70 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -13.20 6100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -14.40 6200.0 0.0 +0 +endtrack +node -1 0 hl_71 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -14.40 6200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -15.60 6300.0 0.0 +0 +endtrack +node -1 0 hl_72 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -15.60 6300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -16.80 6400.0 0.0 +0 +endtrack +node -1 0 hl_73 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -16.80 6400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -18.00 6500.0 0.0 +0 +endtrack +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hl_sem_mem memcell -2997.3 -4.00 6000.0 SetVelocity 0.0 0.0 none endmemcell +event hl_sem_info getvalues 5.0 hl_sem_mem endevent + +trainset {{timetable}} hl_08 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_downgrade_restriction.scn b/tests/scenarios/cases/td_downgrade_restriction.scn new file mode 100644 index 000000000..42c7cf775 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade_restriction.scn @@ -0,0 +1,638 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 3500 m down a gradient of 20 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the timetable +// {{timetable}} (no stop; a freight train leaves Gora at once): its line limit, a 20 km/h restriction from 1500 to 1900 m +// down the gradient, then the signal hr_sem at stop 3000 m down the gradient. the line goes on 500 m past the signal +node -1 0 hr_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hr_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hr_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hr_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hr_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hr_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hr_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.00 100.0 0.0 +0 +endtrack +node -1 0 hr_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.00 200.0 0.0 +0 +endtrack +node -1 0 hr_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 300.0 0.0 +0 +endtrack +node -1 0 hr_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.00 400.0 0.0 +0 +endtrack +node -1 0 hr_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.00 500.0 0.0 +0 +endtrack +node -1 0 hr_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 600.0 0.0 +0 +endtrack +node -1 0 hr_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.00 700.0 0.0 +0 +endtrack +node -1 0 hr_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.00 800.0 0.0 +0 +endtrack +node -1 0 hr_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 900.0 0.0 +0 +endtrack +node -1 0 hr_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.00 1000.0 0.0 +0 +endtrack +node -1 0 hr_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.00 1100.0 0.0 +0 +endtrack +node -1 0 hr_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 1200.0 0.0 +0 +endtrack +node -1 0 hr_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.00 1300.0 0.0 +0 +endtrack +node -1 0 hr_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.00 1400.0 0.0 +0 +endtrack +node -1 0 hr_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 1500.0 0.0 +0 +endtrack +node -1 0 hr_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.00 1600.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.00 1700.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 1800.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.00 1900.0 0.0 +0 +velocity 20 +endtrack +node -1 0 hr_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.00 2000.0 0.0 +0 +endtrack +node -1 0 hr_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 2100.0 0.0 +0 +endtrack +node -1 0 hr_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.00 2200.0 0.0 +0 +endtrack +node -1 0 hr_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.00 2300.0 0.0 +0 +endtrack +node -1 0 hr_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 2400.0 0.0 +0 +endtrack +node -1 0 hr_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.00 2500.0 0.0 +0 +endtrack +node -1 0 hr_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.00 2600.0 0.0 +0 +endtrack +node -1 0 hr_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 2700.0 0.0 +0 +endtrack +node -1 0 hr_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.00 2800.0 0.0 +0 +endtrack +node -1 0 hr_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.00 2900.0 0.0 +0 +endtrack +node -1 0 hr_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 0.00 3000.0 0.0 +0 +event2 hr_sem_info +endtrack +node -1 0 hr_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 0.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -2.00 3100.0 0.0 +0 +endtrack +node -1 0 hr_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -2.00 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -4.00 3200.0 0.0 +0 +endtrack +node -1 0 hr_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -4.00 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -6.00 3300.0 0.0 +0 +endtrack +node -1 0 hr_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -6.00 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -8.00 3400.0 0.0 +0 +endtrack +node -1 0 hr_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 -8.00 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 -10.00 3500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 hr_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 63.60 100.0 +-3000.0 67.30 0.0 +-3000.0 65.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 63.60 100.0 +-3000.0 61.60 200.0 +-3000.0 65.30 100.0 +-3000.0 63.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 61.60 200.0 +-3000.0 59.60 300.0 +-3000.0 63.30 200.0 +-3000.0 61.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 59.60 300.0 +-3000.0 57.60 400.0 +-3000.0 61.30 300.0 +-3000.0 59.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 57.60 400.0 +-3000.0 55.60 500.0 +-3000.0 59.30 400.0 +-3000.0 57.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 55.60 500.0 +-3000.0 53.60 600.0 +-3000.0 57.30 500.0 +-3000.0 55.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 53.60 600.0 +-3000.0 51.60 700.0 +-3000.0 55.30 600.0 +-3000.0 53.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 51.60 700.0 +-3000.0 49.60 800.0 +-3000.0 53.30 700.0 +-3000.0 51.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 49.60 800.0 +-3000.0 47.60 900.0 +-3000.0 51.30 800.0 +-3000.0 49.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 47.60 900.0 +-3000.0 45.60 1000.0 +-3000.0 49.30 900.0 +-3000.0 47.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 45.60 1000.0 +-3000.0 43.60 1100.0 +-3000.0 47.30 1000.0 +-3000.0 45.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 43.60 1100.0 +-3000.0 41.60 1200.0 +-3000.0 45.30 1100.0 +-3000.0 43.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 41.60 1200.0 +-3000.0 39.60 1300.0 +-3000.0 43.30 1200.0 +-3000.0 41.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 39.60 1300.0 +-3000.0 37.60 1400.0 +-3000.0 41.30 1300.0 +-3000.0 39.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 37.60 1400.0 +-3000.0 35.60 1500.0 +-3000.0 39.30 1400.0 +-3000.0 37.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 35.60 1500.0 +-3000.0 33.60 1600.0 +-3000.0 37.30 1500.0 +-3000.0 35.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 33.60 1600.0 +-3000.0 31.60 1700.0 +-3000.0 35.30 1600.0 +-3000.0 33.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 31.60 1700.0 +-3000.0 29.60 1800.0 +-3000.0 33.30 1700.0 +-3000.0 31.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 29.60 1800.0 +-3000.0 27.60 1900.0 +-3000.0 31.30 1800.0 +-3000.0 29.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 27.60 1900.0 +-3000.0 25.60 2000.0 +-3000.0 29.30 1900.0 +-3000.0 27.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 25.60 2000.0 +-3000.0 23.60 2100.0 +-3000.0 27.30 2000.0 +-3000.0 25.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 23.60 2100.0 +-3000.0 21.60 2200.0 +-3000.0 25.30 2100.0 +-3000.0 23.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 21.60 2200.0 +-3000.0 19.60 2300.0 +-3000.0 23.30 2200.0 +-3000.0 21.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 19.60 2300.0 +-3000.0 17.60 2400.0 +-3000.0 21.30 2300.0 +-3000.0 19.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 17.60 2400.0 +-3000.0 15.60 2500.0 +-3000.0 19.30 2400.0 +-3000.0 17.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 15.60 2500.0 +-3000.0 13.60 2600.0 +-3000.0 17.30 2500.0 +-3000.0 15.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 13.60 2600.0 +-3000.0 11.60 2700.0 +-3000.0 15.30 2600.0 +-3000.0 13.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 11.60 2700.0 +-3000.0 9.60 2800.0 +-3000.0 13.30 2700.0 +-3000.0 11.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 9.60 2800.0 +-3000.0 7.60 2900.0 +-3000.0 11.30 2800.0 +-3000.0 9.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 7.60 2900.0 +-3000.0 5.60 3000.0 +-3000.0 9.30 2900.0 +-3000.0 7.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 5.60 3000.0 +-3000.0 3.60 3100.0 +-3000.0 7.30 3000.0 +-3000.0 5.30 3100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 3.60 3100.0 +-3000.0 1.60 3200.0 +-3000.0 5.30 3100.0 +-3000.0 3.30 3200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 1.60 3200.0 +-3000.0 -0.40 3300.0 +-3000.0 3.30 3200.0 +-3000.0 1.30 3300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 -0.40 3300.0 +-3000.0 -2.40 3400.0 +-3000.0 1.30 3300.0 +-3000.0 -0.70 3400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 -2.40 3400.0 +-3000.0 -4.40 3500.0 +-3000.0 -0.70 3400.0 +-3000.0 -2.70 3500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hr_sem_mem memcell -2997.3 8.00 3000.0 SetVelocity 0.0 0.0 none endmemcell +event hr_sem_info getvalues 5.0 hr_sem_mem endevent + +trainset {{timetable}} hr_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_downgrade_w4_signal.scn b/tests/scenarios/cases/td_downgrade_w4_signal.scn new file mode 100644 index 000000000..ffa43ecc3 --- /dev/null +++ b/tests/scenarios/cases/td_downgrade_w4_signal.scn @@ -0,0 +1,518 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 300 m level, then 3000 m down a gradient of 20 per mille, +// under an overhead wire. +// the train starts on the level, with the W4 of Gora about 40 m ahead, and runs on the timetable {{timetable}}: +// Gora 10:35 -> Dol, a W4 1500 m down the gradient (stop, leaves at 10:38) -> the signal gr_sem, 1100 m further +// down, which stays at stop. the line goes on 400 m past the signal +node -1 0 gr_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 gr_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 gr_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 gr_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 58.00 100.0 0.0 +0 +endtrack +node -1 0 gr_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 58.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 56.00 200.0 0.0 +0 +endtrack +node -1 0 gr_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 56.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 54.00 300.0 0.0 +0 +endtrack +node -1 0 gr_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 54.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 52.00 400.0 0.0 +0 +endtrack +node -1 0 gr_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 52.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 50.00 500.0 0.0 +0 +endtrack +node -1 0 gr_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 50.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 48.00 600.0 0.0 +0 +endtrack +node -1 0 gr_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 48.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 46.00 700.0 0.0 +0 +endtrack +node -1 0 gr_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 46.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 44.00 800.0 0.0 +0 +endtrack +node -1 0 gr_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 44.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 42.00 900.0 0.0 +0 +endtrack +node -1 0 gr_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 42.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 40.00 1000.0 0.0 +0 +endtrack +node -1 0 gr_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 40.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 38.00 1100.0 0.0 +0 +endtrack +node -1 0 gr_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 38.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 36.00 1200.0 0.0 +0 +endtrack +node -1 0 gr_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 36.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 34.00 1300.0 0.0 +0 +endtrack +node -1 0 gr_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 34.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 32.00 1400.0 0.0 +0 +endtrack +node -1 0 gr_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 32.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 30.00 1500.0 0.0 +0 +event2 dol#1_stopinfo +endtrack +node -1 0 gr_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 30.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 28.00 1600.0 0.0 +0 +endtrack +node -1 0 gr_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 28.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 26.00 1700.0 0.0 +0 +endtrack +node -1 0 gr_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 26.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 24.00 1800.0 0.0 +0 +endtrack +node -1 0 gr_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 24.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 22.00 1900.0 0.0 +0 +endtrack +node -1 0 gr_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 22.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 20.00 2000.0 0.0 +0 +endtrack +node -1 0 gr_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 20.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 18.00 2100.0 0.0 +0 +endtrack +node -1 0 gr_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 18.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 16.00 2200.0 0.0 +0 +endtrack +node -1 0 gr_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 16.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 14.00 2300.0 0.0 +0 +endtrack +node -1 0 gr_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 14.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 12.00 2400.0 0.0 +0 +endtrack +node -1 0 gr_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 12.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 10.00 2500.0 0.0 +0 +endtrack +node -1 0 gr_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 10.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 8.00 2600.0 0.0 +0 +event2 gr_sem_info +endtrack +node -1 0 gr_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 8.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 6.00 2700.0 0.0 +0 +endtrack +node -1 0 gr_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 6.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 4.00 2800.0 0.0 +0 +endtrack +node -1 0 gr_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 4.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 2.00 2900.0 0.0 +0 +endtrack +node -1 0 gr_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 2.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 0.00 3000.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 gr_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 63.60 100.0 +-3000.0 67.30 0.0 +-3000.0 65.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 63.60 100.0 +-3000.0 61.60 200.0 +-3000.0 65.30 100.0 +-3000.0 63.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 61.60 200.0 +-3000.0 59.60 300.0 +-3000.0 63.30 200.0 +-3000.0 61.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 59.60 300.0 +-3000.0 57.60 400.0 +-3000.0 61.30 300.0 +-3000.0 59.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 57.60 400.0 +-3000.0 55.60 500.0 +-3000.0 59.30 400.0 +-3000.0 57.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 55.60 500.0 +-3000.0 53.60 600.0 +-3000.0 57.30 500.0 +-3000.0 55.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 53.60 600.0 +-3000.0 51.60 700.0 +-3000.0 55.30 600.0 +-3000.0 53.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 51.60 700.0 +-3000.0 49.60 800.0 +-3000.0 53.30 700.0 +-3000.0 51.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 49.60 800.0 +-3000.0 47.60 900.0 +-3000.0 51.30 800.0 +-3000.0 49.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 47.60 900.0 +-3000.0 45.60 1000.0 +-3000.0 49.30 900.0 +-3000.0 47.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 45.60 1000.0 +-3000.0 43.60 1100.0 +-3000.0 47.30 1000.0 +-3000.0 45.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 43.60 1100.0 +-3000.0 41.60 1200.0 +-3000.0 45.30 1100.0 +-3000.0 43.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 41.60 1200.0 +-3000.0 39.60 1300.0 +-3000.0 43.30 1200.0 +-3000.0 41.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 39.60 1300.0 +-3000.0 37.60 1400.0 +-3000.0 41.30 1300.0 +-3000.0 39.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 37.60 1400.0 +-3000.0 35.60 1500.0 +-3000.0 39.30 1400.0 +-3000.0 37.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 35.60 1500.0 +-3000.0 33.60 1600.0 +-3000.0 37.30 1500.0 +-3000.0 35.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 33.60 1600.0 +-3000.0 31.60 1700.0 +-3000.0 35.30 1600.0 +-3000.0 33.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 31.60 1700.0 +-3000.0 29.60 1800.0 +-3000.0 33.30 1700.0 +-3000.0 31.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 29.60 1800.0 +-3000.0 27.60 1900.0 +-3000.0 31.30 1800.0 +-3000.0 29.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 27.60 1900.0 +-3000.0 25.60 2000.0 +-3000.0 29.30 1900.0 +-3000.0 27.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 25.60 2000.0 +-3000.0 23.60 2100.0 +-3000.0 27.30 2000.0 +-3000.0 25.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 23.60 2100.0 +-3000.0 21.60 2200.0 +-3000.0 25.30 2100.0 +-3000.0 23.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 21.60 2200.0 +-3000.0 19.60 2300.0 +-3000.0 23.30 2200.0 +-3000.0 21.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 19.60 2300.0 +-3000.0 17.60 2400.0 +-3000.0 21.30 2300.0 +-3000.0 19.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 17.60 2400.0 +-3000.0 15.60 2500.0 +-3000.0 19.30 2400.0 +-3000.0 17.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 15.60 2500.0 +-3000.0 13.60 2600.0 +-3000.0 17.30 2500.0 +-3000.0 15.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 13.60 2600.0 +-3000.0 11.60 2700.0 +-3000.0 15.30 2600.0 +-3000.0 13.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 11.60 2700.0 +-3000.0 9.60 2800.0 +-3000.0 13.30 2700.0 +-3000.0 11.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 9.60 2800.0 +-3000.0 7.60 2900.0 +-3000.0 11.30 2800.0 +-3000.0 9.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction gr_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 7.60 2900.0 +-3000.0 5.60 3000.0 +-3000.0 9.30 2900.0 +-3000.0 7.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction + +// the W4 of the two stations of the timetable; the middle of the consist 2 m before it, leaves on time +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -60.0 180 0 0 2 202 end +include ip/pkp/w4n.inc dol#1 -2997.3 30.00 1500.0 180 0 0 2 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 gr_sem_mem memcell -2997.3 8.00 2600.0 SetVelocity 0.0 0.0 none endmemcell +event gr_sem_info getvalues 5.0 gr_sem_mem endevent + +trainset {{timetable}} gr_02 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_freight_downgrade.txt b/tests/scenarios/cases/td_freight_downgrade.txt new file mode 100644 index 000000000..1fd01f911 --- /dev/null +++ b/tests/scenarios/cases/td_freight_downgrade.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST44 ] +[ Kategoria | TME ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 50% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | ET41 1700 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 60 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 10.55 | 20] +[ | | R1 1 10.56 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_freight_downgrade12.txt b/tests/scenarios/cases/td_freight_downgrade12.txt new file mode 100644 index 000000000..1fc503342 --- /dev/null +++ b/tests/scenarios/cases/td_freight_downgrade12.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST45 ] +[ Kategoria | TME ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 50% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | ST43 3000 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 40 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 11.10 | 35] +[ | | R1 1 11.11 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_level_signal.scn b/tests/scenarios/cases/td_level_signal.scn new file mode 100644 index 000000000..c3d13eb87 --- /dev/null +++ b/tests/scenarios/cases/td_level_signal.scn @@ -0,0 +1,333 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 2100 m level, under an overhead wire. the train starts with +// its head 10 m before the W4 of Gora and runs on the timetable {{timetable}} (no stop; a freight train leaves Gora at once) to the signal +// lv_sem at stop 1000 m ahead. the line goes on 500 m past it +node -1 0 lv_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 lv_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 lv_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 lv_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 lv_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 lv_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 lv_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 100.0 0.0 +0 +endtrack +node -1 0 lv_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 200.0 0.0 +0 +endtrack +node -1 0 lv_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 300.0 0.0 +0 +endtrack +node -1 0 lv_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 400.0 0.0 +0 +endtrack +node -1 0 lv_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 500.0 0.0 +0 +endtrack +node -1 0 lv_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 600.0 0.0 +0 +endtrack +node -1 0 lv_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 700.0 0.0 +0 +endtrack +node -1 0 lv_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 800.0 0.0 +0 +endtrack +node -1 0 lv_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 900.0 0.0 +0 +endtrack +node -1 0 lv_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1000.0 0.0 +0 +event2 lv_sem_info +endtrack +node -1 0 lv_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1100.0 0.0 +0 +endtrack +node -1 0 lv_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1200.0 0.0 +0 +endtrack +node -1 0 lv_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1300.0 0.0 +0 +endtrack +node -1 0 lv_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1400.0 0.0 +0 +endtrack +node -1 0 lv_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 1500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 lv_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 65.60 100.0 +-3000.0 67.30 0.0 +-3000.0 67.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 100.0 +-3000.0 65.60 200.0 +-3000.0 67.30 100.0 +-3000.0 67.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 200.0 +-3000.0 65.60 300.0 +-3000.0 67.30 200.0 +-3000.0 67.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 300.0 +-3000.0 65.60 400.0 +-3000.0 67.30 300.0 +-3000.0 67.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 400.0 +-3000.0 65.60 500.0 +-3000.0 67.30 400.0 +-3000.0 67.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 500.0 +-3000.0 65.60 600.0 +-3000.0 67.30 500.0 +-3000.0 67.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 600.0 +-3000.0 65.60 700.0 +-3000.0 67.30 600.0 +-3000.0 67.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 700.0 +-3000.0 65.60 800.0 +-3000.0 67.30 700.0 +-3000.0 67.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 800.0 +-3000.0 65.60 900.0 +-3000.0 67.30 800.0 +-3000.0 67.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 900.0 +-3000.0 65.60 1000.0 +-3000.0 67.30 900.0 +-3000.0 67.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1000.0 +-3000.0 65.60 1100.0 +-3000.0 67.30 1000.0 +-3000.0 67.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1100.0 +-3000.0 65.60 1200.0 +-3000.0 67.30 1100.0 +-3000.0 67.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1200.0 +-3000.0 65.60 1300.0 +-3000.0 67.30 1200.0 +-3000.0 67.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1300.0 +-3000.0 65.60 1400.0 +-3000.0 67.30 1300.0 +-3000.0 67.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction lv_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 1400.0 +-3000.0 65.60 1500.0 +-3000.0 67.30 1400.0 +-3000.0 67.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 lv_sem_mem memcell -2997.3 68.00 1000.0 SetVelocity 0.0 0.0 none endmemcell +event lv_sem_info getvalues 5.0 lv_sem_mem endevent + +trainset {{timetable}} lv_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_no_wire.scn b/tests/scenarios/cases/td_no_wire.scn new file mode 100644 index 000000000..edca73c0b --- /dev/null +++ b/tests/scenarios/cases/td_no_wire.scn @@ -0,0 +1,18 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a piece of track of its own, 200 m long and with no overhead wire above it, 400 m off the line of td.scn +// (all of whose tracks are under the wire), and an electric locomotive with an AI driver standing on it. +// the driver raises the pantographs, which find no wire, and waits in Prepare_engine for the voltage for good +// (eu07/maszyna#421); it tells of it in the log once. +node -1 0 autotest_no_wire track normal 200.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-400.0 0.2 0.0 0.0 //point 1 +0.0 0.0 0.0 //control vector 1 +0.0 0.0 0.0 //control vector 2 +-400.0 0.2 200.0 0.0 //point 2 +0 +endtrack + +// no timetable: the driver goes shunting; 0.01 km/h has it prepare the vehicle and wait for a signal (at 0 it sleeps) +trainset none autotest_no_wire 100.0 0.01 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_off_track.scn b/tests/scenarios/cases/td_off_track.scn new file mode 100644 index 000000000..0318e961d --- /dev/null +++ b/tests/scenarios/cases/td_off_track.scn @@ -0,0 +1,14 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, +// so it stays put and logs its physics; the train of the case has no driver and runs at {{velocity}} km/h from +// {{offset}} m past point 1 of {{track}} towards its point 2. on the line of td.scn, from tdo_n157 on, that is the +// curve of R 600 m (tdo_n213, tdo_n222, tdo_n231), cant 65 mm +{{track_nodes}} +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none {{track}} {{offset}} {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_cutting.scn b/tests/scenarios/cases/td_off_track_curve_cutting.scn new file mode 100644 index 000000000..2c32a3f50 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_cutting.scn @@ -0,0 +1,441 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 none triangle_strip grass +-456.70 32.10 355.67 0 1 0 0 0 end +-322.47 4.00 314.15 0 1 0 0 0 end +-455.43 32.10 359.99 0 1 0 0 0 end +-320.02 4.00 322.51 0 1 0 0 0 end +-454.30 32.10 364.34 0 1 0 0 0 end +-317.83 4.00 330.95 0 1 0 0 0 end +-453.30 32.10 368.73 0 1 0 0 0 end +-315.88 4.00 339.44 0 1 0 0 0 end +-452.42 32.10 373.15 0 1 0 0 0 end +-314.19 4.00 347.99 0 1 0 0 0 end +-451.68 32.10 377.58 0 1 0 0 0 end +-312.76 4.00 356.59 0 1 0 0 0 end +-451.08 32.10 382.04 0 1 0 0 0 end +-311.59 4.00 365.22 0 1 0 0 0 end +-450.61 32.10 386.52 0 1 0 0 0 end +-310.68 4.00 373.89 0 1 0 0 0 end +-450.27 32.10 391.01 0 1 0 0 0 end +-310.02 4.00 382.58 0 1 0 0 0 end +-450.07 32.10 395.50 0 1 0 0 0 end +-309.63 4.00 391.29 0 1 0 0 0 end +-450.00 32.10 400.00 0 1 0 0 0 end +-309.50 4.00 400.00 0 1 0 0 0 end +-450.07 32.10 404.50 0 1 0 0 0 end +-309.63 4.00 408.71 0 1 0 0 0 end +-450.27 32.10 408.99 0 1 0 0 0 end +-310.02 4.00 417.42 0 1 0 0 0 end +-450.61 32.10 413.48 0 1 0 0 0 end +-310.68 4.00 426.11 0 1 0 0 0 end +-451.08 32.10 417.96 0 1 0 0 0 end +-311.59 4.00 434.78 0 1 0 0 0 end +-451.68 32.10 422.42 0 1 0 0 0 end +-312.76 4.00 443.41 0 1 0 0 0 end +-452.42 32.10 426.85 0 1 0 0 0 end +-314.19 4.00 452.01 0 1 0 0 0 end +-453.30 32.10 431.27 0 1 0 0 0 end +-315.88 4.00 460.56 0 1 0 0 0 end +-454.30 32.10 435.66 0 1 0 0 0 end +-317.83 4.00 469.05 0 1 0 0 0 end +-455.43 32.10 440.01 0 1 0 0 0 end +-320.02 4.00 477.49 0 1 0 0 0 end +-456.70 32.10 444.33 0 1 0 0 0 end +-322.47 4.00 485.85 0 1 0 0 0 end +-458.09 32.10 448.61 0 1 0 0 0 end +-325.17 4.00 494.13 0 1 0 0 0 end +-459.62 32.10 452.84 0 1 0 0 0 end +-328.12 4.00 502.34 0 1 0 0 0 end +-461.26 32.10 457.03 0 1 0 0 0 end +-331.31 4.00 510.44 0 1 0 0 0 end +-463.04 32.10 461.16 0 1 0 0 0 end +-334.75 4.00 518.45 0 1 0 0 0 end +-464.93 32.10 465.24 0 1 0 0 0 end +-338.42 4.00 526.36 0 1 0 0 0 end +-466.95 32.10 469.27 0 1 0 0 0 end +-342.33 4.00 534.15 0 1 0 0 0 end +-469.09 32.10 473.23 0 1 0 0 0 end +-346.47 4.00 541.82 0 1 0 0 0 end +-471.34 32.10 477.12 0 1 0 0 0 end +-350.84 4.00 549.36 0 1 0 0 0 end +-473.71 32.10 480.94 0 1 0 0 0 end +-355.43 4.00 556.76 0 1 0 0 0 end +-476.20 32.10 484.70 0 1 0 0 0 end +-360.24 4.00 564.03 0 1 0 0 0 end +-478.80 32.10 488.37 0 1 0 0 0 end +-365.27 4.00 571.15 0 1 0 0 0 end +-481.50 32.10 491.97 0 1 0 0 0 end +-370.51 4.00 578.11 0 1 0 0 0 end +-484.31 32.10 495.48 0 1 0 0 0 end +-375.95 4.00 584.91 0 1 0 0 0 end +-487.23 32.10 498.91 0 1 0 0 0 end +-381.60 4.00 591.55 0 1 0 0 0 end +-490.25 32.10 502.25 0 1 0 0 0 end +-387.44 4.00 598.02 0 1 0 0 0 end +-493.36 32.10 505.49 0 1 0 0 0 end +-393.48 4.00 604.30 0 1 0 0 0 end +-496.58 32.10 508.64 0 1 0 0 0 end +-399.70 4.00 610.41 0 1 0 0 0 end +-499.88 32.10 511.70 0 1 0 0 0 end +-406.10 4.00 616.32 0 1 0 0 0 end +-503.28 32.10 514.65 0 1 0 0 0 end +-412.68 4.00 622.04 0 1 0 0 0 end +-506.76 32.10 517.50 0 1 0 0 0 end +-419.42 4.00 627.56 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-322.47 4.00 314.15 0 1 0 0 0 end +-316.74 0.00 312.38 0 1 0 0 0 end +-320.02 4.00 322.51 0 1 0 0 0 end +-314.24 0.00 320.91 0 1 0 0 0 end +-317.83 4.00 330.95 0 1 0 0 0 end +-312.00 0.00 329.52 0 1 0 0 0 end +-315.88 4.00 339.44 0 1 0 0 0 end +-310.01 0.00 338.19 0 1 0 0 0 end +-314.19 4.00 347.99 0 1 0 0 0 end +-308.29 0.00 346.92 0 1 0 0 0 end +-312.76 4.00 356.59 0 1 0 0 0 end +-306.83 0.00 355.69 0 1 0 0 0 end +-311.59 4.00 365.22 0 1 0 0 0 end +-305.63 0.00 364.51 0 1 0 0 0 end +-310.68 4.00 373.89 0 1 0 0 0 end +-304.70 0.00 373.35 0 1 0 0 0 end +-310.02 4.00 382.58 0 1 0 0 0 end +-304.03 0.00 382.22 0 1 0 0 0 end +-309.63 4.00 391.29 0 1 0 0 0 end +-303.63 0.00 391.11 0 1 0 0 0 end +-309.50 4.00 400.00 0 1 0 0 0 end +-303.50 0.00 400.00 0 1 0 0 0 end +-309.63 4.00 408.71 0 1 0 0 0 end +-303.63 0.00 408.89 0 1 0 0 0 end +-310.02 4.00 417.42 0 1 0 0 0 end +-304.03 0.00 417.78 0 1 0 0 0 end +-310.68 4.00 426.11 0 1 0 0 0 end +-304.70 0.00 426.65 0 1 0 0 0 end +-311.59 4.00 434.78 0 1 0 0 0 end +-305.63 0.00 435.49 0 1 0 0 0 end +-312.76 4.00 443.41 0 1 0 0 0 end +-306.83 0.00 444.31 0 1 0 0 0 end +-314.19 4.00 452.01 0 1 0 0 0 end +-308.29 0.00 453.08 0 1 0 0 0 end +-315.88 4.00 460.56 0 1 0 0 0 end +-310.01 0.00 461.81 0 1 0 0 0 end +-317.83 4.00 469.05 0 1 0 0 0 end +-312.00 0.00 470.48 0 1 0 0 0 end +-320.02 4.00 477.49 0 1 0 0 0 end +-314.24 0.00 479.09 0 1 0 0 0 end +-322.47 4.00 485.85 0 1 0 0 0 end +-316.74 0.00 487.62 0 1 0 0 0 end +-325.17 4.00 494.13 0 1 0 0 0 end +-319.50 0.00 496.08 0 1 0 0 0 end +-328.12 4.00 502.34 0 1 0 0 0 end +-322.51 0.00 504.45 0 1 0 0 0 end +-331.31 4.00 510.44 0 1 0 0 0 end +-325.76 0.00 512.73 0 1 0 0 0 end +-334.75 4.00 518.45 0 1 0 0 0 end +-329.27 0.00 520.90 0 1 0 0 0 end +-338.42 4.00 526.36 0 1 0 0 0 end +-333.02 0.00 528.97 0 1 0 0 0 end +-342.33 4.00 534.15 0 1 0 0 0 end +-337.01 0.00 536.92 0 1 0 0 0 end +-346.47 4.00 541.82 0 1 0 0 0 end +-341.23 0.00 544.74 0 1 0 0 0 end +-350.84 4.00 549.36 0 1 0 0 0 end +-345.69 0.00 552.44 0 1 0 0 0 end +-355.43 4.00 556.76 0 1 0 0 0 end +-350.38 0.00 560.00 0 1 0 0 0 end +-360.24 4.00 564.03 0 1 0 0 0 end +-355.29 0.00 567.42 0 1 0 0 0 end +-365.27 4.00 571.15 0 1 0 0 0 end +-360.42 0.00 574.68 0 1 0 0 0 end +-370.51 4.00 578.11 0 1 0 0 0 end +-365.77 0.00 581.79 0 1 0 0 0 end +-375.95 4.00 584.91 0 1 0 0 0 end +-371.33 0.00 588.73 0 1 0 0 0 end +-381.60 4.00 591.55 0 1 0 0 0 end +-377.09 0.00 595.51 0 1 0 0 0 end +-387.44 4.00 598.02 0 1 0 0 0 end +-383.05 0.00 602.11 0 1 0 0 0 end +-393.48 4.00 604.30 0 1 0 0 0 end +-389.21 0.00 608.52 0 1 0 0 0 end +-399.70 4.00 610.41 0 1 0 0 0 end +-395.56 0.00 614.75 0 1 0 0 0 end +-406.10 4.00 616.32 0 1 0 0 0 end +-402.10 0.00 620.79 0 1 0 0 0 end +-412.68 4.00 622.04 0 1 0 0 0 end +-408.81 0.00 626.62 0 1 0 0 0 end +-419.42 4.00 627.56 0 1 0 0 0 end +-415.69 0.00 632.26 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-316.74 0.00 312.38 0 1 0 0 0 end +-310.06 0.00 310.31 0 1 0 0 0 end +-314.24 0.00 320.91 0 1 0 0 0 end +-307.50 0.00 319.05 0 1 0 0 0 end +-312.00 0.00 329.52 0 1 0 0 0 end +-305.20 0.00 327.86 0 1 0 0 0 end +-310.01 0.00 338.19 0 1 0 0 0 end +-303.17 0.00 336.73 0 1 0 0 0 end +-308.29 0.00 346.92 0 1 0 0 0 end +-301.40 0.00 345.66 0 1 0 0 0 end +-306.83 0.00 355.69 0 1 0 0 0 end +-299.91 0.00 354.65 0 1 0 0 0 end +-305.63 0.00 364.51 0 1 0 0 0 end +-298.68 0.00 363.67 0 1 0 0 0 end +-304.70 0.00 373.35 0 1 0 0 0 end +-297.73 0.00 372.72 0 1 0 0 0 end +-304.03 0.00 382.22 0 1 0 0 0 end +-297.05 0.00 381.80 0 1 0 0 0 end +-303.63 0.00 391.11 0 1 0 0 0 end +-296.64 0.00 390.90 0 1 0 0 0 end +-303.50 0.00 400.00 0 1 0 0 0 end +-296.50 0.00 400.00 0 1 0 0 0 end +-303.63 0.00 408.89 0 1 0 0 0 end +-296.64 0.00 409.10 0 1 0 0 0 end +-304.03 0.00 417.78 0 1 0 0 0 end +-297.05 0.00 418.20 0 1 0 0 0 end +-304.70 0.00 426.65 0 1 0 0 0 end +-297.73 0.00 427.28 0 1 0 0 0 end +-305.63 0.00 435.49 0 1 0 0 0 end +-298.68 0.00 436.33 0 1 0 0 0 end +-306.83 0.00 444.31 0 1 0 0 0 end +-299.91 0.00 445.35 0 1 0 0 0 end +-308.29 0.00 453.08 0 1 0 0 0 end +-301.40 0.00 454.34 0 1 0 0 0 end +-310.01 0.00 461.81 0 1 0 0 0 end +-303.17 0.00 463.27 0 1 0 0 0 end +-312.00 0.00 470.48 0 1 0 0 0 end +-305.20 0.00 472.14 0 1 0 0 0 end +-314.24 0.00 479.09 0 1 0 0 0 end +-307.50 0.00 480.95 0 1 0 0 0 end +-316.74 0.00 487.62 0 1 0 0 0 end +-310.06 0.00 489.69 0 1 0 0 0 end +-319.50 0.00 496.08 0 1 0 0 0 end +-312.88 0.00 498.35 0 1 0 0 0 end +-322.51 0.00 504.45 0 1 0 0 0 end +-315.96 0.00 506.92 0 1 0 0 0 end +-325.76 0.00 512.73 0 1 0 0 0 end +-319.29 0.00 515.39 0 1 0 0 0 end +-329.27 0.00 520.90 0 1 0 0 0 end +-322.88 0.00 523.76 0 1 0 0 0 end +-333.02 0.00 528.97 0 1 0 0 0 end +-326.71 0.00 532.01 0 1 0 0 0 end +-337.01 0.00 536.92 0 1 0 0 0 end +-330.80 0.00 540.15 0 1 0 0 0 end +-341.23 0.00 544.74 0 1 0 0 0 end +-335.12 0.00 548.16 0 1 0 0 0 end +-345.69 0.00 552.44 0 1 0 0 0 end +-339.69 0.00 556.04 0 1 0 0 0 end +-350.38 0.00 560.00 0 1 0 0 0 end +-344.48 0.00 563.78 0 1 0 0 0 end +-355.29 0.00 567.42 0 1 0 0 0 end +-349.51 0.00 571.37 0 1 0 0 0 end +-360.42 0.00 574.68 0 1 0 0 0 end +-354.76 0.00 578.81 0 1 0 0 0 end +-365.77 0.00 581.79 0 1 0 0 0 end +-360.24 0.00 586.08 0 1 0 0 0 end +-371.33 0.00 588.73 0 1 0 0 0 end +-365.93 0.00 593.19 0 1 0 0 0 end +-377.09 0.00 595.51 0 1 0 0 0 end +-371.83 0.00 600.12 0 1 0 0 0 end +-383.05 0.00 602.11 0 1 0 0 0 end +-377.93 0.00 606.88 0 1 0 0 0 end +-389.21 0.00 608.52 0 1 0 0 0 end +-384.24 0.00 613.45 0 1 0 0 0 end +-395.56 0.00 614.75 0 1 0 0 0 end +-390.74 0.00 619.82 0 1 0 0 0 end +-402.10 0.00 620.79 0 1 0 0 0 end +-397.43 0.00 626.00 0 1 0 0 0 end +-408.81 0.00 626.62 0 1 0 0 0 end +-404.30 0.00 631.97 0 1 0 0 0 end +-415.69 0.00 632.26 0 1 0 0 0 end +-411.34 0.00 637.74 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-310.06 0.00 310.31 0 1 0 0 0 end +-304.32 4.00 308.54 0 1 0 0 0 end +-307.50 0.00 319.05 0 1 0 0 0 end +-301.71 4.00 317.45 0 1 0 0 0 end +-305.20 0.00 327.86 0 1 0 0 0 end +-299.37 4.00 326.43 0 1 0 0 0 end +-303.17 0.00 336.73 0 1 0 0 0 end +-297.30 4.00 335.48 0 1 0 0 0 end +-301.40 0.00 345.66 0 1 0 0 0 end +-295.50 4.00 344.59 0 1 0 0 0 end +-299.91 0.00 354.65 0 1 0 0 0 end +-293.98 4.00 353.75 0 1 0 0 0 end +-298.68 0.00 363.67 0 1 0 0 0 end +-292.73 4.00 362.95 0 1 0 0 0 end +-297.73 0.00 372.72 0 1 0 0 0 end +-291.75 4.00 372.18 0 1 0 0 0 end +-297.05 0.00 381.80 0 1 0 0 0 end +-291.06 4.00 381.44 0 1 0 0 0 end +-296.64 0.00 390.90 0 1 0 0 0 end +-290.64 4.00 390.72 0 1 0 0 0 end +-296.50 0.00 400.00 0 1 0 0 0 end +-290.50 4.00 400.00 0 1 0 0 0 end +-296.64 0.00 409.10 0 1 0 0 0 end +-290.64 4.00 409.28 0 1 0 0 0 end +-297.05 0.00 418.20 0 1 0 0 0 end +-291.06 4.00 418.56 0 1 0 0 0 end +-297.73 0.00 427.28 0 1 0 0 0 end +-291.75 4.00 427.82 0 1 0 0 0 end +-298.68 0.00 436.33 0 1 0 0 0 end +-292.73 4.00 437.05 0 1 0 0 0 end +-299.91 0.00 445.35 0 1 0 0 0 end +-293.98 4.00 446.25 0 1 0 0 0 end +-301.40 0.00 454.34 0 1 0 0 0 end +-295.50 4.00 455.41 0 1 0 0 0 end +-303.17 0.00 463.27 0 1 0 0 0 end +-297.30 4.00 464.52 0 1 0 0 0 end +-305.20 0.00 472.14 0 1 0 0 0 end +-299.37 4.00 473.57 0 1 0 0 0 end +-307.50 0.00 480.95 0 1 0 0 0 end +-301.71 4.00 482.55 0 1 0 0 0 end +-310.06 0.00 489.69 0 1 0 0 0 end +-304.32 4.00 491.46 0 1 0 0 0 end +-312.88 0.00 498.35 0 1 0 0 0 end +-307.20 4.00 500.29 0 1 0 0 0 end +-315.96 0.00 506.92 0 1 0 0 0 end +-310.34 4.00 509.03 0 1 0 0 0 end +-319.29 0.00 515.39 0 1 0 0 0 end +-313.74 4.00 517.67 0 1 0 0 0 end +-322.88 0.00 523.76 0 1 0 0 0 end +-317.40 4.00 526.20 0 1 0 0 0 end +-326.71 0.00 532.01 0 1 0 0 0 end +-321.31 4.00 534.62 0 1 0 0 0 end +-330.80 0.00 540.15 0 1 0 0 0 end +-325.48 4.00 542.92 0 1 0 0 0 end +-335.12 0.00 548.16 0 1 0 0 0 end +-329.89 4.00 551.09 0 1 0 0 0 end +-339.69 0.00 556.04 0 1 0 0 0 end +-334.54 4.00 559.13 0 1 0 0 0 end +-344.48 0.00 563.78 0 1 0 0 0 end +-339.43 4.00 567.02 0 1 0 0 0 end +-349.51 0.00 571.37 0 1 0 0 0 end +-344.56 4.00 574.76 0 1 0 0 0 end +-354.76 0.00 578.81 0 1 0 0 0 end +-349.92 4.00 582.34 0 1 0 0 0 end +-360.24 0.00 586.08 0 1 0 0 0 end +-355.50 4.00 589.76 0 1 0 0 0 end +-365.93 0.00 593.19 0 1 0 0 0 end +-361.30 4.00 597.01 0 1 0 0 0 end +-371.83 0.00 600.12 0 1 0 0 0 end +-367.32 4.00 604.08 0 1 0 0 0 end +-377.93 0.00 606.88 0 1 0 0 0 end +-373.54 4.00 610.97 0 1 0 0 0 end +-384.24 0.00 613.45 0 1 0 0 0 end +-379.97 4.00 617.66 0 1 0 0 0 end +-390.74 0.00 619.82 0 1 0 0 0 end +-386.60 4.00 624.17 0 1 0 0 0 end +-397.43 0.00 626.00 0 1 0 0 0 end +-393.42 4.00 630.47 0 1 0 0 0 end +-404.30 0.00 631.97 0 1 0 0 0 end +-400.43 4.00 636.56 0 1 0 0 0 end +-411.34 0.00 637.74 0 1 0 0 0 end +-407.61 4.00 642.44 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-304.32 4.00 308.54 0 1 0 0 0 end +-170.10 32.10 267.02 0 1 0 0 0 end +-301.71 4.00 317.45 0 1 0 0 0 end +-166.30 32.10 279.97 0 1 0 0 0 end +-299.37 4.00 326.43 0 1 0 0 0 end +-162.90 32.10 293.03 0 1 0 0 0 end +-297.30 4.00 335.48 0 1 0 0 0 end +-159.89 32.10 306.19 0 1 0 0 0 end +-295.50 4.00 344.59 0 1 0 0 0 end +-157.27 32.10 319.44 0 1 0 0 0 end +-293.98 4.00 353.75 0 1 0 0 0 end +-155.05 32.10 332.75 0 1 0 0 0 end +-292.73 4.00 362.95 0 1 0 0 0 end +-153.24 32.10 346.13 0 1 0 0 0 end +-291.75 4.00 372.18 0 1 0 0 0 end +-151.82 32.10 359.55 0 1 0 0 0 end +-291.06 4.00 381.44 0 1 0 0 0 end +-150.81 32.10 373.02 0 1 0 0 0 end +-290.64 4.00 390.72 0 1 0 0 0 end +-150.20 32.10 386.50 0 1 0 0 0 end +-290.50 4.00 400.00 0 1 0 0 0 end +-150.00 32.10 400.00 0 1 0 0 0 end +-290.64 4.00 409.28 0 1 0 0 0 end +-150.20 32.10 413.50 0 1 0 0 0 end +-291.06 4.00 418.56 0 1 0 0 0 end +-150.81 32.10 426.98 0 1 0 0 0 end +-291.75 4.00 427.82 0 1 0 0 0 end +-151.82 32.10 440.45 0 1 0 0 0 end +-292.73 4.00 437.05 0 1 0 0 0 end +-153.24 32.10 453.87 0 1 0 0 0 end +-293.98 4.00 446.25 0 1 0 0 0 end +-155.05 32.10 467.25 0 1 0 0 0 end +-295.50 4.00 455.41 0 1 0 0 0 end +-157.27 32.10 480.56 0 1 0 0 0 end +-297.30 4.00 464.52 0 1 0 0 0 end +-159.89 32.10 493.81 0 1 0 0 0 end +-299.37 4.00 473.57 0 1 0 0 0 end +-162.90 32.10 506.97 0 1 0 0 0 end +-301.71 4.00 482.55 0 1 0 0 0 end +-166.30 32.10 520.03 0 1 0 0 0 end +-304.32 4.00 491.46 0 1 0 0 0 end +-170.10 32.10 532.98 0 1 0 0 0 end +-307.20 4.00 500.29 0 1 0 0 0 end +-174.28 32.10 545.82 0 1 0 0 0 end +-310.34 4.00 509.03 0 1 0 0 0 end +-178.85 32.10 558.52 0 1 0 0 0 end +-313.74 4.00 517.67 0 1 0 0 0 end +-183.79 32.10 571.08 0 1 0 0 0 end +-317.40 4.00 526.20 0 1 0 0 0 end +-189.11 32.10 583.49 0 1 0 0 0 end +-321.31 4.00 534.62 0 1 0 0 0 end +-194.80 32.10 595.73 0 1 0 0 0 end +-325.48 4.00 542.92 0 1 0 0 0 end +-200.85 32.10 607.80 0 1 0 0 0 end +-329.89 4.00 551.09 0 1 0 0 0 end +-207.26 32.10 619.68 0 1 0 0 0 end +-334.54 4.00 559.13 0 1 0 0 0 end +-214.03 32.10 631.36 0 1 0 0 0 end +-339.43 4.00 567.02 0 1 0 0 0 end +-221.14 32.10 642.83 0 1 0 0 0 end +-344.56 4.00 574.76 0 1 0 0 0 end +-228.60 32.10 654.09 0 1 0 0 0 end +-349.92 4.00 582.34 0 1 0 0 0 end +-236.39 32.10 665.12 0 1 0 0 0 end +-355.50 4.00 589.76 0 1 0 0 0 end +-244.50 32.10 675.90 0 1 0 0 0 end +-361.30 4.00 597.01 0 1 0 0 0 end +-252.94 32.10 686.44 0 1 0 0 0 end +-367.32 4.00 604.08 0 1 0 0 0 end +-261.69 32.10 696.72 0 1 0 0 0 end +-373.54 4.00 610.97 0 1 0 0 0 end +-270.74 32.10 706.74 0 1 0 0 0 end +-379.97 4.00 617.66 0 1 0 0 0 end +-280.09 32.10 716.48 0 1 0 0 0 end +-386.60 4.00 624.17 0 1 0 0 0 end +-289.73 32.10 725.93 0 1 0 0 0 end +-393.42 4.00 630.47 0 1 0 0 0 end +-299.64 32.10 735.09 0 1 0 0 0 end +-400.43 4.00 636.56 0 1 0 0 0 end +-309.83 32.10 743.95 0 1 0 0 0 end +-407.61 4.00 642.44 0 1 0 0 0 end +-320.28 32.10 752.50 0 1 0 0 0 +endtri +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 0.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 0.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_embankment.scn b/tests/scenarios/cases/td_off_track_curve_embankment.scn new file mode 100644 index 000000000..4f9d6c7c8 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_embankment.scn @@ -0,0 +1,273 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), on an embankment 4 m high with slopes of 1:1.5; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 none triangle_strip grass +-322.47 0.00 314.15 0 1 0 0 0 end +-316.74 4.00 312.38 0 1 0 0 0 end +-320.02 0.00 322.51 0 1 0 0 0 end +-314.24 4.00 320.91 0 1 0 0 0 end +-317.83 0.00 330.95 0 1 0 0 0 end +-312.00 4.00 329.52 0 1 0 0 0 end +-315.88 0.00 339.44 0 1 0 0 0 end +-310.01 4.00 338.19 0 1 0 0 0 end +-314.19 0.00 347.99 0 1 0 0 0 end +-308.29 4.00 346.92 0 1 0 0 0 end +-312.76 0.00 356.59 0 1 0 0 0 end +-306.83 4.00 355.69 0 1 0 0 0 end +-311.59 0.00 365.22 0 1 0 0 0 end +-305.63 4.00 364.51 0 1 0 0 0 end +-310.68 0.00 373.89 0 1 0 0 0 end +-304.70 4.00 373.35 0 1 0 0 0 end +-310.02 0.00 382.58 0 1 0 0 0 end +-304.03 4.00 382.22 0 1 0 0 0 end +-309.63 0.00 391.29 0 1 0 0 0 end +-303.63 4.00 391.11 0 1 0 0 0 end +-309.50 0.00 400.00 0 1 0 0 0 end +-303.50 4.00 400.00 0 1 0 0 0 end +-309.63 0.00 408.71 0 1 0 0 0 end +-303.63 4.00 408.89 0 1 0 0 0 end +-310.02 0.00 417.42 0 1 0 0 0 end +-304.03 4.00 417.78 0 1 0 0 0 end +-310.68 0.00 426.11 0 1 0 0 0 end +-304.70 4.00 426.65 0 1 0 0 0 end +-311.59 0.00 434.78 0 1 0 0 0 end +-305.63 4.00 435.49 0 1 0 0 0 end +-312.76 0.00 443.41 0 1 0 0 0 end +-306.83 4.00 444.31 0 1 0 0 0 end +-314.19 0.00 452.01 0 1 0 0 0 end +-308.29 4.00 453.08 0 1 0 0 0 end +-315.88 0.00 460.56 0 1 0 0 0 end +-310.01 4.00 461.81 0 1 0 0 0 end +-317.83 0.00 469.05 0 1 0 0 0 end +-312.00 4.00 470.48 0 1 0 0 0 end +-320.02 0.00 477.49 0 1 0 0 0 end +-314.24 4.00 479.09 0 1 0 0 0 end +-322.47 0.00 485.85 0 1 0 0 0 end +-316.74 4.00 487.62 0 1 0 0 0 end +-325.17 0.00 494.13 0 1 0 0 0 end +-319.50 4.00 496.08 0 1 0 0 0 end +-328.12 0.00 502.34 0 1 0 0 0 end +-322.51 4.00 504.45 0 1 0 0 0 end +-331.31 0.00 510.44 0 1 0 0 0 end +-325.76 4.00 512.73 0 1 0 0 0 end +-334.75 0.00 518.45 0 1 0 0 0 end +-329.27 4.00 520.90 0 1 0 0 0 end +-338.42 0.00 526.36 0 1 0 0 0 end +-333.02 4.00 528.97 0 1 0 0 0 end +-342.33 0.00 534.15 0 1 0 0 0 end +-337.01 4.00 536.92 0 1 0 0 0 end +-346.47 0.00 541.82 0 1 0 0 0 end +-341.23 4.00 544.74 0 1 0 0 0 end +-350.84 0.00 549.36 0 1 0 0 0 end +-345.69 4.00 552.44 0 1 0 0 0 end +-355.43 0.00 556.76 0 1 0 0 0 end +-350.38 4.00 560.00 0 1 0 0 0 end +-360.24 0.00 564.03 0 1 0 0 0 end +-355.29 4.00 567.42 0 1 0 0 0 end +-365.27 0.00 571.15 0 1 0 0 0 end +-360.42 4.00 574.68 0 1 0 0 0 end +-370.51 0.00 578.11 0 1 0 0 0 end +-365.77 4.00 581.79 0 1 0 0 0 end +-375.95 0.00 584.91 0 1 0 0 0 end +-371.33 4.00 588.73 0 1 0 0 0 end +-381.60 0.00 591.55 0 1 0 0 0 end +-377.09 4.00 595.51 0 1 0 0 0 end +-387.44 0.00 598.02 0 1 0 0 0 end +-383.05 4.00 602.11 0 1 0 0 0 end +-393.48 0.00 604.30 0 1 0 0 0 end +-389.21 4.00 608.52 0 1 0 0 0 end +-399.70 0.00 610.41 0 1 0 0 0 end +-395.56 4.00 614.75 0 1 0 0 0 end +-406.10 0.00 616.32 0 1 0 0 0 end +-402.10 4.00 620.79 0 1 0 0 0 end +-412.68 0.00 622.04 0 1 0 0 0 end +-408.81 4.00 626.62 0 1 0 0 0 end +-419.42 0.00 627.56 0 1 0 0 0 end +-415.69 4.00 632.26 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-316.74 4.00 312.38 0 1 0 0 0 end +-310.06 4.00 310.31 0 1 0 0 0 end +-314.24 4.00 320.91 0 1 0 0 0 end +-307.50 4.00 319.05 0 1 0 0 0 end +-312.00 4.00 329.52 0 1 0 0 0 end +-305.20 4.00 327.86 0 1 0 0 0 end +-310.01 4.00 338.19 0 1 0 0 0 end +-303.17 4.00 336.73 0 1 0 0 0 end +-308.29 4.00 346.92 0 1 0 0 0 end +-301.40 4.00 345.66 0 1 0 0 0 end +-306.83 4.00 355.69 0 1 0 0 0 end +-299.91 4.00 354.65 0 1 0 0 0 end +-305.63 4.00 364.51 0 1 0 0 0 end +-298.68 4.00 363.67 0 1 0 0 0 end +-304.70 4.00 373.35 0 1 0 0 0 end +-297.73 4.00 372.72 0 1 0 0 0 end +-304.03 4.00 382.22 0 1 0 0 0 end +-297.05 4.00 381.80 0 1 0 0 0 end +-303.63 4.00 391.11 0 1 0 0 0 end +-296.64 4.00 390.90 0 1 0 0 0 end +-303.50 4.00 400.00 0 1 0 0 0 end +-296.50 4.00 400.00 0 1 0 0 0 end +-303.63 4.00 408.89 0 1 0 0 0 end +-296.64 4.00 409.10 0 1 0 0 0 end +-304.03 4.00 417.78 0 1 0 0 0 end +-297.05 4.00 418.20 0 1 0 0 0 end +-304.70 4.00 426.65 0 1 0 0 0 end +-297.73 4.00 427.28 0 1 0 0 0 end +-305.63 4.00 435.49 0 1 0 0 0 end +-298.68 4.00 436.33 0 1 0 0 0 end +-306.83 4.00 444.31 0 1 0 0 0 end +-299.91 4.00 445.35 0 1 0 0 0 end +-308.29 4.00 453.08 0 1 0 0 0 end +-301.40 4.00 454.34 0 1 0 0 0 end +-310.01 4.00 461.81 0 1 0 0 0 end +-303.17 4.00 463.27 0 1 0 0 0 end +-312.00 4.00 470.48 0 1 0 0 0 end +-305.20 4.00 472.14 0 1 0 0 0 end +-314.24 4.00 479.09 0 1 0 0 0 end +-307.50 4.00 480.95 0 1 0 0 0 end +-316.74 4.00 487.62 0 1 0 0 0 end +-310.06 4.00 489.69 0 1 0 0 0 end +-319.50 4.00 496.08 0 1 0 0 0 end +-312.88 4.00 498.35 0 1 0 0 0 end +-322.51 4.00 504.45 0 1 0 0 0 end +-315.96 4.00 506.92 0 1 0 0 0 end +-325.76 4.00 512.73 0 1 0 0 0 end +-319.29 4.00 515.39 0 1 0 0 0 end +-329.27 4.00 520.90 0 1 0 0 0 end +-322.88 4.00 523.76 0 1 0 0 0 end +-333.02 4.00 528.97 0 1 0 0 0 end +-326.71 4.00 532.01 0 1 0 0 0 end +-337.01 4.00 536.92 0 1 0 0 0 end +-330.80 4.00 540.15 0 1 0 0 0 end +-341.23 4.00 544.74 0 1 0 0 0 end +-335.12 4.00 548.16 0 1 0 0 0 end +-345.69 4.00 552.44 0 1 0 0 0 end +-339.69 4.00 556.04 0 1 0 0 0 end +-350.38 4.00 560.00 0 1 0 0 0 end +-344.48 4.00 563.78 0 1 0 0 0 end +-355.29 4.00 567.42 0 1 0 0 0 end +-349.51 4.00 571.37 0 1 0 0 0 end +-360.42 4.00 574.68 0 1 0 0 0 end +-354.76 4.00 578.81 0 1 0 0 0 end +-365.77 4.00 581.79 0 1 0 0 0 end +-360.24 4.00 586.08 0 1 0 0 0 end +-371.33 4.00 588.73 0 1 0 0 0 end +-365.93 4.00 593.19 0 1 0 0 0 end +-377.09 4.00 595.51 0 1 0 0 0 end +-371.83 4.00 600.12 0 1 0 0 0 end +-383.05 4.00 602.11 0 1 0 0 0 end +-377.93 4.00 606.88 0 1 0 0 0 end +-389.21 4.00 608.52 0 1 0 0 0 end +-384.24 4.00 613.45 0 1 0 0 0 end +-395.56 4.00 614.75 0 1 0 0 0 end +-390.74 4.00 619.82 0 1 0 0 0 end +-402.10 4.00 620.79 0 1 0 0 0 end +-397.43 4.00 626.00 0 1 0 0 0 end +-408.81 4.00 626.62 0 1 0 0 0 end +-404.30 4.00 631.97 0 1 0 0 0 end +-415.69 4.00 632.26 0 1 0 0 0 end +-411.34 4.00 637.74 0 1 0 0 0 +endtri +node -1 0 none triangle_strip grass +-310.06 4.00 310.31 0 1 0 0 0 end +-304.32 0.00 308.54 0 1 0 0 0 end +-307.50 4.00 319.05 0 1 0 0 0 end +-301.71 0.00 317.45 0 1 0 0 0 end +-305.20 4.00 327.86 0 1 0 0 0 end +-299.37 0.00 326.43 0 1 0 0 0 end +-303.17 4.00 336.73 0 1 0 0 0 end +-297.30 0.00 335.48 0 1 0 0 0 end +-301.40 4.00 345.66 0 1 0 0 0 end +-295.50 0.00 344.59 0 1 0 0 0 end +-299.91 4.00 354.65 0 1 0 0 0 end +-293.98 0.00 353.75 0 1 0 0 0 end +-298.68 4.00 363.67 0 1 0 0 0 end +-292.73 0.00 362.95 0 1 0 0 0 end +-297.73 4.00 372.72 0 1 0 0 0 end +-291.75 0.00 372.18 0 1 0 0 0 end +-297.05 4.00 381.80 0 1 0 0 0 end +-291.06 0.00 381.44 0 1 0 0 0 end +-296.64 4.00 390.90 0 1 0 0 0 end +-290.64 0.00 390.72 0 1 0 0 0 end +-296.50 4.00 400.00 0 1 0 0 0 end +-290.50 0.00 400.00 0 1 0 0 0 end +-296.64 4.00 409.10 0 1 0 0 0 end +-290.64 0.00 409.28 0 1 0 0 0 end +-297.05 4.00 418.20 0 1 0 0 0 end +-291.06 0.00 418.56 0 1 0 0 0 end +-297.73 4.00 427.28 0 1 0 0 0 end +-291.75 0.00 427.82 0 1 0 0 0 end +-298.68 4.00 436.33 0 1 0 0 0 end +-292.73 0.00 437.05 0 1 0 0 0 end +-299.91 4.00 445.35 0 1 0 0 0 end +-293.98 0.00 446.25 0 1 0 0 0 end +-301.40 4.00 454.34 0 1 0 0 0 end +-295.50 0.00 455.41 0 1 0 0 0 end +-303.17 4.00 463.27 0 1 0 0 0 end +-297.30 0.00 464.52 0 1 0 0 0 end +-305.20 4.00 472.14 0 1 0 0 0 end +-299.37 0.00 473.57 0 1 0 0 0 end +-307.50 4.00 480.95 0 1 0 0 0 end +-301.71 0.00 482.55 0 1 0 0 0 end +-310.06 4.00 489.69 0 1 0 0 0 end +-304.32 0.00 491.46 0 1 0 0 0 end +-312.88 4.00 498.35 0 1 0 0 0 end +-307.20 0.00 500.29 0 1 0 0 0 end +-315.96 4.00 506.92 0 1 0 0 0 end +-310.34 0.00 509.03 0 1 0 0 0 end +-319.29 4.00 515.39 0 1 0 0 0 end +-313.74 0.00 517.67 0 1 0 0 0 end +-322.88 4.00 523.76 0 1 0 0 0 end +-317.40 0.00 526.20 0 1 0 0 0 end +-326.71 4.00 532.01 0 1 0 0 0 end +-321.31 0.00 534.62 0 1 0 0 0 end +-330.80 4.00 540.15 0 1 0 0 0 end +-325.48 0.00 542.92 0 1 0 0 0 end +-335.12 4.00 548.16 0 1 0 0 0 end +-329.89 0.00 551.09 0 1 0 0 0 end +-339.69 4.00 556.04 0 1 0 0 0 end +-334.54 0.00 559.13 0 1 0 0 0 end +-344.48 4.00 563.78 0 1 0 0 0 end +-339.43 0.00 567.02 0 1 0 0 0 end +-349.51 4.00 571.37 0 1 0 0 0 end +-344.56 0.00 574.76 0 1 0 0 0 end +-354.76 4.00 578.81 0 1 0 0 0 end +-349.92 0.00 582.34 0 1 0 0 0 end +-360.24 4.00 586.08 0 1 0 0 0 end +-355.50 0.00 589.76 0 1 0 0 0 end +-365.93 4.00 593.19 0 1 0 0 0 end +-361.30 0.00 597.01 0 1 0 0 0 end +-371.83 4.00 600.12 0 1 0 0 0 end +-367.32 0.00 604.08 0 1 0 0 0 end +-377.93 4.00 606.88 0 1 0 0 0 end +-373.54 0.00 610.97 0 1 0 0 0 end +-384.24 4.00 613.45 0 1 0 0 0 end +-379.97 0.00 617.66 0 1 0 0 0 end +-390.74 4.00 619.82 0 1 0 0 0 end +-386.60 0.00 624.17 0 1 0 0 0 end +-397.43 4.00 626.00 0 1 0 0 0 end +-393.42 0.00 630.47 0 1 0 0 0 end +-404.30 4.00 631.97 0 1 0 0 0 end +-400.43 0.00 636.56 0 1 0 0 0 end +-411.34 4.00 637.74 0 1 0 0 0 end +-407.61 0.00 642.44 0 1 0 0 0 +endtri +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 4.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 4.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_off_track_curve_flat.scn b/tests/scenarios/cases/td_off_track_curve_flat.scn new file mode 100644 index 000000000..ddaf4f287 --- /dev/null +++ b/tests/scenarios/cases/td_off_track_curve_flat.scn @@ -0,0 +1,21 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles +// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the +// fields of td.scn (autotest_curve), on level ground; written by a script, see the README. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 0.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 0.2 543.8277 0.0 //point 2 +300.0 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_overspeed_bad_limit.scn b/tests/scenarios/cases/td_overspeed_bad_limit.scn new file mode 100644 index 000000000..e74351bdd --- /dev/null +++ b/tests/scenarios/cases/td_overspeed_bad_limit.scn @@ -0,0 +1,33 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new): the track of +// R 300 m without cant of td_off_track_curve_flat.scn laid on its own in the fields of td.scn, on level ground, with a +// speed limit of 140 km/h the curve doesn't take (EU07 overturns in it at about 108 km/h): a defect of the data, as +// physics.trackcheck finds on some tracks of the bundled sceneries. a straight track of 900 m goes on from its end, +// so a vehicle that keeps to the rails runs on. +// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so +// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past +// point 1 of the curve towards its point 2 +node -1 0 autotest_curve track normal 150.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-300.0000 0.2 400.0000 0.0 //point 1 +-0.0000 0.0 50.2621 //control vector 1 +24.0969 0.0 -44.1091 //control vector 2 +-336.7252 0.2 543.8277 0.0 //point 2 +300.0 +velocity 140 +endtrack +node -1 0 autotest_curve_out track normal 900.0000 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-336.7252 0.2 543.8277 0.0 //point 1 +0.0 0.0 0.0 //control vector 1 +0.0 0.0 0.0 //control vector 2 +-768.2080 0.2 1333.6521 0.0 //point 2 +0 +velocity 140 +endtrack +trainset none tdo_n1734 0.0 0.0 +node -1 0 {{vehicle}} dynamic pkp\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic +endtrainset + +trainset none autotest_curve 20.0 {{velocity}} +node -1 0 {{vehicle}}_off dynamic pkp\4e_v1 4e-004 4e 0 nobody 0 0 enddynamic +endtrainset diff --git a/tests/scenarios/cases/td_passenger_upgrade.txt b/tests/scenarios/cases/td_passenger_upgrade.txt new file mode 100644 index 000000000..bc8e12087 --- /dev/null +++ b/tests/scenarios/cases/td_passenger_upgrade.txt @@ -0,0 +1,17 @@ +________________________________________________________________ +[ Rodzaj i numer pociagu | TEST28 ] +[ Kategoria | RO ] +[________________________________________________|______________] +[ | Gora ] +[ Relacja pociagu | Koniec ] +[________________________________________________|______________] +[ Wymagany % ciezaru hamujacego | 88% ] +[________________________________________________|______________] +[ Seria i obciazenie lokomotywy | EU07 400 ] +[________________________________________________|______________] +[ | | Gora 2 | | ] +[ | 80 | R1,L,H,RT,PP 2 10.35 | ] +[ | |----------------------------------1----------|---] +[ | | Koniec 1 10.45 | 10] +[ | | R1 1 10.46 | ] +[_______|_____|__________________________________1__________|___] diff --git a/tests/scenarios/cases/td_past_red_signal.scn b/tests/scenarios/cases/td_past_red_signal.scn new file mode 100644 index 000000000..e5e68da5f --- /dev/null +++ b/tests/scenarios/cases/td_past_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad) set at a stand past the exit signal stacja1_j, which stays at stop +// (no route): the head {{offset}} m into tor1k, whose memory cell of the signal is 51 m into the track. the train +// starts at 0.1 km/h, as in td_red_signal.scn: set at 0 its AI driver doesn't wake up within the case +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_reinspect_brakes.scn b/tests/scenarios/cases/td_reinspect_brakes.scn new file mode 100644 index 000000000..37c76550a --- /dev/null +++ b/tests/scenarios/cases/td_reinspect_brakes.scn @@ -0,0 +1,33 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// on the line from Stacja1 to Stacja2 (flat, curves of 600 m): a locomotive with an AI driver stands cold +// (trainset velocity 0) on koniec, its front 35 m past point 1 of the track, facing point 2, towards Stacja2; +// a cut of wagons (vars.cut) stands, braked as well and with nobody in it, ahead of it, its front 56 m past +// point 1 of tdo_n222, some 45 m in front of the locomotive. +trainset none koniec 35.0 0.0 +node -1 0 {{vehicle}} dynamic {{locomotive}} 0 headdriver 0 0 enddynamic +endtrainset + +trainset none tdo_n222 56.0 0.0 +{{cut}} +endtrainset + +// event0 of the locomotive's track (the case's track_events) runs while the locomotive stands there. it wakes +// the driver and gives it, once, the order to couple to the cut ahead and run it on as a train: Shunt -3 3, +// Connect (with the coupler and the brake hose) then Obey_train, which waits for the way to be given. the AI +// couples on the run, at some 4 km/h, and the wagon inspector of the train run looks at the new train then, +// before it stands. +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -3 3 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// the way: no signal of the line is in sight, so event2 of tdo_n231 (the case's track_events), 40 m in front of +// the cut, gives the speed a signal at proceed would, 40 km/h, which the AI reads as it scans the track ahead +event autotest_way PutValues 0 none 0 0 0 SetVelocity 40 40 endevent + +// event2 of tdo_n240 (the case's track_events), some 700 m on, as the locomotive runs over it pushing the train: +// the driver is taken off (Crew: 0 0), which leaves the brake valve in the emergency position, so the +// train stops on the brakes it has. the pass comes 150 s later, with the train standing. +event autotest_crew_off multiple 0 none autotest_driver_off autotest_pass endevent +event autotest_driver_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent +event autotest_pass UpdateValues 150 __test.result the_train_was_stopped_with_the_brakes_it_has 1 * endevent diff --git a/tests/scenarios/cases/td_shunt_red_signal.scn b/tests/scenarios/cases/td_shunt_red_signal.scn new file mode 100644 index 000000000..649427247 --- /dev/null +++ b/tests/scenarios/cases/td_shunt_red_signal.scn @@ -0,0 +1,7 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// like td_red_signal_moving.scn (no route, the exit signal stacja1_j about 150 m ahead of the start of +// tdo_n1734 stays at stop), but the train has no timetable, so its AI driver shunts (Shunt), and it +// starts {{offset}} m into tdo_n1734, already moving at {{velocity}} km/h. +trainset none tdo_n1734 {{offset}} {{velocity}} +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_switch_thrown.scn b/tests/scenarios/cases/td_switch_thrown.scn new file mode 100644 index 000000000..b7706034b --- /dev/null +++ b/tests/scenarios/cases/td_switch_thrown.scn @@ -0,0 +1,45 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a switch of Stacja1 thrown by an event while a train stands or runs over it (the review of MaSzyna-EU07/maszyna#289, +// point 2b). Both switches of the station have their points (point 1) towards the line and two ways from there to +// the station: position 0 straight to track 2 (x 0.4), position 1 curved to track 1 (x 2.3 at the end of the switch, +// x 5.0 further on). The events of zwrp34r300.inc / zwrl34r300.inc: + sets position 0, - position 1 +// (and the speed of the switch: none on the straight, 40 on the curve). +// - zwr01, west end: points at z 336, the ways end at z 370 (tor2p, track 2; tdo_n1641, track 1). A train running +// towards z 2000 (into the station) goes through it facing, from the points. +// - zwr02, east end: points at z 1436 (tdo_n145, the line), the ways end at z 1402 (tor2k, track 2; tdo_n1744, +// track 1). A train running towards z 2000 (out of the station) goes through it trailing, from the frog end. +// A trainset faces point 2 of its track (towards z 2000 on all these tracks): the first vehicle has its front as many +// metres past point 1 as the trainset says, the others stand behind it. +{{trainsets}} + +// the way set at the start, if any (a launcher with a positive time fires once at that hour, the scenery starts +// at 10:34) +{{route}} + +// the throw (vars.throw), once: whichever of the events hung on the tracks of the case (track_events) or the +// launcher (vars.trigger) sets it off first, the memory cell keeps the others from doing it again +node -1 0 autotest_thrown memcell 0 0 0 thrown 0 0 none endmemcell +event autotest_throw multiple 0 autotest_thrown {{throw}} autotest_throw_done condition memcompare * 0 * endevent +event autotest_throw_done UpdateValues 0 autotest_thrown * 1 * endevent +{{trigger}} + +// a driver of a trainset of velocity 0 sleeps until it gets an order. event0 of the track its vehicle stands on +// (track_events) gives it, once: vars.order, e.g. Shunt -1 0 (go on shunting with the whole train; a proceed aspect +// of a main signal ahead turns that into a train run) or Obey_train 0 0. autotest_wake gives it at once, +// autotest_wake_after_throw only once the switch has been thrown (for a train standing over the switch) +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake_after_throw multiple 0 autotest_thrown autotest_wake condition memcompare * 1 * endevent +event autotest_wake multiple 0 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 {{order}} endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// a signal at stop on track 1 for a train running towards z 2000: the memory cell stands beside the track at z 1100 +// and event2 of tdo_n1725 (z 1065-1165, track_events) reads it. A train on track 1 has to stop before it, with its head +// on tdo_n1725, where event0 passes the test; running onto tdo_n1734 (z 1165-1265) beyond the signal fails it. On +// track 2 the train stops before the exit signal stacja1_k (z 1316, at stop all the time), with its head on tdo_n109 +// (z 1236-1336) +node -1 0 autotest_signal1 memcell 5.04488 0.2 1100.0 SetVelocity 0 0 none endmemcell +event autotest_signal1_info getvalues 0 autotest_signal1 endevent +event autotest_pass UpdateValues 0 __test.result stopped_before_the_signal 1 * endevent +event autotest_fail UpdateValues 0 __test.result ran_past_the_signal_of_track_1 0 * endevent +event autotest_pass_running UpdateValues 0 __test.result ran_clear_of_the_switch 1 * endevent diff --git a/tests/scenarios/cases/td_timetable_genset.scn b/tests/scenarios/cases/td_timetable_genset.scn new file mode 100644 index 000000000..0918dc1bc --- /dev/null +++ b/tests/scenarios/cases/td_timetable_genset.scn @@ -0,0 +1,18 @@ +// td_timetable.scn (the timetable train on track 1 of Stacja1, route out at 10:34) with the train switched to its +// genset by the scenery before it leaves (eu07/maszyna#536, a dual-mode vehicle): event0 of the start track (the +// track_events of the case) runs while the vehicle with a driver stands there and gives it, once, PutValues +// MainSwitch 0, TractionMode 1 and GensetSwitch 1, a second apart, as the vehicle holds one command at a time. +// the AI knows nothing of the genset: it closes the line breaker once the genset runs and drives on its power +trainset td/rozklad tdo_n1734 0.0 0.1 +{{consist}} +endtrainset + +// the way out of track 1, see td_timetable.scn +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end + +node -1 0 autotest_genset_done memcell 0 0 0 done 0 0 none endmemcell +event autotest_genset multiple 0 autotest_genset_done autotest_genset_ws autotest_genset_mode autotest_genset_on autotest_genset_mark condition memcompare * 0 * endevent +event autotest_genset_ws PutValues 0 none 0 0 0 MainSwitch 0 0 endevent +event autotest_genset_mode PutValues 1 none 0 0 0 TractionMode 1 0 endevent +event autotest_genset_on PutValues 2 none 0 0 0 GensetSwitch 1 0 endevent +event autotest_genset_mark UpdateValues 0 autotest_genset_done * 1 * endevent diff --git a/tests/scenarios/cases/td_timetable_past_w4.scn b/tests/scenarios/cases/td_timetable_past_w4.scn new file mode 100644 index 000000000..e7e83d51b --- /dev/null +++ b/tests/scenarios/cases/td_timetable_past_w4.scn @@ -0,0 +1,9 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// the timetable train of td.scn (td/rozklad, Stacja1 10:35 -> Przystanek -> Stacja2) placed past the W4 of +// Stacja1 instead of before it: the head {{offset}} m into tor1k, the track after the one with the W4, which is +// left under the consist, behind the head. the route out of track 1 is set at 10:34 +trainset td/rozklad tor1k {{offset}} 0.1 +{{consist}} +endtrainset + +node -1 0 autotest_route eventlauncher 0 0 0 -1 none 1034 keyctrl04 end diff --git a/tests/scenarios/cases/td_uncouple_past_signal.scn b/tests/scenarios/cases/td_uncouple_past_signal.scn new file mode 100644 index 000000000..98ab9033e --- /dev/null +++ b/tests/scenarios/cases/td_uncouple_past_signal.scn @@ -0,0 +1,31 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a shunter with no timetable stands at the far end of tor1k (point 2), turned (offset -1) to face back towards +// track 1 of Stacja1, with its wagons (vars.wagons) behind it, towards the exit signal stacja1_j (at stop, no route; +// its memory cell is 51 m into tor1k). the trainset's velocity is negative, so its driver takes the direction of the +// locomotive's cab and pulls. tdo_n1734, the track behind tor1k, is closed (speed 0) from the start, so the shunter +// pulls the wagons back along tor1k and stops in front of it, with the far end of the last wagon a few metres past +// the signal: the signal stands at stop over that wagon for the direction the shunter pushes in when it uncouples. +// the pull leaves the screw coupler stretched, as at a real stop. +trainset none tor1k 100.0 -0.1 +{{wagons}} +node -1 0 {{vehicle}} dynamic pkp\sm42_v1 6DA-1096 6da -1 headdriver 0 0 enddynamic +endtrainset + +node -1 0 autotest_closed eventlauncher 0 0 0 -1 none 1034 autotest_close end +event autotest_close trackvel 0 tdo_n1734 0 endevent + +// a standing shunter waits for the scenery's orders. event0 of tor1k (the case's track_events) runs while it stands +// there. the first time it gives the order to go (Shunt -1 0). 25 s later the shunter is on its way, and the first +// time it stands again, in front of tdo_n1734, it gets the order a scenery gives to leave the wagons: Shunt 0 0, +// uncouple everything behind the locomotive and stay. it brakes the wagons, changes direction, pushes the buffers in +// and lets the coupler go. the order comes at once: standing for long, the wagons' brakes release and the coupler +// draws the buffers together, which leaves nothing to push +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event autotest_wake multiple 0 none autotest_go autotest_uncouple endevent +event autotest_go multiple 0 autotest_ordered autotest_go_order autotest_go_given autotest_go_done condition memcompare * 0 * endevent +event autotest_go_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_go_given UpdateValues 0 autotest_ordered * 1 * endevent +event autotest_go_done UpdateValues 25 autotest_ordered * 2 * endevent +event autotest_uncouple multiple 0 autotest_ordered autotest_uncouple_order autotest_uncouple_given condition memcompare * 2 * endevent +event autotest_uncouple_order PutValues 0 none 0 0 0 Shunt 0 0 endevent +event autotest_uncouple_given UpdateValues 0 autotest_ordered * 3 * endevent diff --git a/tests/scenarios/cases/td_upgrade_long.scn b/tests/scenarios/cases/td_upgrade_long.scn new file mode 100644 index 000000000..12ff5c713 --- /dev/null +++ b/tests/scenarios/cases/td_upgrade_long.scn @@ -0,0 +1,934 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 5500 m up a gradient of 10 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the +// timetable {{timetable}} (leaves Gora at 10:35, no other stop) at the line limit of the timetable, up to the signal ul_sem +// at stop 5300 m up the gradient. the line goes on 200 m past it +node -1 0 ul_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 ul_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 ul_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 ul_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 ul_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 ul_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 ul_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 61.00 100.0 0.0 +0 +endtrack +node -1 0 ul_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 61.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 62.00 200.0 0.0 +0 +endtrack +node -1 0 ul_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 62.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 63.00 300.0 0.0 +0 +endtrack +node -1 0 ul_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 63.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 64.00 400.0 0.0 +0 +endtrack +node -1 0 ul_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 64.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 65.00 500.0 0.0 +0 +endtrack +node -1 0 ul_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 65.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 66.00 600.0 0.0 +0 +endtrack +node -1 0 ul_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 66.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 67.00 700.0 0.0 +0 +endtrack +node -1 0 ul_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 67.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 68.00 800.0 0.0 +0 +endtrack +node -1 0 ul_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 68.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 69.00 900.0 0.0 +0 +endtrack +node -1 0 ul_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 69.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 70.00 1000.0 0.0 +0 +endtrack +node -1 0 ul_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 70.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 71.00 1100.0 0.0 +0 +endtrack +node -1 0 ul_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 71.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 72.00 1200.0 0.0 +0 +endtrack +node -1 0 ul_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 72.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 73.00 1300.0 0.0 +0 +endtrack +node -1 0 ul_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 73.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 74.00 1400.0 0.0 +0 +endtrack +node -1 0 ul_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 74.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 75.00 1500.0 0.0 +0 +endtrack +node -1 0 ul_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 75.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 76.00 1600.0 0.0 +0 +endtrack +node -1 0 ul_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 76.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 77.00 1700.0 0.0 +0 +endtrack +node -1 0 ul_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 77.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 78.00 1800.0 0.0 +0 +endtrack +node -1 0 ul_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 78.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 79.00 1900.0 0.0 +0 +endtrack +node -1 0 ul_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 79.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 80.00 2000.0 0.0 +0 +endtrack +node -1 0 ul_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 80.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 81.00 2100.0 0.0 +0 +endtrack +node -1 0 ul_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 81.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 82.00 2200.0 0.0 +0 +endtrack +node -1 0 ul_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 82.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 83.00 2300.0 0.0 +0 +endtrack +node -1 0 ul_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 83.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 84.00 2400.0 0.0 +0 +endtrack +node -1 0 ul_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 84.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 85.00 2500.0 0.0 +0 +endtrack +node -1 0 ul_31 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 85.00 2500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 86.00 2600.0 0.0 +0 +endtrack +node -1 0 ul_32 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 86.00 2600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 87.00 2700.0 0.0 +0 +endtrack +node -1 0 ul_33 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 87.00 2700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 88.00 2800.0 0.0 +0 +endtrack +node -1 0 ul_34 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 88.00 2800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 89.00 2900.0 0.0 +0 +endtrack +node -1 0 ul_35 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 89.00 2900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 90.00 3000.0 0.0 +0 +endtrack +node -1 0 ul_36 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 90.00 3000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 91.00 3100.0 0.0 +0 +endtrack +node -1 0 ul_37 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 91.00 3100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 92.00 3200.0 0.0 +0 +endtrack +node -1 0 ul_38 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 92.00 3200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 93.00 3300.0 0.0 +0 +endtrack +node -1 0 ul_39 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 93.00 3300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 94.00 3400.0 0.0 +0 +endtrack +node -1 0 ul_40 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 94.00 3400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 95.00 3500.0 0.0 +0 +endtrack +node -1 0 ul_41 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 95.00 3500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 96.00 3600.0 0.0 +0 +endtrack +node -1 0 ul_42 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 96.00 3600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 97.00 3700.0 0.0 +0 +endtrack +node -1 0 ul_43 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 97.00 3700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 98.00 3800.0 0.0 +0 +endtrack +node -1 0 ul_44 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 98.00 3800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 99.00 3900.0 0.0 +0 +endtrack +node -1 0 ul_45 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 99.00 3900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 100.00 4000.0 0.0 +0 +endtrack +node -1 0 ul_46 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 100.00 4000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 101.00 4100.0 0.0 +0 +endtrack +node -1 0 ul_47 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 101.00 4100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 102.00 4200.0 0.0 +0 +endtrack +node -1 0 ul_48 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 102.00 4200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 103.00 4300.0 0.0 +0 +endtrack +node -1 0 ul_49 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 103.00 4300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 104.00 4400.0 0.0 +0 +endtrack +node -1 0 ul_50 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 104.00 4400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 105.00 4500.0 0.0 +0 +endtrack +node -1 0 ul_51 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 105.00 4500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 106.00 4600.0 0.0 +0 +endtrack +node -1 0 ul_52 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 106.00 4600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 107.00 4700.0 0.0 +0 +endtrack +node -1 0 ul_53 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 107.00 4700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 108.00 4800.0 0.0 +0 +endtrack +node -1 0 ul_54 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 108.00 4800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 109.00 4900.0 0.0 +0 +endtrack +node -1 0 ul_55 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 109.00 4900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 110.00 5000.0 0.0 +0 +endtrack +node -1 0 ul_56 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 110.00 5000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 111.00 5100.0 0.0 +0 +endtrack +node -1 0 ul_57 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 111.00 5100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 112.00 5200.0 0.0 +0 +endtrack +node -1 0 ul_58 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 112.00 5200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 113.00 5300.0 0.0 +0 +event2 ul_sem_info +endtrack +node -1 0 ul_59 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 113.00 5300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 114.00 5400.0 0.0 +0 +endtrack +node -1 0 ul_60 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 114.00 5400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 115.00 5500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 ul_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 66.60 100.0 +-3000.0 67.30 0.0 +-3000.0 68.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 66.60 100.0 +-3000.0 67.60 200.0 +-3000.0 68.30 100.0 +-3000.0 69.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 67.60 200.0 +-3000.0 68.60 300.0 +-3000.0 69.30 200.0 +-3000.0 70.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 68.60 300.0 +-3000.0 69.60 400.0 +-3000.0 70.30 300.0 +-3000.0 71.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 69.60 400.0 +-3000.0 70.60 500.0 +-3000.0 71.30 400.0 +-3000.0 72.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 70.60 500.0 +-3000.0 71.60 600.0 +-3000.0 72.30 500.0 +-3000.0 73.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 71.60 600.0 +-3000.0 72.60 700.0 +-3000.0 73.30 600.0 +-3000.0 74.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 72.60 700.0 +-3000.0 73.60 800.0 +-3000.0 74.30 700.0 +-3000.0 75.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 73.60 800.0 +-3000.0 74.60 900.0 +-3000.0 75.30 800.0 +-3000.0 76.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 74.60 900.0 +-3000.0 75.60 1000.0 +-3000.0 76.30 900.0 +-3000.0 77.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 75.60 1000.0 +-3000.0 76.60 1100.0 +-3000.0 77.30 1000.0 +-3000.0 78.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 76.60 1100.0 +-3000.0 77.60 1200.0 +-3000.0 78.30 1100.0 +-3000.0 79.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 77.60 1200.0 +-3000.0 78.60 1300.0 +-3000.0 79.30 1200.0 +-3000.0 80.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 78.60 1300.0 +-3000.0 79.60 1400.0 +-3000.0 80.30 1300.0 +-3000.0 81.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 79.60 1400.0 +-3000.0 80.60 1500.0 +-3000.0 81.30 1400.0 +-3000.0 82.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 80.60 1500.0 +-3000.0 81.60 1600.0 +-3000.0 82.30 1500.0 +-3000.0 83.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 81.60 1600.0 +-3000.0 82.60 1700.0 +-3000.0 83.30 1600.0 +-3000.0 84.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 82.60 1700.0 +-3000.0 83.60 1800.0 +-3000.0 84.30 1700.0 +-3000.0 85.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 83.60 1800.0 +-3000.0 84.60 1900.0 +-3000.0 85.30 1800.0 +-3000.0 86.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 84.60 1900.0 +-3000.0 85.60 2000.0 +-3000.0 86.30 1900.0 +-3000.0 87.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 85.60 2000.0 +-3000.0 86.60 2100.0 +-3000.0 87.30 2000.0 +-3000.0 88.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 86.60 2100.0 +-3000.0 87.60 2200.0 +-3000.0 88.30 2100.0 +-3000.0 89.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 87.60 2200.0 +-3000.0 88.60 2300.0 +-3000.0 89.30 2200.0 +-3000.0 90.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 88.60 2300.0 +-3000.0 89.60 2400.0 +-3000.0 90.30 2300.0 +-3000.0 91.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 89.60 2400.0 +-3000.0 90.60 2500.0 +-3000.0 91.30 2400.0 +-3000.0 92.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 90.60 2500.0 +-3000.0 91.60 2600.0 +-3000.0 92.30 2500.0 +-3000.0 93.30 2600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 91.60 2600.0 +-3000.0 92.60 2700.0 +-3000.0 93.30 2600.0 +-3000.0 94.30 2700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 92.60 2700.0 +-3000.0 93.60 2800.0 +-3000.0 94.30 2700.0 +-3000.0 95.30 2800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 93.60 2800.0 +-3000.0 94.60 2900.0 +-3000.0 95.30 2800.0 +-3000.0 96.30 2900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 94.60 2900.0 +-3000.0 95.60 3000.0 +-3000.0 96.30 2900.0 +-3000.0 97.30 3000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 95.60 3000.0 +-3000.0 96.60 3100.0 +-3000.0 97.30 3000.0 +-3000.0 98.30 3100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 96.60 3100.0 +-3000.0 97.60 3200.0 +-3000.0 98.30 3100.0 +-3000.0 99.30 3200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 97.60 3200.0 +-3000.0 98.60 3300.0 +-3000.0 99.30 3200.0 +-3000.0 100.30 3300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 98.60 3300.0 +-3000.0 99.60 3400.0 +-3000.0 100.30 3300.0 +-3000.0 101.30 3400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 99.60 3400.0 +-3000.0 100.60 3500.0 +-3000.0 101.30 3400.0 +-3000.0 102.30 3500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 100.60 3500.0 +-3000.0 101.60 3600.0 +-3000.0 102.30 3500.0 +-3000.0 103.30 3600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 101.60 3600.0 +-3000.0 102.60 3700.0 +-3000.0 103.30 3600.0 +-3000.0 104.30 3700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 102.60 3700.0 +-3000.0 103.60 3800.0 +-3000.0 104.30 3700.0 +-3000.0 105.30 3800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 103.60 3800.0 +-3000.0 104.60 3900.0 +-3000.0 105.30 3800.0 +-3000.0 106.30 3900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 104.60 3900.0 +-3000.0 105.60 4000.0 +-3000.0 106.30 3900.0 +-3000.0 107.30 4000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 105.60 4000.0 +-3000.0 106.60 4100.0 +-3000.0 107.30 4000.0 +-3000.0 108.30 4100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 106.60 4100.0 +-3000.0 107.60 4200.0 +-3000.0 108.30 4100.0 +-3000.0 109.30 4200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 107.60 4200.0 +-3000.0 108.60 4300.0 +-3000.0 109.30 4200.0 +-3000.0 110.30 4300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 108.60 4300.0 +-3000.0 109.60 4400.0 +-3000.0 110.30 4300.0 +-3000.0 111.30 4400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 109.60 4400.0 +-3000.0 110.60 4500.0 +-3000.0 111.30 4400.0 +-3000.0 112.30 4500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 110.60 4500.0 +-3000.0 111.60 4600.0 +-3000.0 112.30 4500.0 +-3000.0 113.30 4600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 111.60 4600.0 +-3000.0 112.60 4700.0 +-3000.0 113.30 4600.0 +-3000.0 114.30 4700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 112.60 4700.0 +-3000.0 113.60 4800.0 +-3000.0 114.30 4700.0 +-3000.0 115.30 4800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 113.60 4800.0 +-3000.0 114.60 4900.0 +-3000.0 115.30 4800.0 +-3000.0 116.30 4900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 114.60 4900.0 +-3000.0 115.60 5000.0 +-3000.0 116.30 4900.0 +-3000.0 117.30 5000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 115.60 5000.0 +-3000.0 116.60 5100.0 +-3000.0 117.30 5000.0 +-3000.0 118.30 5100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 116.60 5100.0 +-3000.0 117.60 5200.0 +-3000.0 118.30 5100.0 +-3000.0 119.30 5200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 117.60 5200.0 +-3000.0 118.60 5300.0 +-3000.0 119.30 5200.0 +-3000.0 120.30 5300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 118.60 5300.0 +-3000.0 119.60 5400.0 +-3000.0 120.30 5300.0 +-3000.0 121.30 5400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction ul_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 119.60 5400.0 +-3000.0 120.60 5500.0 +-3000.0 121.30 5400.0 +-3000.0 122.30 5500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 ul_sem_mem memcell -2997.3 121.00 5300.0 SetVelocity 0.0 0.0 none endmemcell +event ul_sem_info getvalues 5.0 ul_sem_mem endevent + +trainset {{timetable}} ul_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/td_upgrade_signal_start.scn b/tests/scenarios/cases/td_upgrade_signal_start.scn new file mode 100644 index 000000000..3995d3a96 --- /dev/null +++ b/tests/scenarios/cases/td_upgrade_signal_start.scn @@ -0,0 +1,492 @@ +// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed. +// a line of its own, away from the tracks of td.scn: 600 m level, then 2500 m up a gradient of 10 per mille, +// under an overhead wire. the train starts on the level with its head 10 m before the W4 of Gora and runs on the +// timetable {{timetable}} (no stop; a freight train leaves Gora at once) up to the signal hu_sem1 1000 m up the gradient, at stop until 10:42, +// where it stops with the whole train on the gradient, then on to the signal hu_sem2 at stop 2300 m up the +// gradient. the line goes on 200 m past it +node -1 0 hu_00 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -500.0 0.0 +0 +endtrack +node -1 0 hu_01 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -400.0 0.0 +0 +endtrack +node -1 0 hu_02 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -300.0 0.0 +0 +endtrack +node -1 0 hu_03 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -200.0 0.0 +0 +endtrack +node -1 0 hu_04 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 -100.0 0.0 +0 +endtrack +node -1 0 hu_05 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 -100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 60.00 0.0 0.0 +0 +event2 gora#1_stopinfo +endtrack +node -1 0 hu_06 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 60.00 0.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 61.00 100.0 0.0 +0 +endtrack +node -1 0 hu_07 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 61.00 100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 62.00 200.0 0.0 +0 +endtrack +node -1 0 hu_08 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 62.00 200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 63.00 300.0 0.0 +0 +endtrack +node -1 0 hu_09 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 63.00 300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 64.00 400.0 0.0 +0 +endtrack +node -1 0 hu_10 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 64.00 400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 65.00 500.0 0.0 +0 +endtrack +node -1 0 hu_11 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 65.00 500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 66.00 600.0 0.0 +0 +endtrack +node -1 0 hu_12 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 66.00 600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 67.00 700.0 0.0 +0 +endtrack +node -1 0 hu_13 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 67.00 700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 68.00 800.0 0.0 +0 +endtrack +node -1 0 hu_14 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 68.00 800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 69.00 900.0 0.0 +0 +endtrack +node -1 0 hu_15 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 69.00 900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 70.00 1000.0 0.0 +0 +event2 hu_sem1_info +endtrack +node -1 0 hu_16 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 70.00 1000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 71.00 1100.0 0.0 +0 +endtrack +node -1 0 hu_17 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 71.00 1100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 72.00 1200.0 0.0 +0 +endtrack +node -1 0 hu_18 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 72.00 1200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 73.00 1300.0 0.0 +0 +endtrack +node -1 0 hu_19 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 73.00 1300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 74.00 1400.0 0.0 +0 +endtrack +node -1 0 hu_20 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 74.00 1400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 75.00 1500.0 0.0 +0 +endtrack +node -1 0 hu_21 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 75.00 1500.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 76.00 1600.0 0.0 +0 +endtrack +node -1 0 hu_22 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 76.00 1600.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 77.00 1700.0 0.0 +0 +endtrack +node -1 0 hu_23 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 77.00 1700.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 78.00 1800.0 0.0 +0 +endtrack +node -1 0 hu_24 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 78.00 1800.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 79.00 1900.0 0.0 +0 +endtrack +node -1 0 hu_25 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 79.00 1900.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 80.00 2000.0 0.0 +0 +endtrack +node -1 0 hu_26 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 80.00 2000.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 81.00 2100.0 0.0 +0 +endtrack +node -1 0 hu_27 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 81.00 2100.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 82.00 2200.0 0.0 +0 +endtrack +node -1 0 hu_28 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 82.00 2200.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 83.00 2300.0 0.0 +0 +event2 hu_sem2_info +endtrack +node -1 0 hu_29 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 83.00 2300.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 84.00 2400.0 0.0 +0 +endtrack +node -1 0 hu_30 track normal 100.0 1.435 0.15 25.0 20 0 flat vis + rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1 +-3000.0 84.00 2400.0 0.0 +0.0 0.0 0.0 +0.0 0.0 0.0 +-3000.0 85.00 2500.0 0.0 +0 +endtrack +// the overhead wire along the whole line, as td.scn has it: 5.6 m above the rail, the carrier 1.7 m higher, fed by +// a substation of its own +node -1 0 hu_pwr tractionpowersource -3000.0 60.00 0.0 3400 0 0.01 2000 1.0 3 60.0 end +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -600.0 +-3000.0 65.60 -500.0 +-3000.0 67.30 -600.0 +-3000.0 67.30 -500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -500.0 +-3000.0 65.60 -400.0 +-3000.0 67.30 -500.0 +-3000.0 67.30 -400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -400.0 +-3000.0 65.60 -300.0 +-3000.0 67.30 -400.0 +-3000.0 67.30 -300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -300.0 +-3000.0 65.60 -200.0 +-3000.0 67.30 -300.0 +-3000.0 67.30 -200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -200.0 +-3000.0 65.60 -100.0 +-3000.0 67.30 -200.0 +-3000.0 67.30 -100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 -100.0 +-3000.0 65.60 0.0 +-3000.0 67.30 -100.0 +-3000.0 67.30 0.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 65.60 0.0 +-3000.0 66.60 100.0 +-3000.0 67.30 0.0 +-3000.0 68.30 100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 66.60 100.0 +-3000.0 67.60 200.0 +-3000.0 68.30 100.0 +-3000.0 69.30 200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 67.60 200.0 +-3000.0 68.60 300.0 +-3000.0 69.30 200.0 +-3000.0 70.30 300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 68.60 300.0 +-3000.0 69.60 400.0 +-3000.0 70.30 300.0 +-3000.0 71.30 400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 69.60 400.0 +-3000.0 70.60 500.0 +-3000.0 71.30 400.0 +-3000.0 72.30 500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 70.60 500.0 +-3000.0 71.60 600.0 +-3000.0 72.30 500.0 +-3000.0 73.30 600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 71.60 600.0 +-3000.0 72.60 700.0 +-3000.0 73.30 600.0 +-3000.0 74.30 700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 72.60 700.0 +-3000.0 73.60 800.0 +-3000.0 74.30 700.0 +-3000.0 75.30 800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 73.60 800.0 +-3000.0 74.60 900.0 +-3000.0 75.30 800.0 +-3000.0 76.30 900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 74.60 900.0 +-3000.0 75.60 1000.0 +-3000.0 76.30 900.0 +-3000.0 77.30 1000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 75.60 1000.0 +-3000.0 76.60 1100.0 +-3000.0 77.30 1000.0 +-3000.0 78.30 1100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 76.60 1100.0 +-3000.0 77.60 1200.0 +-3000.0 78.30 1100.0 +-3000.0 79.30 1200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 77.60 1200.0 +-3000.0 78.60 1300.0 +-3000.0 79.30 1200.0 +-3000.0 80.30 1300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 78.60 1300.0 +-3000.0 79.60 1400.0 +-3000.0 80.30 1300.0 +-3000.0 81.30 1400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 79.60 1400.0 +-3000.0 80.60 1500.0 +-3000.0 81.30 1400.0 +-3000.0 82.30 1500.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 80.60 1500.0 +-3000.0 81.60 1600.0 +-3000.0 82.30 1500.0 +-3000.0 83.30 1600.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 81.60 1600.0 +-3000.0 82.60 1700.0 +-3000.0 83.30 1600.0 +-3000.0 84.30 1700.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 82.60 1700.0 +-3000.0 83.60 1800.0 +-3000.0 84.30 1700.0 +-3000.0 85.30 1800.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 83.60 1800.0 +-3000.0 84.60 1900.0 +-3000.0 85.30 1800.0 +-3000.0 86.30 1900.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 84.60 1900.0 +-3000.0 85.60 2000.0 +-3000.0 86.30 1900.0 +-3000.0 87.30 2000.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 85.60 2000.0 +-3000.0 86.60 2100.0 +-3000.0 87.30 2000.0 +-3000.0 88.30 2100.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 86.60 2100.0 +-3000.0 87.60 2200.0 +-3000.0 88.30 2100.0 +-3000.0 89.30 2200.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 87.60 2200.0 +-3000.0 88.60 2300.0 +-3000.0 89.30 2200.0 +-3000.0 90.30 2300.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 88.60 2300.0 +-3000.0 89.60 2400.0 +-3000.0 90.30 2300.0 +-3000.0 91.30 2400.0 +0.4 4.0 3 0.04 vis +endtraction +node -1 0 none traction hu_pwr 3500 4500 0.01 cu 3.0 1 +-3000.0 89.60 2400.0 +-3000.0 90.60 2500.0 +-3000.0 91.30 2400.0 +-3000.0 92.30 2500.0 +0.4 4.0 3 0.04 vis +endtraction +// the W4 of the stations of the timetable +include ip/pkp/w4n.inc gora#1 -2997.3 60.00 -90.0 180 0 0 -10 202 end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hu_sem1_mem memcell -2997.3 78.00 1000.0 SetVelocity 0.0 0.0 none endmemcell +event hu_sem1_info getvalues 5.0 hu_sem1_mem endevent +// cleared at 10:42: the memory cell lets the train go at the line speed +event hu_sem1_go updatevalues 0.0 hu_sem1_mem SetVelocity 100 100 endevent +node -1 0 hu_sem1_launcher eventlauncher 0 0 0 -1 none 1042 hu_sem1_go end +// a signal at stop: what the AI reads of one, a memory cell with SetVelocity 0 0 and the event that reads it +node -1 0 hu_sem2_mem memcell -2997.3 91.00 2300.0 SetVelocity 0.0 0.0 none endmemcell +event hu_sem2_info getvalues 5.0 hu_sem2_mem endevent + +trainset {{timetable}} hu_05 0.0 0.1 +{{consist}} +endtrainset diff --git a/tests/scenarios/cases/test_mode_standing_1m_past_signal.json b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json new file mode 100644 index 000000000..4157dc52d --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_1m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 1 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "52.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/scenarios/cases/test_mode_standing_4m_past_signal.json b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json new file mode 100644 index 000000000..b0b668873 --- /dev/null +++ b/tests/scenarios/cases/test_mode_standing_4m_past_signal.json @@ -0,0 +1,16 @@ +{ + "description": "Test mode, no signal passed at danger for a train set past a signal: EU07 on td.scn standing with its head 4 m past the exit signal stacja1_j at stop (no route). Its driver finds the signal behind the head at its first look ahead, about 13 s in; a standing train passes nothing, so it isn't a signal passed at danger, and the case runs into its timeout.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_past_red_signal.scn", + "vars": { + "offset": "55.0", + "consist": "node -1 0 {{vehicle}} dynamic pkp\\4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic" + }, + "duration": 60, + "timeout": 600, + "checks": [ + { "type": "max_speed", "limit": 1 }, + { "type": "distance", "max": 1 } + ] +} diff --git a/tests/scenarios/cases/traxx_td_crew_add.json b/tests/scenarios/cases/traxx_td_crew_add.json new file mode 100644 index 000000000..9d6200a1b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_crew_add.json @@ -0,0 +1,31 @@ +{ + "description": "As eu07_td_crew_add, with a Traxx (E186, p160dc) standing ready to depart (trainset velocity 0.1) with nobody in it: its brake handle, one with a time chamber (MHZ_6P), in the holding position and the brake pipe and the control reservoir at running pressure. The AI driver put in cab A 20 s after the start gets the locomotive ready, puts the handle to running and leaves through the exit signal.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset none tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 nobody 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_put putvalues 0 none 0 0 0 Crew:{{vehicle}} 1 0 endevent", + "event autotest_crew_on multiple 20 none autotest_crew_put autotest_crew_waits endevent", + "node -1 0 autotest_crew_on_launcher eventlauncher 0 0 0 -1 none 1034 autotest_crew_on end" + ] + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "log_contains", "pattern": "Crew: \\[autotest_traxx_td_crew_add\\] an AI driver takes cab A" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "ai", "after": 15, "before": 30 }, + { "type": "starts", "min_speed": 20, "within": 240 }, + { "type": "moves", "vehicle": "{{vehicle}}", "direction": "front", "min_speed": 20 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/traxx_td_timetable.json b/tests/scenarios/cases/traxx_td_timetable.json new file mode 100644 index 000000000..51d84860b --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable.json @@ -0,0 +1,17 @@ +{ + "description": "Traxx (E186, p160dc) on td.scn, AI driver on the td/rozklad timetable: a driver's brake handle with a time chamber (MHZ_6P), for which the AI getting the locomotive ready has a rule of its own for releasing the train brake (5775493b2, #444). Starts from Stacja1, keeps to the speed limit, brakes to a stop at Przystanek.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 headdriver 0 0 enddynamic" + }, + "duration": 240, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/traxx_td_timetable_cold.json b/tests/scenarios/cases/traxx_td_timetable_cold.json new file mode 100644 index 000000000..bfdb833a2 --- /dev/null +++ b/tests/scenarios/cases/traxx_td_timetable_cold.json @@ -0,0 +1,20 @@ +{ + "description": "As traxx_td_timetable, from a cold start: the trainset stands with velocity 0, so the locomotive starts braked, its brake handle (MHZ_6P, with a time chamber) in the holding position and the brake pipe below running pressure. The driver gets the order to run as a train, starts the locomotive, puts the handle to running, charges the brake pipe and leaves on time.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_cold_timetable.scn", + "vars": { + "consist": "node -1 0 {{vehicle}} dynamic pkp/e186_v2 146_226-6 p160dc 0 headdriver 0 0 enddynamic" + }, + "track_events": { + "tdo_n1734": "event0 autotest_wake" + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "max_speed", "limit": 90, "tolerance": 3 }, + { "type": "brakes", "min_pressure": 0.5 }, + { "type": "stops", "moving_speed": 20, "stop_speed": 1.0, "hold": 0, "min_distance": 1380, "max_distance": 1420 } + ] +} diff --git a/tests/scenarios/cases/vectron_td_crew_remove.json b/tests/scenarios/cases/vectron_td_crew_remove.json new file mode 100644 index 000000000..e677b8a3a --- /dev/null +++ b/tests/scenarios/cases/vectron_td_crew_remove.json @@ -0,0 +1,27 @@ +{ + "description": "Crew event, the driver disappears (eu07/maszyna#510): as eu07_td_crew_remove, with a Vectron (induction motors, an integrated power and brake handle) which loses its AI driver on the run at 10:36, stops and stays where it stopped.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": "td_crew.scn", + "vars": { + "trainsets": [ + "trainset td/rozklad tdo_n1734 0.0 0.1", + "node -1 0 {{vehicle}} dynamic pkp\\vectron_v1 1293-107 wariant_7w 0 headdriver 0 0 enddynamic", + "endtrainset" + ], + "crew": [ + "event autotest_crew_off putvalues 0 none 0 0 0 Crew:{{vehicle}} 0 0 endevent", + "node -1 0 autotest_crew_off_launcher eventlauncher 0 0 0 -1 none 1036 autotest_crew_off end" + ] + }, + "duration": 300, + "timeout": 600, + "checks": [ + { "type": "starts", "min_speed": 20, "within": 150 }, + { "type": "log_contains", "pattern": "Crew: \\[autotest_vectron_td_crew_remove\\] the AI driver leaves" }, + { "type": "driver_changes", "vehicle": "{{vehicle}}", "to": "none", "after": 115, "before": 130 }, + { "type": "stops_driverless", "vehicle": "{{vehicle}}", "min_speed": 20, "within": 60, "hold": 100 }, + { "type": "log_lacks", "pattern": "derailed" }, + { "type": "log_lacks", "pattern": "collided" } + ] +} diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couple.scn b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn new file mode 100644 index 000000000..c0d504d57 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couple.scn @@ -0,0 +1,39 @@ +// added by tests/scenarios/run.py to wrzosy_pxe336080.scn, which keeps its own trainsets: the mission of +// eu07/maszyna#524. EU07-234 runs light from final_2t839 through the Wolica depot to the rake of 12 coaches +// pxe_1 .. pxe_12 (linia053_wrzosy/pxe336080_dekoracje.scm, "trainset none woa_odst009 304 0"), has to +// couple to it and take it out of the depot. +// +// the scenery gives the locomotive no order at all: its trainset has velocity 0, so with nobody in the cab +// its driver sleeps in Wait_for_orders, and nothing in the scenery tells it to couple, the player does that +// by hand. the two orders the player's hands stand for are given here. +// +// 1. a minute after the start (the scenery sets the way and the shunting signals at 50-55 s): shunt, as +// the signals say (Shunt -1 0). PutValues goes to the vehicle that set the event off, so it hangs on +// event0 of the track the locomotive stands on (the three its 16 m may reach); event0 comes again and +// again while it stands there, the cell lets the order through once. +// the first order is not the one to couple, on purpose: a driver whose first order is Connect never +// releases the hand brake the locomotive starts with, and pulls against it for good (CheckVehicles() +// leaves AutoRewident() out for Connect). +node -1 0 autotest_ordered memcell 0 0 0 ordered 0 0 none endmemcell +event final_2t838:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t839:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event final_2t840:event0 multiple 60 autotest_ordered autotest_order autotest_order_given condition memcompare * 0 * endevent +event autotest_order PutValues 0 none 0 0 0 Shunt -1 0 endevent +event autotest_order_given UpdateValues 0 autotest_ordered * 1 * endevent + +// 2. on the last track before the rake, in the direction the locomotive comes from (event2 of +// woa_lokom007, some 35-45 m short of the first coach): couple to the consist standing ahead with the +// coupler and the brake hose (3), turn round and wait for the shunting signal. it is the order these +// sceneries give their AI shunters (dos_sm42_przypnij). +event woa_lokom007:event2 PutValues 0 none 0 0 0 Shunt -2 -3 endevent + +// 330 s after the locomotive ran over lok_woa005 towards the rake the scenery sets the way out +// (lok_woa005:event2 -> PXE_gotowy -> pxe_manewry_ruszaj), coupled or not. it leads back over lok_woa005, +// towards its point 1. every vehicle going that way is counted (eventall1); the locomotive alone makes 1, +// so the second vehicle is a coach of the rake, coupled and pulled. the test ends there, with the train +// still moving (test.no_movement_before_pass no). +node -1 0 autotest_left memcell 0 0 0 left 0 0 none endmemcell +event lok_woa005:eventall1 multiple 0 none autotest_count autotest_judge endevent +event autotest_count AddValues 0 autotest_left * 1 0 endevent +event autotest_judge multiple 0 autotest_left autotest_pass condition memcompare * 2 * endevent +event autotest_pass UpdateValues 0 __test.result the_rake_left_the_depot_behind_the_locomotive 1 * endevent diff --git a/tests/scenarios/cases/wrzosy_pxe336080_couples.json b/tests/scenarios/cases/wrzosy_pxe336080_couples.json new file mode 100644 index 000000000..11d385871 --- /dev/null +++ b/tests/scenarios/cases/wrzosy_pxe336080_couples.json @@ -0,0 +1,26 @@ +{ + "description": "eu07/maszyna#524, Wrzosy PXE336080: EU07-234 runs light to the rake of 12 coaches in the Wolica depot, gets the order to couple (the player's hand, the scenery gives none), has to couple to the first coach and leave the depot with the rake behind it.", + "base_scenery": "wrzosy_pxe336080.scn", + "strip_trainsets": false, + "vehicle": "EU07-234", + "fragment": "wrzosy_pxe336080_couple.scn", + "slow": true, + "ini": [ + "file.binary.terrain no" + ], + "test_config": [ + "test.timeout 1800", + "test.standstill 900", + "test.fail_if_stop_overran no", + "test.no_movement_before_pass no" + ], + "expect": "pass", + "timeout": 1200, + "checks": [ + { + "type": "couples", + "vehicle": "EU07-234", + "other": "pxe_1" + } + ] +} diff --git a/tests/scenarios/make_off_track_curves.py b/tests/scenarios/make_off_track_curves.py new file mode 100644 index 000000000..447d8ddb1 --- /dev/null +++ b/tests/scenarios/make_off_track_curves.py @@ -0,0 +1,118 @@ +"""Writes the eu07_td_off_track_curve_* cases and their fragments (cases/td_off_track_curve_*.scn): a track of R 300 m +laid on its own in the fields of td.scn, on level ground, on an embankment 4 m high and in a cutting whose banks rise +4 m at 1:1.5 and on at 1:5, with an EU07 without a driver overturning on it (physics.derailment new). + + python tests/scenarios/make_off_track_curves.py +""" +import json +import math +from pathlib import Path + +CASES = str(Path(__file__).resolve().parent / "cases") + "/" +R = 300.0 +CENTRE = (-600.0, 400.0) # x, z +THETA = 0.5 # rad of the track, 150 m +RAIL = {'flat': 0.2, 'embankment': 4.2, 'cutting': 0.2} +# the cross section of the ground: (offset from the axis, height), outwards from the centre of the curve positive; +# the grass of td.scn lies at 0 around it +SECTIONS = { + 'embankment': [(-9.5, 0.0), (-3.5, 4.0), (3.5, 4.0), (9.5, 0.0)], + 'cutting': [(-150.0, 32.1), (-9.5, 4.0), (-3.5, 0.0), (3.5, 0.0), (9.5, 4.0), (150.0, 32.1)], +} +BACKSLASH = chr(92) +NEWLINE = chr(10) + + +def point(phi, offset, height): + # outwards: away from the centre of the curve + r = R + offset + return (CENTRE[0] + r * math.cos(phi), height, CENTRE[1] + r * math.sin(phi)) + + +def triangles(kind): + # a triangle strip for each band of the cross section, along the curve every 0.03 rad (9 m) + nodes = [] + section = SECTIONS[kind] + phis = [-0.3 + 0.03 * i for i in range(41)] # 90 m before the track to 120 m past it + for (o1, h1), (o2, h2) in zip(section, section[1:]): + lines = [] + for phi in phis: + for offset, height in ((o1, h1), (o2, h2)): + x, y, z = point(phi, offset, height) + lines.append(f"{x:.2f} {y:.2f} {z:.2f} 0 1 0 0 0") + nodes.append("node -1 0 none triangle_strip grass" + NEWLINE + (" end" + NEWLINE).join(lines) + NEWLINE + "endtri") + return nodes + + +def track(kind): + y = RAIL[kind] + p1 = point(0.0, 0.0, y) + p2 = point(THETA, 0.0, y) + k = 4.0 / 3.0 * math.tan(THETA / 4.0) * R + t1 = (-math.sin(0.0), math.cos(0.0)) + t2 = (-math.sin(THETA), math.cos(THETA)) + return NEWLINE.join([ + f"node -1 0 autotest_curve track normal {R * THETA:.4f} 1.435 0.15 25.0 20 0 flat vis", + " rail_screw_used1 6 1435mm/tpbps-new2 0.2 0.5 1.1", + f"{p1[0]:.4f} {y} {p1[2]:.4f} 0.0 //point 1", + f"{t1[0] * k:.4f} 0.0 {t1[1] * k:.4f} //control vector 1", + f"{-t2[0] * k:.4f} 0.0 {-t2[1] * k:.4f} //control vector 2", + f"{p2[0]:.4f} {y} {p2[2]:.4f} 0.0 //point 2", + f"{R}", + "endtrack"]) + + +WORDS = { + 'flat': ("on level ground", "the grass of td.scn", + "it slides on the grass out of the curve, falls on its side and stops"), + 'embankment': ("on an embankment 4 m high with slopes of 1:1.5", "triangles of the fragment", + "it falls on its side over the edge of the embankment, slides down its slope and on over the level ground at its foot, 4 m lower"), + 'cutting': ("in a cutting with banks of 1:1.5 4 m high, the ground rising on beyond them at 1:5", "triangles of the fragment", + "it runs into the bank on the outside of the curve, climbs it and stops sooner than on level ground"), +} +CHECKS = { + 'flat': {"min_offset": 3, "min_distance": 50, "max_distance": 250, "lying": True}, + 'embankment': {"min_offset": 5, "min_distance": 30, "max_distance": 300, "lying": True}, + 'cutting': {"min_offset": 3, "min_distance": 20, "max_distance": 230}, +} +HEADER = [ + "// added by tests/scenarios/run.py to td.scn, whose own trainsets were removed (physics.derailment new, the vehicles", + "// off the track moving on the ground, vehicle/derailmotion.h): a track of R 300 m without cant laid on its own in the", + "// fields of td.scn (autotest_curve), {where}; written by a script, see the README.", + "// an EU07 with an AI driver and no timetable stands on track 1 of Stacja1, where td.scn keeps its timetable train, so", + "// it stays put and logs its physics; the EU07 of the case has no driver and runs at {{velocity}} km/h from 20 m past", + "// point 1 of the curve towards its point 2", +] +TRAINS = [ + "trainset none tdo_n1734 0.0 0.0", + "node -1 0 {{vehicle}} dynamic pkp" + BACKSLASH + "4e_v1 4e-004 4e 0 headdriver 0 0 enddynamic", + "endtrainset", + "", + "trainset none autotest_curve 20.0 {{velocity}}", + "node -1 0 {{vehicle}}_off dynamic pkp" + BACKSLASH + "4e_v1 4e-004 4e 0 nobody 0 0 enddynamic", + "endtrainset", +] +for kind in ('flat', 'embankment', 'cutting'): + nodes = ([] if kind == 'flat' else triangles(kind)) + [track(kind)] + where, source, what = WORDS[kind] + lines = [line.replace("{where}", where) for line in HEADER] + nodes + TRAINS + with open(CASES + f"td_off_track_curve_{kind}.scn", "w", encoding="utf-8", newline=NEWLINE) as out: + out.write(NEWLINE.join(lines) + NEWLINE) + case = { + "description": f"physics.derailment new: an EU07 without a driver runs at 150 km/h into a curve of R 300 m without cant, a track of 150 m laid on its own in the fields of td.scn (autotest_curve), {where} ({source}). Over its overturning speed (about 120 km/h) it overturns out of the curve: {what}.", + "base_scenery": "td.scn", + "time": "10:34", + "fragment": f"td_off_track_curve_{kind}.scn", + "vars": {"velocity": "150"}, + "ini": ["gfxrenderer null", "physics.derailment new", "couplerphysics all"], + "expect": "timeout", + "duration": 60, + "timeout": 600, + "checks": [ + {"type": "log_contains", "pattern": "derailment: autotest_" + BACKSLASH + "S+_off leaves the track"}, + dict({"type": "leaves_track", "vehicle": "{{vehicle}}_off", "cause": "overturned"}, **CHECKS[kind]), + ], + } + with open(CASES + f"eu07_td_off_track_curve_{kind}.json", "w", encoding="utf-8", newline=NEWLINE) as out: + out.write(json.dumps(case, indent=2, ensure_ascii=False) + NEWLINE) +print("written") diff --git a/tests/scenarios/run.py b/tests/scenarios/run.py index 51fdc3c66..ad7ac5bcb 100644 --- a/tests/scenarios/run.py +++ b/tests/scenarios/run.py @@ -27,7 +27,9 @@ Usage: from __future__ import annotations import argparse +import heapq import json +import math import os import re import shutil @@ -48,7 +50,9 @@ OUT_DIR = HERE / "out" # Velocity is in km/h and pressures in bar, despite the header saying m/s and MPa. COL_TIME = 0 COL_VELOCITY = 1 # wheel speed: stays at 0 while the wheels are locked in a skid +COL_TRACTION_FORCE = 5 # N, despite the header saying kN COL_BRAKE_PRESS = 8 +COL_MASTER_CONTROLLER = 11 # the position of the master controller COL_COMMAND = 16 # text, read as None COL_WHEELSLIP = 20 COL_VEHICLE_VELOCITY = 25 # signed vehicle speed, km/h; only in builds which log it @@ -77,12 +81,14 @@ width 1280 height 720 inactivepause no soundenabled no -physicslog yes +convertmodels 0 +physicslog {physicslog} multiplelogs yes timespeed {timespeed} """ # multiplelogs: log and errors go to logs/log () .txt instead of the shared # log.txt, so runs of different cases can go in parallel +# convertmodels 0: a test run writes no converted models (.e3d) into the game dir # ---------------------------------------------------------------- scenery @@ -143,6 +149,60 @@ def scenery_cache(game_dir: Path, case_name: str) -> Path: return game_dir / "scenery" / f"autotest_{case_name}.sbt" +def timetable_name(case_name: str) -> str: + """The case's own timetable as a trainset names it: {{timetable}} in the fragment.""" + return f"autotest_{case_name}" + + +def timetable_path(game_dir: Path, case_name: str) -> Path: + return game_dir / "scenery" / f"{timetable_name(case_name)}.txt" + + +def variant_name(case_name: str, name: str) -> str: + """A vehicle variant of the case as a trainset names it: {{variant_}} in the fragment.""" + return f"autotest_{case_name}_{name}" + + +def variant_paths(game_dir: Path, case_name: str, variant: dict) -> list[Path]: + """The .fiz and .mmd of a vehicle variant of the case, beside those of the vehicle it is made from.""" + folder = (game_dir / "dynamic" / variant["from"]).parent + return [folder / f"{variant_name(case_name, variant['name'])}{suffix}" for suffix in (".fiz", ".mmd")] + + +def write_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None: + """Writes the case's vehicle variants into the game's dynamic/ dir: a copy of a vehicle's .fiz with the + case's replacements, e.g. a .fiz key the shipped data doesn't have yet, and a copy of its .mmd. The + simulator hands the .mmd its type name as (p2), which some pass on to the include that names the + model (et42_v2: `include 112e-a.mmd.inc (p2) end`, `models: (p1).t3d`), so the copy has the name of + the vehicle it is made from in place of (p2) and looks and loads as that one does.""" + files = {} + for variant in case.get("vehicle_variants", []): + source = game_dir / "dynamic" / variant["from"] + # the .fiz to copy: the vehicle's own, or another file named in full (fiz_from), e.g. the .fiz.inc a + # vehicle's .fiz only includes, as keys added after the include on a second line of the same section + # would load that section again + fiz_source = game_dir / "dynamic" / variant["fiz_from"] if "fiz_from" in variant else source.with_name(source.name + ".fiz") + fiz_name = variant.get("fiz_from", f"{variant['from']}.fiz") + # .fiz files are cp1250 like the sceneries; latin-1 round-trips every byte + fiz = fiz_source.read_bytes().decode("latin-1") + for old, new in variant.get("replace", []): + if old not in fiz: + sys.exit(f"vehicle_variants: {fiz_name} has no {old!r}") + fiz = fiz.replace(old, new) + mmd = source.with_name(source.name + ".mmd").read_bytes().decode("latin-1").replace("(p2)", source.name) + fiz_path, mmd_path = variant_paths(game_dir, case_name, variant) + files[fiz_path], files[mmd_path] = fiz, mmd + # written once every variant is made, so a case with a wrong replacement leaves nothing in the game dir + for path, text in files.items(): + path.write_bytes(text.encode("latin-1")) + + +def remove_vehicle_variants(case: dict, game_dir: Path, case_name: str) -> None: + for variant in case.get("vehicle_variants", []): + for path in variant_paths(game_dir, case_name, variant): + path.unlink(missing_ok=True) + + def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> str: """Writes the case scenery into the game's scenery dir and returns its file name.""" scenery_dir = game_dir / "scenery" @@ -156,10 +216,16 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s text = set_track_friction(text, case["track_friction"]) if "track_events" in case: text = add_track_events(text, case["track_events"]) - fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") - # vars first: {{vehicle}} inside a var's value gets filled in the second pass - fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle"}) - fragment = fill_vars(fragment, {"vehicle": vehicle}) + for old, new in case.get("replace", []): + if old not in text: + sys.exit(f"replace: the base scenery has no {old!r}") + text = text.replace(old, new) + # a case on a mission of the base scenery may have nothing to add but its test_config + fragment = (CASES_DIR / case["fragment"]).read_bytes().decode("latin-1") if "fragment" in case else "" + # vars first: {{vehicle}} and {{timetable}} inside a var's value get filled in the second pass + variants = {f"variant_{v['name']}": variant_name(case_name, v["name"]) for v in case.get("vehicle_variants", [])} + fragment = fill_vars(fragment, case.get("vars", {}), keep={"vehicle", "timetable", *variants}) + fragment = fill_vars(fragment, {"vehicle": vehicle, "timetable": timetable_name(case_name), **variants}) # FirstInit binds event launchers to their events and links the tracks. so launchers and # events of the case go in before it (read after it they never fire), trainsets after it # (placed before it they stand on unlinked track and derail at once) @@ -175,13 +241,19 @@ def build_scenery(case: dict, game_dir: Path, case_name: str, vehicle: str) -> s else: text += header + before + "\n" text += header + trainsets + "\n" + # vehicles of the case's own, made from those of the game + write_vehicle_variants(case, game_dir, case_name) name = f"autotest_{case_name}.scn" (scenery_dir / name).write_bytes(text.encode("latin-1")) + # a timetable of the case's own, for a train whose timetable the sceneries of the game have none like + if "timetable" in case: + shutil.copyfile(CASES_DIR / case["timetable"], timetable_path(game_dir, case_name)) # the simulator caches the scenery's static geometry in .sbt and reads it instead of # the terrain in the .scn (tracks, events and trainsets always come from the .scn), so - # drop the cache once the base scenery has changed + # drop the cache once the base scenery, or the fragment of the case (its own terrain), has changed cache = scenery_cache(game_dir, case_name) - if cache.exists() and cache.stat().st_mtime < (scenery_dir / case["base_scenery"]).stat().st_mtime: + sources = [scenery_dir / case["base_scenery"]] + ([CASES_DIR / case["fragment"]] if "fragment" in case else []) + if cache.exists() and cache.stat().st_mtime < max(source.stat().st_mtime for source in sources): cache.unlink() return name @@ -235,9 +307,14 @@ def read_text(path: Path | None) -> str: # physicslog/_.blackbox. A header, then records: a byte of the kind, the length, the content BLACKBOX_MAGIC = b"EU07BBX\0" BLACKBOX_HEADER = 12 # the magic, the version of the format, two bytes reserved +BLACKBOX_TRACK = 0x10 # the map: a rail track, or one way of a switch, as points along it BLACKBOX_VEHICLE = 0x12 # a vehicle: its number and its name +BLACKBOX_VEHICLES = 0x21 # once a second: the vehicles which moved, changed speed or got another driver BLACKBOX_COUPLING = 0x37 # a coupler of a vehicle coupled, uncoupled, or its hoses and cables changed +BLACKBOX_DERAILMENT = 0x38 # a vehicle left the track, or came to rest off it (physics.derailment new) +DERAILMENT_CAUSES = {1: "flange climbed", 2: "overturned", 3: "end of track", 4: "pulled off", 5: "collision"} COUPLING_COUPLER = 0x01 # of the bits telling what is coupled: the coupler itself +BLACKBOX_DRIVERS = {"none": 0, "user": 1, "ai": 2} # the driver byte of a vehicle state @dataclass @@ -253,10 +330,49 @@ class Coupling: previous_other: int +@dataclass +class VehicleState: + """A vehicle in a `vehicles` record: where it is and who drives it from `time` on, until its next one.""" + time: float + position: tuple[float, float, float] + speed: float # km/h, positive along its front + driver: int # 0 none, 1 a user, 2 the AI + + +@dataclass +class Derailment: + """A derailment record: a vehicle off the track as it left it (phase 0) or came to rest (phase 1).""" + time: float + vehicle: int + phase: int + cause: int # DERAILMENT_CAUSES + position: tuple[float, float, float] + heading: float # rad + speed: float # km/h + offset: float # m from the axis of the track, to the left of its front positive + roll: float # rad, to the left positive + travelled: float # m on the ground since it left the rails + lying: bool + + +@dataclass +class Track: + """A `track` record: a plain track, or one way of a switch (several records under the number of the switch).""" + number: int + name: str + kind: int # 0 a plain track, 1 a way of a switch + branch: int # the switch position this way is taken in + points: list[tuple[float, float, float]] + + @dataclass class Blackbox: vehicles: dict[int, str] = field(default_factory=dict) # names by number + tracks: list[Track] = field(default_factory=list) # the map, in the order written couplings: list[Coupling] = field(default_factory=list) # in the order written + derailments: list[Derailment] = field(default_factory=list) # in the order written + states: dict[int, list[VehicleState]] = field(default_factory=dict) # of each vehicle by number, in time order + end_time: float = 0.0 # of the last `vehicles` record def find_blackbox(game_dir: Path, scenery: str, since: float) -> Path | None: @@ -269,8 +385,22 @@ def find_blackbox(game_dir: Path, scenery: str, since: float) -> Path | None: return max(files, key=lambda p: p.stat().st_mtime, default=None) +def _blackbox_text(content: bytes, start: int) -> tuple[str, int]: + """A text of a black box record at `start`, and where the field after it begins.""" + # its length in 7 bit groups, low first, the high bit set on all but the last + size, shift = 0, 0 + while True: + byte = content[start] + start += 1 + size |= (byte & 0x7F) << shift + shift += 7 + if byte < 0x80: + break + return content[start: start + size].decode("utf-8", errors="replace"), start + size + + def read_blackbox(path: Path | None) -> Blackbox | None: - """The vehicles and the coupling records of a black box; None when there is none or it can't be read.""" + """The map, the vehicles and the coupling records of a black box; None when there is none or it can't be read.""" try: data = path.read_bytes() if path else b"" except FileNotFoundError: @@ -288,19 +418,29 @@ def read_blackbox(path: Path | None) -> Blackbox | None: at += 5 + length if kind == BLACKBOX_VEHICLE: number, = struct.unpack_from(" RunResult: + duration: float | None, timeout: float, watch: bool, say, expect_rows: bool = True) -> RunResult: """Runs the simulator on the scenery. In test mode it quits by itself and the exit code is the result; with watch it runs in a window and gets closed after `duration`.""" physicslog.unlink(missing_ok=True) @@ -351,7 +491,9 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog while True: time.sleep(0.25) # at timespeed 20 that is 5 s of simulation wall = time.monotonic() - started - result.rows = read_physicslog(physicslog) + # the whole file is read each time: in test mode, once there are rows, only for the progress line + if watch or not result.rows or wall - last_report >= 15: + result.rows = read_physicslog(physicslog) sim_t = result.rows[-1][COL_TIME] if result.rows else 0.0 if wall - last_report >= 15: v = result.rows[-1][COL_VELOCITY] if result.rows else 0.0 @@ -366,7 +508,10 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog if wall > timeout + (0 if watch else KILL_GRACE): result.failure = f"timed out after {wall:.0f}s before {duration}s of simulation" break - if not result.rows: + # not for a case with physicslog off, which has no rows to wait for, nor for one on a mission of the + # base scenery: a big scenery loads for minutes, and a bad vehicle among its decorations isn't the + # case's (a missing test vehicle ends the test mode with `error` by itself) + if expect_rows and not result.rows: result.logs = find_logs(game_dir, scenery, since) fatal = [l.strip() for l in read_text(result.logs.get("errors")).splitlines() if any(k in l for k in FATAL_LOG_LINES)] @@ -397,11 +542,14 @@ def run_simulator(exe: Path, game_dir: Path, scenery: str, ini: Path, physicslog # ---------------------------------------------------------------- checks -def check_starts(rows, min_speed, within): +def check_starts(rows, min_speed, within, after=None): for r in rows: if r[COL_TIME] > within: break if r[COL_VELOCITY] >= min_speed: + # a case can also say the train mustn't leave before something it waits for (a converter starting) + if after is not None and r[COL_TIME] < after: + return False, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s, before {after}s" return True, f"reached {min_speed} km/h at t={r[COL_TIME]:.1f}s" top = max((r[COL_VELOCITY] for r in rows if r[COL_TIME] <= within), default=0.0) return False, f"top speed in the first {within}s was {top:.1f} km/h, wanted {min_speed}" @@ -437,25 +585,42 @@ def check_brakes(rows, min_pressure, moving_speed=20): return False, f"brake cylinder pressure never reached {min_pressure} bar after moving off" -def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None): +def check_stops(rows, moving_speed, stop_speed, hold, min_distance=None, max_distance=None, max_time=None, nth=1): + """The nth stop of `hold` seconds after moving off at `moving_speed` (each stop after the first counts once the + train is moving at `moving_speed` again).""" start = _first_moving(rows, moving_speed) if start is None: return False, f"never reached {moving_speed} km/h" dist = _distances(rows) stopped_at = None + held = 0 + moving = True for i in range(start, len(rows)): r = rows[i] + if not moving: + moving = r[COL_VELOCITY] >= moving_speed + continue if r[COL_VELOCITY] <= stop_speed: if stopped_at is None: stopped_at = i if r[COL_TIME] - rows[stopped_at][COL_TIME] >= hold: + held += 1 + if held < nth: + stopped_at = None + moving = False + continue where = dist[stopped_at] - detail = f"came to a stop at t={rows[stopped_at][COL_TIME]:.1f}s after {where:.0f} m" + when = rows[stopped_at][COL_TIME] + detail = f"came to a stop at t={when:.1f}s after {where:.0f} m" if (min_distance is not None and where < min_distance) or (max_distance is not None and where > max_distance): return False, f"{detail}, wanted between {min_distance} and {max_distance} m" + if max_time is not None and when > max_time: + return False, f"{detail}, wanted by t={max_time}s" return True, detail else: stopped_at = None + if held: + return False, f"stopped {held} times for {hold}s after moving off, wanted stop {nth}" return False, f"did not stay below {stop_speed} km/h for {hold}s after moving off" @@ -522,6 +687,58 @@ def check_ends_moving(rows, min_speed): return ok, f"last row t={last[COL_TIME]:.1f}s, v={last[COL_VELOCITY]:.1f} km/h (wanted >= {min_speed})" +def check_keeps_moving(rows, moving_speed, min_speed, until_distance, from_distance=0.0): + """(*vehicle speed*) Once at moving_speed, the speed stays at or above min_speed between the two distances (metres + travelled, from the vehicle speed), e.g. a train doesn't come to a stand on a gradient before a restriction or in + it. The vehicle speed, as wheels slipping at the start would count as moving off.""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + speed = [abs(r[COL_VEHICLE_VELOCITY]) for r in rows] + start = next((i for i, v in enumerate(speed) if v >= moving_speed), None) + if start is None: + return False, f"never reached {moving_speed} km/h" + dist, d = [0.0], 0.0 + for i in range(1, len(rows)): + d += (speed[i - 1] + speed[i]) / 2 / 3.6 * (rows[i][COL_TIME] - rows[i - 1][COL_TIME]) + dist.append(d) + span = [i for i in range(start, len(rows)) if from_distance <= dist[i] <= until_distance] + if not span or dist[-1] < until_distance: + return False, f"travelled {dist[-1]:.0f} m only, wanted {until_distance} m" + low = min(span, key=lambda i: speed[i]) + r = rows[low] + detail = (f"lowest speed {speed[low]:.1f} km/h at t={r[COL_TIME]:.1f}s after {dist[low]:.0f} m " + f"(brake cylinder {r[COL_BRAKE_PRESS]:.2f} bar), wanted >= {min_speed} between {from_distance:.0f} and {until_distance} m") + return speed[low] >= min_speed, detail + + +def check_starts_again(rows, after, min_speed, within, max_rollback=None): + """Standing at the time `after` (e.g. at a signal that clears then), the vehicle reaches min_speed within `within` + seconds; with max_rollback (*vehicle speed*), it rolls back no more than that many metres meanwhile.""" + first = next((i for i, r in enumerate(rows) if r[COL_TIME] >= after), None) + if first is None: + return False, f"the physicslog ends before t={after}s" + if rows[first][COL_VELOCITY] > 1.0: + return False, f"moving at {rows[first][COL_VELOCITY]:.1f} km/h at t={after}s, wanted standing" + moved = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] > 1.0), None) + reached = next((r[COL_TIME] for r in rows[first:] if r[COL_VELOCITY] >= min_speed), None) + rollback, back = 0.0, 0.0 + if max_rollback is not None: + if len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column, the build is too old" + end = reached if reached is not None else after + within + for a, b in zip(rows[first:], rows[first + 1:]): + if b[COL_TIME] > end: + break + back += (a[COL_VEHICLE_VELOCITY] + b[COL_VEHICLE_VELOCITY]) / 2 / 3.6 * (b[COL_TIME] - a[COL_TIME]) + rollback = max(rollback, -back) + detail = (f"moved off (1 km/h) {moved - after:.1f}s after t={after}s" if moved is not None else f"didn't move off after t={after}s") + detail += f", {min_speed} km/h after {reached - after:.1f}s" if reached is not None else f", never reached {min_speed} km/h" + if max_rollback is not None: + detail += f", rolled back {rollback:.2f} m (wanted <= {max_rollback})" + ok = reached is not None and reached - after <= within and (max_rollback is None or rollback <= max_rollback) + return ok, detail + f" (wanted {min_speed} km/h within {within}s)" + + def check_slip_clears(rows, moving_speed, stop_speed, within): """Once the vehicle has stopped after moving off, its wheels stop slipping within `within` seconds (a vehicle left skidding on locked wheels keeps its brakes capped by the sliding adhesion).""" @@ -540,7 +757,68 @@ def check_slip_clears(rows, moving_speed, stop_speed, within): return True, f"stopped at t={rows[stop][COL_TIME]:.1f}s, no slipping after t={deadline:.1f}s" +def check_traction(rows, from_distance, to_distance, reaches=None, at_most=None, at_least=None): + """The traction force of the vehicle in kN (the physicslog has it in N, whatever its header says) while it + runs between two points of its way, in metres travelled as in `distance`: the highest there `reaches` a + force, e.g. the power taken again behind a section without voltage; it stays `at_most` a force, e.g. none + taken where there is no voltage; it stays `at_least` a force, e.g. no power lost under an insulator.""" + dist = _distances(rows) + window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance] + if not window: + return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)" + + def describe(item): + d, r = item + return f"{r[COL_TRACTION_FORCE] / 1000:.1f} kN at {d:.0f} m, t={r[COL_TIME]:.1f}s, v={r[COL_VELOCITY]:.1f} km/h" + + top = max(window, key=lambda item: item[1][COL_TRACTION_FORCE]) + low = min(window, key=lambda item: item[1][COL_TRACTION_FORCE]) + detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) " + f"the traction force was {describe(low)} at its lowest, {describe(top)} at its highest") + if reaches is not None and top[1][COL_TRACTION_FORCE] / 1000 < reaches: + return False, f"{detail}; wanted it to reach {reaches} kN" + if at_most is not None and top[1][COL_TRACTION_FORCE] / 1000 > at_most: + return False, f"{detail}; wanted at most {at_most} kN" + if at_least is not None and low[1][COL_TRACTION_FORCE] / 1000 < at_least: + return False, f"{detail}; wanted at least {at_least} kN" + return True, detail + + +def check_master_controller(rows, from_distance, to_distance, at_most): + """The master controller of the vehicle stays at or below a position while it runs between two points of its + way (metres travelled, as in `distance`), e.g. at 0 where the scenery tells the driver to coast.""" + dist = _distances(rows) + window = [(d, r) for d, r in zip(dist, rows) if from_distance <= d <= to_distance] + if not window: + return False, f"never got between {from_distance} and {to_distance} m (travelled {dist[-1] if dist else 0:.0f} m)" + d, top = max(window, key=lambda item: item[1][COL_MASTER_CONTROLLER]) + detail = (f"between {from_distance} and {to_distance} m (t={window[0][1][COL_TIME]:.1f}-{window[-1][1][COL_TIME]:.1f}s) " + f"the master controller was at {top[COL_MASTER_CONTROLLER]:.0f} at most, at {d:.0f} m, t={top[COL_TIME]:.1f}s") + if top[COL_MASTER_CONTROLLER] > at_most: + return False, f"{detail}; wanted at most {at_most}" + return True, detail + + +def check_traction_power(rows, max_kw, min_peak_kw=None): + """The power at the wheels, the traction force times the vehicle speed, stays at or below max_kw + and, given min_peak_kw, reaches it, e.g. a dual-mode vehicle on its genset (eu07/maszyna#536).""" + if not rows or len(rows[0]) <= COL_VEHICLE_VELOCITY or rows[0][COL_VEHICLE_VELOCITY] is None: + return False, "the physicslog has no vehicle speed column" + power = [abs(r[COL_TRACTION_FORCE]) * abs(r[COL_VEHICLE_VELOCITY]) / 3.6 / 1000 for r in rows] + peak = max(range(len(rows)), key=power.__getitem__) + r = rows[peak] + detail = (f"peak {power[peak]:.0f} kW at t={r[COL_TIME]:.1f}s, v={r[COL_VEHICLE_VELOCITY]:.1f} km/h, " + f"Ft={r[COL_TRACTION_FORCE] / 1000:.1f} kN") + if power[peak] > max_kw: + return False, f"{detail}, above {max_kw} kW" + if min_peak_kw is not None and power[peak] < min_peak_kw: + return False, f"{detail}, below {min_peak_kw} kW" + return True, detail + + CHECKS = { + "master_controller": check_master_controller, + "traction": check_traction, "slips": check_slips, "slip_clears": check_slip_clears, "holds_still": check_holds_still, @@ -551,6 +829,9 @@ CHECKS = { "stays_stopped": check_stays_stopped, "distance": check_distance, "ends_moving": check_ends_moving, + "traction_power": check_traction_power, + "keeps_moving": check_keeps_moving, + "starts_again": check_starts_again, } @@ -571,19 +852,46 @@ def check_log_lacks(log, pattern): # checks on the text of the run's log.txt rather than on the physicslog rows +OVERLAP_LINE = re.compile(r"derailment: the bodies overlap by up to ([\d.]+) m(?: \((.*?)\))? over the last second, " + r"([\d.]+) m now(, all at rest)?") + + +def check_no_overlap(log, max_transient, max_at_rest): + """physics.derailment new: the bodies of the vehicles off the track (and of those near them) don't go into each + other: the log has the most they overlapped by every second; at most `max_transient` m at any time, and at most + `max_at_rest` m once all of them came to rest.""" + lines = [m for m in (OVERLAP_LINE.search(line) for line in log.splitlines()) if m] + if not lines: + return False, "no line of the overlap of the bodies in the log" + worst = max(lines, key=lambda m: float(m.group(1))) + rest = next((m for m in reversed(lines) if m.group(4)), None) + detail = f"most {float(worst.group(1)):.2f} m" + (f" ({worst.group(2)})" if worst.group(2) else "") + if rest is None: + return False, detail + ", the vehicles never all came to rest" + detail += f", {float(rest.group(3)):.2f} m at rest" + failed = [] + if float(worst.group(1)) > max_transient: + failed.append(f"over {max_transient} m on the way") + if float(rest.group(3)) > max_at_rest: + failed.append(f"over {max_at_rest} m at rest") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + LOG_CHECKS = { "log_contains": check_log_contains, "log_lacks": check_log_lacks, + "no_overlap": check_no_overlap, } def check_couples(box, vehicle, other): """The two vehicles couple in the run and stay coupled to its end; coupled from the start doesn't count.""" - numbers = {name: number for number, name in box.vehicles.items()} - unknown = [name for name in (vehicle, other) if name not in numbers] + # the simulator reads the names of a scenery in lower case, whatever the scenery (or the case) writes + numbers = {name.lower(): number for number, name in box.vehicles.items()} + unknown = [name for name in (vehicle, other) if name.lower() not in numbers] if unknown: return False, f"the black box has no vehicle {' nor '.join(unknown)}" - pair = {numbers[vehicle], numbers[other]} + pair = {numbers[vehicle.lower()], numbers[other.lower()]} # of the two vehicles of a coupling the one with the lower number tells it, each change of that coupler # under the same vehicle and side: the record which coupled the two, for as long as they stay coupled made, parted = {}, None @@ -605,9 +913,353 @@ def check_couples(box, vehicle, other): f"{ends[c.other_side]} one of {box.vehicles[c.other]}, coupling 0x{c.flags:02X}") +def check_parts(box, vehicle, other, before=None): + """The two vehicles, coupled to each other, come apart in the run: a coupler broken, or uncoupled.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + unknown = [name for name in (vehicle, other) if name.lower() not in numbers] + if unknown: + return False, f"the black box has no vehicle {' nor '.join(unknown)}" + pair = {numbers[vehicle.lower()], numbers[other.lower()]} + # the record of the coupler which let go: coupled to the other vehicle before, the coupler itself no more + c = next((c for c in box.couplings if {c.vehicle, c.previous_other} == pair + and c.previous_flags & COUPLING_COUPLER and not c.flags & COUPLING_COUPLER), None) + if c is None: + return False, f"none of the {len(box.couplings)} coupling record(s) of the black box parts {vehicle} and {other}" + if before is not None and c.time > before: + return False, f"{vehicle} and {other} came apart at t={c.time:.1f}s, after {before:g}s" + ends = ("front", "rear") + return True, (f"at t={c.time:.1f}s the {ends[c.side]} coupler of {box.vehicles[c.vehicle]} let go of " + f"{box.vehicles[c.previous_other]}, coupling 0x{c.previous_flags:02X} before") + + +def _vehicle_states(box, vehicle): + """The states of the vehicle named, or None and why not.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + number = numbers.get(vehicle.lower()) + if number is None: + return None, f"the black box has no vehicle {vehicle}" + states = box.states.get(number) + if not states: + return None, f"the black box has no state of {vehicle}" + return states, "" + + +def _driver_change(states, to): + """The first state with the driver `to` after one with another driver; None when there is none.""" + return next((now for before, now in zip(states, states[1:]) if now.driver == to and before.driver != to), None) + + +def check_driver_changes(box, vehicle, to, after=0.0, before=None): + """The vehicle gets the driver `to` (none, ai, user) between the times given, and keeps it to the end.""" + states, why = _vehicle_states(box, vehicle) + if states is None: + return False, why + wanted = BLACKBOX_DRIVERS[to] + names = {number: name for name, number in BLACKBOX_DRIVERS.items()} + change = _driver_change(states, wanted) + if change is None: + return False, f"{vehicle} starts with driver {names.get(states[0].driver)} and never changes to {to}" + if change.time < after or (before is not None and change.time > before): + return False, f"{vehicle} got driver {to} at t={change.time:.1f}s, outside {after:g}..{before if before is not None else 'end'}" + later = next((s for s in states if s.time > change.time and s.driver != wanted), None) + if later is not None: + return False, f"{vehicle} got driver {to} at t={change.time:.1f}s but {names.get(later.driver)} at t={later.time:.1f}s" + return True, f"{vehicle} has driver {to} from t={change.time:.1f}s to the end (t={box.end_time:.1f}s)" + + +def check_stops_driverless(box, vehicle, min_speed, within, stop_speed=0.5, max_creep=1.0, hold=60.0, + min_deceleration=None, max_deceleration=None): + """The vehicle loses its driver at `min_speed` or faster, stands `within` seconds later and stays where it + stopped, to the end of the recording or until it gets a driver again. With the decelerations, the mean one of + that stop (from the speed and the way to the stop, m/s²) has to be within them: how well the train brakes.""" + states, why = _vehicle_states(box, vehicle) + if states is None: + return False, why + left = _driver_change(states, BLACKBOX_DRIVERS["none"]) + if left is None: + return False, f"{vehicle} never loses its driver" + if abs(left.speed) < min_speed: + return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, below {min_speed}" + after = [s for s in states if s.time >= left.time] + stop = next((s for s in after if abs(s.speed) <= stop_speed), None) + if stop is None or stop.time - left.time > within: + took = "never" if stop is None else f"after {stop.time - left.time:.0f}s" + return False, f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h and stood {took} (limit {within}s)" + # left alone until the recording ends, or a driver comes again + crewed = next((s for s in after if s.time > stop.time and s.driver != BLACKBOX_DRIVERS["none"]), None) + until = crewed.time if crewed else box.end_time + alone = "until a driver came" if crewed else "to the end" + if until - stop.time < hold: + return False, f"{vehicle} stood at t={stop.time:.1f}s, with no driver for {until - stop.time:.0f}s more {alone} (hold {hold}s)" + # a standing vehicle is listed again only in the keyframes, or when it moves + standing = [s for s in after if stop.time <= s.time <= until] + fastest = max(abs(s.speed) for s in standing) + creep = max(math.dist(s.position, stop.position) for s in standing) + if fastest > stop_speed or creep > max_creep: + return False, f"{vehicle} stood at t={stop.time:.1f}s, then moved {creep:.1f} m at up to {fastest:.1f} km/h with no driver" + way = sum(math.dist(a.position, b.position) for a, b in zip(after, after[1:]) if b.time <= stop.time) + stopped = (f"{vehicle} lost its driver at t={left.time:.1f}s at {abs(left.speed):.1f} km/h, stood {stop.time - left.time:.0f}s " + f"and {way:.0f} m later") + # v² / 2s: the black box lists a vehicle once a second, so the way is closer to the truth than the time + deceleration = (abs(left.speed) / 3.6) ** 2 / (2 * way) if way > 0 else math.inf + if ((min_deceleration is not None and deceleration < min_deceleration) + or (max_deceleration is not None and deceleration > max_deceleration)): + bounds = f"{min_deceleration if min_deceleration is not None else 0:g}..{max_deceleration if max_deceleration is not None else 'any'}" + return False, f"{stopped}: a mean deceleration of {deceleration:.2f} m/s², outside {bounds}" + return True, f"{stopped} ({deceleration:.2f} m/s²), moved {creep:.2f} m in the {until - stop.time:.0f}s {alone}" + + +def check_moves(box, vehicle, min_speed, direction="front"): + """The vehicle reaches `min_speed` with its front end leading, or its rear one (the physicslog has no direction).""" + states, why = _vehicle_states(box, vehicle) + if states is None: + return False, why + sign = {"front": 1.0, "rear": -1.0}[direction] + fastest = max(states, key=lambda s: sign * s.speed) + if sign * fastest.speed < min_speed: + return False, f"{vehicle} never reaches {min_speed} km/h {direction} end leading, at most {sign * fastest.speed:.1f}" + first = next(s for s in states if sign * s.speed >= min_speed) + return True, f"{vehicle} runs {direction} end leading: {min_speed} km/h at t={first.time:.1f}s, up to {sign * fastest.speed:.1f} km/h" + + +def check_leaves_track(box, vehicle, cause=None, min_offset=None, max_offset=None, min_distance=None, max_distance=None, + lying=None): + """The vehicle leaves the track (physics.derailment new) and comes to rest off it: what derailed it, how far from + the axis of the track (either side) and how far it went on the ground, and whether it ends on its side.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + number = numbers.get(vehicle.lower()) + if number is None: + return False, f"the black box has no vehicle {vehicle}" + records = [d for d in box.derailments if d.vehicle == number] + left = next((d for d in records if d.phase == 0), None) + if left is None: + return False, f"{vehicle} never left the track ({len(box.derailments)} derailment record(s) of others)" + rest = next((d for d in records if d.phase == 1 and d.time >= left.time), None) + detail = (f"{vehicle} left the track at t={left.time:.1f}s at {abs(left.speed):.0f} km/h " + f"({DERAILMENT_CAUSES.get(left.cause, left.cause)})") + if rest is None: + return False, detail + ", and never came to rest" + detail += (f", came to rest at t={rest.time:.1f}s {rest.travelled:.1f} m on, {rest.offset:+.1f} m from the axis of the " + f"track, roll {math.degrees(rest.roll):+.0f} deg{', on its side' if rest.lying else ''}") + failed = [] + if cause is not None and DERAILMENT_CAUSES.get(left.cause) != cause: + failed.append(f"derailed by {DERAILMENT_CAUSES.get(left.cause, left.cause)}, wanted {cause}") + if min_offset is not None and abs(rest.offset) < min_offset: + failed.append(f"offset under {min_offset} m") + if max_offset is not None and abs(rest.offset) > max_offset: + failed.append(f"offset over {max_offset} m") + if min_distance is not None and rest.travelled < min_distance: + failed.append(f"went under {min_distance} m") + if max_distance is not None and rest.travelled > max_distance: + failed.append(f"went over {max_distance} m") + if lying is not None and rest.lying != lying: + failed.append("lying on its side" if rest.lying else "upright") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + +def check_consist_folds(box, vehicles, min_bend, min_folds=1, alternate=False, both_sides=False): + """The vehicles of a train (names, front to back, comma separated) left the track (physics.derailment new) and came + to rest folded up: at least `min_folds` of the bends between neighbours at rest (the angle between their headings, + either way along) are `min_bend` degrees or more; with `alternate` the bends of neighbouring joints turn opposite + ways, a zigzag; with `both_sides` some of them rest on one side of the track and some on the other.""" + numbers = {name.lower(): number for number, name in box.vehicles.items()} + names = [name.strip() for name in vehicles.split(",") if name.strip()] + rests = [] + for name in names: + number = numbers.get(name.lower()) + rests.append(next((d for d in box.derailments if number is not None and d.vehicle == number and d.phase == 1), None)) + if all(rest is None for rest in rests): + return False, f"none of {', '.join(names)} came to rest off the track" + bends = [] + for first, second in zip(rests, rests[1:]): + if first is None or second is None: + bends.append(None) + continue + # either way along: a vehicle turned about in the train has its heading the other way + bends.append(math.degrees(math.remainder(math.remainder(second.heading - first.heading, 2 * math.pi), math.pi))) + folds = [bend for bend in bends if bend is not None and abs(bend) >= min_bend] + sides = {1 if rest.offset > 0 else -1 for rest in rests if rest is not None and abs(rest.offset) > 0.5} + detail = "at rest: " + "; ".join( + f"{name} " + ("on the track" if rest is None else + f"{rest.travelled:.0f} m on, {rest.offset:+.1f} m, heading {math.degrees(rest.heading):+.0f} deg") + for name, rest in zip(names, rests)) + detail += "; bends " + ", ".join("-" if bend is None else f"{bend:+.0f}" for bend in bends) + " deg" + failed = [] + if len(folds) < min_folds: + failed.append(f"{len(folds)} bend(s) of {min_bend} deg or more, wanted {min_folds}") + if alternate: + pairs = [(a, b) for a, b in zip(bends, bends[1:]) if a is not None and b is not None + and abs(a) >= min_bend and abs(b) >= min_bend] + if not pairs or any(a * b > 0 for a, b in pairs): + failed.append("the bends don't alternate") + if both_sides and len(sides) < 2: + failed.append("all on one side of the track") + return not failed, detail + ("" if not failed else ": " + "; ".join(failed)) + + +def _along_track(track, x, z): + """Where the point (x, z) lies by the track: its level distance [m] from the line of the track, and how far along + the track [m] from its first point that nearest point of the line is.""" + best, at, run_length = math.inf, 0.0, 0.0 + if len(track.points) == 1: + return math.hypot(x - track.points[0][0], z - track.points[0][2]), 0.0 + for (ax, _, az), (bx, _, bz) in zip(track.points, track.points[1:]): + dx, dz = bx - ax, bz - az + length = dx * dx + dz * dz + share = 0.0 if length == 0.0 else max(0.0, min(1.0, ((x - ax) * dx + (z - az) * dz) / length)) + offset = math.hypot(x - (ax + share * dx), z - (az + share * dz)) + if offset < best: + best, at = offset, run_length + share * math.sqrt(length) + run_length += math.sqrt(length) + return best, at + + +def _track_length(track): + return sum(math.hypot(b[0] - a[0], b[2] - a[2]) for a, b in zip(track.points, track.points[1:])) + + +def _track_label(track): + return f"{track.name or '#' + str(track.number)}" + (f" (way {track.branch})" if track.kind == 1 else "") + + +class _TrackMap: + """The tracks of a black box as a network: the ends of the tracks (and of the ways of the switches) that meet are + one node, each track an edge of its length between its two ends.""" + + JOINT = 0.3 # ends closer than this [m], level, meet + + def __init__(self, tracks): + self.tracks = tracks + self.lengths = [_track_length(t) for t in tracks] + nodes = [] # (x, z) of each node + self.ends = [] # the nodes of the first and the last point of each track + for track in tracks: + pair = [] + for x, _, z in (track.points[0], track.points[-1]): + node = next((i for i, (nx, nz) in enumerate(nodes) if math.hypot(nx - x, nz - z) < self.JOINT), None) + if node is None: + nodes.append((x, z)) + node = len(nodes) - 1 + pair.append(node) + self.ends.append(tuple(pair)) + self.edges = {} # node: [(other node, length)] + for (a, b), length in zip(self.ends, self.lengths): + self.edges.setdefault(a, []).append((b, length)) + self.edges.setdefault(b, []).append((a, length)) + + def places(self, position, max_offset): + """The tracks the position lies on: within max_offset [m] of their line, (track index, offset, along).""" + x, _, z = position + found = [(i, *_along_track(t, x, z)) for i, t in enumerate(self.tracks)] + near = [f for f in found if f[1] <= max_offset] + return near or [min(found, key=lambda f: f[1])] + + def distance(self, one, other, limit): + """The shortest way [m] along the tracks between two places (track index, offset, along), up to `limit` + (beyond it, infinity).""" + (i, _, s), (j, _, t) = one, other + if i == j: + return abs(s - t) + start = {self.ends[i][0]: s, self.ends[i][1]: self.lengths[i] - s} + goal = {self.ends[j][0]: t, self.ends[j][1]: self.lengths[j] - t} + reached = dict(start) + queue = [(cost, node) for node, cost in start.items()] + heapq.heapify(queue) + best = math.inf + while queue: + cost, node = heapq.heappop(queue) + if cost > reached.get(node, math.inf) or cost >= min(best, limit): + continue + if node in goal: + best = min(best, cost + goal[node]) + for nxt, length in self.edges.get(node, []): + if cost + length < reached.get(nxt, math.inf): + reached[nxt] = cost + length + heapq.heappush(queue, (cost + length, nxt)) + return best if best <= limit else math.inf + + +def _coupled_pairs(box, chosen, upto): + """The pairs of vehicles (by number) among `chosen` whose couplers hold each other at the time `upto`.""" + held = {} + for c in box.couplings: + if c.time > upto: + break + held[(c.vehicle, c.side)] = (c.other, c.flags) + return {tuple(sorted((vehicle, other))) for (vehicle, _), (other, flags) in held.items() + if flags & COUPLING_COUPLER and vehicle in chosen and other in chosen} + + +def check_on_track(box, vehicles, max_offset=0.75, max_detour=5.0): + """Every vehicle whose name starts with `vehicles` stays on the line of a track in every state the black box has of + it, and the vehicles coupled to each other stay on one way: the way along the tracks from one to the other is no + more than `max_detour` [m] longer than the straight line between them. A vehicle thrown sideways has its middle off + any track; one with its bogies on two tracks that part too, once they are apart; and a train whose vehicles went + two ways at a switch runs on with two coupled vehicles on two tracks, side by side, with the way between them back + through the switch.""" + if not box.tracks: + return False, "the black box has no map of the tracks" + chosen = {number: name for number, name in box.vehicles.items() if name.lower().startswith(vehicles.lower())} + if not chosen: + return False, f"the black box has no vehicle named {vehicles}..." + network = _TrackMap(box.tracks) + # the states of the chosen vehicles by time: a vehicle is listed when it moved, or every 60 s + times = sorted({s.time for number in chosen for s in box.states.get(number, [])}) + if not times: + return False, f"the black box has no state of {', '.join(chosen.values())}" + latest, index, places = {}, {number: 0 for number in chosen}, {} + worst_offset, worst_detour, failures = None, None, [] + for when in times: + for number in chosen: + states = box.states.get(number, []) + while index[number] < len(states) and states[index[number]].time <= when: + latest[number] = states[index[number]] + index[number] += 1 + for number, state in latest.items(): + if (number, state.time) in places: + continue + places[(number, state.time)] = network.places(state.position, max_offset) + nearest = min(places[(number, state.time)], key=lambda p: p[1]) + if worst_offset is None or nearest[1] > worst_offset[0]: + worst_offset = (nearest[1], chosen[number], state, box.tracks[nearest[0]]) + for one, other in _coupled_pairs(box, chosen, when): + if one not in latest or other not in latest: + continue + straight = math.dist(latest[one].position, latest[other].position) + at_one, at_other = places[(one, latest[one].time)], places[(other, latest[other].time)] + way = min(network.distance(a, b, straight + 1000.0) for a in at_one for b in at_other) + detour = way - straight + if worst_detour is None or detour > worst_detour[0]: + worst_detour = (detour, chosen[one], chosen[other], when, at_one, at_other) + offset, name, state, track = worst_offset + where = f"{name} at t={state.time:.1f}s ({abs(state.speed):.1f} km/h) {offset:.2f} m off {_track_label(track)}" + if offset > max_offset: + failures.append(f"{where}, more than {max_offset} m") + detail = f"the farthest off a track {where}" + if worst_detour is not None: + detour, one, other, when, at_one, at_other = worst_detour + tracks = (f"{_track_label(box.tracks[min(at_one, key=lambda p: p[1])[0]])} and " + f"{_track_label(box.tracks[min(at_other, key=lambda p: p[1])[0]])}") + length = "no way along the tracks" if math.isinf(detour) else f"the way along the tracks {detour:.1f} m longer than the straight line" + said = f"{one} and {other}, coupled, at t={when:.1f}s on {tracks}: {length}" + if detour > max_detour: + failures.append(f"{said}, more than {max_detour} m") + detail += f"; of the coupled ones {said}" + if failures: + return False, "; ".join(failures) + return True, f"{len(chosen)} vehicle(s), {detail}" + + # checks on the black box of the run rather than on the physicslog rows BLACKBOX_CHECKS = { + "leaves_track": check_leaves_track, + "consist_folds": check_consist_folds, "couples": check_couples, + "parts": check_parts, + "driver_changes": check_driver_changes, + "stops_driverless": check_stops_driverless, + "moves": check_moves, + "on_track": check_on_track, } @@ -637,22 +1289,49 @@ def describe_exit(code: int | None) -> str: return f"{code} ({name})" if name else f"{code} (0x{code & 0xFFFFFFFF:08X}, a crash?)" -def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say) -> bool: - case = json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) +def load_case(name: str) -> dict: + return json.loads((CASES_DIR / f"{name}.json").read_text(encoding="utf-8")) + + +def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, seed: str | None = None) -> str: + """Runs the case and returns PASS or FAIL; for a case marked `xfail` (a known, reported bug) XFAIL + when it fails as expected, and XPASS when it passes, which means the mark has to go.""" + case = load_case(name) + ok = _run_case(name, case, exe, game_dir, timespeed, watch, say, seed) + if "xfail" not in case or watch: + return "PASS" if ok else "FAIL" + if ok: + say(f" XPASS the case passes although it is marked xfail ({case['xfail']}): remove the mark") + return "XPASS" + say(f" XFAIL fails as expected: {case['xfail']}") + return "XFAIL" + + +def exclusive_case(case: dict) -> bool: + """A case on a mission of the base scenery with the physicslog on: it removes every physicslog written + while it ran, those of other cases running at the time too, so it has to run alone.""" + return "vehicle" in case and case.get("physicslog", True) + + +def _run_case(name: str, case: dict, exe: Path, game_dir: Path, timespeed: float, watch: bool, say, + seed: str | None = None) -> bool: say(f"\n=== {name}: {case.get('description', '')}") out = OUT_DIR / name shutil.rmtree(out, ignore_errors=True) out.mkdir(parents=True) - # the lead vehicle is named after the case, so parallel runs never share a physicslog - vehicle = f"autotest_{name}" - scenery = build_scenery(case, game_dir, name, vehicle) - ini = out / "autotest.ini" - # the case's own settings go last, over the common ones - ini.write_text(TEST_INI.format(timespeed=timespeed) + "".join(line + "\n" for line in case.get("ini", [])), - encoding="ascii") - physicslog = game_dir / "physicslog" / f"{vehicle}.dat" - + # the lead vehicle is named after the case, so parallel runs never share a physicslog. a case on a + # mission of the base scenery (strip_trainsets false) names one of the scenery's own vehicles instead + own_vehicle = "vehicle" in case + vehicle = case.get("vehicle", f"autotest_{name}") + # a long run on a scenery with dozens of AI trains would write a physicslog for each of them into the + # game dir (3-4 kB per second of simulation and train); such a case turns them off and relies on the + # result of the test mode and on the log + with_physicslog = case.get("physicslog", True) + needs_physicslog = [c["type"] for c in case.get("checks", []) if c["type"] not in LOG_CHECKS] + if not with_physicslog and (watch or needs_physicslog): + sys.exit(f"{name}: with physicslog off a case can have log checks only ({', '.join(LOG_CHECKS)}), " + "and can't run with --watch") duration = float(case["duration"]) if "duration" in case else None # a case that only records `duration` seconds ends on the test timeout; one that says # how the test ends (a pass event, a signal passed at danger...) expects that result @@ -661,8 +1340,27 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool sys.exit(f"{name}: expect must be one of {', '.join(RESULTS)}") if watch and duration is None: sys.exit(f"{name}: --watch needs a case with duration") - result = run_simulator(exe, game_dir, scenery, ini, physicslog, - duration, float(case.get("timeout", 600)), watch, say) + + ini = out / "autotest.ini" + # the case's own settings go last, over the common ones; then the seed of this run of the suite, if any + settings = [*case.get("ini", []), *([f"randomseed {seed}"] if seed else [])] + ini.write_text(TEST_INI.format(timespeed=timespeed, physicslog="yes" if with_physicslog else "no") + + "".join(line + "\n" for line in settings), encoding="ascii") + physicslog = game_dir / "physicslog" / f"{vehicle}.dat" + started = time.time() - 1 + # from here on the case has files of its own in the game dir (the vehicle variants, the timetable) + try: + scenery = build_scenery(case, game_dir, name, vehicle) + result = run_simulator(exe, game_dir, scenery, ini, physicslog, + duration, float(case.get("timeout", 600)), watch, say, + expect_rows=with_physicslog and not own_vehicle) + finally: + # the case's own files go from the game dir also when the run is broken off (ctrl+c) + timetable_path(game_dir, name).unlink(missing_ok=True) + remove_vehicle_variants(case, game_dir, name) + # a case that asked for no geometry cache (file.binary.terrain no) leaves none of an earlier run behind + if any(line.split()[:2] == ["file.binary.terrain", "no"] for line in case.get("ini", [])): + scenery_cache(game_dir, name).unlink(missing_ok=True) # the logs are ours alone (named after the case scenery), move them out of the game dir for kind, path in result.logs.items(): @@ -672,6 +1370,17 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool # other trains of the case with a driver, named _, log too for other in physicslog.parent.glob(f"*_{vehicle}.dat"): shutil.move(other, out / other.name) + # on a mission of the base scenery every train with a driver logs under its own name, the road vehicles + # too (250 files and 740 MB after 900 s of Wrzosy): the ones written in this run are removed, nothing + # checks them (so such a case can't share the game dir with another run at the time: main() runs it + # alone, see exclusive_case()). a file still held open by another simulator is left where it is + if own_vehicle and with_physicslog: + for other in physicslog.parent.glob("*.dat"): + try: + if other.stat().st_mtime >= started: + other.unlink() + except OSError as error: + say(f" left {other.name} in the game dir: {error}") # the black box is named after the case scenery too if result.blackbox: result.blackbox = Path(shutil.move(result.blackbox, out / f"{vehicle}.blackbox")) @@ -694,14 +1403,17 @@ def run_case(name: str, exe: Path, game_dir: Path, timespeed: float, watch: bool say(f" {'PASS' if passed else 'FAIL'} exit code {describe_exit(result.exit_code)}{watchdog}, expected {expect}") ok &= passed # a run cut short (the real time watchdog, an error, a crash, or closed by us) could have been writing - # the scenery's geometry cache; the simulator checks only the header of it, so the next runs would read - # a truncated one. it is written again on the next run + # the scenery's geometry cache. the simulator writes it through .sbt.tmp and turns down a cut-short + # one, but older builds wrote it in place and checked only its header, so the next runs would read a + # truncated one. either is written again on the next run if result.failure or (not watch and got in (None, "error", WALL_TIMEOUT)): - scenery_cache(game_dir, name).unlink(missing_ok=True) + cache = scenery_cache(game_dir, name) + cache.unlink(missing_ok=True) + cache.with_name(cache.name + ".tmp").unlink(missing_ok=True) if result.failure: say(f" FAIL {result.failure}") ok = False - if not result.rows and case.get("checks"): + if not result.rows and needs_physicslog: if not result.failure: say(f" FAIL no physicslog for '{vehicle}'") return False @@ -751,6 +1463,10 @@ def main() -> int: help="with --watch: simulation time multiplier, the simulator offers 1, 5, 20 and 60 (default 1)") ap.add_argument("-j", "--jobs", type=int, default=1, help="cases run at once, each in a simulator of its own (default 1)") + ap.add_argument("--seed", help="seed of the simulator's random numbers for this run (randomseed), a number or a " + "word; the default is the fixed one of the test mode. For bugs that show up only sometimes") + ap.add_argument("--slow", action="store_true", + help="with no cases named: run the ones marked slow too (they are skipped otherwise)") args = ap.parse_args() if not args.game_dir: @@ -763,6 +1479,12 @@ def main() -> int: missing = [n for n in names if not (CASES_DIR / f"{n}.json").exists()] if missing: sys.exit("no such case: " + ", ".join(missing)) + # a case marked slow (a whole mission on a big scenery, many minutes) runs when named, or with --slow + if not args.cases and not args.slow: + slow = [n for n in names if load_case(n).get("slow")] + if slow: + names = [n for n in names if n not in slow] + print(f"skipped {len(slow)} slow case(s), run them by name or with --slow: {', '.join(slow)}") started = time.monotonic() results = {} @@ -770,28 +1492,38 @@ def main() -> int: def say(line, progress=False): print(line, flush=True) for n in names: - results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say) + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) else: + # a case on a mission of the base scenery removes the physicslogs written while it ran, so it runs + # alone, after the others + alone = [n for n in names if exclusive_case(load_case(n))] + together = [n for n in names if n not in alone] + if alone: + print(f"run alone after the others, they clear the physicslogs of the game dir: {', '.join(alone)}") # each case prints its block when it is done, so parallel output does not interleave def job(n): lines = [] def say(line, progress=False): if not progress: lines.append(line) - ok = run_case(n, exe, game_dir, args.timespeed, args.watch, say) - return n, ok, lines + status = run_case(n, exe, game_dir, args.timespeed, args.watch, say, args.seed) + return n, status, lines with ThreadPoolExecutor(max_workers=args.jobs) as pool: - for n in names: + for n in together: print(f"started {n}", flush=True) - for fut in as_completed([pool.submit(job, n) for n in names]): - n, ok, lines = fut.result() + for fut in as_completed([pool.submit(job, n) for n in together]): + n, status, lines = fut.result() print("\n".join(lines), flush=True) - results[n] = ok + results[n] = status + for n in alone: + results[n] = run_case(n, exe, game_dir, args.timespeed, args.watch, + lambda line, progress=False: print(line, flush=True), args.seed) print(f"\n=== summary ({time.monotonic() - started:.0f}s)") for n in names: - print(f" {'PASS' if results[n] else 'FAIL'} {n}") - return 0 if all(results.values()) else 1 + print(f" {results[n]:5} {n}") + # a known failure keeps the suite green; one that stopped failing doesn't, so that its mark gets removed + return 0 if all(status in ("PASS", "XFAIL") for status in results.values()) else 1 if __name__ == "__main__": diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index b8e324e3b..44684b79b 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -38,14 +38,30 @@ add_executable(${UNIT_TESTS_NAME} "${CMAKE_SOURCE_DIR}/rendering/common/freecameramotion.cpp" # and the http client the editor fetches its aids with "${CMAKE_SOURCE_DIR}/editor/editorHttp.cpp" + "${CMAKE_SOURCE_DIR}/utilities/asciiname.cpp" + # and what the switch tool tells of the drives of the switches + "${CMAKE_SOURCE_DIR}/editor/editorSwitchDrives.cpp" + # the camera, for the order of its rotations (test_camera.cpp) + "${CMAKE_SOURCE_DIR}/vehicle/Camera.cpp" ${UNIT_TEST_CASES}) # the core library brings the game's build settings along target_link_libraries(${UNIT_TESTS_NAME} PRIVATE eu07_core) + +# a precompiled header, as the game has: the system and library headers of stdafx.h and doctest are parsed once, not +# again in each of the files. the vehicle physics stays out of it, its unscoped enums (end::front...) would clash with +# the names of the tests. main.cpp defines the implementation of doctest before it includes doctest.h, so it goes without +if(USE_PCH) + target_precompile_headers(${UNIT_TESTS_NAME} PRIVATE + "$<$:${CMAKE_SOURCE_DIR}/stdafx.h>" + "$<$:${CMAKE_SOURCE_DIR}/ref/doctest/doctest.h>") + set_source_files_properties(main.cpp PROPERTIES SKIP_PRECOMPILE_HEADERS TRUE) +endif() + # the script screen host, tested with the real runtimes (test_script_screen_host.cpp) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/scriptscreens.cpp") if (WITH_LUA) - target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") + target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/luaprogram.cpp" "${CMAKE_SOURCE_DIR}/scripting/luasandbox.cpp" "${CMAKE_SOURCE_DIR}/stb/stb_image.c") endif() if (WITH_WASM) target_sources(${UNIT_TESTS_NAME} PRIVATE "${CMAKE_SOURCE_DIR}/scripting/wasmprogram.cpp") diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 5e2c55696..74eacedcd 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -1,6 +1,6 @@ # Coverage of the simulation core by the unit tests -These tests characterise the physics of the vehicles (`McZapkie/Mover.cpp`, `hamulce.cpp`, `Oerlikon_ESt.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: +These tests characterise the physics of the vehicles (`physics/components/*.cpp`, once `Mover.cpp`; `physics/brakes.cpp`, `oerlikonest.cpp`, `friction.cpp`). They exist to show that refactors of those files, such as splitting `TractionForce` or `RunCommand`, leave the behaviour as it was. This page lists: - what the tests reach; - what nothing in the game ever runs; @@ -14,9 +14,9 @@ Coverage was measured on Windows with MSVC's SanitizerCoverage (`/fsanitize-cove | File | Blocks run, at the start | Now | |---|---|---| -| `Mover.cpp` | 8.9% | 80.7% (3323 of 4118) | -| `hamulce.cpp` | 30% | 76.3% (649 of 851) | -| `Oerlikon_ESt.cpp` | 58% | 87.4% (118 of 135) | +| `Mover.cpp` (now `physics/components/*.cpp`) | 8.9% | 80.7% (3323 of 4118) | +| `brakes.cpp` | 30% | 76.3% (649 of 851) | +| `oerlikonest.cpp` | 58% | 87.4% (118 of 135) | | `friction.cpp` | 9% | 90.9% (10 of 11) | The aim is branch coverage with the rest explained below, not 100%. @@ -34,8 +34,8 @@ Nothing creates these objects or calls these functions anywhere in the game, whi - **`TFV4a`** (`GetPF`, `Init`): the FV4a handle of the vehicle definitions creates `TFV4aM`. - **Base implementations always overridden:** `TFricMat::GetFC` (every material, the default P10 too, has its own) and `TPrzekladnik::Update` (every relay has its own). - **Functions without callers:** - - In `hamulce.cpp`: `PF_old`, `TBrake::GetBCF`, `TDriverHandle::OvrldButton`, `TReservoir::pa` and `TBrakeCyl::pa`. - - In `Mover.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress`, `DecBrakePress`, `MainCtrlActualPowerPos` and `GetExternalCommand`. + - In `brakes.cpp`: `PF_old`, `TBrake::GetBCF`, `TDriverHandle::OvrldButton`, `TReservoir::pa` and `TBrakeCyl::pa`. + - In `physics/components/pneumatics.cpp`: `BrakeVP`, `PipeRatio`, `RealPipeRatio`, `IncBrakeLevel`, `DecBrakeLevel`, `IncBrakePress` and `DecBrakePress`; in `physics/components/controllers.cpp`: `MainCtrlActualPowerPos`. (`GetExternalCommand` was removed.) - **Inverter failures** of the induction motor drives (`inverter::Failure_Drive`, `Failure_Const`, `Activate`): nothing ever sets them. The cab only shows them. The branches reading them in `TractionForce` can't be reached. ## Code only data no game vehicle has would run @@ -60,7 +60,7 @@ Where it was worth it, a test fits the missing parameter to a real vehicle or bu These are run by the game, by vehicles it has or by the cab, the AI or the scenery, but no test reaches them yet. Most of them are the far sides of conditions inside functions the tests do run. - **Entry points from outside the core:** - - `TBrake::ForceEmptiness` and its overrides: a scenario's vehicle set up with empty brakes (`DynObj.cpp`). + - `TBrake::ForceEmptiness` and its overrides: a scenario's vehicle set up with empty brakes (`vehicle/dynamic/lifecycle.cpp`). - `TBrake::GetSoundFlag`: the sounds of the brakes. - `LoadFIZ` and `reload_FIZ`: the file loading around `LoadFIZ_Text`, which the tests call directly. - `TSecuritySystem::set_cabsignal_lock`. @@ -81,13 +81,21 @@ These are run by the game, by vehicles it has or by the cab, the AI or the scene The core library (`eu07_core`) and the test binary hold more than the physics: the parser of the game's text files, the helpers of `utilities.cpp`, the PLC of a vehicle, the parts of the vehicles and of the simulation moved out of the big classes to be tested, and the hosts of the script screens. The sections above don't cover them. Their numbers are lines run, from the report of the Coverage workflow. -The tables show the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. What those tests add is measured by the Coverage run of the pull request which brings them, and shown in the summary of that run. +The per-file table further down is from the run before the tests of the parser, the helpers and the PLC (`test_parser.cpp`, `test_utilities.cpp`, `test_ladder_logic.cpp`) were written. With them, in the Coverage run of master `bac9954a` (2026-11-11, after #333; GCC 13.3, unoptimised, gcov): + +| File | Lines run, before | Lines run, with the tests | Functions run, with the tests | +|---|---|---|---| +| `scripting/ladderlogic.cpp` | 4.1% (9 of 217) | 98.2% (213 of 217) | 11 of 11 | +| `utilities/parser.cpp` | 40.0% (170 of 425) | 97.6% (415 of 425) | 41 of 41 | +| `utilities/utilities.cpp` | 28.2% (82 of 291) | 95.5% (299 of 313) | 51 of 51 | + +`utilities.cpp` grew by 22 lines on master between the two runs (`user_cache_path`, `utf8_to_win1250`). All 62 files of the game in that report together: lines 83.5% (15411 of 18464), functions 85.5% (1378 of 1612), branches 59.5% (15503 of 26046). The totals aren't comparable with the run below: the report holds 13 more files, from the merges in between. **The run measured:** pull request #325 on 2026-11-11 (its commit `33cedc45` merged into master `10c7527a`), GCC 13.3, unoptimised, gcov lines. All 49 files of the game in the report together: lines 84.4% (10305 of 12204), functions 85.0% (927 of 1090), branches 62.3% (10325 of 16578). | File | Lines run | Functions run | |---|---|---| -| `McZapkie/couplerphysics.cpp` | 93.6% (147 of 157) | 20 of 21 | +| `physics/couplerphysics.cpp` | 93.6% (147 of 157) | 20 of 21 | | `scripting/ladderlogic.cpp` | 4.1% (9 of 217) | 2 of 11 | | `scripting/ladderlogic.h` | 0% (0 of 25) | 0 of 4 | | `scripting/luaprogram.cpp` | 74.7% (334 of 447) | 50 of 66 | @@ -114,8 +122,10 @@ The tables show the run before the tests of the parser, the helpers and the PLC Notes to the table: - The small headers with the logic of a single part are all run in full: `vehicle/doorwings.h`, `gaugeduplicates.h`, `gaugepositions.h`, `holdcoillever.h`, `lightsprogrammer.h`, `mainctrlact.h`, `mirrors.h`, `scripting/scriptscreendrawing.h`, `scriptscreenkernels.h`, `scriptscreenprogram.h`, `scriptscreens.h`, `utilities/dictionary.h` and `vehicle/blackbox.h`. -- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. They have tests (`test_brake_setting.cpp`, `test_odometer.cpp`) and no numbers yet. +- `vehicle/brakesetting.cpp` and `vehicle/odometer.cpp` (the brake setting of the wagons, the odometer store) joined the library on master after that run. In the run of `bac9954a` their tests (`test_brake_setting.cpp`, `test_odometer.cpp`) run 94.1% (144 of 153) and 87.9% (189 of 215) of their lines, and all 14 and 26 of 28 of their functions. - The script hosts (`scriptscreens.cpp`, `luaprogram.cpp`, `wasmprogram.cpp`) aren't in the library. The test binary compiles them itself, with the real runtimes. +- `vehicle/Camera.cpp` isn't in the library either. The test binary compiles it for the order of the camera's rotations (`test_camera.cpp`, #414), with stubs for the command queue and the clock that `TCamera::Update()` reaches for. +- The colour of the smoke of a cold diesel (#413) isn't tested: the fix is in `smoke_source::update()` (`rendering/particles.cpp`), which needs the world environment (sky, sun, precipitation, sounds) and a whole `TDynamicObject` to link. - `scene/scenelayers.h`, `scene/scenenode.h` and `scene/scenenodegroups.h` are in the report with a few lines each: the parser reports the files it includes to the scenery, which the tests replace with stubs (`engine_stubs.cpp`). ### The parser, the helpers and the PLC @@ -137,14 +147,13 @@ The tests are written for the first two columns, and for what the game doesn't c - The messages of the log (`Failed to open file`, `Bad include`) are run, and not checked: the log of the tests is a stub. - A buffer type which is neither a file nor a text (the `default:` of the constructor) can't be given without an invalid value of the type. - **`utilities.cpp`:** - - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. + - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. The choice among the XDG variables and the home folder which Linux makes is apart from the environment (`xdg_base_directory()`) and tested on every system. - `FileCased()` looks through the working folder for a name given without a folder, and through the folder of the file elsewhere; on Windows it only asks whether the file is there. The search is run on Linux only. - - `Bezogonkow()` gives other letters with MSVC than with GCC and Clang, see the findings. The test takes either, told by the entry of the table the difference starts at, so each build checks the half it is. - **`ladderlogic.cpp`:** the two `return`s marked "not reachable" after the switches over the kind of an element. **Code nothing in the game runs** (checked against the whole source tree): -- **The PLC as a whole.** A vehicle has one (`TMoverParameters::m_plc`) and runs it in every step (`m_plc.update()`), but nothing calls `load()`, so its program is always empty; nothing calls `find_or_insert()`, `input()` or `output()` either, so no file of the game data can be a program for it. Of `ladderlogic.cpp` the game runs the 9 lines of an update without timers and without operations. The tests run the rest with programs made up for them. +- **The PLC as a whole.** A vehicle has one (`physics::Vehicle::m_plc`) and runs it in every step (`m_plc.update()`), but nothing calls `load()`, so its program is always empty; nothing calls `find_or_insert()`, `input()` or `output()` either, so no file of the game data can be a program for it. Of `ladderlogic.cpp` the game runs the 9 lines of an update without timers and without operations. The tests run the rest with programs made up for them. - **In `parser.cpp`:** `countTokens()` with its `count()`, and `addCommentStyle()`. No caller gives the separators as a null pointer either, which `updateCharClasses()` allows for. - **In `utilities.cpp`:** `generate_uuid_v4()`, `FuzzyLogicAI()` and `last_modified()`. In `utilities.h`: `BorlandTime()`. @@ -154,9 +163,9 @@ The tests are written for the first two columns, and for what the game doesn't c The tests record the behaviour as it is. The following points may deserve a look by someone who knows how the real vehicles behave. -- **`Random(10) - Random(10)` (`Mover.cpp`, the noise of the control pipe pressure `CntrlPipePress`):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. +- **`Random(10) - Random(10)` (`physics/components/fizsections.cpp`, the noise of the control pipe pressure `brakes.controlReservoirPressure`, `CntrlPipePress` before):** the order the two calls were evaluated in isn't specified. MSVC Release, MSVC Debug and GCC gave different traces, a control pipe pressure mirrored around 5 bar, which failed 32 tests on the Linux CI. Fixed: the draws are sequenced in the order of MSVC Release, which the golden traces were recorded with. - **`TCommand::Location` isn't initialised** in a new vehicle. The game always sets it through `PutCommand()`, but a test calling `RunCommand()` directly got different results run to run. -- **`CompressorList` is `int[4][9]`** (`MOVER.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. +- **The `CompressorList` table (`air.compressor.list`) holds `int`s** (`physics/components/airsupply.h`), though its factors are fractions: 0.9 is read as 0. No game vehicle has the list yet. - **A train whose pipe leaks under 2.75 bar before its start-up can't be released:** - Where this happens: an FV4a handle and an LSt valve, for example 4 minutes standing with wagons, waiting for a hot engine. - The cause: the pipe gets cut off the main reservoir (`lock_old` in `UpdatePipePressure`). The AI presses its unlock button only for the lock set by `LPOn` and `LPOff` (`control_main_pipe`). @@ -201,12 +210,12 @@ The tests record the behaviour as it is. The following points may deserve a look - `deserialize_map()` (`utilities.h`, the sound overrides) therefore reads an empty key from an empty file, and one from a file ending with a line break; in a file with Windows line ends its values keep the carriage return. The game's `sound_overrides.txt` is a single line without a line break. - The separators given as a null pointer are taken as none by the tokenizer, but passed on to `strcmp` for a token of 7 characters or more starting with `i`, which crashes (tried by hand, not kept as a test). No caller gives a null pointer. - **The helpers (`utilities.cpp`, `utilities.h`):** - - `Bezogonkow()`, which takes the marks off the letters for the timetable and the on-screen texts: its table has a `±` in the source, a UTF-8 file. MSVC makes one byte of it, GCC and Clang two, which moves every entry from 0xB2 on by one. With MSVC the 18 polish letters come out as `ACELNOSZZacelnoszz`; with GCC as `ALELDNSZZ,le,dnszl`: `Ć` as L, `Ń` as D, `Ó` as N, `ą` and `ł` as a comma, `ć` as l, `ń` as d, `ó` as n, `ż` as l, only `Ę` and `ę` by luck as themselves. The Linux and macOS builds of the game show the names of the stations that way. The test checks whichever table the build has (the GCC one was tried with the table alone, compiled by GCC 6.3). + - `Bezogonkow()`, which takes the marks off the letters for the file names, the scripts and the multiplayer texts: its table had a `±` written as the character in the source, a UTF-8 file. MSVC made one byte of it, GCC and Clang two, which moved every entry from 0xB2 on by one: with GCC the 18 polish letters came out as `ALELDNSZZ,le,dnszl`. Fixed with MaSzyna-EU07/maszyna#94: the entry is written as the byte `±`, and the test checks the one table in every build. - `to_minutes_str()` reads past its table of raised digits for minutes with a fraction of 0.99 or more, and before it for negative minutes, which `CompareTime()` can give it for a timetable whose times go back. Tried by hand, both ended in `std::bad_alloc`, the text read from outside of the table being no text; not kept as a test. A width under 2 throws `std::length_error`. - `stol_def()` gives its default only for an empty text. A text which isn't a number gives 0 (the flags of an event, the log setting). - `split_string_and_number()` throws for a name with a hyphen which no digit follows (`a-b`), and for a number too big. The gamepad bindings and the PLC use it on names from files. - `extract_value()` throws `std::out_of_range` when the key is the last thing in the text with nothing after its `=`. With a space after the `=`, the next `key=value` is taken for the value. - - `seed_of()` takes a word starting with digits for the number in front (`12abc` is 12), so different words can stand for the same seed. + - `seed_of()` took a word starting with digits for the number in front (`12abc` was 12), so different words could stand for the same seed, and a seed of 0 stood for none. Fixed: the whole text has to be the number, anything else is a word, and whether a seed was given is kept apart (`random_seed_given`). - `erase_extension()` cuts at the dot of a folder when the file has none (`dir.d/file` becomes `dir`). - `Round()` adds a half and cuts the fraction, which rounds the negative numbers up: -1.6 becomes -1. - **The PLC (`ladderlogic.cpp`):** diff --git a/tests/unit/README.md b/tests/unit/README.md index 80deab5e4..301717221 100644 --- a/tests/unit/README.md +++ b/tests/unit/README.md @@ -68,7 +68,7 @@ TEST_CASE("brakes: service braking stops a heavier wagon too") { physics iterations a frame. With a cab (`vehicle{definition, 0.0, "name", 1}`) it has a driver. - `consist` (`consist.h`) couples vehicles into a train and steps them together, coupler forces, air, control and power passing between them. The physics reaches a neighbour through its - `TDynamicObject`, for its `MoverParameters` only; the tests have a stand-in of it with just that. + `TDynamicObject`, for its `physics` only; the tests have a stand-in of it with just that. - `drive.h` has the driver's part, made of the AI's steps: `start_up()` (battery, pumps, pantographs, line breaker, converter, compressor), `drive()` (running, acknowledging the vigilance), `release_brakes()`, `drive_cycle()` (a whole run from start-up to a stop). diff --git a/tests/unit/consist.cpp b/tests/unit/consist.cpp index a5f10d936..796943c7d 100644 --- a/tests/unit/consist.cpp +++ b/tests/unit/consist.cpp @@ -8,25 +8,25 @@ namespace test { consist::consist() = default; consist::~consist() = default; -vehicle &consist::add(definition const &Definition, int Cab, int Coupling, double Velocity, double Gap) { +vehicle &consist::add(definition const &Definition, int Cab, CouplingSet const couplings, double Velocity, double Gap) { auto added{std::make_unique(Definition, Velocity, std::format("test{}", m_vehicles.size()), Cab)}; - auto &mover{added->mover()}; + auto &physics{added->physics()}; std::vector object(sizeof(TDynamicObject)); - reinterpret_cast(object.data())->MoverParameters = &mover; // NOSONAR see m_objects + reinterpret_cast(object.data())->physics = &physics; // NOSONAR see m_objects auto position{0.0}; if (false == m_vehicles.empty()) { - auto &last{m_vehicles.back()->mover()}; - position = m_positions.back() - 0.5 * (last.Dim.L + mover.Dim.L) - Gap; - mover.Loc = TLocation{position, 0.0, 0.0}; - if (Coupling != coupling::faux) { - last.Attach(end::rear, end::front, &mover, Coupling, true, false); - mover.Attach(end::front, end::rear, &last, Coupling, true, false); + auto &last{m_vehicles.back()->physics()}; + position = m_positions.back() - 0.5 * (last.Dim.L + physics.Dim.L) - Gap; + physics.SetLoc(TLocation{position, 0.0, 0.0}); + if (false == couplings.Empty()) { + last.Attach(VehicleEnd::rear, VehicleEnd::front, &physics, couplings, true, false); + physics.Attach(VehicleEnd::front, VehicleEnd::rear, &last, couplings, true, false); } } else { - mover.Loc = TLocation{position, 0.0, 0.0}; + physics.SetLoc(TLocation{position, 0.0, 0.0}); } m_vehicles.push_back(std::move(added)); m_positions.push_back(position); @@ -38,25 +38,25 @@ vehicle &consist::add(definition const &Definition, int Cab, int Coupling, doubl void consist::update_neighbours() { // TDynamicObject::update_neighbours(), for vehicles coupled in a line for (std::size_t i = 0; i < m_vehicles.size(); ++i) { - auto &mover{m_vehicles[i]->mover()}; - for (int end = end::front; end <= end::rear; ++end) { - auto &neighbour{mover.Neighbours[end]}; - auto const other{end == end::front ? static_cast(i) - 1 : static_cast(i) + 1}; + auto &physics{m_vehicles[i]->physics()}; + for (auto const end : VehicleEnds) { + auto &neighbour{physics.Neighbours[end]}; + auto const other{end == VehicleEnd::front ? static_cast(i) - 1 : static_cast(i) + 1}; if (other < 0 || other >= static_cast(m_vehicles.size())) { neighbour = neighbour_data(); continue; } - auto const &othermover{m_vehicles[other]->mover()}; - auto const otherend{end == end::front ? end::rear : end::front}; - auto const distance{TMoverParameters::CouplerDist(&mover, &othermover) - mover.Couplers[end].adapter_length - - othermover.Couplers[otherend].adapter_length}; + auto const &otherPhysics{m_vehicles[other]->physics()}; + auto const otherend{Opposite(end)}; + auto const distance{physics::Vehicle::CouplerDist(&physics, &otherPhysics) - physics.Couplers[end].adapter_length - + otherPhysics.Couplers[otherend].adapter_length}; // a vehicle not coupled is a collision source when it's within the range the game scans - if (mover.Couplers[end].Connected == nullptr && distance > std::max(10.0, std::abs(mover.V)) + 40.0) { + if (physics.Couplers[end].Connected == nullptr && distance > std::max(10.0, std::abs(physics.V())) + 40.0) { neighbour = neighbour_data(); continue; } neighbour.vehicle = reinterpret_cast(m_objects[other].data()); // NOSONAR see m_objects - neighbour.vehicle_end = otherend; + neighbour.vehicle_end = NumberOf(otherend); neighbour.distance = static_cast(distance); } } @@ -74,6 +74,7 @@ void consist::step(track const &Track, double Dt) { for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->fast_move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}); } + update_brake_pipes(Dt); } for (auto const &vehicle : m_vehicles) { vehicle->forces(Dt); @@ -83,13 +84,23 @@ void consist::step(track const &Track, double Dt) { auto pipe{0.0}; auto length{0.0}; for (auto const &vehicle : m_vehicles) { - pipe += vehicle->mover().PipePress * vehicle->mover().Dim.L; - length += vehicle->mover().Dim.L; + pipe += vehicle->physics().brakePipe.Pressure() * vehicle->physics().Dim.L; + length += vehicle->physics().Dim.L; } pipe /= length; for (std::size_t i = 0; i < m_vehicles.size(); ++i) { m_positions[i] += m_vehicles[i]->move(Track, Dt, TLocation{m_positions[i], 0.0, 0.0}, pipe); } + update_brake_pipes(Dt); +} + +void consist::update_brake_pipes(double Dt) const { + // vehicle_table::update_brake_pipes() + std::vector vehicles; + for (auto const &vehicle : m_vehicles) { + vehicles.push_back(&vehicle->physics()); + } + physics::Vehicle::UpdatePipeCouplers(vehicles, Dt); } void consist::run(double Seconds, track const &Track, double Dt) { @@ -100,7 +111,7 @@ void consist::run(double Seconds, track const &Track, double Dt) { } double consist::gap(std::size_t Index) const { - return TMoverParameters::CouplerDist(&m_vehicles[Index]->mover(), &m_vehicles[Index + 1]->mover()); + return physics::Vehicle::CouplerDist(&m_vehicles[Index]->physics(), &m_vehicles[Index + 1]->physics()); } } // namespace test diff --git a/tests/unit/consist.h b/tests/unit/consist.h index 02001e042..73daa6294 100644 --- a/tests/unit/consist.h +++ b/tests/unit/consist.h @@ -21,8 +21,8 @@ namespace test { class consist { public: // everything a coupler can join, as two vehicles of a train coupled by a crew - static constexpr int full_coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control | coupling::gangway | coupling::heating | - coupling::permanent | coupling::power110v | coupling::power24v | coupling::highvoltage}; + static constexpr CouplingSet full_coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control | Coupling::gangway | Coupling::heating | + Coupling::permanent | Coupling::power110v | Coupling::power24v | Coupling::highVoltage}; consist(); ~consist(); @@ -31,8 +31,8 @@ public: // a vehicle at the back of the train, its front coupler joined to the rear one of the last vehicle with // the given coupling (coupling flags), Gap [m] between their buffers. Cab as for a vehicle. a vehicle - // with no coupling (coupling::faux) is free on the same track, as one about to be coupled or hit - vehicle &add(definition const &Definition, int Cab = 0, int Coupling = full_coupling, double Velocity = 0.0, double Gap = 0.0); + // with no coupling (Coupling::none) is free on the same track, as one about to be coupled or hit + vehicle &add(definition const &Definition, int Cab = 0, CouplingSet couplings = full_coupling, double Velocity = 0.0, double Gap = 0.0); vehicle &operator[](std::size_t Index) { return *m_vehicles[Index]; } std::size_t size() const { return m_vehicles.size(); } @@ -45,10 +45,11 @@ public: private: void update_neighbours(); + void update_brake_pipes(double Dt) const; std::vector> m_vehicles; std::vector m_positions; // of the vehicles' middles along the track - // the physics reaches a neighbouring vehicle through its TDynamicObject, for its MoverParameters alone. + // the physics reaches a neighbouring vehicle through its TDynamicObject, for its physics alone. // the game's object can't be made without the rest of the game, so it's a stand-in: storage of its size // with that one member set, never constructed, which only the physics ever looks into std::vector> m_objects; diff --git a/tests/unit/data/fiz/6dg_v1/6dg.json b/tests/unit/data/fiz/6dg_v1/6dg.json new file mode 100644 index 000000000..9ad99dec4 --- /dev/null +++ b/tests/unit/data/fiz/6dg_v1/6dg.json @@ -0,0 +1,55 @@ +{ + "_source": "pkp/6dg_v1/6dg.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "70000", "Mred": "10000", "Vmax": "90", "PWR": "708", "SandCap": "300"}, + "Dimensions": {"L": "14.24", "H": "4.285", "W": "3.170", "Cx": "0.2"}, + "Wheels": {"D": "1.100", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "2.6", "Bd": "7.524", "Rmin": "80"}, + "Brake": {"BrakeValve": "LSt", "NBpA": "4", "MBF": "85.0", "MaxBP": "6.2", "MaxASBP": "2.0", "BCN": "4", "BCR": "0.1143", "BCD": "0.05", "BCM": "6.68", "HiPP": "5.0", "LoPP": "3.5", "Vv": "0.8", "MinCP": "7.5", "MaxCP": "8.5", "CompressorSpeed": "0.05", "CompressorPower": "Converter", "BVV": "200", "BRE": "0.9", "UBB1": "1", "UBB2": "12", "UBB3": "16", "HandlePipeUnlockPos": "-0.5", "LPOn": "2.75", "LPOff": "4.5"}, + "BuffCoupl": {"ControlType": "6Dg", "CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "39"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BCPN": "10", "BDelay1": "15", "BDelay2": "3", "BDelay3": "35", "BDelay4": "36", "ASB": "Manual", "LocalBrake": "PneumaticBrake", "MCPN": "6", "SCPN": "1", "AutoRelay": "Yes", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GP", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "FuelStart": "Automatic", "OilStart": "Automatic", "BrakeOpModes": "PN", "EIMCtrlType": "3", "DirChangeMaxPos": "3", "HAO": "No", "HMO": "Yes", "HGDP1": "2", "rows": [ + ["-1","0.7","-1","15","Pneumatic"], + ["0","0.5","-1","9","Pneumatic"], + ["1","0.46","-1","9","Pneumatic"], + ["2","0.42","-1","9","Pneumatic"], + ["3","0.38","-1","9","Pneumatic"], + ["4","0.34","-1","9","Pneumatic"], + ["5","0.29","-1","9","Pneumatic"], + ["6","0","-1","15","Pneumatic"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal", "AwareDelay": "60", "SoundSignalDelay": "5", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "6", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "110", "LMaxCurrent": "91"}, + "Engine": {"AIM": "0.55", "EngineType": "DumbDE", "Trans": "17:75", "Ftmax": "219000", "Vhyp": "7", "Vadd": "5.5", "Cr": "1", "ShuntMode": "0", "WaterCoolingTemperature": "81", "WaterCoolingFanSpeed": "-1200", "WaterMaxTemperature": "85", "OilMinPressure": "0.15", "OilMinTemperature": "25", "OilMaxTemperature": "90", "HeaterMinTemperature": "55", "HeaterMaxTemperature": "60", "HeatKFS": "35", "HeatKFO": "30", "HeatKFE": "7", "HeatKW": "0.01", "HeatKV": "0.3", "HeatKFO2": "100"}, + "MotorParamTable": {"rows": [ + ["0","17.567","64","1500","15","800","1320"], + ["1","15","183.3","2000","49","800","1320"] + ]}, + "SpringBrake": {"Volume": "8", "MBF": "5", "MaxSP": "6", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "WWList": {"Size": "6", "rows": [ + ["596","0","0","0"], + ["840","120","324","1150"], + ["1080","240","468","1350"], + ["1320","360","612","1550"], + ["1560","480","756","1750"], + ["1800","600","900","2000"], + ["1800","600","900","2000"] + ]}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "Yes", "InitPwr": "0.3", "MaxPwrVel": "5", "StartVel": "2", "MinPwr": "0.3", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "120", "Offset": "-0.5", "kPpos": "0.1", "kPneg": "0.4", "kIpos": "0.06", "kIneg": "0.06", "BrakeIntervention": "Yes"}, + "LightsList": {"Size": "7", "Wrap": "no", "Default": "1", "rows": [ + ["0","0"], + ["34","34"], + ["38","34"], + ["22","34"], + ["16","1"], + ["1","16"], + ["21","34"] + ]}, + "UCList": {"Size": "6", "IntegratedBrakePN": "no", "IntegratedLocBrake": "yes", "IntegratedBrake": "no", "CtrlValStep": "0.05", "rows": [ + ["0","0","-1","0","-1","0.15","0.15","0","1","1"], + ["1","0","-1","0","0","0.00","0.00","1","3","1"], + ["2","0","-1","0","0","0.15","0.00","1","3","1"], + ["3","0","0","0","0","0.00","0.00","1","5","3"], + ["4","0","0","1","0","0.00","0.15","3","5","5"], + ["5","0","0","1","0","0.00","0.00","3","6","5"], + ["6","0","0","1","1","0.15","0.15","5","6","5"] + ]} +} diff --git a/tests/unit/data/fiz/README.md b/tests/unit/data/fiz/README.md index 514fb6287..f5be32563 100644 --- a/tests/unit/data/fiz/README.md +++ b/tests/unit/data/fiz/README.md @@ -20,6 +20,7 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `3wl_v2/3wl.fiz` | 3WL | - | ESt3 | - | ManualBrake | Screw | | `430w_v2/430w.fiz` | 430W | - | ESt3AL2HBG300 | - | ManualBrake | Screw | | `4e_v1/4e.fiz` | 4E | ElectricSeriesMotor | LSt | FV4a | PneumaticBrake | Screw | +| `6dg_v1/6dg.fiz` | 6Dg | DumbDE | LSt | MHZ_K8P | PneumaticBrake | Screw | | `bdhpumn_v3/bdhpumn.fiz` | BDHPUMN | - | KE | - | ManualBrake | Screw | | `bhp_v1/bhp-b.fiz` | BHP | - | ESt3AL2 | - | ManualBrake | Articulated | | `br285_v1/br285.fiz` | BR285 | DieselElectric | KE | MHZ_6P | PneumaticBrake | Screw | @@ -59,8 +60,9 @@ Every `.json` here is a vehicle picked up by `test_fiz.cpp`: record the paramete | `su45_v2/301d.fiz` | SU45 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `su46_v2/303d.fiz` | SU46 | DumbDE | LSt | FV4a | PneumaticBrake | Screw | | `tem2_v2/tem2a.fiz` | TEM2 | DieselElectric | LSt | M394 | PneumaticBrake | Screw | +| `vectron_v1/wariant_7w.fiz` | VECTRON | ElectricInductionMotor | EStED | MHZ_K8P | PneumaticBrake | Screw | | `wm15_v1/wm15.fiz` | WM15 | Dumb | LSt | FV4a | PneumaticBrake | Screw | | `wmb10_v1/wmb10.fiz` | WMB10 | DieselEngine | LSt | FV4a | PneumaticBrake | Screw | | `z1_v2/152a.fiz` | Z1 | - | KE | - | ManualBrake | Screw | -The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. +The paths are those of the game's `.fiz` files. `elf_v1/inverter.fiz` is a part the Elf units include, not a vehicle. The 218M (V2NList), the SA134 (HTCList) and the 22WEc (ffBrakeList) are there for lists the others lack, the EP05 for its camshaft, the Vectron for its ED brake lever of its own (SplitEDPneumaticBrake). The 6Dg is there for its universal controller (UCList) setting the power in steps (CtrlValStep), converted alone from the game data of 2026-11 (SVN r9630, which added the key), the others staying as they were. The 214MA stands for the 214M railbus, whose own file repeats a section (TurboPos and MotorParamTable twice), which the definitions here can't hold. diff --git a/tests/unit/data/fiz/vectron_v1/wariant_7w.json b/tests/unit/data/fiz/vectron_v1/wariant_7w.json new file mode 100644 index 000000000..777f4a78b --- /dev/null +++ b/tests/unit/data/fiz/vectron_v1/wariant_7w.json @@ -0,0 +1,72 @@ +{ + "_source": "pkp/vectron_v1/wariant_7w.fiz", + "_comment": "converted by test_fiz.cpp from the game's definition with the files it includes, keeping what the game's loader reads", + "Param": {"Category": "train", "M": "90000", "Mred": "12000", "Vmax": "200", "PWR": "6400", "SandCap": "700"}, + "Load": {"MaxLoad": "7", "LoadQ": "pieces", "LoadAccepted": "pantstate", "LoadSpeed": "1", "UnLoadSpeed": "0.1"}, + "Dimensions": {"L": "18.925", "H": "3.95", "W": "2.95", "Cx": "0.1"}, + "Wheels": {"D": "1.250", "AIM": "4000", "Tw": "1.435", "Axle": "Bo'Bo'", "Ad": "3", "Bd": "9.5", "Rmin": "80"}, + "Brake": {"BrakeValve": "EStED", "NBpA": "4", "MBF": "50", "MaxBP": "3.7", "MaxLBP": "3.7", "BCN": "8", "RM": "0.81", "BCR": "0.127", "BCD": "0.04", "BCM": "2.7", "BCS": "0.8", "BSA": "0", "BM": "Disk2", "BVV": "125", "Vv": "0.8", "CompressorSpeed": "0.06", "CompressorPower": "Main", "MinCP": "8.5", "MaxCP": "9.9", "UBB1": "8", "UBB2": "2", "LPOn": "3.0", "LPOff": "4.5", "HandlePipeUnlockPos": "-1", "EmergencyCutsOffHandle": "Yes"}, + "SpringBrake": {"Volume": "10", "MBF": "8", "MaxSP": "5.5", "ResetP": "4.0", "MinFP": "3.5", "PressOff": "4.5", "PressOn": "3.5", "ValveOnArea": "0.0002", "ValveOffArea": "0.0002", "ValvePNBArea": "0.002", "MTC": "4"}, + "BuffCoupl": {"CType": "Screw", "kB": "9200", "DmaxB": "0.15", "FmaxB": "740", "kC": "4800", "DmaxC": "0.15", "FmaxC": "780", "beta": "0.58", "AllowedFlag": "103"}, + "Cntrl": {"BrakeSystem": "Pneumatic", "BrakeOpModes": "PN", "BCPN": "4", "BDelay1": "15", "BDelay2": "4", "BDelay3": "35", "BDelay4": "25", "ASB": "Automatic", "LocalBrake": "PneumaticBrake", "MCPN": "15", "SCPN": "40", "SpeedCtrlDelay": "0.5", "AutoRelay": "No", "MainInitTime": "10", "MainStart": "Manual", "IniCDelay": "0.5", "SCDelay": "0.1", "BrakeDelays": "GPR", "BrakeHandle": "MHZ_K8P", "LocBrakeHandle": "FD1", "ScndS": "Yes", "SBD": "0", "ConverterStart": "Automatic", "ConverterStartDelay": "10", "PantCompressorStart": "Automatic", "PantAutoValve": "Yes", "EIMCtrlType": "0", "HAO": "No", "HMO": "No", "HGDP1": "0.1", "OMP": "0.4", "DirChangeMaxPos": "0", "LocalBrakeTraxx": "No", "PantEPValveStart": "Manual", "PantEPValveSpring": "No", "HideDirStatusWhenMoving": "Yes", "HideDirStatusSpeed": "5", "AutomaticCabActivation": "No", "InactiveCabFlag": "161", "DCMB": "Yes", "DCDPP": "1.0", "IBTB": "Yes", "SBBBH": "Yes", "BBHT": "2.0", "MotorBlowersStart": "Converter", "SplitEDPneumaticBrake": "Yes", "DBPN": "15", "rows": [ + ["-1","0.8","-1","20","Pneumatic"], + ["0","0.5","-1","2","Pneumatic"], + ["1","0.46","-1","2","Pneumatic"], + ["2","0.42","-1","2","Pneumatic"], + ["3","0.38","-1","2","Pneumatic"], + ["4","0.34","-1","2","Pneumatic"], + ["5","0.29","-1","2","Pneumatic"], + ["6","0","-1","40","Pneumatic"], + ["LampRed=255","LampGreen=255","LampBlue=228"] + ]}, + "Security": {"AwareSystem": "Active,CabSignal,SeparateAcknowledge", "AwareDelay": "30", "SoundSignalDelay": "0", "MaxHoldTime": "1.0", "EmergencyBrakeDelay": "5", "RadioStop": "Yes"}, + "Light": {"Light": "Generator", "LGeneratorEngine": "ElectricSeriesMotor", "LMaxVoltage": "24", "LMaxCurrent": "155"}, + "Clima": {"Heating": "Main"}, + "Power": {"EnginePower": "CurrentCollector", "CollectorsNo": "2", "MaxVoltage": "4200", "MaxCurrent": "2000", "MinH": "0.38", "MinV": "1900", "MaxH": "2.4", "CSW": "1.4", "PhysicalLayout": "3", "PantType": "WBL85"}, + "Engine": {"EngineType": "ElectricInductionMotor", "Trans": "10:47", "dfic": "931", "dfmax": "1.67", "p": "2", "cfu": "29", "cim": "8.86", "icif": "0.642", "Uzmax": "2216", "Uzh": "2216", "DU": "20", "I0": "20", "fcfu": "30", "F0": "340", "a1": "0.35", "Pmax": "6400", "Fh": "150", "Ph": "5200", "Vh0": "5", "Vh1": "10", "Imax": "2500", "Flat": "Yes", "abed": "1", "edep": "1.5", "Imaxrpc": "500", "BRVto": "15", "MotorBlowersSustainTime": "30", "MotorBlowersStartVelocity": "0.1", "MotorBlowersSpeed": "-10"}, + "SpeedControl": {"SpeedCtrl": "Yes", "OverrideManual": "No", "InitPwr": "1.0", "MaxPwrVel": "-1", "StartVel": "-1", "VelStep": "5", "PwrStep": "0.01", "MinPwr": "0.0", "MaxPwr": "1.0", "MinVel": "0", "MaxVel": "200", "Offset": "0", "kPpos": "0.1", "kPneg": "0.2", "kIpos": "0.03", "kIneg": "0.03", "BrakeIntervention": "No", "SpeedCtrlType": "Time", "SpeedCtrlDelay": "0.5"}, + "Doors": {"OpenCtrl": "Mixed", "CloseCtrl": "Mixed", "DoorOpenWithPermit": "1", "DoorMaxShiftL": "2", "DoorsPermitLightBlinking": "0"}, + "Switches": {"Pantograph": "Impulse", "PantographPresets": "2|1|3|2", "PantographPresetDefault": "1", "ModernDimmer": "Yes"}, + "DimmerList": {"Size": "5", "Cycle": "no", "DefaultPos": "3", "rows": [ + ["yes","no","no"], + ["yes","yes","no"], + ["no","no","yes"], + ["no","no","no"], + ["no","yes","no"] + ]}, + "ffList": {"Size": "8", "rows": [ + ["0","0.2"], + ["1","0.2"], + ["9.2","0.6"], + ["24.6","0.8"], + ["30.0","0.8"], + ["30.0","1.74"], + ["35.2","2.07"], + ["35.2","2.44"], + ["49.8","3.388"] + ]}, + "LightsList": {"Size": "16", "Wrap": "Yes", "Default": "1", "rows": [ + ["0","0"], + ["17","0"], + ["4","0"], + ["16","1"], + ["1","16"], + ["21","34"], + ["34","0"], + ["21","0"], + ["37","0"], + ["33","0"], + ["22","34"], + ["36","0"], + ["21","0"], + ["21","0"], + ["38","34"], + ["38","0"] + ]}, + "WiperList": {"Size": "4", "Angle": "58", "rows": [ + ["0","0.7","0.0","0.5"], + ["3","0.7","7.0","0.5"], + ["3","0.7","0.7","0.0"], + ["3","0.5","0.5","0.0"] + ]} +} diff --git a/tests/unit/drive.cpp b/tests/unit/drive.cpp index b03eeac2d..524a9e39a 100644 --- a/tests/unit/drive.cpp +++ b/tests/unit/drive.cpp @@ -4,7 +4,8 @@ #include "golden.h" #include "doctest.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" +#include "vehicle/fieldshunting.h" namespace test { @@ -14,40 +15,40 @@ void mark(trace *Trace, std::string const &Event) { } } -bool is_powered(TMoverParameters const &Vehicle) { +bool is_powered(physics::Vehicle const &Vehicle) { using enum TEngineType; auto const type{Vehicle.EngineType}; return Vehicle.Power > 1.0 && (type == ElectricSeriesMotor || type == ElectricInductionMotor || type == DieselEngine || type == DieselElectric); } driven driving(vehicle &Vehicle) { - return {Vehicle.mover(), Vehicle.mover(), Vehicle.mover(), [&Vehicle](double Seconds, track const &Track) { Vehicle.run(Seconds, Track); }}; + return {Vehicle.physics(), Vehicle.physics(), Vehicle.physics(), [&Vehicle](double Seconds, track const &Track) { Vehicle.run(Seconds, Track); }}; } driven driving(consist &Consist) { - // the AI's mvControlling and mvPantographUnit: the first vehicle with an engine, and with pantographs - auto *controlling{&Consist[0].mover()}; - auto *pantographs{&Consist[0].mover()}; + // the AI's mvControlling and pantographUnit: the first vehicle with an engine, and with pantographs + auto *controlling{&Consist[0].physics()}; + auto *pantographs{&Consist[0].physics()}; for (auto i = Consist.size(); i-- > 0;) { - auto &mover{Consist[i].mover()}; - if (is_powered(mover)) { - controlling = &mover; + auto &physics{Consist[i].physics()}; + if (is_powered(physics)) { + controlling = &physics; } - if (mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector && mover.EnginePowerSource.CollectorParameters.CollectorsNo > 0) { - pantographs = &mover; + if (physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector && physics.EnginePowerSource.CollectorParameters.CollectorsNo > 0) { + pantographs = &physics; } } - return {Consist[0].mover(), *controlling, *pantographs, [&Consist](double Seconds, track const &Track) { Consist.run(Seconds, Track); }}; + return {Consist[0].physics(), *controlling, *pantographs, [&Consist](double Seconds, track const &Track) { Consist.run(Seconds, Track); }}; } namespace { -void attend(TMoverParameters &Mover) { - if (Mover.SecuritySystem.is_cabsignal_blinking() && Mover.SecuritySystem.has_separate_acknowledge()) { - Mover.SecuritySystem.cabsignal_reset(); +void attend(physics::Vehicle &Physics) { + if (Physics.SecuritySystem.is_cabsignal_blinking() && Physics.SecuritySystem.has_separate_acknowledge()) { + Physics.SecuritySystem.cabsignal_reset(); } - if (Mover.SecuritySystem.is_blinking()) { - Mover.SecuritySystemReset(); + if (Physics.SecuritySystem.is_blinking()) { + Physics.SecuritySystemReset(); } } @@ -61,8 +62,8 @@ void drive(driven Driven, track const &Track, double Seconds) { } } -void release_brakes(TMoverParameters &Cab) { - Cab.BrakeLevelSet(Cab.Handle->GetPos(bh_RP)); +void release_brakes(physics::Vehicle &Cab) { + Cab.BrakeLevelSet(Cab.brakes.driverValve->GetPos(bh_RP)); Cab.DecLocalBrakeLevel(LocalBrakePosNo); Cab.DecManualBrakeLevel(ManualBrakePosNo); Cab.SpringBrakeActivate(false); @@ -73,9 +74,9 @@ void release_brakes(TMoverParameters &Cab) { auto const *vehicle{pending.back()}; pending.pop_back(); for (auto const &thiscoupler : vehicle->Couplers) { - if (thiscoupler.Connected != nullptr && thiscoupler.CouplingFlag != coupling::faux && std::ranges::find(train, thiscoupler.Connected) == train.end()) { + if (thiscoupler.Connected != nullptr && thiscoupler.CouplingFlag != Coupling::none && std::ranges::find(train, thiscoupler.Connected) == train.end()) { thiscoupler.Connected->DecManualBrakeLevel(ManualBrakePosNo); - thiscoupler.Connected->SpringBrake.Activate = false; + thiscoupler.Connected->brakes.spring.activate = false; train.push_back(thiscoupler.Connected); pending.push_back(thiscoupler.Connected); } @@ -84,12 +85,12 @@ void release_brakes(TMoverParameters &Cab) { } bool is_ready(driven const &Driven) { - auto const &mover{Driven.controlling}; - auto const air{mover.VeselVolume <= 0.0 || mover.ScndPipePress >= 4.5}; + auto const &physics{Driven.controlling}; + auto const air{physics.air.config.mainReservoirVolume <= 0.0 || physics.mainPipe.Pressure() >= 4.5}; // the converter feeds the 110 V circuits (the electrodynamic brake's control among them); the AI switches // it on once the line breaker is closed, so a train already charged with air isn't ready before it runs - auto const converter{mover.ConverterStart != start_t::manual || mover.ConverterFlag}; - return mover.Mains && air && converter; + auto const converter{physics.converter.config.start != start_t::manual || physics.converter.IsRunning()}; + return physics.lineBreaker.IsClosed() && air && converter; } namespace { @@ -107,17 +108,17 @@ void prepare_diesel(driven const &Driven) { // the pantographs' own air topped up by their compressor, and the pantographs raised void raise_pantographs(driven const &Driven) { auto &pantographs{Driven.pantographs}; - if (auto const enough{(pantographs.TrainType == dt_EZT ? 2.5 : 3.5) + 0.1}; pantographs.PantPress < enough) { - if (false == pantographs.PantAutoValve) { - pantographs.bPantKurek3 = false; // the pantographs on their own air + if (auto const enough{(pantographs.TrainType() == train_type::emu ? 2.5 : 3.5) + 0.1}; pantographs.pantographAir.Pressure() < enough) { + if (false == pantographs.pantographAir.config.autoValve) { + pantographs.pantographAir.ConnectToMainReservoir(false); // the pantographs on their own air } - pantographs.PantCompFlag = true; + pantographs.pantographAir.SwitchCompressor(true); } - else if (false == pantographs.bPantKurek3 || pantographs.PantPress <= pantographs.ScndPipePress) { - pantographs.PantCompFlag = false; + else if (false == pantographs.pantographAir.IsConnectedToMainReservoir() || pantographs.pantographAir.Pressure() <= pantographs.mainPipe.Pressure()) { + pantographs.pantographAir.SwitchCompressor(false); } Driven.cab.OperatePantographsValve(operation_t::enable); - Driven.cab.OperatePantographValve(end::rear, operation_t::enable); + Driven.cab.OperatePantographValve(VehicleEnd::rear, operation_t::enable); } // the line breaker closed, which it does only with the controller at zero, and after the relays are reset @@ -130,23 +131,27 @@ void close_line_breaker(driven const &Driven) { Driven.cab.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload); if (controlling.EngineType == TEngineType::DieselEngine) { // a mechanical diesel starts at idle, the first position giving the engine fuel - while (controlling.RList[controlling.MainCtrlPos].Mn == 0 && controlling.IncMainCtrl(1)) { + while (controlling.RList[controlling.MainCtrlPos()].Mn == 0 && controlling.IncMainCtrl(1)) { // up to the first position with fuel } } Driven.cab.MainSwitch(true); } -// the converter, the compressor and the motor blowers, once the line breaker is closed -void switch_auxiliaries_on(TMoverParameters &Cab) { +// the converter, the compressor and the motor blowers, once the line breaker is closed; and the switch of the +// field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes), as the AI does +void switch_auxiliaries_on(physics::Vehicle &Cab) { Cab.ConverterSwitch(true); Cab.CompressorSwitch(true); - for (auto const side : {end::front, end::rear}) { + for (auto const side : VehicleEnds) { if (Cab.MotorBlowers[side].speed != 0) { Cab.MotorBlowersSwitchOff(false, side); Cab.MotorBlowersSwitch(true, side); } } + if (Cab.EngineType == TEngineType::DieselElectric && fieldshunting::has_switch(Cab.AutoRelayType(), Cab.FieldShuntSwitch())) { + Cab.AutoRelaySwitch(true); + } } } // namespace @@ -169,7 +174,7 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { if (diesel) { prepare_diesel(Driven); } - if (controlling.PantographsRequireMains && false == controlling.Mains) { + if (controlling.lineBreaker.config.pantographsRequireIt && false == controlling.lineBreaker.IsClosed()) { // the pantographs rise only through the closed line breaker, which closes without their voltage for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); @@ -179,12 +184,12 @@ bool start_up(driven Driven, track const &Track, double Seconds, trace *Trace) { if (collector) { raise_pantographs(Driven); } - if (false == collector || std::max(controlling.GetTrainsetHighVoltage(), controlling.PantographVoltage) > controlling.EnginePowerSource.CollectorParameters.MinV) { + if (false == collector || std::max(controlling.GetTrainsetHighVoltage(), controlling.pantographCircuit.SupplyVoltage()) > controlling.EnginePowerSource.CollectorParameters.MinV) { // a direction first, as in TController::PrepareDirection(): the relays reset only with one set for (int i = 0; i < 3 && cab.DirActive <= 0; ++i) { cab.DirectionForward(); } - if (false == controlling.Mains) { + if (false == controlling.lineBreaker.IsClosed()) { close_line_breaker(Driven); } else { @@ -205,7 +210,7 @@ void drive_cycle(driven Driven, track const &Track, trace &Trace) { auto &cab{Driven.cab}; auto &controlling{Driven.controlling}; if (false == start_up(Driven, Track, 300.0, &Trace)) { - MESSAGE("didn't get ready: Mains " << controlling.Mains << ", main reservoir " << controlling.ScndPipePress); + MESSAGE("didn't get ready: Mains " << controlling.lineBreaker.IsClosed() << ", main reservoir " << controlling.mainPipe.Pressure()); } Trace.mark("release brakes"); release_brakes(cab); @@ -243,10 +248,10 @@ void drive_cycle(driven Driven, track const &Track, trace &Trace) { drive(Driven, Track, 10.0); Trace.mark("brake"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); drive(Driven, Track, 60.0); Trace.mark("release"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_RP)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_RP)); drive(Driven, Track, 20.0); } diff --git a/tests/unit/drive.h b/tests/unit/drive.h index a1aed95be..dce224af9 100644 --- a/tests/unit/drive.h +++ b/tests/unit/drive.h @@ -15,12 +15,12 @@ class consist; // (Cab != 0): a lone one, or the first one of a consist, and drives the whole of it // what the driver drives: the vehicle with the driver in it, the vehicles the driver controls the engine and -// the pantographs of (the AI's mvOccupied, mvControlling, mvPantographUnit; all the same one in a lone +// the pantographs of (the AI's occupied, mvControlling, pantographUnit; all the same one in a lone // vehicle or a locomotive), and the way to run the whole of it struct driven { - TMoverParameters &cab; - TMoverParameters &controlling; - TMoverParameters &pantographs; + physics::Vehicle &cab; + physics::Vehicle &controlling; + physics::Vehicle &pantographs; std::function run; }; driven driving(vehicle &Vehicle); @@ -37,13 +37,13 @@ void drive(driven Driven, track const &Track, double Seconds); // releases every brake the driver has a hand on: the train brake to running, the independent brake, the // hand brake and the spring brake; and the hand and spring brakes of the vehicles coupled to the cab's -void release_brakes(TMoverParameters &Cab); +void release_brakes(physics::Vehicle &Cab); // whether the vehicle is ready to run: line breaker closed (or the engine running), air in the main reservoir bool is_ready(driven const &Driven); // whether the vehicle drives itself -bool is_powered(TMoverParameters const &Vehicle); +bool is_powered(physics::Vehicle const &Vehicle); // a trace mark, when there's a trace void mark(trace *Trace, std::string const &Event); diff --git a/tests/unit/engine_stubs.cpp b/tests/unit/engine_stubs.cpp index c1a807a32..52a503ac5 100644 --- a/tests/unit/engine_stubs.cpp +++ b/tests/unit/engine_stubs.cpp @@ -12,6 +12,10 @@ #include #include +#include +#include +#include +#include // settings --------------------------------------------------------------------------------------- @@ -34,9 +38,39 @@ bool log_enabled() { static bool const enabled{std::getenv("EU07_UNIT_TESTS_LOG") != nullptr}; return enabled; } + +// the lines kept for a test that checks what goes to the log, from any thread; see unit_tests_log_capture() +std::mutex &captured_mutex() { + static std::mutex mutex; + return mutex; +} + +std::optional> &captured_lines() { + static std::optional> lines; + return lines; +} + } // namespace +// for the tests: keeps every line logged from now on (true), or stops keeping them and forgets them (false) +void unit_tests_log_capture(bool const Enabled) { + std::scoped_lock lock{captured_mutex()}; + captured_lines() = Enabled ? std::make_optional>() : std::nullopt; +} + +// for the tests: the lines kept so far +std::vector unit_tests_logged_lines() { + std::scoped_lock lock{captured_mutex()}; + return captured_lines().value_or(std::vector{}); +} + void WriteLog(const char *str, logtype const, bool const isError) { + if (str != nullptr) { + std::scoped_lock lock{captured_mutex()}; + if (captured_lines().has_value()) { + captured_lines()->emplace_back(str); + } + } if (log_enabled() && str != nullptr) { (isError ? std::cerr : std::cout) << str << "\n"; } diff --git a/tests/unit/figures.cpp b/tests/unit/figures.cpp index 96f5a3d74..bb3483dff 100644 --- a/tests/unit/figures.cpp +++ b/tests/unit/figures.cpp @@ -59,22 +59,22 @@ constexpr double pipe_back{4.9}; } // namespace -void figures::sample(double Time, TMoverParameters const &Vehicle) { +void figures::sample(double Time, physics::Vehicle const &Vehicle) { auto &part{m_parts.back()}; - auto const speed{Vehicle.V * 3.6}; - auto const pipe{Vehicle.PipePress}; + auto const speed{Vehicle.V() * 3.6}; + auto const pipe{Vehicle.brakePipe.Pressure()}; if (false == part.sampled) { part.sampled = true; // from the last step of the part before, so the parts add up to the run part.start = m_last_time < 0.0 ? Time : m_last_time; part.speed_start = m_last_time < 0.0 ? speed : m_last_speed; - part.distance_start = m_last_time < 0.0 ? Vehicle.DistCounter : m_last_distance; + part.distance_start = m_last_time < 0.0 ? Vehicle.DistCounter() : m_last_distance; part.pipe_lowest = pipe; } part.end = Time; part.speed_end = speed; part.speed_peak = std::max(part.speed_peak, std::abs(speed)); - part.distance_end = Vehicle.DistCounter; + part.distance_end = Vehicle.DistCounter(); if (part.stopped < 0.0 && std::abs(part.speed_start) > 1.0 && std::abs(speed) < 0.05) { part.stopped = Time - part.start; } @@ -86,19 +86,19 @@ void figures::sample(double Time, TMoverParameters const &Vehicle) { if (part.pipe_back < 0.0 && part.pipe_lowest < pipe_drop && pipe >= pipe_back) { part.pipe_back = Time - part.start; } - part.cylinders_peak = std::max(part.cylinders_peak, Vehicle.BrakePress); + part.cylinders_peak = std::max(part.cylinders_peak, Vehicle.brakes.cylinderPressure); part.current_peak = std::max(part.current_peak, std::abs(Vehicle.Im)); - part.force_peak = std::max(part.force_peak, std::abs(Vehicle.Ft) / 1000.0); + part.force_peak = std::max(part.force_peak, std::abs(Vehicle.Ft()) / 1000.0); m_last_time = Time; m_last_speed = speed; - m_last_distance = Vehicle.DistCounter; + m_last_distance = Vehicle.DistCounter(); // which figures the vehicle has, over the whole run, so each part has the same ones m_moved |= std::abs(speed) >= 0.05; m_piped |= pipe >= 0.1; - m_braked |= Vehicle.BrakePress >= 0.005; + m_braked |= Vehicle.brakes.cylinderPressure >= 0.005; m_current |= std::abs(Vehicle.Im) >= 0.5; - m_force |= std::abs(Vehicle.Ft) >= 50.0; + m_force |= std::abs(Vehicle.Ft()) >= 50.0; } void figures::mark(std::string const &Event) { diff --git a/tests/unit/figures.h b/tests/unit/figures.h index e69e67ef4..793eaecb8 100644 --- a/tests/unit/figures.h +++ b/tests/unit/figures.h @@ -3,7 +3,7 @@ #include #include -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" namespace test { @@ -26,7 +26,7 @@ namespace test { class figures { public: // called on every step of the vehicle - void sample(double Time, TMoverParameters const &Vehicle); + void sample(double Time, physics::Vehicle const &Vehicle); // a part of the run starts with the event void mark(std::string const &Event); diff --git a/tests/unit/fiz.h b/tests/unit/fiz.h index 1e65049fc..5deec2c5f 100644 --- a/tests/unit/fiz.h +++ b/tests/unit/fiz.h @@ -6,7 +6,7 @@ class cParser; -// what the game's vehicle loader (TMoverParameters::LoadFIZ_Parse) makes of the lines of a vehicle definition, +// what the game's vehicle loader (physics::Vehicle::LoadFIZ_Parse) makes of the lines of a vehicle definition, // for the test definitions to give it the same and for checking they do namespace test::fiz { diff --git a/tests/unit/golden.cpp b/tests/unit/golden.cpp index 45bd1c532..d083d3468 100644 --- a/tests/unit/golden.cpp +++ b/tests/unit/golden.cpp @@ -11,76 +11,99 @@ #include #include -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" namespace test { +namespace { + +// the number the traces record for the type of a vehicle: the bit it was before the type became an enum, so the traces +// recorded before it still compare +int legacy_code(train_type const Type) { + switch (Type) { + case train_type::emu: return 0x1; + case train_type::et41: return 0x2; + case train_type::et42: return 0x4; + case train_type::pseudodiesel: return 0x8; + case train_type::et22: return 0x10; + case train_type::sn61: return 0x20; + case train_type::ep05: return 0x40; + case train_type::et40: return 0x80; + case train_type::skoda181: return 0x100; + case train_type::dmu: return 0x200; + case train_type::generic: return 0; + } + return 0; +} + +} // namespace + namespace channels { std::vector motion() { return { - {"V", [](auto const &M) { return M.V; }}, - {"DistCounter", [](auto const &M) { return M.DistCounter; }}, - {"AccS", [](auto const &M) { return M.AccS; }}, - {"nrot", [](auto const &M) { return M.nrot; }}, - {"Ft", [](auto const &M) { return M.Ft; }}, - {"Fb", [](auto const &M) { return M.Fb; }}, + {"V", [](auto const &M) { return M.V(); }}, + {"DistCounter", [](auto const &M) { return M.DistCounter(); }}, + {"AccS", [](auto const &M) { return M.AccS(); }}, + {"nrot", [](auto const &M) { return M.nrot(); }}, + {"Ft", [](auto const &M) { return M.Ft(); }}, + {"Fb", [](auto const &M) { return M.Fb(); }}, {"FStand", [](auto const &M) { return M.FStand; }}, - {"SlippingWheels", [](auto const &M) { return M.SlippingWheels ? 1.0 : 0.0; }}, + {"SlippingWheels", [](auto const &M) { return M.SlippingWheels() ? 1.0 : 0.0; }}, }; } std::vector traction() { return { - {"Mains", [](auto const &M) { return M.Mains ? 1.0 : 0.0; }}, + {"Mains", [](auto const &M) { return M.lineBreaker.IsClosed() ? 1.0 : 0.0; }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, - {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, + {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos(); }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, - {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos; }}, + {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos(); }}, {"ScndCtrlActualPos", [](auto const &M) { return M.ScndCtrlActualPos; }}, {"Im", [](auto const &M) { return M.Im; }}, {"Itot", [](auto const &M) { return M.Itot; }}, {"EngineVoltage", [](auto const &M) { return M.EngineVoltage; }}, {"EnginePower", [](auto const &M) { return M.EnginePower; }}, {"enrot", [](auto const &M) { return M.enrot; }}, - {"dizel_fill", [](auto const &M) { return M.dizel_fill; }}, - {"eimv_pr", [](auto const &M) { return M.eimv_pr; }}, - {"DynamicBrakeFlag", [](auto const &M) { return M.DynamicBrakeFlag ? 1.0 : 0.0; }}, + {"dizel_fill", [](auto const &M) { return M.diesel.fill; }}, + {"eimv_pr", [](auto const &M) { return M.inductionMotor.forceShare; }}, + {"DynamicBrakeFlag", [](auto const &M) { return M.brakes.electrodynamic.on ? 1.0 : 0.0; }}, }; } std::vector brakes() { return { - {"BrakeCtrlPos", [](auto const &M) { return M.BrakeCtrlPos; }}, - {"PipePress", [](auto const &M) { return M.PipePress; }}, - {"BrakePress", [](auto const &M) { return M.BrakePress; }}, - {"LocBrakePress", [](auto const &M) { return M.LocBrakePress; }}, - {"BRP", [](auto const &M) { return M.Hamulec->GetBRP(); }}, - {"VRP", [](auto const &M) { return M.Hamulec->GetVRP(); }}, - {"CRP", [](auto const &M) { return M.Hamulec->GetCRP(); }}, + {"BrakeCtrlPos", [](auto const &M) { return M.brakes.HandlePosition(); }}, + {"PipePress", [](auto const &M) { return M.brakePipe.Pressure(); }}, + {"BrakePress", [](auto const &M) { return M.brakes.cylinderPressure; }}, + {"LocBrakePress", [](auto const &M) { return M.brakes.independentCylinderPressure; }}, + {"BRP", [](auto const &M) { return M.brakes.distributor->GetBRP(); }}, + {"VRP", [](auto const &M) { return M.brakes.distributor->GetVRP(); }}, + {"CRP", [](auto const &M) { return M.brakes.distributor->GetCRP(); }}, }; } std::vector air() { return { - {"Compressor", [](auto const &M) { return M.Compressor; }}, - {"CompressorFlag", [](auto const &M) { return M.CompressorFlag ? 1.0 : 0.0; }}, - {"ScndPipePress", [](auto const &M) { return M.ScndPipePress; }}, + {"Compressor", [](auto const &M) { return M.air.MainReservoirPressure(); }}, + {"CompressorFlag", [](auto const &M) { return M.air.compressor.IsRunning() ? 1.0 : 0.0; }}, + {"ScndPipePress", [](auto const &M) { return M.mainPipe.Pressure(); }}, }; } std::vector handles() { std::vector result{ - {"BrakeCtrlPosR", [](auto const &M) { return M.BrakeCtrlPosR; }}, - {"dpMainValve", [](auto const &M) { return M.dpMainValve; }}, - {"HandleCP", [](auto const &M) { return M.Handle->GetCP(); }}, - {"HandleRP", [](auto const &M) { return M.Handle->GetRP(); }}, - {"HandleEP", [](auto const &M) { return M.Handle->GetEP(); }}, - {"LocalBrakePosA", [](auto const &M) { return M.LocalBrakePosA; }}, - {"dpLocalValve", [](auto const &M) { return M.dpLocalValve; }}, + {"BrakeCtrlPosR", [](auto const &M) { return M.brakes.HandlePositionReal(); }}, + {"dpMainValve", [](auto const &M) { return M.brakes.driverValveFlow; }}, + {"HandleCP", [](auto const &M) { return M.brakes.driverValve->GetCP(); }}, + {"HandleRP", [](auto const &M) { return M.brakes.driverValve->GetRP(); }}, + {"HandleEP", [](auto const &M) { return M.brakes.driverValve->GetEP(); }}, + {"LocalBrakePosA", [](auto const &M) { return M.brakes.IndependentPosition(); }}, + {"dpLocalValve", [](auto const &M) { return M.brakes.independentValveFlow; }}, }; for (int i = 0; i < 5; ++i) { - result.emplace_back(std::format("HandleSound{}", i), [i](auto const &M) { return M.Handle->GetSound(i); }); + result.emplace_back(std::format("HandleSound{}", i), [i](auto const &M) { return M.brakes.driverValve->GetSound(i); }); } return result; } @@ -89,8 +112,8 @@ std::vector doors() { std::vector result{ {"DoorsLocked", [](auto const &M) { return M.Doors.is_locked ? 1.0 : 0.0; }}, }; - for (int side : {side::right, side::left}) { - auto const name{std::string{side == side::right ? "Right" : "Left"}}; + for (auto const side : VehicleSides) { + auto const name{std::string{side == VehicleSide::right ? "Right" : "Left"}}; result.emplace_back(name + "Position", [side](auto const &M) { return M.Doors.instances[side].position; }); result.emplace_back(name + "Step", [side](auto const &M) { return M.Doors.instances[side].step_position; }); result.emplace_back(name + "Open", [side](auto const &M) { return M.Doors.instances[side].is_open ? 1.0 : 0.0; }); @@ -103,76 +126,76 @@ std::vector doors() { std::vector parameters() { std::vector result{ {"CategoryFlag", [](auto const &M) { return M.CategoryFlag; }}, - {"TrainType", [](auto const &M) { return M.TrainType; }}, + {"TrainType", [](auto const &M) { return legacy_code(M.TrainType()); }}, {"EngineType", [](auto const &M) { return static_cast(M.EngineType); }}, - {"Vmax", [](auto const &M) { return M.Vmax; }}, - {"Mass", [](auto const &M) { return M.Mass; }}, - {"TotalMass", [](auto const &M) { return M.TotalMass; }}, - {"Mred", [](auto const &M) { return M.Mred; }}, + {"Vmax", [](auto const &M) { return M.Vmax(); }}, + {"Mass", [](auto const &M) { return M.Mass(); }}, + {"TotalMass", [](auto const &M) { return M.TotalMass(); }}, + {"Mred", [](auto const &M) { return M.Mred(); }}, {"Power", [](auto const &M) { return M.Power; }}, - {"HeatingPower", [](auto const &M) { return M.HeatingPower; }}, + {"HeatingPower", [](auto const &M) { return M.trainHeating.config.power; }}, {"LightPower", [](auto const &M) { return M.LightPower; }}, - {"BatteryVoltage", [](auto const &M) { return M.BatteryVoltage; }}, + {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.BatteryVoltage(); }}, {"Cx", [](auto const &M) { return M.Cx; }}, - {"WheelDiameter", [](auto const &M) { return M.WheelDiameter; }}, + {"WheelDiameter", [](auto const &M) { return M.WheelDiameter(); }}, {"TrackW", [](auto const &M) { return M.TrackW; }}, {"AxleInertialMoment", [](auto const &M) { return M.AxleInertialMoment; }}, - {"NPoweredAxles", [](auto const &M) { return M.NPoweredAxles; }}, - {"NAxles", [](auto const &M) { return M.NAxles; }}, + {"NPoweredAxles", [](auto const &M) { return M.NPoweredAxles(); }}, + {"NAxles", [](auto const &M) { return M.NAxles(); }}, {"BearingType", [](auto const &M) { return M.BearingType; }}, - {"ADist", [](auto const &M) { return M.ADist; }}, - {"BDist", [](auto const &M) { return M.BDist; }}, - {"NBpA", [](auto const &M) { return M.NBpA; }}, + {"ADist", [](auto const &M) { return M.ADist(); }}, + {"BDist", [](auto const &M) { return M.BDist(); }}, + {"NBpA", [](auto const &M) { return M.brakes.config.blocksPerAxle; }}, {"SandCapacity", [](auto const &M) { return M.SandCapacity; }}, - {"BrakeSystem", [](auto const &M) { return static_cast(M.BrakeSystem); }}, - {"BrakeValve", [](auto const &M) { return static_cast(M.BrakeValve); }}, - {"BrakeHandle", [](auto const &M) { return static_cast(M.BrakeHandle); }}, - {"BrakeLocHandle", [](auto const &M) { return static_cast(M.BrakeLocHandle); }}, - {"LocalBrake", [](auto const &M) { return static_cast(M.LocalBrake); }}, - {"ASBType", [](auto const &M) { return M.ASBType; }}, - {"MaxBrakeForce", [](auto const &M) { return M.MaxBrakeForce; }}, - {"P2FTrans", [](auto const &M) { return M.P2FTrans; }}, - {"BrakeMethod", [](auto const &M) { return M.BrakeMethod; }}, - {"HighPipePress", [](auto const &M) { return M.HighPipePress; }}, - {"LowPipePress", [](auto const &M) { return M.LowPipePress; }}, - {"DeltaPipePress", [](auto const &M) { return M.DeltaPipePress; }}, - {"CntrlPipePress", [](auto const &M) { return M.CntrlPipePress; }}, - {"BrakeVolume", [](auto const &M) { return M.BrakeVolume; }}, - {"BrakeVVolume", [](auto const &M) { return M.BrakeVVolume; }}, - {"VeselVolume", [](auto const &M) { return M.VeselVolume; }}, - {"BrakeCylNo", [](auto const &M) { return M.BrakeCylNo; }}, - {"BrakeCylRadius", [](auto const &M) { return M.BrakeCylRadius; }}, - {"BrakeCylDist", [](auto const &M) { return M.BrakeCylDist; }}, - {"BrakeCylSpring", [](auto const &M) { return M.BrakeCylSpring; }}, - {"BrakeSlckAdj", [](auto const &M) { return M.BrakeSlckAdj; }}, - {"BrakeRigEff", [](auto const &M) { return M.BrakeRigEff; }}, - {"RapidMult", [](auto const &M) { return M.RapidMult; }}, - {"RapidVel", [](auto const &M) { return M.RapidVel; }}, - {"BrakeValveSize", [](auto const &M) { return M.BrakeValveSize; }}, - {"MinCompressor", [](auto const &M) { return M.MinCompressor; }}, - {"MaxCompressor", [](auto const &M) { return M.MaxCompressor; }}, - {"CompressorSpeed", [](auto const &M) { return M.CompressorSpeed; }}, - {"EmergencyValveOn", [](auto const &M) { return M.EmergencyValveOn; }}, - {"AirLeakRate", [](auto const &M) { return M.AirLeakRate; }}, - {"BrakeCtrlPosNo", [](auto const &M) { return M.BrakeCtrlPosNo; }}, + {"BrakeSystem", [](auto const &M) { return static_cast(M.brakes.config.kind); }}, + {"BrakeValve", [](auto const &M) { return static_cast(M.brakes.config.distributorType); }}, + {"BrakeHandle", [](auto const &M) { return static_cast(M.brakes.config.driverValveType); }}, + {"BrakeLocHandle", [](auto const &M) { return static_cast(M.brakes.config.independentValveType); }}, + {"LocalBrake", [](auto const &M) { return static_cast(M.brakes.config.localKind); }}, + {"ASBType", [](auto const &M) { return M.brakes.config.antiSlipType; }}, + {"MaxBrakeForce", [](auto const &M) { return M.brakes.config.maxForce; }}, + {"P2FTrans", [](auto const &M) { return M.brakes.config.pressureToForce; }}, + {"BrakeMethod", [](auto const &M) { return M.brakes.config.method; }}, + {"HighPipePress", [](auto const &M) { return M.brakes.config.pipeHighPressure; }}, + {"LowPipePress", [](auto const &M) { return M.brakes.config.pipeLowPressure; }}, + {"DeltaPipePress", [](auto const &M) { return M.brakes.config.pipePressureRange; }}, + {"CntrlPipePress", [](auto const &M) { return M.brakes.controlReservoirPressure; }}, + {"BrakeVolume", [](auto const &M) { return M.brakes.config.cylinderVolume; }}, + {"BrakeVVolume", [](auto const &M) { return M.brakes.config.valveVolume; }}, + {"VeselVolume", [](auto const &M) { return M.air.config.mainReservoirVolume; }}, + {"BrakeCylNo", [](auto const &M) { return M.brakes.config.cylinders.count; }}, + {"BrakeCylRadius", [](auto const &M) { return M.brakes.config.cylinders.radius; }}, + {"BrakeCylDist", [](auto const &M) { return M.brakes.config.cylinders.stroke; }}, + {"BrakeCylSpring", [](auto const &M) { return M.brakes.config.cylinders.springForce; }}, + {"BrakeSlckAdj", [](auto const &M) { return M.brakes.config.cylinders.slackAdjusterForce; }}, + {"BrakeRigEff", [](auto const &M) { return M.brakes.config.cylinders.riggingEfficiency; }}, + {"RapidMult", [](auto const &M) { return M.brakes.config.rapidRatio; }}, + {"RapidVel", [](auto const &M) { return M.brakes.config.rapidSpeed; }}, + {"BrakeValveSize", [](auto const &M) { return M.brakes.config.distributorSize; }}, + {"MinCompressor", [](auto const &M) { return M.air.compressor.config.minPressure; }}, + {"MaxCompressor", [](auto const &M) { return M.air.compressor.config.maxPressure; }}, + {"CompressorSpeed", [](auto const &M) { return M.air.compressor.config.speed; }}, + {"EmergencyValveOn", [](auto const &M) { return M.brakes.emergencyValve.onPressure; }}, + {"AirLeakRate", [](auto const &M) { return M.air.config.leakRate; }}, + {"BrakeCtrlPosNo", [](auto const &M) { return M.brakes.config.handlePositions; }}, {"MainCtrlPosNo", [](auto const &M) { return M.MainCtrlPosNo; }}, - {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo; }}, + {"ScndCtrlPosNo", [](auto const &M) { return M.ScndCtrlPosNo(); }}, {"LightsPosNo", [](auto const &M) { return M.LightsPosNo; }}, - {"MBrake", [](auto const &M) { return M.MBrake ? 1.0 : 0.0; }}, - {"StopBrakeDecc", [](auto const &M) { return M.StopBrakeDecc; }}, - {"BrakeDelays", [](auto const &M) { return M.BrakeDelays; }}, - {"BrakeOpModes", [](auto const &M) { return M.BrakeOpModes; }}, - {"Imin", [](auto const &M) { return M.Imin; }}, + {"MBrake", [](auto const &M) { return M.brakes.config.hasHandBrake ? 1.0 : 0.0; }}, + {"StopBrakeDecc", [](auto const &M) { return M.brakes.holding.deceleration; }}, + {"BrakeDelays", [](auto const &M) { return M.brakes.config.availableDelays; }}, + {"BrakeOpModes", [](auto const &M) { return M.brakes.config.availableOperatingModes; }}, + {"Imin", [](auto const &M) { return M.Imin(); }}, {"Imax", [](auto const &M) { return M.Imax; }}, {"EIMCtrlType", [](auto const &M) { return M.EIMCtrlType; }}, - {"Volume", [](auto const &M) { return M.Volume; }}, - {"PantVolume", [](auto const &M) { return M.PantVolume; }}, + {"Volume", [](auto const &M) { return M.brakes.reservoirAir; }}, + {"PantVolume", [](auto const &M) { return M.pantographAir.Volume(); }}, }; for (int i = 0; i < 5; ++i) { - result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.MaxBrakePress[i]; }); + result.emplace_back(std::format("MaxBrakePress{}", i), [i](auto const &M) { return M.brakes.config.maxCylinderPressure[i]; }); } for (int i = 0; i < 3; ++i) { - result.emplace_back(std::format("BrakeCylMult{}", i), [i](auto const &M) { return M.BrakeCylMult[i]; }); + result.emplace_back(std::format("BrakeCylMult{}", i), [i](auto const &M) { return M.brakes.config.cylinders.leverRatio[i]; }); } return result; } @@ -243,7 +266,7 @@ bool same(std::string const &Recorded, std::string const &Now, bool const Exact) trace::trace(std::string Name, std::vector Channels, int Every, bool Figures) : m_name(std::move(Name)), m_channels(std::move(Channels)), m_every(Every), m_keep_figures(Figures) {} -void trace::sample(double Time, TMoverParameters const &Vehicle) { +void trace::sample(double Time, physics::Vehicle const &Vehicle) { // the invariants on every step, the first time each is broken for (auto const &invariant : invariants()) { if (std::ranges::find(m_broken, invariant.name) != m_broken.end()) { @@ -255,7 +278,7 @@ void trace::sample(double Time, TMoverParameters const &Vehicle) { m_last_event.empty() ? std::string{} : std::format(", after \"{}\"", m_last_event), invariant.explain(Vehicle))); } } - m_before = {Time, Vehicle.V, Vehicle.DistCounter}; + m_before = {Time, Vehicle.V(), Vehicle.DistCounter()}; m_sampled = true; m_figures.sample(Time, Vehicle); diff --git a/tests/unit/golden.h b/tests/unit/golden.h index cb82ed0da..a4714a925 100644 --- a/tests/unit/golden.h +++ b/tests/unit/golden.h @@ -5,7 +5,7 @@ #include #include -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" #include "figures.h" #include "invariants.h" @@ -14,7 +14,7 @@ namespace test { // one value of the vehicle a trace follows struct channel { std::string name; - std::function value; + std::function value; }; // sets of channels for the usual subjects of a test, which can be put together @@ -55,7 +55,7 @@ public: trace(std::string Name, std::vector Channels, int Every = 10, bool Figures = true); // called by the vehicle after every step - void sample(double Time, TMoverParameters const &Vehicle); + void sample(double Time, physics::Vehicle const &Vehicle); // adds an event of the test to the trace, so a difference can be told apart from the moment of the action void mark(std::string const &Event); diff --git a/tests/unit/invariants.cpp b/tests/unit/invariants.cpp index 4fafeb04d..caf85d879 100644 --- a/tests/unit/invariants.cpp +++ b/tests/unit/invariants.cpp @@ -18,13 +18,13 @@ std::string values(std::initializer_list> Values return result; } -bool electric(TMoverParameters const &M) { +bool electric(physics::Vehicle const &M) { return M.EngineType == TEngineType::ElectricSeriesMotor || M.EngineType == TEngineType::ElectricInductionMotor; } -double max_brake_press(TMoverParameters const &M) { +double max_brake_press(physics::Vehicle const &M) { auto result{0.0}; - for (auto const press : M.MaxBrakePress) { + for (auto const press : M.brakes.config.maxCylinderPressure) { result = std::max(result, press); } return result; @@ -41,60 +41,60 @@ std::vector const &invariants() { static std::vector const rules{ {"every value a number", [](auto const &M, double, auto const *) { - std::initializer_list const values{M.V, M.AccS, M.Ft, M.Fb, M.Im, M.Itot, M.EngineVoltage, - M.enrot, M.PipePress, M.BrakePress, M.LocBrakePress, M.ScndPipePress, M.Compressor, M.BatteryVoltage}; + std::initializer_list const values{M.V(), M.AccS(), M.Ft(), M.Fb(), M.Im, M.Itot, M.EngineVoltage, + M.enrot, M.brakePipe.Pressure(), M.brakes.cylinderPressure, M.brakes.independentCylinderPressure, M.mainPipe.Pressure(), M.air.MainReservoirPressure(), M.lowVoltage.BatteryVoltage()}; return std::ranges::all_of(values, [](double const Value) { return std::isfinite(Value); }); }, [](auto const &M) { - return values({{"V", M.V}, {"AccS", M.AccS}, {"Ft", M.Ft}, {"Fb", M.Fb}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, - {"enrot", M.enrot}, {"PipePress", M.PipePress}, {"BrakePress", M.BrakePress}, {"LocBrakePress", M.LocBrakePress}, - {"ScndPipePress", M.ScndPipePress}, {"Compressor", M.Compressor}, {"BatteryVoltage", M.BatteryVoltage}}); + return values({{"V", M.V()}, {"AccS", M.AccS()}, {"Ft", M.Ft()}, {"Fb", M.Fb()}, {"Im", M.Im}, {"Itot", M.Itot}, {"EngineVoltage", M.EngineVoltage}, + {"enrot", M.enrot}, {"PipePress", M.brakePipe.Pressure()}, {"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, + {"ScndPipePress", M.mainPipe.Pressure()}, {"Compressor", M.air.MainReservoirPressure()}, {"BatteryVoltage", M.lowVoltage.BatteryVoltage()}}); }}, {"brake cylinders between empty and the vehicle's highest pressure", [](auto const &M, double, auto const *) { // a step overshoots the setting a little: the EU07's LSt fills its cylinders to 4.0 bar of its 3.8 auto const limit{1.1 * max_brake_press(M) + pressure_margin}; - return M.BrakePress >= -pressure_margin && M.BrakePress <= limit && M.LocBrakePress >= -pressure_margin && M.LocBrakePress <= limit; + return M.brakes.cylinderPressure >= -pressure_margin && M.brakes.cylinderPressure <= limit && M.brakes.independentCylinderPressure >= -pressure_margin && M.brakes.independentCylinderPressure <= limit; }, - [](auto const &M) { return values({{"BrakePress", M.BrakePress}, {"LocBrakePress", M.LocBrakePress}, {"max(MaxBrakePress)", max_brake_press(M)}}); }}, + [](auto const &M) { return values({{"BrakePress", M.brakes.cylinderPressure}, {"LocBrakePress", M.brakes.independentCylinderPressure}, {"max(MaxBrakePress)", max_brake_press(M)}}); }}, {"pipes between empty and the highest governor setting", [](auto const &M, double, auto const *) { // all the air comes from the main reservoirs, which the game sets up to 10 bar, some (the Impuls) to 12; // the driver's valve in its filling position joins the brake pipe to them - auto const highest{1.01 * std::max(10.0, M.MaxCompressor) + pressure_margin}; - std::initializer_list const pressures{M.PipePress, M.ScndPipePress, M.Compressor}; + auto const highest{1.01 * std::max(10.0, M.air.compressor.config.maxPressure) + pressure_margin}; + std::initializer_list const pressures{M.brakePipe.Pressure(), M.mainPipe.Pressure(), M.air.MainReservoirPressure()}; return std::ranges::all_of(pressures, [highest](double const Press) { return Press >= -pressure_margin && Press <= highest; }); }, - [](auto const &M) { return values({{"PipePress", M.PipePress}, {"ScndPipePress", M.ScndPipePress}, {"Compressor", M.Compressor}}); }}, + [](auto const &M) { return values({{"PipePress", M.brakePipe.Pressure()}, {"ScndPipePress", M.mainPipe.Pressure()}, {"Compressor", M.air.MainReservoirPressure()}}); }}, {"main reservoir no higher than the compressor's governor", - [](auto const &M, double, auto const *) { return M.MaxCompressor <= 0.0 || M.Compressor <= 1.01 * M.MaxCompressor + pressure_margin; }, - [](auto const &M) { return values({{"Compressor", M.Compressor}, {"MaxCompressor", M.MaxCompressor}}); }}, + [](auto const &M, double, auto const *) { return M.air.compressor.config.maxPressure <= 0.0 || M.air.MainReservoirPressure() <= 1.01 * M.air.compressor.config.maxPressure + pressure_margin; }, + [](auto const &M) { return values({{"Compressor", M.air.MainReservoirPressure()}, {"MaxCompressor", M.air.compressor.config.maxPressure}}); }}, {"no motor current with the line breaker open", - [](auto const &M, double, auto const *) { return M.Mains || false == electric(M) || std::abs(M.Im) < 1.0; }, - [](auto const &M) { return values({{"Mains", M.Mains}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, + [](auto const &M, double, auto const *) { return M.lineBreaker.IsClosed() || false == electric(M) || std::abs(M.Im) < 1.0; }, + [](auto const &M) { return values({{"Mains", M.lineBreaker.IsClosed()}, {"Im", M.Im}, {"Itot", M.Itot}}); }}, {"no motor current with the line contactors open, but for the dynamic brake", [](auto const &M, double, auto const *) { // the dynamic brake closes its own circuit of the motors and the resistors - return M.StLinFlag || M.DynamicBrakeFlag || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; + return M.lineContactors.IsClosed() || M.brakes.electrodynamic.on || M.EngineType != TEngineType::ElectricSeriesMotor || std::abs(M.Im) < 1.0; }, [](auto const &M) { - return values({{"StLinFlag", M.StLinFlag}, {"DynamicBrakeFlag", M.DynamicBrakeFlag}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); + return values({{"StLinFlag", M.lineContactors.IsClosed()}, {"DynamicBrakeFlag", M.brakes.electrodynamic.on}, {"Im", M.Im}, {"MainCtrlActualPos", M.MainCtrlActualPos}}); }}, {"no tractive force without power", - [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft) < 1.0; }, - [](auto const &M) { return values({{"Power", M.Power}, {"Ft", M.Ft}}); }}, + [](auto const &M, double, auto const *) { return M.Power >= 0.01 || std::abs(M.Ft()) < 1.0; }, + [](auto const &M) { return values({{"Power", M.Power}, {"Ft", M.Ft()}}); }}, {"engine fill between none and full", - [](auto const &M, double, auto const *) { return M.dizel_fill >= 0.0 && M.dizel_fill <= 1.0; }, - [](auto const &M) { return values({{"dizel_fill", M.dizel_fill}}); }}, + [](auto const &M, double, auto const *) { return M.diesel.fill >= 0.0 && M.diesel.fill <= 1.0; }, + [](auto const &M) { return values({{"dizel_fill", M.diesel.fill}}); }}, {"diesel engine turning forward, no faster than its top speed", [](auto const &M, double, auto const *) { // the governor lets it overshoot a little (the SN61 by 1%) - return M.EngineType != TEngineType::DieselEngine || (M.enrot >= 0.0 && M.enrot <= 1.05 * M.dizel_nmax); + return M.EngineType != TEngineType::DieselEngine || (M.enrot >= 0.0 && M.enrot <= 1.05 * M.diesel.maxRevolutions); }, - [](auto const &M) { return values({{"enrot", M.enrot}, {"dizel_nmax", M.dizel_nmax}}); }}, + [](auto const &M) { return values({{"enrot", M.enrot}, {"dizel_nmax", M.diesel.maxRevolutions}}); }}, {"battery no higher than its nominal voltage", - [](auto const &M, double, auto const *) { return M.NominalBatteryVoltage <= 0.0 || M.BatteryVoltage <= 1.05 * M.NominalBatteryVoltage; }, - [](auto const &M) { return values({{"BatteryVoltage", M.BatteryVoltage}, {"NominalBatteryVoltage", M.NominalBatteryVoltage}}); }}, + [](auto const &M, double, auto const *) { return M.lowVoltage.config.nominalBatteryVoltage <= 0.0 || M.lowVoltage.BatteryVoltage() <= 1.05 * M.lowVoltage.config.nominalBatteryVoltage; }, + [](auto const &M) { return values({{"BatteryVoltage", M.lowVoltage.BatteryVoltage()}, {"NominalBatteryVoltage", M.lowVoltage.config.nominalBatteryVoltage}}); }}, {"distance counted as the speed runs", [](auto const &M, double Time, auto const *Before) { if (Before == nullptr) { @@ -103,20 +103,20 @@ std::vector const &invariants() { // the speed of the step is between the speeds at its ends, or a bit off it, as the movement is integrated; // through a standstill, down to none auto const dt{Time - Before->time}; - auto const covered{(M.DistCounter - Before->DistCounter) * 1000.0}; - auto const lowest{M.V * Before->V > 0.0 ? std::min(std::abs(M.V), std::abs(Before->V)) : 0.0}; - auto const highest{std::max(std::abs(M.V), std::abs(Before->V))}; + auto const covered{(M.DistCounter() - Before->distCounter) * 1000.0}; + auto const lowest{M.V() * Before->v > 0.0 ? std::min(std::abs(M.V()), std::abs(Before->v)) : 0.0}; + auto const highest{std::max(std::abs(M.V()), std::abs(Before->v))}; return covered >= lowest * dt * 0.9 - 0.01 && covered <= highest * dt * 1.1 + 0.01; }, - [](auto const &M) { return values({{"V", M.V}, {"DistCounter", M.DistCounter}}); }}, + [](auto const &M) { return values({{"V", M.V()}, {"DistCounter", M.DistCounter()}}); }}, {"no acceleration over 5 g", [](auto const &M, double Time, auto const *Before) { - return Before == nullptr || std::abs(M.V - Before->V) <= highest_acceleration * (Time - Before->time) + 0.01; + return Before == nullptr || std::abs(M.V() - Before->v) <= highest_acceleration * (Time - Before->time) + 0.01; }, - [](auto const &M) { return values({{"V", M.V}, {"AccS", M.AccS}}); }}, + [](auto const &M) { return values({{"V", M.V()}, {"AccS", M.AccS()}}); }}, {"hand brake applied, the wheels braked on the move", - [](auto const &M, double, auto const *) { return false == M.MBrake || M.ManualBrakePos == 0 || std::abs(M.V) < 0.5 || std::abs(M.Fb) > 0.0; }, - [](auto const &M) { return values({{"ManualBrakePos", M.ManualBrakePos}, {"V", M.V}, {"Fb", M.Fb}}); }}, + [](auto const &M, double, auto const *) { return false == M.brakes.config.hasHandBrake || M.brakes.HandBrakePosition() == 0 || std::abs(M.V()) < 0.5 || std::abs(M.Fb()) > 0.0; }, + [](auto const &M) { return values({{"ManualBrakePos", M.brakes.HandBrakePosition()}, {"V", M.V()}, {"Fb", M.Fb()}}); }}, }; return rules; } diff --git a/tests/unit/invariants.h b/tests/unit/invariants.h index 491edc84b..b319a23b4 100644 --- a/tests/unit/invariants.h +++ b/tests/unit/invariants.h @@ -5,15 +5,15 @@ #include #include -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" namespace test { // what the rules over time need of the step before struct snapshot { double time; - double V; - double DistCounter; + double v; + double distCounter; }; // a rule of physics or of the vehicle's circuits, which holds for every vehicle after every step, whatever @@ -23,9 +23,9 @@ struct snapshot { struct invariant { std::string name; // Before is null at the first step of a trace - std::function holds; + std::function holds; // the values the rule looks at, shown when it's broken - std::function explain; + std::function explain; }; std::vector const &invariants(); diff --git a/tests/unit/scenario.cpp b/tests/unit/scenario.cpp index 4af8be18a..94e58e300 100644 --- a/tests/unit/scenario.cpp +++ b/tests/unit/scenario.cpp @@ -1,7 +1,7 @@ #include "stdafx.h" #include "scenario.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" namespace test { @@ -11,7 +11,7 @@ namespace { // switch is on when the controller leaves zero doesn't close its line contactors until the controller is back at zero bool start_cut_off(consist &Train) { for (std::size_t i = 0; i < Train.size(); ++i) { - if (Train[i].mover().ControlPressureSwitch) { + if (Train[i].physics().protection.PressureSwitchTripped()) { return true; } } @@ -24,8 +24,8 @@ scenario::scenario(std::string Name, std::vector Channels, track const reseed_random(); } -scenario &scenario::add(std::string const &Path, int Cab, int Coupling, double Velocity, double Gap) { - m_train.add(definition::fiz(Path), Cab, Coupling, Velocity, Gap); +scenario &scenario::add(std::string const &Path, int Cab, CouplingSet const couplings, double Velocity, double Gap) { + m_train.add(definition::fiz(Path), Cab, couplings, Velocity, Gap); return *this; } @@ -74,7 +74,7 @@ void scenario::full_power(double Seconds) { wait(1.0); } controlling.IncMainCtrl(1); - for (int i = 0; i < 90 && false == controlling.StLinFlag; ++i) { + for (int i = 0; i < 90 && false == controlling.lineContactors.IsClosed(); ++i) { wait(1.0); } for (int i = 0; i < 60 && false == controlling.IsMainCtrlMaxPowerPos(); ++i) { @@ -86,7 +86,7 @@ void scenario::full_power(double Seconds) { void scenario::notch_back(int Position) { auto &controlling{driver().controlling}; - while (controlling.MainCtrlPos > Position && controlling.DecMainCtrl(1)) { + while (controlling.MainCtrlPos() > Position && controlling.DecMainCtrl(1)) { wait(1.0); } } diff --git a/tests/unit/scenario.h b/tests/unit/scenario.h index fff4d9619..195e6fc3a 100644 --- a/tests/unit/scenario.h +++ b/tests/unit/scenario.h @@ -17,7 +17,7 @@ namespace test { // scenario.add("elf_v1/21we-a", 1).add("elf_v1/21we-b").add("elf_v1/21we-c"); // scenario.start_up(); // scenario.act("open left"); -// scenario.cab().OperateDoors(side::left, true); +// scenario.cab().OperateDoors(VehicleSide::left, true); // scenario.wait(10.0); // scenario.check(); class scenario { @@ -25,11 +25,11 @@ public: scenario(std::string Name, std::vector Channels, track const &Track = {0.15, 0.0, catenary_3kv}); // adds a real vehicle at the back, see consist::add() - scenario &add(std::string const &Path, int Cab = 0, int Coupling = consist::full_coupling, double Velocity = 0.0, double Gap = 0.0); + scenario &add(std::string const &Path, int Cab = 0, CouplingSet couplings = consist::full_coupling, double Velocity = 0.0, double Gap = 0.0); consist &train() { return m_train; } - TMoverParameters &vehicle(std::size_t Index) { return m_train[Index].mover(); } - TMoverParameters &cab() { return m_train[0].mover(); } + physics::Vehicle &vehicle(std::size_t Index) { return m_train[Index].physics(); } + physics::Vehicle &cab() { return m_train[0].physics(); } driven driver() { return driving(m_train); } track &line() { return m_track; } diff --git a/tests/unit/test_6dg_power_steps.cpp b/tests/unit/test_6dg_power_steps.cpp new file mode 100644 index 000000000..c3ecc2fb0 --- /dev/null +++ b/tests/unit/test_6dg_power_steps.cpp @@ -0,0 +1,219 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "drive.h" + +#include +#include + +// the 6Dg shunter as the game ships it (data/fiz/6dg_v1/6dg.json): the power demand of its universal controller +// (EIMCtrlType 3, UCList) moves in steps of 5% (UCList CtrlValStep=0.05, eu07/maszyna#412), and its diesel-electric +// drive follows the demand. the controller's positions in the 6Dg's table: 3 holds no power, 4 lowers the power +// to 0, 5 holds it, 6 raises it to 1, each at 0.15 a second after IniCDelay (0.5 s) + +using test::definition; +using test::vehicle; + +namespace { + +constexpr int no_power{3}; +constexpr int lower{4}; +constexpr int hold{5}; +constexpr int raise{6}; + +definition shipped() { + return definition::fiz("6dg_v1/6dg"); +} + +void move_to(vehicle &Loco, int const Position) { + // one notch at a time, as far as the controller goes + while (Loco->MainCtrlPos() < Position) { + if (false == Loco->IncMainCtrl(1)) { + break; + } + } + while (Loco->MainCtrlPos() > Position) { + if (false == Loco->DecMainCtrl(1)) { + break; + } + } + REQUIRE(Loco->MainCtrlPos() == Position); +} + +// the 6Dg started up (engine running), its brakes released and its direction set, its controller holding no power +void get_ready(vehicle &Loco, test::track const &Track) { + auto driven{test::driving(Loco)}; + REQUIRE(test::start_up(driven, Track)); + test::release_brakes(driven.cab); + move_to(Loco, no_power); + for (int i = 0; i < 3 && Loco->DirActive <= 0; ++i) { + Loco->DirectionForward(); + } + REQUIRE(Loco->DirActive > 0); + // the brake pipe was charged during the start-up: the brakes release slowly (about a minute), and the pressure + // switch keeps the line contactors open while the brake cylinders hold over 2 bar + for (int second = 0; second < 180 && Loco->brakes.cylinderPressure > 0.1; ++second) { + test::drive(driven, Track, 1.0); + } + REQUIRE(Loco->brakes.cylinderPressure <= 0.1); + // the line contactors close on the first position past the ones with no power, as the driver passes it + move_to(Loco, lower); + test::drive(driven, Track, 1.0); + move_to(Loco, hold); + test::drive(driven, Track, 5.0); + REQUIRE(Loco->lineBreaker.IsClosed()); // the engine running + REQUIRE(Loco->lineContactors.IsClosed()); // the line contactors closed + REQUIRE(false == Loco->SpeedCtrlUnit.IsActive); // the demand of the controller drives, not the speed control + REQUIRE(Loco->eimic == doctest::Approx(0.0)); +} + +// a tap of the controller onto the given position and back onto holding, then a second of running +void tap(vehicle &Loco, int const Position, test::track const &Track) { + move_to(Loco, Position); + Loco.step(Track); + move_to(Loco, hold); + test::drive(test::driving(Loco), Track, 1.0); +} + +// the changes of the demand while the controller stays on the given position for Seconds +std::vector changes_held(vehicle &Loco, int const Position, double const Seconds, test::track const &Track) { + std::vector changes; + move_to(Loco, Position); + auto previous{Loco->eimic}; + for (int i = 0; i < std::lround(Seconds / 0.01); ++i) { + if (Loco->SecuritySystem.is_blinking()) { + Loco->SecuritySystemReset(); // the driver acknowledging the vigilance + } + Loco.step(Track); + if (std::abs(Loco->eimic - previous) > 1e-9) { + changes.push_back(Loco->eimic - previous); + previous = Loco->eimic; + } + } + return changes; +} + +} // namespace + +TEST_CASE("6Dg: the shipped definition sets the controller's power demand in steps of 5%") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped(), 0.0, "test", 1}; + // the key as the game data has it, on the controller it acts on + REQUIRE(loco->EIMCtrlType == 3); + CHECK(loco->UniCtrlValStep() == doctest::Approx(0.05)); + // the ends of the table: raising goes up to 1, lowering down to 0, 20 steps of 0.05 between them + auto const top{loco->UniCtrlList[raise].SetCtrlVal}; + auto const bottom{loco->UniCtrlList[lower].SetCtrlVal}; + REQUIRE(top == doctest::Approx(1.0)); + REQUIRE(bottom == doctest::Approx(0.0)); + REQUIRE(loco->UniCtrlList[raise].MaxCtrlVal == doctest::Approx(top)); + REQUIRE(loco->UniCtrlList[lower].MinCtrlVal == doctest::Approx(bottom)); + auto const steps{static_cast(std::lround((top - bottom) / 0.05))}; + CHECK(steps == 20); + get_ready(loco, line); + + SUBCASE("tapped: every tap moves the demand by one step, up to the top and down to the bottom, and no further") { + auto changed{0}; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, raise, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::min(top, before + 0.05))); + CHECK(loco->eimic <= top + 1e-9); + CHECK(loco->EimicReal() == doctest::Approx(loco->eimic)); // the demand reaching the drive + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(top)); + + changed = 0; + for (int i = 1; i <= steps + 3; ++i) { + auto const before{loco->eimic}; + tap(loco, lower, line); + CAPTURE(i); + CHECK(loco->eimic == doctest::Approx(std::max(bottom, before - 0.05))); + CHECK(loco->eimic >= bottom - 1e-9); + changed += std::abs(loco->eimic - before) > 1e-9 ? 1 : 0; + } + CHECK(changed == steps); + CHECK(loco->eimic == doctest::Approx(bottom)); + } + + SUBCASE("held: the demand goes over the whole range in steps of 0.05, never in between nor past the ends") { + // 20 steps of 0.05 at 0.15 a second take under 7 s, after the initial delay + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() == static_cast(steps)); + for (auto const change : up) { + CHECK(change == doctest::Approx(0.05)); + } + CHECK(loco->eimic == doctest::Approx(top)); + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() == static_cast(steps)); + for (auto const change : down) { + CHECK(change == doctest::Approx(-0.05)); + } + CHECK(loco->eimic == doctest::Approx(bottom)); + } +} + +TEST_CASE("6Dg: the diesel-electric drive follows the stepped demand") { + test::track const line{0.15, 0.0}; + struct reading { + double demand; + double revolutions; // of the engine, after the demand is set + double force; // tractive + double power; // of the generator + double speed; // reached after the same time + }; + std::vector readings; + for (auto const taps : {5, 10, 15, 20}) { + CAPTURE(taps); + test::reseed_random(); + vehicle loco{shipped(), 0.0, "test", 1}; + get_ready(loco, line); + for (int i = 0; i < taps; ++i) { + move_to(loco, raise); + loco.step(line); + move_to(loco, hold); + loco.step(line); + } + REQUIRE(loco->eimic == doctest::Approx(0.05 * taps)); + REQUIRE(loco->EimicReal() == doctest::Approx(0.05 * taps)); + test::drive(test::driving(loco), line, 10.0); + readings.emplace_back(loco->EimicReal(), loco->enrot, std::abs(loco->Ft()), loco->EnginePower, std::abs(loco.speed())); + } + // at 0.25, 0.5, 0.75 and 1: the engine at 897, 1198, 1499 and (still running up to) 1800 rpm as the WWList table + // gives, about 28, 37, 48 and 59 kN, 87, 261, 445 and 663 kW, 14, 24, 28 and 30 km/h + for (std::size_t i = 1; i < readings.size(); ++i) { + CAPTURE(i); + INFO("demand " << readings[i].demand << ": " << readings[i].revolutions * 60.0 << " rpm, " << readings[i].force << " N, " << readings[i].power << " kW, " << readings[i].speed + << " km/h; before it " << readings[i - 1].revolutions * 60.0 << " rpm, " << readings[i - 1].force << " N, " << readings[i - 1].power << " kW, " + << readings[i - 1].speed << " km/h"); + CHECK(readings[i].demand > readings[i - 1].demand); + CHECK(readings[i].revolutions > readings[i - 1].revolutions); + CHECK(readings[i].force > readings[i - 1].force); + CHECK(readings[i].power > readings[i - 1].power); + CHECK(readings[i].speed > readings[i - 1].speed); + } +} + +TEST_CASE("6Dg: without CtrlValStep the demand moves continuously between the rows of the table, as before") { + test::track const line{0.15, 0.0}; + vehicle loco{shipped().remove("UCList", "CtrlValStep"), 0.0, "test", 1}; + REQUIRE(loco->UniCtrlValStep() == 0.0); + get_ready(loco, line); + // a tap moves it by 0.01 only + tap(loco, raise, line); + CHECK(loco->eimic == doctest::Approx(0.01)); + // held, it goes on at the row's 0.15 a second after the initial delay, a little every step + auto const up{changes_held(loco, raise, 12.0, line)}; + CHECK(up.size() > 100); + for (auto const change : up) { + CHECK(change > 0.0); + CHECK(change < 0.05 - 1e-6); + } + CHECK(loco->eimic == doctest::Approx(1.0)); // up to the top of the table, as with the steps + auto const down{changes_held(loco, lower, 12.0, line)}; + CHECK(down.size() > 100); + CHECK(loco->eimic == doctest::Approx(0.0)); +} diff --git a/tests/unit/test_ai_hints.cpp b/tests/unit/test_ai_hints.cpp index d01e421c9..e23a9bf36 100644 --- a/tests/unit/test_ai_hints.cpp +++ b/tests/unit/test_ai_hints.cpp @@ -10,8 +10,8 @@ using test::vehicle; TEST_CASE("ai hints: without the AI section the pantographs follow the built-in logic") { vehicle wagon{definition::load("wagon")}; - CHECK(wagon->AIHintPantstate == 0); - CHECK(wagon->AIHintShuntPantstate == 0); + CHECK(wagon->AIHintPantstate() == 0); + CHECK(wagon->AIHintShuntPantstate() == 0); CHECK(wagon->AIHintPantUpIfIdle); } @@ -19,13 +19,13 @@ TEST_CASE("ai hints: the suggested pantograph setup for shunting is read apart f // eu07/maszyna#461: so the ET41 doesn't shunt with all of its four pantographs up vehicle shunting{definition::load("wagon").set("AI", "Pantstate", 1).set("AI", "ShuntPantstate", 2)}; - CHECK(shunting->AIHintPantstate == 1); - CHECK(shunting->AIHintShuntPantstate == 2); + CHECK(shunting->AIHintPantstate() == 1); + CHECK(shunting->AIHintShuntPantstate() == 2); } TEST_CASE("ai hints: a .fiz with the setup for train mode only has none for shunting") { vehicle train{definition::load("wagon").set("AI", "Pantstate", 3)}; - CHECK(train->AIHintPantstate == 3); - CHECK(train->AIHintShuntPantstate == 0); + CHECK(train->AIHintPantstate() == 3); + CHECK(train->AIHintShuntPantstate() == 0); } diff --git a/tests/unit/test_ai_power.cpp b/tests/unit/test_ai_power.cpp new file mode 100644 index 000000000..330f09e0a --- /dev/null +++ b/tests/unit/test_ai_power.cpp @@ -0,0 +1,105 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/aipower.h" + +// the AI driver of an electric vehicle standing with its pantographs up and no voltage at them: what it makes of +// it, and when it tells of it in the log (eu07/maszyna#421) + +namespace { + +using ai_power::stall; + +// standing with the pantographs up, past the end of the overhead wire +ai_power::state past_the_wire() { + ai_power::state state; + state.collector = true; + state.power = false; + state.standing = true; + state.pantographs_up = true; + state.wire = false; + return state; +} + +} // namespace + +TEST_CASE("ai power: standing with the pantographs up and no wire above them is a stall") { + CHECK(ai_power::check(past_the_wire()) == stall::no_wire); +} + +TEST_CASE("ai power: a wire above the raised pantographs which carries no voltage is told apart") { + auto state{past_the_wire()}; + state.wire = true; + + CHECK(ai_power::check(state) == stall::no_voltage); +} + +TEST_CASE("ai power: with the voltage there, or without a pantograph to take it, there is nothing to tell") { + auto powered{past_the_wire()}; + powered.power = true; // at the pantographs, or from the rest of the train through its high voltage cable + auto diesel{past_the_wire()}; + diesel.collector = false; + + CHECK(ai_power::check(powered) == stall::not_stalled); + CHECK(ai_power::check(diesel) == stall::not_stalled); +} + +TEST_CASE("ai power: moving, or the pantographs not up yet, it only waits") { + auto moving{past_the_wire()}; + moving.standing = false; // coasting through a gap of the wire, say + auto rising{past_the_wire()}; + rising.pantographs_up = false; // the air for the pantographs still being pumped up + + CHECK(ai_power::check(moving) == stall::waiting); + CHECK(ai_power::check(rising) == stall::waiting); +} + +TEST_CASE("ai power: a stall is reported once it lasted report_delay, and only once") { + ai_power::reporter reporter; + + CHECK_FALSE(reporter.update(stall::no_wire, 100.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 100.0 + ai_power::report_delay - 0.5).has_value()); + auto const report{reporter.update(stall::no_wire, 100.0 + ai_power::report_delay)}; + REQUIRE(report.has_value()); + CHECK(*report == stall::no_wire); + // the driver keeps trying to prepare the vehicle, without telling of it again + CHECK_FALSE(reporter.update(stall::no_wire, 100.0 + ai_power::report_delay + 1.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 1000.0).has_value()); +} + +TEST_CASE("ai power: the voltage coming back ends the stall, the next one is reported again") { + ai_power::reporter reporter; + reporter.update(stall::no_wire, 0.0); + REQUIRE(reporter.update(stall::no_wire, ai_power::report_delay).has_value()); + + // towed back under the wire: the vehicle gets prepared + CHECK_FALSE(reporter.update(stall::not_stalled, 100.0).has_value()); + // and later stands without voltage again, under a wire switched off this time + CHECK_FALSE(reporter.update(stall::no_voltage, 200.0).has_value()); + auto const report{reporter.update(stall::no_voltage, 200.0 + ai_power::report_delay)}; + REQUIRE(report.has_value()); + CHECK(*report == stall::no_voltage); +} + +TEST_CASE("ai power: moving or lowering the pantographs restarts the count but doesn't end a reported stall") { + ai_power::reporter reporter; + reporter.update(stall::no_wire, 0.0); + // the vehicle moves before the stall is reported: the count starts again once it stands + CHECK_FALSE(reporter.update(stall::waiting, 20.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 25.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 25.0 + ai_power::report_delay - 1.0).has_value()); + REQUIRE(reporter.update(stall::no_wire, 25.0 + ai_power::report_delay).has_value()); + // still with no voltage, the vehicle moved (pushed a bit) and stands again: no second report + CHECK_FALSE(reporter.update(stall::waiting, 100.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 110.0).has_value()); + CHECK_FALSE(reporter.update(stall::no_wire, 110.0 + 2.0 * ai_power::report_delay).has_value()); +} + +TEST_CASE("ai power: the report names the vehicle, where it stands and why") { + auto const nowire{ai_power::message(stall::no_wire, "et21-367", {1817.4, 0.38, 4785.94})}; + auto const novoltage{ai_power::message(stall::no_voltage, "et21-367", {1817.4, 0.38, 4785.94})}; + + CHECK(nowire == "AI [et21-367]: can't start, no overhead wire above its raised pantographs (at 1817.40, 0.38, 4785.94); it waits for the voltage"); + CHECK(novoltage.find("no voltage in the overhead wire") != std::string::npos); + CHECK(novoltage.find("et21-367") != std::string::npos); +} diff --git a/tests/unit/test_ai_wire.cpp b/tests/unit/test_ai_wire.cpp new file mode 100644 index 000000000..070f8618f --- /dev/null +++ b/tests/unit/test_ai_wire.cpp @@ -0,0 +1,254 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/aiwire.h" + +#include +#include +#include + +// where the overhead wire is for the AI driver (vehicle/aiwire.h): a pantograph against a span of the wire, and how far +// short of its target a train stops to keep its pantograph under the wire. the scene query over these +// (basic_region::wire_over) needs the scene, which the unit tests don't link + +namespace { + +// a vehicle running along +z on level track, the pantograph's base point 4 m above the origin +glm::dvec3 const front{0.0, 0.0, 1.0}; +glm::dvec3 const up{0.0, 1.0, 0.0}; +glm::dvec3 const left{1.0, 0.0, 0.0}; +glm::dvec3 const pantograph{0.0, 4.0, 0.0}; +double const halfwidth{0.5}; + +// a 100 m span along the track, at height Height and Offset to the side, its middle at Middle along the track +ai_wire::contact along(double const Offset, double const Height, double const Middle = 0.0) { + return ai_wire::span_contact({Offset, Height, Middle - 50.0}, {0.0, 0.0, 100.0}, pantograph, front, up, left, + halfwidth); +} + +// the wire over the route up to Last metres from the head of the train +auto wire_to(double const Last) { + return [Last](double const Distance) { return Distance <= Last; }; +} + +} // namespace + +TEST_CASE("ai wire: a span centred over the pantograph is on the slide") { + auto const contact{along(0.0, 6.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(2.0)); + CHECK(contact.horizontal == doctest::Approx(-halfwidth)); + CHECK(ai_wire::reaches(contact, 1.0, 3.0)); +} + +TEST_CASE("ai wire: a span at the very edge of the slide still touches it, one beyond it doesn't") { + auto const edge{along(halfwidth, 6.0)}; + CHECK(edge.horizontal == doctest::Approx(0.0)); + CHECK(ai_wire::reaches(edge, 1.0, 3.0)); + // either side + CHECK(ai_wire::reaches(along(-halfwidth, 6.0), 1.0, 3.0)); + + auto const beyond{along(halfwidth + 0.1, 6.0)}; + CHECK(beyond.within); + CHECK(beyond.horizontal == doctest::Approx(0.1)); + CHECK_FALSE(ai_wire::reaches(beyond, 1.0, 3.0)); +} + +TEST_CASE("ai wire: the wire is reached only within the given heights") { + auto const contact{along(0.0, 6.0)}; + + CHECK_FALSE(ai_wire::reaches(contact, 3.0, 9.0)); // too low: below the lowest height + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 1.5)); // too high: a bridge's wire above the line + CHECK(ai_wire::reaches(contact, 2.0, 2.0)); // the limits are included +} + +TEST_CASE("ai wire: a span below the pantograph is crossed but out of reach") { + auto const contact{along(0.0, 3.0)}; + + CHECK(contact.within); + CHECK(contact.vertical == doctest::Approx(-1.0)); + CHECK_FALSE(ai_wire::reaches(contact, 0.0, 9.0)); +} + +TEST_CASE("ai wire: a span ahead of or behind the pantograph isn't crossed") { + auto const ahead{along(0.0, 6.0, 60.0)}; + CHECK_FALSE(ahead.within); + CHECK_FALSE(ai_wire::reaches(ahead, 0.0, 9.0)); + + CHECK_FALSE(along(0.0, 6.0, -60.0).within); + // the ends of the span have the tolerance of the vehicles: 0.001 of the span's length + CHECK(along(0.0, 6.0, 50.05).within); + CHECK(along(0.0, 6.0, -50.05).within); + CHECK_FALSE(along(0.0, 6.0, 50.2).within); +} + +TEST_CASE("ai wire: a span skewed against the track is met where it crosses the plane of the pantograph") { + // the zigzag of the wire: from 0.3 m to the right to 0.3 m to the left over 100 m + auto const zigzag{ai_wire::span_contact({-0.3, 6.0, -50.0}, {0.6, 0.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(zigzag.within); + CHECK(zigzag.horizontal == doctest::Approx(0.15 - halfwidth)); + CHECK(ai_wire::reaches(zigzag, 1.0, 3.0)); + + // a sloping span from a tunnel portal, 1 m lower at its far end: the height where the plane crosses it + auto const sloping{ai_wire::span_contact({0.0, 6.0, -50.0}, {0.0, -1.0, 100.0}, pantograph + glm::dvec3{0, 0, 25.0}, + front, up, left, halfwidth)}; + CHECK(sloping.vertical == doctest::Approx(1.25)); + + // a span of a wire crossing the line at a right angle lies in the plane of the pantograph over the track, and is + // out of reach a step along the track (the division by zero trap) + auto const across{ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph, front, up, left, halfwidth)}; + CHECK(across.within); + CHECK(std::isfinite(across.vertical)); + CHECK_FALSE(ai_wire::reaches(across, 0.0, 9.0)); // its end, 5 m to the side + CHECK_FALSE(ai_wire::span_contact({-5.0, 6.0, 0.0}, {10.0, 0.0, 0.0}, pantograph + glm::dvec3{0, 0, 1.0}, front, up, + left, halfwidth) + .within); +} + +TEST_CASE("ai wire: the direction of travel doesn't change what the pantograph meets") { + auto const forward{along(0.3, 6.0)}; + auto const backward{ai_wire::span_contact({0.3, 6.0, -50.0}, {0.0, 0.0, 100.0}, pantograph, -front, up, -left, + halfwidth)}; + + CHECK(backward.within); + CHECK(backward.vertical == forward.vertical); + CHECK(backward.horizontal == forward.horizontal); +} + +TEST_CASE("ai wire: the span test gives the very numbers of the code the vehicles had before it was moved here") { + // the math of basic_cell::update_traction before it called span_contact, as it was there + struct legacy { + bool within; + double vertical; + double horizontal; + }; + auto const legacy_contact{[](glm::dvec3 const &pPoint1, glm::dvec3 const &vParametric, + glm::dvec3 const &pantographposition, glm::dvec3 const &vFront, glm::dvec3 const &vUp, + glm::dvec3 const &vLeft, double const fWidth) { + auto const paramfrontdot = glm::dot(vParametric, vFront); + auto const fRaParam = + -(glm::dot(pPoint1, vFront) - glm::dot(pantographposition, vFront)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + if (fRaParam < -0.001 || fRaParam > 1.001) { + return legacy{false, 0.0, 0.0}; + } + auto const vStyk = pPoint1 + fRaParam * vParametric; + auto const vGdzie = vStyk - pantographposition; + auto const fVertical = glm::dot(vGdzie, vUp); + auto const fHorizontal = std::abs(glm::dot(vGdzie, vLeft)) - fWidth; + return legacy{true, fVertical, fHorizontal}; + }}; + + // pseudo-random vehicles and spans around a point far from the origin, as in a real scenery + std::uint32_t seed{12345}; + auto const next{[&seed](double const Low, double const High) { + seed = seed * 1664525u + 1013904223u; + return Low + (High - Low) * (seed >> 8) / double(1u << 24); + }}; + int within{0}; + for (int sample = 0; sample < 2000; ++sample) { + auto const heading{next(0.0, 6.283185307179586)}; + auto const cant{next(-0.1, 0.1)}; + glm::dvec3 const vFront{std::sin(heading), next(-0.03, 0.03), std::cos(heading)}; + glm::dvec3 const vUp{std::sin(cant) * std::cos(heading), std::cos(cant), -std::sin(cant) * std::sin(heading)}; + auto const vLeft{glm::cross(vUp, vFront)}; + glm::dvec3 const position{next(-20000.0, 20000.0), next(100.0, 300.0), next(-20000.0, 20000.0)}; + auto const pantographposition{position + vUp * 4.2}; + auto const spanheading{heading + next(-0.05, 0.05)}; + glm::dvec3 const vParametric{60.0 * std::sin(spanheading), next(-0.5, 0.5), 60.0 * std::cos(spanheading)}; + auto const pPoint1{position + glm::dvec3{next(-1.0, 1.0), next(5.0, 7.0), next(-1.0, 1.0)} - vParametric * next(-0.2, 1.2)}; + auto const fWidth{next(0.4, 0.7)}; + + auto const old{legacy_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + auto const now{ai_wire::span_contact(pPoint1, vParametric, pantographposition, vFront, vUp, vLeft, fWidth)}; + CAPTURE(sample); + REQUIRE(now.within == old.within); + if (old.within) { + ++within; + // bit for bit + REQUIRE(now.vertical == old.vertical); + REQUIRE(now.horizontal == old.horizontal); + } + } + // both kinds were tried + CHECK(within > 200); + CHECK(within < 1800); +} + +TEST_CASE("ai wire: a stop with the wire over the pantograph stays where it is") { + auto const everywhere{[](double) { return true; }}; + CHECK(ai_wire::wire_shortfall(everywhere, 20.0, 130.0) == 0.0); + + // the wire ends between the pantographs: the rear one the train relies on is under it, with the margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(118.0), 20.0, 130.0) == 0.0); + // gaps behind the pantograph don't matter + auto const gap_behind{[](double const Distance) { return Distance <= 90.0 || Distance >= 95.0; }}; + CHECK(ai_wire::wire_shortfall(gap_behind, 20.0, 130.0) == 0.0); +} + +TEST_CASE("ai wire: a stop past the end of the wire is moved back to put the pantograph under the wire") { + // the head stops at 130 m, the pantograph 20 m behind it at 110 m; the wire ends at 100 m. 2 m steps back to the + // first place with the wire over the pantograph and 3 m ahead of it: 96 m + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0) == doctest::Approx(14.0)); + // the wire ends right at the pantograph: no margin ahead + CHECK(ai_wire::wire_shortfall(wire_to(110.0), 20.0, 130.0) == doctest::Approx(4.0)); + // a gap in the wire at the pantograph: the stop goes before the gap + auto const gap{[](double const Distance) { return Distance <= 107.0 || Distance >= 112.0; }}; + CHECK(ai_wire::wire_shortfall(gap, 20.0, 130.0) == doctest::Approx(6.0)); +} + +TEST_CASE("ai wire: the margin of wire ahead of the pantograph") { + // exactly the margin ahead: fine + CHECK(ai_wire::wire_shortfall(wire_to(113.0), 20.0, 130.0) == 0.0); + // a little less: one step back + CHECK(ai_wire::wire_shortfall(wire_to(112.9), 20.0, 130.0) == doctest::Approx(2.0)); + // other margins and steps + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 0.0, 1.0) == doctest::Approx(10.0)); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 5.0, 1.0) == doctest::Approx(15.0)); +} + +TEST_CASE("ai wire: without the wire within the walk back the stop stays where it is") { + auto const nowhere{[](double) { return false; }}; + CHECK(ai_wire::wire_shortfall(nowhere, 20.0, 130.0) == 0.0); + + // the pantograph at 110 m: the wire ends more than 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-200.0), 20.0, 130.0) == 0.0); + // the last place looked at is 300 m back + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0) == doctest::Approx(300.0)); + CHECK(ai_wire::wire_shortfall(wire_to(-187.0), 20.0, 130.0, 3.0, 2.0, 298.0) == 0.0); +} + +TEST_CASE("ai wire: a stop without a coverage or a step to walk with stays where it is") { + CHECK(ai_wire::wire_shortfall({}, 20.0, 130.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, 0.0) == 0.0); + CHECK(ai_wire::wire_shortfall(wire_to(100.0), 20.0, 130.0, 3.0, -2.0) == 0.0); +} + +TEST_CASE("ai wire: the walk back asks for the places the 2 m steps give") { + std::vector asked; + auto const recording{[&asked](double const Distance) { + asked.push_back(Distance); + return Distance <= 100.0; + }}; + ai_wire::wire_shortfall(recording, 20.0, 130.0); + + // the pantograph's place and the margin ahead, then the steps back; the margin is asked only where the place is + // under the wire + std::vector const expected{110.0, 108.0, 106.0, 104.0, 102.0, 100.0, 103.0, 98.0, 101.0, 96.0, 99.0}; + CHECK(asked == expected); +} + +TEST_CASE("ai wire: which stops keep the pantograph under the wire") { + using ai_wire::stop_kind; + // the stops of a train that runs with the wire + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::track_end)); + CHECK(ai_wire::stops_under_wire(true, true, false, stop_kind::timetable_stop)); + // a signal is a wait, the vehicle to couple to may stand without the wire + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::signal)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, false, stop_kind::coupling)); + // without a current collector, with the voltage made up, where the scenery says to coast or lower the pantographs + CHECK_FALSE(ai_wire::stops_under_wire(false, true, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, false, false, stop_kind::track_end)); + CHECK_FALSE(ai_wire::stops_under_wire(true, true, true, stop_kind::timetable_stop)); +} diff --git a/tests/unit/test_asciiname.cpp b/tests/unit/test_asciiname.cpp new file mode 100644 index 000000000..166947350 --- /dev/null +++ b/tests/unit/test_asciiname.cpp @@ -0,0 +1,40 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "utilities/asciiname.h" + +TEST_CASE("ascii name: plain names stay as they are") +{ + CHECK(ascii_name::plain("tor_01-a")); + CHECK(ascii_name::fold("tor_01-a") == "tor_01-a"); + CHECK(ascii_name::fold("ToR") == "tor"); +} + +TEST_CASE("ascii name: the Polish letters in UTF-8 lose their marks") +{ + auto const name{std::string{"\xC5\x81\xC4\x85\x6B\x61_\xC5\xBC\xC3\xB3\xC5\x82\x74\xC4\x99_\xC5\x9B\xC4\x87\xC5\x84\xC5\xBA"}}; // Łąka_żółtę_śćńź + CHECK_FALSE(ascii_name::plain(name)); + CHECK(ascii_name::fold(name) == "laka_zolte_scnz"); + CHECK(ascii_name::readable(name) == name); +} + +TEST_CASE("ascii name: the Polish letters in Windows-1250 lose their marks") +{ + // ąćęłńóśźż ĄĆĘŁŃÓŚŹŻ + auto const name{std::string{"\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF_\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF"}}; + CHECK(ascii_name::fold(name) == "acelnoszz_acelnoszz"); + CHECK(ascii_name::readable(name) == "\xC4\x85\xC4\x87\xC4\x99\xC5\x82\xC5\x84\xC3\xB3\xC5\x9B\xC5\xBA\xC5\xBC_\xC4\x84\xC4\x86\xC4\x98\xC5\x81\xC5\x83\xC3\x93\xC5\x9A\xC5\xB9\xC5\xBB"); +} + +TEST_CASE("ascii name: other letters with marks, and whatever else isn't ASCII") +{ + CHECK(ascii_name::fold("Stra\xC3\x9F" "e") == "strasse"); // Straße + CHECK(ascii_name::fold("\xC4\x8C" "esk\xC3\xA1") == "ceska"); // Česká + CHECK(ascii_name::fold("\xC3\x86" "r\xC3\xB8") == "aero"); // Ærø + CHECK(ascii_name::fold("tor\xE2\x82\xAC" "1") == "tor_1"); // the euro sign + CHECK(ascii_name::fold("\xD0\xBF\xD1\x83\xD1\x82\xD1\x8C") == "____"); // путь + CHECK(ascii_name::fold("x\x81y") == "x_y"); // a byte the code page doesn't have + for (int byte = 0x80; byte < 0x100; ++byte) + CHECK(ascii_name::plain(ascii_name::fold(std::string(1, static_cast(byte))))); +} diff --git a/tests/unit/test_audio_output.cpp b/tests/unit/test_audio_output.cpp new file mode 100644 index 000000000..a2319b960 --- /dev/null +++ b/tests/unit/test_audio_output.cpp @@ -0,0 +1,259 @@ +#include "stdafx.h" + +#include "doctest.h" + +#include "audio/outputfollow.h" + +// the following of the audio output: when the renderer is told to open its playback device again + +namespace +{ + +using audio::output_follower; +using action = audio::output_follower::action; +using std::chrono::milliseconds; + +// a follower with a device that answers the checks of its connection as told, and counts them +struct output_rig +{ + output_follower follower; + output_follower::clock::time_point now{}; + bool connected{true}; + int checks{0}; + + explicit output_rig(bool const Pinned = false, bool const Fallback = false) + { + follower.start(Pinned, Fallback, now); + } + action step(milliseconds const Elapsed, unsigned const Events = 0u) + { + now += Elapsed; + return follower.update(Events, now, [this]() { + ++checks; + return connected; + }); + } +}; + +} // namespace + +TEST_CASE("audio output: a working device is left alone and checked about once a second") +{ + output_rig rig; + for (int frame = 0; frame < 300; ++frame) // 3 s at 100 fps + CHECK(rig.step(milliseconds{10}) == action::none); + CHECK(rig.checks == 3); +} + +TEST_CASE("audio output: a lost connection is found without any event from the system") +{ + // the stream invalidated, the device not removed and the default output unchanged: nothing is reported + output_rig rig; + rig.connected = false; + CHECK(rig.step(milliseconds{500}) == action::none); // not yet checked + CHECK(rig.step(milliseconds{500}) == action::reopen); + CHECK(rig.checks == 1); +} + +TEST_CASE("audio output: a removed device has the connection checked at once") +{ + output_rig rig; + CHECK(rig.step(milliseconds{10}, output_follower::device_removed) == action::none); // another device was removed + CHECK(rig.checks == 1); + rig.connected = false; + CHECK(rig.step(milliseconds{10}, output_follower::device_removed) == action::reopen); +} + +TEST_CASE("audio output: a change of the default output is followed, the arrival of some device is not") +{ + output_rig rig; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::reopen); + CHECK(rig.checks == 0); +} + +TEST_CASE("audio output: opening that failed is tried again, with growing delays and at once on any event") +{ + output_rig rig; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); // the first failure in a row is the one to log + CHECK(rig.follower.lost()); + + // the following attempts come after 0.5, 1, 2, 4 and then every 4 s + for (auto const delay : {500, 1000, 2000, 4000, 4000}) + { + CHECK(rig.step(milliseconds{delay - 1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + CHECK_FALSE(rig.follower.failed(rig.now)); + } + // whatever the system reports may be the output coming back: the next attempt at once, but not sooner than + // event_retry_min after the last one, as a device coming reports a burst of events + CHECK(rig.step(milliseconds{1}, output_follower::device_added) == action::none); + CHECK(rig.step(output_follower::event_retry_min - milliseconds{2}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); // the event brought the attempt forward and wasn't forgotten + CHECK_FALSE(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::event_retry_min, output_follower::default_changed) == action::reopen); + + // a lost device isn't asked about its connection, it is opened again + CHECK(rig.checks == 1); + + rig.connected = true; + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.lost()); + CHECK(rig.step(milliseconds{10}) == action::none); + // and the next loss starts from the short delay, with its own line in the log + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::retry_min) == action::reopen); +} + +TEST_CASE("audio output: a device set in eu07.ini doesn't follow the default output while it works") +{ + output_rig rig{true}; + CHECK_FALSE(rig.follower.follows_default()); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::none); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); + // but it is opened again when it loses the connection + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); +} + +TEST_CASE("audio output: the default output standing in for the device set in eu07.ini") +{ + output_rig rig{true}; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + // the device set is gone, the default one was opened instead + rig.connected = true; + rig.follower.succeeded(true, rig.now); + CHECK(rig.follower.fallback()); + CHECK(rig.follower.follows_default()); + + // the default output is followed for as long as it stands in + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::reopen); + rig.follower.succeeded(true, rig.now); + // and a device that appears may be the one set + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + CHECK(rig.follower.fallback()); // it wasn't, nothing changes + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::default_changed) == action::none); +} + +TEST_CASE("audio output: the game started on the default output, the device set in eu07.ini being absent") +{ + output_rig rig{true, true}; + CHECK(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); +} + +TEST_CASE("audio output: without a device set in eu07.ini there is nothing to fall back from") +{ + output_rig rig{false, true}; + CHECK_FALSE(rig.follower.fallback()); + rig.follower.succeeded(true, rig.now); + CHECK_FALSE(rig.follower.fallback()); + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::none); +} + +TEST_CASE("audio output: after a minute without an output the attempts thin out, the events still count at once") +{ + output_rig rig; + rig.connected = false; + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + auto const loststart{rig.now}; + + // 0.5, 1, 2, then 4 s until a minute has gone by since the first failure + while (rig.now - loststart < output_follower::retry_late_after) + { + auto const before{rig.now}; + auto next{rig.step(milliseconds{50})}; + while (next != action::reopen) + next = rig.step(milliseconds{50}); + CHECK(rig.now - before <= output_follower::retry_max); + rig.follower.failed(rig.now); + } + // the failure past the minute puts the next attempt 30 s away + CHECK(rig.step(output_follower::retry_late - milliseconds{1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + rig.follower.failed(rig.now); + CHECK(rig.step(output_follower::retry_late - milliseconds{1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::reopen); + rig.follower.failed(rig.now); + + // a device coming has the attempt made at once still + CHECK(rig.step(output_follower::event_retry_min, output_follower::device_added) == action::reopen); + rig.follower.failed(rig.now); + + // and the next loss starts from the short delays again + rig.follower.succeeded(false, rig.now); + CHECK(rig.step(output_follower::check_interval) == action::reopen); + CHECK(rig.follower.failed(rig.now)); + CHECK(rig.step(output_follower::retry_min) == action::reopen); +} + +TEST_CASE("audio output: a move back to the device set in eu07.ini that didn't work out is tried again 3 times") +{ + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); // reported before it was ready, say + + // again after 1, 2 and 4 s + for (auto const delay : {1000, 2000, 4000}) + { + CHECK(rig.step(milliseconds{delay - 1}) == action::none); + CHECK(rig.step(milliseconds{1}) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + } + // then not any more: a device that never works doesn't break the sound every few seconds + for (int second = 0; second < 60; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); + + // until a device appears again, which starts a fresh round + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + CHECK(rig.step(output_follower::restore_retry_min) == action::restore_preferred); + + // the device works this time: nothing more to try + rig.follower.succeeded(false, rig.now); + CHECK_FALSE(rig.follower.fallback()); + for (int second = 0; second < 10; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +} + +TEST_CASE("audio output: the default output opened anew after a failed move back keeps the round of attempts") +{ + // the device set opened but didn't start, and the library had let go of the default output before: that's opened + // again, and the move back is still retried, with no endless round + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + for (int attempt = 0; attempt < output_follower::restore_retries; ++attempt) + { + rig.follower.succeeded(true, rig.now); + rig.follower.restore_failed(rig.now); + CHECK(rig.follower.fallback()); + action next{action::none}; + for (int frame = 0; frame < 1000 && next == action::none; ++frame) + next = rig.step(milliseconds{10}); + CHECK(next == action::restore_preferred); + } + rig.follower.succeeded(true, rig.now); + rig.follower.restore_failed(rig.now); + for (int second = 0; second < 60; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +} + +TEST_CASE("audio output: the settings applied drop a pending move back") +{ + output_rig rig{true, true}; + CHECK(rig.step(milliseconds{10}, output_follower::device_added) == action::restore_preferred); + rig.follower.restore_failed(rig.now); + // the settings applied: the device set may be another one now, a pending attempt is dropped + rig.follower.start(true, true, rig.now); + for (int second = 0; second < 10; ++second) + CHECK(rig.step(milliseconds{1000}) == action::none); +} diff --git a/tests/unit/test_auxiliaries.cpp b/tests/unit/test_auxiliaries.cpp index bb823a4cf..2b6ad7ed8 100644 --- a/tests/unit/test_auxiliaries.cpp +++ b/tests/unit/test_auxiliaries.cpp @@ -14,15 +14,15 @@ namespace { std::vector auxiliaries() { return { - {"BatteryVoltage", [](auto const &M) { return M.BatteryVoltage; }}, - {"Battery", [](auto const &M) { return M.Battery ? 1.0 : 0.0; }}, - {"ConverterFlag", [](auto const &M) { return M.ConverterFlag ? 1.0 : 0.0; }}, - {"Power110vIsAvailable", [](auto const &M) { return M.Power110vIsAvailable ? 1.0 : 0.0; }}, - {"PantPress", [](auto const &M) { return M.PantPress; }}, - {"PantVolume", [](auto const &M) { return M.PantVolume; }}, - {"PantCompFlag", [](auto const &M) { return M.PantCompFlag ? 1.0 : 0.0; }}, - {"PantPressSwitchActive", [](auto const &M) { return M.PantPressSwitchActive ? 1.0 : 0.0; }}, - {"PantPressLockActive", [](auto const &M) { return M.PantPressLockActive ? 1.0 : 0.0; }}, + {"BatteryVoltage", [](auto const &M) { return M.lowVoltage.BatteryVoltage(); }}, + {"Battery", [](auto const &M) { return M.lowVoltage.IsBatteryOn() ? 1.0 : 0.0; }}, + {"ConverterFlag", [](auto const &M) { return M.converter.IsRunning() ? 1.0 : 0.0; }}, + {"Power110vIsAvailable", [](auto const &M) { return M.lowVoltage.Is110vAvailable() ? 1.0 : 0.0; }}, + {"PantPress", [](auto const &M) { return M.pantographAir.Pressure(); }}, + {"PantVolume", [](auto const &M) { return M.pantographAir.Volume(); }}, + {"PantCompFlag", [](auto const &M) { return M.pantographAir.IsCompressorRunning() ? 1.0 : 0.0; }}, + {"PantPressSwitchActive", [](auto const &M) { return M.pantographAir.IsPressureSwitchPrimed() ? 1.0 : 0.0; }}, + {"PantPressLockActive", [](auto const &M) { return M.pantographAir.IsPressureLockActive() ? 1.0 : 0.0; }}, }; } @@ -35,21 +35,21 @@ TEST_CASE("auxiliaries: the battery drained by the lights and the pantographs' c scenario.add("4e_v1/4e", 1); REQUIRE(scenario.start_up()); auto &eu07{scenario.cab()}; - REQUIRE(eu07.BatteryVoltage == doctest::Approx(eu07.NominalBatteryVoltage)); + REQUIRE(eu07.lowVoltage.BatteryVoltage() == doctest::Approx(eu07.lowVoltage.config.nominalBatteryVoltage)); scenario.act("converter off, lights on, small compressor on"); eu07.ConverterSwitch(false); - eu07.iLights[end::front] = 1 | 2 | 4; - eu07.iLights[end::rear] = 16; - eu07.PantCompFlag = true; + eu07.SetLitLights(VehicleEnd::front, 1 | 2 | 4); + eu07.SetLitLights(VehicleEnd::rear, 16); + eu07.pantographAir.SwitchCompressor(true); scenario.wait(30.0); - CHECK(eu07.BatteryVoltage < 0.83 * eu07.NominalBatteryVoltage); - CHECK(eu07.Mains); + CHECK(eu07.lowVoltage.BatteryVoltage() < 0.83 * eu07.lowVoltage.config.nominalBatteryVoltage); + CHECK(eu07.lineBreaker.IsClosed()); scenario.wait(5000.0); - CHECK(eu07.BatteryVoltage < eu07.NominalBatteryVoltage / 1.57); - CHECK_FALSE(eu07.Mains); + CHECK(eu07.lowVoltage.BatteryVoltage() < eu07.lowVoltage.config.nominalBatteryVoltage / 1.57); + CHECK_FALSE(eu07.lineBreaker.IsClosed()); scenario.act("start up again"); CHECK_FALSE(scenario.start_up()); - CHECK(eu07.BatteryVoltage < eu07.NominalBatteryVoltage / 1.57); + CHECK(eu07.lowVoltage.BatteryVoltage() < eu07.lowVoltage.config.nominalBatteryVoltage / 1.57); scenario.check(); } @@ -61,20 +61,20 @@ TEST_CASE("auxiliaries: the battery switched off, and charged by the converter") scenario.act("converter off"); eu07.ConverterSwitch(false); scenario.wait(10.0); - auto const discharged{eu07.BatteryVoltage}; - CHECK(discharged < 0.83 * eu07.NominalBatteryVoltage); + auto const discharged{eu07.lowVoltage.BatteryVoltage()}; + CHECK(discharged < 0.83 * eu07.lowVoltage.config.nominalBatteryVoltage); // the converter charges it back at once scenario.act("converter on"); eu07.ConverterSwitch(true); scenario.wait(10.0); - CHECK(eu07.BatteryVoltage == doctest::Approx(eu07.NominalBatteryVoltage)); + CHECK(eu07.lowVoltage.BatteryVoltage() == doctest::Approx(eu07.lowVoltage.config.nominalBatteryVoltage)); // switched off, the battery falls to 90 V at once, then holds scenario.act("battery off"); eu07.MainSwitch(false); eu07.ConverterSwitch(false); eu07.BatterySwitch(false); scenario.wait(10.0); - CHECK(eu07.BatteryVoltage == doctest::Approx(discharged).epsilon(0.01)); + CHECK(eu07.lowVoltage.BatteryVoltage() == doctest::Approx(discharged).epsilon(0.01)); scenario.check(); } @@ -90,23 +90,23 @@ TEST_CASE("auxiliaries: the pantographs on their own tank, leaking until the pre auto &eu07{scenario.cab()}; // started up on the small compressor, the tank gets joined to the main reservoir, which primes the switch scenario.act("tank joined to the main reservoir"); - eu07.bPantKurek3 = true; + eu07.pantographAir.ConnectToMainReservoir(true); scenario.wait(30.0); - REQUIRE(eu07.PantPressSwitchActive); + REQUIRE(eu07.pantographAir.IsPressureSwitchPrimed()); scenario.act("tank cut off the main reservoir"); - eu07.bPantKurek3 = false; - eu07.PantCompFlag = false; + eu07.pantographAir.ConnectToMainReservoir(false); + eu07.pantographAir.SwitchCompressor(false); scenario.wait(600.0); - CHECK(eu07.PantPress < eu07.EnginePowerSource.CollectorParameters.MinPress); - CHECK_FALSE(eu07.PantPressSwitchActive); - CHECK_FALSE(eu07.Mains); + CHECK(eu07.pantographAir.Pressure() < eu07.EnginePowerSource.CollectorParameters.MinPress); + CHECK_FALSE(eu07.pantographAir.IsPressureSwitchPrimed()); + CHECK_FALSE(eu07.lineBreaker.IsClosed()); scenario.act("small compressor on"); - eu07.PantCompFlag = true; - for (int i = 0; i < 60 && eu07.PantCompFlag; ++i) { + eu07.pantographAir.SwitchCompressor(true); + for (int i = 0; i < 60 && eu07.pantographAir.IsCompressorRunning(); ++i) { scenario.wait(10.0); } - CHECK_FALSE(eu07.PantCompFlag); - CHECK(eu07.PantPress >= 4.6); // stopped at 4.8, leaking since - CHECK(eu07.PantPressSwitchActive); + CHECK_FALSE(eu07.pantographAir.IsCompressorRunning()); + CHECK(eu07.pantographAir.Pressure() >= 4.6); // stopped at 4.8, leaking since + CHECK(eu07.pantographAir.IsPressureSwitchPrimed()); scenario.check(); } diff --git a/tests/unit/test_blackbox.cpp b/tests/unit/test_blackbox.cpp index cad1920a1..77e3e55f4 100644 --- a/tests/unit/test_blackbox.cpp +++ b/tests/unit/test_blackbox.cpp @@ -439,6 +439,43 @@ TEST_CASE("blackbox: the camera and the couplings are written field by field") { } } +TEST_CASE("blackbox: a vehicle off the track is written field by field") { + std::ostringstream file; + blackbox::writer out{file}; + out.header(); + blackbox::derailment_state state; + state.time = 21.5; + state.vehicle = 6; + state.phase = blackbox::derailment_phases::at_rest; + state.cause = blackbox::derailment_causes::overturned; + state.position = {100.0, 2.5, -40.0}; + state.heading = 0.75f; + state.speed_kmh = 0.0f; + state.offset = -12.25f; + state.roll = -1.5f; + state.travelled = 87.5f; + state.lying = true; + out.derailment(state); + auto const all{records(file.str())}; + REQUIRE(all.size() == 1); + CHECK(all[0].type == blackbox::record::derailment); + reader derailment{all[0].payload}; + CHECK(derailment.get() == 21.5); + CHECK(derailment.get() == 6); + CHECK(derailment.get() == 1); + CHECK(derailment.get() == 2); + CHECK(derailment.get() == 100.0); + CHECK(derailment.get() == 2.5); + CHECK(derailment.get() == -40.0); + CHECK(derailment.get() == 0.75f); + CHECK(derailment.get() == 0.0f); + CHECK(derailment.get() == -12.25f); + CHECK(derailment.get() == -1.5f); + CHECK(derailment.get() == 87.5f); + CHECK(derailment.get() == 1); + CHECK(derailment.done()); +} + TEST_CASE("blackbox: a look at the vehicles takes 25 bytes a vehicle") { std::ostringstream file; blackbox::writer out{file}; 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_cycle.cpp b/tests/unit/test_brake_cycle.cpp index 1dc5a84c1..42e0fc2c5 100644 --- a/tests/unit/test_brake_cycle.cpp +++ b/tests/unit/test_brake_cycle.cpp @@ -4,7 +4,7 @@ #include "golden.h" #include "real_vehicles.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include #include @@ -39,7 +39,7 @@ std::map> run_cycle(vehicle &Vehicle, test::tra Trace.mark(stage.name); Vehicle.hold_brake_pipe(stage.pipe); Vehicle.run(stage.seconds); - cylinders[stage.name] = Vehicle->BrakePress; + cylinders[stage.name] = Vehicle->brakes.cylinderPressure; } return cylinders; } @@ -79,7 +79,7 @@ TEST_CASE("brake cycle: every brake delay setting of the real vehicles") { test::reseed_random(); vehicle probe{definition::fiz(path)}; for (auto const delay : {bdelay_G, bdelay_P, bdelay_R, bdelay_R + bdelay_M, bdelay_G + bdelay_M}) { - if ((probe->BrakeDelays & delay) != delay || delay == probe->BrakeDelayFlag) { + if ((probe->brakes.config.availableDelays & delay) != delay || delay == probe->brakes.delaySetting) { continue; } CAPTURE(delay); @@ -93,7 +93,7 @@ TEST_CASE("brake cycle: every brake delay setting of the real vehicles") { trace.mark(stage.name); real.hold_brake_pipe(stage.pipe); real.run(stage.seconds); - cylinders[stage.name] = real->BrakePress; + cylinders[stage.name] = real->brakes.cylinderPressure; } // every setting brakes in half a minute and releases in a minute CHECK(cylinders["full service"] > 1.0); @@ -136,7 +136,7 @@ TEST_CASE("brake cycle: the rapid setting at speed, the anti-slip brake and the vehicle real{definition::fiz(path), 160.0}; real->DecManualBrakeLevel(ManualBrakePosNo); real->BrakeDelaySwitch(delay); // false when already set - REQUIRE(real->BrakeDelayFlag == delay); + REQUIRE(real->brakes.delaySetting == delay); using test::channels::operator+; test::trace trace{std::string{"brake cycle/at speed/"} + name, test::channels::motion() + test::channels::brakes(), 100}; real.record(trace); @@ -147,20 +147,20 @@ TEST_CASE("brake cycle: the rapid setting at speed, the anti-slip brake and the real.hold_brake_pipe(3.5); real.run(10.0); CHECK(real->Vel > 100.0); - CHECK(real->BrakePress == doctest::Approx(service).epsilon(0.01)); + CHECK(real->brakes.cylinderPressure == doctest::Approx(service).epsilon(0.01)); trace.mark("anti-slip"); - real->Hamulec->ASB(3); + real->brakes.distributor->ASB(3); real.run(2.0); - real->Hamulec->ASB(0); + real->brakes.distributor->ASB(0); real.run(3.0); trace.mark("releaser button"); - real->Hamulec->SetUniversalFlag(TUniversalBrake::ub_Release); + real->brakes.distributor->SetUniversalFlag(TUniversalBrake::ub_Release); real.run(3.0); - real->Hamulec->SetUniversalFlag(0); - CHECK((real->BrakePress < 1.0) == releases); + real->brakes.distributor->SetUniversalFlag(0); + CHECK((real->brakes.cylinderPressure < 1.0) == releases); // released for good, the pipe still at full service real.run(40.0); - CHECK((real->BrakePress < 0.1) == releases); + CHECK((real->brakes.cylinderPressure < 0.1) == releases); trace.check(); } } @@ -185,7 +185,7 @@ TEST_CASE("brake cycle: every material of the brake shoes and disks, braking a w real.hold_brake_pipe(3.5); real.run(20.0); CHECK(real->Vel < speed - 10.0); - CHECK(real->Fb > 0.0); + CHECK(real->Fb() > 0.0); trace.mark("emergency"); real.hold_brake_pipe(0.0); real.run(60.0); diff --git a/tests/unit/test_brake_handles.cpp b/tests/unit/test_brake_handles.cpp index 889beb338..98ca34336 100644 --- a/tests/unit/test_brake_handles.cpp +++ b/tests/unit/test_brake_handles.cpp @@ -6,7 +6,7 @@ #include "drive.h" #include "consist.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" using test::definition; using test::vehicle; @@ -24,7 +24,7 @@ std::vector handle_channels() { // the vehicles with a driver's brake handle bool has_handle(vehicle &Vehicle) { - return Vehicle->BrakeCtrlPosNo > 1; + return Vehicle->brakes.config.handlePositions > 1; } void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double Position, double Seconds) { @@ -35,9 +35,9 @@ void hold(vehicle &Vehicle, test::trace &Trace, std::string const &Event, double // every position of the driver's handle, recorded in the trace void every_position(vehicle &Vehicle, test::trace &Trace) { - Vehicle.hold_main_reservoir(std::max(Vehicle->MaxCompressor, 8.0)); - REQUIRE(Vehicle->Handle != nullptr); - auto &handle{*Vehicle->Handle}; + Vehicle.hold_main_reservoir(std::max(Vehicle->air.compressor.config.maxPressure, 8.0)); + REQUIRE(Vehicle->brakes.driverValve != nullptr); + auto &handle{*Vehicle->brakes.driverValve}; Vehicle.record(Trace); hold(Vehicle, Trace, "running", handle.GetPos(bh_RP), 90.0); @@ -102,16 +102,16 @@ TEST_CASE("brake handles: the local brake handle of every real vehicle") { if (false == has_handle(real)) { continue; } - real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.config.maxPressure, 8.0)); test::trace trace{"local brake/" + path, handle_channels(), 100}; real.record(trace); - REQUIRE(real->Handle != nullptr); - real->BrakeLevelSet(real->Handle->GetPos(bh_RP)); + REQUIRE(real->brakes.driverValve != nullptr); + real->BrakeLevelSet(real->brakes.driverValve->GetPos(bh_RP)); trace.mark("charge"); real.run(60.0); for (auto const position : {0.25, 0.5, 1.0, 0.5, 0.0}) { trace.mark(std::format("local {:f}", position)); - real->LocalBrakePosA = position; + real->brakes.SetIndependentPosition(position); real.run(15.0); } trace.check(); @@ -133,22 +133,22 @@ TEST_CASE("brake handles: the overload and the high pressure buttons of the MHZ vehicle real{definition, 0.0, "test", 1}; real->BatterySwitch(true); real->CabActivisation(); - real.hold_main_reservoir(std::max(real->MaxCompressor, 8.0)); + real.hold_main_reservoir(std::max(real->air.compressor.config.maxPressure, 8.0)); test::trace trace{"brake handles/buttons/" + name, handle_channels(), 100}; real.record(trace); - REQUIRE(real->Handle != nullptr); - auto &handle{*real->Handle}; + REQUIRE(real->brakes.driverValve != nullptr); + auto &handle{*real->brakes.driverValve}; driven_at(real, trace, "running", handle.GetPos(bh_RP), 60.0); - auto const running{real->PipePress}; + auto const running{real->brakePipe.Pressure()}; handle.SetUniversalFlag(TUniversalBrake::ub_Overload); driven_at(real, trace, "overload button", handle.GetPos(bh_RP), 30.0); handle.SetUniversalFlag(0); - auto const overloaded{real->PipePress}; + auto const overloaded{real->brakePipe.Pressure()}; driven_at(real, trace, "overload decaying", handle.GetPos(bh_RP), 240.0); - auto const decayed{real->PipePress}; + auto const decayed{real->brakePipe.Pressure()}; handle.SetUniversalFlag(TUniversalBrake::ub_HighPressure); driven_at(real, trace, "high pressure button, filling stroke", handle.GetPos(bh_FS), 10.0); - auto const filled{real->PipePress}; + auto const filled{real->brakePipe.Pressure()}; handle.SetUniversalFlag(0); driven_at(real, trace, "running", handle.GetPos(bh_RP), 120.0); CHECK(running == doctest::Approx(5.0).epsilon(0.01)); @@ -171,12 +171,12 @@ void ready_knorr_ep(test::consist &Unit) { Unit.add(definition::fiz("en57_v1/6bai"), 1); Unit.add(definition::fiz("en57_v1/5bgb")); auto &cab{Unit[0]}; - REQUIRE(cab->BrakeHandle == TBrakeHandle::St113); - REQUIRE(cab->Handle != nullptr); + REQUIRE(cab->brakes.config.driverValveType == TBrakeHandle::St113); + REQUIRE(cab->brakes.driverValve != nullptr); cab->BatterySwitch(true); cab->CabActivisation(); cab.hold_brake_pipe(5.0); - cab->BrakeLevelSet(cab->Handle->GetPos(bh_RP)); + cab->BrakeLevelSet(cab->brakes.driverValve->GetPos(bh_RP)); Unit.run(60.0); } @@ -187,7 +187,7 @@ double ep_brake(test::consist &Unit, double Position, double Seconds) { Unit.run(0.1); cab->SwitchEPBrake(1); Unit.run(Seconds); - return cab->BrakePress; + return cab->brakes.cylinderPressure; } // the EP force the St113 handle of the cab car gives in the given position @@ -195,7 +195,7 @@ double ep_at(test::consist &Unit, double Position) { auto &cab{Unit[0]}; cab->BrakeLevelSet(Position); Unit.run(0.1); - return cab->Handle->GetEP(); + return cab->brakes.driverValve->GetEP(); } } // namespace @@ -204,13 +204,13 @@ TEST_CASE("brake handles: the positions of the Knorr St113 EP brake") { test::consist unit; ready_knorr_ep(unit); auto &cab{unit[0]}; - REQUIRE(cab->Handle != nullptr); - auto &handle{*cab->Handle}; + REQUIRE(cab->brakes.driverValve != nullptr); + auto &handle{*cab->brakes.driverValve}; // the keys: Num 6 running, Num 8 the first position on, Num 5 the middle of the handle CHECK(handle.GetPos(bh_RP) == doctest::Approx(0.0)); CHECK(ep_at(unit, 0.0) == doctest::Approx(-1.0)); // EP release CHECK(ep_at(unit, 1.0) == doctest::Approx(1.0)); // EP brake - CHECK(ep_at(unit, cab->BrakeCtrlPosNo / 2) == doctest::Approx(0.0)); // lap, Num 5 + CHECK(ep_at(unit, cab->brakes.config.handlePositions / 2) == doctest::Approx(0.0)); // lap, Num 5 CHECK(ep_at(unit, handle.GetPos(bh_FB)) == doctest::Approx(0.0)); CHECK(ep_at(unit, handle.GetPos(bh_EPR)) == doctest::Approx(-1.0)); CHECK(ep_at(unit, handle.GetPos(bh_EPB)) == doctest::Approx(1.0)); @@ -254,10 +254,10 @@ TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab cab->DirectionBackward(); unit.run(0.1); CHECK(cab->EpForce == doctest::Approx(0.0)); - auto const held{cab->BrakePress}; + auto const held{cab->brakes.cylinderPressure}; unit.run(5.0); - CHECK(cab->BrakePress < held + 0.05); - CHECK(cab->BrakePress > 0.2); + CHECK(cab->brakes.cylinderPressure < held + 0.05); + CHECK(cab->brakes.cylinderPressure > 0.2); // and doesn't release either, until the control is powered again CHECK(ep_brake(unit, 0.0, 5.0) > 0.2); cab->SwitchEPBrake(0); @@ -265,3 +265,81 @@ TEST_CASE("brake handles: the Knorr St113 EP brake needs the control of the cab unit.run(0.1); CHECK(ep_brake(unit, 0.0, 10.0) < 0.1); } + +// the Knorr St113 of the EN57 (TSt113, derived from TH14K1) over a service application, lap and release: its +// control chamber (GetCP), the brake pipe and the cylinder, against the values the code gave when the test was +// written, at 1e-9. a change of the handle's code which shouldn't alter anything has to keep them +namespace { + +struct st113_sample { + double cp; // the handle's control chamber + double pipe; // the brake pipe + double cylinder; + double ep; // the EP intensity the handle gives +}; + +std::vector st113_run() { + test::reseed_random(); + vehicle real{definition::fiz("en57_v1/6bai")}; + REQUIRE(real->brakes.config.driverValveType == TBrakeHandle::St113); + REQUIRE(real->brakes.driverValve != nullptr); + real.hold_main_reservoir(std::max(real->air.compressor.config.maxPressure, 8.0)); + auto &handle{*real->brakes.driverValve}; + std::vector samples; + auto const sample{[&] { samples.push_back({handle.GetCP(), real->brakePipe.Pressure(), real->brakes.cylinderPressure, handle.GetEP()}); }}; + auto const hold{[&](double Position, std::initializer_list Seconds) { + real->BrakeLevelSet(Position); + for (auto const seconds : Seconds) { + real.run(seconds); + sample(); + } + }}; + sample(); // before the first step: the chamber as Init left it + hold(handle.GetPos(bh_RP), {1.0, 30.0, 30.0}); // charged in the running position + hold(handle.GetPos(bh_MB), {1.0, 5.0}); // the first step of the service brake + hold(handle.GetPos(bh_FB), {1.0, 2.0, 5.0, 10.0}); // full service + hold(handle.GetPos(bh_NP), {5.0}); // lap + hold(handle.GetPos(bh_RP), {1.0, 5.0, 10.0, 30.0}); // released + hold(handle.GetPos(bh_EB), {1.0, 5.0}); // emergency + hold(handle.GetPos(bh_FS), {1.0, 3.0}); // filling stroke + hold(handle.GetPos(bh_RP), {10.0, 60.0}); // released again + return samples; +} + +} // namespace + +TEST_CASE("brake handles: the pressures of the Knorr St113 of the EN57 over an application and a release") { + // {control chamber, brake pipe, cylinder, EP} after each hold of st113_run(), as the code gave them + std::vector const expected{ + {0, 3.5, 6, 0}, + {4.9984786171489723, 4.9985239614132073, 3.8589217414374479, -1}, + {4.9987671731417445, 4.9988125312381184, 9.6079198677899244e-17, -1}, + {4.9991258752288621, 4.9991713394295099, 9.6079198677899244e-17, -1}, + {4.9533680060376426, 4.9530025463238161, 9.6079198677899244e-17, 0}, + {4.8311329228109479, 4.8310446333333399, 9.6079198677899244e-17, 0}, + {4.7310321436160523, 4.7325637973526726, 9.6079198677899244e-17, 0}, + {4.5872331917154092, 4.5890657213751611, 9.6079198677899244e-17, 0}, + {4.1778305377419631, 4.1793406294291415, 1.6739519661380537, 0}, + {3.355298669598576, 3.3569433138107754, 2.5006765921012648, 0}, + {3.340608574818968, 3.3406062128010463, 2.5006765921012648, 0}, + {4.9982940431020717, 4.9983393759288948, 1.805897475684926, -1}, + {4.9983349224059745, 4.9983802579817755, 0.096548127644583259, -1}, + {4.9984201641741199, 4.9984655050733862, 0.062980447840665657, -1}, + {4.9987011353434028, 4.998746490639209, 9.2221356484789066e-17, -1}, + {0.005419548331438478, 0.0049542946616295885, 2.0688047473966584, 0}, + {1.1051369154140042e-16, 1.1051359148828238e-16, 2.5210994451474482, 0}, + {7.9894372542519436, 7.9895176172361353, 1.9107481967960043, 0}, + {7.9894891501326404, 7.9895615214846529, 0.36406880055594204, 0}, + {6.2299691431411732, 6.2285260180794131, 0.068969473862745739, -1}, + {4.9988917107669719, 4.9989370736220264, 1.0102243333979078e-16, -1}, + }; + auto const samples{st113_run()}; + REQUIRE(samples.size() == expected.size()); + for (std::size_t i = 0; i < samples.size(); ++i) { + CAPTURE(i); + CHECK(samples[i].cp == doctest::Approx(expected[i].cp).epsilon(1e-9)); + CHECK(samples[i].pipe == doctest::Approx(expected[i].pipe).epsilon(1e-9)); + CHECK(samples[i].cylinder == doctest::Approx(expected[i].cylinder).epsilon(1e-9)); + CHECK(samples[i].ep == doctest::Approx(expected[i].ep).epsilon(1e-9)); + } +} diff --git a/tests/unit/test_brake_pipe.cpp b/tests/unit/test_brake_pipe.cpp new file mode 100644 index 000000000..e1281992b --- /dev/null +++ b/tests/unit/test_brake_pipe.cpp @@ -0,0 +1,118 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "physics/vehicle.h" +#include "physics/brakes.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the brake hoses between the vehicles of a train (physics::Vehicle::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, the hose between two short freight wagons carried twice the air which evens +// out their pipes: the pipes overshot each other in turns, and an ESt3 distributor saw the pipe pressure up to +// 0.28 bar off what was in it, lapped at the first stage of braking and kept the AI's train from leaving +// (eu07/maszyna#368) + +namespace { + +using test::definition; + +// a freight train standing charged: a locomotive and Wagons empty two-axle freight wagons with ESt3, set to G +void freight_train(test::consist &Train, int const Wagons) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Wagons; ++i) { + auto &wagon{Train.add(definition::fiz("3wl_v2/3wl"))}; + wagon->BrakeDelaySwitch(bdelay_G); + REQUIRE(wagon->brakes.config.distributorType == TBrakeValve::ESt3); + REQUIRE(wagon->brakes.config.pipeSection == doctest::Approx(0.792)); // the pipe of a freight wagon + } + Train[0].hold_brake_pipe(5.0); // the locomotive's driver's valve in the running position +} + +// a passenger train standing charged: a locomotive and Cars passenger cars with ESt4, set to R +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("st44_v2/m62-1151")); + for (int i = 0; i < Cars; ++i) { + auto &car{Train.add(definition::fiz("11xa_v2/93a"))}; + REQUIRE(car->brakes.config.pipeSection == doctest::Approx(0.507)); // the pipe of a passenger car + } + Train[0].hold_brake_pipe(5.0); +} + +// the time [s] until the brake pipe of the train's last vehicle is 0.5 bar down, once the locomotive holds its pipe +// at Pressure [bar], the physics stepping by Dt +double application_time(test::consist &Train, double const Pressure, double const Dt) { + auto &last{Train[Train.size() - 1]}; + auto const start{last->brakePipe.Pressure()}; + Train[0].hold_brake_pipe(Pressure); + auto time{0.0}; + while (last->brakePipe.Pressure() > start - 0.5 && time < 60.0) { + Train.step({}, Dt); + time += Dt; + } + return time; +} + +// the same train standing a minute, then braked from the locomotive, all of it in steps of Dt +template +double application_time(Builder Train, int const Vehicles, double const Pressure, double const Dt) { + test::consist train; + Train(train, Vehicles); + train.run(60.0, {}, Dt); + return application_time(train, Pressure, Dt); +} + +} // namespace + +TEST_CASE("brake pipe: the distributors of a standing freight train see the pressure in the pipe, and none of them brakes") { + test::consist train; + freight_train(train, 37); + // standing a while, the locomotive keeping the pipe charged + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &wagon{train[i].physics()}; + // the distributor's valve chamber follows the pressure the distributor works with: the pipe's own + CHECK(std::abs(wagon.brakes.distributor->GetVRP() - wagon.brakePipe.Pressure()) < 0.005); + CHECK(wagon.brakePipe.Pressure() > 4.9); + // released, as the AI wants every vehicle before it starts (TController::CheckVehicles()) + CHECK((wagon.brakes.distributor->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(wagon.brakes.cylinderPressure < 0.1); + } + // the exchange between the 14 m wagons takes 3 sub-steps of a step of 0.01 s + CHECK(train[1]->PipeCouplersSubsteps(0.01) == 3); +} + +TEST_CASE("brake pipe: an application from the locomotive reaches the end of a freight train as with a short step") { + // a light application, the locomotive's pipe 1 bar down: the last wagon's pipe 0.5 bar down as soon as in the + // step of 0.001 s, at which the exchange through the hoses converges + auto const converged{application_time(freight_train, 37, 4.0, 0.001)}; + auto const usual{application_time(freight_train, 37, 4.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.1)); + // a full service application + auto const convergedfull{application_time(freight_train, 37, 3.5, 0.001)}; + auto const usualfull{application_time(freight_train, 37, 3.5, 0.01)}; + CAPTURE(convergedfull); + CAPTURE(usualfull); + CHECK(usualfull == doctest::Approx(convergedfull).epsilon(0.1)); +} + +TEST_CASE("brake pipe: a passenger train, whose exchange was stable in one step, brakes as with a short step") { + test::consist train; + passenger_train(train, 10); + train.run(300.0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + auto &car{train[i].physics()}; + CHECK(std::abs(car.brakes.distributor->GetVRP() - car.brakePipe.Pressure()) < 0.005); + CHECK((car.brakes.distributor->GetBrakeStatus() & (b_on | b_hld)) == 0); + CHECK(car.brakes.cylinderPressure < 0.1); + } + auto const converged{application_time(passenger_train, 10, 3.5, 0.001)}; + auto const usual{application_time(passenger_train, 10, 3.5, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/tests/unit/test_brake_releaser.cpp b/tests/unit/test_brake_releaser.cpp new file mode 100644 index 000000000..ce2c9fb20 --- /dev/null +++ b/tests/unit/test_brake_releaser.cpp @@ -0,0 +1,131 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/brakereleaser.h" + +// when the AI works the brake releaser of its locomotive (TController::control_releaser). in stage 3 of uncoupling +// the locomotive pushes towards the cut it leaves, until the screw coupler slackens enough to be let go +// (TController::UpdateDisconnect). the consist brakes applied in stage 2 hold the locomotive too, and only the +// releaser lets it go. the releaser was worked only while the driver wanted to speed up (AccDesired above +// -0.05), so a signal at stop the cut stood across after the direction change, which caps the speed at 0, left the +// locomotive braked and the uncoupling went on for good (SM42 at Debica on L053). + +namespace { + +// a locomotive standing in stage 3 of uncoupling, braked by the consist's brake application of stage 2 +brake_releaser::conditions compressing_buffers(double const Acceleration) { + brake_releaser::conditions state; + state.acceleration_desired = Acceleration; + state.pipe_pressure = 3.8; + state.cylinder_pressure = 1.5; + state.control_pressure = 5.0; + state.velocity = 0.0; + state.pressing = true; + state.compressing_buffers = true; + return state; +} + +// a locomotive standing braked at the head of a train with a charged brake pipe, about to start off +brake_releaser::conditions standing_braked(double const Acceleration) { + brake_releaser::conditions state; + state.acceleration_desired = Acceleration; + state.pipe_pressure = 5.0; + state.cylinder_pressure = 1.0; + state.control_pressure = 5.0; + state.velocity = 0.0; + return state; +} + +} // namespace + +TEST_CASE("brake releaser: stage 3 of uncoupling releases the locomotive whatever the driver's acceleration") { + for (auto const acceleration : {0.3, 0.0, -0.05, -0.2, -0.9}) { + CAPTURE(acceleration); + auto const wanted{brake_releaser::decide(compressing_buffers(acceleration))}; + CHECK(wanted.actuate); + CHECK_FALSE(wanted.fill_pipe); + } +} + +TEST_CASE("brake releaser: stage 3 of uncoupling leaves a released locomotive alone") { + for (auto const acceleration : {0.3, -0.9}) { + CAPTURE(acceleration); + auto state{compressing_buffers(acceleration)}; + state.cylinder_pressure = 0.05; + CHECK_FALSE(brake_releaser::decide(state).actuate); + } +} + +TEST_CASE("brake releaser: pressing outside stage 3 still needs the driver to want to speed up") { + // the direction changes of stages 2 and 4, and coupling, are as before: the releaser goes on only with + // AccDesired above -0.05 + auto state{compressing_buffers(0.3)}; + state.compressing_buffers = false; + CHECK(brake_releaser::decide(state).actuate); + state.acceleration_desired = -0.05; + CHECK_FALSE(brake_releaser::decide(state).actuate); + state.acceleration_desired = -0.9; + CHECK_FALSE(brake_releaser::decide(state).actuate); +} + +TEST_CASE("brake releaser: starting off releases a braked locomotive below 1 km/h") { + CHECK(brake_releaser::decide(standing_braked(0.3)).actuate); + CHECK_FALSE(brake_releaser::decide(standing_braked(-0.05)).actuate); + + auto moving{standing_braked(0.3)}; + moving.velocity = 1.0; + CHECK_FALSE(brake_releaser::decide(moving).actuate); + + auto lightly{standing_braked(0.3)}; + lightly.cylinder_pressure = 0.4; + CHECK_FALSE(brake_releaser::decide(lightly).actuate); + + // the control reservoir not charged: releasing would vent it + auto uncharged{standing_braked(0.3)}; + uncharged.control_pressure = 4.9; + CHECK_FALSE(brake_releaser::decide(uncharged).actuate); + // unless the train brake is held on purpose to start uphill + uncharged.uphill_start = true; + CHECK(brake_releaser::decide(uncharged).actuate); +} + +TEST_CASE("brake releaser: an empty brake pipe is filled up when the driver wants to speed up") { + auto state{standing_braked(0.3)}; + state.pipe_pressure = 2.9; + state.cylinder_pressure = 0.0; + auto const wanted{brake_releaser::decide(state)}; + CHECK(wanted.actuate); + CHECK(wanted.fill_pipe); + + state.acceleration_desired = -0.2; + auto const braking{brake_releaser::decide(state)}; + CHECK_FALSE(braking.actuate); + CHECK_FALSE(braking.fill_pipe); +} + +TEST_CASE("brake releaser: an overcharged brake pipe turns the releaser off, in stage 3 of uncoupling too") { + auto starting{standing_braked(0.3)}; + starting.pipe_pressure = 5.3; + CHECK_FALSE(brake_releaser::decide(starting).actuate); + + auto uncoupling{compressing_buffers(-0.9)}; + 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_brake_setting.cpp b/tests/unit/test_brake_setting.cpp index 5034bf3c5..b4f7cb26c 100644 --- a/tests/unit/test_brake_setting.cpp +++ b/tests/unit/test_brake_setting.cpp @@ -1,8 +1,8 @@ #include "stdafx.h" #include "doctest.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/vehicle.h" +#include "physics/brakes.h" #include "vehicle.h" #include "vehicle/brakesetting.h" #include "vehicle/Driver.h" @@ -209,18 +209,18 @@ void charge_and_apply(test::vehicle &Vehicle) { // running it as a train or shunting it, standing or on the run int inspect_heavy_train(test::vehicle &Vehicle, bool const Train = as_train, bool const Standstill = standstill) { auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; - consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); + consist.emplace_back(brake_setting::describe(Vehicle.physics(), false)); auto const setting{brake_setting::choose(consist, Train).back()}; - brake_setting::apply(Vehicle.mover(), setting, Standstill); + brake_setting::apply(Vehicle.physics(), setting, Standstill); return setting; } // the same on a light train, which runs on P int inspect_light_train(test::vehicle &Vehicle) { auto consist{train(locomotive(), 4, freight_wagon())}; - consist.emplace_back(brake_setting::describe(Vehicle.mover(), false)); + consist.emplace_back(brake_setting::describe(Vehicle.physics(), false)); auto const setting{brake_setting::choose(consist, as_train).back()}; - brake_setting::apply(Vehicle.mover(), setting, standstill); + brake_setting::apply(Vehicle.physics(), setting, standstill); return setting; } @@ -229,13 +229,13 @@ int inspect_light_train(test::vehicle &Vehicle) { bool inspection_pending(std::vector const &Vehicles, bool const Train, bool const Standstill) { auto consist{train(locomotive(), 30, freight_wagon(15.0, 80.0))}; for (auto *vehicle : Vehicles) { - consist.emplace_back(brake_setting::describe(vehicle->mover(), false)); + consist.emplace_back(brake_setting::describe(vehicle->physics(), false)); } auto const settings{brake_setting::choose(consist, Train)}; auto setting{settings.end() - static_cast(Vehicles.size())}; auto pending{false}; for (auto *vehicle : Vehicles) { - if (brake_setting::apply(vehicle->mover(), *setting++, Standstill)) { + if (brake_setting::apply(vehicle->physics(), *setting++, Standstill)) { pending = true; } } @@ -247,70 +247,70 @@ bool inspection_pending(std::vector const &Vehicles, bool const TEST_CASE("brake setting: the inspector cuts the brake out in a train on G and puts it back in a train on P") { test::vehicle car{passenger_car_definition()}; charge_and_apply(car); - REQUIRE(car->BrakePress > 1.0); + REQUIRE(car->brakes.cylinderPressure > 1.0); // made up into a heavy train on G: the brake is cut out and released REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(car.mover())); - CHECK(car->BrakeCutOutByInspector); + CHECK(brake_setting::is_cut_out(car.physics())); + CHECK(car->brakes.cutOutByInspector); car.run(30.0); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); // and it stays off whatever the brake pipe does car.hold_brake_pipe(5.0); car.run(60.0); car.hold_brake_pipe(3.5); car.run(20.0); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); car.hold_brake_pipe(0.0); car.run(20.0); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); // to the inspector looking at the train again it's a car like any other, and the train needs it cut out still - CHECK(false == brake_setting::describe(car.mover(), false).cut_out); + CHECK(false == brake_setting::describe(car.physics(), false).cut_out); REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(car->BrakeCutOutByInspector); + CHECK(car->brakes.cutOutByInspector); // made up into a light train: the brake is back on P, charges and brakes again CHECK(inspect_light_train(car) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); - CHECK(false == car->BrakeCutOutByInspector); - CHECK(car->BrakeDelayFlag == P); + CHECK(false == brake_setting::is_cut_out(car.physics())); + CHECK(false == car->brakes.cutOutByInspector); + CHECK(car->brakes.delaySetting == P); // the reservoirs emptied when it was cut out take some five minutes to charge from the brake pipe car.hold_brake_pipe(5.0); car.run(300.0); - CHECK(car->Hamulec->GetBRP() > 4.9); + CHECK(car->brakes.distributor->GetBRP() > 4.9); charge_and_apply(car); - CHECK(car->BrakePress > 1.0); + CHECK(car->brakes.cylinderPressure > 1.0); } TEST_CASE("brake setting: the inspector never puts back a brake cut out for another reason") { test::vehicle car{passenger_car_definition()}; charge_and_apply(car); // cut out the way the scenery's '0' does it - car->Hamulec->ForceEmptiness(); - car->Hamulec->SetBrakeStatus(car->Hamulec->GetBrakeStatus() | b_dmg); - CHECK(brake_setting::describe(car.mover(), false).cut_out); + car->brakes.distributor->ForceEmptiness(); + car->brakes.distributor->SetBrakeStatus(car->brakes.distributor->GetBrakeStatus() | b_dmg); + CHECK(brake_setting::describe(car.physics(), false).cut_out); // a train on G wants it cut out anyway: it isn't the inspector's to put back CHECK(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(false == car->BrakeCutOutByInspector); + CHECK(false == car->brakes.cutOutByInspector); // a train on P would want it working: it stays cut out CHECK(inspect_light_train(car) == P); - CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(brake_setting::is_cut_out(car.physics())); charge_and_apply(car); - CHECK(car->BrakePress < 0.1); + CHECK(car->brakes.cylinderPressure < 0.1); // a brake the inspector cut out, which someone else puts back and cuts out again, is theirs from then on test::vehicle other{passenger_car_definition()}; REQUIRE(inspect_heavy_train(other) == brake_setting::cut_out); - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() & ~b_dmg); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() & ~b_dmg); CHECK(inspect_heavy_train(other) == brake_setting::cut_out); // the inspector cuts it out again, and it's its own again - CHECK(other->BrakeCutOutByInspector); - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() & ~b_dmg); + CHECK(other->brakes.cutOutByInspector); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() & ~b_dmg); CHECK(inspect_light_train(other) == P); - CHECK(false == other->BrakeCutOutByInspector); - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); + CHECK(false == other->brakes.cutOutByInspector); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() | b_dmg); CHECK(inspect_light_train(other) == P); - CHECK(brake_setting::is_cut_out(other.mover())); + CHECK(brake_setting::is_cut_out(other.physics())); } TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and cuts none out") { @@ -318,50 +318,50 @@ TEST_CASE("brake setting: shunting puts back a brake the inspector cut out, and charge_and_apply(car); // shunted in a heavy consist: nothing is cut out, the car is on P and brakes CHECK(inspect_heavy_train(car, shunting) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); - CHECK(car->BrakeDelayFlag == P); - CHECK(car->BrakePress > 1.0); + CHECK(false == brake_setting::is_cut_out(car.physics())); + CHECK(car->brakes.delaySetting == P); + CHECK(car->brakes.cylinderPressure > 1.0); // cut out when the consist became a train, then shunted again (e.g. left in a yard): the brake is back REQUIRE(inspect_heavy_train(car) == brake_setting::cut_out); - REQUIRE(car->BrakeCutOutByInspector); + REQUIRE(car->brakes.cutOutByInspector); CHECK(inspect_heavy_train(car, shunting) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); - CHECK(false == car->BrakeCutOutByInspector); + CHECK(false == brake_setting::is_cut_out(car.physics())); + CHECK(false == car->brakes.cutOutByInspector); car.hold_brake_pipe(5.0); car.run(300.0); charge_and_apply(car); - CHECK(car->BrakePress > 1.0); + CHECK(car->brakes.cylinderPressure > 1.0); // a brake cut out for a reason of its own stays cut out in shunting too test::vehicle other{passenger_car_definition()}; - other->Hamulec->SetBrakeStatus(other->Hamulec->GetBrakeStatus() | b_dmg); + other->brakes.distributor->SetBrakeStatus(other->brakes.distributor->GetBrakeStatus() | b_dmg); CHECK(inspect_heavy_train(other, shunting) == P); - CHECK(brake_setting::is_cut_out(other.mover())); + CHECK(brake_setting::is_cut_out(other.physics())); } TEST_CASE("brake setting: the inspector doesn't cut a brake out on the run, it waits for a standstill") { test::vehicle car{passenger_car_definition()}; charge_and_apply(car); - REQUIRE(car->BrakePress > 1.0); + REQUIRE(car->brakes.cylinderPressure > 1.0); // the train checked on the run (the order changed mid-run): the car keeps its brake and its setting - auto const setting{car->BrakeDelayFlag}; + auto const setting{car->brakes.delaySetting}; CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); - CHECK(false == brake_setting::is_cut_out(car.mover())); - CHECK(false == car->BrakeCutOutByInspector); - CHECK(car->BrakeDelayFlag == setting); + CHECK(false == brake_setting::is_cut_out(car.physics())); + CHECK(false == car->brakes.cutOutByInspector); + CHECK(car->brakes.delaySetting == setting); car.run(5.0); - CHECK(car->BrakePress > 1.0); + CHECK(car->brakes.cylinderPressure > 1.0); // the next check, standing, cuts it out CHECK(inspect_heavy_train(car) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(car.mover())); - CHECK(car->BrakeCutOutByInspector); + CHECK(brake_setting::is_cut_out(car.physics())); + CHECK(car->brakes.cutOutByInspector); // a brake cut out already stays cut out on the run, and one put back on the run is back CHECK(inspect_heavy_train(car, as_train, moving) == brake_setting::cut_out); - CHECK(car->BrakeCutOutByInspector); + CHECK(car->brakes.cutOutByInspector); CHECK(inspect_heavy_train(car, shunting, moving) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); - CHECK(false == car->BrakeCutOutByInspector); + CHECK(false == brake_setting::is_cut_out(car.physics())); + CHECK(false == car->brakes.cutOutByInspector); } TEST_CASE("brake setting: a cut-out skipped on the run is reported, and done at the next inspection standing") { @@ -374,57 +374,57 @@ TEST_CASE("brake setting: a cut-out skipped on the run is reported, and done at for (auto *vehicle : vehicles) { charge_and_apply(*vehicle); } - auto const setting{first->BrakeDelayFlag}; + auto const setting{first->brakes.delaySetting}; // moving: nothing is cut out, and the inspector tells it has to come back CHECK(inspection_pending(vehicles, as_train, brake_setting::at_standstill(3.0))); for (auto *vehicle : vehicles) { - CHECK(false == brake_setting::is_cut_out(vehicle->mover())); - CHECK(false == vehicle->mover().BrakeCutOutByInspector); + CHECK(false == brake_setting::is_cut_out(vehicle->physics())); + CHECK(false == vehicle->physics().brakes.cutOutByInspector); } - CHECK(first->BrakeDelayFlag == setting); - CHECK(wagon->BrakeDelayFlag == G); + CHECK(first->brakes.delaySetting == setting); + CHECK(wagon->brakes.delaySetting == G); // still moving: still pending CHECK(inspection_pending(vehicles, as_train, moving)); // the train stands (its brake pipe charging after the coupling): the cars get cut out, nothing is left CHECK(false == inspection_pending(vehicles, as_train, brake_setting::at_standstill(0.0))); - CHECK(brake_setting::is_cut_out(first.mover())); - CHECK(first->BrakeCutOutByInspector); - CHECK(brake_setting::is_cut_out(second.mover())); - CHECK(second->BrakeCutOutByInspector); - CHECK(false == brake_setting::is_cut_out(wagon.mover())); + CHECK(brake_setting::is_cut_out(first.physics())); + CHECK(first->brakes.cutOutByInspector); + CHECK(brake_setting::is_cut_out(second.physics())); + CHECK(second->brakes.cutOutByInspector); + CHECK(false == brake_setting::is_cut_out(wagon.physics())); // and nothing is pending when the train moves off CHECK(false == inspection_pending(vehicles, as_train, moving)); - CHECK(brake_setting::is_cut_out(first.mover())); + CHECK(brake_setting::is_cut_out(first.physics())); } TEST_CASE("brake setting: an inspection on the run with nothing to cut out leaves nothing pending") { // a wagon with G in a heavy train on G test::vehicle wagon{test::definition::load("wagon").set("Cntrl", "BrakeDelays", "GP")}; CHECK(false == inspection_pending({&wagon}, as_train, moving)); - CHECK(wagon->BrakeDelayFlag == G); + CHECK(wagon->brakes.delaySetting == G); // a car without G in a consist being shunted: it keeps its brake, on P test::vehicle car{passenger_car_definition()}; CHECK(false == inspection_pending({&car}, shunting, moving)); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(false == brake_setting::is_cut_out(car.physics())); // a car whose brake is cut out already, for a reason of its own or by the inspector test::vehicle damaged{passenger_car_definition()}; - damaged->Hamulec->SetBrakeStatus(damaged->Hamulec->GetBrakeStatus() | b_dmg); + damaged->brakes.distributor->SetBrakeStatus(damaged->brakes.distributor->GetBrakeStatus() | b_dmg); CHECK(false == inspection_pending({&damaged}, as_train, moving)); - CHECK(false == damaged->BrakeCutOutByInspector); + CHECK(false == damaged->brakes.cutOutByInspector); test::vehicle done{passenger_car_definition()}; REQUIRE(false == inspection_pending({&done}, as_train, standstill)); - REQUIRE(done->BrakeCutOutByInspector); + REQUIRE(done->brakes.cutOutByInspector); CHECK(false == inspection_pending({&done}, as_train, moving)); // a brake put back on the run (the train became a consist being shunted) leaves nothing either CHECK(false == inspection_pending({&done}, shunting, moving)); - CHECK(false == brake_setting::is_cut_out(done.mover())); + CHECK(false == brake_setting::is_cut_out(done.physics())); // a single vehicle's apply() tells the same test::vehicle single{passenger_car_definition()}; - CHECK(brake_setting::apply(single.mover(), brake_setting::cut_out, moving)); - CHECK(false == brake_setting::apply(single.mover(), P, moving)); - CHECK(false == brake_setting::apply(single.mover(), 0, moving)); - CHECK(false == brake_setting::apply(single.mover(), brake_setting::cut_out, standstill)); - CHECK(false == brake_setting::apply(single.mover(), brake_setting::cut_out, moving)); + CHECK(brake_setting::apply(single.physics(), brake_setting::cut_out, moving)); + CHECK(false == brake_setting::apply(single.physics(), P, moving)); + CHECK(false == brake_setting::apply(single.physics(), 0, moving)); + CHECK(false == brake_setting::apply(single.physics(), brake_setting::cut_out, standstill)); + CHECK(false == brake_setting::apply(single.physics(), brake_setting::cut_out, moving)); } TEST_CASE("brake setting: a train creeping to a stop counts as standing, one on the run or coupling doesn't") { @@ -443,35 +443,58 @@ TEST_CASE("brake setting: a train creeping to a stop counts as standing, one on test::vehicle creeping{passenger_car_definition()}; charge_and_apply(creeping); CHECK(inspect_heavy_train(creeping, as_train, brake_setting::at_standstill(0.9)) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(creeping.mover())); - CHECK(creeping->BrakeCutOutByInspector); + CHECK(brake_setting::is_cut_out(creeping.physics())); + CHECK(creeping->brakes.cutOutByInspector); // checked at 30 km/h: the car keeps its brake test::vehicle running{passenger_car_definition()}; charge_and_apply(running); CHECK(inspect_heavy_train(running, as_train, brake_setting::at_standstill(30.0)) == brake_setting::cut_out); - CHECK(false == brake_setting::is_cut_out(running.mover())); - CHECK(false == running->BrakeCutOutByInspector); + CHECK(false == brake_setting::is_cut_out(running.physics())); + CHECK(false == running->brakes.cutOutByInspector); running.run(5.0); - CHECK(running->BrakePress > 1.0); + CHECK(running->brakes.cylinderPressure > 1.0); } TEST_CASE("brake setting: a bank engine's run counts as a train, shunting doesn't") { - CHECK(brake_setting::runs_as_train(Obey_train)); - CHECK(brake_setting::runs_as_train(Bank)); - CHECK(brake_setting::runs_as_train(Obey_train | Connect)); - CHECK(false == brake_setting::runs_as_train(Shunt)); - CHECK(false == brake_setting::runs_as_train(Loose_shunt)); - CHECK(false == brake_setting::runs_as_train(Connect)); - CHECK(false == brake_setting::runs_as_train(Wait_for_orders)); + CHECK(brake_setting::runs_as_train(DriverOrder::obeyTrain)); + CHECK(brake_setting::runs_as_train(DriverOrder::bank)); + CHECK(brake_setting::runs_as_train(DriverOrder::obeyTrain | DriverOrder::connect)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::shunt)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::looseShunt)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::connect)); + CHECK(false == brake_setting::runs_as_train(DriverOrder::waitForOrders)); // a heavy consist on G banked: the wagon without G has its brake cut out, as in a train test::vehicle car{passenger_car_definition()}; charge_and_apply(car); - CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(Bank)) == brake_setting::cut_out); - CHECK(brake_setting::is_cut_out(car.mover())); + CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(DriverOrder::bank)) == brake_setting::cut_out); + CHECK(brake_setting::is_cut_out(car.physics())); // shunted: it's back on P - CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(Shunt)) == P); - CHECK(false == brake_setting::is_cut_out(car.mover())); + CHECK(inspect_heavy_train(car, brake_setting::runs_as_train(DriverOrder::shunt)) == P); + CHECK(false == brake_setting::is_cut_out(car.physics())); +} + +TEST_CASE("brake setting: the AI looks at its train under the orders it drives it under, Connect included") { + CHECK(brake_setting::inspects_train(DriverOrder::shunt, false)); + CHECK(brake_setting::inspects_train(DriverOrder::looseShunt, false)); + CHECK(brake_setting::inspects_train(DriverOrder::obeyTrain, false)); + CHECK(brake_setting::inspects_train(DriverOrder::bank, false)); + // the run up to the wagons: a locomotive standing cold has its hand brake to release first + CHECK(brake_setting::inspects_train(DriverOrder::connect, false)); + CHECK(brake_setting::inspects_train(DriverOrder::connect | DriverOrder::changeDirection, false)); + // but not at the coupling: the wagons just coupled wait for the next order, which may leave some of them + CHECK(false == brake_setting::inspects_train(DriverOrder::connect, true)); + CHECK(false == brake_setting::inspects_train(DriverOrder::connect | DriverOrder::changeDirection, true)); + // a train run with a coupling on it is still a train run + CHECK(brake_setting::inspects_train(DriverOrder::obeyTrain | DriverOrder::connect, true)); + CHECK(brake_setting::inspects_train(DriverOrder::shunt, true)); + // standing, starting or stopping the engine, turning round, uncoupling: nothing to look at + CHECK(false == brake_setting::inspects_train(DriverOrder::waitForOrders, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::prepareEngine, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::releaseEngine, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::changeDirection, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::disconnect, false)); + CHECK(false == brake_setting::inspects_train(DriverOrder::jumpToFirstOrder, false)); } TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of an LSt kept") { @@ -483,13 +506,13 @@ TEST_CASE("brake setting: R+Mg brakes as hard as R at speed, the rapid stage of test::vehicle real{definition, 160.0}; real->DecManualBrakeLevel(ManualBrakePosNo); real->BrakeDelaySwitch(Setting); // false when already set - REQUIRE(real->BrakeDelayFlag == Setting); + REQUIRE(real->brakes.delaySetting == Setting); real.hold_brake_pipe(5.0); real.run(60.0); real.hold_brake_pipe(3.5); real.run(10.0); REQUIRE(real->Vel > 100.0); - return real->BrakePress; + return real->brakes.cylinderPressure; }; auto const rapid{service(R)}; CHECK(service(R | M) == doctest::Approx(rapid).epsilon(0.01)); diff --git a/tests/unit/test_brakes.cpp b/tests/unit/test_brakes.cpp index e12694f3f..bd93b8ca6 100644 --- a/tests/unit/test_brakes.cpp +++ b/tests/unit/test_brakes.cpp @@ -2,6 +2,9 @@ #include "doctest.h" #include "vehicle.h" #include "consist.h" +#include "utilities/Globals.h" + +#include using test::definition; using test::vehicle; @@ -14,16 +17,16 @@ TEST_CASE("brakes: KE wagon applies up to its tare limit on a service applicatio wagon.hold_brake_pipe(5.0); wagon.run(60.0); - CHECK(wagon->BrakePress < 0.1); - CHECK(wagon->Hamulec->GetBRP() > 4.5); // auxiliary reservoir charged + CHECK(wagon->brakes.cylinderPressure < 0.1); + CHECK(wagon->brakes.distributor->GetBRP() > 4.5); // auxiliary reservoir charged wagon.hold_brake_pipe(3.5); wagon.run(10.0); - CHECK(wagon->BrakePress == doctest::Approx(2.3).epsilon(0.05)); + CHECK(wagon->brakes.cylinderPressure == doctest::Approx(2.3).epsilon(0.05)); wagon.hold_brake_pipe(5.0); wagon.run(60.0); - CHECK(wagon->BrakePress < 0.1); + CHECK(wagon->brakes.cylinderPressure < 0.1); } TEST_CASE("brakes: a deeper brake pipe reduction brakes harder") { @@ -33,7 +36,7 @@ TEST_CASE("brakes: a deeper brake pipe reduction brakes harder") { wagon.run(60.0); wagon.hold_brake_pipe(Pipe); wagon.run(20.0); - return wagon->BrakePress; + return wagon->brakes.cylinderPressure; }; auto const light{applied(4.6)}; auto const medium{applied(4.2)}; @@ -52,14 +55,14 @@ TEST_CASE("brakes: every implemented distributor valve charges, applies and rele vehicle wagon{definition::load("wagon").set("Brake", "BrakeValve", valve).set("Brake", "Size", 16)}; wagon.hold_brake_pipe(5.0); wagon.run(90.0); - CHECK(wagon->BrakePress < 0.1); + CHECK(wagon->brakes.cylinderPressure < 0.1); wagon.hold_brake_pipe(3.5); wagon.run(20.0); - CHECK(wagon->BrakePress > 1.0); - CHECK(wagon->BrakePress <= 3.8 + 0.1); // MaxBP + CHECK(wagon->brakes.cylinderPressure > 1.0); + CHECK(wagon->brakes.cylinderPressure <= 3.8 + 0.1); // MaxBP wagon.hold_brake_pipe(5.0); wagon.run(90.0); - CHECK(wagon->BrakePress < 0.1); + CHECK(wagon->brakes.cylinderPressure < 0.1); } } @@ -99,41 +102,110 @@ TEST_CASE("brakes: service braking stops a heavier wagon too") { TEST_CASE("brakes: a dead EN57 hauled with the brake hose alone charges from the brake pipe and brakes") { test::consist train; auto &locomotive{train.add(definition::fiz("sm42_v1/6d1"))}; - train.add(definition::fiz("en57_v1/5bgb"), 0, coupling::coupler | coupling::brakehose); + train.add(definition::fiz("en57_v1/5bgb"), 0, Coupling::coupler | Coupling::brakeHose); train.add(definition::fiz("en57_v1/6ba_840")); train.add(definition::fiz("en57_v1/5bgaiii_led_spot")); // a unit standing dead: no air anywhere, nothing in its main reservoir pipe for (std::size_t i = 1; i < train.size(); ++i) { - auto &car{train[i].mover()}; - REQUIRE(car.BrakeValve == TBrakeValve::EP2); - car.Hamulec->ForceEmptiness(); - car.Pipe->CreatePress(0.0); - car.Pipe->Act(); - car.Pipe2->CreatePress(0.0); - car.Pipe2->Act(); - car.CompressedVolume = 0.0; + auto &car{train[i].physics()}; + REQUIRE(car.brakes.config.distributorType == TBrakeValve::EP2); + car.brakes.distributor->ForceEmptiness(); + car.brakePipe.reservoir->CreatePress(0.0); + car.brakePipe.reservoir->Act(); + car.mainPipe.reservoir->CreatePress(0.0); + car.mainPipe.reservoir->Act(); + car.air.Fill(0.0); } locomotive.hold_brake_pipe(5.0); train.run(900.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - auto &car{train[i].mover()}; - REQUIRE(car.ScndPipePress < 0.1); // no main reservoir pipe - CHECK(car.Hamulec->GetBRP() > 4.8); - CHECK(car.Hamulec->GetCRP() > 4.8); - CHECK(car.BrakePress < 0.1); + auto &car{train[i].physics()}; + REQUIRE(car.mainPipe.Pressure() < 0.1); // no main reservoir pipe + CHECK(car.brakes.distributor->GetBRP() > 4.8); + CHECK(car.brakes.distributor->GetCRP() > 4.8); + CHECK(car.brakes.cylinderPressure < 0.1); } // a full service application brakes the unit, and it releases again locomotive.hold_brake_pipe(3.5); train.run(20.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - CHECK(train[i]->BrakePress > 2.0); + CHECK(train[i]->brakes.cylinderPressure > 2.0); } locomotive.hold_brake_pipe(5.0); train.run(60.0); for (std::size_t i = 1; i < train.size(); ++i) { CAPTURE(i); - CHECK(train[i]->BrakePress < 0.1); + CHECK(train[i]->brakes.cylinderPressure < 0.1); } } + +namespace { + +// Global.physics_sleepheld, off by default, on for the test it's made in +struct sleepheld_on { + bool const was{Global.physics_sleepheld}; + sleepheld_on() { Global.physics_sleepheld = true; } + ~sleepheld_on() { Global.physics_sleepheld = was; } + sleepheld_on(sleepheld_on const &) = delete; + sleepheld_on &operator=(sleepheld_on const &) = delete; +}; + +} // namespace + +TEST_CASE("brakes: a wagon standing braked on a gradient sleeps while the brakes hold, and wakes and rolls away once they release") { + // Global.physics_sleepheld: a vehicle standing still held by its brakes lets its physics sleep, keeping the brake force of + // the step it fell asleep in. the brake system of the test vehicle steps on while asleep, as in the vehicle the user is in + sleepheld_on const sleepheld; + test::track slope; + slope.gradient = 0.01; // the brakes hold it, the running resistance alone (about 2.5 per mille) doesn't + vehicle wagon{definition::load("wagon")}; + // made standing, it has the hand brake on too (SetBraked()), which is the other test's + wagon->DecManualBrakeLevel(ManualBrakePosNo); + wagon.hold_brake_pipe(3.5); + wagon.run(30.0, slope); + REQUIRE(wagon->brakes.cylinderPressure > 1.0); + CHECK(std::abs(wagon.speed()) < 0.01); + CHECK_FALSE(wagon->PhysicActivation()); + + // the brakes holding as they are, it sleeps on + auto wakes{0}; + for (int step = 0; step < 12000; ++step) { + auto const asleep{false == wagon->PhysicActivation()}; + wagon.step(slope); + if (asleep && wagon->PhysicActivation()) { + ++wakes; + } + } + CHECK(wakes == 0); + CHECK(std::abs(wagon.speed()) < 0.01); + + // released, it wakes, the force of the brakes is gone and it rolls down the gradient + wagon.hold_brake_pipe(5.0); + wagon.run(60.0, slope); + CHECK(wagon->brakes.cylinderPressure < 0.1); + CHECK(wagon->Fb() < 1.0); + CHECK(std::abs(wagon.speed()) > 1.0); + CHECK(wagon->PhysicActivation()); +} + +TEST_CASE("brakes: a wagon held by its hand brake on a gradient wakes and rolls away once the hand brake is released") { + // the setting changes by hand on a sleeping vehicle, whose brake system doesn't step in the game while asleep + sleepheld_on const sleepheld; + test::track slope; + slope.gradient = 0.01; + vehicle wagon{definition::load("wagon")}; + // made standing, it has the hand brake on (SetBraked()) + REQUIRE(wagon->brakes.HandBrakePosition() == ManualBrakePosNo); + wagon.hold_brake_pipe(5.0); + wagon.run(90.0, slope); + REQUIRE(wagon->brakes.cylinderPressure < 0.1); + CHECK(std::abs(wagon.speed()) < 0.01); + CHECK_FALSE(wagon->PhysicActivation()); + + wagon->DecManualBrakeLevel(ManualBrakePosNo); + wagon.run(30.0, slope); + CHECK(wagon->Fb() < 1.0); + CHECK(std::abs(wagon.speed()) > 1.0); +} diff --git a/tests/unit/test_braking_curve.cpp b/tests/unit/test_braking_curve.cpp index 7102d06e0..f542ec27c 100644 --- a/tests/unit/test_braking_curve.cpp +++ b/tests/unit/test_braking_curve.cpp @@ -154,6 +154,41 @@ TEST_CASE("braking curve: a train with a worked out brake table plans along the } } +TEST_CASE("braking curve: the train brake handle or the independent brake counts as braking") { + CHECK_FALSE(braking_curve::brake_acting(0.0, 0.0)); + // the handle in its release or filling positions is below running + CHECK_FALSE(braking_curve::brake_acting(-1.0, 0.0)); + CHECK(braking_curve::brake_acting(1.0, 0.0)); + CHECK(braking_curve::brake_acting(0.5, 0.0)); + // a light locomotive or a railcar alone brakes with the independent brake, the handle stays in running + CHECK(braking_curve::brake_acting(0.0, 0.25)); + CHECK(braking_curve::brake_acting(-1.0, 1.0)); + CHECK(braking_curve::brake_acting(2.0, 0.5)); +} + +TEST_CASE("braking curve: a vehicle braking with its independent brake uses the whole distance, as with the train brake") { + // before, only the train brake handle counted: a light locomotive that had put its independent brake on still + // planned, on every look, to stop short by the distance the brake takes to fill, so it slowed down too early + // and crawled the last tens of metres to the stop + flat_table const light; + auto const table{light.table()}; + auto approach{stop_at(60.0, 300.0)}; + approach.offset = 20.0; + approach.fill_horizon = 8.0; + approach.brake_applied = braking_curve::brake_acting(0.0, 0.3); + + auto const demand{braking_curve::demand(approach, &table)}; + + CHECK(demand == doctest::Approx(braking_curve::shaped_demand(60.0, 0.0, 280.0 + 0.1 / 25.92, 0.0, table))); + auto trainbrake{approach}; + trainbrake.brake_applied = braking_curve::brake_acting(1.0, 0.0); + CHECK(demand == doctest::Approx(braking_curve::demand(trainbrake, &table))); + auto released{approach}; + released.brake_applied = braking_curve::brake_acting(0.0, 0.0); + // with no brake on, the room to fill is kept, and more is asked for + CHECK(braking_curve::demand(released, &table) < demand); +} + TEST_CASE("braking curve: a train gets the demand it got before the curve moved out of the AI") { // a table that grips harder as the train slows, on a gradient; the demands were worked out with the // code of TController::adjust_desired_speed_for_braking_curve before the move (origin/master 80fd5aad) @@ -193,3 +228,19 @@ TEST_CASE("braking curve: a train gets the demand it got before the curve moved CHECK(braking_curve::demand(approach, &table) == doctest::Approx(expected).epsilon(1e-7)); } + +TEST_CASE("braking curve: down a gradient a train at walking pace in the last metres before its stop stops there") { + // EU07 alone down 20 per mille to the signal gr_sem (eu07_td_downgrade_w4_signal): 3.5 km/h 1.3 m short of the + // middle of the stopping window, the curve asked for next to no braking; the independent brake let off for it, the + // gradient took the locomotive again, and it crept on and braked again three times, for some 12 s + auto constexpr descent{0.196}; // [m/s2] 20 per mille + CHECK(braking_curve::stops_where_it_is(3.5, 1.3, descent)); + // past the point it aims at, it doesn't creep on half a metre at a time either + CHECK(braking_curve::stops_where_it_is(0.2, -1.2, descent)); + // faster, or further out, it follows the curve down to the point + CHECK_FALSE(braking_curve::stops_where_it_is(5.8, 2.6, descent)); + CHECK_FALSE(braking_curve::stops_where_it_is(3.5, 10.0, descent)); + // on the flat and uphill the gradient doesn't take the train when the brake lets off + CHECK_FALSE(braking_curve::stops_where_it_is(3.5, 1.3, 0.0)); + CHECK_FALSE(braking_curve::stops_where_it_is(3.5, 1.3, -0.196)); +} diff --git a/tests/unit/test_cab.cpp b/tests/unit/test_cab.cpp index 063e70911..5cf01117f 100644 --- a/tests/unit/test_cab.cpp +++ b/tests/unit/test_cab.cpp @@ -4,7 +4,7 @@ #include "scenario.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" #include "utilities/utilities.h" // characterisation of what the cab (Train.cpp) and the AI (Driver.cpp, driverhints.cpp) call on a vehicle @@ -21,9 +21,9 @@ using namespace test::channels; TEST_CASE("cab: the engine rotation of up to three vehicles in multiple, on the tachometers of the SN61") { consist train; - auto &first{train.add(definition::fiz("sn61_v2/sn61"), 1).mover()}; - auto &second{train.add(definition::fiz("sn61_v2/sn61")).mover()}; - auto &third{train.add(definition::fiz("sn61_v2/sn61")).mover()}; + auto &first{train.add(definition::fiz("sn61_v2/sn61"), 1).physics()}; + auto &second{train.add(definition::fiz("sn61_v2/sn61")).physics()}; + auto &third{train.add(definition::fiz("sn61_v2/sn61")).physics()}; first.enrot = -10.0; second.enrot = 20.0; third.enrot = 30.0; @@ -37,15 +37,15 @@ TEST_CASE("cab: the engine rotation of up to three vehicles in multiple, on the CHECK(third.ShowEngineRotation(3) == doctest::Approx(10.0)); // no control cable, no reading consist apart; - auto const &alone{apart.add(definition::fiz("sn61_v2/sn61"), 1).mover()}; - apart.add(definition::fiz("sn61_v2/sn61"), 0, coupling::coupler | coupling::brakehose); + auto const &alone{apart.add(definition::fiz("sn61_v2/sn61"), 1).physics()}; + apart.add(definition::fiz("sn61_v2/sn61"), 0, Coupling::coupler | Coupling::brakeHose); CHECK(alone.ShowEngineRotation(2) == doctest::Approx(0.0)); } TEST_CASE("cab: the lamps of the overload relay and the starting resistors, read through the control cable") { consist unit; - auto &trailer{unit.add(definition::fiz("ed72_v1/5bs-ra"), 1).mover()}; - auto &motor{unit.add(definition::fiz("ed72_v1/6bs-sa")).mover()}; + auto &trailer{unit.add(definition::fiz("ed72_v1/5bs-ra"), 1).physics()}; + auto &motor{unit.add(definition::fiz("ed72_v1/6bs-sa")).physics()}; REQUIRE(trailer.Power < 0.01); REQUIRE(motor.Power > 0.01); CHECK_FALSE(trailer.FuseFlagCheck()); @@ -60,7 +60,7 @@ TEST_CASE("cab: the lamps of the overload relay and the starting resistors, read TEST_CASE("cab: the engine's idle speed, and the ET42's second controller shown in its dynamic brake") { vehicle sn61{definition::fiz("sn61_v2/sn61")}; - CHECK(sn61->EngineIdleRPM() == doctest::Approx(sn61->dizel_nmin * 60.0)); + CHECK(sn61->EngineIdleRPM() == doctest::Approx(sn61->diesel.minRevolutions * 60.0)); vehicle su45{definition::fiz("su45_v2/301d")}; CHECK(su45->EngineIdleRPM() == doctest::Approx(su45->DElist[su45->MainCtrlNoPowerPos()].RPM)); vehicle eu07{definition::fiz("4e_v1/4e")}; @@ -68,14 +68,14 @@ TEST_CASE("cab: the engine's idle speed, and the ET42's second controller shown vehicle et42{definition::fiz("et42_v2/112e-a")}; CHECK(et42->GetVirtualScndPos() == 0); - et42->DynamicBrakeFlag = true; + et42->brakes.electrodynamic.on = true; CHECK(et42->GetVirtualScndPos() == -1); - et42->ScndCtrlPos = 1; + et42->SetScndCtrlPos(1); CHECK(et42->GetVirtualScndPos() == 1); // with a speed control in place of the second controller, either end of it, for the AI vehicle railbus{definition::fiz("21xm_v1/214ma")}; - REQUIRE(railbus->SpeedCtrl); - railbus->ScndCtrlPos = 1; + REQUIRE(railbus->SpeedCtrl()); + railbus->SetScndCtrlPos(1); CHECK(railbus->IsScndCtrlNoPowerPos()); CHECK(railbus->IsScndCtrlMaxPowerPos()); CHECK(eu07->IsScndCtrlNoPowerPos()); @@ -91,9 +91,9 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local CHECK_FALSE(eu47.IncDynamicBrakeLevel(1.f)); CHECK(eu47.DynamicBrakeRatio() == doctest::Approx(0.0)); - scenario.train()[0].mover().SplitEDPneumaticBrake = true; + scenario.train()[0].physics().brakes.electrodynamic.splitFromPneumatic = true; REQUIRE(scenario.start_up()); - REQUIRE(eu47.DynamicBrakeCtrlPosNo == 10); + REQUIRE(eu47.brakes.electrodynamic.controllerPositions == 10); CHECK(eu47.DynamicBrakeAvailable()); scenario.act("dynamic brake up"); for (int i = 0; i < 5; ++i) { @@ -101,9 +101,9 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local } CHECK(eu47.DynamicBrakeRatio() == doctest::Approx(0.5)); scenario.wait(10.0); - CHECK(eu47.DynamicBrakeFlag); + CHECK(eu47.brakes.electrodynamic.on); CHECK(eu47.Im < -50.0); - CHECK(eu47.BrakePress < 0.1); + CHECK(eu47.brakes.cylinderPressure < 0.1); scenario.act("dynamic brake full"); CHECK(eu47.DynamicBrakeLevelSet(2.0)); CHECK(eu47.DynamicBrakeRatio() == doctest::Approx(1.0)); @@ -118,7 +118,7 @@ TEST_CASE("cab: the controller of the electrodynamic brake apart from the local scenario.act("local brake"); eu47.IncLocalBrakeLevel(LocalBrakePosNo); scenario.wait(5.0); - CHECK(eu47.BrakePress > 1.0); + CHECK(eu47.brakes.cylinderPressure > 1.0); scenario.check(); } @@ -130,10 +130,10 @@ TEST_CASE("cab: the spring brake shut off and released by hand, the ep brake's f scenario.act("spring brake on"); railbus.SpringBrakeActivate(true); scenario.wait(10.0); - CHECK(railbus.SpringBrake.IsActive); + CHECK(railbus.brakes.spring.isActive); // released by hand only with its cylinder empty of the air holding it off - auto const pressure{railbus.SpringBrake.Cylinder->P()}; - CHECK(railbus.SpringBrakeRelease() == (pressure < railbus.SpringBrake.MinForcePressure)); + auto const pressure{railbus.brakes.spring.cylinder->P()}; + CHECK(railbus.SpringBrakeRelease() == (pressure < railbus.brakes.spring.minForcePressure)); scenario.act("shut off"); CHECK(railbus.SpringBrakeShutOff(true)); CHECK_FALSE(railbus.SpringBrakeShutOff(true)); @@ -148,9 +148,9 @@ TEST_CASE("cab: the spring brake shut off and released by hand, the ep brake's f CHECK(railbus.EpFuseSwitch(true)); // the train brake handle stepped as the AI does, false at its ends scenario.act("handle stepped"); - railbus.BrakeLevelSet(railbus.Handle->GetPos(bh_RP)); + railbus.BrakeLevelSet(railbus.brakes.driverValve->GetPos(bh_RP)); CHECK(railbus.BrakeLevelAdd(1.0)); - CHECK(railbus.BrakeCtrlPos == static_cast(railbus.Handle->GetPos(bh_RP)) + 1); + CHECK(railbus.brakes.HandlePosition() == static_cast(railbus.brakes.driverValve->GetPos(bh_RP)) + 1); CHECK(railbus.BrakeLevelAdd(-1.0)); CHECK_FALSE(railbus.BrakeLevelAdd(-10.0)); CHECK_FALSE(railbus.BrakeLevelAdd(100.0)); @@ -164,17 +164,17 @@ TEST_CASE("cab: damaged motors cut off in a car without a driver") { vehicle driven{definition::fiz("ew58_v1/ew58-sa"), 0.0, "test", 1}; driven->BatterySwitch(true); REQUIRE(driven->CabActivisation()); - driven->DamageFlag |= dtrain_engine; + driven->DamageFlag |= VehicleDamage::engine; CHECK_FALSE(driven->CutOffEngine()); vehicle car{definition::fiz("ew58_v1/ew58-sa")}; - auto const axles{car->NPoweredAxles}; + auto const axles{car->NPoweredAxles()}; CHECK_FALSE(car->CutOffEngine()); - car->DamageFlag |= dtrain_engine; + car->DamageFlag |= VehicleDamage::engine; CHECK(car->CutOffEngine()); - CHECK(car->NPoweredAxles == axles / 2); - CHECK_FALSE(TestFlag(car->DamageFlag, dtrain_engine)); + CHECK(car->NPoweredAxles() == axles / 2); + CHECK_FALSE(car->DamageFlag.HasAll(VehicleDamage::engine)); vehicle wagon{definition::fiz("3wl_v2/3wl")}; - wagon->DamageFlag |= dtrain_engine; + wagon->DamageFlag |= VehicleDamage::engine; CHECK_FALSE(wagon->CutOffEngine()); } @@ -195,7 +195,7 @@ TEST_CASE("cab: a road vehicle moved across its road") { bus.step(test::track{0.15, 0.0, 0.0, 2, 1, 7.0}); REQUIRE(TestFlag(bus->CategoryFlag, 2)); CHECK(bus->ChangeOffsetH(0.5)); - CHECK(bus->OffsetTrackH == doctest::Approx(0.5)); + CHECK(bus->OffsetTrackH() == doctest::Approx(0.5)); // off the edge of the road CHECK_FALSE(bus->ChangeOffsetH(100.0)); vehicle eu07{definition::fiz("4e_v1/4e")}; @@ -223,7 +223,7 @@ TEST_CASE("cab: the lamps and the buzzer of the security system left unattended" CHECK(blinked); CHECK(beeped); CHECK_FALSE(security.is_cabsignal_beeping()); - CHECK(eu07.PipePress < 1.0); + CHECK(eu07.brakePipe.Pressure() < 1.0); CHECK(security.radiostop_available()); scenario.check(); } @@ -259,7 +259,7 @@ TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode, wher REQUIRE(sm42.CurrentSwitch(true)); REQUIRE(sm42.ShuntMode); scenario.get_going(); - sm42.AnPos = 0.3; + sm42.SetAnPos(0.3); sm42.IncMainCtrl(1); scenario.act("unattended in shunt mode"); bool blinked{false}; @@ -269,7 +269,7 @@ TEST_CASE("cab: the SM42's vigilance device switched off in the shunt mode, wher } CHECK(sm42.Vel > 1.0); CHECK_FALSE(blinked); - CHECK(sm42.PipePress > 3.5); + CHECK(sm42.brakePipe.Pressure() > 3.5); scenario.act("shunt mode off"); scenario.notch_back(0); REQUIRE(sm42.CurrentSwitch(false)); @@ -288,12 +288,12 @@ TEST_CASE("cab: the vigilance device of the SM42 kept in the shunt mode, by defa REQUIRE(sm42.CurrentSwitch(true)); REQUIRE(sm42.ShuntMode); scenario.get_going(); - sm42.AnPos = 0.3; + sm42.SetAnPos(0.3); sm42.IncMainCtrl(1); scenario.act("unattended in shunt mode"); CHECK(unattended(scenario, 120)); CHECK(sm42.ShuntMode); - CHECK(sm42.PipePress < 1.0); + CHECK(sm42.brakePipe.Pressure() < 1.0); scenario.check(); } @@ -324,7 +324,7 @@ TEST_CASE("cab: the SM42's vigilance alarm on, not cleared by switching into the CHECK(security.is_vigilance_blinking()); CHECK(security.is_beeping()); CHECK(security.is_braking()); - CHECK(sm42.PipePress < 1.0); + CHECK(sm42.brakePipe.Pressure() < 1.0); scenario.act("acknowledged"); sm42.SecuritySystemReset(); scenario.train().run(1.0, scenario.line()); diff --git a/tests/unit/test_camera.cpp b/tests/unit/test_camera.cpp new file mode 100644 index 000000000..c0a75978d --- /dev/null +++ b/tests/unit/test_camera.cpp @@ -0,0 +1,157 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include +#include +#include + +#include "input/command.h" +#include "utilities/Timer.h" +#include "vehicle/Camera.h" +#include "vehicle/DynObj.h" + +// the view matrix of the camera (TCamera::SetMatrix): the pitch (Angle.x) and the yaw (Angle.y) give the line of sight, +// the roll (Angle.z) turns the view about that line, wherever the camera looks. The roll comes from the sway of the cab +// (drivermode.cpp) or the angles of a camera entry of the scenery. Multiplied in last, it once acted about the world's z +// axis instead, and nodded the view up and down when looking out of a side window (623c4f82, put back in #414). +// vehicle/Camera.cpp isn't in the core library; the test binary compiles it itself (tests/unit/CMakeLists.txt) + +// the parts of the engine TCamera::Update() reaches for, which no test here runs: the command queue and the clock +// (simulation::Commands itself is in test_script_screen_host.cpp) +bool command_queue::pop(command_data &, uint32_t const) { // NOSONAR signature from input/command.h + return false; +} + +double Timer::GetDeltaRenderTime() { // NOSONAR signature from utilities/Timer.h + return 0.0; +} + +namespace { + +// the axes of the view in the world, from the view matrix +struct view_axes { + glm::dvec3 eye; + glm::dvec3 forward; // the line of sight + glm::dvec3 up; + glm::dvec3 right; +}; + +view_axes axes(TCamera const &Camera) { + glm::dmat4 matrix{1.0}; + REQUIRE(Camera.SetMatrix(matrix)); + auto const toworld{glm::inverse(matrix)}; + return { + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, 0.0, 1.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 0.0, -1.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{0.0, 1.0, 0.0, 0.0}}, + glm::dvec3{toworld * glm::dvec4{1.0, 0.0, 0.0, 0.0}}}; +} + +void check_equal(glm::dvec3 const &Actual, glm::dvec3 const &Expected) { + CAPTURE(Actual.x); + CAPTURE(Actual.y); + CAPTURE(Actual.z); + CHECK(Actual.x == doctest::Approx(Expected.x).epsilon(1e-9)); + CHECK(Actual.y == doctest::Approx(Expected.y).epsilon(1e-9)); + CHECK(Actual.z == doctest::Approx(Expected.z).epsilon(1e-9)); +} + +// the free camera, at Position, turned by Angle (pitch, yaw, roll) +TCamera free_camera(glm::dvec3 const &Position, glm::vec3 const &Angle) { + TCamera camera; + camera.Init(Position, glm::dvec3{Angle}, nullptr); + return camera; +} + +struct turn { + float pitch; + float yaw; +}; + +// the camera looking ahead (-z), out of the left and the right side window, back, up and down at an angle +std::vector const turns{ + {0.f, 0.f}, + {0.f, static_cast(std::numbers::pi / 2)}, + {0.3f, static_cast(-std::numbers::pi / 2)}, + {-0.4f, static_cast(std::numbers::pi)}, + {0.2f, 0.7f}, + {-0.6f, -2.1f}, +}; + +std::vector const rolls{0.1f, -0.2f, 0.5f}; + +} // namespace + +TEST_CASE("camera: the pitch and the yaw give the line of sight, the roll leaves it as it is (#414)") { + glm::dvec3 const position{120.0, 4.5, -300.0}; + for (auto const &turn : turns) { + auto const pitch{static_cast(turn.pitch)}; + auto const yaw{static_cast(turn.yaw)}; + // the yaw from -z towards -x, the pitch up from the ground, as TCamera::RaLook() works them out + glm::dvec3 const sight{-std::sin(yaw) * std::cos(pitch), std::sin(pitch), -std::cos(yaw) * std::cos(pitch)}; + for (auto const roll : {0.f, rolls[0], rolls[1], rolls[2]}) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const view{axes(free_camera(position, {turn.pitch, turn.yaw, roll}))}; + check_equal(view.eye, position); + check_equal(view.forward, sight); + } + } +} + +TEST_CASE("camera: the roll turns the view about the line of sight, wherever the camera looks (#414)") { + for (auto const &turn : turns) { + auto const level{axes(free_camera({}, {turn.pitch, turn.yaw, 0.f}))}; + for (auto const roll : rolls) { + CAPTURE(turn.pitch); + CAPTURE(turn.yaw); + CAPTURE(roll); + auto const rolled{axes(free_camera({}, {turn.pitch, turn.yaw, roll}))}; + auto const angle{static_cast(roll)}; + // the up of the view leans towards the left by the roll, and stays square to the line of sight + check_equal(rolled.up, std::cos(angle) * level.up - std::sin(angle) * level.right); + check_equal(rolled.right, std::cos(angle) * level.right + std::sin(angle) * level.up); + CHECK(glm::dot(rolled.up, rolled.forward) == doctest::Approx(0.0).epsilon(1e-9)); + } + } +} + +// the camera in the cab: the eye in the cab, looking at a point ahead of the vehicle (TCamera::LookAt), the head turned +// by the yaw and the pitch, the sway of the cab given as the roll. The camera needs no more of the vehicle than that it +// has one, so the vehicle is a zeroed block of its size, never used as an object (as the neighbours in vehicle.cpp) +static_assert(alignof(TDynamicObject) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__); + +TEST_CASE("camera: in the cab, the sway leaves the view out of a side window level (#414)") { + std::vector vehicle(sizeof(TDynamicObject)); // zeroed + + glm::dvec3 const eye{10.0, 2.0, -5.0}; + // the vehicle heading north-east on level track + auto const ahead{glm::normalize(glm::dvec3{1.0, 0.0, -1.0})}; + glm::dvec3 const left{ahead.z, 0.0, -ahead.x}; // the vehicle's left, flat + + for (auto const head : {-1, 1}) { // turned to the right, to the left + for (auto const roll : {0.1f, -0.15f}) { + CAPTURE(head); + CAPTURE(roll); + + TCamera camera; + camera.Init(eye, {}, reinterpret_cast(vehicle.data())); // NOSONAR see above + camera.LookAt = eye + ahead; + camera.vUp = {0.f, 1.f, 0.f}; + camera.Angle = {0.f, static_cast(head * std::numbers::pi / 2), roll}; + + auto const view{axes(camera)}; + check_equal(view.eye, eye); + // out of the window to the left or the right, still level, whatever the sway (the yaw is a float, a hair + // off a right angle) + auto const yaw{static_cast(camera.Angle.y)}; + check_equal(view.forward, std::sin(yaw) * left + std::cos(yaw) * ahead); + CHECK(glm::dot(view.forward, static_cast(head) * left) == doctest::Approx(1.0).epsilon(1e-6)); + // the sway tilts the view about that line by its angle + CHECK(glm::dot(view.up, view.forward) == doctest::Approx(0.0).epsilon(1e-9)); + CHECK(view.up.y == doctest::Approx(std::cos(static_cast(roll))).epsilon(1e-9)); + } + } +} diff --git a/tests/unit/test_camera_views.cpp b/tests/unit/test_camera_views.cpp new file mode 100644 index 000000000..2529efbb9 --- /dev/null +++ b/tests/unit/test_camera_views.cpp @@ -0,0 +1,386 @@ +#include "stdafx.h" +#include "doctest.h" + +#include +#include + +#include "vehicle/cameraviews.h" + +// the outside views of the train that go with one of its vehicles (eu07/maszyna#551): orbit, shunting from above, +// beside a coupling, trackside. The camera follows from the place of the vehicle and the keys alone. + +namespace { + +using cameraviews::move_keys; + +// a 20 m coach standing at Position, facing Front +cameraviews::vehicle_pose coach(glm::dvec3 const &Position = {100.0, 50.0, 200.0}, glm::dvec3 const &Front = {0.0, 0.0, -1.0}) { + cameraviews::vehicle_pose pose; + pose.position = Position; + pose.front = Front; + pose.length = 20.0; + pose.width = 3.0; + pose.height = 4.0; + return pose; +} + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +// a key held, as TCamera::Velocity has it outside the cab +double constexpr key{1.0}; + +} // namespace + +TEST_CASE("camera views: the orbit starts outside the vehicle, ahead of it on its left, above the rails") { + auto const pose{coach()}; + auto const orbit{cameraviews::orbit_start(pose)}; + auto const place{cameraviews::orbit_placement(orbit, pose)}; + auto const centre{cameraviews::orbit_centre(pose)}; + + CHECK(place.target == centre); + CHECK(glm::distance(place.eye, centre) == doctest::Approx(orbit.radius)); + CHECK(orbit.radius >= cameraviews::orbit_min_radius(pose)); + auto const offset{place.eye - centre}; + CHECK(glm::dot(offset, pose.front) > 0.0); // ahead + CHECK(glm::dot(offset, glm::dvec3{-1.0, 0.0, 0.0}) > 0.0); // on the left of a vehicle facing -z + CHECK(place.eye.y > pose.position.y + pose.height); +} + +TEST_CASE("camera views: the orbit radius stays between the body of the vehicle and its limit") { + auto const pose{coach()}; + auto orbit{cameraviews::orbit_start(pose)}; + // the up arrow held for a minute brings the camera as close as the body lets it + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, -key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(pose))); + // the diagonal of the body, so it's outside at any angle + CHECK(orbit.radius > 0.5 * std::hypot(pose.length, pose.width)); + + for (int frame = 0; frame < 600; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, 0.0, key}, {}, 0.1, pose); + } + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_max_radius)); + + // a radius not set yet becomes the default one of the vehicle + cameraviews::orbit unset; + CHECK(cameraviews::orbit_clamped(unset, pose).radius == doctest::Approx(cameraviews::orbit_start(pose).radius)); +} + +TEST_CASE("camera views: the orbit keeps above the rails however low it goes") { + auto const pose{coach()}; + for (auto const radius : {12.0, 25.0, 100.0, 250.0}) { + CAPTURE(radius); + auto orbit{cameraviews::orbit_start(pose)}; + orbit.radius = radius; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, -key, 0.0}, {}, 0.1, pose); + } + auto const place{cameraviews::orbit_placement(orbit, pose)}; + CHECK(place.eye.y >= pose.position.y + cameraviews::rail_clearance - 1e-9); + CHECK(orbit.elevation >= cameraviews::orbit_min_elevation - 1e-9); + } + // up to its highest it doesn't go over the top + auto orbit{cameraviews::orbit_start(pose)}; + for (int frame = 0; frame < 300; ++frame) { + orbit = cameraviews::orbit_moved(orbit, move_keys{0.0, key, 0.0}, {}, 0.1, pose); + } + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_max_elevation)); + // the mouse moved up a lot at once is held the same way + orbit = cameraviews::orbit_moved(orbit, {}, {10.0, 0.0}, 0.0, pose); + CHECK(orbit.elevation == doctest::Approx(cameraviews::orbit_lowest_elevation(pose, orbit.radius))); +} + +TEST_CASE("camera views: the left key takes the orbit clockwise around the vehicle, as a step to the left") { + auto const pose{coach()}; + cameraviews::orbit orbit; + orbit.radius = 30.0; + orbit = cameraviews::orbit_clamped(orbit, pose); + auto const ahead{cameraviews::orbit_placement(orbit, pose)}; + CHECK(glm::dot(ahead.eye - ahead.target, pose.front) > 0.0); + + // a little to the left from in front of the vehicle: the camera comes round to its right side + auto const moved{cameraviews::orbit_moved(orbit, move_keys{-key, 0.0, 0.0}, {}, 0.5, pose)}; + CHECK(moved.azimuth < orbit.azimuth); + auto const place{cameraviews::orbit_placement(moved, pose)}; + CHECK((place.eye - place.target).x > 0.0); // the right of a vehicle facing -z is +x + + // so does the mouse moved to the right (TCamera::Angle.y goes down) + CHECK(cameraviews::orbit_moved(orbit, {}, {0.0, -0.2}, 0.0, pose).azimuth == doctest::Approx(orbit.azimuth - 0.2)); + + // all the way round, the azimuth stays within half a turn either way + auto round{orbit}; + for (int frame = 0; frame < 200; ++frame) { + round = cameraviews::orbit_moved(round, move_keys{key, 0.0, 0.0}, {}, 0.1, pose); + REQUIRE(std::abs(round.azimuth) <= std::numbers::pi + 1e-9); + } +} + +TEST_CASE("camera views: the orbit turns with the vehicle and moves with it") { + auto const north{coach({0.0, 10.0, 0.0}, {0.0, 0.0, -1.0})}; + // the same vehicle further on, turned to face east (+x) on a slope + auto const east{coach({500.0, 20.0, -300.0}, glm::normalize(glm::dvec3{1.0, 0.05, 0.0}))}; + auto const orbit{cameraviews::orbit_start(north)}; + + auto const before{cameraviews::orbit_placement(orbit, north)}; + auto const after{cameraviews::orbit_placement(orbit, east)}; + auto const a{before.eye - before.target}; + auto const b{after.eye - after.target}; + CHECK(b.y == doctest::Approx(a.y)); + // a quarter turn clockwise from above: -z becomes +x, so the offset (x, z) becomes (-z, x) + CHECK(b.x == doctest::Approx(-a.z)); + CHECK(b.z == doctest::Approx(a.x)); + CHECK(after.target == cameraviews::orbit_centre(east)); +} + +TEST_CASE("camera views: a longer vehicle picked keeps the orbit outside its body") { + auto const shortvehicle{coach()}; + auto longvehicle{coach()}; + longvehicle.length = 40.0; + cameraviews::orbit orbit; + orbit.radius = cameraviews::orbit_min_radius(shortvehicle); + orbit = cameraviews::orbit_clamped(orbit, longvehicle); + CHECK(orbit.radius == doctest::Approx(cameraviews::orbit_min_radius(longvehicle))); + CHECK(orbit.radius > 20.0); +} + +TEST_CASE("camera views: the shunting view looks straight down, the way the user drives up the screen") { + auto const pose{coach()}; + cameraviews::topdown view; + view = cameraviews::topdown_clamped(view, pose, 100.0); + CHECK(view.height >= cameraviews::topdown_min_height(pose)); + + auto const place{cameraviews::topdown_placement(view, pose, 1)}; + CHECK(place.eye.x == doctest::Approx(pose.position.x)); + CHECK(place.eye.z == doctest::Approx(pose.position.z)); + CHECK(place.eye.y == doctest::Approx(pose.position.y + view.height)); + CHECK(place.target.x == doctest::Approx(place.eye.x)); + CHECK(place.target.z == doctest::Approx(place.eye.z)); + CHECK(place.up.z == doctest::Approx(-1.0)); // the front of the vehicle up the screen + + // driven from the rear cab, its rear is up the screen + CHECK(cameraviews::topdown_placement(view, pose, -1).up.z == doctest::Approx(1.0)); + + // the vehicle turned to face east: the screen turns with it + auto const east{coach({0.0, 0.0, 0.0}, {1.0, 0.0, 0.0})}; + CHECK(cameraviews::topdown_placement(view, east, 1).up.x == doctest::Approx(1.0)); +} + +TEST_CASE("camera views: the shunting view moves along and across the train and up, within its limits") { + auto const pose{coach()}; + auto const along{60.0}; + auto view{cameraviews::topdown_clamped({}, pose, along)}; + auto const height{view.height}; + + // the up arrow moves it up the screen, the way the user drives + auto const forward{cameraviews::topdown_moved(view, move_keys{0.0, 0.0, -key}, 1.0, pose, along)}; + CHECK(forward.along > 0.0); + auto const place{cameraviews::topdown_placement(forward, pose, -1)}; + CHECK(place.eye.z > pose.position.z); // driven from the rear cab, up the screen is +z + // the right arrow to the right of the screen + auto const right{cameraviews::topdown_moved(view, move_keys{key, 0.0, 0.0}, 1.0, pose, along)}; + CHECK(cameraviews::topdown_placement(right, pose, 1).eye.x > pose.position.x); + CHECK(cameraviews::topdown_placement(right, pose, -1).eye.x < pose.position.x); + + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{key, -key, -key}, 0.1, pose, along); + } + CHECK(view.along == doctest::Approx(along)); + CHECK(view.across == doctest::Approx(cameraviews::topdown_max_across)); + CHECK(view.height == doctest::Approx(cameraviews::topdown_min_height(pose))); + CHECK(view.height < height); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::topdown_moved(view, move_keys{0.0, key, 0.0}, 0.1, pose, along); + } + CHECK(view.height == doctest::Approx(cameraviews::topdown_max_height)); +} + +TEST_CASE("camera views: the way the user drives, seen from another vehicle of the train") { + glm::dvec3 const north{0.0, 0.0, -1.0}; + glm::dvec3 const south{0.0, 0.0, 1.0}; + CHECK(cameraviews::driving_facing(north, north, 1) == 1); + CHECK(cameraviews::driving_facing(north, north, -1) == -1); + CHECK(cameraviews::driving_facing(north, north, 0) == 1); // no cab occupied counts as the front one + // a vehicle turned round in the train + CHECK(cameraviews::driving_facing(south, north, 1) == -1); + CHECK(cameraviews::driving_facing(south, north, -1) == 1); +} + +TEST_CASE("camera views: [ and ] step through the vehicles of the train and stop at its ends") { + CHECK(cameraviews::step_index(2, 5, 1) == 3); + CHECK(cameraviews::step_index(2, 5, -1) == 1); + CHECK(cameraviews::step_index(0, 5, -1) == 0); + CHECK(cameraviews::step_index(4, 5, 1) == 4); + CHECK(cameraviews::step_index(1, 5, 10) == 4); + CHECK(cameraviews::step_index(3, 1, 1) == 0); // a vehicle alone + CHECK(cameraviews::step_index(3, 0, 1) == 0); // no train + // a picked vehicle beyond the end of a train which got shorter + CHECK(cameraviews::step_index(7, 3, 0) == 2); +} + +TEST_CASE("camera views: the head and the tail of a train are its ends the way it goes") { + std::vector const positions{{0.0, 0.0, 0.0}, {0.0, 0.0, 20.0}, {0.0, 0.0, 40.0}}; + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, -1.0}) == std::pair{0, 2}); + CHECK(cameraviews::train_ends(positions, {0.0, 0.0, 1.0}) == std::pair{2, 0}); + CHECK(cameraviews::train_ends({}, {0.0, 0.0, 1.0}) == std::pair{-1, -1}); +} + +TEST_CASE("camera views: the coupling view starts where another vehicle comes closer") { + auto const count{5}; + CHECK(cameraviews::first_coupling(-1.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(30.0, -1.0, count) == 0); + CHECK(cameraviews::first_coupling(-1.0, 30.0, count) == count); + CHECK(cameraviews::first_coupling(50.0, 10.0, count) == count); + CHECK(cameraviews::first_coupling(10.0, 50.0, count) == 0); + // a vehicle too far away doesn't count + CHECK(cameraviews::first_coupling(-1.0, cameraviews::coupler_watch_range + 1.0, count) == 0); +} + +TEST_CASE("camera views: the coupling view stands beside the coupler and steps back for the vehicle coming closer") { + cameraviews::coupler coupler; + coupler.position = {0.0, 10.0, -10.0}; + coupler.outward = {0.0, 0.0, -1.0}; + coupler.width = 3.0; + cameraviews::coupler_view const view; + + auto const alone{cameraviews::coupler_placement(view, coupler, nullptr)}; + CHECK(alone.eye.x == doctest::Approx(-(1.5 + view.distance))); // on the left of the outward way, -x + CHECK(alone.eye.z > coupler.position.z); // a little back towards its vehicle + CHECK(alone.eye.y == doctest::Approx(coupler.position.y + cameraviews::buffer_height + view.height)); + CHECK(alone.target.z < coupler.position.z); // looking out past the coupler + + // a vehicle 30 m away: the camera steps back from the track and looks between the two couplers + glm::dvec3 const other{0.0, 10.0, -40.0}; + auto const coming{cameraviews::coupler_placement(view, coupler, &other)}; + CHECK(coming.eye.x < alone.eye.x); + CHECK(coming.target.z == doctest::Approx(-25.0)); + CHECK(coming.target.y == doctest::Approx(10.0 + cameraviews::buffer_height)); + // closer, the camera comes back to the track with it + glm::dvec3 const closer{0.0, 10.0, -12.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &closer).eye.x == doctest::Approx(alone.eye.x)); + // far away, it stops stepping back + glm::dvec3 const distant{0.0, 10.0, -500.0}; + CHECK(cameraviews::coupler_placement(view, coupler, &distant).eye.x == doctest::Approx(-(1.5 + cameraviews::coupler_max_distance))); +} + +TEST_CASE("camera views: the keys of the coupling view") { + cameraviews::coupler_view view; + view = cameraviews::coupler_moved(view, move_keys{key, 0.0, 0.0}, 0.1); + CHECK(view.side == -1.0); + view = cameraviews::coupler_moved(view, {}, 0.1); + CHECK(view.side == -1.0); // stays on its side without the key + view = cameraviews::coupler_moved(view, move_keys{-key, 0.0, 0.0}, 0.1); + CHECK(view.side == 1.0); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, key, key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_max_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_max_height)); + for (int frame = 0; frame < 600; ++frame) { + view = cameraviews::coupler_moved(view, move_keys{0.0, -key, -key}, 0.1); + } + CHECK(view.distance == doctest::Approx(cameraviews::coupler_min_distance)); + CHECK(view.height == doctest::Approx(cameraviews::coupler_min_height)); + // the lowest still above the rails + CHECK(cameraviews::buffer_height + cameraviews::coupler_min_height > 0.0); +} + +TEST_CASE("camera views: along an arc of the line, and its curvature from two vehicles") { + glm::dvec3 const start{0.0, 5.0, 0.0}; + glm::dvec3 const north{0.0, 0.0, -1.0}; + auto const [straight, straightway]{cameraviews::along_arc(start, north, 0.0, 100.0)}; + CHECK(straight.z == doctest::Approx(-100.0)); + CHECK(straight.y == doctest::Approx(5.0)); + CHECK(straightway.z == doctest::Approx(-1.0)); + + // a quarter of a circle of 500 m to the left: from going north to going west + auto const radius{500.0}; + auto const [point, way]{cameraviews::along_arc(start, north, 1.0 / radius, 0.5 * std::numbers::pi * radius)}; + CHECK(point.x == doctest::Approx(-radius)); + CHECK(point.z == doctest::Approx(-radius)); + CHECK(way.x == doctest::Approx(-1.0)); + CHECK(way.z == doctest::Approx(0.0).epsilon(1e-9)); + + // two vehicles 25 m apart on that circle, the one ahead turned to the left of the one behind + auto const angle{25.0 / radius}; + glm::dvec3 const centre{-radius, 0.0, 0.0}; + glm::dvec3 const behind{0.0, 0.0, 0.0}; + glm::dvec3 const ahead{centre + glm::dvec3{radius * std::cos(angle), 0.0, -radius * std::sin(angle)}}; + glm::dvec3 const aheadway{-std::sin(angle), 0.0, -std::cos(angle)}; + auto const curvature{cameraviews::line_curvature(ahead, aheadway, behind, north)}; + CHECK(curvature == doctest::Approx(1.0 / radius).epsilon(0.01)); + // the other way round it turns to the right + CHECK(cameraviews::line_curvature(ahead, glm::dvec3{-aheadway.x, 0.0, aheadway.z}, behind, north) < 0.0); + // too close to tell + CHECK(cameraviews::line_curvature(behind, aheadway, behind, north) == 0.0); +} + +TEST_CASE("camera views: the railfan waits for the train ahead of it and moves on once it's gone by") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.head = {0.0, 0.0, 0.0}; + train.tail = {0.0, 0.0, 100.0}; + train.speed = 20.0; // 72 km/h + train.width = 3.0; + + cameraviews::trackside view; + REQUIRE(cameraviews::trackside_expired(view, train)); + view = cameraviews::trackside_next(view, train); + REQUIRE(view.placed); + // ahead of the head by the 15 s it needs to get there, beside the line on the right, at the eye of a man + CHECK(view.spot.z == doctest::Approx(-20.0 * cameraviews::trackside_lead_time)); + CHECK(view.spot.x == doctest::Approx(1.5 + cameraviews::trackside_distance)); + CHECK(view.spot.y == doctest::Approx(cameraviews::trackside_eye_height)); + + // the train comes and goes by: the railfan stays until its tail is well past + auto const spot{view.spot}; + for (int step = 0; step < 50; ++step) { + auto const run{10.0 * step}; + auto passing{train}; + passing.head.z -= run; + passing.tail.z -= run; + auto const tailpast{spot.z - passing.tail.z}; + CAPTURE(run); + CHECK(cameraviews::trackside_expired(view, passing) == (tailpast > cameraviews::trackside_passed)); + } + // and then walks to the other side of the line, ahead again + auto gone{train}; + gone.head.z -= 500.0; + gone.tail.z -= 500.0; + auto const next{cameraviews::trackside_next(view, gone)}; + CHECK(next.side == -view.side); + CHECK(next.spot.x == doctest::Approx(-(1.5 + cameraviews::trackside_distance))); + CHECK(next.spot.z < gone.head.z); + CHECK(false == cameraviews::trackside_expired(next, gone)); +} + +TEST_CASE("camera views: the railfan's spot ahead keeps to the line in a curve, and nearby when the train stands") { + cameraviews::train_motion train; + train.direction = {0.0, 0.0, -1.0}; + train.speed = 40.0; + auto const radius{400.0}; + train.curvature = 1.0 / radius; + cameraviews::trackside const view; + auto const next{cameraviews::trackside_next(view, train)}; + // the centre of the curve is on the left of the head, the railfan on the right of the line: outside the circle + glm::dvec3 const centre{-radius, 0.0, 0.0}; + CHECK(flat_distance(next.spot, centre) == doctest::Approx(radius + 0.5 * train.width + cameraviews::trackside_distance)); + // no further round than a quarter of the circle + CHECK(next.spot.z >= -radius - 1e-6); + + // a train standing still gets a railfan at the shortest lead + auto standing{train}; + standing.speed = 0.0; + standing.curvature = 0.0; + auto const nearby{cameraviews::trackside_next(view, standing)}; + CHECK(nearby.spot.z == doctest::Approx(-cameraviews::trackside_min_lead)); + // and as long as it stands, the railfan stays + CHECK(false == cameraviews::trackside_expired(nearby, standing)); + // a train gone far away (moved by the user, or a long way back) gets a new railfan + auto away{standing}; + away.head = {0.0, 0.0, 2000.0}; + away.tail = {0.0, 0.0, 2100.0}; + CHECK(cameraviews::trackside_expired(nearby, away)); +} diff --git a/tests/unit/test_camshaft.cpp b/tests/unit/test_camshaft.cpp index 940616a62..c53cf7490 100644 --- a/tests/unit/test_camshaft.cpp +++ b/tests/unit/test_camshaft.cpp @@ -67,23 +67,25 @@ definition skoda() { // the locomotive running with the line contactors closed and the camshaft at Position, the master controller moved // to Controller, in the given direction; the time since the last step of the camshaft long enough for the next one -void running(TMoverParameters &Locomotive, int const Direction, int const Position, int const Controller) { +void running(physics::Vehicle &Locomotive, int const Direction, int const Position, int const Controller) { Locomotive.CabActive = 1; Locomotive.DirActive = Direction; - Locomotive.Mains = true; - Locomotive.PipePress = 5.0; // bar, the pressure switch lets the line contactors close - Locomotive.BrakePress = 0.0; - Locomotive.StLinFlag = true; + Locomotive.lineBreaker.Close(); + Locomotive.brakePipe.SetPressure(5.0); // bar, the pressure switch lets the line contactors close + Locomotive.brakes.cylinderPressure = 0.0; + Locomotive.lineContactors.Close(); Locomotive.MainCtrlActualPos = Position; - Locomotive.MainCtrlPos = Controller; - Locomotive.LastRelayTime = 10.0; + Locomotive.SetMainCtrlPos(Controller); + Locomotive.lineContactors.RestartSwitchTimer(); + Locomotive.lineContactors.AdvanceSwitchTimer(10.0); } // steps the camshaft as the physics does, each step once the delay since the previous one passed; returns where it // ended up -int run_camshaft(TMoverParameters &Locomotive, int const Steps) { +int run_camshaft(physics::Vehicle &Locomotive, int const Steps) { for (int step = 0; step < Steps; ++step) { - Locomotive.LastRelayTime = 10.0; + Locomotive.lineContactors.RestartSwitchTimer(); + Locomotive.lineContactors.AdvanceSwitchTimer(10.0); Locomotive.AutoRelayCheck(); } return Locomotive.MainCtrlActualPos; @@ -93,43 +95,43 @@ int run_camshaft(TMoverParameters &Locomotive, int const Steps) { TEST_CASE("camshaft: running backwards, the camshaft goes back down from the last series position (eu07/maszyna#393)") { vehicle locomotive{skoda()}; - auto &mover{locomotive.mover()}; - REQUIRE(mover.HasCamshaft); - REQUIRE(mover.RlistSize == 43); - REQUIRE(mover.RList[22].Bn == 1); - REQUIRE(mover.RList[23].Bn == 2); + auto &physics{locomotive.physics()}; + REQUIRE(physics.HasCamshaft); + REQUIRE(physics.RlistSize == 43); + REQUIRE(physics.RList[22].Bn == 1); + REQUIRE(physics.RList[23].Bn == 2); SUBCASE("the controller turned back a few positions") { - running(mover, -1, 22, 15); - CHECK(run_camshaft(mover, 1) == 21); // it used to stay at 22 - CHECK(run_camshaft(mover, 10) == 15); + running(physics, -1, 22, 15); + CHECK(run_camshaft(physics, 1) == 21); // it used to stay at 22 + CHECK(run_camshaft(physics, 10) == 15); } SUBCASE("the controller turned back to zero: the camshaft runs down and the line contactors open") { - running(mover, -1, 22, 0); - run_camshaft(mover, 30); - CHECK(mover.MainCtrlActualPos == 0); - CHECK_FALSE(mover.StLinFlag); // the motors don't pull any more + running(physics, -1, 22, 0); + run_camshaft(physics, 30); + CHECK(physics.MainCtrlActualPos == 0); + CHECK_FALSE(physics.lineContactors.IsClosed()); // the motors don't pull any more } } TEST_CASE("camshaft: running backwards, the camshaft still doesn't go past the series connection") { vehicle locomotive{skoda()}; - auto &mover{locomotive.mover()}; - running(mover, -1, 20, 43); - CHECK(run_camshaft(mover, 10) == 22); + auto &physics{locomotive.physics()}; + running(physics, -1, 20, 43); + CHECK(run_camshaft(physics, 10) == 22); SUBCASE("unless more branches are allowed backwards") { - mover.BackwardsBranchesAllowed = 2; - CHECK(run_camshaft(mover, 20) == 34); + physics.BackwardsBranchesAllowed = 2; + CHECK(run_camshaft(physics, 20) == 34); } } TEST_CASE("camshaft: running forwards, the camshaft goes through all the connections and back") { vehicle locomotive{skoda()}; - auto &mover{locomotive.mover()}; - running(mover, 1, 20, 43); - CHECK(run_camshaft(mover, 30) == 43); + auto &physics{locomotive.physics()}; + running(physics, 1, 20, 43); + CHECK(run_camshaft(physics, 30) == 43); - mover.MainCtrlPos = 10; - CHECK(run_camshaft(mover, 40) == 10); + physics.SetMainCtrlPos(10); + CHECK(run_camshaft(physics, 40) == 10); } diff --git a/tests/unit/test_catenary_file_name.cpp b/tests/unit/test_catenary_file_name.cpp new file mode 100644 index 000000000..7d55494e8 --- /dev/null +++ b/tests/unit/test_catenary_file_name.cpp @@ -0,0 +1,26 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "editor/editorCatenaryFile.hpp" + +// the names of the catenary files the editor makes (editor/editorCatenaryFile.hpp): the directive which includes the file is +// read as tokens, and the file is written into the folder of the scenery + +TEST_CASE("catenary file name: what the directive and the folder of the scenery take") { + CHECK(catenary_file_name_valid("linia8.scm")); + CHECK(catenary_file_name_valid("siec/linia8.scm")); + CHECK(catenary_file_name_valid("siec\\linia_8.scm")); + // a space or a ';' splits the token: the directive would name another file + CHECK_FALSE(catenary_file_name_valid("catenary linia 8.scm")); + CHECK_FALSE(catenary_file_name_valid("linia\t8.scm")); + CHECK_FALSE(catenary_file_name_valid("linia;8.scm")); + CHECK_FALSE(catenary_file_name_valid("\"linia8.scm\"")); + // out of the folder of the scenery + CHECK_FALSE(catenary_file_name_valid("..\\linia8.scm")); + CHECK_FALSE(catenary_file_name_valid("siec/../../linia8.scm")); + CHECK_FALSE(catenary_file_name_valid("/linia8.scm")); + CHECK_FALSE(catenary_file_name_valid("c:\\linia8.scm")); + CHECK_FALSE(catenary_file_name_valid("siec//linia8.scm")); + CHECK_FALSE(catenary_file_name_valid("siec/")); + CHECK_FALSE(catenary_file_name_valid("")); +} diff --git a/tests/unit/test_cntrl.cpp b/tests/unit/test_cntrl.cpp index c73c45d85..428381092 100644 --- a/tests/unit/test_cntrl.cpp +++ b/tests/unit/test_cntrl.cpp @@ -5,43 +5,43 @@ using test::definition; using test::vehicle; -// the Cntrl. section of the vehicle definition, as read by TMoverParameters::LoadFIZ_Cntrl() +// the Cntrl. section of the vehicle definition, as read by physics::Vehicle::LoadFIZ_Cntrl() TEST_CASE("cntrl: the brake delays of the settings come from BDelay1 to BDelay4") { vehicle wagon{definition::load("wagon").set("Cntrl", "BDelay1", 10.0).set("Cntrl", "BDelay2", 20.0).set("Cntrl", "BDelay3", 30.0).set("Cntrl", "BDelay4", 40.0)}; - CHECK(wagon->BrakeDelay[0] == doctest::Approx(10.0)); + CHECK(wagon->brakes.config.delays[0] == doctest::Approx(10.0)); // the vehicle varies the others a little, by 0.83 to 0.9 (CheckLocomotiveParameters()) for (auto setting{1}; setting < 4; ++setting) { CAPTURE(setting); auto const given{10.0 * (setting + 1)}; - CHECK(wagon->BrakeDelay[setting] >= 0.83 * given); - CHECK(wagon->BrakeDelay[setting] <= 0.9 * given); + CHECK(wagon->brakes.config.delays[setting] >= 0.83 * given); + CHECK(wagon->brakes.config.delays[setting] <= 0.9 * given); } } TEST_CASE("cntrl: the relays of a multiple unit start on their own, of other vehicles by hand") { SUBCASE("multiple unit") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt")}; - REQUIRE(unit->TrainType == dt_EZT); - CHECK(unit->GroundRelayStart == start_t::automatic); - CHECK(unit->ConverterOverloadRelayStart == start_t::converter); // activates when the converter is switched off + REQUIRE(unit->TrainType() == train_type::emu); + CHECK(unit->protection.config.groundStart == start_t::automatic); + CHECK(unit->converter.config.overloadRelayStart == start_t::converter); // activates when the converter is switched off } SUBCASE("other vehicle") { vehicle wagon{definition::load("wagon")}; - CHECK(wagon->GroundRelayStart == start_t::manual); - CHECK(wagon->ConverterOverloadRelayStart == start_t::manual); + CHECK(wagon->protection.config.groundStart == start_t::manual); + CHECK(wagon->converter.config.overloadRelayStart == start_t::manual); } SUBCASE("given in the definition") { vehicle unit{definition::load("wagon").set("Param", "Type", "ezt").set("Cntrl", "GroundRelayStart", "Manual").set("Cntrl", "ConverterOverloadRelayStart", "Automatic")}; - CHECK(unit->GroundRelayStart == start_t::manual); - CHECK(unit->ConverterOverloadRelayStart == start_t::automatic); + CHECK(unit->protection.config.groundStart == start_t::manual); + CHECK(unit->converter.config.overloadRelayStart == start_t::automatic); } } namespace { // the first position of the master controller after Position without the starting resistors in the circuit -int resistance_free_position(TMoverParameters const &Vehicle, int Position = 0) { +int resistance_free_position(physics::Vehicle const &Vehicle, int Position = 0) { for (auto position{Position + 1}; position <= Vehicle.MainCtrlPosNo; ++position) { if (Vehicle.RList[position].R < 0.01) { return position; @@ -53,8 +53,8 @@ int resistance_free_position(TMoverParameters const &Vehicle, int Position = 0) // the vehicle with its cab occupied, the master controller set to Position and the shunt controller off void controllers_at(vehicle &Vehicle, int Position) { Vehicle->CabActive = 1; - Vehicle->MainCtrlPos = Position; - Vehicle->ScndCtrlPos = 0; + Vehicle->SetMainCtrlPos(Position); + Vehicle->SetScndCtrlPos(0); } } // namespace @@ -64,8 +64,8 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and CAPTURE(path); vehicle locked{definition::fiz(path).set("Cntrl", "ScndCtrlResistiveLock", "Yes"), 0.0, "test", 1}; REQUIRE(locked->ScndCtrlResistiveLock); - REQUIRE(locked->ScndCtrlPosNo > 0); - auto const resistancefree{resistance_free_position(locked.mover())}; + REQUIRE(locked->ScndCtrlPosNo() > 0); + auto const resistancefree{resistance_free_position(locked.physics())}; REQUIRE(resistancefree > 1); if (resistancefree <= 1) { continue; // not reached, the REQUIRE above ends the test; tells the static analysis the index below is in range @@ -77,23 +77,23 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and CHECK(locked->IsScndCtrlLockedByMainCtrl()); CHECK_FALSE(locked->IncScndCtrl(1)); CHECK_FALSE(locked->IncScndCtrl(2)); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->ScndCtrlPos() == 0); } SUBCASE("resistive positions") { for (auto position{1}; position < resistancefree; ++position) { CAPTURE(position); controllers_at(locked, position); CHECK_FALSE(locked->IncScndCtrl(1)); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->ScndCtrlPos() == 0); } } SUBCASE("every resistance-free position") { - for (auto position{resistancefree}; position > 0; position = resistance_free_position(locked.mover(), position)) { + for (auto position{resistancefree}; position > 0; position = resistance_free_position(locked.physics(), position)) { CAPTURE(position); controllers_at(locked, position); CHECK_FALSE(locked->IsScndCtrlLockedByMainCtrl()); CHECK(locked->IncScndCtrl(1)); - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); } } SUBCASE("the shunt goes down on a resistance-free position") { @@ -101,48 +101,48 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and REQUIRE(locked->IncScndCtrl(1)); REQUIRE(locked->IncScndCtrl(1)); CHECK(locked->DecScndCtrl(1)); - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); CHECK(locked->DecScndCtrl(2)); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->ScndCtrlPos() == 0); } SUBCASE("the shunt doesn't go down on a resistive position either") { // a state the lock doesn't let arise (see below), set by hand to check the controller alone controllers_at(locked, resistancefree - 1); - locked->ScndCtrlPos = 1; + locked->SetScndCtrlPos(1); CHECK(locked->IsScndCtrlLockedByMainCtrl()); CHECK_FALSE(locked->DecScndCtrl(1)); CHECK_FALSE(locked->DecScndCtrl(2)); - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); } SUBCASE("the master controller taken back from a shunt step drops the shunt") { controllers_at(locked, resistancefree); REQUIRE(locked->IncScndCtrl(1)); - if (locked->TrainType == dt_ET22) { + if (locked->TrainType() == train_type::et22) { // the ET22's master controller doesn't turn with the shunt on: the shunt goes off first, as before CHECK_FALSE(locked->DecMainCtrl(1)); - CHECK(locked->MainCtrlPos == resistancefree); + CHECK(locked->MainCtrlPos() == resistancefree); CHECK(locked->DecScndCtrl(1)); } CHECK(locked->DecMainCtrl(1)); - CHECK(locked->MainCtrlPos == resistancefree - 1); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->MainCtrlPos() == resistancefree - 1); + CHECK(locked->ScndCtrlPos() == 0); // and the master controller goes on down to zero, nothing left locked - while (locked->MainCtrlPos > 0 && locked->DecMainCtrl(1)) { + while (locked->MainCtrlPos() > 0 && locked->DecMainCtrl(1)) { } - CHECK(locked->MainCtrlPos == 0); + CHECK(locked->MainCtrlPos() == 0); } SUBCASE("the master controller set directly (AI, consist) drops the shunt in the next update") { controllers_at(locked, resistancefree); REQUIRE(locked->IncScndCtrl(1)); - locked->MainCtrlPos = resistancefree - 1; + locked->SetMainCtrlPos(resistancefree - 1); locked.step(); - CHECK(locked->ScndCtrlPos == 0); - CHECK(locked->MainCtrlPos == resistancefree - 1); + CHECK(locked->ScndCtrlPos() == 0); + CHECK(locked->MainCtrlPos() == resistancefree - 1); } SUBCASE("the master controller moved up from a shunt step onto a resistive position drops the shunt") { // the last series position, followed by the resistive parallel ones auto lastseries{0}; - for (auto position{resistancefree}; position > 0 && position < locked->MainCtrlPosNo; position = resistance_free_position(locked.mover(), position)) { + for (auto position{resistancefree}; position > 0 && position < locked->MainCtrlPosNo; position = resistance_free_position(locked.physics(), position)) { if (locked->RList[position + 1].R >= 0.01) { lastseries = position; break; @@ -152,14 +152,14 @@ TEST_CASE("cntrl: ScndCtrlResistiveLock keeps the field shunting off at zero and controllers_at(locked, lastseries); locked->DirActive = 1; REQUIRE(locked->IncScndCtrl(1)); - if (locked->TrainType == dt_ET22) { + if (locked->TrainType() == train_type::et22) { CHECK_FALSE(locked->IncMainCtrl(1)); // the ET22's interlock, as before - CHECK(locked->ScndCtrlPos == 1); + CHECK(locked->ScndCtrlPos() == 1); } else { CHECK(locked->IncMainCtrl(1)); - CHECK(locked->MainCtrlPos == lastseries + 1); - CHECK(locked->ScndCtrlPos == 0); + CHECK(locked->MainCtrlPos() == lastseries + 1); + CHECK(locked->ScndCtrlPos() == 0); } } } @@ -175,7 +175,7 @@ TEST_CASE("cntrl: without ScndCtrlResistiveLock the field shunting engages on an controllers_at(unlocked, position); CHECK_FALSE(unlocked->IsScndCtrlLockedByMainCtrl()); CHECK(unlocked->IncScndCtrl(1)); - CHECK(unlocked->ScndCtrlPos == 1); + CHECK(unlocked->ScndCtrlPos() == 1); } } } diff --git a/tests/unit/test_collisions.cpp b/tests/unit/test_collisions.cpp new file mode 100644 index 000000000..e63cb6c71 --- /dev/null +++ b/tests/unit/test_collisions.cpp @@ -0,0 +1,1506 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" +#include "vehicle.h" +#include "physics/collision.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" + +#include +#include +#include +#include + +// collisions past the buffers with physics.collisions new (physics/collision.h): the crush of the ends, the override, +// the push off the track, and what they do in trains of real vehicles + +using test::consist; +using test::definition; +using test::vehicle; +namespace cl = collision; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of collisions for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::collision_model m_previous; +}; + +// the given setting of a global flag for the test, restored after it +class flag_setting { +public: + flag_setting(bool &Flag, bool Enabled) : m_flag{Flag}, m_previous{Flag} { m_flag = Enabled; } + ~flag_setting() { m_flag = m_previous; } + flag_setting(flag_setting const &) = delete; + flag_setting &operator=(flag_setting const &) = delete; + +private: + bool &m_flag; + bool m_previous; +}; + +// ---- the hit of two masses on the stop of their buffers, the way the vehicles take it + +struct pair_outcome { + double crush1{0.0}; + double crush2{0.0}; + double velocity1{0.0}; + double velocity2{0.0}; + double peak{0.0}; // force +}; + +// the first mass runs at the velocity into the second one standing, their buffers pressed all the way already; the +// springs carry the given force while pressed, stepped by Dt as the vehicles are: the springs over the step first, the +// hit after them +pair_outcome hit_pair(cl::end_state First, cl::end_state Second, double const Mass1, double const Mass2, double const Velocity, double const Springs, double const Dt) { + pair_outcome result; + auto velocity1{Velocity}; + auto velocity2{0.0}; + for (int step = 0; step < 1000000; ++step) { + velocity1 -= Springs * Dt / Mass1; + velocity2 += Springs * Dt / Mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.mass1 = Mass1; + input.mass2 = Mass2; + input.restitution = 0.2; + input.stiffness = 1.4e8; + input.springs = Springs; + input.dt = Dt; + auto const hit{cl::hit(First, Second, input)}; + if (false == hit.crushing) { + // elastic: bounced apart with the restitution + auto const reduced{Mass1 * Mass2 / (Mass1 + Mass2)}; + auto const impulse{reduced * closing * (1.0 + input.restitution)}; + velocity1 -= impulse / Mass1; + velocity2 += impulse / Mass2; + break; + } + velocity1 -= hit.impulse / Mass1; + velocity2 += hit.impulse / Mass2; + First.crush += hit.crush1; + Second.crush += hit.crush2; + result.peak = std::max(result.peak, hit.force); + if (hit.velocity <= 0.0) { + break; + } + } + result.crush1 = First.crush; + result.crush2 = Second.crush; + result.velocity1 = velocity1; + result.velocity2 = velocity2; + return result; +} + +cl::crush_curve const wagon_curve{cl::default_crush(cl::vehicle_kind::wagon)}; +cl::crush_curve const locomotive_curve{cl::default_crush(cl::vehicle_kind::locomotive)}; + +// ---- trains of real vehicles + +bool derailed(physics::Vehicle const &Vehicle) { + return Vehicle.DamageFlag.HasAll(VehicleDamage::derailed); +} + +double crush_of(physics::Vehicle const &Vehicle) { + return std::max(Vehicle.Couplers[VehicleEnd::front].crush, Vehicle.Couplers[VehicleEnd::rear].crush); +} + +// a mixed freight train as the PoC has it: every third wagon from the given one an empty two-axle 3WL (10.5 t), the +// rest 430W coal wagons loaded full (80 t) +definition mixed_wagon(int const Index) { + return definition::fiz(Index % 3 == 1 ? "3wl_v2/3wl" : "430w_v2/430w"); +} + +vehicle &add_mixed(consist &Train, int const Index, CouplingSet const couplings, double const Velocity, double const Gap) { + auto &wagon{Train.add(mixed_wagon(Index), 0, couplings, Velocity, Gap)}; + if (Index % 3 != 1) { + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + } + return wagon; +} + +struct crash_outcome { + int derailed{0}; + int overridden{0}; + int pushed{0}; + int crushed{0}; // ends crushed past the mark + int broken{0}; // couplings torn off + double crush{0.0}; // the deepest crush of an end + bool locomotive{false}; // it derailed + std::string list; // what happened to which vehicle, for the messages +}; + +// the PoC of G14: a locomotive (EU07, 80 t) with 12 mixed wagons running into the rear of 8 mixed wagons standing +// braked, in emergency, on a straight track or in a curve +crash_outcome freight_crash(double const Speed, double const Radius, double const Dt = 0.01) { + test::track track; + track.radius = Radius; + consist train; + // the standing train, the wagon it's hit at last; its brakes charged, then in emergency + constexpr int standing{8}; + for (int i = standing - 1; i >= 0; --i) { + add_mixed(train, i, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, track); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, track); + // the train running into it, its locomotive leading, a metre short of the hit + train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, Speed, 1.0); + for (int i = 0; i < 12; ++i) { + add_mixed(train, i, consist::full_coupling, Speed, 0.0); + } + train.run(12.0, track, Dt); + + crash_outcome result; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const &vehicle{train[i].physics()}; + auto const name{i < standing ? std::format("standing {}", standing - 1 - i) : i == standing ? std::string{"locomotive"} : std::format("running {}", i - standing - 1)}; + for (auto const end : VehicleEnds) { + if (vehicle.Couplers[end].crush >= cl::crush_mark) { + ++result.crushed; + } + } + result.crush = std::max(result.crush, crush_of(vehicle)); + if (derailed(vehicle)) { + ++result.derailed; + result.overridden += vehicle.CollisionDerail() == COLLISION_OVERRIDE; + result.pushed += vehicle.CollisionDerail() == COLLISION_PUSHED_OFF; + result.locomotive = result.locomotive || i == standing; + result.list += std::format("{} ({:.1f} t) {}; ", name, vehicle.TotalMass() / 1000.0, vehicle.CollisionDerail() == COLLISION_OVERRIDE ? "overrode" : "pushed off"); + } + else if (crush_of(vehicle) >= cl::crush_mark) { + result.list += std::format("{} crushed {:.2f} m; ", name, crush_of(vehicle)); + } + } + for (std::size_t i = 0; i + 1 < train.size(); ++i) { + result.broken += train[i]->Couplers[VehicleEnd::rear].broken; + } + return result; +} + +// a locomotive running into a loaded coal wagon standing free, both on the rails: the crush of the pair after the hit +double locomotive_into_wagon(double const Speed, double const Dt) { + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + // behind the wagon, running forwards into its rear end + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, Speed, 0.5)}; + train.run(3.0, {}, Dt); + return wagon->Couplers[VehicleEnd::rear].crush + locomotive->Couplers[VehicleEnd::front].crush; +} + +// the energy the crush of both ends of the pair took, by their curves [J] +double crush_energy(physics::Vehicle const &First, VehicleEnd const FirstEnd, physics::Vehicle const &Second, VehicleEnd const SecondEnd) { + return First.crush_curve_at(FirstEnd).energy(0.0, First.Couplers[FirstEnd].crush) + Second.crush_curve_at(SecondEnd).energy(0.0, Second.Couplers[SecondEnd].crush); +} + +// what the buffers of EN 15551 of the two ends take in [J] +double capacity_of(physics::Vehicle const &First, VehicleEnd const FirstEnd, physics::Vehicle const &Second, VehicleEnd const SecondEnd) { + return cl::buffer_capacity(First.Couplers[FirstEnd].collision, First.collision_kind()) + cl::buffer_capacity(Second.Couplers[SecondEnd].collision, Second.collision_kind()); +} + +// the kinetic energy of the relative motion of two vehicles closing in at the velocity [J] +double relative_energy(physics::Vehicle const &First, physics::Vehicle const &Second, double const Velocity) { + auto const mass{First.TotalMass() * Second.TotalMass() / (First.TotalMass() + Second.TotalMass())}; + return 0.5 * mass * Velocity * Velocity; +} + +struct contact_outcome { + double crush{0.0}; // of both ends [m] + double energy{0.0}; // the crush took [J] + double available{0.0}; // the kinetic energy of the hit past the buffers of EN 15551 [J] + bool derailed{false}; // either vehicle +}; + +// the second vehicle runs into the rear end of the first one standing, Gap metres short of the hit (negative: the +// buffers pressed that far already), unbraked and alone on the track +contact_outcome contact(definition const &Front, definition const &Back, double const Speed, double const Gap, double const Seconds = 5.0, double const Dt = 0.01) { + consist train; + auto &front{train.add(Front)}; + auto &back{train.add(Back, 0, Coupling::none, Speed, Gap)}; + train.run(Seconds, {}, Dt); + contact_outcome result; + result.crush = front->Couplers[VehicleEnd::rear].crush + back->Couplers[VehicleEnd::front].crush; + result.energy = crush_energy(front.physics(), VehicleEnd::rear, back.physics(), VehicleEnd::front); + result.available = std::max(0.0, relative_energy(front.physics(), back.physics(), Speed * kmh) - capacity_of(front.physics(), VehicleEnd::rear, back.physics(), VehicleEnd::front)); + result.derailed = derailed(front.physics()) || derailed(back.physics()); + return result; +} + +// a coach of data/wagon.json of the given mass without its rotating masses +definition coach(double const Mass) { + return definition::load("wagon").set("Param", "M", Mass); +} + +// Y / Q of the leading wheel of the vehicle at the end pressed in by its coupling, as check_pushed_off() takes it +double pushed_ratio_of(physics::Vehicle const &Vehicle, VehicleEnd const End, double const OtherLength, double const Radius) { + cl::pushed_vehicle pushed; + pushed.mass = Vehicle.TotalMass() - Vehicle.Mred(); + pushed.axles = Vehicle.NAxles() > 0 ? Vehicle.NAxles() : 4; + pushed.length = Vehicle.Dim.L; + pushed.pivots = Vehicle.BDist(); + pushed.axle_base = Vehicle.ADist() > 0.0 ? Vehicle.ADist() : Vehicle.BDist(); + cl::pushed_end end; + end.force = std::max(0.0, (End == VehicleEnd::front ? -1.0 : 1.0) * Vehicle.Couplers[End].CForce); + end.other_length = OtherLength; + end.crush = Vehicle.Couplers[End].crush; + return cl::pushed_ratio(pushed, end, Radius); +} + +// a loaded 430W coal wagon +vehicle &add_loaded(consist &Train, CouplingSet const couplings, double const Velocity, double const Gap) { + auto &wagon{Train.add(definition::fiz("430w_v2/430w"), 0, couplings, Velocity, Gap)}; + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + return wagon; +} + +} // namespace + +// ---- the crush curve + +TEST_CASE("collisions: the crush curve, a peak, a plateau, packing down, and the limit") { + auto const &curve{wagon_curve}; + CHECK(curve.force(0.0) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.049) == doctest::Approx(3.0e6)); + CHECK(curve.force(0.05) == doctest::Approx(2.0e6)); + CHECK(curve.force(0.79) == doctest::Approx(2.0e6)); + // 2 / m past 0.8 m: a metre further it's three times the plateau + CHECK(curve.force(1.3) == doctest::Approx(2.0e6 * (1.0 + 2.0 * 0.5))); + CHECK_FALSE(std::isfinite(curve.force(1.5))); + // the energy is the area under it + CHECK(curve.energy(0.0, 0.05) == doctest::Approx(3.0e6 * 0.05)); + CHECK(curve.energy(0.0, 0.8) == doctest::Approx(3.0e6 * 0.05 + 2.0e6 * 0.75)); + CHECK(curve.energy(0.8, 1.3) == doctest::Approx(0.5 * (2.0e6 + 4.0e6) * 0.5)); + CHECK(curve.energy(0.0, 0.3) + curve.energy(0.3, 1.0) == doctest::Approx(curve.energy(0.0, 1.0))); + // past the limit there's nothing more to crush + CHECK(curve.energy(1.5, 3.0) == 0.0); + + // the kinds of vehicles; a crash zone gives a steady force with no peak + CHECK(locomotive_curve.peak > wagon_curve.peak); + auto const zone{cl::default_crush(cl::vehicle_kind::crash_zone)}; + CHECK(zone.force(0.0) == doctest::Approx(zone.force(0.5))); + // the keys of the .fiz override the defaults of the kind + cl::end_definition given; + given.plateau = 1.0e6; + given.crash_zone = true; + auto const own{cl::crush_of(given, cl::vehicle_kind::coach)}; + CHECK(own.plateau == doctest::Approx(1.0e6)); + CHECK(own.densify == doctest::Approx(zone.densify)); + CHECK(cl::anticlimber_of(given, cl::vehicle_kind::coach)); + CHECK_FALSE(cl::anticlimber_of({}, cl::vehicle_kind::locomotive)); +} + +TEST_CASE("collisions: the buffers of EN 15551, their stroke and energy") { + for (auto const category : {cl::buffer_category::A, cl::buffer_category::B, cl::buffer_category::C, cl::buffer_category::L, cl::buffer_category::passenger}) { + auto const rated{cl::rating(category)}; + for (auto const progression : {0.0, 0.5, 0.9}) { + auto const curve{cl::buffer_curve(category, progression)}; + CHECK(curve.travel == doctest::Approx(rated.stroke)); + // two buffers side by side + CHECK(curve.energy(curve.travel) == doctest::Approx(2.0 * rated.energy)); + } + } + CHECK(cl::rating(cl::buffer_category::A).energy < cl::rating(cl::buffer_category::C).energy); + CHECK(cl::buffer_category_of('C') == cl::buffer_category::C); + CHECK_FALSE(cl::buffer_category_of('X').has_value()); + // the triangle of category A: 2 x 30 kJ over 105 mm is about 1.1 MN at the end of the stroke, 570 kN a buffer + CHECK(cl::buffer_curve(cl::buffer_category::A, 0.0).end_force() == doctest::Approx(4.0 * 30.0e3 / 0.105)); +} + +// ---- the hit + +TEST_CASE("collisions: a hit the steel takes stays elastic, a harder one crushes the weaker end") { + cl::hit_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.stiffness = 1.4e8; + input.dt = 0.01; + // 40 t reduced: the steel takes 3 MN at 3 / sqrt(1.4e8 * 4e4) = 1.27 m/s + input.velocity = 1.0; + CHECK_FALSE(cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input).crushing); + input.velocity = 5.0; + auto const hit{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + REQUIRE(hit.crushing); + // the wagon gives, the locomotive doesn't; at its peak force for the whole step + CHECK(hit.crush1 == 0.0); + CHECK(hit.crush2 > 0.0); + CHECK(hit.force == doctest::Approx(3.0e6)); + CHECK(hit.impulse == doctest::Approx(3.0e6 * 0.01)); + CHECK(hit.duration == doctest::Approx(0.01)); + CHECK(hit.velocity == doctest::Approx(5.0 - 3.0e6 * 0.01 / 40.0e3)); + // with the springs carrying a part of the force, the hit adds the rest + input.springs = 1.0e6; + auto const sprung{cl::hit({locomotive_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(sprung.impulse == doctest::Approx(2.0e6 * 0.01)); + // two alike crush alike + input.springs = 0.0; + auto const alike{cl::hit({wagon_curve, 0.0}, {wagon_curve, 0.0}, input)}; + CHECK(alike.crush1 == doctest::Approx(alike.crush2)); + // a wall: the end crushed all the way doesn't give, the other one does + auto const wall{cl::hit({wagon_curve, 2.0}, {wagon_curve, 0.0}, input)}; + CHECK(wall.crush1 == 0.0); + CHECK(wall.crush2 > 0.0); + // both crushed all the way: rigid, the legacy exchange + CHECK_FALSE(cl::hit({wagon_curve, 2.0}, {wagon_curve, 2.0}, input).crushing); +} + +TEST_CASE("collisions: the crush doesn't depend on the step, and it takes the energy of the hit") { + struct pair { + char const *name; + double mass1; + double mass2; + double velocity; + double springs; + }; + for (auto const &[name, mass1, mass2, velocity, springs] : { + pair{"80 t into 80 t at 25 km/h", 80.0e3, 80.0e3, 25.0 * kmh, 0.0}, + pair{"80 t into 80 t at 40 km/h, the springs at 1 MN", 80.0e3, 80.0e3, 40.0 * kmh, 1.0e6}, + pair{"80 t into 12 t at 40 km/h", 80.0e3, 12.0e3, 40.0 * kmh, 0.5e6}, + pair{"300 t into 80 t at 35 km/h, past the densification", 300.0e3, 80.0e3, 35.0 * kmh, 0.0}, + }) { + CAPTURE(name); + auto const fine{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, 0.001)}; + REQUIRE(fine.crush2 > 0.05); + CHECK(fine.crush1 == 0.0); + for (auto const dt : {0.005, 0.01, 0.05}) { + CAPTURE(dt); + auto const coarse{hit_pair({locomotive_curve, 0.0}, {wagon_curve, 0.0}, mass1, mass2, velocity, springs, dt)}; + CHECK(coarse.crush2 == doctest::Approx(fine.crush2).epsilon(0.02)); + // the momentum stays with the pair + CHECK(mass1 * coarse.velocity1 + mass2 * coarse.velocity2 == doctest::Approx(mass1 * velocity)); + // never past the force the wagon gives at: its peak, or what it packed down to + CHECK(coarse.peak <= std::max(wagon_curve.peak, wagon_curve.force(coarse.crush2)) * (1.0 + 1e-9)); + } + if (springs == 0.0) { + // the energy of the relative motion goes into the crush, but for what the steel takes back + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + auto const kinetic{0.5 * reduced * velocity * velocity}; + auto const crushforce{wagon_curve.force(fine.crush2)}; + auto const elastic{crushforce * crushforce / (2.0 * 1.4e8)}; + CHECK(wagon_curve.energy(0.0, fine.crush2) == doctest::Approx(kinetic - elastic).epsilon(0.01)); + } + } +} + +TEST_CASE("collisions: the crush of two pairs of masses at the speeds of the table") { + // 80 t on 80 t: the steel takes the hit up to 1.3 m/s past the buffers; at 25 km/h the two ends alike crush by + // 0.4 m between them, the 0.97 MJ at 3 MN to 0.05 m each and at 2 MN past it (the buffers aren't here) + auto const slow{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 1.2, 0.0, 0.01)}; + CHECK(slow.crush1 + slow.crush2 == 0.0); + auto const hard{hit_pair({wagon_curve, 0.0}, {wagon_curve, 0.0}, 80.0e3, 80.0e3, 25.0 * kmh, 0.0, 0.01)}; + CHECK(hard.crush1 + hard.crush2 > 0.2); + CHECK(hard.crush1 + hard.crush2 < 0.5); +} + +// ---- override + +TEST_CASE("collisions: the lighter or the higher vehicle climbs onto the other one, both past a deeper crush") { + cl::override_input input; + input.mass1 = 80.0e3; + input.mass2 = 80.0e3; + input.height1 = 1.040; + input.height2 = 1.040; + SUBCASE("a shallow crush holds") { + input.crush1 = 0.3; + auto const result{cl::override_of(input)}; + CHECK_FALSE(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("alike: past 0.35 m they hold, past 0.6 m both climb") { + input.crush1 = 0.4; + CHECK_FALSE(cl::override_of(input).first); + input.crush2 = 0.25; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK(result.second); + } + SUBCASE("the lighter one climbs past 0.35 m") { + input.mass1 = 12.0e3; + input.crush1 = 0.4; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("40 mm higher, the higher one climbs") { + input.height2 = 1.000; + input.crush1 = 0.2; + input.crush2 = 0.2; + auto const result{cl::override_of(input)}; + CHECK(result.first); + CHECK_FALSE(result.second); + } + SUBCASE("interlocked anticlimbers hold them until the crush zone of an end is used up") { + input.anticlimbers = true; + input.zone1 = 0.8; + input.zone2 = 0.8; + input.height2 = 1.000; + input.mass1 = 40.0e3; + input.crush1 = 0.5; + input.crush2 = 0.5; + auto const held{cl::override_of(input)}; + CHECK_FALSE(held.first); + CHECK_FALSE(held.second); + input.crush1 = 0.85; + auto const spent{cl::override_of(input)}; + CHECK(spent.first); + CHECK(spent.second); + } +} + +// ---- pushed off the track + +TEST_CASE("collisions: an empty two-axle wagon between loaded ones in a curve of 150 m is pushed off past the safe push of EN 15566") { + // the vehicles of data/fiz: the 3WL empty (10.5 t, two axles 6 m apart), between 430W coal wagons + vehicle empty{definition::fiz("3wl_v2/3wl")}; + vehicle loaded{definition::fiz("430w_v2/430w")}; + cl::pushed_vehicle wagon; + wagon.mass = empty->TotalMass() - empty->Mred(); + wagon.axles = empty->NAxles(); + wagon.length = empty->Dim.L; + wagon.pivots = empty->BDist(); + wagon.axle_base = empty->ADist() > 0.0 ? empty->ADist() : empty->BDist(); + REQUIRE(wagon.axles == 2); + cl::pushed_end end; + end.other_length = loaded->Dim.L; + auto const ratio = [&](double const Force, double const Radius) { + end.force = Force; + return cl::pushed_ratio(wagon, end, Radius); + }; + // 250 kN on the pair of buffers in a curve of 150 m is safe (EN 15566, 4.2); 600 kN pushes it off + CHECK(ratio(250.0e3, 150.0) < 1.2); + CHECK(ratio(250.0e3, 150.0) > 0.5); + CHECK(ratio(600.0e3, 150.0) > 1.2); + // the wider the curve the more it takes; on a straight track the empty wagon lifts off past 1.5 MN: the force + // pitching it takes the load off its leading wheels + CHECK(ratio(600.0e3, 500.0) < ratio(600.0e3, 150.0)); + CHECK(ratio(600.0e3, 0.0) < 1.2); + CHECK(ratio(1.5e6, 0.0) < 1.2); + CHECK(ratio(2.5e6, 0.0) > 1.2); + // a crushed end no longer holds the ends in line + end.crush = 0.5; + CHECK(ratio(1.5e6, 0.0) > 1.2); + end.crush = 0.0; + + // the loaded wagon, four axles, takes it + cl::pushed_vehicle heavy; + heavy.mass = loaded->TotalMass() - loaded->Mred() + 59.5e3; + heavy.axles = loaded->NAxles(); + heavy.length = loaded->Dim.L; + heavy.pivots = loaded->BDist(); + heavy.axle_base = loaded->ADist(); + end.force = 600.0e3; + CHECK(cl::pushed_ratio(heavy, end, 150.0) < 0.5); + + // past 3 MN on a straight track the push takes the whole load off its leading wheels: they lift off the rail + CHECK_FALSE(cl::pushed_forces(wagon, end, 0.0).lifted()); + end.force = 3.5e6; + CHECK(cl::pushed_forces(wagon, end, 0.0).lifted()); + CHECK(cl::pushed_ratio(wagon, end, 0.0) > 1e8); +} + +TEST_CASE("collisions: the flange climbs while the wheels roll on, a lifted wheel goes in a short time") { + SUBCASE("Y / Q over the limit over 2 m rolled, however long the steps") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK_FALSE(monitor.update(true, 0.7, false, 0.03)); + CHECK(monitor.distance() == doctest::Approx(1.4)); + CHECK(monitor.update(true, 0.7, false, 0.03)); + } + SUBCASE("a break starts it over") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK_FALSE(monitor.update(false, 0.1, false, 0.03)); + CHECK_FALSE(monitor.update(true, 1.5, false, 0.03)); + CHECK(monitor.update(true, 0.5, false, 0.03)); + } + SUBCASE("standing, it never climbs, however long the push holds") { + cl::pushed_monitor monitor; + auto climbed{false}; + for (int step = 0; step < 100000; ++step) { + climbed = climbed || monitor.update(true, 0.0, false, 0.01); + } + CHECK_FALSE(climbed); + CHECK(monitor.distance() == 0.0); + } + SUBCASE("the wheels lifted off the rail for 0.05 s, standing or not") { + cl::pushed_monitor monitor; + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK_FALSE(monitor.update(false, 0.0, false, 0.01)); + CHECK_FALSE(monitor.update(true, 0.0, true, 0.03)); + CHECK(monitor.update(true, 0.0, true, 0.03)); + } + SUBCASE("a reset clears both") { + cl::pushed_monitor monitor; + monitor.update(true, 1.9, true, 0.04); + monitor.reset(); + CHECK(monitor.distance() == 0.0); + CHECK(monitor.time() == 0.0); + CHECK_FALSE(monitor.update(true, 0.05, true, 0.005)); + } +} + +TEST_CASE("collisions: a locomotive at its starting effort against a braked train doesn't push the empty wagon off at a stand") { + // the reviewer's case: an ST44 pressing a rake with an empty two-axle wagon right in front of it, in a yard curve. + // the push is over the climbing limit of the empty wagon, but nothing rolls: a wheel which doesn't roll doesn't + // climb. the time criterion pushed it off in five steps of 0.01 s. the ST44 gives some 390 kN, at the climbing + // limit of the empty wagon in a curve of 150 m: the yard curve is one of 120 m, to be past it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track line; + line.radius = 120.0; + consist train; + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + empty.hold_brake_pipe(5.0); + train.run(90.0, line); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + auto &locomotive{train.add(definition::fiz("st44_v2/m62-1151"), 1, Coupling::none, 0.0, 0.0)}; + test::driven const driver{locomotive.physics(), locomotive.physics(), locomotive.physics(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.physics()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto const start{empty->DistCounter()}; + auto pushed{0.0}; + auto worst{0.0}; + auto const watch = [&]() { + pushed = std::max(pushed, -locomotive->Couplers[VehicleEnd::front].CForce); + worst = std::max(worst, pushed_ratio_of(empty.physics(), VehicleEnd::rear, locomotive->Dim.L, line.radius)); + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->lineContactors.IsClosed(); ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + watch(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + watch(); + } + auto const rolled{(empty->DistCounter() - start) * 1000.0}; + MESSAGE(std::format("ST44 pushing at up to {:.0f} kN, the empty 3WL at Y/Q {:.2f}, rolled {:.3f} m", pushed / 1000.0, worst, rolled)); + REQUIRE(worst >= derailment::climbing_limit); + CHECK(rolled < 0.5); + CHECK_FALSE(derailed(empty.physics())); + CHECK(empty->CollisionDerail() == NONE); +} + +TEST_CASE("collisions: a locomotive running onto an empty wagon at 9 km/h doesn't push it off with the peak of the springs") { + // the reviewer's case: an 80 t locomotive onto a free empty 3WL in a curve of 150 m. the springs of the buffers + // press past the climbing limit for some 0.06 s, the wagon rolls a few centimetres meanwhile + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + auto &empty{train.add(definition::fiz("3wl_v2/3wl"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 9.0, 0.5)}; + auto pushed{0.0}; + auto worst{0.0}; + auto over{0}; // steps past the climbing limit + for (int step = 0; step < 500; ++step) { + train.step(curve); + pushed = std::max(pushed, empty->Couplers[VehicleEnd::rear].CForce); + auto const ratio{pushed_ratio_of(empty.physics(), VehicleEnd::rear, locomotive->Dim.L, curve.radius)}; + worst = std::max(worst, ratio); + over += ratio >= derailment::climbing_limit; + } + MESSAGE(std::format("EU07 at 9 km/h onto the empty 3WL: up to {:.0f} kN, Y/Q {:.2f}, {} steps of 0.01 s past the limit, the wagon at {:.1f} km/h", pushed / 1000.0, worst, over, + empty.speed())); + REQUIRE(worst >= derailment::climbing_limit); + REQUIRE(over >= 5); + CHECK_FALSE(derailed(empty.physics())); + CHECK_FALSE(derailed(locomotive.physics())); +} + +TEST_CASE("collisions: a train propelling an empty wagon into a braked one in a curve pushes it off as it rolls on") { + // the genuine push off: the empty 3WL leading a heavy train at 15 km/h, the train pressing it on into a braked + // rake through the curve while it all slides along + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track curve; + curve.radius = 150.0; + consist train; + constexpr int standing{4}; + for (int i = 0; i < standing; ++i) { + add_loaded(train, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, curve); + for (int i = 0; i < standing; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, curve); + auto &empty{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 15.0, 1.0)}; + train.add(definition::fiz("4e_v1/4e"), 0, consist::full_coupling, 15.0, 0.0); + for (int i = 0; i < 6; ++i) { + add_loaded(train, consist::full_coupling, 15.0, 0.0); + } + auto const start{empty->DistCounter()}; + train.run(10.0, curve); + MESSAGE(std::format("the empty 3WL: derailed {}, {}, rolled {:.2f} m", derailed(empty.physics()), empty->CollisionDerail() == COLLISION_PUSHED_OFF ? "pushed off" : "not pushed off", + (empty->DistCounter() - start) * 1000.0)); + CHECK(empty->CollisionDerail() == COLLISION_PUSHED_OFF); +} + +// ---- recovery + +TEST_CASE("collisions: a repaired vehicle has its ends rebuilt and is back on the rails") { + // resetconsist: the crush of the ends shifted the stop of the buffers, the next hit of the repaired consist would + // have started from it; and a vehicle derailed in a collision kept its reason and the state of the push + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{add_loaded(train, Coupling::none, 0.0, 0.0)}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 30.0, 0.5)}; + train.run(3.0); + REQUIRE(wagon->Couplers[VehicleEnd::rear].crush + locomotive->Couplers[VehicleEnd::front].crush > cl::override_crush); + REQUIRE((derailed(wagon.physics()) || derailed(locomotive.physics()))); + for (auto *vehicle : {&wagon, &locomotive}) { + auto &physics{vehicle->physics()}; + physics.repair_damage(); + CHECK(physics.DamageFlag.Empty()); + CHECK(physics.Derailed() == derailment::outcome::none); + CHECK(physics.CollisionDerail() == NONE); + CHECK(physics.pushed_off_monitor.distance() == 0.0); + CHECK(physics.pushed_off_monitor.time() == 0.0); + for (auto const &coupler : physics.Couplers) { + CHECK(coupler.crush == 0.0); + CHECK(coupler.contact.absorbed() == 0.0); + CHECK(coupler.contact.crush_work() == 0.0); + CHECK_FALSE(coupler.hit_handled); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.crush_monitored); + CHECK_FALSE(coupler.inside_reported); + } + } +} + +TEST_CASE("collisions: the repair of a coupler torn off by the crush rebuilds its end") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto &coupler{wagon->Couplers[VehicleEnd::rear]}; + coupler.crush = 0.3; + coupler.broken = true; + coupler.hit_force = 2.0e6; + wagon->DamageFlag.Set(VehicleDamage::coupling); + REQUIRE(wagon->repair_coupler(VehicleEnd::rear)); + CHECK(coupler.crush == 0.0); + CHECK(coupler.hit_force == 0.0); + CHECK_FALSE(coupler.broken); + CHECK_FALSE(wagon->DamageFlag.HasAll(VehicleDamage::coupling)); +} + +TEST_CASE("collisions: SetDamage taking the derailment off clears the collision's") { + vehicle wagon{definition::fiz("3wl_v2/3wl")}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "test"); + REQUIRE(wagon->CollisionDerail() == COLLISION_PUSHED_OFF); + REQUIRE(wagon->Derailed() == derailment::outcome::off_rails); + wagon->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::derailed}.Bits(), -1); + CHECK(wagon->CollisionDerail() == NONE); + CHECK(wagon->Derailed() == derailment::outcome::none); + CHECK_FALSE(wagon->DamageFlag.HasAll(VehicleDamage::derailed)); +} + +// ---- the model of eu07.ini + +TEST_CASE("collisions: the legacy rule with physics.collisions old, the crush with new") { + flag_setting const crashdamage{Global.crash_damage, true}; + struct collision { + char const *name; + char const *front; + char const *back; + double speed; // of the back one, running into the front one standing + bool frontout_old; + bool backout_old; + bool frontout_new; + bool backout_new; + int monitored; // the hits the monitor tells of + }; + // the legacy rule: over 15 km/h weighed by the ratio of the masses. the crush: the light wagon is crushed deep and + // climbs onto the locomotive at 60 km/h; two locomotives at 25 km/h crush their ends 0.1-0.3 m and stay on the rails + // the monitor tells of each hit once: the wagon derailed by the legacy rule is a wall the locomotive presses on into + // until it springs back, the same hit (the wall slowing down took the pair from parting at the start of a step to + // closing in at 0.3 km/h, which was told of as a second hit); the locomotives derailed both stay where they are + for (auto const &[name, front, back, speed, frontout_old, backout_old, frontout_new, backout_new, monitored] : { + collision{"locomotive into a wagon at 60", "3wl_v2/3wl", "4e_v1/4e", 60.0, true, false, true, false, 1}, + collision{"locomotive into a locomotive at 25", "4e_v1/4e", "4e_v1/4e", 25.0, true, true, false, false, 1}, + collision{"locomotive into a locomotive at 50", "4e_v1/4e", "4e_v1/4e", 50.0, true, true, true, true, 1}, + }) { + CAPTURE(name); + // monitor: the legacy rule, and the log tells of the crush once + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { + auto const physical{model == global_settings::collision_model::physical}; + CAPTURE(name_of(model)); + model_setting const setting{model}; + consist train; + train.add(definition::fiz(front)); + train.add(definition::fiz(back), 0, Coupling::none, speed, 20.0); + train.run(10.0); + CHECK(derailed(train[0].physics()) == (physical ? frontout_new : frontout_old)); + CHECK(derailed(train[1].physics()) == (physical ? backout_new : backout_old)); + auto const crush{train[0]->Couplers[VehicleEnd::rear].crush + train[1]->Couplers[VehicleEnd::front].crush}; + if (physical) { + MESSAGE(name, ": crush ", crush, " m"); + CHECK(crush > 0.05); + } + else { + CHECK(crush == 0.0); + } + CHECK(train[0]->crush_reports() + train[1]->crush_reports() == (model == global_settings::collision_model::monitor ? monitored : 0)); + } + } +} + +TEST_CASE("collisions: the names of the models in eu07.ini") { + using model = global_settings::collision_model; + CHECK(collision_model_of("new") == model::physical); + CHECK(collision_model_of("old") == model::old); + CHECK(collision_model_of("monitor") == model::monitor); + // a name it doesn't know is the default + CHECK(collision_model_of("physical") == model::physical); + CHECK(global_settings{}.collisions == model::physical); + for (auto const value : {model::old, model::physical, model::monitor}) { + CHECK(collision_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} + +TEST_CASE("collisions: the model of the collisions goes apart from the one of the derailment") { + // the crush with the legacy draw of the derailment in a curve, the legacy collisions with the criteria + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const derailment : {global_settings::derailment_model::old, global_settings::derailment_model::physical}) { + for (auto const collisions : {global_settings::collision_model::old, global_settings::collision_model::physical}) { + auto const previous{Global.derailment}; + Global.derailment = derailment; + model_setting const setting{collisions}; + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 25.0, 20.0); + train.run(10.0); + Global.derailment = previous; + auto const crush{train[0]->Couplers[VehicleEnd::rear].crush + train[1]->Couplers[VehicleEnd::front].crush}; + CHECK((crush > 0.05) == (collisions == global_settings::collision_model::physical)); + } + } +} + +TEST_CASE("collisions: the crush of a locomotive hitting a wagon doesn't depend on the step, nor on the model of the coupling") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + auto const fine{locomotive_into_wagon(30.0, 0.001)}; + auto const game{locomotive_into_wagon(30.0, 0.01)}; + auto const coarse{locomotive_into_wagon(30.0, 0.05)}; + MESSAGE(std::format("30 km/h, couplerphysics {}: crush {:.3f} / {:.3f} / {:.3f} m with dt 0.001 / 0.01 / 0.05 s", physics, fine, game, coarse)); + REQUIRE(fine > 0.05); + // the step of the game, and a step five times as long, which the buffers past the crush aren't made for + CHECK(game == doctest::Approx(fine).epsilon(0.1)); + CHECK(coarse == doctest::Approx(fine).epsilon(0.5)); + } + // the models of the coupling differ in their buffers, not past them + { + auto const legacy{locomotive_into_wagon(30.0, 0.01)}; + flag_setting const couplerphysics{Global.coupler_physics, true}; + flag_setting const everywhere{Global.coupler_physics_all, true}; + CHECK(locomotive_into_wagon(30.0, 0.01) == doctest::Approx(legacy).epsilon(0.3)); + } + // slow enough, the buffers take it all + CHECK(locomotive_into_wagon(5.0, 0.01) == 0.0); +} + +TEST_CASE("collisions: automatic couplers hit too fast don't catch, the ends crush; torn off, they don't couple again") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Coupling::coupler | Coupling::brakeHose)}; + for (auto const speed : {20.0, 30.0, 45.0}) { + CAPTURE(speed); + vehicle moving{automatic, speed, "moving"}; + vehicle standing{automatic, 0.0, "standing"}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; + auto coupled{false}; + auto fast{false}; // coupled while closing in faster than the couplers catch + for (int i = 0; i < 1000; ++i) { + auto const closing{moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear)}; + pair.step(); + fast = fast || (pair.coupled() && false == coupled && closing > physics::Vehicle::SafeCollisionVelocity); + coupled = coupled || pair.coupled(); + } + auto const crush{moving->Couplers[VehicleEnd::front].crush + standing->Couplers[VehicleEnd::rear].crush}; + MESSAGE(speed, " km/h: crush ", crush, " m, derailed ", derailed(moving.physics()), " ", derailed(standing.physics()), ", coupled later ", coupled); + CHECK_FALSE(fast); + CHECK(crush > 0.0); + // crushed past the draw gear, the coupler is gone; short of it, the wagons may roll together again slowly + // after the hit, and couple then + if (std::max(moving->Couplers[VehicleEnd::front].crush, standing->Couplers[VehicleEnd::rear].crush) >= cl::draw_gear_crush) { + CHECK_FALSE(coupled); + CHECK((moving->Couplers[VehicleEnd::front].broken || standing->Couplers[VehicleEnd::rear].broken)); + } + // the two alike: neither climbs onto the other until the crush is deep enough for both to + CHECK(derailed(moving.physics()) == derailed(standing.physics())); + CHECK(derailed(moving.physics()) == (crush > cl::override_both)); + } +} + +TEST_CASE("collisions: road vehicles keep the legacy rule") { + // the traffic of a scenery: cars and buses have no underframe to crush; over 15 km/h weighed by the masses they + // derail, as with physics.collisions old (found running line 107: two cars of its traffic, 119 km/h head-on) + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const model : {global_settings::collision_model::old, global_settings::collision_model::physical, global_settings::collision_model::monitor}) { + model_setting const setting{model}; + consist road; + road.add(definition::fiz("road/man/nl293")); + road.add(definition::fiz("road/man/nl293"), 0, Coupling::none, 40.0, 5.0); + road.run(5.0); + CHECK(derailed(road[0].physics())); + CHECK(derailed(road[1].physics())); + CHECK(road[0]->Couplers[VehicleEnd::rear].crush == 0.0); + CHECK(road[1]->CollisionDerail() == NONE); + CHECK(road[0]->crush_reports() + road[1]->crush_reports() == 0); + } +} + +TEST_CASE("collisions: a vehicle off the rails by the new model stays in the chain of forces") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + consist train; + auto &wagon{train.add(definition::fiz("430w_v2/430w"))}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 10.0, 0.5)}; + wagon->derail_in_collision(COLLISION_PUSHED_OFF, "for the test"); + REQUIRE(derailed(wagon.physics())); + auto const before{wagon->TotalMass() * wagon->V() + locomotive->TotalMass() * locomotive->V()}; + // the hit is over within a second, the friction of the derailed wagon slows the pair down over it + train.run(1.0); + auto const after{wagon->TotalMass() * wagon->V() + locomotive->TotalMass() * locomotive->V()}; + // pushed along, not a wall the locomotive bounces off + CHECK(wagon.speed() > 1.0); + CHECK(locomotive.speed() > 0.0); + CHECK(after < before); + CHECK(after > 0.5 * before); + // and it slides on with the friction of the ballast, stopping before long + train.run(10.0); + CHECK(std::abs(wagon.speed()) < 0.1); +} + +TEST_CASE("collisions: a freight train running into a standing one, the cases of the PoC of G14") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct crash { + double speed; + double radius; + }; + for (auto const &[speed, radius] : {crash{10.0, 0.0}, crash{15.0, 0.0}, crash{15.0, 190.0}, crash{25.0, 0.0}, crash{25.0, 190.0}, crash{40.0, 0.0}, crash{40.0, 190.0}}) { + CAPTURE(speed); + CAPTURE(radius); + auto const result{freight_crash(speed, radius)}; + MESSAGE(std::format("{:.0f} km/h, R {:.0f}: {} derailed ({} overrode, {} pushed off), {} ends crushed (deepest {:.2f} m), {} couplings broken: {}", speed, radius, result.derailed, + result.overridden, result.pushed, result.crushed, result.crush, result.broken, result.list)); + if (speed <= 10.0) { + // the buffers take it + CHECK(result.derailed == 0); + CHECK(result.crushed == 0); + } + } +} + +TEST_CASE("collisions: identical units built to EN 15227 at 36 km/h") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + // two coaches of data/wagon.json (42.2 t) a unit, their ends crash zones with anticlimbers, unbraked + auto const unit = [](bool const Anticlimbers, double const Height) { + return definition::load("wagon").set("BuffCoupl", "CrashZone", "Yes").set("BuffCoupl", "AntiClimber", Anticlimbers ? "Yes" : "No").set("BuffCoupl", "BufferHeight", Height); + }; + auto const crash = [&](bool const Anticlimbers, double const Speed, double const Offset) { + consist train; + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040)); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, Coupling::none, Speed, 1.0); + train.add(unit(Anticlimbers, 1.040 + Offset), 0, consist::full_coupling, Speed); + train.run(6.0); + struct { + double crush; + double inner; + int derailed; + bool higher; + } result{train[1]->Couplers[VehicleEnd::rear].crush + train[2]->Couplers[VehicleEnd::front].crush, std::max(crush_of(train[0].physics()), crush_of(train[3].physics())), 0, + derailed(train[2].physics())}; + for (std::size_t i = 0; i < train.size(); ++i) { + result.derailed += derailed(train[i].physics()); + } + return result; + }; + SUBCASE("scenario 1: the crush stays in the zones, nothing climbs") { + auto const result{crash(true, 36.0, 0.04)}; + MESSAGE("36 km/h, 40 mm offset: crush ", result.crush, " m, the far ends ", result.inner, " m"); + CHECK(result.crush > 0.2); + CHECK(result.crush < 2.0 * 0.8); + CHECK(result.derailed == 0); + } + SUBCASE("the same units without the anticlimbers override") { + auto const result{crash(false, 36.0, 0.0)}; + CHECK(result.derailed >= 2); + } + SUBCASE("slower, without the anticlimbers, the higher one climbs") { + auto const result{crash(false, 32.0, 0.04)}; + MESSAGE("32 km/h, 40 mm offset: crush ", result.crush, " m"); + CHECK(result.crush > cl::override_crush); + CHECK(result.crush < cl::override_both); + CHECK(result.higher); + CHECK(result.derailed == 1); + auto const held{crash(true, 32.0, 0.04)}; + CHECK(held.derailed == 0); + } +} + +// ---- the energy of the hit: what the buffers of EN 15551 take in never crushes (found running every scenario of the +// install: calkowo_v2_kontenera, baltyk_sdm) + +TEST_CASE("collisions: the buffers of EN 15551 of an end take in their energy, of the category given or by the kind") { + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::wagon) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::locomotive) == doctest::Approx(60.0e3)); + CHECK(cl::buffer_capacity({}, cl::vehicle_kind::coach) == doctest::Approx(60.0e3)); + CHECK(cl::default_buffers(cl::vehicle_kind::coach) == cl::buffer_category::passenger); + cl::end_definition category_c; + category_c.buffers = cl::buffer_category::C; + CHECK(cl::buffer_capacity(category_c, cl::vehicle_kind::wagon) == doctest::Approx(140.0e3)); + // the key of the .fiz + vehicle wagon{definition::load("wagon").set("BuffCoupl", "BufferCategory", "B")}; + REQUIRE(wagon->Couplers[VehicleEnd::front].collision.buffers.has_value()); + CHECK(*wagon->Couplers[VehicleEnd::front].collision.buffers == cl::buffer_category::B); + CHECK(cl::buffer_capacity(wagon->Couplers[VehicleEnd::rear].collision, wagon->collision_kind()) == doctest::Approx(100.0e3)); +} + +TEST_CASE("collisions: the budget of a contact, by what the hit brings to the buffers") { + cl::contact_energy contact; + // not touching: nothing + contact.update(false, false, 1.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + // pressed in, closing: the springs take in their work + contact.update(true, false, 1.0, 1.0e6, 0.05, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // pressed all the way, they take in nothing more + contact.update(true, true, 1.0, 1.4e6, 0.3, 0.01); + CHECK(contact.absorbed() == doctest::Approx(10.0e3)); + // the kinetic energy and what the buffers took, past their capacity + CHECK(contact.budget(40.0e3, 2.0, 60.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0 + 10.0e3 - 60.0e3)); + // the springs of the .fiz taking in more than the buffers of EN 15551: no more than the kinetic energy + CHECK(contact.budget(40.0e3, 2.0, 5.0e3) == doctest::Approx(0.5 * 40.0e3 * 4.0)); + // springing back they hold no more than their springs pressed in + contact.update(true, false, -0.5, 0.2e6, 0.02, 0.01); + CHECK(contact.absorbed() == doctest::Approx(0.5 * 0.2e6 * 0.02)); + // a train pushing at a stand: the oscillation of the pair never builds the energy up + for (int i = 0; i < 6000; ++i) { + auto const closing{0.05 * std::sin(i * 0.3)}; + contact.update(true, false, closing, 0.3e6 + 1.0e6 * closing, 0.03, 0.01); + } + CHECK(contact.absorbed() < 0.5 * 0.35e6 * 0.03 + 0.35e6 * 0.05 * 0.01 * 12.0); + // parted: a new contact + contact.crushed(5.0e3); + CHECK(contact.crush_work() == doctest::Approx(5.0e3)); + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.crush_work() == 0.0); +} + +TEST_CASE("collisions: the crush of a hit takes no more than its energy past the buffers, with any step") { + // two masses at the stop of their buffers from the start (nothing taken in by the springs), the budget of the + // crush taken anew in every step of the hit, as the vehicles take it + struct masses { + double mass1; + double mass2; + }; + constexpr double capacity{120.0e3}; + constexpr double springs{1.2e6}; + for (auto const &[mass1, mass2] : {masses{80.0e3, 80.0e3}, masses{117.0e3, 84.0e3}, masses{300.0e3, 20.0e3}, masses{36.0e3, 41.6e3}}) { + auto const reduced{mass1 * mass2 / (mass1 + mass2)}; + for (auto const speed : {2.0, 5.0, 8.0, 12.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.003, 0.01, 0.02, 0.03}) { + CAPTURE(mass1); + CAPTURE(mass2); + CAPTURE(speed); + CAPTURE(dt); + cl::end_state first{locomotive_curve, 0.0}; + cl::end_state second{wagon_curve, 0.0}; + auto velocity1{speed * kmh}; + auto velocity2{0.0}; + auto work{0.0}; + for (int step = 0; step < 100000; ++step) { + auto const start{velocity1 - velocity2}; + velocity1 -= springs * dt / mass1; + velocity2 += springs * dt / mass2; + auto const closing{velocity1 - velocity2}; + if (closing <= 0.0) { + break; + } + cl::hit_input input; + input.velocity = closing; + input.start_velocity = start; + input.mass1 = mass1; + input.mass2 = mass2; + input.stiffness = 1.4e8; + input.springs = springs; + input.dt = dt; + input.budget = 0.5 * reduced * start * start - capacity; + auto const hit{cl::hit(first, second, input)}; + if (false == hit.crushing) { + break; + } + CHECK(hit.work <= input.budget * (1.0 + 1e-9) + 1e-6); + work += hit.work; + first.crush += hit.crush1; + second.crush += hit.crush2; + velocity1 -= hit.impulse / mass1; + velocity2 += hit.impulse / mass2; + if (hit.velocity <= 0.0) { + break; + } + } + auto const available{std::max(0.0, 0.5 * reduced * (speed * kmh) * (speed * kmh) - capacity)}; + auto const crushed{locomotive_curve.energy(0.0, first.crush) + wagon_curve.energy(0.0, second.crush)}; + CHECK(work <= available + 1.0); + CHECK(crushed <= available * 1.001 + 1.0); + if (available <= 0.0) { + CHECK(first.crush + second.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: the crush of two vehicles takes no more than the energy of the hit past the buffers, with any step") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + struct pair_of { + char const *name; + definition front; + definition back; + }; + for (auto const &[name, front, back] : {pair_of{"EU07 into EU07", definition::fiz("4e_v1/4e"), definition::fiz("4e_v1/4e")}, + pair_of{"SU45 into SM42", definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, + pair_of{"EU07 into a wagon", definition::fiz("430w_v2/430w"), definition::fiz("4e_v1/4e")}}) { + for (auto const speed : {2.0, 5.0, 10.0, 15.0, 20.0, 30.0, 45.0, 60.0}) { + for (auto const dt : {0.001, 0.01, 0.03}) { + CAPTURE(name); + CAPTURE(speed); + CAPTURE(dt); + auto const result{contact(front, back, speed, 0.5, 4.0, dt)}; + // the explicit steps of the springs before the stop rate what they took in a little off. at 0.03 s, 0.5 m a + // step at 60 km/h, the legacy movement of the vehicles past the stop gives the hit energy of its own (the + // crush goes past what it is at 0.01 s and 0.001 s): the budget doesn't bind there, every step of the hit + // is within it (the test of the hit of two masses above), the same crush as before the budget + CHECK(result.energy <= result.available * (dt > 0.02 ? 1.15 : 1.05) + 5.0e3); + if (result.available <= 0.0) { + CHECK(result.crush == 0.0); + } + } + } + } +} + +TEST_CASE("collisions: two locomotives (117 t and 84 t) touching at walking speed don't crush (calkowo_v2_kontenera)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const su45{definition::fiz("su45_v2/301d")}; + auto const sm42{definition::fiz("sm42_v1/6d1")}; + { + vehicle check{su45}; + CHECK(check->TotalMass() == doctest::Approx(117.0e3).epsilon(0.02)); + } + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const speed : {5.0, 5.8, 6.0}) { + CAPTURE(speed); + // a hit from a metre away + { + auto const result{contact(sm42, su45, speed, 1.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // put down by the scenery with the buffers pressed in, up to past their stop, closing in: the log of the run + // had 5.8 km/h at the stop, both ends crushed, deeper hit after hit until both overrode + for (auto const overlap : {0.1, 0.4, 1.0}) { + CAPTURE(overlap); + auto const result{contact(sm42, su45, speed, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: locomotives put down inside each other don't crush, whatever their springs make of them") { + // calkowo_v2_kontenera puts an SM42 on an SU45 with their middles 2.7 m apart: the springs at the stops of both + // ends and the neighbours found at either end shook them up to 9-13 km/h, past the energy of the buffers + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const speed : {0.0, 10.0, 15.0}) { + CAPTURE(speed); + auto const result{contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), speed, -3.0, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + // a hit from a distance at the same speeds crushes past the energy of the buffers + CHECK(contact(definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d"), 20.0, 0.5).crush > 0.0); +} + +TEST_CASE("collisions: two coaches (36 t and 41.6 t) at 8 km/h don't crush, nor run into a wall (baltyk_sdm)") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + auto const light{coach(34.3e3)}; + auto const heavy{coach(39.9e3)}; + { + vehicle check{light}; + CHECK(check->TotalMass() == doctest::Approx(36.0e3).epsilon(0.01)); + CHECK(vehicle{heavy}->TotalMass() == doctest::Approx(41.6e3).epsilon(0.01)); + } + for (auto const speed : {5.0, 8.0}) { + CAPTURE(speed); + // a hit from a metre away, and one with the buffers pressed all the way already, as the coach knocked onto the + // other one by the hit of the train on the vehicle derailed at the end of the track + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + auto const result{contact(light, heavy, speed, gap)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + // the vehicle derailed the legacy way is a wall that the coach runs into + for (auto const gap : {1.0, -0.25}) { + CAPTURE(gap); + consist train; + auto &wall{train.add(light)}; + wall->Derail(END_OF_TRACK); + REQUIRE(derailed(wall.physics())); + auto &running{train.add(heavy, 0, Coupling::none, 5.0, gap)}; + train.run(5.0); + CHECK(wall->Couplers[VehicleEnd::rear].crush + running->Couplers[VehicleEnd::front].crush == 0.0); + CHECK(running->CollisionDerail() == NONE); + } +} + +TEST_CASE("collisions: a locomotive pushing a standing braked train at full power doesn't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + test::track const line{0.15, 0.0, test::catenary_3kv}; + // the diesel-electric keeps its full power at a stand (an electric one trips its overload relays there) + for (auto const *path : {"su45_v2/301d"}) { + CAPTURE(path); + consist train; + // four loaded coal wagons, braked in emergency once their brakes are charged + constexpr int wagons{4}; + for (int i = 0; i < wagons; ++i) { + add_mixed(train, 0, consist::full_coupling, 0.0, 0.0).hold_brake_pipe(5.0); + } + train.run(90.0, line); + for (int i = 0; i < wagons; ++i) { + train[i].hold_brake_pipe(0.0); + } + train.run(30.0, line); + // the locomotive behind them, touching, driven forwards into them at full power + auto &locomotive{train.add(definition::fiz(path), 1, Coupling::none, 0.0, 0.0)}; + test::driven const driver{locomotive.physics(), locomotive.physics(), locomotive.physics(), [&train](double const Seconds, test::track const &Track) { train.run(Seconds, Track); }}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(locomotive.physics()); + for (int i = 0; i < 3 && locomotive->DirActive <= 0; ++i) { + locomotive->DirectionForward(); + } + test::drive(driver, line, 10.0); + auto pushed{0.0}; + auto seconds{0}; // pushing with 100 kN or more + auto const push = [&]() { + auto const force{std::max(0.0, -locomotive->Couplers[VehicleEnd::front].CForce)}; + pushed = std::max(pushed, force); + seconds += force >= 100.0e3; + }; + // the line contactors close at the first position, once their delay and the pressure switch let them + locomotive->IncMainCtrl(1); + for (int i = 0; i < 90 && false == locomotive->lineContactors.IsClosed(); ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && false == locomotive->IsMainCtrlMaxPowerPos(); ++i) { + locomotive->IncMainCtrl(1); + test::drive(driver, line, 1.0); + push(); + } + for (int i = 0; i < 60; ++i) { + test::drive(driver, line, 1.0); + push(); + } + MESSAGE(std::format("{}: pushing at up to {:.0f} kN, {} s at 100 kN or more, at {:.1f} km/h at the end", path, pushed / 1000.0, seconds, locomotive.speed())); + CHECK(pushed > 200.0e3); + CHECK(seconds >= 55); + for (std::size_t i = 0; i < train.size(); ++i) { + CAPTURE(i); + CHECK(crush_of(train[i].physics()) == 0.0); + CHECK_FALSE(derailed(train[i].physics())); + } + } +} + +TEST_CASE("collisions: vehicles put down with their buffers pressed in don't crush") { + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + for (auto const overlap : {0.1, 0.3, 0.6}) { + CAPTURE(overlap); + for (auto const &[front, back] : {std::pair{definition::fiz("sm42_v1/6d1"), definition::fiz("su45_v2/301d")}, std::pair{coach(34.3e3), coach(39.9e3)}, + std::pair{definition::fiz("3wl_v2/3wl"), definition::fiz("4e_v1/4e")}}) { + auto const result{contact(front, back, 0.0, -overlap, 10.0)}; + CHECK(result.crush == 0.0); + CHECK_FALSE(result.derailed); + } + } + } +} + +TEST_CASE("collisions: the monitor goes by the energy of the hit as well") { + flag_setting const crashdamage{Global.crash_damage, true}; + model_setting const monitor{global_settings::collision_model::monitor}; + // a hit the buffers take in: the monitor tells of nothing + for (auto const gap : {1.0, -0.4}) { + CAPTURE(gap); + consist train; + train.add(definition::fiz("sm42_v1/6d1")); + train.add(definition::fiz("su45_v2/301d"), 0, Coupling::none, 5.8, gap); + train.run(5.0); + CHECK(train[0]->crush_reports() + train[1]->crush_reports() == 0); + } + // one past them it does + consist train; + train.add(definition::fiz("4e_v1/4e")); + train.add(definition::fiz("4e_v1/4e"), 0, Coupling::none, 25.0, 20.0); + train.run(10.0); + CHECK(train[0]->crush_reports() + train[1]->crush_reports() == 1); +} + +// ---- the legacy derailment (physics.derailment old or monitor) in a train, with physics.collisions new + +namespace { + +// what the vehicles of the train did to each other +struct train_damage { + double crush{0.0}; // the deepest crush of an end [m] + double energy{0.0}; // the crush of all the ends took [J] + int derailed{0}; // in a collision + int broken{0}; // couplings torn off + std::string list; // which vehicle, for the messages +}; + +train_damage damage_of(consist &Train) { + train_damage result; + for (std::size_t i = 0; i < Train.size(); ++i) { + auto const &vehicle{Train[i].physics()}; + result.crush = std::max(result.crush, crush_of(vehicle)); + for (auto const end : VehicleEnds) { + result.energy += vehicle.crush_curve_at(end).energy(0.0, vehicle.Couplers[end].crush); + } + result.derailed += vehicle.CollisionDerail() != NONE; + if (i + 1 < Train.size()) { + result.broken += vehicle.Couplers[VehicleEnd::rear].broken; + } + if (crush_of(vehicle) > 0.0 || vehicle.CollisionDerail() != NONE) { + result.list += std::format("{} crushed {:.2f} m{}; ", i, crush_of(vehicle), vehicle.CollisionDerail() != NONE ? ", derailed" : ""); + } + } + return result; +} + +// the kinetic energy of the vehicles of the train [J] +double kinetic_of(consist &Train) { + auto energy{0.0}; + for (std::size_t i = 0; i < Train.size(); ++i) { + energy += 0.5 * Train[i]->TotalMass() * Train[i]->V() * Train[i]->V(); + } + return energy; +} + +} // namespace + +TEST_CASE("collisions: the cut of the speed of the legacy derailment is no hit inside the train (moczniki_eu06_eu07, tomaszewo_raj49843)") { + // the legacy derailment takes 35 % of the speed of the vehicle off in a step: the coaches coupled behind it, at the + // speed they had, ran into it at a third of the speed of the train, crushed their ends and rode up onto it + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // an SU46 with its coaches at 95 km/h, as in moczniki_eu06_eu07; an electric locomotive at 48 km/h, as in + // tomaszewo_raj49843 + for (auto const &[path, speed] : {std::pair{"su46_v2/303d", 95.0}, std::pair{"4e_v1/4e", 48.0}}) { + CAPTURE(path); + // too fast in a curve, the draw in the movement of the vehicle; off the end of the track, in its next step + for (auto const reason : {TOO_HIGH_SPEED, END_OF_TRACK}) { + CAPTURE(reason); + consist train; + auto &locomotive{train.add(definition::fiz(path), 0, Coupling::none, speed)}; + for (int i = 0; i < 3; ++i) { + train.add(coach(41.0e3), 0, consist::full_coupling, speed); + } + train.run(2.0); + if (reason == END_OF_TRACK) { + locomotive.damage_track(dtrack_norail); + } + else { + locomotive->Derail(reason); + } + train.step(); + REQUIRE(derailed(locomotive.physics())); + // the train loses the speed with it + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK(train[i].speed() == doctest::Approx(locomotive.speed()).epsilon(0.03)); + } + train.run(15.0); + auto const damage{damage_of(train)}; + INFO(damage.list); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + } + } + } +} + +TEST_CASE("collisions: the train behind a vehicle that ran off the end of the track doesn't crush into it (l053-sluzba-2-night, l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the vehicle derailed the legacy way at the end of the track stopped as a wall the train behind it ran into: the + // vehicles behind it pressed into each other past their stops, and crushed by more than the energy of the train + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const physics : {false, true}) { + CAPTURE(physics); + flag_setting const couplerphysics{Global.coupler_physics, physics}; + flag_setting const everywhere{Global.coupler_physics_all, physics}; + // pulled: an M62 leading wagons of 22 t at 30 km/h (l053_calkowo-sluzba-tlk-1, linia61_osobowy3); pushed: an SM42 + // at the back of wagons of 35 t at 33 km/h, the leading wagon goes off (l053-sluzba-2-night) + for (auto const pushed : {false, true}) { + CAPTURE(pushed); + auto const speed{pushed ? 33.0 : 30.0}; + consist train; + if (false == pushed) { + train.add(definition::fiz("st44_v2/m62-1151"), 0, Coupling::none, speed); + } + constexpr int wagons{6}; + for (int i = 0; i < wagons; ++i) { + auto &wagon{train.add(definition::fiz("430w_v2/430w"), 0, consist::full_coupling, speed)}; + if (pushed) { + wagon->AssignLoad("coal", 12.0f); + wagon->ComputeMass(); + } + } + if (pushed) { + train.add(definition::fiz("sm42_v1/6d1"), 0, consist::full_coupling, speed); + } + train.run(2.0); + auto const kinetic{kinetic_of(train)}; + train[0].damage_track(dtrack_norail); + train.run(20.0); + REQUIRE(derailed(train[0].physics())); + auto const damage{damage_of(train)}; + INFO(damage.list); + MESSAGE(std::format("{}: crush {:.3f} m, {:.0f} kJ of the {:.0f} kJ of the train", pushed ? "pushed" : "pulled", damage.crush, damage.energy / 1000.0, kinetic / 1000.0)); + CHECK(damage.crush < cl::crush_mark); + CHECK(damage.energy <= kinetic); + CHECK(damage.derailed == 0); + CHECK(damage.broken == 0); + for (std::size_t i = 1; i < train.size(); ++i) { + CAPTURE(i); + CHECK_FALSE(derailed(train[i].physics())); + } + } + } +} + +TEST_CASE("collisions: the buffers of vehicles found inside each other take in nothing for the budget of the crush") { + cl::contact_energy contact; + // pressed in at 2 m/s under 1 MN for 0.1 s: 200 kJ, past the 120 kJ the buffers of both ends take + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + REQUIRE(contact.absorbed() == doctest::Approx(200.0e3)); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) > 0.0); + // found inside each other: what their springs made of it is no hit (l053_calkowo-sluzba-tlk-1: 163 kJ "in the + // buffers" let a pair crush with 15 kJ of motion) + contact.inside(); + CHECK(contact.absorbed() == 0.0); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == 0.0); + CHECK(contact.budget(11.0e3, 1.7, 120.0e3) < 0.0); + // the buffers apart, the next contact is a hit again + contact.update(false, false, 0.0, 0.0, 0.0, 0.01); + contact.update(true, false, 2.0, 1.0e6, 0.1, 0.1); + CHECK(contact.absorbed() == doctest::Approx(200.0e3)); +} + +TEST_CASE("collisions: a pair parting at the start of the step isn't crushed (l053_calkowo-sluzba-tlk-1, linia61_osobowy3)") { + // the log had "closing at -7.1 km/h at the start of the step" on a crush of a pair knocked back onto each other in + // the step: the legacy collision takes such a knock, a pair still closing in at the start of a step is a hit + model_setting const physical{global_settings::collision_model::physical}; + flag_setting const crashdamage{Global.crash_damage, true}; + for (auto const parting : {true, false}) { + CAPTURE(parting); + consist train; + auto &front{train.add(definition::fiz("430w_v2/430w"))}; + // behind it with the buffers pressed to their stop, moving back away from it, or standing + auto &back{train.add(definition::fiz("430w_v2/430w"), 0, Coupling::none, parting ? -3.0 : 0.0, -0.3)}; + // one step, the way the consist steps it, with the vehicle behind knocked forwards onto the front one between + // the forces and the movement, as a hit of another vehicle in the step does + constexpr double dt{0.01}; + for (auto *vehicle : {&front, &back}) { + vehicle->begin_step(); + } + for (auto *vehicle : {&front, &back}) { + vehicle->forces(dt); + } + REQUIRE((front->Couplers[VehicleEnd::rear].closing < 0.0) == parting); + back->SetV(25.0 * kmh); + for (auto *vehicle : {&front, &back}) { + vehicle->move({}, dt, (*vehicle)->Loc(), 5.0); + } + auto const crush{front->Couplers[VehicleEnd::rear].crush + back->Couplers[VehicleEnd::front].crush}; + if (parting) { + CHECK(crush == 0.0); + // the legacy collision pushed them apart + CHECK(back->V() < 25.0 * kmh); + } + else { + // closing in from a stand, the knock is a hit past the energy of the buffers + CHECK(crush > 0.0); + } + } +} diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 6f5730cf7..cbef02369 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -8,7 +8,7 @@ #include #include -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // characterisation of the commands vehicles pass each other along the couplers (RunCommand): what each of them // does to every real vehicle, recorded in golden traces (data/golden/commands/), how they travel through a train of @@ -26,63 +26,63 @@ double flag(bool Value) { // what the commands change std::vector state() { std::vector result{ - {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos; }}, - {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos; }}, - {"LastRelayTime", [](auto const &M) { return M.LastRelayTime; }}, - {"eimic_real", [](auto const &M) { return M.eimic_real; }}, + {"MainCtrlPos", [](auto const &M) { return M.MainCtrlPos(); }}, + {"ScndCtrlPos", [](auto const &M) { return M.ScndCtrlPos(); }}, + {"LastRelayTime", [](auto const &M) { return M.lineContactors.TimeSinceSwitch(); }}, + {"eimic_real", [](auto const &M) { return M.EimicReal(); }}, {"TUHEX_StageActual", [](auto const &M) { return M.TUHEX_StageActual; }}, {"TUHEX_Active", [](auto const &M) { return flag(M.TUHEX_Active); }}, - {"DynamicBrakeEMUStatus", [](auto const &M) { return flag(M.DynamicBrakeEMUStatus); }}, - {"BrakeReleaser", [](auto const &M) { return flag(M.Hamulec->Releaser()); }}, + {"DynamicBrakeEMUStatus", [](auto const &M) { return flag(M.brakes.electrodynamic.emuWorking); }}, + {"BrakeReleaser", [](auto const &M) { return flag(M.brakes.distributor->Releaser()); }}, {"WaterPumpBreaker", [](auto const &M) { return flag(M.WaterPump.breaker); }}, {"WaterPumpEnabled", [](auto const &M) { return flag(M.WaterPump.is_enabled); }}, {"WaterPumpDisabled", [](auto const &M) { return flag(M.WaterPump.is_disabled); }}, {"WaterHeaterBreaker", [](auto const &M) { return flag(M.WaterHeater.breaker); }}, {"WaterHeaterEnabled", [](auto const &M) { return flag(M.WaterHeater.is_enabled); }}, - {"WaterCircuitsLink", [](auto const &M) { return flag(M.WaterCircuitsLink); }}, + {"WaterCircuitsLink", [](auto const &M) { return flag(M.WaterCircuitsLink()); }}, {"FuelPumpEnabled", [](auto const &M) { return flag(M.FuelPump.is_enabled); }}, {"FuelPumpDisabled", [](auto const &M) { return flag(M.FuelPump.is_disabled); }}, {"OilPumpEnabled", [](auto const &M) { return flag(M.OilPump.is_enabled); }}, {"OilPumpDisabled", [](auto const &M) { return flag(M.OilPump.is_disabled); }}, {"CompartmentLightsEnabled", [](auto const &M) { return flag(M.CompartmentLights.is_enabled); }}, {"CompartmentLightsDisabled", [](auto const &M) { return flag(M.CompartmentLights.is_disabled); }}, - {"MainSwitch", [](auto const &M) { return flag(M.Mains); }}, - {"Heating", [](auto const &M) { return flag(M.Heating); }}, + {"MainSwitch", [](auto const &M) { return flag(M.lineBreaker.IsClosed()); }}, + {"Heating", [](auto const &M) { return flag(M.trainHeating.IsOn()); }}, {"DirActive", [](auto const &M) { return M.DirActive; }}, {"DirAbsolute", [](auto const &M) { return M.DirAbsolute; }}, {"CabActive", [](auto const &M) { return M.CabActive; }}, - {"CabMaster", [](auto const &M) { return flag(M.CabMaster); }}, - {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag); }}, - {"ConverterAllow", [](auto const &M) { return flag(M.ConverterAllow); }}, - {"Battery", [](auto const &M) { return flag(M.Battery); }}, - {"CompressorAllow", [](auto const &M) { return flag(M.CompressorAllow); }}, - {"CompressorListPos", [](auto const &M) { return M.CompressorListPos; }}, + {"CabMaster", [](auto const &M) { return flag(M.CabMaster()); }}, + {"AutoRelayFlag", [](auto const &M) { return flag(M.AutoRelayFlag()); }}, + {"ConverterAllow", [](auto const &M) { return flag(M.converter.IsAllowed()); }}, + {"Battery", [](auto const &M) { return flag(M.lowVoltage.IsBatteryOn()); }}, + {"CompressorAllow", [](auto const &M) { return flag(M.air.compressor.IsAllowed()); }}, + {"CompressorListPos", [](auto const &M) { return M.air.compressor.ListPosition(); }}, {"DoorLock", [](auto const &M) { return flag(M.Doors.lock_enabled); }}, {"DoorStep", [](auto const &M) { return flag(M.Doors.step_enabled); }}, {"DoorRemoteOnly", [](auto const &M) { return flag(M.Doors.remote_only); }}, - {"DepartureSignal", [](auto const &M) { return flag(M.DepartureSignal); }}, - {"PantsValve", [](auto const &M) { return flag(M.PantsValve.is_enabled) + 2 * flag(M.PantsValve.is_disabled); }}, - {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold); }}, - {"Imin", [](auto const &M) { return M.Imin; }}, - {"DamageFlag", [](auto const &M) { return M.DamageFlag; }}, - {"RadioStop", [](auto const &M) { return flag(M.RadioStopFlag); }}, - {"BrakeDelayFlag", [](auto const &M) { return M.BrakeDelayFlag; }}, - {"SandDose", [](auto const &M) { return flag(M.SandDose); }}, + {"DepartureSignal", [](auto const &M) { return flag(M.DepartureSignal()); }}, + {"PantsValve", [](auto const &M) { return flag(M.pantographAir.valve.is_enabled) + 2 * flag(M.pantographAir.valve.is_disabled); }}, + {"MaxCurrentHigh", [](auto const &M) { return flag(M.MotorOverloadRelayHighThreshold()); }}, + {"Imin", [](auto const &M) { return M.Imin(); }}, + {"DamageFlag", [](auto const &M) { return M.DamageFlag.Bits(); }}, + {"RadioStop", [](auto const &M) { return flag(M.RadioStopFlag()); }}, + {"BrakeDelayFlag", [](auto const &M) { return M.brakes.delaySetting; }}, + {"SandDose", [](auto const &M) { return flag(M.SandDose()); }}, {"CabSignal", [](auto const &M) { return flag(M.SecuritySystem.is_cabsignal_blinking()); }}, - {"LoadAmount", [](auto const &M) { return M.LoadAmount; }}, - {"LoadStatus", [](auto const &M) { return M.LoadStatus; }}, + {"LoadAmount", [](auto const &M) { return M.LoadAmount(); }}, + {"LoadStatus", [](auto const &M) { return M.LoadStatus(); }}, {"SpeedCtrlValue", [](auto const &M) { return M.SpeedCtrlValue; }}, {"SpeedCtrlParking", [](auto const &M) { return flag(M.SpeedCtrlUnit.Parking); }}, - {"SpringBrakeActivate", [](auto const &M) { return flag(M.SpringBrake.Activate); }}, + {"SpringBrakeActivate", [](auto const &M) { return flag(M.brakes.spring.activate); }}, }; - for (int end : {end::front, end::rear}) { - auto const name{std::string{end == end::front ? "Front" : "Rear"}}; + for (auto const end : VehicleEnds) { + auto const name{std::string{end == VehicleEnd::front ? "Front" : "Rear"}}; result.emplace_back("MotorBlowers" + name + "Enabled", [end](auto const &M) { return flag(M.MotorBlowers[end].is_enabled); }); result.emplace_back("MotorBlowers" + name + "Disabled", [end](auto const &M) { return flag(M.MotorBlowers[end].is_disabled); }); - result.emplace_back("Pant" + name + "Valve", [end](auto const &M) { return flag(M.Pantographs[end].valve.is_enabled) + 2 * flag(M.Pantographs[end].valve.is_disabled); }); + result.emplace_back("Pant" + name + "Valve", [end](auto const &M) { return flag(M.pantographs[end].valve.is_enabled) + 2 * flag(M.pantographs[end].valve.is_disabled); }); } - for (int side : {side::right, side::left}) { - auto const name{std::string{side == side::right ? "Right" : "Left"}}; + for (auto const side : VehicleSides) { + auto const name{std::string{side == VehicleSide::right ? "Right" : "Left"}}; result.emplace_back(name + "DoorPermit", [side](auto const &M) { return flag(M.Doors.instances[side].open_permit); }); result.emplace_back(name + "DoorRemoteOpen", [side](auto const &M) { return flag(M.Doors.instances[side].remote_open); }); result.emplace_back(name + "DoorRemoteClose", [side](auto const &M) { return flag(M.Doors.instances[side].remote_close); }); @@ -239,17 +239,18 @@ TEST_CASE("commands: every command run on every real vehicle") { vehicle real{definition::fiz(path), 0.0, "test", 1}; // loading takes place where the command was given, which comes with the command (PutCommand). a // vehicle gets none before its first one, TCommand::Location is left uninitialised - real->CommandIn.Location = real->Loc; + real->CommandIn.Location = real->Loc(); auto done{false}; auto channels{state()}; channels.emplace_back("Done", [&done](auto const &) { return flag(done); }); test::trace trace{"commands/" + path, channels, 1, false}; - trace.sample(0.0, real.mover()); + trace.sample(0.0, real.physics()); for (std::size_t i = 0; i < commands.size(); ++i) { auto const &command{commands[i]}; trace.mark(std::format("{} {} {}", command.name, command.value1, command.value2)); - done = real->RunCommand(command.name, command.value1, command.value2, coupling::control); - trace.sample(static_cast(i + 1), real.mover()); + auto const parsed{ParseVehicleCommand(command.name)}; + done = real->RunCommand(parsed.command, command.value1, command.value2, Coupling::control, parsed.argument); + trace.sample(static_cast(i + 1), real.physics()); } trace.check(); } @@ -260,7 +261,7 @@ namespace { // a switch of the cab, worked on the driven vehicle struct action { std::string name; - std::function work; + std::function work; }; // every switch sending its state to the rest of the train, each way and to each range, in the order a crew @@ -284,16 +285,16 @@ std::vector const actions{ {"OilPumpSwitch on", [](auto &M) { return M.OilPumpSwitch(true, range_t::consist); }}, {"OilPumpSwitchOff on", [](auto &M) { return M.OilPumpSwitchOff(true, range_t::unit); }}, {"OilPumpSwitchOff off", [](auto &M) { return M.OilPumpSwitchOff(false, range_t::consist); }}, - {"MotorBlowersSwitch front on", [](auto &M) { return M.MotorBlowersSwitch(true, end::front, range_t::consist); }}, - {"MotorBlowersSwitch rear on", [](auto &M) { return M.MotorBlowersSwitch(true, end::rear, range_t::unit); }}, - {"MotorBlowersSwitchOff front on", [](auto &M) { return M.MotorBlowersSwitchOff(true, end::front, range_t::consist); }}, - {"MotorBlowersSwitchOff rear on", [](auto &M) { return M.MotorBlowersSwitchOff(true, end::rear, range_t::unit); }}, - {"MotorBlowersSwitchOff front off", [](auto &M) { return M.MotorBlowersSwitchOff(false, end::front, range_t::consist); }}, - {"MotorBlowersSwitchOff rear off", [](auto &M) { return M.MotorBlowersSwitchOff(false, end::rear, range_t::consist); }}, + {"MotorBlowersSwitch front on", [](auto &M) { return M.MotorBlowersSwitch(true, VehicleEnd::front, range_t::consist); }}, + {"MotorBlowersSwitch rear on", [](auto &M) { return M.MotorBlowersSwitch(true, VehicleEnd::rear, range_t::unit); }}, + {"MotorBlowersSwitchOff front on", [](auto &M) { return M.MotorBlowersSwitchOff(true, VehicleEnd::front, range_t::consist); }}, + {"MotorBlowersSwitchOff rear on", [](auto &M) { return M.MotorBlowersSwitchOff(true, VehicleEnd::rear, range_t::unit); }}, + {"MotorBlowersSwitchOff front off", [](auto &M) { return M.MotorBlowersSwitchOff(false, VehicleEnd::front, range_t::consist); }}, + {"MotorBlowersSwitchOff rear off", [](auto &M) { return M.MotorBlowersSwitchOff(false, VehicleEnd::rear, range_t::consist); }}, {"OperatePantographsValve enable", [](auto &M) { return M.OperatePantographsValve(operation_t::enable, range_t::consist); }}, - {"OperatePantographValve front enable", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::enable, range_t::consist); }}, - {"OperatePantographValve rear enable_on", [](auto &M) { return M.OperatePantographValve(end::rear, operation_t::enable_on, range_t::unit); }}, - {"OperatePantographValve rear enable_off", [](auto &M) { return M.OperatePantographValve(end::rear, operation_t::enable_off, range_t::unit); }}, + {"OperatePantographValve front enable", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::consist); }}, + {"OperatePantographValve rear enable_on", [](auto &M) { return M.OperatePantographValve(VehicleEnd::rear, operation_t::enable_on, range_t::unit); }}, + {"OperatePantographValve rear enable_off", [](auto &M) { return M.OperatePantographValve(VehicleEnd::rear, operation_t::enable_off, range_t::unit); }}, {"DirectionForward", [](auto &M) { return M.DirectionForward(); }}, {"ConverterSwitch on", [](auto &M) { return M.ConverterSwitch(true, range_t::consist); }}, {"CompressorSwitch on", [](auto &M) { return M.CompressorSwitch(true, range_t::consist); }}, @@ -329,30 +330,30 @@ std::vector const actions{ {"SandboxAuto off", [](auto &M) { return M.SandboxAuto(false, range_t::consist); }}, {"SandboxManual off", [](auto &M) { return M.SandboxManual(false, range_t::consist); }}, {"Sandbox off", [](auto &M) { return M.Sandbox(false, range_t::consist); }}, - {"PermitDoors right", [](auto &M) { return M.PermitDoors(side::right, true, range_t::consist); }}, - {"PermitDoors left", [](auto &M) { return M.PermitDoors(side::left, true, range_t::unit); }}, + {"PermitDoors right", [](auto &M) { return M.PermitDoors(VehicleSide::right, true, range_t::consist); }}, + {"PermitDoors left", [](auto &M) { return M.PermitDoors(VehicleSide::left, true, range_t::unit); }}, {"ChangeDoorPermitPreset +1", [](auto &M) { return M.ChangeDoorPermitPreset(1, range_t::consist); }}, {"ChangeDoorPermitPreset -1", [](auto &M) { return M.ChangeDoorPermitPreset(-1, range_t::consist); }}, {"PermitDoorStep off", [](auto &M) { return M.PermitDoorStep(false, range_t::consist); }}, {"PermitDoorStep on", [](auto &M) { return M.PermitDoorStep(true, range_t::unit); }}, {"LockDoors off", [](auto &M) { return M.LockDoors(false, range_t::consist); }}, - {"OperateDoors right open local", [](auto &M) { return M.OperateDoors(side::right, true, range_t::local); }}, - {"OperateDoors left open", [](auto &M) { return M.OperateDoors(side::left, true, range_t::consist); }}, - {"OperateDoors right close", [](auto &M) { return M.OperateDoors(side::right, false, range_t::unit); }}, + {"OperateDoors right open local", [](auto &M) { return M.OperateDoors(VehicleSide::right, true, range_t::local); }}, + {"OperateDoors left open", [](auto &M) { return M.OperateDoors(VehicleSide::left, true, range_t::consist); }}, + {"OperateDoors right close", [](auto &M) { return M.OperateDoors(VehicleSide::right, false, range_t::unit); }}, {"ChangeDoorControlMode remote", [](auto &M) { return M.ChangeDoorControlMode(true, range_t::consist); }}, {"ChangeDoorControlMode local", [](auto &M) { return M.ChangeDoorControlMode(false, range_t::unit); }}, {"LockDoors on", [](auto &M) { return M.LockDoors(true, range_t::unit); }}, {"signal_departure on", [](auto &M) { return M.signal_departure(true, range_t::consist); }}, {"signal_departure off", [](auto &M) { return M.signal_departure(false, range_t::unit); }}, - {"PermitDoors right off", [](auto &M) { return M.PermitDoors(side::right, false, range_t::consist); }}, + {"PermitDoors right off", [](auto &M) { return M.PermitDoors(VehicleSide::right, false, range_t::consist); }}, {"HeatingSwitch off", [](auto &M) { return M.HeatingSwitch(false, range_t::unit); }}, {"MainSwitch off", [](auto &M) { return M.MainSwitch(false, range_t::consist); }}, {"DropAllPantographs", [](auto &M) { return M.DropAllPantographs(true, range_t::consist); }}, {"DropAllPantographs released", [](auto &M) { return M.DropAllPantographs(false, range_t::unit); }}, {"OperatePantographsValve disable", [](auto &M) { return M.OperatePantographsValve(operation_t::disable, range_t::unit); }}, - {"OperatePantographValve front disable_on", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::disable_on, range_t::consist); }}, - {"OperatePantographValve front disable_off", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::disable_off, range_t::consist); }}, - {"OperatePantographValve front none", [](auto &M) { return M.OperatePantographValve(end::front, operation_t::none, range_t::local); }}, + {"OperatePantographValve front disable_on", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::disable_on, range_t::consist); }}, + {"OperatePantographValve front disable_off", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::disable_off, range_t::consist); }}, + {"OperatePantographValve front none", [](auto &M) { return M.OperatePantographValve(VehicleEnd::front, operation_t::none, range_t::local); }}, {"CompressorSwitch off", [](auto &M) { return M.CompressorSwitch(false, range_t::unit); }}, {"ConverterSwitch off", [](auto &M) { return M.ConverterSwitch(false, range_t::unit); }}, {"WaterCircuitsLinkSwitch off", [](auto &M) { return M.WaterCircuitsLinkSwitch(false, range_t::unit); }}, @@ -362,8 +363,8 @@ std::vector const actions{ {"WaterPumpBreakerSwitch off", [](auto &M) { return M.WaterPumpBreakerSwitch(false, range_t::unit); }}, {"FuelPumpSwitch off", [](auto &M) { return M.FuelPumpSwitch(false, range_t::unit); }}, {"OilPumpSwitch off", [](auto &M) { return M.OilPumpSwitch(false, range_t::unit); }}, - {"MotorBlowersSwitch front off", [](auto &M) { return M.MotorBlowersSwitch(false, end::front, range_t::unit); }}, - {"MotorBlowersSwitch rear off", [](auto &M) { return M.MotorBlowersSwitch(false, end::rear, range_t::consist); }}, + {"MotorBlowersSwitch front off", [](auto &M) { return M.MotorBlowersSwitch(false, VehicleEnd::front, range_t::unit); }}, + {"MotorBlowersSwitch rear off", [](auto &M) { return M.MotorBlowersSwitch(false, VehicleEnd::rear, range_t::consist); }}, {"CompartmentLightsSwitch off", [](auto &M) { return M.CompartmentLightsSwitch(false, range_t::unit); }}, {"BatterySwitch off", [](auto &M) { return M.BatterySwitch(false, range_t::unit); }}, {"CabDeactivisation", [](auto &M) { return M.CabDeactivisation(); }}, @@ -377,19 +378,19 @@ TEST_CASE("commands: every switch of the cab, sent to the next vehicle") { test::reseed_random(); vehicle driven{definition::fiz(path), 0.0, "driven", 1}; vehicle next{definition::fiz(path), 0.0, "next"}; - driven->Attach(end::rear, end::front, &next.mover(), test::consist::full_coupling, true, false); + driven->Attach(VehicleEnd::rear, VehicleEnd::front, &next.physics(), test::consist::full_coupling, true, false); auto done{false}; auto channels{state()}; for (auto const &channel : state()) { - channels.emplace_back("next." + channel.name, [&next, value = channel.value](auto const &) { return value(next.mover()); }); + channels.emplace_back("next." + channel.name, [&next, value = channel.value](auto const &) { return value(next.physics()); }); } channels.emplace_back("Done", [&done](auto const &) { return flag(done); }); test::trace trace{"switches/" + path, channels, 1, false}; - trace.sample(0.0, driven.mover()); + trace.sample(0.0, driven.physics()); for (std::size_t i = 0; i < actions.size(); ++i) { trace.mark(actions[i].name); - done = actions[i].work(driven.mover()); - trace.sample(static_cast(i + 1), driven.mover()); + done = actions[i].work(driven.physics()); + trace.sample(static_cast(i + 1), driven.physics()); } trace.check(); } @@ -407,13 +408,13 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th auto done{false}; auto channels{state()}; channels.insert(channels.end(), { - {"PantFrontActive", [](auto const &M) { return flag(M.Pantographs[end::front].is_active); }}, - {"PantRearActive", [](auto const &M) { return flag(M.Pantographs[end::rear].is_active); }}, - {"PantPress", [](auto const &M) { return M.PantPress; }}, - {"GroundRelay", [](auto const &M) { return flag(M.GroundRelay); }}, - {"ConverterFlag", [](auto const &M) { return flag(M.ConverterFlag); }}, - {"CompressorFlag", [](auto const &M) { return flag(M.CompressorFlag); }}, - {"Compressor", [](auto const &M) { return M.Compressor; }}, + {"PantFrontActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::front].is_active); }}, + {"PantRearActive", [](auto const &M) { return flag(M.pantographs[VehicleEnd::rear].is_active); }}, + {"PantPress", [](auto const &M) { return M.pantographAir.Pressure(); }}, + {"GroundRelay", [](auto const &M) { return flag(M.protection.GroundHolds()); }}, + {"ConverterFlag", [](auto const &M) { return flag(M.converter.IsRunning()); }}, + {"CompressorFlag", [](auto const &M) { return flag(M.air.compressor.IsRunning()); }}, + {"Compressor", [](auto const &M) { return M.air.MainReservoirPressure(); }}, {"MainCtrlActualPos", [](auto const &M) { return M.MainCtrlActualPos; }}, {"Itot", [](auto const &M) { return M.Itot; }}, {"FuseFlag", [](auto const &M) { return flag(M.FuseFlag); }}, @@ -421,17 +422,17 @@ TEST_CASE("commands: every switch of the cab, worked on a pair standing under th }); auto const own{channels.size()}; for (std::size_t i = 0; i < own; ++i) { - channels.emplace_back("next." + channels[i].name, [&pair, value = channels[i].value](auto const &) { return value(pair[1].mover()); }); + channels.emplace_back("next." + channels[i].name, [&pair, value = channels[i].value](auto const &) { return value(pair[1].physics()); }); } channels.emplace_back("Done", [&done](auto const &) { return flag(done); }); test::trace trace{"switches_live/" + path, channels, 1, false}; - trace.sample(0.0, pair[0].mover()); + trace.sample(0.0, pair[0].physics()); test::track const catenary{.voltage = test::catenary_3kv}; for (std::size_t i = 0; i < actions.size(); ++i) { trace.mark(actions[i].name); - done = actions[i].work(pair[0].mover()); + done = actions[i].work(pair[0].physics()); pair.run(2.0, catenary); - trace.sample(static_cast(i + 1), pair[0].mover()); + trace.sample(static_cast(i + 1), pair[0].physics()); } trace.check(); } @@ -447,9 +448,9 @@ struct train { vehicle middle{definition::fiz("4e_v1/4e"), 0.0, "middle"}; vehicle last{definition::fiz("4e_v1/4e"), 0.0, "last"}; - explicit train(int Coupling) { - head->Attach(end::rear, end::rear, &middle.mover(), Coupling, true, false); - middle->Attach(end::front, end::front, &last.mover(), Coupling, true, false); + explicit train(CouplingSet const couplings) { + head->Attach(VehicleEnd::rear, VehicleEnd::rear, &middle.physics(), couplings, true, false); + middle->Attach(VehicleEnd::front, VehicleEnd::front, &last.physics(), couplings, true, false); } }; @@ -463,85 +464,85 @@ TEST_CASE("commands: travel along the train, turned round for a vehicle facing b CHECK(consist.middle->CabActive == -1); CHECK(consist.last->CabActive == 1); // the command is done in each vehicle and cleared - CHECK(consist.middle->CommandIn.Command.empty()); - CHECK(consist.last->CommandIn.Command.empty()); + CHECK(consist.middle->CommandIn.Command == VehicleCommand::none); + CHECK(consist.last->CommandIn.Command == VehicleCommand::none); SUBCASE("door permits: the right side of the sender is the left one of a vehicle facing backwards") { - consist.head->PermitDoors(side::right, true, range_t::consist); - CHECK(consist.head->Doors.instances[side::right].open_permit); - CHECK(consist.middle->Doors.instances[side::left].open_permit); - CHECK_FALSE(consist.middle->Doors.instances[side::right].open_permit); - CHECK(consist.last->Doors.instances[side::right].open_permit); + consist.head->PermitDoors(VehicleSide::right, true, range_t::consist); + CHECK(consist.head->Doors.instances[VehicleSide::right].open_permit); + CHECK(consist.middle->Doors.instances[VehicleSide::left].open_permit); + CHECK_FALSE(consist.middle->Doors.instances[VehicleSide::right].open_permit); + CHECK(consist.last->Doors.instances[VehicleSide::right].open_permit); // and revoked the same way - consist.head->PermitDoors(side::right, false, range_t::consist); - CHECK_FALSE(consist.middle->Doors.instances[side::left].open_permit); - CHECK_FALSE(consist.last->Doors.instances[side::right].open_permit); + consist.head->PermitDoors(VehicleSide::right, false, range_t::consist); + CHECK_FALSE(consist.middle->Doors.instances[VehicleSide::left].open_permit); + CHECK_FALSE(consist.last->Doors.instances[VehicleSide::right].open_permit); } SUBCASE("a pantograph valve: the vehicles past one coupled by its control cable take the other pantograph") { - consist.head->OperatePantographValve(end::front, operation_t::enable, range_t::consist); - CHECK(consist.head->Pantographs[end::front].valve.is_enabled); - CHECK(consist.middle->Pantographs[end::front].valve.is_enabled); - CHECK(consist.last->Pantographs[end::rear].valve.is_enabled); + consist.head->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::consist); + CHECK(consist.head->pantographs[VehicleEnd::front].valve.is_enabled); + CHECK(consist.middle->pantographs[VehicleEnd::front].valve.is_enabled); + CHECK(consist.last->pantographs[VehicleEnd::rear].valve.is_enabled); } SUBCASE("sent backwards, it goes no further than the sender: nothing is coupled at its front") { - consist.head->RunCommand("DoorLock", 0, -1, coupling::control); + consist.head->RunCommand(VehicleCommand::doorLock, 0, -1, Coupling::control); CHECK_FALSE(consist.head->Doors.lock_enabled); CHECK(consist.middle->Doors.lock_enabled); } SUBCASE("the same command again isn't taken by the next vehicle a second time") { - CHECK(consist.middle->SetInternalCommand("DoorStep", 0, 1, coupling::control)); - CHECK_FALSE(consist.middle->SetInternalCommand("DoorStep", 0, 1, coupling::control)); + CHECK(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, Coupling::control)); + CHECK_FALSE(consist.middle->SetInternalCommand(VehicleCommand::doorStep, 0, 1, Coupling::control)); CHECK_FALSE(consist.head->RunInternalCommand()); // nothing to run } } TEST_CASE("commands: don't pass a coupling without the control cable") { - train consist{coupling::coupler | coupling::brakehose}; - consist.head->RunCommand("DoorLock", 0, 1, coupling::control); + train consist{Coupling::coupler | Coupling::brakeHose}; + consist.head->RunCommand(VehicleCommand::doorLock, 0, 1, Coupling::control); CHECK_FALSE(consist.head->Doors.lock_enabled); CHECK(consist.middle->Doors.lock_enabled); // a command of another coupling goes through it - consist.head->RunCommand("DoorStep", 0, 1, coupling::brakehose); + consist.head->RunCommand(VehicleCommand::doorStep, 0, 1, Coupling::brakeHose); CHECK_FALSE(consist.middle->Doors.step_enabled); } TEST_CASE("commands: a wagon loaded and unloaded by commands, which repeat until done") { vehicle wagon{definition::fiz("3wl_v2/3wl")}; - REQUIRE(wagon->MaxLoad > 0); + REQUIRE(wagon->MaxLoad() > 0); test::trace trace{"commands/loading", state(), 100}; wagon.record(trace); // the game gives the commands of loading through PutCommand, with the place of the platform or the ramp SUBCASE("loading 12 tonnes of coal") { trace.mark("load"); - wagon->PutCommand("Load=Coal", 12, 0, wagon->Loc); + wagon->PutCommand("Load=Coal", 12, 0, wagon->Loc()); wagon.run(30.0); - CHECK(wagon->LoadAmount == doctest::Approx(12.0).epsilon(0.1)); + CHECK(wagon->LoadAmount() == doctest::Approx(12.0).epsilon(0.1)); CHECK(wagon->LoadType.name == "coal"); - CHECK(wagon->CommandIn.Command.empty()); + CHECK(wagon->CommandIn.Command == VehicleCommand::none); trace.mark("unload"); - wagon->PutCommand("UnLoad=Coal", 20, 0, wagon->Loc); + wagon->PutCommand("UnLoad=Coal", 20, 0, wagon->Loc()); wagon.run(200.0); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LoadType.name.empty()); trace.check(); } SUBCASE("a load the wagon doesn't take stays a command, not done") { - wagon->PutCommand("Load=passengers", 12, 0, wagon->Loc); + wagon->PutCommand("Load=passengers", 12, 0, wagon->Loc()); wagon.run(10.0); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); - CHECK_FALSE(wagon->CommandIn.Command.empty()); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); + CHECK_FALSE(wagon->CommandIn.Command == VehicleCommand::none); } SUBCASE("away from the place of the command nothing is loaded") { wagon->PutCommand("Load=Coal", 12, 5.0, TLocation{100.0, 0.0, 0.0}); wagon.run(10.0); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LastLoadChangeTime == doctest::Approx(0.0)); } SUBCASE("unloading an empty wagon isn't done either") { - wagon->PutCommand("UnLoad=Coal", 12, 0, wagon->Loc); + wagon->PutCommand("UnLoad=Coal", 12, 0, wagon->Loc()); wagon.run(10.0); - CHECK_FALSE(wagon->CommandIn.Command.empty()); + CHECK_FALSE(wagon->CommandIn.Command == VehicleCommand::none); } } diff --git a/tests/unit/test_compartment_lights.cpp b/tests/unit/test_compartment_lights.cpp new file mode 100644 index 000000000..8724a135b --- /dev/null +++ b/tests/unit/test_compartment_lights.cpp @@ -0,0 +1,80 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the compartment lights lamp of the cab (i-compartmentlights:) shows CompartmentLights.is_active of the cab's own +// vehicle, which LightsCheck() works out from the low voltage power and the compartment lights switch (eu07/maszyna#456) +// NOTE: the checks call LightsCheck() the way the vehicle update does, after setting the power by hand + +namespace { + +void lights_check(vehicle &Car) { + Car->LightsCheck(0.01); +} + +} // namespace + +TEST_CASE("compartment lights: the lights need low voltage power and the switch") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + REQUIRE(car->CompartmentLights.start_type == start_t::manual); + car->lowVoltage.Set24vAvailableForTest(false); + car->lowVoltage.Set110vAvailableForTest(false); + + car->CompartmentLightsSwitch(true, range_t::local); // switch on, no power + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + + car->lowVoltage.Set110vAvailableForTest(true); // converter on + lights_check(car); + CHECK(car->CompartmentLights.is_active); + CHECK(car->CompartmentLights.intensity == doctest::Approx(1.0)); + + car->lowVoltage.Set110vAvailableForTest(false); // battery only: the lights stay on, dimmed + car->lowVoltage.Set24vAvailableForTest(true); + lights_check(car); + CHECK(car->CompartmentLights.is_active); + CHECK(car->CompartmentLights.intensity == doctest::Approx(0.5)); + + car->lowVoltage.Set24vAvailableForTest(false); // no power at all + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); +} + +TEST_CASE("compartment lights: the off switch turns the lights off, the on switch back on") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + car->lowVoltage.Set110vAvailableForTest(true); + + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); // manual start: off until switched on + + // push buttons: the on button latches the lights, they stay on once it is released + car->CompartmentLightsSwitch(true, range_t::local); + lights_check(car); + car->CompartmentLightsSwitch(false, range_t::local); + lights_check(car); + CHECK(car->CompartmentLights.is_active); + + car->CompartmentLightsSwitchOff(true, range_t::local); + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + car->CompartmentLightsSwitchOff(false, range_t::local); + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); // still off once the off button is released +} + +TEST_CASE("compartment lights: lights started automatically come on with the power alone") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "CompartmentLightsStart", "Automatic")}; + REQUIRE(car->CompartmentLights.start_type == start_t::automatic); + car->lowVoltage.Set24vAvailableForTest(false); + car->lowVoltage.Set110vAvailableForTest(false); + + lights_check(car); + CHECK_FALSE(car->CompartmentLights.is_active); + + car->lowVoltage.Set110vAvailableForTest(true); + lights_check(car); + CHECK(car->CompartmentLights.is_active); +} diff --git a/tests/unit/test_compartment_lights_switch.cpp b/tests/unit/test_compartment_lights_switch.cpp new file mode 100644 index 000000000..0433c1d1f --- /dev/null +++ b/tests/unit/test_compartment_lights_switch.cpp @@ -0,0 +1,227 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "vehicle/compartmentlightsswitch.h" + +using test::definition; +using test::vehicle; + +// the compartment lights commands of the cab (TTrain::OnCommand_compartmentlightsenable/disable/toggle): whether the +// command for one request (on: CompartmentLights.is_enabled, off: is_disabled) also withdraws the other one. In a cab +// without compartmentlights_sw: and without the push buttons (the CD 810 cab A) the keyboard toggle, ctrl+;, turned +// the lights on and off once, then never again: the off request stayed set alongside the on one. In a cab with the +// compartmentlightson_sw: / compartmentlightsoff_sw: push buttons (the EN57-2000) the toggle sent the key release to the +// other command than the press, picked again from the state the press had changed: the pressed button never withdrew +// its request and the lights were off only while ctrl+; was held. + +TEST_CASE("compartment lights switch: which command withdraws the other request") { + // a two-state compartmentlights_sw: holds one request at a time + CHECK(compartment_lights_switch::withdraws_other_request(true, true, false)); + CHECK(compartment_lights_switch::withdraws_other_request(true, true, true)); + // a push type compartmentlights_sw: withdraws both requests itself, when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, false)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(true, false, true)); + // no compartmentlights_sw:, the push button of the other request withdraws it when it's released + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, false, true)); + CHECK_FALSE(compartment_lights_switch::withdraws_other_request(false, true, true)); + // no compartmentlights_sw: and no push button: nothing else would withdraw it + CHECK(compartment_lights_switch::withdraws_other_request(false, false, false)); + CHECK(compartment_lights_switch::withdraws_other_request(false, true, false)); +} + +namespace { + +// the compartment lights controls a cab's .mmd may have +struct cab_controls { + bool has_switch{false}; // compartmentlights_sw: + bool switch_is_toggle{true}; // its type (a gauge is a toggle type unless declared otherwise) + bool has_on_button{false}; // compartmentlightson_sw: + bool has_off_button{false}; // compartmentlightsoff_sw: +}; + +// the effect of the cab's commands on the vehicle, as TTrain::OnCommand_compartmentlightsenable/disable/toggle do it +// NOTE: LightsCheck() runs between the press and the release, as the vehicle update does between two frames +void lights_check(vehicle &Car) { + Car->LightsCheck(0.01); +} + +void enable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitch(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_off_button)) { + Car->CompartmentLightsSwitchOff(false, range_t::local); + } +} + +void enable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_on_button) { + Car->CompartmentLightsSwitch(false, local); + } +} + +void disable_press(vehicle &Car, cab_controls const &Cab) { + Car->CompartmentLightsSwitchOff(true, range_t::local); + if (compartment_lights_switch::withdraws_other_request(Cab.has_switch, Cab.switch_is_toggle, Cab.has_on_button)) { + Car->CompartmentLightsSwitch(false, range_t::local); + } +} + +void disable_release(vehicle &Car, cab_controls const &Cab) { + using enum range_t; + if (Cab.has_switch && false == Cab.switch_is_toggle) { + Car->CompartmentLightsSwitch(false, local); + Car->CompartmentLightsSwitchOff(false, local); + } + if (Cab.has_off_button) { + Car->CompartmentLightsSwitchOff(false, local); + } +} + +// a click on the control of the command (or its own key): the press, then the release +void enable(vehicle &Car, cab_controls const &Cab) { + enable_press(Car, Cab); + lights_check(Car); + enable_release(Car, Cab); + lights_check(Car); +} + +void disable(vehicle &Car, cab_controls const &Cab) { + disable_press(Car, Cab); + lights_check(Car); + disable_release(Car, Cab); + lights_check(Car); +} + +// the keyboard toggle picks the command from the state on the press, the key held down for a few frames; the release +// goes to both commands, the press changed the state it would be picked from +void toggle(vehicle &Car, cab_controls const &Cab) { + if (auto const &lights{Car->CompartmentLights}; false == lights.is_active && false == lights.is_enabled) { + enable_press(Car, Cab); + } + else { + disable_press(Car, Cab); + } + for (auto frame = 0; frame < 3; ++frame) { + lights_check(Car); + } + enable_release(Car, Cab); + disable_release(Car, Cab); + lights_check(Car); +} + +// the Elf (21WE-a), its compartment lights started by hand, with the converter running +void power_up(vehicle &Car) { + REQUIRE(Car->CompartmentLights.start_type == start_t::manual); + Car->lowVoltage.Set110vAvailableForTest(true); + lights_check(Car); + REQUIRE_FALSE(Car->CompartmentLights.is_active); +} + +} // namespace + +TEST_CASE("compartment lights switch: the keyboard toggle works every time in a cab without the switch") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{}; // no compartmentlights_sw:, no push buttons, like the CD 810 cab A + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // one request at a time + CHECK_FALSE((car->CompartmentLights.is_enabled && car->CompartmentLights.is_disabled)); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle in a cab with the two-state switch, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = true}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // the switch holds the request of its position + CHECK(car->CompartmentLights.is_enabled == (press % 2 == 1)); + CHECK(car->CompartmentLights.is_disabled == (press % 2 == 0)); + } +} + +TEST_CASE("compartment lights switch: the push type switch withdraws both requests when released, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_switch = true, .switch_is_toggle = false}; + + for (auto press = 1; press <= 4; ++press) { + CAPTURE(press); + toggle(car, cab); + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the on and off push buttons latch the lights, as before") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + for (auto round = 1; round <= 2; ++round) { + CAPTURE(round); + // each button withdraws its own request when it's released, the lights stay as they were put + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle latches the lights in a cab with the on and off push buttons") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; // no compartmentlights_sw:, like the EN57-2000 + + for (auto press = 1; press <= 6; ++press) { + CAPTURE(press); + toggle(car, cab); + // odd presses turn the lights on, even ones off, and they stay so after the key is released + CHECK(car->CompartmentLights.is_active == (press % 2 == 1)); + // both push buttons are back in the neutral position, neither request is left behind + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); + } +} + +TEST_CASE("compartment lights switch: the keyboard toggle and the on and off push buttons work together") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + power_up(car); + cab_controls const cab{.has_on_button = true, .has_off_button = true}; + + toggle(car, cab); + REQUIRE(car->CompartmentLights.is_active); + // the off button turns off what the key turned on... + disable(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + // ...and the key turns on what the off button turned off + toggle(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + enable(car, cab); + CHECK(car->CompartmentLights.is_active); + toggle(car, cab); + CHECK_FALSE(car->CompartmentLights.is_active); + CHECK_FALSE(car->CompartmentLights.is_enabled); + CHECK_FALSE(car->CompartmentLights.is_disabled); +} diff --git a/tests/unit/test_compressor.cpp b/tests/unit/test_compressor.cpp index 4f55ce0b8..5694f2d65 100644 --- a/tests/unit/test_compressor.cpp +++ b/tests/unit/test_compressor.cpp @@ -26,7 +26,7 @@ vehicle compressor_vehicle(double const Delay, std::string const &Power = "Main" definition.set("Brake", "CompressorStartDelay", Delay); } vehicle vehicle{definition}; - vehicle->CompressedVolume = 0.0; + vehicle->air.Fill(0.0); vehicle->LastSwitchingTime = 10.0; // nothing was switched lately return vehicle; } @@ -45,106 +45,106 @@ void run_compressor(vehicle &Vehicle, double const Seconds) { TEST_CASE("compressor: without a start delay the compressor starts with its power") { auto vehicle{compressor_vehicle(0.0)}; run_compressor(vehicle, 1.0); - REQUIRE_FALSE(vehicle->CompressorFlag); // no power, no compressor + REQUIRE_FALSE(vehicle->air.compressor.IsRunning()); // no power, no compressor - vehicle->Mains = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, step); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the compressor starts the delay after getting its power") { auto vehicle{compressor_vehicle(5.0)}; - vehicle->Mains = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->CompressorFlag); - CHECK(vehicle->Compressor == doctest::Approx(0.0)); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); + CHECK(vehicle->air.MainReservoirPressure() == doctest::Approx(0.0)); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 10.0); - CHECK(vehicle->Compressor > 0.0); // and fills the reservoir + CHECK(vehicle->air.MainReservoirPressure() > 0.0); // and fills the reservoir } TEST_CASE("compressor: the delay starts over once the power is gone") { auto vehicle{compressor_vehicle(5.0)}; - vehicle->Mains = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, 10.0); - REQUIRE(vehicle->CompressorFlag); + REQUIRE(vehicle->air.compressor.IsRunning()); - vehicle->Mains = false; // the engine stopped + vehicle->lineBreaker.Open(); // the engine stopped run_compressor(vehicle, 1.0); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); - vehicle->Mains = true; // and started again + vehicle->lineBreaker.Close(); // and started again run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: a compressor fed from the low voltage waits from the low voltage coming on") { auto vehicle{compressor_vehicle(5.0, "")}; // the default supply: the converter, the 110 V - vehicle->Mains = true; // which alone doesn't feed it + vehicle->lineBreaker.Close(); // which alone doesn't feed it run_compressor(vehicle, 10.0); - REQUIRE_FALSE(vehicle->CompressorFlag); + REQUIRE_FALSE(vehicle->air.compressor.IsRunning()); - vehicle->Power110vIsAvailable = true; + vehicle->lowVoltage.Set110vAvailableForTest(true); run_compressor(vehicle, 4.9); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the pressure switch stops the compressor above the cut-out pressure") { auto vehicle{compressor_vehicle(0.0)}; - vehicle->Mains = true; - vehicle->CompressedVolume = 8.5; // over MaxCP, in the reservoir of 1 m3 + vehicle->lineBreaker.Close(); + vehicle->air.Fill(8.5); // over MaxCP, in the reservoir of 1 m3 run_compressor(vehicle, step); - CHECK(vehicle->CompressorGovernorLock); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.IsGovernorLocked()); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: without a pressure switch the air over the cut-out pressure is vented") { auto vehicle{compressor_vehicle(0.0, "Main", 8.0)}; // MinCP the same as MaxCP: no pressure switch - vehicle->Mains = true; - vehicle->CompressedVolume = 8.5; + vehicle->lineBreaker.Close(); + vehicle->air.Fill(8.5); run_compressor(vehicle, step); - REQUIRE(vehicle->CompressorFlag); // nothing stops it - CHECK(vehicle->CompressedVolume < 8.5 * 0.81); // a fifth of the air let out + REQUIRE(vehicle->air.compressor.IsRunning()); // nothing stops it + CHECK(vehicle->air.CompressedVolume() < 8.5 * 0.81); // a fifth of the air let out } TEST_CASE("compressor: an engine stopped before the delay passed counts the whole delay again") { auto vehicle{compressor_vehicle(30.0)}; - vehicle->Mains = true; // engine started + vehicle->lineBreaker.Close(); // engine started run_compressor(vehicle, 20.0); - REQUIRE_FALSE(vehicle->CompressorFlag); + REQUIRE_FALSE(vehicle->air.compressor.IsRunning()); - vehicle->Mains = false; // engine stopped, 10 s short of the delay + vehicle->lineBreaker.Open(); // engine stopped, 10 s short of the delay run_compressor(vehicle, 1.0); - vehicle->Mains = true; + vehicle->lineBreaker.Close(); run_compressor(vehicle, 15.0); // 36 s since the first start, but only 15 s since this one - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 15.1); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the start delay holds back a compressor switched on by hand too") { auto vehicle{compressor_vehicle(30.0)}; - vehicle->CompressorStart = start_t::manual; - vehicle->CompressorAllow = true; // switch in the cabinet on before the engine start - vehicle->Mains = true; + vehicle->air.compressor.config.start = start_t::manual; + vehicle->air.compressor.Allow(true); // switch in the cabinet on before the engine start + vehicle->lineBreaker.Close(); run_compressor(vehicle, 29.9); - CHECK_FALSE(vehicle->CompressorFlag); + CHECK_FALSE(vehicle->air.compressor.IsRunning()); run_compressor(vehicle, 0.2); - CHECK(vehicle->CompressorFlag); + CHECK(vehicle->air.compressor.IsRunning()); } TEST_CASE("compressor: the start delay is read from the brake section") { auto const delay{[](std::string const &Section) { - return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->CompressorStartDelay; + return vehicle{definition::load("wagon").set(Section, "CompressorStartDelay", 30)}->air.compressor.config.startDelay; }}; CHECK(delay("Brake") == doctest::Approx(30.0)); CHECK(delay("Cntrl") == doctest::Approx(0.0)); // the key isn't taken from the control section @@ -174,32 +174,32 @@ definition generator_vehicle(double const ConverterDelay, double const Compresso TEST_CASE("compressor: fed from the converter it waits for the converter start delay") { vehicle loco{generator_vehicle(30.0, 0.0)}; - REQUIRE(loco->CompressorPower == 2); - REQUIRE(loco->ConverterStartDelay == doctest::Approx(30.0)); + REQUIRE(loco->air.compressor.config.supply == physics::CompressorSupply::converter); + REQUIRE(loco->converter.config.startDelay == doctest::Approx(30.0)); loco.run(1.0); // engine off - CHECK_FALSE(loco->Power110vIsAvailable); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); - loco->Mains = true; // engine started + loco->lineBreaker.Close(); // engine started loco.run(25.0); - CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); + CHECK_FALSE(loco->air.compressor.IsRunning()); loco.run(10.0); - CHECK(loco->Power110vIsAvailable); - CHECK(loco->CompressorFlag); + CHECK(loco->lowVoltage.Is110vAvailable()); + CHECK(loco->air.compressor.IsRunning()); } TEST_CASE("compressor: fed from the converter the start delay counts from the converter voltage") { vehicle loco{generator_vehicle(20.0, 10.0)}; - REQUIRE(loco->CompressorStartDelay == doctest::Approx(10.0)); + REQUIRE(loco->air.compressor.config.startDelay == doctest::Approx(10.0)); loco.run(1.0); // engine off - loco->Mains = true; // engine started + loco->lineBreaker.Close(); // engine started loco.run(25.0); - REQUIRE(loco->Power110vIsAvailable); // the converter is up - CHECK_FALSE(loco->CompressorFlag); // but the compressor waits for its own delay as well + REQUIRE(loco->lowVoltage.Is110vAvailable()); // the converter is up + CHECK_FALSE(loco->air.compressor.IsRunning()); // but the compressor waits for its own delay as well loco.run(10.0); - CHECK(loco->CompressorFlag); + CHECK(loco->air.compressor.IsRunning()); } diff --git a/tests/unit/test_consist.cpp b/tests/unit/test_consist.cpp index 8305be171..3dba41b68 100644 --- a/tests/unit/test_consist.cpp +++ b/tests/unit/test_consist.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "golden.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" using test::consist; using test::definition; @@ -67,8 +67,8 @@ TEST_CASE("consist: every real electric unit driven whole from its front cab") { // the drive cycle marks the events in the trace it gets; the first car's carries them test::drive_cycle(test::driving(train), test::track{0.15, 0.0, test::catenary_3kv}, *traces.front()); // every unit runs off and is braked to a stop, but the EN57, which doesn't get ready (COVERAGE.md) - auto const &leading{train[0].mover()}; - CHECK((leading.DistCounter > 0.2 /* km */) != (std::string{unit.name} == "en57")); + auto const &leading{train[0].physics()}; + CHECK((leading.DistCounter() > 0.2 /* km */) != (std::string{unit.name} == "en57")); CHECK(leading.Vel < 0.5); for (auto const &trace : traces) { trace->check(); diff --git a/tests/unit/test_consist_braking.cpp b/tests/unit/test_consist_braking.cpp new file mode 100644 index 000000000..78859f9db --- /dev/null +++ b/tests/unit/test_consist_braking.cpp @@ -0,0 +1,108 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" + +#include "physics/consistbraking.h" +#include "physics/brakes.h" + +#include + +// the blending of the brakes of a consist driven by induction motors (physics::ConsistBrakeBlending, the MED of the +// .fiz), which the game runs from the vehicle with the driver (TDynamicObject::distributeInductionBraking()) + +using test::definition; + +namespace { + +// a three-car Elf ready to run, standing with its brakes released, driven from the front cab of the head car +struct elf { + elf() { + for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) { + unit.add(definition::fiz(car), unit.size() == 0 ? 1 : 0); + } + ready = test::start_up(test::driving(unit), line); + for (int i = 0; i < 3 && cab().DirActive <= 0; ++i) { + cab().DirectionForward(); + } + test::release_brakes(cab()); + for (std::size_t index = 0; index < unit.size(); ++index) { + cars.emplace_back(&unit[index].physics()); + } + } + physics::Vehicle &cab() { return unit[0].physics(); } + // the steps of the game: the physics of the cars, then the blending from the head car + double step(double Seconds, double Dt = 0.01) { + auto amax{0.0}; + for (auto time{0.0}; time < Seconds; time += Dt) { + unit.step(line, Dt); + amax = blending.Update(cab(), cars, {}, Dt); + } + return amax; + } + test::consist unit; + test::track line{0.0, 0.0, test::catenary_3kv}; + std::vector cars; + physics::ConsistBrakeBlending blending; + bool ready{false}; +}; + +// the figures of the debug screen, by their labels +constexpr std::size_t mass{0}; // [t] +constexpr std::size_t deceleration{1}; // the most of the service braking [m/s2] +constexpr std::size_t demand{2}; // [kN] + +} // namespace + +TEST_CASE("consist braking: the full braking position demands the most deceleration of the consist, over all its mass") { + elf unit; + REQUIRE(unit.ready); + unit.cab().SetMainCtrlPos(0); // the full braking position of the Elf's controller + auto const amax{unit.step(2.0)}; + CHECK(amax > 0.0); + CHECK(amax <= unit.cab().brakes.blending.maxDeceleration); + auto const &figures{unit.blending.Figures()}; + CHECK(figures[deceleration] == doctest::Approx(amax)); + auto mass_t{0.0}; + for (auto const *car : unit.cars) { + mass_t += car->TotalMass() * 0.001; + } + CHECK(figures[mass] == doctest::Approx(mass_t)); + // the holding brake standing still asks for no more than the service braking does + CHECK(figures[demand] == doctest::Approx(amax * mass_t)); +} + +TEST_CASE("consist braking: standing at full braking, every car brakes with its electropneumatic brake") { + elf unit; + REQUIRE(unit.ready); + unit.cab().SetMainCtrlPos(0); + unit.step(2.0); + for (auto const *car : unit.cars) { + CAPTURE(car->Name); + CHECK(car->brakes.IndependentPositionEim() > 0.0); + CHECK(car->brakes.IndependentPositionEim() <= 1.0); + // the shunting mode (the holding brake) of the head car goes to all of them + CHECK(car->ShuntMode == unit.cab().ShuntMode); + } +} + +TEST_CASE("consist braking: with the controller at neutral and the train released, moving, nothing is demanded") { + elf unit; + REQUIRE(unit.ready); + while (unit.cab().MainCtrlPos() < unit.cab().MainCtrlNoPowerPos() && unit.cab().IncMainCtrl(1)) { + // up to neutral + } + // the controller's demand comes back from full braking to nothing gradually + unit.step(10.0); + REQUIRE(unit.cab().eimic == doctest::Approx(0.0)); + for (auto *car : unit.cars) { + car->SetV(10.0); // [m/s], above the speed the holding brake comes in at + car->Vel = 36.0; + } + unit.blending.Update(unit.cab(), unit.cars, {}, 0.01); + CHECK(unit.blending.Figures()[demand] == doctest::Approx(0.0)); + for (auto const *car : unit.cars) { + CAPTURE(car->Name); + CHECK(car->brakes.IndependentPositionEim() == doctest::Approx(0.0)); + } +} diff --git a/tests/unit/test_controls.cpp b/tests/unit/test_controls.cpp index 4e5255ff4..4f754d0fc 100644 --- a/tests/unit/test_controls.cpp +++ b/tests/unit/test_controls.cpp @@ -3,7 +3,8 @@ #include "scenario.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the controls a driver and a crew use besides driving and braking: doors, direction and @@ -32,9 +33,9 @@ void notch_down(scenario &Scenario) { void brake_to_stop(scenario &Scenario, double Seconds = 60.0) { Scenario.act("brake to stop"); - Scenario.cab().BrakeLevelSet(Scenario.cab().Handle->GetPos(bh_FB)); + Scenario.cab().BrakeLevelSet(Scenario.cab().brakes.driverValve->GetPos(bh_FB)); Scenario.wait(Seconds); - Scenario.cab().BrakeLevelSet(Scenario.cab().Handle->GetPos(bh_RP)); + Scenario.cab().BrakeLevelSet(Scenario.cab().brakes.driverValve->GetPos(bh_RP)); Scenario.wait(20.0); } @@ -42,7 +43,7 @@ void brake_to_stop(scenario &Scenario, double Seconds = 60.0) { void recharge(scenario &Scenario) { auto &cab{Scenario.cab()}; Scenario.act("releaser held, the pipe charged"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_RP)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_RP)); cab.BrakeReleaser(1); Scenario.wait(30.0); cab.BrakeReleaser(0); @@ -61,23 +62,23 @@ bool stopped(scenario &Scenario) { // the brake cylinders of every vehicle of the train under the pressure given bool released(scenario &Scenario, double Pressure = 0.1) { for (std::size_t i = 0; i < Scenario.train().size(); ++i) { - if (Scenario.vehicle(i).BrakePress > Pressure) { + if (Scenario.vehicle(i).brakes.cylinderPressure > Pressure) { return false; } } return true; } -bool open(TMoverParameters const &Vehicle, int Side) { +bool open(physics::Vehicle const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].is_open; } // the leaf shut, whatever the step does (closed, is_closed, wants the step folded too) -bool shut(TMoverParameters const &Vehicle, int Side) { +bool shut(physics::Vehicle const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].position <= 0.f; } -bool closed(TMoverParameters const &Vehicle, int Side) { +bool closed(physics::Vehicle const &Vehicle, VehicleSide Side) { return Vehicle.Doors.instances[Side].is_closed; } @@ -99,30 +100,30 @@ TEST_CASE("controls: the doors of an electric unit, opened, locked, permitted an auto &cab{scenario.cab()}; auto const &last{scenario.vehicle(scenario.train().size() - 1)}; scenario.act("permit left"); - cab.PermitDoors(side::left, true); + cab.PermitDoors(VehicleSide::left, true); scenario.wait(2.0); scenario.act("open left"); - cab.OperateDoors(side::left, true); + cab.OperateDoors(VehicleSide::left, true); scenario.wait(10.0); - CHECK(open(cab, side::left)); - CHECK(open(last, side::left)); - CHECK(closed(cab, side::right)); + CHECK(open(cab, VehicleSide::left)); + CHECK(open(last, VehicleSide::left)); + CHECK(closed(cab, VehicleSide::right)); scenario.act("close left"); - cab.OperateDoors(side::left, false); + cab.OperateDoors(VehicleSide::left, false); scenario.wait(10.0); - CHECK(shut(cab, side::left)); - CHECK(shut(last, side::left)); + CHECK(shut(cab, VehicleSide::left)); + CHECK(shut(last, VehicleSide::left)); scenario.act("open right without permit"); - cab.OperateDoors(side::right, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(5.0); // the EN57 needs no permit - CHECK(shut(cab, side::right) == cab.Doors.permit_needed); + CHECK(shut(cab, VehicleSide::right) == cab.Doors.permit_needed); scenario.act("permit right, open"); - cab.PermitDoors(side::right, true); - cab.OperateDoors(side::right, true); + cab.PermitDoors(VehicleSide::right, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(10.0); - CHECK(open(cab, side::right)); - CHECK(open(last, side::right)); + CHECK(open(cab, VehicleSide::right)); + CHECK(open(last, VehicleSide::right)); scenario.act("lock"); cab.LockDoors(true); scenario.wait(5.0); @@ -135,29 +136,29 @@ TEST_CASE("controls: the doors of an electric unit, opened, locked, permitted an cab.PermitDoorStep(true); cab.ChangeDoorControlMode(false); scenario.act("close all, unlock"); - cab.OperateDoors(side::right, false); - cab.OperateDoors(side::left, false); + cab.OperateDoors(VehicleSide::right, false); + cab.OperateDoors(VehicleSide::left, false); cab.LockDoors(false); scenario.wait(10.0); - CHECK(shut(cab, side::left)); - CHECK(shut(cab, side::right)); + CHECK(shut(cab, VehicleSide::left)); + CHECK(shut(cab, VehicleSide::right)); scenario.act("open both and drive off"); - cab.PermitDoors(side::left, true); - cab.PermitDoors(side::right, true); - cab.OperateDoors(side::left, true); - cab.OperateDoors(side::right, true); + cab.PermitDoors(VehicleSide::left, true); + cab.PermitDoors(VehicleSide::right, true); + cab.OperateDoors(VehicleSide::left, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(5.0); - CHECK_FALSE(shut(cab, side::left)); - CHECK_FALSE(shut(cab, side::right)); + CHECK_FALSE(shut(cab, VehicleSide::left)); + CHECK_FALSE(shut(cab, VehicleSide::right)); scenario.get_going(); notch_up(scenario, 4, 2.0); scenario.wait(20.0); // the doors of a train ready to run close as the driver starts off. no CHECK of the speed: the Elf and // the Impuls keep their steps out under the permit, which keeps them from moving (COVERAGE.md) - CHECK(shut(cab, side::left) == ready); - CHECK(shut(cab, side::right) == ready); - CHECK(shut(last, side::left) == ready); - CHECK(shut(last, side::right) == ready); + CHECK(shut(cab, VehicleSide::left) == ready); + CHECK(shut(cab, VehicleSide::right) == ready); + CHECK(shut(last, VehicleSide::left) == ready); + CHECK(shut(last, VehicleSide::right) == ready); notch_down(scenario); brake_to_stop(scenario); scenario.check(); @@ -176,28 +177,28 @@ TEST_CASE("controls: the doors of wagons, worked from the locomotive") { for (auto const range : {range_t::consist, range_t::unit, range_t::local}) { CAPTURE(static_cast(range)); scenario.act(std::format("open right {}", static_cast(range))); - cab.PermitDoors(side::right, true, range); - cab.OperateDoors(side::right, true, range); + cab.PermitDoors(VehicleSide::right, true, range); + cab.OperateDoors(VehicleSide::right, true, range); scenario.wait(10.0); - CHECK(open(coach, side::right) == (range != range_t::local)); - CHECK(shut(coach, side::left)); - CHECK(shut(freight, side::right)); + CHECK(open(coach, VehicleSide::right) == (range != range_t::local)); + CHECK(shut(coach, VehicleSide::left)); + CHECK(shut(freight, VehicleSide::right)); scenario.act("close right"); - cab.OperateDoors(side::right, false, range); + cab.OperateDoors(VehicleSide::right, false, range); scenario.wait(10.0); - CHECK(shut(coach, side::right)); + CHECK(shut(coach, VehicleSide::right)); } scenario.act("wagon opens its own"); - coach.OperateDoors(side::left, true, range_t::local); + coach.OperateDoors(VehicleSide::left, true, range_t::local); // a second at a time, the same run as one wait. the coach's doors close by themselves 5 s after they // opened (DoorStayOpen) scenario.wait(1.0); - CHECK_FALSE(shut(coach, side::left)); + CHECK_FALSE(shut(coach, VehicleSide::left)); scenario.wait(9.0); - CHECK(shut(coach, side::left)); - coach.OperateDoors(side::left, false, range_t::local); + CHECK(shut(coach, VehicleSide::left)); + coach.OperateDoors(VehicleSide::left, false, range_t::local); scenario.wait(10.0); - CHECK(shut(coach, side::left)); + CHECK(shut(coach, VehicleSide::left)); scenario.check(); } @@ -210,7 +211,7 @@ TEST_CASE("controls: reversing and changing the cab of a locomotive") { // the speed along the vehicle, its front ahead notch_up(scenario, 10, 1.5); scenario.wait(10.0); - CHECK(cab.V > 3.0); + CHECK(cab.V() > 3.0); notch_down(scenario); brake_to_stop(scenario); CHECK(stopped(scenario)); @@ -221,7 +222,7 @@ TEST_CASE("controls: reversing and changing the cab of a locomotive") { CHECK(cab.DirActive < 0); notch_up(scenario, 10, 1.5); scenario.wait(10.0); - CHECK(cab.V < -3.0); + CHECK(cab.V() < -3.0); notch_down(scenario); brake_to_stop(scenario); CHECK(stopped(scenario)); @@ -240,7 +241,7 @@ TEST_CASE("controls: reversing and changing the cab of a locomotive") { notch_up(scenario, 10, 1.5); scenario.wait(10.0); // forward from the rear cab is the vehicle's backward - CHECK(cab.V < -3.0); + CHECK(cab.V() < -3.0); notch_down(scenario); brake_to_stop(scenario); CHECK(stopped(scenario)); @@ -258,10 +259,10 @@ TEST_CASE("controls: wheel slip on a slippery track, sand and the anti-slip brak // a notch a second: the controller put to full power at once never gets the line contactors closed scenario.act("full power"); scenario.full_power(0.0); - auto slipped{cab.SlippingWheels}; + auto slipped{cab.SlippingWheels()}; for (int i = 0; i < 10; ++i) { scenario.wait(1.0); - slipped = slipped || cab.SlippingWheels; + slipped = slipped || cab.SlippingWheels(); } // the electric locomotives slip at full power, the SM42, of less power for its weight, doesn't CHECK(slipped == (std::string{path} != "sm42_v1/6d1")); @@ -300,16 +301,16 @@ TEST_CASE("controls: emergency stops by the alarm chain and the radio-stop") { scenario.wait(40.0); // the pipe emptied, the whole train braked to a stop CHECK(stopped(scenario)); - CHECK(cab.PipePress < 0.5); - CHECK(scenario.vehicle(2).BrakePress > 1.0); + CHECK(cab.brakePipe.Pressure() < 0.5); + CHECK(scenario.vehicle(2).brakes.cylinderPressure > 1.0); scenario.act("alarm chain reset"); scenario.vehicle(1).AlarmChainSwitch(false); scenario.wait(10.0); // the FV4a handle stays cut off the emptied pipe of an LSt locomotive (lock_old in UpdatePipePressure) // until the releaser is held - CHECK(cab.PipePress < 0.5); + CHECK(cab.brakePipe.Pressure() < 0.5); recharge(scenario); - CHECK(cab.PipePress > 4.5); + CHECK(cab.brakePipe.Pressure() > 4.5); scenario.get_going(); notch_up(scenario, 20, 1.0); scenario.wait(20.0); @@ -319,12 +320,12 @@ TEST_CASE("controls: emergency stops by the alarm chain and the radio-stop") { cab.RadiostopSwitch(true); scenario.wait(40.0); CHECK(stopped(scenario)); - CHECK(cab.PipePress < 0.5); + CHECK(cab.brakePipe.Pressure() < 0.5); scenario.act("radio-stop reset"); cab.RadiostopSwitch(false); scenario.wait(10.0); recharge(scenario); - CHECK(cab.PipePress > 4.5); + CHECK(cab.brakePipe.Pressure() > 4.5); scenario.check(); } @@ -336,29 +337,29 @@ TEST_CASE("controls: releasers and the universal brake buttons") { auto &cab{scenario.cab()}; auto &wagon{scenario.vehicle(2)}; scenario.act("service brake"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); scenario.wait(20.0); - CHECK(cab.BrakePress > 1.0); - CHECK(wagon.BrakePress > 1.0); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_NP)); + CHECK(cab.brakes.cylinderPressure > 1.0); + CHECK(wagon.brakes.cylinderPressure > 1.0); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_NP)); auto &coach{scenario.vehicle(1)}; // the releaser of the cab is passed along the whole train, a wagon's works on the wagon alone - auto const coachbraked{coach.BrakePress}; - auto wagonbraked{wagon.BrakePress}; + auto const coachbraked{coach.brakes.cylinderPressure}; + auto wagonbraked{wagon.brakes.cylinderPressure}; scenario.act("releaser of the locomotive"); cab.BrakeReleaser(1); scenario.wait(10.0); cab.BrakeReleaser(0); - CHECK(cab.BrakePress < 0.5); - CHECK(coach.BrakePress < coachbraked - 1.0); - CHECK(wagon.BrakePress < wagonbraked - 0.5); - CHECK(cab.PipePress < 4.0); // the pipe stays where the service application left it - wagonbraked = wagon.BrakePress; + CHECK(cab.brakes.cylinderPressure < 0.5); + CHECK(coach.brakes.cylinderPressure < coachbraked - 1.0); + CHECK(wagon.brakes.cylinderPressure < wagonbraked - 0.5); + CHECK(cab.brakePipe.Pressure() < 4.0); // the pipe stays where the service application left it + wagonbraked = wagon.brakes.cylinderPressure; scenario.act("releaser of the wagon"); wagon.BrakeReleaser(1); scenario.wait(10.0); wagon.BrakeReleaser(0); - CHECK(wagon.BrakePress < wagonbraked - 0.5); + CHECK(wagon.brakes.cylinderPressure < wagonbraked - 0.5); for (int button = 0; button < 3; ++button) { scenario.act(std::format("universal button {}", button)); cab.UniversalBrakeButton(button, 1); @@ -367,9 +368,9 @@ TEST_CASE("controls: releasers and the universal brake buttons") { scenario.wait(5.0); } scenario.act("running"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_RP)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_RP)); scenario.wait(60.0); - CHECK(cab.PipePress > 4.8); + CHECK(cab.brakePipe.Pressure() > 4.8); CHECK(released(scenario)); scenario.check(); } @@ -394,7 +395,7 @@ TEST_CASE("controls: the ep brake of electric units") { for (std::size_t i = 0; i < positions.size(); ++i) { CAPTURE(positions[i]); scenario.act(std::format("handle {}", positions[i])); - cab.BrakeLevelSet(cab.Handle->GetPos(positions[i])); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(positions[i])); scenario.wait(15.0); if (i == 2) { CHECK(released(scenario)); @@ -402,9 +403,9 @@ TEST_CASE("controls: the ep brake of electric units") { if (i == 3) { // the ep brake works the cylinders of every car by wire, the pipe stays charged (by the first // application the EW58's pipe is still charging after the start-up) - CHECK(cab.PipePress > 4.8); - CHECK(cab.BrakePress > 1.0); - CHECK(last.BrakePress > 1.0); + CHECK(cab.brakePipe.Pressure() > 4.8); + CHECK(cab.brakes.cylinderPressure > 1.0); + CHECK(last.brakes.cylinderPressure > 1.0); } } // the EW58 releases at the running position, the ED72 holds the ep application there, and with the ep @@ -436,7 +437,7 @@ TEST_CASE("controls: the electrodynamic brake of locomotives having one") { cab.DynamicBrakeSwitch(true); scenario.wait(5.0); scenario.act("brake"); - cab.BrakeLevelSet(cab.Handle->GetPos(bh_FB)); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); scenario.wait(40.0); CHECK(cab.Vel < speed); scenario.act("dynamic brake off"); @@ -455,13 +456,13 @@ TEST_CASE("controls: train heating from the locomotive") { scenario.act("heating on"); cab.HeatingSwitch(true); scenario.wait(30.0); - CHECK(cab.Heating); - CHECK(scenario.vehicle(2).Heating); + CHECK(cab.trainHeating.IsOn()); + CHECK(scenario.vehicle(2).trainHeating.IsOn()); scenario.act("heating off"); cab.HeatingSwitch(false); scenario.wait(10.0); - CHECK_FALSE(cab.Heating); - CHECK_FALSE(scenario.vehicle(2).Heating); + CHECK_FALSE(cab.trainHeating.IsOn()); + CHECK_FALSE(scenario.vehicle(2).trainHeating.IsOn()); scenario.check(); } @@ -476,11 +477,11 @@ TEST_CASE("controls: a freight wagon loaded and braked") { CHECK(wagon.AssignLoad(load, 30.f) == (known || std::string{load}.empty())); wagon.ComputeMass(); if (*load == '\0') { - emptymass = wagon.TotalMass; + emptymass = wagon.TotalMass(); } else { // 30 t of a load the wagon takes, none of one it doesn't - CHECK(wagon.TotalMass == doctest::Approx(emptymass + (known ? 30000.0 : 0.0)).epsilon(0.01)); + CHECK(wagon.TotalMass() == doctest::Approx(emptymass + (known ? 30000.0 : 0.0)).epsilon(0.01)); } scenario.start_up(); scenario.get_going(); @@ -495,18 +496,26 @@ TEST_CASE("controls: a freight wagon loaded and braked") { } TEST_CASE("controls: a locomotive running into a standing wagon") { + // the legacy collisions of physics.collisions old: derailed, the wagon is a wall (test_collisions.cpp has the new) + struct legacy { + global_settings::collision_model previous{Global.collisions}; + legacy() { Global.collisions = global_settings::collision_model::old; } + ~legacy() { Global.collisions = previous; } + legacy(legacy const &) = delete; + legacy &operator=(legacy const &) = delete; + } const model; for (auto const speed : {5.0, 15.0, 40.0}) { CAPTURE(speed); scenario scenario{std::format("controls/collision/{} kmh", static_cast(speed)), motion()}; // the wagon stands in front, the locomotive comes from behind it - scenario.add("bdhpumn_v3/bdhpumn").add("4e_v1/4e", 0, coupling::faux, speed, 30.0); + scenario.add("bdhpumn_v3/bdhpumn").add("4e_v1/4e", 0, Coupling::none, speed, 30.0); auto const &wagon{scenario.vehicle(0)}; scenario.wait(30.0); // slow, the locomotive pushes the wagon off, the buffers only touching, and both roll to a stop; fast, // the wagon derails where it stands auto const derailed{speed > 30.0}; - CHECK(TestFlag(wagon.DamageFlag, dtrain_out) == derailed); - CHECK((std::abs(wagon.DistCounter) > 0.0001) != derailed); + CHECK(wagon.DamageFlag.HasAll(VehicleDamage::derailed) == derailed); + CHECK((std::abs(wagon.DistCounter()) > 0.0001) != derailed); CHECK(stopped(scenario)); scenario.check(); } @@ -543,22 +552,22 @@ TEST_CASE("controls: the automatic electrodynamic brake of the EP09, in service scenario.add("bdhpumn_v3/bdhpumn", 0, test::consist::full_coupling, 120.0); REQUIRE(scenario.start_up()); auto &ep09{scenario.cab()}; - REQUIRE(ep09.Power110vIsAvailable); + REQUIRE(ep09.lowVoltage.Is110vAvailable()); scenario.act(std::string{"brake "} + name); - ep09.BrakeLevelSet(ep09.Handle->GetPos(bh_MB) + steps); + ep09.BrakeLevelSet(ep09.brakes.driverValve->GetPos(bh_MB) + steps); scenario.wait(10.0); - CHECK(ep09.DynamicBrakeFlag); + CHECK(ep09.brakes.electrodynamic.on); CHECK(ep09.Im < -100.0); - CHECK(ep09.BrakePress < 0.25 * ep09.Hamulec->GetEDBCP()); + CHECK(ep09.brakes.cylinderPressure < 0.25 * ep09.brakes.distributor->GetEDBCP()); scenario.wait(110.0); // stopped, held by the air alone. the flag of the electrodynamic brake stays on while the cylinders hold // less than 2.1 bar, though the motors give nothing; a stronger application drops it before the stop CHECK(ep09.Vel == doctest::Approx(0.0)); CHECK(ep09.Im == doctest::Approx(0.0)); - CHECK(ep09.DynamicBrakeFlag == (ep09.BrakePress <= 2.1)); - CHECK(ep09.BrakePress == doctest::Approx(ep09.Hamulec->GetEDBCP()).epsilon(0.05)); + CHECK(ep09.brakes.electrodynamic.on == (ep09.brakes.cylinderPressure <= 2.1)); + CHECK(ep09.brakes.cylinderPressure == doctest::Approx(ep09.brakes.distributor->GetEDBCP()).epsilon(0.05)); scenario.act("release"); - ep09.BrakeLevelSet(ep09.Handle->GetPos(bh_RP)); + ep09.BrakeLevelSet(ep09.brakes.driverValve->GetPos(bh_RP)); scenario.wait(30.0); scenario.check(); } @@ -591,17 +600,17 @@ TEST_CASE("controls: the automatic electrodynamic brake under ep and service bra cab.BrakeLevelSet(Position); scenario.wait(Seconds); }}; - brake("ep brake", cab.Handle->GetPos(bh_EPB), 15.0); - CHECK(cab.DynamicBrakeFlag == epelectric); + brake("ep brake", cab.brakes.driverValve->GetPos(bh_EPB), 15.0); + CHECK(cab.brakes.electrodynamic.on == epelectric); CHECK((cab.Im < -100.0) == epelectric); - brake("ep hold", cab.Handle->GetPos(bh_EPN), 5.0); - brake("first step", cab.Handle->GetPos(bh_MB), 20.0); - brake("deeper", cab.Handle->GetPos(bh_MB) + 1.0, 15.0); + brake("ep hold", cab.brakes.driverValve->GetPos(bh_EPN), 5.0); + brake("first step", cab.brakes.driverValve->GetPos(bh_MB), 20.0); + brake("deeper", cab.brakes.driverValve->GetPos(bh_MB) + 1.0, 15.0); // the pipe alone doesn't bring the EW58's motors in CHECK((cab.Im < -50.0) != epelectric); - brake("release", cab.Handle->GetPos(bh_RP), 20.0); - brake("full service", cab.Handle->GetPos(bh_FB), 40.0); - brake("release", cab.Handle->GetPos(bh_RP), 20.0); + brake("release", cab.brakes.driverValve->GetPos(bh_RP), 20.0); + brake("full service", cab.brakes.driverValve->GetPos(bh_FB), 40.0); + brake("release", cab.brakes.driverValve->GetPos(bh_RP), 20.0); scenario.check(); } } diff --git a/tests/unit/test_coupler_physics.cpp b/tests/unit/test_coupler_physics.cpp index 6785a2cb3..520a985b4 100644 --- a/tests/unit/test_coupler_physics.cpp +++ b/tests/unit/test_coupler_physics.cpp @@ -2,13 +2,14 @@ #include "doctest.h" #include "vehicle.h" #include "consist.h" -#include "McZapkie/couplerphysics.h" +#include "physics/couplerphysics.h" #include "utilities/Globals.h" #include #include +#include -// the physical model of the couplings (McZapkie/couplerphysics.h, couplerphysics in eu07.ini): progressive buffers and +// the physical model of the couplings (physics/couplerphysics.h, couplerphysics in eu07.ini): progressive buffers and // draw gear with friction hysteresis, pressed in series, the play of the coupling, its yield and its breaking using test::definition; @@ -268,9 +269,9 @@ TEST_CASE("coupler physics: a jerk on the solid draw gear breaks the coupling by namespace { // couples the facing ends of the two vehicles, as the scenery does -void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, int Coupling = coupling::coupler) { - REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), Coupling, true, false)); - REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), Coupling, true, false)); +void join(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, CouplingSet const couplings = Coupling::coupler) { + REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.physics(), couplings, true, false)); + REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.physics(), couplings, true, false)); } // the wagon of data/wagon.json with the given play of its screw couplings @@ -279,16 +280,16 @@ vehicle loose_wagon(double Slack, double Velocity, std::string const &Name) { } bool coupler_damaged(vehicle &Vehicle) { - return TestFlag(Vehicle->DamageFlag, dtrain_coupling); + return Vehicle->DamageFlag.HasAll(VehicleDamage::coupling); } } // namespace TEST_CASE("coupler physics: the play of the coupling and the parameters of the model come from the vehicle definition") { auto loose{loose_wagon(0.05, 0.0, "loose")}; - auto const &physics{loose->Couplers[end::front].physics}; + auto const &physics{loose->Couplers[VehicleEnd::front].physics}; CHECK(physics.slack == doctest::Approx(0.05)); - CHECK(loose->Couplers[end::rear].physics.slack == doctest::Approx(0.05)); + CHECK(loose->Couplers[VehicleEnd::rear].physics.slack == doctest::Approx(0.05)); CHECK(physics.buffers.stiffness == doctest::Approx(9200e3)); CHECK(physics.buffers.travel == doctest::Approx(0.11)); CHECK(physics.draw_gear.end_force() == doctest::Approx(450e3)); @@ -300,11 +301,11 @@ TEST_CASE("coupler physics: the play of the coupling and the parameters of the m CHECK(physics.link.breakable); auto tight{vehicle{definition::load("wagon"), 0.0, "tight"}}; - CHECK(tight->Couplers[end::front].physics.slack == 0.0); + CHECK(tight->Couplers[VehicleEnd::front].physics.slack == 0.0); auto automatic{vehicle{definition::load("wagon").set("BuffCoupl", "CType", "Automatic"), 0.0, "automatic"}}; - CHECK(automatic->Couplers[end::front].physics.slack == doctest::Approx(0.005)); + CHECK(automatic->Couplers[VehicleEnd::front].physics.slack == doctest::Approx(0.005)); auto articulated{vehicle{definition::load("wagon").set("BuffCoupl", "CType", "Articulated"), 0.0, "articulated"}}; - CHECK_FALSE(articulated->Couplers[end::front].physics.link.breakable); + CHECK_FALSE(articulated->Couplers[VehicleEnd::front].physics.link.breakable); } TEST_CASE("coupler physics: a coupling with play pulls only once the play is taken up") { @@ -313,15 +314,15 @@ TEST_CASE("coupler physics: a coupling with play pulls only once the play is tak flag_setting const crashdamage{Global.crash_damage, true}; auto front{loose_wagon(0.05, 3.0, "front")}; auto rear{loose_wagon(0.05, 0.1, "rear")}; - join(rear, end::front, front, end::rear); - test::pair pair{rear, end::front, front, end::rear, 0.0}; + join(rear, VehicleEnd::front, front, VehicleEnd::rear); + test::pair pair{rear, VehicleEnd::front, front, VehicleEnd::rear, 0.0}; front.hold_brake_pipe(5.0); rear.hold_brake_pipe(5.0); auto pulledwithinplay{false}; for (int i = 0; i < 300 && pair.gap() < 0.09; ++i) { pair.step(); - pulledwithinplay = pulledwithinplay || rear->Couplers[end::front].CForce != 0.0; + pulledwithinplay = pulledwithinplay || rear->Couplers[VehicleEnd::front].CForce != 0.0; } REQUIRE(pair.gap() >= 0.09); CHECK_FALSE(pulledwithinplay); @@ -336,6 +337,63 @@ TEST_CASE("coupler physics: a coupling with play pulls only once the play is tak CHECK(front.speed() < 2.5); } +TEST_CASE("coupler physics: off the track, ends gone past each other pull the coupling taut, it holds or breaks") { + // eu07_td_off_track_buckle: the locomotive lay at rest beside the track, the coach coupled to it ran on past it along + // the rails. the gap between their ends grew with the run of the coach, but the model took the run along the track, + // as closing the gap: the draw gear unloaded, the coupling carried 0 N while the gap grew to 30 m, and it never broke + flag_setting const physics{Global.coupler_physics, true}; + flag_setting const everywhere{Global.coupler_physics_all, true}; + auto running{loose_wagon(0.05, 30.0, "running")}; + auto lying{loose_wagon(0.05, 0.0, "lying")}; + join(running, VehicleEnd::front, lying, VehicleEnd::rear); + test::pair pair{running, VehicleEnd::front, lying, VehicleEnd::rear, 0.0}; + running.hold_brake_pipe(5.0); + lying.hold_brake_pipe(5.0); + // as TDynamicObject::update_neighbours() measures the ends where they are: gone past each other, the run of the + // running wagon forwards opens the gap, the other one running after it closes it. from where the pair stands at + // the first step, the ends at one place + std::optional start; + auto const gap = [&]() { return (running->Loc().X - lying->Loc().X) - start.value_or(running->Loc().X - lying->Loc().X); }; + pair.neighbours_found = [&]() { + if (false == start.has_value()) { + start = running->Loc().X - lying->Loc().X; + } + auto const gap{(running->Loc().X - lying->Loc().X) - *start}; + auto &fromrunning{running->Neighbours[VehicleEnd::front]}; + fromrunning.distance = static_cast(gap); + fromrunning.off_track = true; + fromrunning.own_share = 1.0; + fromrunning.other_share = -1.0; + auto &fromlying{lying->Neighbours[VehicleEnd::rear]}; + fromlying.distance = static_cast(gap); + fromlying.off_track = true; + fromlying.own_share = -1.0; + fromlying.other_share = 1.0; + }; + + SUBCASE("with crash damage, the jerk breaks it") { + flag_setting const crashdamage{Global.crash_damage, true}; + pair.run(1.0); + CHECK_FALSE(pair.coupled()); + CHECK((coupler_damaged(running) || coupler_damaged(lying))); + } + SUBCASE("without it, the coupling holds: the wagon running past is held back, the gap stays within the draw gear") { + flag_setting const crashdamage{Global.crash_damage, false}; + auto pulled{false}; + auto widest{0.0}; + for (int i = 0; i < 300; ++i) { + pair.step(); + pulled = pulled || running->Couplers[VehicleEnd::front].CForce != 0.0; + widest = std::max(widest, gap()); + } + CHECK(pulled); + CHECK(pair.coupled()); + // it ran 25 m on past the other one, the coupling carrying nothing + CHECK(widest < 0.5); + CHECK(running.speed() == doctest::Approx(lying.speed()).epsilon(0.2)); + } +} + TEST_CASE("coupler physics: buffers hit at a walking pace give back less than they took") { flag_setting const physics{Global.coupler_physics, true}; flag_setting const everywhere{Global.coupler_physics_all, true}; @@ -343,7 +401,7 @@ TEST_CASE("coupler physics: buffers hit at a walking pace give back less than th auto moving{vehicle{definition::load("wagon"), 5.0, "moving"}}; // barely moving, so that its brakes are released auto standing{vehicle{definition::load("wagon"), 0.1, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 0.3}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.3}; moving.hold_brake_pipe(5.0); standing.hold_brake_pipe(5.0); @@ -352,7 +410,7 @@ TEST_CASE("coupler physics: buffers hit at a walking pace give back less than th for (int i = 0; i < 500; ++i) { pair.step(); touched = touched || pair.gap() < 0.0; - solid = solid || moving->Couplers[end::front].physics_state.stop != 0; + solid = solid || moving->Couplers[VehicleEnd::front].physics_state.stop != 0; if (touched && pair.gap() > 0.3) { break; // parted } @@ -377,8 +435,8 @@ TEST_CASE("coupler physics: coupled vehicles at rest stay at rest") { flag_setting const everywhere{Global.coupler_physics_all, true}; auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; - join(first, end::rear, second, end::front); - test::pair pair{first, end::rear, second, end::front, 0.0}; + join(first, VehicleEnd::rear, second, VehicleEnd::front); + test::pair pair{first, VehicleEnd::rear, second, VehicleEnd::front, 0.0}; pair.run(5.0); CHECK(std::abs(first.speed()) < 0.01); @@ -391,8 +449,8 @@ TEST_CASE("coupler physics: a jerk on a coupling with play breaks it, the brake flag_setting const everywhere{Global.coupler_physics_all, true}; auto front{loose_wagon(0.05, 20.0, "front")}; auto rear{loose_wagon(0.05, 0.1, "rear")}; - join(rear, end::front, front, end::rear, coupling::coupler | coupling::brakehose); - test::pair pair{rear, end::front, front, end::rear, 0.0}; + join(rear, VehicleEnd::front, front, VehicleEnd::rear, Coupling::coupler | Coupling::brakeHose); + test::pair pair{rear, VehicleEnd::front, front, VehicleEnd::rear, 0.0}; front.hold_brake_pipe(5.0); rear.hold_brake_pipe(5.0); @@ -402,8 +460,8 @@ TEST_CASE("coupler physics: a jerk on a coupling with play breaks it, the brake CHECK_FALSE(pair.coupled()); CHECK((coupler_damaged(rear) || coupler_damaged(front))); // both parts of the train brake, their pipe vented through the torn hoses - CHECK(rear->AlarmChainFlag); - CHECK(front->AlarmChainFlag); + CHECK(rear->brakes.alarmChain); + CHECK(front->brakes.alarmChain); // the front wagon runs away from the rear one CHECK(front.speed() > rear.speed() + 5.0); CHECK(pair.gap() > 0.3); @@ -424,31 +482,31 @@ TEST_CASE("coupler physics: a gentle pull on a coupling with play doesn't hurt i flag_setting const crashdamage{Global.crash_damage, true}; auto front{loose_wagon(0.05, 3.0, "front")}; auto rear{loose_wagon(0.05, 0.1, "rear")}; - join(rear, end::front, front, end::rear); - test::pair pair{rear, end::front, front, end::rear, 0.0}; + join(rear, VehicleEnd::front, front, VehicleEnd::rear); + test::pair pair{rear, VehicleEnd::front, front, VehicleEnd::rear, 0.0}; front.hold_brake_pipe(5.0); rear.hold_brake_pipe(5.0); pair.run(3.0); CHECK(pair.coupled()); CHECK_FALSE(coupler_damaged(rear)); - CHECK(rear->Couplers[end::front].physics_state.elongation == 0.0); + CHECK(rear->Couplers[VehicleEnd::front].physics_state.elongation == 0.0); } TEST_CASE("coupler physics: automatic couplers still catch a wagon rolling into a standing one") { flag_setting const physics{Global.coupler_physics, true}; flag_setting const everywhere{Global.coupler_physics_all, true}; flag_setting const crashdamage{Global.crash_damage, true}; - auto automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", coupling::coupler | coupling::brakehose)}; + auto automatic{definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Coupling::coupler | Coupling::brakeHose)}; auto moving{vehicle{automatic, 5.0, "moving"}}; auto standing{vehicle{automatic, 0.0, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; pair.run(3.0); REQUIRE(pair.coupled()); pair.run(2.0); CHECK(moving.speed() == doctest::Approx(standing.speed()).epsilon(0.1)); - CHECK_FALSE(TestFlag(moving->DamageFlag, dtrain_out)); + CHECK_FALSE(moving->DamageFlag.HasAll(VehicleDamage::derailed)); } TEST_CASE("couplers: a broken coupling of vehicles facing each other uncouples the ends coupled") { @@ -456,51 +514,51 @@ TEST_CASE("couplers: a broken coupling of vehicles facing each other uncouples t auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; auto third{vehicle{definition::load("wagon"), 0.0, "third"}}; - join(first, end::front, second, end::front); - join(second, end::rear, third, end::front); + join(first, VehicleEnd::front, second, VehicleEnd::front); + join(second, VehicleEnd::rear, third, VehicleEnd::front); - first->damage_coupler(end::front); - CHECK(first->Couplers[end::front].CouplingFlag == coupling::faux); - CHECK(second->Couplers[end::front].CouplingFlag == coupling::faux); + first->damage_coupler(VehicleEnd::front); + CHECK(first->Couplers[VehicleEnd::front].CouplingFlag == Coupling::none); + CHECK(second->Couplers[VehicleEnd::front].CouplingFlag == Coupling::none); // the other coupling of the second vehicle stays - CHECK(second->Couplers[end::rear].CouplingFlag == coupling::coupler); + CHECK(second->Couplers[VehicleEnd::rear].CouplingFlag == Coupling::coupler); } TEST_CASE("couplers: a broken coupler is repaired alone, with the one of the vehicle it was coupled with") { auto first{vehicle{definition::load("wagon"), 0.0, "first"}}; auto second{vehicle{definition::load("wagon"), 0.0, "second"}}; auto third{vehicle{definition::load("wagon"), 0.0, "third"}}; - join(first, end::rear, second, end::front, coupling::coupler | coupling::brakehose); - join(second, end::rear, third, end::front, coupling::coupler | coupling::brakehose); + join(first, VehicleEnd::rear, second, VehicleEnd::front, Coupling::coupler | Coupling::brakeHose); + join(second, VehicleEnd::rear, third, VehicleEnd::front, Coupling::coupler | Coupling::brakeHose); // both couplings of the second wagon break - second->damage_coupler(end::front); - second->damage_coupler(end::rear); - REQUIRE(second->Couplers[end::front].broken); - REQUIRE(first->Couplers[end::rear].broken); - REQUIRE(third->Couplers[end::front].broken); - REQUIRE(TestFlag(second->DamageFlag, dtrain_coupling)); + second->damage_coupler(VehicleEnd::front); + second->damage_coupler(VehicleEnd::rear); + REQUIRE(second->Couplers[VehicleEnd::front].broken); + REQUIRE(first->Couplers[VehicleEnd::rear].broken); + REQUIRE(third->Couplers[VehicleEnd::front].broken); + REQUIRE(second->DamageFlag.HasAll(VehicleDamage::coupling)); // nothing to repair at the far end of the first wagon - CHECK_FALSE(first->repair_coupler(end::front)); + CHECK_FALSE(first->repair_coupler(VehicleEnd::front)); // repaired from the first wagon: the coupling between the first two, the other one stays broken - CHECK(first->repair_coupler(end::rear)); - CHECK_FALSE(first->Couplers[end::rear].broken); - CHECK_FALSE(second->Couplers[end::front].broken); - CHECK(second->Couplers[end::rear].broken); - CHECK(third->Couplers[end::front].broken); + CHECK(first->repair_coupler(VehicleEnd::rear)); + CHECK_FALSE(first->Couplers[VehicleEnd::rear].broken); + CHECK_FALSE(second->Couplers[VehicleEnd::front].broken); + CHECK(second->Couplers[VehicleEnd::rear].broken); + CHECK(third->Couplers[VehicleEnd::front].broken); // the second wagon keeps its damage, and its emergency braking, while a coupler of it is broken - CHECK(TestFlag(second->DamageFlag, dtrain_coupling)); - CHECK(second->AlarmChainFlag); + CHECK(second->DamageFlag.HasAll(VehicleDamage::coupling)); + CHECK(second->brakes.alarmChain); - CHECK(third->repair_coupler(end::front)); - CHECK_FALSE(second->Couplers[end::rear].broken); - CHECK_FALSE(TestFlag(second->DamageFlag, dtrain_coupling)); - CHECK_FALSE(second->AlarmChainFlag); + CHECK(third->repair_coupler(VehicleEnd::front)); + CHECK_FALSE(second->Couplers[VehicleEnd::rear].broken); + CHECK_FALSE(second->DamageFlag.HasAll(VehicleDamage::coupling)); + CHECK_FALSE(second->brakes.alarmChain); // repaired, not coupled: the vehicles are coupled again as usual - CHECK(second->Couplers[end::rear].CouplingFlag == coupling::faux); - CHECK(second->Attach(end::rear, end::front, &third.mover(), coupling::coupler, true, false)); + CHECK(second->Couplers[VehicleEnd::rear].CouplingFlag == Coupling::none); + CHECK(second->Attach(VehicleEnd::rear, VehicleEnd::front, &third.physics(), Coupling::coupler, true, false)); } TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehicle covered take the physical model") { @@ -508,28 +566,28 @@ TEST_CASE("coupler physics: with couplerphysics yes, only the pairs with a vehic flag_setting const everywhere{Global.coupler_physics_all, false}; auto moving{vehicle{definition::load("wagon"), 5.0, "moving"}}; auto standing{vehicle{definition::load("wagon"), 0.1, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 0.1}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.1}; SUBCASE("neither covered: the legacy model") { pair.run(1.0); - CHECK_FALSE(moving->coupler_physics_at(end::front)); - CHECK_FALSE(standing->coupler_physics_at(end::rear)); + CHECK_FALSE(moving->coupler_physics_at(VehicleEnd::front)); + CHECK_FALSE(standing->coupler_physics_at(VehicleEnd::rear)); // the state of the physical model untouched - CHECK(moving->Couplers[end::front].physics_state.gap == 0.0); + CHECK(moving->Couplers[VehicleEnd::front].physics_state.gap == 0.0); } SUBCASE("one covered: both compute the pair physically") { // as the player's train closing in on the other one - moving->CouplerPhysics = true; + moving->SetCouplerPhysics(true); pair.run(1.0); - CHECK(moving->coupler_physics_at(end::front)); - CHECK(standing->coupler_physics_at(end::rear)); - CHECK(moving->Couplers[end::front].physics_state.gap != 0.0); - CHECK(standing->Couplers[end::rear].physics_state.gap == moving->Couplers[end::front].physics_state.gap); + CHECK(moving->coupler_physics_at(VehicleEnd::front)); + CHECK(standing->coupler_physics_at(VehicleEnd::rear)); + CHECK(moving->Couplers[VehicleEnd::front].physics_state.gap != 0.0); + CHECK(standing->Couplers[VehicleEnd::rear].physics_state.gap == moving->Couplers[VehicleEnd::front].physics_state.gap); } SUBCASE("the setting off: the legacy model, covered or not") { flag_setting const off{Global.coupler_physics, false}; - moving->CouplerPhysics = true; - CHECK_FALSE(moving->coupler_physics_at(end::front)); + moving->SetCouplerPhysics(true); + CHECK_FALSE(moving->coupler_physics_at(VehicleEnd::front)); } } @@ -543,7 +601,7 @@ TEST_CASE("coupler physics: a hit on a braked train runs through it as a wave, w train.add(definition::load("wagon")); } // a wagon rolling at 15 km/h into the rear of the standing train, its brakes applied - train.add(definition::load("wagon"), 0, coupling::faux, 15.0, 0.3); + train.add(definition::load("wagon"), 0, Coupling::none, 15.0, 0.3); std::vector peak(wagons, 0.0); std::vector started(wagons, -1.0); @@ -560,7 +618,7 @@ TEST_CASE("coupler physics: a hit on a braked train runs through it as a wave, w CAPTURE(i); CAPTURE(peak[i]); REQUIRE(started[i] >= 0.0); - CHECK_FALSE(TestFlag(train[i]->DamageFlag, dtrain_out)); + CHECK_FALSE(train[i]->DamageFlag.HasAll(VehicleDamage::derailed)); } // the wagon hit first takes less than the hit, the one at the far end the least CHECK(peak[wagons - 1] < 12.0); diff --git a/tests/unit/test_couplers.cpp b/tests/unit/test_couplers.cpp index bbb1c0dd9..5cacb2c4b 100644 --- a/tests/unit/test_couplers.cpp +++ b/tests/unit/test_couplers.cpp @@ -9,7 +9,7 @@ using test::vehicle; namespace { // the wagon from data/wagon.json with automatic couplers at both ends, which couple the given connections -definition automatic_definition(int Flag = coupling::coupler | coupling::brakehose) { +definition automatic_definition(CouplingSet const Flag = Coupling::coupler | Coupling::brakeHose) { return definition::load("wagon").set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", Flag); } @@ -24,7 +24,7 @@ vehicle heavy_automatic_wagon(double Velocity, std::string const &Name) { } bool derailed(vehicle &Vehicle) { - return TestFlag(Vehicle->DamageFlag, dtrain_out); + return Vehicle->DamageFlag.HasAll(VehicleDamage::derailed); } // runs the pair for Seconds, returns whether the vehicles were coupled at any point @@ -49,6 +49,19 @@ private: bool m_previous{Global.crash_damage}; }; +// the legacy collisions of physics.collisions old for the test, restored after it: the rule of the safe closing speed +// weighed by the ratio of the masses (the crush of the ends of the new model is in test_collisions.cpp) +class legacy_collisions { +public: + legacy_collisions() { Global.collisions = global_settings::collision_model::old; } + ~legacy_collisions() { Global.collisions = m_previous; } + legacy_collisions(legacy_collisions const &) = delete; + legacy_collisions &operator=(legacy_collisions const &) = delete; + +private: + global_settings::collision_model m_previous{Global.collisions}; +}; + } // namespace // issue #86: automatic couplers used to catch at any closing speed, so the vehicles never collided nor derailed @@ -57,13 +70,13 @@ TEST_CASE("couplers: automatic couplers catch a standing wagon hit at a walking crash_damage_setting const crashdamage{true}; auto moving{automatic_wagon(10.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - REQUIRE(moving->Couplers[end::front].type() == TCouplerType::Automatic); + REQUIRE(moving->Couplers[VehicleEnd::front].type() == TCouplerType::Automatic); REQUIRE(moving.speed() == doctest::Approx(10.0)); // the front of the moving wagon runs into the rear of the standing one - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(10.0)); - CHECK(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); - CHECK(standing->AutomaticCouplingSafe(end::rear, moving.mover(), end::front)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(10.0)); + CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); + CHECK(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.physics(), VehicleEnd::front)); } TEST_CASE("couplers: automatic couplers don't catch a wagon hit too fast, the wagons collide instead") { @@ -72,9 +85,9 @@ TEST_CASE("couplers: automatic couplers don't catch a wagon hit too fast, the wa auto standing{automatic_wagon(0.0, "standing")}; REQUIRE(moving.speed() == doctest::Approx(30.0)); - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) > TMoverParameters::SafeCollisionVelocity); - CHECK_FALSE(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); - CHECK_FALSE(standing->AutomaticCouplingSafe(end::rear, moving.mover(), end::front)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) > physics::Vehicle::SafeCollisionVelocity); + CHECK_FALSE(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); + CHECK_FALSE(standing->AutomaticCouplingSafe(VehicleEnd::rear, moving.physics(), VehicleEnd::front)); } TEST_CASE("couplers: automatic couplers catch a wagon running ahead only a little slower") { @@ -82,9 +95,9 @@ TEST_CASE("couplers: automatic couplers catch a wagon running ahead only a littl auto faster{automatic_wagon(60.0, "faster")}; auto slower{automatic_wagon(50.0, "slower")}; - CHECK(faster->CollisionVelocity(end::front, slower.mover(), end::rear) == doctest::Approx(10.0)); - CHECK(slower->CollisionVelocity(end::rear, faster.mover(), end::front) == doctest::Approx(10.0)); - CHECK(faster->AutomaticCouplingSafe(end::front, slower.mover(), end::rear)); + CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.physics(), VehicleEnd::rear) == doctest::Approx(10.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.physics(), VehicleEnd::front) == doctest::Approx(10.0)); + CHECK(faster->AutomaticCouplingSafe(VehicleEnd::front, slower.physics(), VehicleEnd::rear)); } TEST_CASE("couplers: without crash damage automatic couplers catch at any speed") { @@ -92,7 +105,7 @@ TEST_CASE("couplers: without crash damage automatic couplers catch at any speed" auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - CHECK(moving->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK(moving->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); } // the closing speed used to treat the speed of each vehicle as a vector turned by half its heading, so for vehicles @@ -103,16 +116,16 @@ TEST_CASE("couplers: the closing speed of a rear-end collision is the difference auto slower{automatic_wagon(25.0, "slower")}; // running forwards, the front of the faster wagon hits the rear of the slower one - CHECK(faster->CollisionVelocity(end::front, slower.mover(), end::rear) == doctest::Approx(15.0)); - CHECK(slower->CollisionVelocity(end::rear, faster.mover(), end::front) == doctest::Approx(15.0)); + CHECK(faster->CollisionVelocity(VehicleEnd::front, slower.physics(), VehicleEnd::rear) == doctest::Approx(15.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::rear, faster.physics(), VehicleEnd::front) == doctest::Approx(15.0)); // the wagons running ahead of each other are parting - CHECK(slower->CollisionVelocity(end::front, faster.mover(), end::rear) == doctest::Approx(-15.0)); + CHECK(slower->CollisionVelocity(VehicleEnd::front, faster.physics(), VehicleEnd::rear) == doctest::Approx(-15.0)); // backing up, the rear of the faster wagon hits the front of the slower one auto backingfaster{automatic_wagon(-40.0, "backing faster")}; auto backingslower{automatic_wagon(-25.0, "backing slower")}; - CHECK(backingfaster->CollisionVelocity(end::rear, backingslower.mover(), end::front) == doctest::Approx(15.0)); - CHECK(backingslower->CollisionVelocity(end::front, backingfaster.mover(), end::rear) == doctest::Approx(15.0)); + CHECK(backingfaster->CollisionVelocity(VehicleEnd::rear, backingslower.physics(), VehicleEnd::front) == doctest::Approx(15.0)); + CHECK(backingslower->CollisionVelocity(VehicleEnd::front, backingfaster.physics(), VehicleEnd::rear) == doctest::Approx(15.0)); } TEST_CASE("couplers: the closing speed of a head-on collision is the sum of the speeds") { @@ -121,27 +134,27 @@ TEST_CASE("couplers: the closing speed of a head-on collision is the sum of the auto second{automatic_wagon(10.0, "second")}; // both wagons run forwards, their fronts meet - CHECK(first->CollisionVelocity(end::front, second.mover(), end::front) == doctest::Approx(20.0)); - CHECK(second->CollisionVelocity(end::front, first.mover(), end::front) == doctest::Approx(20.0)); + CHECK(first->CollisionVelocity(VehicleEnd::front, second.physics(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(second->CollisionVelocity(VehicleEnd::front, first.physics(), VehicleEnd::front) == doctest::Approx(20.0)); // 20 km/h is above the limit, the couplers don't catch (the old formula gave 14.1 km/h and coupled them) - CHECK(first->CollisionVelocity(end::front, second.mover(), end::front) > TMoverParameters::SafeCollisionVelocity); - CHECK_FALSE(first->AutomaticCouplingSafe(end::front, second.mover(), end::front)); - CHECK_FALSE(second->AutomaticCouplingSafe(end::front, first.mover(), end::front)); + CHECK(first->CollisionVelocity(VehicleEnd::front, second.physics(), VehicleEnd::front) > physics::Vehicle::SafeCollisionVelocity); + CHECK_FALSE(first->AutomaticCouplingSafe(VehicleEnd::front, second.physics(), VehicleEnd::front)); + CHECK_FALSE(second->AutomaticCouplingSafe(VehicleEnd::front, first.physics(), VehicleEnd::front)); // both wagons back up, their rears meet auto firstbacking{automatic_wagon(-10.0, "first backing")}; auto secondbacking{automatic_wagon(-10.0, "second backing")}; - CHECK(firstbacking->CollisionVelocity(end::rear, secondbacking.mover(), end::rear) == doctest::Approx(20.0)); + CHECK(firstbacking->CollisionVelocity(VehicleEnd::rear, secondbacking.physics(), VehicleEnd::rear) == doctest::Approx(20.0)); // running back to back, the wagons part - CHECK(first->CollisionVelocity(end::rear, second.mover(), end::rear) == doctest::Approx(-20.0)); - CHECK(first->AutomaticCouplingSafe(end::rear, second.mover(), end::rear)); + CHECK(first->CollisionVelocity(VehicleEnd::rear, second.physics(), VehicleEnd::rear) == doctest::Approx(-20.0)); + CHECK(first->AutomaticCouplingSafe(VehicleEnd::rear, second.physics(), VehicleEnd::rear)); // slow enough, the couplers catch auto slowfirst{automatic_wagon(5.0, "slow first")}; auto slowsecond{automatic_wagon(5.0, "slow second")}; - CHECK(slowfirst->CollisionVelocity(end::front, slowsecond.mover(), end::front) == doctest::Approx(10.0)); - CHECK(slowfirst->AutomaticCouplingSafe(end::front, slowsecond.mover(), end::front)); + CHECK(slowfirst->CollisionVelocity(VehicleEnd::front, slowsecond.physics(), VehicleEnd::front) == doctest::Approx(10.0)); + CHECK(slowfirst->AutomaticCouplingSafe(VehicleEnd::front, slowsecond.physics(), VehicleEnd::front)); } TEST_CASE("couplers: the closing speed of a hit on a standing vehicle is the speed of the moving one, whichever way it faces") { @@ -149,17 +162,17 @@ TEST_CASE("couplers: the closing speed of a hit on a standing vehicle is the spe auto standing{automatic_wagon(0.0, "standing")}; // the standing wagon faces away from the moving one - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(20.0)); - CHECK(standing->CollisionVelocity(end::rear, moving.mover(), end::front) == doctest::Approx(20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(20.0)); + CHECK(standing->CollisionVelocity(VehicleEnd::rear, moving.physics(), VehicleEnd::front) == doctest::Approx(20.0)); // the standing wagon faces the moving one - CHECK(moving->CollisionVelocity(end::front, standing.mover(), end::front) == doctest::Approx(20.0)); - CHECK(standing->CollisionVelocity(end::front, moving.mover(), end::front) == doctest::Approx(20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(standing->CollisionVelocity(VehicleEnd::front, moving.physics(), VehicleEnd::front) == doctest::Approx(20.0)); // the moving wagon backs up into the standing one auto backing{automatic_wagon(-20.0, "backing")}; - CHECK(backing->CollisionVelocity(end::rear, standing.mover(), end::front) == doctest::Approx(20.0)); - CHECK(backing->CollisionVelocity(end::rear, standing.mover(), end::rear) == doctest::Approx(20.0)); + CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.physics(), VehicleEnd::front) == doctest::Approx(20.0)); + CHECK(backing->CollisionVelocity(VehicleEnd::rear, standing.physics(), VehicleEnd::rear) == doctest::Approx(20.0)); // the moving wagon runs away from the standing one - CHECK(moving->CollisionVelocity(end::rear, standing.mover(), end::front) == doctest::Approx(-20.0)); + CHECK(moving->CollisionVelocity(VehicleEnd::rear, standing.physics(), VehicleEnd::front) == doctest::Approx(-20.0)); } // the coupling as the simulation runs it: two vehicles on a track, closing in on each other until the couplers (or @@ -170,28 +183,28 @@ TEST_CASE("couplers: automatic couplers catch right up to the safe closing speed auto standing{automatic_wagon(0.0, "standing")}; auto below{automatic_wagon(14.9, "below")}; - CHECK(below->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(14.9)); - CHECK(below->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK(below->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(14.9)); + CHECK(below->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); auto above{automatic_wagon(15.1, "above")}; - CHECK(above->CollisionVelocity(end::front, standing.mover(), end::rear) == doctest::Approx(15.1)); - CHECK_FALSE(above->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK(above->CollisionVelocity(VehicleEnd::front, standing.physics(), VehicleEnd::rear) == doctest::Approx(15.1)); + CHECK_FALSE(above->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); auto faster{automatic_wagon(15.5, "faster")}; - CHECK_FALSE(faster->AutomaticCouplingSafe(end::front, standing.mover(), end::rear)); + CHECK_FALSE(faster->AutomaticCouplingSafe(VehicleEnd::front, standing.physics(), VehicleEnd::rear)); } TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it") { crash_damage_setting const crashdamage{true}; auto moving{automatic_wagon(5.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; pair.run(3.0); REQUIRE(pair.coupled()); - CHECK(moving->Couplers[end::front].CouplingFlag == (coupling::coupler | coupling::brakehose)); - CHECK(standing->Couplers[end::rear].CouplingFlag == (coupling::coupler | coupling::brakehose)); - CHECK(moving->Couplers[end::front].Connected == &standing.mover()); + CHECK(moving->Couplers[VehicleEnd::front].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); + CHECK(standing->Couplers[VehicleEnd::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); + CHECK(moving->Couplers[VehicleEnd::front].Connected == &standing.physics()); CHECK_FALSE(derailed(moving)); CHECK_FALSE(derailed(standing)); // coupled, they run on together @@ -202,9 +215,10 @@ TEST_CASE("couplers: a wagon rolling slowly into a standing one couples with it" TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor once the hit has slowed it down") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; auto touched{false}; auto parted{false}; @@ -213,12 +227,12 @@ TEST_CASE("couplers: a wagon hitting a standing one too fast doesn't couple, nor for (int i = 0; i < 1000; ++i) { pair.step(); // as far as the couplers know: the distance between them at the start of the step - auto const distance{moving->Neighbours[end::front].distance}; + auto const distance{moving->Neighbours[VehicleEnd::front].distance}; touched = touched || distance < 0.0; parted = parted || (touched && distance > 0.05); coupled = coupled || pair.coupled(); if (touched && false == parted) { - locked = locked && false == moving->Couplers[end::front].AutomaticCouplingAllowed && false == standing->Couplers[end::rear].AutomaticCouplingAllowed; + locked = locked && false == moving->Couplers[VehicleEnd::front].AutomaticCouplingAllowed && false == standing->Couplers[VehicleEnd::rear].AutomaticCouplingAllowed; } } @@ -239,17 +253,17 @@ TEST_CASE("couplers: the automatic coupling locked by a hit is unlocked once the auto moving{automatic_wagon(3.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; // as a hit too fast or manual uncoupling leaves them - moving->Couplers[end::front].AutomaticCouplingAllowed = false; - standing->Couplers[end::rear].AutomaticCouplingAllowed = false; + moving->Couplers[VehicleEnd::front].AutomaticCouplingAllowed = false; + standing->Couplers[VehicleEnd::rear].AutomaticCouplingAllowed = false; SUBCASE("parted by more than 5 cm, they couple on the next approach") { - test::pair pair{moving, end::front, standing, end::rear, 0.5}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.5}; pair.step(); - CHECK(moving->Couplers[end::front].AutomaticCouplingAllowed); + CHECK(moving->Couplers[VehicleEnd::front].AutomaticCouplingAllowed); CHECK(couple_during(pair, 3.0)); } SUBCASE("kept together, they don't") { - test::pair pair{moving, end::front, standing, end::rear, 0.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 0.0}; auto coupled{false}; for (int i = 0; i < 300; ++i) { pair.step(); @@ -268,9 +282,10 @@ TEST_CASE("couplers: the automatic coupling locked by a hit is unlocked once the TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicles apart, uncoupled and on the rails") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; auto moving{automatic_wagon(20.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); CHECK_FALSE(derailed(moving)); @@ -281,11 +296,12 @@ TEST_CASE("couplers: a hit a little too fast for the couplers bounces the vehicl TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over the limit adjusted for their mass ratio") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("equal masses: both derail") { auto moving{automatic_wagon(30.0, "moving")}; auto standing{automatic_wagon(0.0, "standing")}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(moving)); CHECK(derailed(standing)); @@ -293,7 +309,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t SUBCASE("half the mass: between the safe closing speed and twice that, only the lighter one derails") { auto light{automatic_wagon(27.0, "light")}; auto heavy{heavy_automatic_wagon(0.0, "heavy")}; - test::pair pair{light, end::front, heavy, end::rear, 1.0}; + test::pair pair{light, VehicleEnd::front, heavy, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(light)); CHECK_FALSE(derailed(heavy)); @@ -301,7 +317,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t SUBCASE("half the mass: above twice the safe closing speed both derail") { auto light{automatic_wagon(45.0, "light")}; auto heavy{heavy_automatic_wagon(0.0, "heavy")}; - test::pair pair{light, end::front, heavy, end::rear, 1.0}; + test::pair pair{light, VehicleEnd::front, heavy, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(light)); CHECK(derailed(heavy)); @@ -309,7 +325,7 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t SUBCASE("half the mass: below the safe closing speed the couplers catch, nothing derails") { auto light{automatic_wagon(12.0, "light")}; auto heavy{heavy_automatic_wagon(0.0, "heavy")}; - test::pair pair{light, end::front, heavy, end::rear, 1.0}; + test::pair pair{light, VehicleEnd::front, heavy, VehicleEnd::rear, 1.0}; CHECK(couple_during(pair, 5.0)); CHECK_FALSE(derailed(light)); CHECK_FALSE(derailed(heavy)); @@ -318,11 +334,12 @@ TEST_CASE("couplers: a hit too fast for the couplers derails the vehicles over t TEST_CASE("couplers: wagons running head-on into each other couple only up to the safe closing speed") { crash_damage_setting const crashdamage{true}; + legacy_collisions const legacy; SUBCASE("7 + 7 km/h, the couplers catch") { auto first{automatic_wagon(7.0, "first")}; auto second{automatic_wagon(7.0, "second")}; - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; CHECK(couple_during(pair, 3.0)); CHECK_FALSE(derailed(first)); CHECK_FALSE(derailed(second)); @@ -330,7 +347,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th SUBCASE("8 + 8 km/h, the wagons bounce apart") { auto first{automatic_wagon(8.0, "first")}; auto second{automatic_wagon(8.0, "second")}; - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); CHECK_FALSE(derailed(first)); CHECK_FALSE(derailed(second)); @@ -341,7 +358,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th SUBCASE("backing up, 8 + 8 km/h, the wagons bounce apart") { auto first{automatic_wagon(-8.0, "first")}; auto second{automatic_wagon(-8.0, "second")}; - test::pair pair{first, end::rear, second, end::rear, 1.0}; + test::pair pair{first, VehicleEnd::rear, second, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); CHECK(first.speed() > 0.0); CHECK(second.speed() > 0.0); @@ -349,7 +366,7 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th SUBCASE("15 + 15 km/h, both derail") { auto first{automatic_wagon(15.0, "first")}; auto second{automatic_wagon(15.0, "second")}; - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; CHECK_FALSE(couple_during(pair, 5.0)); CHECK(derailed(first)); CHECK(derailed(second)); @@ -363,10 +380,10 @@ TEST_CASE("couplers: wagons running head-on into each other couple only up to th TEST_CASE("couplers: a wagon hit head-on runs off the same as one hit from behind") { // without automatic couplers or crash damage, the collision alone crash_damage_setting const crashdamage{false}; - auto speeds_after_hit = [](int StruckEnd) { + auto speeds_after_hit = [](VehicleEnd StruckEnd) { auto moving{vehicle{definition::load("wagon"), 20.0, "moving"}}; auto struck{vehicle{definition::load("wagon"), 0.0, "struck"}}; - test::pair pair{moving, end::front, struck, StruckEnd, 0.5}; + test::pair pair{moving, VehicleEnd::front, struck, StruckEnd, 0.5}; auto touched{false}; for (int i = 0; i < 300; ++i) { pair.step(); @@ -381,8 +398,8 @@ TEST_CASE("couplers: a wagon hit head-on runs off the same as one hit from behin return std::make_pair(moving.speed(), struck.speed()); }; - auto const [hitterfrombehind, struckfrombehind]{speeds_after_hit(end::rear)}; - auto const [hitterheadon, struckheadon]{speeds_after_hit(end::front)}; + auto const [hitterfrombehind, struckfrombehind]{speeds_after_hit(VehicleEnd::rear)}; + auto const [hitterheadon, struckheadon]{speeds_after_hit(VehicleEnd::front)}; // hit from behind, the struck wagon runs off forwards, faster than the hitter CHECK(struckfrombehind > 10.0); @@ -398,30 +415,30 @@ TEST_CASE("couplers: an automatic coupler doesn't catch a coupler of another typ crash_damage_setting const crashdamage{true}; auto moving{automatic_wagon(5.0, "moving")}; auto standing{vehicle{definition::load("wagon"), 0.0, "standing"}}; - REQUIRE(standing->Couplers[end::rear].type() == TCouplerType::Screw); - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(standing->Couplers[VehicleEnd::rear].type() == TCouplerType::Screw); + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; CHECK_FALSE(couple_during(pair, 3.0)); } TEST_CASE("couplers: automatic couplers of different control systems couple without the control connection") { crash_damage_setting const crashdamage{true}; - auto const flag{coupling::coupler | coupling::brakehose | coupling::control}; + auto const flag{Coupling::coupler | Coupling::brakeHose | Coupling::control}; auto moving{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "first"), 5.0, "moving"}}; SUBCASE("the same control system") { auto standing{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "first"), 0.0, "standing"}}; - REQUIRE(standing->Couplers[end::rear].control_type == "first"); - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(standing->Couplers[VehicleEnd::rear].control_type == "first"); + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); CHECK(pair.coupling() == flag); } SUBCASE("a different one") { auto standing{vehicle{automatic_definition(flag).set("BuffCoupl", "ControlType", "second"), 0.0, "standing"}}; - REQUIRE(standing->Couplers[end::rear].control_type == "second"); - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + REQUIRE(standing->Couplers[VehicleEnd::rear].control_type == "second"); + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); - CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose)); + CHECK(pair.coupling() == (Coupling::coupler | Coupling::brakeHose)); } } @@ -434,26 +451,26 @@ TEST_CASE("couplers: the coupler force of vehicles facing each other lands on th auto second{automatic_wagon(0.0, "second")}; SUBCASE("facing each other") { - test::pair pair{first, end::front, second, end::front, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::front, 1.0}; pair.run(5.0); REQUIRE(pair.coupled()); pair.step(); - REQUIRE(second->Couplers[end::front].CForce != 0.0); - CHECK(first->Couplers[end::front].CForce == doctest::Approx(second->Couplers[end::front].CForce)); - CHECK(first->Couplers[end::rear].CForce == 0.0); // nothing there - CHECK(second->Couplers[end::rear].CForce == 0.0); + REQUIRE(second->Couplers[VehicleEnd::front].CForce != 0.0); + CHECK(first->Couplers[VehicleEnd::front].CForce == doctest::Approx(second->Couplers[VehicleEnd::front].CForce)); + CHECK(first->Couplers[VehicleEnd::rear].CForce == 0.0); // nothing there + CHECK(second->Couplers[VehicleEnd::rear].CForce == 0.0); } SUBCASE("facing the same way") { - test::pair pair{first, end::front, second, end::rear, 1.0}; + test::pair pair{first, VehicleEnd::front, second, VehicleEnd::rear, 1.0}; pair.run(5.0); REQUIRE(pair.coupled()); pair.step(); - REQUIRE(second->Couplers[end::rear].CForce != 0.0); - CHECK(first->Couplers[end::front].CForce == doctest::Approx(-second->Couplers[end::rear].CForce)); - CHECK(first->Couplers[end::rear].CForce == 0.0); - CHECK(second->Couplers[end::front].CForce == 0.0); + REQUIRE(second->Couplers[VehicleEnd::rear].CForce != 0.0); + CHECK(first->Couplers[VehicleEnd::front].CForce == doctest::Approx(-second->Couplers[VehicleEnd::rear].CForce)); + CHECK(first->Couplers[VehicleEnd::rear].CForce == 0.0); + CHECK(second->Couplers[VehicleEnd::front].CForce == 0.0); } } @@ -470,16 +487,16 @@ vehicle articulated_wagon(double Velocity, std::string const &Name) { } // couples the facing ends of the two vehicles for good, as the scenery does for an articulated set -void join(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd) { - REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.mover(), coupling::coupler, true, false)); - REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.mover(), coupling::coupler, true, false)); +void join(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd) { + REQUIRE(First->Attach(FirstEnd, SecondEnd, &Second.physics(), Coupling::coupler, true, false)); + REQUIRE(Second->Attach(SecondEnd, FirstEnd, &First.physics(), Coupling::coupler, true, false)); } } // namespace TEST_CASE("couplers: an articulated joint takes its full tensile force within its travel") { auto wagon{articulated_wagon(0.0, "wagon")}; - auto const &joint{wagon->Couplers[end::front]}; + auto const &joint{wagon->Couplers[VehicleEnd::front]}; REQUIRE(joint.type() == TCouplerType::Articulated); CHECK(joint.SpringKC * joint.DmaxC >= doctest::Approx(joint.FmaxC)); @@ -494,8 +511,8 @@ TEST_CASE("couplers: an articulated set keeps its momentum when one section jerk // and run on together at half the speed, as the momentum they have between them dictates auto front_section{articulated_wagon(20.0, "front")}; auto rear_section{articulated_wagon(0.1, "rear")}; - join(rear_section, end::front, front_section, end::rear); - test::pair pair{rear_section, end::front, front_section, end::rear, 0.0}; + join(rear_section, VehicleEnd::front, front_section, VehicleEnd::rear); + test::pair pair{rear_section, VehicleEnd::front, front_section, VehicleEnd::rear, 0.0}; REQUIRE(pair.coupled()); // brakes released, as a locomotive keeps them front_section.hold_brake_pipe(5.0); @@ -514,8 +531,8 @@ TEST_CASE("couplers: a collision of coupled vehicles keeps the momentum of the p // the same jerk through screw couplers, which collide when stretched beyond their travel as well auto front_wagon{vehicle{definition::load("wagon"), 30.0, "front"}}; auto rear_wagon{vehicle{definition::load("wagon"), 0.1, "rear"}}; - join(rear_wagon, end::front, front_wagon, end::rear); - test::pair pair{rear_wagon, end::front, front_wagon, end::rear, 0.0}; + join(rear_wagon, VehicleEnd::front, front_wagon, VehicleEnd::rear); + test::pair pair{rear_wagon, VehicleEnd::front, front_wagon, VehicleEnd::rear, 0.0}; REQUIRE(pair.coupled()); front_wagon.hold_brake_pipe(5.0); rear_wagon.hold_brake_pipe(5.0); @@ -543,14 +560,14 @@ private: bool m_previous{Global.control_coupling_engine_check}; }; -constexpr int scenario_coupling{coupling::coupler | coupling::brakehose | coupling::mainhose | coupling::control}; +constexpr CouplingSet scenario_coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; // couples the rear of the first vehicle to the front of the second one the way the scenery does (forced, from the // first one only), returns the coupling the pair got -int scenario_couple(vehicle &First, vehicle &Second, int Coupling = scenario_coupling) { - REQUIRE(First->Attach(end::rear, end::front, &Second.mover(), Coupling, true, false)); - CHECK(Second->Couplers[end::front].CouplingFlag == First->Couplers[end::rear].CouplingFlag); - return First->Couplers[end::rear].CouplingFlag; +CouplingSet scenario_couple(vehicle &First, vehicle &Second, CouplingSet const couplings = scenario_coupling) { + REQUIRE(First->Attach(VehicleEnd::rear, VehicleEnd::front, &Second.physics(), couplings, true, false)); + CHECK(Second->Couplers[VehicleEnd::front].CouplingFlag == First->Couplers[VehicleEnd::rear].CouplingFlag); + return First->Couplers[VehicleEnd::rear].CouplingFlag; } } // namespace @@ -564,14 +581,14 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr SUBCASE("a diesel-electric one with its own control system") { auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselElectric); - CHECK_FALSE(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front)); - CHECK(scenario_couple(electric, diesel) == (scenario_coupling & ~coupling::control)); + CHECK_FALSE(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.physics(), VehicleEnd::front)); + CHECK(scenario_couple(electric, diesel) == scenario_coupling.Without(Coupling::control)); } SUBCASE("a diesel-mechanical one without a control system named, either") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; REQUIRE(diesel->EngineType == TEngineType::DieselEngine); - CHECK_FALSE(diesel->ControlCouplingAllowed(end::front, electric.mover(), end::rear)); - CHECK(scenario_couple(diesel, electric) == (scenario_coupling & ~coupling::control)); + CHECK_FALSE(diesel->ControlCouplingAllowed(VehicleEnd::front, electric.physics(), VehicleEnd::rear)); + CHECK(scenario_couple(diesel, electric) == scenario_coupling.Without(Coupling::control)); } SUBCASE("unless both name the same control system") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03").set("BuffCoupl", "ControlType", "shared"), 0.0, "diesel"}}; @@ -580,13 +597,13 @@ TEST_CASE("couplers: an electric and a diesel locomotive don't share their contr } SUBCASE("unless the vehicles make one unit, coupled for good") { auto diesel{vehicle{definition::fiz("sm03_v1/sm03"), 0.0, "diesel"}}; - auto const forgood{scenario_coupling | coupling::permanent}; + auto const forgood{scenario_coupling | Coupling::permanent}; CHECK(scenario_couple(electric, diesel, forgood) == forgood); } SUBCASE("unless the check is turned off") { control_coupling_check_setting const off{false}; auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; - CHECK(electric->ControlCouplingAllowed(end::rear, diesel.mover(), end::front)); + CHECK(electric->ControlCouplingAllowed(VehicleEnd::rear, diesel.physics(), VehicleEnd::front)); CHECK(scenario_couple(electric, diesel) == scenario_coupling); } } @@ -621,7 +638,7 @@ TEST_CASE("couplers: locomotives of the same traction and the cars keep their co TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive couple without the control connection") { crash_damage_setting const crashdamage{true}; control_coupling_check_setting const check{true}; - auto const flag{coupling::coupler | coupling::brakehose | coupling::control}; + auto const flag{Coupling::coupler | Coupling::brakeHose | Coupling::control}; auto automatic = [flag](std::string const &Path) { return definition::fiz(Path).set("BuffCoupl", "CType", "Automatic").set("BuffCoupl", "AutomaticFlag", flag); }; @@ -629,13 +646,13 @@ TEST_CASE("couplers: automatic couplers of an electric and a diesel locomotive c SUBCASE("a diesel one") { auto standing{vehicle{automatic("sm03_v1/sm03"), 0.0, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); - CHECK(pair.coupling() == (coupling::coupler | coupling::brakehose)); + CHECK(pair.coupling() == (Coupling::coupler | Coupling::brakeHose)); } SUBCASE("an electric one") { auto standing{vehicle{automatic("ep09_v2/104e"), 0.0, "standing"}}; - test::pair pair{moving, end::front, standing, end::rear, 1.0}; + test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; REQUIRE(couple_during(pair, 3.0)); CHECK(pair.coupling() == flag); } @@ -647,8 +664,8 @@ TEST_CASE("couplers: the AI and the player get the coupling the vehicles can tak auto diesel{vehicle{definition::fiz("sm42_v1/6d1"), 0.0, "diesel"}}; auto other{vehicle{definition::fiz("ep09_v2/104e"), 0.0, "other"}}; - CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, scenario_coupling) == (scenario_coupling & ~coupling::control)); - CHECK(electric->CompatibleCoupling(end::rear, other.mover(), end::front, scenario_coupling) == scenario_coupling); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.physics(), VehicleEnd::front, scenario_coupling) == scenario_coupling.Without(Coupling::control)); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, other.physics(), VehicleEnd::front, scenario_coupling) == scenario_coupling); // nothing to take away without the control connection asked for - CHECK(electric->CompatibleCoupling(end::rear, diesel.mover(), end::front, coupling::coupler) == coupling::coupler); + CHECK(electric->CompatibleCoupling(VehicleEnd::rear, diesel.physics(), VehicleEnd::front, Coupling::coupler) == Coupling::coupler); } diff --git a/tests/unit/test_couplers_trains.cpp b/tests/unit/test_couplers_trains.cpp index 926964dbe..a98d9bd08 100644 --- a/tests/unit/test_couplers_trains.cpp +++ b/tests/unit/test_couplers_trains.cpp @@ -3,6 +3,7 @@ #include "consist.h" #include "scenario.h" +#include "utilities/Globals.h" #include "utilities/utilities.h" // characterisation of the couplers between vehicles: coupling and uncoupling by hand (Attach, DettachStatus, @@ -14,81 +15,97 @@ using test::definition; using test::scenario; using namespace test::channels; +namespace { + +// the given model of collisions for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::collision_model Model) : m_previous{Global.collisions} { Global.collisions = Model; } + ~model_setting() { Global.collisions = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::collision_model m_previous; +}; + +} // namespace + TEST_CASE("couplers: coupled by hand, touching or apart, of the same kind or not") { consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; // the wagon's buffers touch the locomotive's, the unit's car stands a metre away - auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux).mover()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none).physics()}; train.step(); // nothing to couple to, or nothing to couple - CHECK_FALSE(locomotive.Attach(end::rear, end::front, nullptr, coupling::coupler)); - CHECK_FALSE(locomotive.Attach(end::rear, end::front, &wagon, coupling::faux)); + CHECK_FALSE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, nullptr, Coupling::coupler)); + CHECK_FALSE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, Coupling::none)); // the hook first: the coupler alone, which sounds - locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, coupling::coupler)); - CHECK(locomotive.Couplers[end::rear].Connected == &wagon); - CHECK(wagon.Couplers[end::front].Connected == &locomotive); - CHECK(wagon.Couplers[end::front].CouplingFlag == coupling::coupler); - CHECK(locomotive.Couplers[end::rear].sounds == sound::attachcoupler); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + REQUIRE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, Coupling::coupler)); + CHECK(locomotive.Couplers[VehicleEnd::rear].Connected == &wagon); + CHECK(wagon.Couplers[VehicleEnd::front].Connected == &locomotive); + CHECK(wagon.Couplers[VehicleEnd::front].CouplingFlag == Coupling::coupler); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == sound::attachcoupler); // then the hoses: only what changes sounds - locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, coupling::coupler | coupling::brakehose | coupling::mainhose)); - CHECK(locomotive.Couplers[end::rear].sounds == (sound::attachbrakehose | sound::attachmainhose)); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + REQUIRE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, Coupling::coupler | Coupling::brakeHose | Coupling::mainHose)); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == (sound::attachbrakehose | sound::attachmainhose)); // and again, quietly, the other side naming the coupler by the one it's connected to (2) - locomotive.Couplers[end::rear].sounds = 0; - REQUIRE(wagon.Attach(end::front, 2, &locomotive, coupling::coupler | coupling::brakehose, false, false)); - CHECK(locomotive.Couplers[end::rear].CouplingFlag == (coupling::coupler | coupling::brakehose)); - CHECK(locomotive.Couplers[end::rear].sounds == 0); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + REQUIRE(wagon.Attach(NumberOf(VehicleEnd::front), 2, &locomotive, Coupling::coupler | Coupling::brakeHose, false, false)); + CHECK(locomotive.Couplers[VehicleEnd::rear].CouplingFlag == (Coupling::coupler | Coupling::brakeHose)); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == 0); // a screw coupler with the buffers pressed together comes apart whole train.step(); - CHECK(locomotive.DettachStatus(end::rear) < 0); - locomotive.Couplers[end::rear].sounds = 0; - CHECK(locomotive.Dettach(end::rear)); - CHECK(locomotive.Couplers[end::rear].Connected == nullptr); - CHECK(wagon.Couplers[end::front].Connected == nullptr); - CHECK(locomotive.Couplers[end::rear].sounds == (sound::detach | sound::attachcoupler | sound::attachbrakehose)); - CHECK(locomotive.DettachStatus(end::rear) == 0); - CHECK(locomotive.Dettach(end::rear)); + CHECK(locomotive.DettachStatus(VehicleEnd::rear) < 0); + locomotive.Couplers[VehicleEnd::rear].sounds = 0; + CHECK(locomotive.Dettach(VehicleEnd::rear)); + CHECK(locomotive.Couplers[VehicleEnd::rear].Connected == nullptr); + CHECK(wagon.Couplers[VehicleEnd::front].Connected == nullptr); + CHECK(locomotive.Couplers[VehicleEnd::rear].sounds == (sound::detach | sound::attachcoupler | sound::attachbrakehose)); + CHECK(locomotive.DettachStatus(VehicleEnd::rear) == 0); + CHECK(locomotive.Dettach(VehicleEnd::rear)); } TEST_CASE("couplers: a screw coupler uncoupled with the buffers apart, or with the hoses alone, or broken") { struct state { char const *name; double gap; // between the buffers, the coupler stretched - int coupling; + CouplingSet coupling; bool damaged; bool apart; // whether it comes apart whole }; for (auto const &[name, gap, couplingtype, damaged, apart] : { - state{"stretched a little", 0.1, coupling::coupler | coupling::brakehose, false, false}, - state{"stretched far", 0.3, coupling::coupler | coupling::brakehose, false, true}, - state{"hoses alone", 0.1, coupling::brakehose, false, true}, - state{"broken", 0.1, coupling::coupler | coupling::brakehose, true, true}, + state{"stretched a little", 0.1, Coupling::coupler | Coupling::brakeHose, false, false}, + state{"stretched far", 0.3, Coupling::coupler | Coupling::brakeHose, false, true}, + state{"hoses alone", 0.1, Coupling::brakeHose, false, true}, + state{"broken", 0.1, Coupling::coupler | Coupling::brakeHose, true, true}, }) { CAPTURE(name); consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, coupling::faux, 0.0, gap).mover()}; - REQUIRE(locomotive.Attach(end::rear, end::front, &wagon, couplingtype, true)); + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl"), 0, Coupling::none, 0.0, gap).physics()}; + REQUIRE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &wagon, couplingtype, true)); if (damaged) { - SetFlag(locomotive.DamageFlag, dtrain_coupling); + locomotive.DamageFlag.Set(VehicleDamage::coupling); } train.step(); - CHECK((locomotive.DettachStatus(end::rear) < 0) == apart); - CHECK(locomotive.Dettach(end::rear) == apart); + CHECK((locomotive.DettachStatus(VehicleEnd::rear) < 0) == apart); + CHECK(locomotive.Dettach(VehicleEnd::rear) == apart); // what's left when it doesn't come apart is the coupler, the hoses taken off - CHECK(locomotive.Couplers[end::rear].CouplingFlag == (apart ? coupling::faux : coupling::coupler)); - CHECK(wagon.Couplers[end::front].CouplingFlag == (apart ? coupling::faux : coupling::coupler)); + CHECK(locomotive.Couplers[VehicleEnd::rear].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); + CHECK(wagon.Couplers[VehicleEnd::front].CouplingFlag == (apart ? Coupling::none : Coupling::coupler)); } // couplers of different kinds don't couple, unless forced consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &unit{train.add(definition::fiz("en57_v1/5bgb"), 0, coupling::faux).mover()}; + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; + auto &unit{train.add(definition::fiz("en57_v1/5bgb"), 0, Coupling::none).physics()}; train.step(); - CHECK_FALSE(locomotive.Attach(end::rear, end::front, &unit, coupling::coupler)); - CHECK(locomotive.Attach(end::rear, end::front, &unit, coupling::coupler, true)); + CHECK_FALSE(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &unit, Coupling::coupler)); + CHECK(locomotive.Attach(VehicleEnd::rear, VehicleEnd::front, &unit, Coupling::coupler, true)); } TEST_CASE("couplers: automatic couplers coupling on contact") { @@ -98,56 +115,58 @@ TEST_CASE("couplers: automatic couplers coupling on contact") { char const *name; char const *standing; // its rear coupler met char const *running; // its front coupler meets - int coupling; // what they couple: what both flags allow, the control cable only of one kind + CouplingSet coupling; // what they couple: what both flags allow, the control cable only of one kind }; for (auto const &[name, standing, running, couplingtype] : { - meeting{"en57 to en57", "en57_v1/5bgb", "en57_v1/5bgaiii_led_spot", 39}, - meeting{"impuls to en57", "en57_v1/5bgb", "impuls_v1/31we-a_pr", 39 & ~coupling::control}, - meeting{"en57 without the flag", "en57_v1/5bgaiii_led_spot", "en57_v1/6ba_840", coupling::coupler}, + meeting{"en57 to en57", "en57_v1/5bgb", "en57_v1/5bgaiii_led_spot", CouplingSet::FromBits(39)}, + meeting{"impuls to en57", "en57_v1/5bgb", "impuls_v1/31we-a_pr", CouplingSet::FromBits(39).Without(Coupling::control)}, + meeting{"en57 without the flag", "en57_v1/5bgaiii_led_spot", "en57_v1/6ba_840", Coupling::coupler}, }) { CAPTURE(name); scenario scenario{std::string{"couplers/automatic/"} + name, motion(), test::track{}}; scenario.add(standing, 0, consist::full_coupling); - scenario.add(running, 0, coupling::faux, 3.0, 0.2); + scenario.add(running, 0, Coupling::none, 3.0, 0.2); scenario.wait(10.0); auto &first{scenario.vehicle(0)}; auto &second{scenario.vehicle(1)}; - CHECK(first.Couplers[end::rear].CouplingFlag == couplingtype); - CHECK(second.Couplers[end::front].CouplingFlag == couplingtype); + CHECK(first.Couplers[VehicleEnd::rear].CouplingFlag == couplingtype); + CHECK(second.Couplers[VehicleEnd::front].CouplingFlag == couplingtype); // once coupled, not again until uncoupled; the vehicle which coupled marks it for the AI - CHECK_FALSE(first.Couplers[end::rear].AutomaticCouplingAllowed); - CHECK_FALSE(second.Couplers[end::front].AutomaticCouplingAllowed); - CHECK((TestFlag(first.AIFlag, sound::attachcoupler) || TestFlag(second.AIFlag, sound::attachcoupler))); + CHECK_FALSE(first.Couplers[VehicleEnd::rear].AutomaticCouplingAllowed); + CHECK_FALSE(second.Couplers[VehicleEnd::front].AutomaticCouplingAllowed); + CHECK((TestFlag(first.AIFlag(), sound::attachcoupler) || TestFlag(second.AIFlag(), sound::attachcoupler))); scenario.check(); } } TEST_CASE("couplers: a coupler broken, with its brake hose torn off") { consist train; - auto &locomotive{train.add(definition::fiz("4e_v1/4e")).mover()}; - auto &wagon{train.add(definition::fiz("3wl_v2/3wl")).mover()}; - REQUIRE(locomotive.Couplers[end::rear].Connected == &wagon); - locomotive.damage_coupler(end::rear); - CHECK(TestFlag(locomotive.DamageFlag, dtrain_coupling)); - CHECK(locomotive.AlarmChainFlag); - CHECK(locomotive.Couplers[end::rear].CouplingFlag == coupling::faux); - CHECK(wagon.Couplers[end::front].CouplingFlag == coupling::faux); + auto &locomotive{train.add(definition::fiz("4e_v1/4e")).physics()}; + auto &wagon{train.add(definition::fiz("3wl_v2/3wl")).physics()}; + REQUIRE(locomotive.Couplers[VehicleEnd::rear].Connected == &wagon); + locomotive.damage_coupler(VehicleEnd::rear); + CHECK(locomotive.DamageFlag.HasAll(VehicleDamage::coupling)); + CHECK(locomotive.brakes.alarmChain); + CHECK(locomotive.Couplers[VehicleEnd::rear].CouplingFlag == Coupling::none); + CHECK(wagon.Couplers[VehicleEnd::front].CouplingFlag == Coupling::none); // the front coupler of the wagon, broken on its own: no hose to tear - wagon.damage_coupler(end::front); - CHECK(TestFlag(wagon.DamageFlag, dtrain_coupling)); - CHECK_FALSE(wagon.AlarmChainFlag); + wagon.damage_coupler(VehicleEnd::front); + CHECK(wagon.DamageFlag.HasAll(VehicleDamage::coupling)); + CHECK_FALSE(wagon.brakes.alarmChain); // articulated couplers don't break consist articulated; - auto &unit{articulated.add(definition::fiz("impuls_v1/31we-a_pr")).mover()}; + auto &unit{articulated.add(definition::fiz("impuls_v1/31we-a_pr")).physics()}; articulated.add(definition::fiz("impuls_v1/31we-b_pr")); - unit.damage_coupler(end::rear); - CHECK_FALSE(TestFlag(unit.DamageFlag, dtrain_coupling)); - CHECK(unit.Couplers[end::rear].CouplingFlag != coupling::faux); + unit.damage_coupler(VehicleEnd::rear); + CHECK_FALSE(unit.DamageFlag.HasAll(VehicleDamage::coupling)); + CHECK(unit.Couplers[VehicleEnd::rear].CouplingFlag != Coupling::none); } TEST_CASE("couplers: collisions fast enough to derail") { // a locomotive running into a standing wagon from behind, and a wagon running backwards into a standing - // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail + // locomotive; over 15 km/h, weighed by the ratio of the masses, the vehicles derail. the legacy rule of + // physics.collisions old: the new model crushes the ends (test_collisions.cpp) + model_setting const legacy{global_settings::collision_model::old}; struct collision { char const *name; char const *frontpath; @@ -165,10 +184,10 @@ TEST_CASE("couplers: collisions fast enough to derail") { CAPTURE(name); scenario scenario{std::string{"couplers/collision/"} + name, motion(), test::track{}}; scenario.add(frontpath, 0, consist::full_coupling, frontspeed); - scenario.add(back, 0, coupling::faux, backspeed, 20.0); + scenario.add(back, 0, Coupling::none, backspeed, 20.0); scenario.wait(10.0); - CHECK(TestFlag(scenario.vehicle(0).DamageFlag, dtrain_out) == frontout); - CHECK(TestFlag(scenario.vehicle(1).DamageFlag, dtrain_out) == backout); + CHECK(scenario.vehicle(0).DamageFlag.HasAll(VehicleDamage::derailed) == frontout); + CHECK(scenario.vehicle(1).DamageFlag.HasAll(VehicleDamage::derailed) == backout); scenario.check(); } } diff --git a/tests/unit/test_crew.cpp b/tests/unit/test_crew.cpp new file mode 100644 index 000000000..74edbe7ce --- /dev/null +++ b/tests/unit/test_crew.cpp @@ -0,0 +1,313 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" + +#include "physics/brakes.h" +#include "vehicle/crew.h" + +// a driver put in a vehicle or taken off it by a "Crew:" putvalues event (eu07/maszyna#510): reading the +// command, what gets done about it in each state of the vehicle, and the state a train is left in when the driver +// in charge of it is taken off. the game's side (finding the vehicle, creating and deleting the driver) is run by +// the scenario cases, tests/scenarios/cases/*crew* + +using test::consist; +using test::definition; +using test::track; +using test::vehicle; + +namespace { + +track const line{0.15, 0.0, test::catenary_3kv}; + +// the train started up by its driver, brakes released, then under power for Seconds: a notch a second up to the +// given position of the main controller +void get_under_way(consist &Train, int const Position, double const Seconds) { + auto driver{test::driving(Train)}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(driver.cab); + for (int i = 0; i < 3 && driver.cab.DirActive <= 0; ++i) { + driver.cab.DirectionForward(); + } + test::drive(driver, line, 20.0); + driver.controlling.IncMainCtrl(1); + for (int i = 0; i < 90 && false == driver.controlling.lineContactors.IsClosed(); ++i) { + test::drive(driver, line, 1.0); + } + for (int i = 0; i < 60 && driver.controlling.MainCtrlPos() < Position; ++i) { + driver.controlling.IncMainCtrl(1); + test::drive(driver, line, 1.0); + } + test::drive(driver, line, Seconds); +} + +// seconds until the train stands, up to Limit. nobody attends to it: the driver is gone +double seconds_to_stop(consist &Train, double const Limit) { + auto seconds{0.0}; + while (seconds < Limit && std::abs(Train[0].speed()) > 0.01) { + Train.run(1.0, line); + seconds += 1.0; + } + return seconds; +} + +crew::vehicle_state const empty_locomotive{.has_cab = true}; +crew::vehicle_state const ai_driven{.has_cab = true, .has_driver = true, .driver_is_ai = true}; + +} // namespace + +TEST_CASE("crew: the command is told by its prefix, in this case only") { + CHECK(crew::is_command("Crew:EP07-424")); + CHECK(crew::is_command("Crew:")); + CHECK_FALSE(crew::is_command("crew:ep07-424")); + CHECK_FALSE(crew::is_command("CREW:EP07-424")); + CHECK_FALSE(crew::is_command("Crew")); + CHECK_FALSE(crew::is_command("Timetable:Crew:1")); + CHECK_FALSE(crew::is_command("SetVelocity")); + CHECK_FALSE(crew::is_command("")); +} + +TEST_CASE("crew: the vehicle is named in the text, as the scenery keeps its names") { + // the examples of the issue: Shift+4 a crew in cab A, Shift+5 in cab B, Shift+6 the crew off + auto const front{crew::parse("Crew:EP07-424", 1.0, 0.0)}; + CHECK(front.vehicle == "ep07-424"); + CHECK(front.cab_valid); + CHECK(front.cab == 1); + CHECK(front.flags == 0); + + auto const rear{crew::parse("Crew:EP07-424", -1.0, 0.0)}; + CHECK(rear.cab_valid); + CHECK(rear.cab == -1); + + auto const off{crew::parse("Crew:EP07-424", 0.0, 0.0)}; + CHECK(off.cab_valid); + CHECK(off.cab == 0); + + SUBCASE("only the ASCII letters are folded, as the scenery parser folds them") { + // "Ś" of windows-1250 (0x8C) and the two bytes of "Ł" in UTF-8 stay as they are + std::string const name{"SM42-\x8C\xC5\x81" "A"}; + CHECK(crew::parse("Crew:" + name, 1.0, 0.0).vehicle == "sm42-\x8C\xC5\x81" "a"); + } + SUBCASE("no name: the vehicle which set the event off") { + auto const activator{crew::parse("Crew:", 1.0, 0.0)}; + CHECK(activator.vehicle.empty()); + CHECK(activator.cab_valid); + } + SUBCASE("a name with a colon in it is kept whole") { + CHECK(crew::parse("Crew:a:b", 1.0, 0.0).vehicle == "a:b"); + } + SUBCASE("the second value is kept for later, nothing reads it yet") { + CHECK(crew::parse("Crew:x", 0.0, 1.0).flags == 1); + CHECK(crew::parse("Crew:x", 0.0, 3.0).flags == 3); + } +} + +TEST_CASE("crew: a cab other than 1, -1 or 0 is not guessed at") { + for (auto const cab : {2.0, -2.0, 0.5, -0.5, 1.5, 100.0}) { + CAPTURE(cab); + auto const request{crew::parse("Crew:ep07-424", cab, 0.0)}; + CHECK_FALSE(request.cab_valid); + CHECK(crew::decide(request, empty_locomotive) == crew::action::refuse_cab); + CHECK(crew::decide(request, ai_driven) == crew::action::refuse_cab); + } +} + +TEST_CASE("crew: text which is not the command asks for nothing") { + auto const request{crew::parse("SetVelocity", 1.0, 0.0)}; + CHECK(request.vehicle.empty()); + CHECK_FALSE(request.cab_valid); + CHECK_FALSE(crew::changes_crew(crew::decide(request, empty_locomotive))); +} + +TEST_CASE("crew: a vehicle without a driver gets an AI one in the cab asked for") { + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), empty_locomotive) == crew::action::add_front); + CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), empty_locomotive) == crew::action::add_rear); +} + +TEST_CASE("crew: no second driver in a vehicle, and none in a vehicle without a cab") { + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), ai_driven) == crew::action::refuse_crewed); + CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), ai_driven) == crew::action::refuse_crewed); + // a wagon, or a car of a unit without a cab + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), crew::vehicle_state{}) == crew::action::refuse_no_cab); +} + +TEST_CASE("crew: no second driver in charge of a consist") { + auto const second{crew::vehicle_state{.has_cab = true, .consist_driven = true}}; + CHECK(crew::decide(crew::parse("Crew:x", 1.0, 0.0), second) == crew::action::refuse_consist_driven); + CHECK(crew::decide(crew::parse("Crew:x", -1.0, 0.0), second) == crew::action::refuse_consist_driven); +} + +TEST_CASE("crew: the AI driver is taken off, in charge of the consist or not") { + CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), ai_driven) == crew::action::remove); + auto helper{ai_driven}; + helper.consist_driven = true; + CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), helper) == crew::action::remove); + // AI drivers ride vehicles without a cab of their own too (a car of a unit set as driven in the scenery) + auto const nocab{crew::vehicle_state{.has_driver = true, .driver_is_ai = true}}; + CHECK(crew::decide(crew::parse("Crew:x", 0.0, 0.0), nocab) == crew::action::remove); +} + +TEST_CASE("crew: taking the driver off a vehicle which has none does nothing") { + auto const decision{crew::decide(crew::parse("Crew:x", 0.0, 0.0), empty_locomotive)}; + CHECK(decision == crew::action::nothing); + CHECK_FALSE(crew::changes_crew(decision)); +} + +TEST_CASE("crew: a vehicle with a user in it is left alone") { + // the user drives; the user sits in the cab while the autopilot drives; the user sits in a vehicle whose + // controller is the AI's (a cab of the game bound to the vehicle is what counts) + auto const driving{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = false, .occupied = true}}; + auto const autopilot{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = true, .occupied = true}}; + auto const human{crew::vehicle_state{.has_cab = true, .has_driver = true, .driver_is_ai = false}}; + for (auto const &state : {driving, autopilot, human}) { + for (auto const cab : {1.0, -1.0, 0.0}) { + CAPTURE(cab); + auto const decision{crew::decide(crew::parse("Crew:x", cab, 0.0), state)}; + CHECK(decision == crew::action::refuse_user); + CHECK_FALSE(crew::changes_crew(decision)); + } + } +} + +TEST_CASE("crew: only adding and removing change the crew, and every outcome has its words for the log") { + using enum crew::action; + for (auto const action : {add_front, add_rear, remove}) { + CHECK(crew::changes_crew(action)); + CHECK_FALSE(crew::describe(action).empty()); + } + for (auto const action : {nothing, refuse_cab, refuse_user, refuse_crewed, refuse_no_cab, refuse_consist_driven}) { + CHECK_FALSE(crew::changes_crew(action)); + CHECK_FALSE(crew::describe(action).empty()); + } + // the scenario cases look for these in the log + CHECK(crew::describe(add_front) == "an AI driver takes cab A"); + CHECK(crew::describe(add_rear) == "an AI driver takes cab B"); + CHECK(crew::describe(remove) == "the AI driver leaves"); + CHECK(crew::describe(refuse_user).starts_with("refused")); +} + +TEST_CASE("crew: a locomotive under power left by its driver stops and stays braked") { + test::reseed_random(); + consist train; + train.add(definition::fiz("4e_v1/4e"), 1); + get_under_way(train, 20, 30.0); + auto &eu07{train[0].physics()}; + REQUIRE(train[0].speed() > 20.0); + REQUIRE(eu07.MainCtrlPos() > 0); + REQUIRE(eu07.lineBreaker.IsClosed()); + + crew::secure(eu07, eu07); + + CHECK(eu07.MainCtrlPos() == eu07.MainCtrlNoPowerPos()); + CHECK(eu07.ScndCtrlPos() == 0); + CHECK(eu07.brakes.HandlePosition() == static_cast(eu07.brakes.driverValve->GetPos(bh_EB))); + CHECK(eu07.CabActive == 0); + CHECK(eu07.CabOccupied() == 0); + CHECK_FALSE(eu07.CabMaster()); + + auto const stoppedafter{seconds_to_stop(train, 120.0)}; + CAPTURE(stoppedafter); + CHECK(std::abs(train[0].speed()) <= 0.01); + CHECK(eu07.brakePipe.Pressure() < 1.0); // vented by the emergency position + CHECK(eu07.brakes.cylinderPressure > 2.0); + // it keeps standing, also on a slope, with the engine as the driver left it + train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); + CHECK(std::abs(train[0].speed()) <= 0.01); + CHECK(eu07.lineBreaker.IsClosed()); + CHECK(eu07.Im == doctest::Approx(0.0)); +} + +TEST_CASE("crew: what the AI held is let go when the driver leaves") { + test::reseed_random(); + vehicle cab{definition::load("cab_vehicle")}; + cab->DirActive = 1; + cab->SetWarningSignal(1); + cab->signal_departure(true); + cab->Sandbox(true); + REQUIRE(cab->DepartureSignal()); + REQUIRE(cab->SandDose()); + + crew::secure(cab.physics(), cab.physics()); + + CHECK(cab->WarningSignal() == 0); + CHECK_FALSE(cab->DepartureSignal()); + CHECK_FALSE(cab->SandDose()); +} + +TEST_CASE("crew: a train left by its driver is braked through the whole of it") { + test::reseed_random(); + consist train; + train.add(definition::fiz("4e_v1/4e"), 1); + train.add(definition::fiz("11xa_v2/93a")); + train.add(definition::fiz("11xa_v2/93a")); + get_under_way(train, 20, 40.0); + auto &eu07{train[0].physics()}; + auto &last{train[2].physics()}; + REQUIRE(train[0].speed() > 15.0); + REQUIRE(last.brakes.cylinderPressure < 0.1); + + crew::secure(eu07, eu07); + + auto const stoppedafter{seconds_to_stop(train, 180.0)}; + CAPTURE(stoppedafter); + CHECK(std::abs(train[0].speed()) <= 0.01); + CHECK(std::abs(train[2].speed()) <= 0.01); + CHECK(last.brakePipe.Pressure() < 1.0); + CHECK(last.brakes.cylinderPressure > 1.0); +} + +TEST_CASE("crew: a standing locomotive left by its driver is braked too") { + test::reseed_random(); + consist train; + train.add(definition::fiz("4e_v1/4e"), 1); + auto driver{test::driving(train)}; + REQUIRE(test::start_up(driver, line)); + test::release_brakes(driver.cab); + auto &eu07{train[0].physics()}; + // the cylinders of a locomotive started up cold take their time to empty + for (int i = 0; i < 180 && eu07.brakes.cylinderPressure >= 0.1; ++i) { + test::drive(driver, line, 1.0); + } + REQUIRE(eu07.brakes.cylinderPressure < 0.1); + + crew::secure(eu07, eu07); + + // on a slope it would roll away with the brakes off + train.run(120.0, track{0.15, 0.02, test::catenary_3kv}); + CHECK(eu07.brakes.cylinderPressure > 2.0); + CHECK(std::abs(train[0].speed()) <= 0.01); +} + +TEST_CASE("crew: the power an integrated handle asked for goes when the driver leaves") { + test::reseed_random(); + // the handle's demand (eimic) is worked out only while a driver is in charge of the vehicle; left as it + // was, the unit would go on pulling with nobody in it + vehicle impuls{definition::fiz("impuls_v1/31we-a_pr"), 60.0, "impuls", 1}; + impuls->CabActivisation(); + impuls->SetMainCtrlPos(impuls->MainCtrlPosNo); + impuls->eimic = 0.8; + impuls->SetEimicReal(0.8); + + crew::secure(impuls.physics(), impuls.physics()); + + CHECK(impuls->MainCtrlPos() == impuls->MainCtrlNoPowerPos()); + CHECK(impuls->eimic == 0.0); + CHECK(impuls->EimicReal() == 0.0); + CHECK(impuls->brakes.HandlePosition() == static_cast(impuls->brakes.driverValve->GetPos(bh_EB))); + CHECK(impuls->CabOccupied() == 0); +} + +TEST_CASE("crew: a road vehicle left by its driver gets the brake the driver stops it with") { + test::reseed_random(); + vehicle bus{definition::fiz("road/man/nl293"), 40.0, "bus", 1}; + REQUIRE(bus->brakes.config.kind == TBrakeSystem::Individual); + REQUIRE(bus->brakes.IndependentPosition() == 0.0); + bus->CabActivisation(); + + crew::secure(bus.physics(), bus.physics()); + + CHECK(bus->brakes.IndependentPosition() == 1.0); + CHECK(bus->MainCtrlPos() == bus->MainCtrlNoPowerPos()); + bus.run(60.0, track{0.6, 0.0, 0.0, 2}); + CHECK(std::abs(bus.speed()) <= 0.01); +} diff --git a/tests/unit/test_definition.cpp b/tests/unit/test_definition.cpp index 6b0ce22b3..bfe8466e9 100644 --- a/tests/unit/test_definition.cpp +++ b/tests/unit/test_definition.cpp @@ -9,20 +9,20 @@ using test::vehicle; TEST_CASE("definition: the wagon from data/wagon.json loads with its values") { vehicle wagon{definition::load("wagon")}; - CHECK(wagon->Mass == doctest::Approx(42200.0)); - CHECK(wagon->Vmax == doctest::Approx(120.0)); + CHECK(wagon->Mass() == doctest::Approx(42200.0)); + CHECK(wagon->Vmax() == doctest::Approx(120.0)); CHECK(wagon->Dim.L == doctest::Approx(26.8)); - CHECK(wagon->WheelDiameter == doctest::Approx(0.96)); - CHECK(wagon->NAxles == 4); - CHECK(wagon->MaxBrakePress[3] == doctest::Approx(3.8)); - CHECK(wagon->BrakeSystem == TBrakeSystem::Pneumatic); + CHECK(wagon->WheelDiameter() == doctest::Approx(0.96)); + CHECK(wagon->NAxles() == 4); + CHECK(wagon->brakes.config.maxCylinderPressure[3] == doctest::Approx(3.8)); + CHECK(wagon->brakes.config.kind == TBrakeSystem::Pneumatic); } TEST_CASE("definition: keys set by the test reach the vehicle") { vehicle heavy{definition::load("wagon").set("Param", "M", 60000).set("Wheels", "D", 1.0)}; - CHECK(heavy->Mass == doctest::Approx(60000.0)); - CHECK(heavy->WheelDiameter == doctest::Approx(1.0)); + CHECK(heavy->Mass() == doctest::Approx(60000.0)); + CHECK(heavy->WheelDiameter() == doctest::Approx(1.0)); } TEST_CASE("definition: an unknown test vehicle is an error, not a silently empty one") { @@ -41,8 +41,8 @@ TEST_CASE("definition: rows of a table section reach the vehicle") { .set("LightsList", "rows", {{0, 0}, {pc1, 0}})}; CHECK(wagon->LightsPosNo == 2); - CHECK(wagon->LightsPos == 1); - CHECK(wagon->Lights[end::front][1] == pc1); + CHECK(wagon->LightsPos() == 1); + CHECK(wagon->Lights[VehicleEnd::front][1] == pc1); } TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywhere, leading spaces, carriage returns") { @@ -59,11 +59,11 @@ TEST_CASE("definition: lines the loader skips or trims: comments, a hash anywher } crlf += c; } - TMoverParameters wagon(0.0, "wagon", "test", 0); + physics::Vehicle wagon(0.0, "wagon", "test", 0); REQUIRE(wagon.LoadFIZ_Text(crlf)); - CHECK(wagon.Mass == doctest::Approx(42200.0)); - CHECK(wagon.Vmax == doctest::Approx(120.0)); - CHECK(wagon.MaxBrakePress[3] == doctest::Approx(3.8)); + CHECK(wagon.Mass() == doctest::Approx(42200.0)); + CHECK(wagon.Vmax() == doctest::Approx(120.0)); + CHECK(wagon.brakes.config.maxCylinderPressure[3] == doctest::Approx(3.8)); } TEST_CASE("definition: a compressor list, whose positions allow the compressor and scale its speed and limits") { @@ -76,32 +76,32 @@ TEST_CASE("definition: a compressor list, whose positions allow the compressor a .set("CompressorList", "Default", 1) .set("CompressorList", "rows", {{2, 2, 1, 1}, {1, 1, 1, 1}, {2, 1, 0.9, 0.9}})}; vehicle real{eu07, 0.0, "test", 1}; - CHECK(real->CompressorListPosNo == 3); - CHECK(real->CompressorList[3][3] == 0); + CHECK(real->air.compressor.config.listPositions == 3); + CHECK(real->air.compressor.config.list[3][3] == 0); auto driven{test::driving(real)}; test::track const line{0.15, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); - CHECK(real->CompressorListPos == 1); + CHECK(real->air.compressor.ListPosition() == 1); test::drive(driven, line, 60.0); - CHECK(real->CompressorAllow); - CHECK(real->Compressor <= real->MaxCompressor + 0.05); - CHECK(real->Compressor >= real->MinCompressor - 0.05); + CHECK(real->air.compressor.IsAllowed()); + CHECK(real->air.MainReservoirPressure() <= real->air.compressor.config.maxPressure + 0.05); + CHECK(real->air.MainReservoirPressure() >= real->air.compressor.config.minPressure - 0.05); // the second position doesn't let it run CHECK(real->ChangeCompressorPreset(2)); test::drive(driven, line, 2.0); - CHECK_FALSE(real->CompressorAllow); - CHECK_FALSE(real->CompressorFlag); + CHECK_FALSE(real->air.compressor.IsAllowed()); + CHECK_FALSE(real->air.compressor.IsRunning()); // the third lets it, under limits of nothing: with no span between them for the governor, the reservoir over // the upper limit gets vented while the compressor runs on CHECK(real->ChangeCompressorPreset(3)); - auto const full{real->Compressor}; + auto const full{real->air.MainReservoirPressure()}; test::drive(driven, line, 10.0); - CHECK(real->CompressorAllow); - CHECK(real->CompressorFlag); - CHECK(real->Compressor < full - 1.0); + CHECK(real->air.compressor.IsAllowed()); + CHECK(real->air.compressor.IsRunning()); + CHECK(real->air.MainReservoirPressure() < full - 1.0); // no further than the last position CHECK_FALSE(real->ChangeCompressorPreset(5)); - CHECK(real->CompressorListPos == 3); + CHECK(real->air.compressor.ListPosition() == 3); } TEST_CASE("definition: the compressor's limits set apart for the rear cab") { @@ -113,16 +113,16 @@ TEST_CASE("definition: the compressor's limits set apart for the rear cab") { test::track const line{0.15, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); test::drive(driven, line, 120.0); - CHECK(real->CabDependentCompressor); - CHECK(real->MaxCompressor == doctest::Approx(cab > 0 ? 8.7 : 6.0)); - CHECK(real->MinCompressor == doctest::Approx(cab > 0 ? 7.0 : 5.0)); - CHECK(real->Compressor <= real->MaxCompressor + 0.05); - CHECK(real->Compressor >= real->MinCompressor - 0.05); + CHECK(real->air.compressor.config.cabDependent); + CHECK(real->air.compressor.config.maxPressure == doctest::Approx(cab > 0 ? 8.7 : 6.0)); + CHECK(real->air.compressor.config.minPressure == doctest::Approx(cab > 0 ? 7.0 : 5.0)); + CHECK(real->air.MainReservoirPressure() <= real->air.compressor.config.maxPressure + 0.05); + CHECK(real->air.MainReservoirPressure() >= real->air.compressor.config.minPressure - 0.05); } } TEST_CASE("definition: the highest power of an induction motor drive by the speed (PmaxList)") { - // the drive's power limit (eimc_p_Pmax) follows the table, between its rows and, by the last two, past its end + // the drive's power limit (traction.maxPower) follows the table, between its rows and, by the last two, past its end auto eu47{definition::fiz("e186_v2/eu47").set("PmaxList", "Size", 3).set("PmaxList", "rows", {{0, 1000}, {50, 3000}, {100, 5600}})}; auto const table{[](double Speed) { return Speed < 50.0 ? 1000.0 + 40.0 * Speed : 3000.0 + 52.0 * (Speed - 50.0); }}; for (auto const speed : {25.0, 75.0, 150.0}) { @@ -131,7 +131,7 @@ TEST_CASE("definition: the highest power of an induction motor drive by the spee auto driven{test::driving(real)}; test::track const line{0.0, 0.0, test::catenary_3kv}; REQUIRE(test::start_up(driven, line)); - CHECK(real->eimc[eimc_p_Pmax] == doctest::Approx(table(real->Vel)).epsilon(0.01)); + CHECK(real->inductionMotor.traction.maxPower == doctest::Approx(table(real->Vel)).epsilon(0.01)); } } diff --git a/tests/unit/test_derail_motion.cpp b/tests/unit/test_derail_motion.cpp new file mode 100644 index 000000000..2d3a7f1af --- /dev/null +++ b/tests/unit/test_derail_motion.cpp @@ -0,0 +1,1093 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "vehicle/derailmotion.h" +#include "physics/derailment.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" + +#include +#include +#include +#include +#include +#include + +// a vehicle off the rails moving on the ground by itself (physics.derailment new): vehicle/derailmotion.h, and what +// the vehicle of physics::Vehicle makes of it + +using test::definition; +using test::vehicle; +namespace dm = derail_motion; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; +constexpr double degree{std::numbers::pi / 180.0}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// EU07 (4E of data/fiz): its dimensions and the centre of gravity of its body +dm::vehicle_shape eu07() { + dm::vehicle_shape shape; + shape.length = 15.915; + shape.width = 2.903; + shape.height = 4.348; + shape.centre_of_gravity = dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered); + shape.contact_spacing = dr::contact_spacing(1.435); + shape.base = 8.0; + return shape; +} + +// the lateral acceleration [m/s2] the wheels of EU07 lift at: the wheel unloading of derailment.h reaches 1 +double const eu07_tipping{dr::overturning_acceleration(eu07().centre_of_gravity, dr::contact_spacing(1.435))}; + +// the track along +z at the height 0, its left (+x) the outside of the curve +dm::start leaving(double const Speed, dm::cause const Reason, int const Outward = 0, double const Acceleration = 0.0) { + dm::start start; + start.position = glm::dvec3{0.0}; + start.front = glm::dvec3{0.0, 0.0, 1.0}; + start.line = start.front; + start.speed = Speed; + start.reason = Reason; + start.outward = Outward; + start.acceleration = Acceleration; + return start; +} + +// the ground across the track, along +z: the top of the ballast 0.2 m under the rails out to 3 m each side, then the +// Slope (rise per metre outwards, negative down) to the Depth under the top (above it, rising). as a scenery has it, +// a level ground lies under it all, at the lowest of it: what is over the ceiling asked for isn't found, that is +class profile final : public dm::ground { +public: + profile(double const Slope, double const Depth, bool const Bothsides = false) : m_slope{Slope}, m_depth{Depth}, m_bothsides{Bothsides} {} + std::optional height(double const X, double, double const Ceiling) const override { + constexpr double top{-0.2}; + constexpr double edge{3.0}; + auto const across{m_bothsides ? std::abs(X) : X}; + auto const floor{std::min(top, top + std::clamp(m_slope * 1e6, -std::abs(m_depth), std::abs(m_depth)))}; + auto surface{top}; + if (across > edge) { + surface += std::clamp(m_slope * (across - edge), -std::abs(m_depth), std::abs(m_depth)); + } + return surface <= Ceiling ? surface : floor; + } + +private: + double m_slope; + double m_depth; + bool m_bothsides; +}; + +struct outcome { + double time{0.0}; + double travelled{0.0}; + double along{0.0}; + double across{0.0}; + double tipping{0.0}; + double roll{0.0}; + double height{0.0}; + bool lying{false}; + double lying_at{-1.0}; // the time it came to lie on its side, -1 never +}; + +// the vehicle slides as physics::Vehicle drives it: its speed along the heading falls with the friction of the motion +// and the gravity of the grade under it, the distance of each step goes to the motion +outcome slide(dm::start const &Start, dm::ground const &Ground, double const Dt = 0.01, dm::vehicle_shape const &Shape = eu07(), double const Seconds = 60.0) { + dm::body body; + body.begin(Start, Shape, Ground); + auto speed{Start.speed}; + outcome result; + while (result.time < Seconds) { + auto const direction{speed >= 0.0 ? 1.0 : -1.0}; + auto const deceleration{dm::gravity * (body.friction() * direction + body.grade())}; + auto next{speed - deceleration * Dt}; + if (next * speed <= 0.0 && std::abs(body.grade()) <= body.friction()) { + next = 0.0; + } + auto const reversals{body.reversals()}; + body.step(Dt, 0.5 * (speed + next) * Dt, next, Ground); + speed = (body.reversals() - reversals) % 2 != 0 ? -next : next; + result.time += Dt; + if (body.lying() && result.lying_at < 0.0) { + result.lying_at = result.time; + } + if (body.at_rest()) { + break; + } + } + result.travelled = body.travelled(); + result.along = body.along(); + result.across = body.across(); + result.tipping = body.tipping(); + result.roll = body.roll(); + result.height = body.current().position.y; + result.lying = body.lying(); + return result; +} + +dm::flat_ground const ballast{-0.2}; + +} // namespace + +TEST_CASE("derail motion: the distance it slides goes with the square of the speed and against the friction") { + auto const fast{dm::stopping_distance(133.0 * kmh, dr::off_rails_friction)}; + auto const slow{dm::stopping_distance(40.0 * kmh, dr::off_rails_friction)}; + REQUIRE(fast.has_value()); + REQUIRE(slow.has_value()); + CHECK(*fast == doctest::Approx(232.0).epsilon(0.01)); + CHECK(*slow == doctest::Approx(21.0).epsilon(0.01)); + CHECK(*fast / *slow == doctest::Approx(133.0 * 133.0 / (40.0 * 40.0)).epsilon(1e-9)); + // on its side + CHECK(*dm::stopping_distance(133.0 * kmh, dr::overturned_friction) == doctest::Approx(*fast * 0.3 / 0.5).epsilon(1e-9)); + // uphill sooner, downhill further, down a slope steeper than the friction it doesn't stop + CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, 0.05) < *slow); + CHECK(*dm::stopping_distance(40.0 * kmh, 0.3, -0.05) > *slow); + CHECK_FALSE(dm::stopping_distance(40.0 * kmh, 0.3, -0.4).has_value()); + + SUBCASE("the vehicle off the end of the track slides as far, straight on, upright") { + for (auto const speed : {133.0, 40.0}) { + CAPTURE(speed); + auto const result{slide(leaving(speed * kmh, dm::cause::end_of_track), ballast)}; + MESSAGE(std::format("off the end of the track at {:.0f} km/h: {:.1f} m in {:.1f} s", speed, result.travelled, result.time)); + CHECK(result.travelled == doctest::Approx(*dm::stopping_distance(speed * kmh, dr::off_rails_friction)).epsilon(0.02)); + CHECK(result.along == doctest::Approx(result.travelled).epsilon(1e-6)); + CHECK(std::abs(result.across) < 1e-6); + CHECK(result.tipping == 0.0); + // on the top of the ballast, not on the rails nor under the ground + CHECK(result.height == doctest::Approx(-0.2)); + } + } + SUBCASE("the friction along it rises from the one on its wheels to the one on its side") { + CHECK(dm::sliding_friction(0.0, false) == dr::off_rails_friction); + CHECK(dm::sliding_friction(dm::body::half_turn, false) == dr::overturned_friction); + CHECK(dm::sliding_friction(0.5 * dm::body::half_turn, false) == doctest::Approx(0.5 * (dr::off_rails_friction + dr::overturned_friction))); + CHECK(dm::sliding_friction(0.0, true) == dm::guided_friction); + } +} + +TEST_CASE("derail motion: the way it leaves the track by what derailed it") { + SUBCASE("off the end of the track and in a collision: straight on") { + CHECK(dm::departure_angle(dm::cause::end_of_track, 30.0, 10.0) == 0.0); + CHECK(dm::departure_angle(dm::cause::collision, 30.0, 10.0) == 0.0); + auto const result{slide(leaving(100.0 * kmh, dm::cause::collision, 1, 5.0), ballast)}; + CHECK(std::abs(result.across) < 1e-6); + } + SUBCASE("the flange climbing the rail: towards the rail it climbed, out of the curve, upright") { + for (auto const outward : {1, -1}) { + CAPTURE(outward); + auto const result{slide(leaving(100.0 * kmh, dm::cause::off_rails, outward, 3.0), ballast)}; + MESSAGE(std::format("climbed out of the curve to the {}: {:.1f} m across in {:.1f} m", outward > 0 ? "left" : "right", result.across, result.travelled)); + CHECK(result.across * outward > 1.0); + CHECK(result.tipping == 0.0); + CHECK_FALSE(result.lying); + } + // the faster the speed against the sideways one, the smaller the angle + CHECK(dm::departure_angle(dm::cause::off_rails, 40.0, 3.0) < dm::departure_angle(dm::cause::off_rails, 10.0, 3.0)); + CHECK(dm::departure_angle(dm::cause::off_rails, 0.1, 1000.0) == dm::most_departure); + } + SUBCASE("backwards, out of the curve as well") { + auto const result{slide(leaving(-100.0 * kmh, dm::cause::off_rails, 1, 3.0), ballast)}; + CHECK(result.along < -10.0); + CHECK(result.across > 1.0); + } + SUBCASE("overturned: out of the curve, falling on its side there") { + for (auto const outward : {1, -1}) { + CAPTURE(outward); + auto const result{slide(leaving(120.0 * kmh, dm::cause::overturned, outward, 2.0 * eu07_tipping), ballast)}; + MESSAGE(std::format("overturned to the {}: {:.1f} m across in {:.1f} m, on its side after {:.2f} s", outward > 0 ? "left" : "right", result.across, result.travelled, result.lying_at)); + CHECK(result.across * outward > 1.0); + CHECK(result.lying); + CHECK(result.tipping * outward == doctest::Approx(dm::body::half_turn)); + CHECK(result.roll * outward == doctest::Approx(dm::body::half_turn)); + // lying on its side on the top of the ballast, the origin of its model is half the width of its body up + CHECK(result.height == doctest::Approx(-0.2 + 0.5 * eu07().width)); + } + } + SUBCASE("pulled off by a coupling: to the side it is pulled to") { + auto const result{slide(leaving(50.0 * kmh, dm::cause::pulled_off, -1, 2.0), ballast)}; + CHECK(result.across < -0.1); + } +} + +TEST_CASE("derail motion: tipping over goes as far as the overturning went over its limit") { + // the curve keeps pushing it out while its outer wheels are on the rail: the further over the limit, the sooner it lies + auto const barely{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 1.2 * eu07_tipping), ballast)}; + auto const well{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 2.0 * eu07_tipping), ballast)}; + auto const hard{slide(leaving(120.0 * kmh, dm::cause::overturned, 1, 5.0 * eu07_tipping), ballast)}; + MESSAGE(std::format("on its side after {:.2f} / {:.2f} / {:.2f} s at a wheel unloading of 1.2 / 2 / 5", barely.lying_at, well.lying_at, hard.lying_at)); + REQUIRE(barely.lying); + REQUIRE(well.lying); + REQUIRE(hard.lying); + CHECK(barely.lying_at > well.lying_at); + CHECK(well.lying_at > hard.lying_at); + // it takes its time to fall over, it doesn't jump onto its side + CHECK(hard.lying_at > 0.3); + + SUBCASE("a body on the rails stays upright, on a level ground it isn't tipped by anything") { + auto const upright{slide(leaving(120.0 * kmh, dm::cause::off_rails, 1, 2.0 * eu07_tipping), ballast)}; + CHECK(upright.tipping == 0.0); + } + SUBCASE("slowing down below the limit, the curve doesn't tip it any more") { + dm::body body; + body.begin(leaving(30.0 * kmh, dm::cause::overturned, 1, 1.05 * eu07_tipping), eu07(), ballast); + // stopped at once: the curve pushes it out no more, it falls back on its wheels + body.step(0.01, 0.0, 0.0, ballast); + for (int step = 0; step < 300; ++step) { + body.step(0.01, 0.0, 0.0, ballast); + } + CHECK_FALSE(body.guided()); + CHECK(body.tipping() == 0.0); + } +} + +TEST_CASE("derail motion: the ground under it") { + SUBCASE("off the edge of an embankment it slides down the slope and falls on its side towards the bottom") { + // 1:1.5 down 4 m to the left, the vehicle leaving the track 4 degrees to the left at 60 km/h + profile const embankment{-1.0 / 1.5, 4.0}; + auto start{leaving(60.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const result{slide(start, embankment)}; + MESSAGE(std::format("down the embankment: {:.1f} m across, {:.1f} m down, tipped {:.0f} degrees, after {:.1f} m", result.across, -0.2 - result.height, result.tipping / degree, result.travelled)); + CHECK(result.across > 4.0); + // lying on the slope, its body half its width up off the ground + CHECK(result.height < -1.5); + CHECK(result.lying); + CHECK(result.tipping > 0.0); + } + SUBCASE("on a gentle slope it stays upright, leaning with the ground") { + profile const gentle{-1.0 / 6.0, 4.0}; + auto start{leaving(80.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(6.0 * degree), 0.0, std::cos(6.0 * degree)}; + auto const result{slide(start, gentle)}; + CHECK_FALSE(result.lying); + CHECK(result.tipping == 0.0); + // leaning left, down the slope + CHECK(result.roll == doctest::Approx(std::atan(1.0 / 6.0)).epsilon(0.05)); + } + SUBCASE("a lower centre of gravity tips over on a steeper slope only") { + // a 1:2.2 slope, 24 degrees: the steepest one EU07 stands on is 1:2.8 (20 degrees), a flat wagon tips past 1:1.7 + profile const slope{-1.0 / 2.2, 6.0}; + auto start{leaving(50.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(10.0 * degree), 0.0, std::cos(10.0 * degree)}; + auto low{eu07()}; + low.centre_of_gravity = 0.9; + low.height = 2.0; + CHECK(slide(start, slope).lying); + CHECK_FALSE(slide(start, slope, 0.01, low).lying); + } + SUBCASE("in a cutting it climbs the bank, stops sooner and leans (here falls) back towards the track") { + profile const cutting{1.0 / 1.5, 4.0}; + auto start{leaving(60.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const level{slide(start, ballast)}; + auto const result{slide(start, cutting)}; + MESSAGE(std::format("into a cutting: {:.1f} m against {:.1f} m on a level ground, roll {:.0f} degrees", result.travelled, level.travelled, result.roll / degree)); + CHECK(result.travelled < level.travelled); + CHECK(result.height > -0.2); + CHECK(result.roll < 0.0); + } + SUBCASE("it doesn't sink into the ground, it falls off a step") { + // off a wall 3 m high + profile const wall{-100.0, 3.0}; + auto start{leaving(40.0 * kmh, dm::cause::off_rails)}; + start.front = glm::dvec3{std::sin(20.0 * degree), 0.0, std::cos(20.0 * degree)}; + dm::body body; + body.begin(start, eu07(), wall); + auto lowest{0.0}; + auto speed{start.speed}; + for (int index = 0; index < 1000; ++index) { + auto const next{std::max(0.0, speed - dm::gravity * body.friction() * 0.01)}; + body.step(0.01, 0.5 * (speed + next) * 0.01, next, wall); + speed = next; + auto const &position{body.current().position}; + auto const ground{*wall.height(position.x, position.z, 1e9)}; + CHECK(position.y >= ground - 1e-9); + lowest = std::min(lowest, position.y); + } + CHECK(lowest < -3.0); + } +} + +TEST_CASE("derail motion: the same with steps of 0.01, 0.03 and 0.05 s") { + profile const embankment{-1.0 / 1.5, 4.0}; + auto down{leaving(60.0 * kmh, dm::cause::off_rails)}; + down.front = glm::dvec3{std::sin(4.0 * degree), 0.0, std::cos(4.0 * degree)}; + auto const overturning{leaving(120.0 * kmh, dm::cause::overturned, -1, 2.0 * eu07_tipping)}; + auto const climbing{leaving(100.0 * kmh, dm::cause::off_rails, 1, 3.0)}; + auto const fine{slide(down, embankment, 0.01)}; + auto const finetip{slide(overturning, ballast, 0.01)}; + auto const fineclimb{slide(climbing, ballast, 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{slide(down, embankment, dt)}; + CHECK(coarse.travelled == doctest::Approx(fine.travelled).epsilon(0.02)); + CHECK(coarse.across == doctest::Approx(fine.across).epsilon(0.05)); + CHECK(coarse.lying == fine.lying); + auto const coarsetip{slide(overturning, ballast, dt)}; + CHECK(coarsetip.travelled == doctest::Approx(finetip.travelled).epsilon(0.02)); + CHECK(coarsetip.across == doctest::Approx(finetip.across).epsilon(0.02)); + CHECK(coarsetip.lying_at == doctest::Approx(finetip.lying_at).epsilon(0.1)); + auto const coarseclimb{slide(climbing, ballast, dt)}; + CHECK(coarseclimb.across == doctest::Approx(fineclimb.across).epsilon(0.02)); + } +} + +TEST_CASE("derail motion: the ground of the scenery") { + SUBCASE("the triangles of the terrain") { + std::vector triangles; + // a square 10 m wide at 2 m rising to 4 m along x, and a roof over half of it at 10 m + triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}}); + triangles.push_back({glm::dvec3{0.0, 2.0, 0.0}, glm::dvec3{10.0, 4.0, 10.0}, glm::dvec3{0.0, 2.0, 10.0}}); + triangles.push_back({glm::dvec3{0.0, 10.0, 0.0}, glm::dvec3{5.0, 10.0, 0.0}, glm::dvec3{0.0, 10.0, 10.0}}); + dm::mesh_ground const terrain{triangles, glm::dvec2{-5.0, -5.0}, glm::dvec2{15.0, 15.0}, 2.0}; + CHECK(terrain.size() == 3); + CHECK(*terrain.height(5.0, 5.0, 8.0) == doctest::Approx(3.0)); + CHECK(*terrain.height(7.5, 2.5, 8.0) == doctest::Approx(3.5)); + // under the roof the ground, over it the roof + CHECK(*terrain.height(1.0, 1.0, 8.0) == doctest::Approx(2.2)); + CHECK(*terrain.height(1.0, 1.0, 12.0) == doctest::Approx(10.0)); + CHECK_FALSE(terrain.height(12.0, 5.0, 8.0).has_value()); + CHECK_FALSE(terrain.height(50.0, 5.0, 8.0).has_value()); + CHECK(terrain.covers(14.0, -4.0)); + CHECK_FALSE(terrain.covers(16.0, 0.0)); + // the area of another vehicle: inside the one gathered or not + CHECK(terrain.covers(glm::dvec2{-5.0, -5.0}, glm::dvec2{15.0, 15.0})); + CHECK(terrain.covers(glm::dvec2{0.0, 2.0}, glm::dvec2{10.0, 12.0})); + CHECK_FALSE(terrain.covers(glm::dvec2{0.0, 2.0}, glm::dvec2{10.0, 16.0})); + CHECK_FALSE(terrain.covers(glm::dvec2{-6.0, 0.0}, glm::dvec2{0.0, 1.0})); + // cut down to the ground under a vehicle at rest: the triangles reaching into it, the same height there + auto const under{terrain.cropped(glm::dvec2{6.0, 0.0}, glm::dvec2{9.0, 4.0})}; + CHECK(under.size() == 2); + CHECK(*under.height(7.5, 2.5, 8.0) == doctest::Approx(3.5)); + CHECK(under.covers(6.0, 4.0)); + CHECK_FALSE(under.covers(5.0, 2.0)); + CHECK_FALSE(under.height(5.0, 2.0, 8.0).has_value()); + CHECK(terrain.cropped(glm::dvec2{0.5, 0.5}, glm::dvec2{1.0, 1.0}).size() == 3); + CHECK(terrain.cropped(glm::dvec2{20.0, 20.0}, glm::dvec2{30.0, 30.0}).size() == 0); + } + SUBCASE("the bed of the track over the terrain, level ground without one") { + dm::formation bed; + bed.point = glm::dvec3{0.0, 10.0, 0.0}; + bed.direction = glm::dvec3{0.0, 0.0, 1.0}; + bed.half_width = 2.0; + CHECK(bed.height(1.5, 100.0) == doctest::Approx(9.8)); + CHECK(bed.height(-2.0, -50.0) == doctest::Approx(9.8)); + CHECK(bed.height(3.5, 0.0) == doctest::Approx(9.8 - 1.0)); + dm::flat_ground const low{7.0}; + dm::site const embankment{&low, bed}; + CHECK(*embankment.height(0.0, 0.0, 12.0) == doctest::Approx(9.8)); + CHECK(*embankment.height(4.0, 0.0, 12.0) == doctest::Approx(9.8 - 2.0 / 1.5)); + CHECK(*embankment.height(20.0, 0.0, 12.0) == doctest::Approx(7.0)); + dm::site const bare{nullptr, bed}; + CHECK(*bare.height(20.0, 0.0, 12.0) == doctest::Approx(9.8)); + } +} + +TEST_CASE("derail motion: a coupling pulling sideways") { + // EU07, 80 t on 4 axles: a wheel carries 98 kN + CHECK(dm::pull_ratio(300e3, 0.0, 80e3, 4) == 0.0); + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) == doctest::Approx(0.5 * 150e3 / (80e3 * dm::gravity / 8.0))); + CHECK(dm::pull_ratio(-300e3, -30.0 * degree, 80e3, 4) == dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4)); + // an empty wagon of 20 t goes over the climbing limit with a force the locomotive takes + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 20e3, 4) > dr::climbing_limit); + CHECK(dm::pull_ratio(300e3, 30.0 * degree, 80e3, 4) < dr::climbing_limit); +} + +TEST_CASE("derail motion: the vehicle leaves the track with physics.derailment new only") { + test::track curve; + curve.radius = 300.0; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07().centre_of_gravity, 1.435) / kmh}; + + SUBCASE("new: derailed by the criteria it leaves the track, then slides with the friction of the motion") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 20.0}; + for (int step = 0; step < 10; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); + CHECK(eu07vehicle->DerailCause() == dm::cause::overturned); + CHECK(eu07vehicle->DerailAcceleration() > eu07_tipping); + CHECK(eu07vehicle->leaves_track()); + eu07vehicle->OffTrack.begin(leaving(eu07vehicle->V(), eu07vehicle->DerailCause(), 1, eu07vehicle->DerailAcceleration()), eu07(), ballast); + CHECK_FALSE(eu07vehicle->leaves_track()); + // tipping over on its outer wheels it hardly slows down + auto const start{eu07vehicle->V()}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + auto const deceleration{(start - eu07vehicle->V()) / 0.2}; + CHECK(deceleration == doctest::Approx(dm::guided_friction * dr::gravity * 80.0 / 96.0).epsilon(0.1)); + // back on the rails, not off the track any more, and what derailed it forgotten + eu07vehicle->repair_damage(); + CHECK_FALSE(eu07vehicle->OffTrack.active()); + CHECK_FALSE(eu07vehicle->leaves_track()); + CHECK(eu07vehicle->DerailCause() == dm::cause::off_rails); + CHECK(eu07vehicle->DerailAcceleration() == 0.0); + } + SUBCASE("new: off the end of the track it slides on its wheels, straight on") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 40.0}; + eu07vehicle.damage_track(dtrack_norail); + eu07vehicle.step(); + REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->Derailed() == dr::outcome::off_rails); + CHECK(eu07vehicle->DerailCause() == dm::cause::end_of_track); + CHECK(eu07vehicle->leaves_track()); + } + SUBCASE("new: a vehicle pulled off by a coupling, upright, to the side it was pulled to") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; + pulled->pull_off(-1, 5.0, "test"); + CHECK(pulled->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(pulled->Derailed() == dr::outcome::off_rails); + CHECK(pulled->DerailCause() == dm::cause::pulled_off); + CHECK(pulled->DerailSide() == -1); + CHECK(pulled->leaves_track()); + pulled->repair_damage(); + CHECK(pulled->DerailCause() == dm::cause::off_rails); + CHECK(pulled->DerailAcceleration() == 0.0); + CHECK(pulled->DerailSide() == 0); + } +} + +TEST_CASE("derail motion: with physics.derailment monitor and old the vehicle stays on the track, as before") { + test::track curve; + curve.radius = 300.0; + for (auto const model : {global_settings::derailment_model::monitor, global_settings::derailment_model::old}) { + auto const number{static_cast(model)}; + CAPTURE(number); + model_setting const setting{model}; + vehicle fast{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + fast.step(curve); + } + REQUIRE(fast->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(fast->Derailed() == dr::outcome::none); + CHECK_FALSE(fast->leaves_track()); + CHECK_FALSE(fast->OffTrack.active()); + // stopped dead by the legacy model + CHECK(fast->V() == doctest::Approx(0.0).epsilon(0.01)); + vehicle ending{definition::fiz("4e_v1/4e"), 40.0}; + ending.damage_track(dtrack_norail); + ending.step(); + REQUIRE(ending->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(ending->Derailed() == dr::outcome::none); + CHECK_FALSE(ending->leaves_track()); + // nor is a vehicle pulled off it + vehicle pulled{definition::fiz("4e_v1/4e"), 40.0}; + pulled->pull_off(1, 5.0, "test"); + CHECK_FALSE(pulled->DamageFlag.HasAll(VehicleDamage::derailed)); + } +} + +// ---- the yaw of the body, the train folding up, the scatter + +namespace { + +// a coach of 40 t, 24.5 m over the buffers +dm::vehicle_shape coach() { + dm::vehicle_shape shape; + shape.length = 24.5; + shape.width = 2.825; + shape.height = 4.05; + shape.centre_of_gravity = dr::default_centre_of_gravity(4.05, dr::vehicle_class::unpowered); + shape.contact_spacing = dr::contact_spacing(1.435); + shape.base = 17.2; + shape.mass = 40e3; + return shape; +} + +// an end of the body: its front (Front) or its rear, at the height of the buffers +dm::end_point end_of(dm::body const &Body, bool const Front) { + // over its base, as TDynamicObject takes it + auto const half{0.5 * Body.shape().length * (Front ? 1.0 : -1.0)}; + return dm::end_point{Body.base() + glm::dvec3{0.0, dm::buffer_height, 0.0} + Body.axis() * half, Front ? Body.axis() : -Body.axis(), Body.tipping()}; +} + +struct car { + dm::body body; + double speed{0.0}; + double gap{0.0}; // of the coupling behind it +}; + +// the train of bodies off the track on level ground as physics::Vehicle and TDynamicObject drive it: their buffers and +// couplings a spring of 2 MN/m with its damping, the longitudinal motion of each from the forces of its couplings along +// its heading and the friction of its motion; the forces across turn them. Dt the step [s]; till all stop or 30 s +std::vector run_train(std::vector> const &Starts, dm::vehicle_shape const &Shape, double const Dt = 0.01) { + std::vector train(Starts.size()); + for (std::size_t index = 0; index < train.size(); ++index) { + train[index].body.begin(Starts[index].first, Shape, ballast, Starts[index].second); + train[index].speed = Starts[index].first.speed; + } + for (std::size_t index = 0; index + 1 < train.size(); ++index) { + train[index].gap = dm::meet(end_of(train[index].body, false), end_of(train[index + 1].body, true)).gap; + } + constexpr double stiffness{2e6}; + auto const damping{0.3 * 2.0 * std::sqrt(stiffness * Shape.mass)}; + constexpr double slack{0.05}; + for (int step = 0; step * Dt < 30.0; ++step) { + std::vector> ends(train.size()); + for (std::size_t index = 0; index + 1 < train.size(); ++index) { + auto &ahead{train[index]}; + auto &behind{train[index + 1]}; + auto const rear{dm::meet(end_of(ahead.body, false), end_of(behind.body, true))}; + auto const front{dm::meet(end_of(behind.body, true), end_of(ahead.body, false))}; + auto const closing{(ahead.gap - rear.gap) / Dt}; + ahead.gap = rear.gap; + auto compression{0.0}; + if (rear.gap < 0.0) { + compression = std::max(0.0, -stiffness * rear.gap + damping * closing); + } + else if (rear.gap > slack) { + compression = std::min(0.0, -stiffness * (rear.gap - slack) + damping * closing); + } + ends[index][1] = dm::force_on(rear, compression); + ends[index + 1][0] = dm::force_on(front, compression); + } + auto moving{false}; + for (std::size_t index = 0; index < train.size(); ++index) { + auto &item{train[index]}; + auto const push{glm::dot(ends[index][0].force + ends[index][1].force, item.body.heading()) / Shape.mass}; + auto const friction{dm::gravity * item.body.friction()}; + auto next{item.speed + push * Dt}; + if (std::abs(next) <= friction * Dt) { + next = 0.0; + } + else { + next -= (next > 0.0 ? 1.0 : -1.0) * friction * Dt; + } + auto const reversals{item.body.reversals()}; + item.body.step(Dt, 0.5 * (item.speed + next) * Dt, next, ballast, ends[index]); + item.speed = (item.body.reversals() - reversals) % 2 != 0 ? -next : next; + moving |= (false == item.body.at_rest()); + } + if (false == moving) { + break; + } + } + return train; +} + +// a train of four coaches at 133 km/h overturning out of the curve to the left, the leading one ploughing into the +// ground; each scattered by the seed, or none of them +std::vector> overturning_train(std::uint32_t const Seed, bool const Scattered = true) { + std::vector> starts; + for (int index = 0; index < 4; ++index) { + auto start{leaving(133.0 * kmh, dm::cause::overturned, 1, 2.0 * eu07_tipping)}; + // one after the other along the way they leave the track + auto const angle{dm::departure_angle(start.reason, start.speed, start.acceleration)}; + start.position = -index * coach().length * glm::dvec3{std::sin(angle), 0.0, std::cos(angle)}; + auto scatter{Scattered ? dm::draw_scatter(dm::seed_of(Seed, std::format("coach{}", index))) : dm::scatter{}}; + if (index == 0 && Scattered) { + // the leading one ploughs into the ground: held back harder all the way, the ones behind push into it + scatter.friction_front *= 1.5; + scatter.friction_rear *= 1.5; + } + starts.emplace_back(start, scatter); + } + return starts; +} + +// the bends between the bodies of the train, from the front [rad] +std::vector bends(std::vector const &Train) { + std::vector result; + for (std::size_t index = 0; index + 1 < Train.size(); ++index) { + result.push_back(std::remainder(Train[index + 1].body.yaw() - Train[index].body.yaw(), 2.0 * std::numbers::pi)); + } + return result; +} + +std::string described(std::vector const &Train) { + std::string result; + for (auto const &item : Train) { + result += std::format(" [{:.1f} m along, {:+.1f} m across, yaw {:+.1f} deg]", item.body.along(), item.body.across(), item.body.yaw() / degree); + } + return result; +} + +} // namespace + +TEST_CASE("derail motion: the buffers and the coupling of two ends") { + // two ends facing each other, the second 10 degrees to the left of the axis of the first, the buffers pressed 20 mm + dm::end_point const first{glm::dvec3{0.0, 1.0, 0.0}, glm::dvec3{0.0, 0.0, 1.0}}; + auto const angle{10.0 * degree}; + dm::end_point const second{glm::dvec3{0.0, 1.0, -0.02}, -glm::dvec3{std::sin(angle), 0.0, std::cos(angle)}}; + auto const pressed{dm::meet(first, second)}; + CHECK(pressed.bend == doctest::Approx(angle)); + CHECK(pressed.gap == doctest::Approx(-0.02 * std::cos(0.5 * angle))); + CHECK(pressed.overlap == doctest::Approx(1.0)); + // the push of the buffers: against the bisector of the bend, through the inner buffer (to the left); less far out + // once the push is more than a buffer takes + auto const light{dm::force_on(pressed, 200e3)}; + CHECK(light.force.z == doctest::Approx(-200e3 * std::cos(0.5 * angle))); + CHECK(light.force.x == doctest::Approx(-200e3 * std::sin(0.5 * angle))); + CHECK(light.point.x == doctest::Approx(dm::buffer_half_spacing * std::cos(0.5 * angle)).epsilon(1e-3)); + auto const heavy{dm::force_on(pressed, 4.0 * dm::buffer_limit)}; + CHECK(heavy.point.x == doctest::Approx(0.25 * dm::buffer_half_spacing * std::cos(0.5 * angle)).epsilon(1e-3)); + // a body lower by a buffer head misses the buffers of the other one: the push goes through the middle of the beams + dm::end_point low{second}; + low.point.y -= dm::buffer_head; + CHECK(dm::force_on(dm::meet(first, low), 200e3).point.x == doctest::Approx(0.0)); + // the coupling pulls towards the other beam, taken 1 m to the side + dm::end_point aside{second}; + aside.point = glm::dvec3{1.0, 1.0, 0.5}; + auto const pulled{dm::meet(first, aside)}; + CHECK(pulled.gap == doctest::Approx(std::hypot(1.0, 0.5)).epsilon(0.1)); + auto const pull{dm::force_on(pulled, -100e3)}; + CHECK(pull.force.x == doctest::Approx(100e3 / std::hypot(1.0, 0.5))); + // gone past each other side by side: the coupling stretched + aside.point = glm::dvec3{3.0, 1.0, -5.0}; + CHECK(dm::meet(first, aside).gap > 5.0); + // a body turned about, its end facing the same way as the first one, 5 m behind it: they don't press each other + dm::end_point const about{glm::dvec3{0.0, 1.0, -5.0}, glm::dvec3{0.0, 0.0, 1.0}}; + CHECK(dm::meet(first, about).gap == doctest::Approx(5.0)); +} + +TEST_CASE("derail motion: the yaw of the body") { + auto shape{eu07()}; + shape.mass = 80e3; + SUBCASE("a push off the middle turns it, the friction under it holds it against a small one") { + for (auto const side : {1.0, -1.0}) { + CAPTURE(side); + dm::body body; + body.begin(leaving(0.0, dm::cause::off_rails), shape, ballast); + // 300 kN across at the front end, to the Side: it turns its front that way + std::array ends{}; + ends[0] = dm::end_force{glm::dvec3{side * 300e3, 0.0, 0.0}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + for (int step = 0; step < 50; ++step) { + body.step(0.01, 0.0, 0.0, ballast, ends); + } + CHECK(body.yaw_rate() * side > 0.0); + CHECK(body.yaw() * side > 0.0); + // through the middle along the body it doesn't turn it + dm::body straight; + straight.begin(leaving(0.0, dm::cause::off_rails), shape, ballast); + ends[0] = dm::end_force{glm::dvec3{0.0, 0.0, -300e3}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + straight.step(0.5, 0.0, 0.0, ballast, ends); + CHECK(straight.yaw() == 0.0); + // 30 kN across: the friction holds it, once it stands on the ground + dm::flat_ground const rails{0.0}; + dm::body held; + held.begin(leaving(0.0, dm::cause::off_rails), shape, rails); + ends[0] = dm::end_force{glm::dvec3{side * 30e3, 0.0, 0.0}, glm::dvec3{0.0, 1.0, 0.5 * shape.length}}; + held.step(0.5, 0.0, 0.0, rails, ends); + CHECK(held.yaw() == 0.0); + CHECK(held.at_rest()); + } + } + SUBCASE("the friction under it stops the turning, sliding or standing") { + for (auto const speed : {0.0, 30.0}) { + CAPTURE(speed); + dm::scatter spin; + spin.yaw_rate = 0.5; + dm::body body; + body.begin(leaving(speed, dm::cause::off_rails), shape, ballast, spin); + auto current{speed}; + auto most{0.0}; + auto halfway{0.0}; + for (int step = 0; step < 3000 && false == body.at_rest(); ++step) { + auto const next{std::max(0.0, current - dm::gravity * body.friction() * 0.01)}; + body.step(0.01, 0.5 * (current + next) * 0.01, next, ballast); + if (current > 0.5 * speed && next <= 0.5 * speed) { + halfway = body.yaw_rate(); + } + current = next; + most = std::max(most, std::abs(body.yaw_rate())); + } + MESSAGE(std::format("set turning at 0.5 rad/s at {:.0f} m/s: turned {:.1f} deg", speed, body.yaw() / degree)); + CHECK(body.at_rest()); + CHECK(body.yaw_rate() == 0.0); + // it never turns faster than it was set to + CHECK(most <= 0.5 + 1e-9); + CHECK(body.yaw() > 0.0); + // standing it stops within a turn of a few degrees; sliding fast, little holds it (the friction under it goes + // almost all against the way it slides), it slows the turning as it slows down + if (speed > 0.0) { + CHECK(halfway < 0.4); + CHECK(body.yaw() < 180.0 * degree); + } + else { + CHECK(body.yaw() < 15.0 * degree); + } + } + } + SUBCASE("a body going askew slides harder, and the way it goes turns to the body") { + dm::scatter askew; + askew.yaw = 20.0 * degree; + dm::body body; + body.begin(leaving(30.0, dm::cause::off_rails), shape, ballast, askew); + CHECK(body.friction() > dr::off_rails_friction); + CHECK(body.friction() < dm::lateral_friction); + auto const before{std::abs(std::remainder(std::atan2(body.heading().x, body.heading().z) - body.yaw(), 2.0 * std::numbers::pi))}; + auto current{30.0}; + for (int step = 0; step < 100; ++step) { + auto const next{current - dm::gravity * body.friction() * 0.01}; + body.step(0.01, 0.5 * (current + next) * 0.01, next, ballast); + current = next; + } + auto const after{std::abs(std::remainder(std::atan2(body.heading().x, body.heading().z) - body.yaw(), 2.0 * std::numbers::pi))}; + CHECK(after < before); + } +} + +TEST_CASE("derail motion: a train off the track pushed from behind folds into a zigzag") { + // the leading one held back harder, the ones behind push into it: a chaotic matter, so over eight seeds most of the + // trains fold, and the folds next to each other turn opposite ways + auto foldedtrains{0}; + auto pairs{0}; + auto zigzags{0}; + for (std::uint32_t seed = 1; seed <= 8; ++seed) { + CAPTURE(seed); + auto const train{run_train(overturning_train(seed), coach())}; + auto const bent{bends(train)}; + MESSAGE((std::format("seed {} at rest:", seed) + described(train))); + for (auto const &item : train) { + CHECK(item.body.at_rest()); + } + auto folds{0}; + for (std::size_t index = 0; index < bent.size(); ++index) { + if (std::abs(bent[index]) > 10.0 * degree) { + ++folds; + if (index + 1 < bent.size() && std::abs(bent[index + 1]) > 10.0 * degree) { + ++pairs; + zigzags += (bent[index] * bent[index + 1] < 0.0 ? 1 : 0); + } + } + } + foldedtrains += (folds > 0 ? 1 : 0); + } + MESSAGE(std::format("{} of 8 trains folded, {} of {} neighbouring folds turn opposite ways", foldedtrains, zigzags, pairs)); + CHECK(foldedtrains >= 4); + CHECK(pairs >= 2); + CHECK(zigzags * 4 >= pairs * 3); + SUBCASE("without the bite and the scatter it stays in line") { + auto const straight{run_train(overturning_train(1, false), coach())}; + MESSAGE((std::string{"unscattered at rest:"} + described(straight))); + for (auto const bend : bends(straight)) { + CHECK(std::abs(bend) < 1.0 * degree); + } + } +} + +TEST_CASE("derail motion: the scatter") { + SUBCASE("the same seed, the same scatter; another seed, another one") { + auto const one{dm::draw_scatter(dm::seed_of(7, "coach1"))}; + auto const again{dm::draw_scatter(dm::seed_of(7, "coach1"))}; + auto const other{dm::draw_scatter(dm::seed_of(8, "coach1"))}; + auto const next{dm::draw_scatter(dm::seed_of(7, "coach2"))}; + CHECK(one.departure == again.departure); + CHECK(one.friction_front == again.friction_front); + CHECK(one.dig_in == again.dig_in); + CHECK(one.yaw != other.yaw); + CHECK(one.yaw != next.yaw); + auto bites{0}; + for (std::uint32_t seed = 0; seed < 300; ++seed) { + auto const scatter{dm::draw_scatter(seed)}; + CHECK(std::abs(scatter.departure) <= 0.01); + CHECK(std::abs(scatter.yaw) <= 0.02); + CHECK(std::abs(scatter.yaw_rate) <= 0.02); + CHECK(scatter.friction_front >= 0.85); + CHECK(scatter.friction_rear <= 1.15); + CHECK((scatter.dig_in < 0.0 || (scatter.dig_in >= 0.2 && scatter.dig_in <= 1.5))); + bites += (scatter.dig_in >= 0.0 ? 1 : 0); + } + CHECK(bites > 150); + CHECK(bites < 250); + } + SUBCASE("the train: the same seed, the same way; another seed, another way") { + auto const one{bends(run_train(overturning_train(1), coach()))}; + auto const again{bends(run_train(overturning_train(1), coach()))}; + auto const othertrain{run_train(overturning_train(2), coach())}; + auto const other{bends(othertrain)}; + MESSAGE((std::string{"seed 2 at rest:"} + described(othertrain))); + CHECK(one == again); + auto apart{0.0}; + for (std::size_t index = 0; index < one.size(); ++index) { + apart = std::max(apart, std::abs(one[index] - other[index])); + } + MESSAGE(std::format("the bends of seed 1 and seed 2 differ by {:.1f} deg at most", apart / degree)); + CHECK(apart > 2.0 * degree); + } + SUBCASE("the same with steps of 0.01, 0.03 and 0.05 s") { + auto starts{overturning_train(3)}; + starts.resize(1); + auto const fine{run_train(starts, coach(), 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{run_train(starts, coach(), dt)}; + CHECK(coarse[0].body.travelled() == doctest::Approx(fine[0].body.travelled()).epsilon(0.02)); + CHECK(coarse[0].body.across() == doctest::Approx(fine[0].body.across()).epsilon(0.05)); + CHECK(coarse[0].body.yaw() == doctest::Approx(fine[0].body.yaw()).epsilon(0.05)); + } + } +} + +// ---- the bodies running into each other + +namespace { + +// a body off the track and the speed its vehicle goes with along its heading, as physics::Vehicle keeps it +struct slider { + dm::body body; + double speed{0.0}; +}; + +dm::footprint print_of(dm::body const &Body) { + return dm::footprint_of(Body.current(), Body.shape().length, Body.shape().width, Body.shape().height); +} + +dm::contact_body contact_of(dm::body const &Body) { + dm::contact_body result; + result.mass = Body.shape().mass; + result.base = Body.base(); + result.velocity = Body.velocity(); + result.yaw_rate = Body.yaw_rate(); + result.gyration = Body.gyration(); + return result; +} + +// the kinetic energy of the body per its motion along and about the vertical [J] +double energy_of(dm::contact_body const &Body) { + return 0.5 * Body.mass * (glm::dot(Body.velocity, Body.velocity) + Body.gyration * Body.yaw_rate * Body.yaw_rate); +} + +// the hit of two bodies as vehicle_table::update_off_track_contacts() takes it: the impulse, the kick of each, the two +// moved apart by the overlap; the depth of it [m] +double touch(slider &First, slider &Second) { + auto const hit{dm::collide(print_of(First.body), print_of(Second.body))}; + if (false == hit.has_value()) { + return 0.0; + } + auto const first{contact_of(First.body)}; + auto const second{contact_of(Second.body)}; + auto const impulse{dm::contact_impulse(*hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit->point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit->point)}; + if (glm::length(impulse) > 0.0) { + First.body.kick(velocity, yawrate); + First.speed = First.body.speed(); + Second.body.kick(othervelocity, otheryawrate); + Second.speed = Second.body.speed(); + } + auto const correction{dm::contact_correction * std::max(0.0, hit->depth - dm::contact_slop)}; + First.body.nudge(-hit->normal * (0.5 * correction)); + Second.body.nudge(hit->normal * (0.5 * correction)); + return hit->depth; +} + +void slide_on(slider &Item, double const Dt) { + auto const friction{dm::gravity * Item.body.friction()}; + auto next{Item.speed}; + if (std::abs(next) <= friction * Dt) { + next = 0.0; + } + else { + next -= (next > 0.0 ? 1.0 : -1.0) * friction * Dt; + } + auto const reversals{Item.body.reversals()}; + Item.body.step(Dt, 0.5 * (Item.speed + next) * Dt, next, ballast); + Item.speed = (Item.body.reversals() - reversals) % 2 != 0 ? -next : next; +} + +struct hit_outcome { + double most{0.0}; // the deepest the two went into each other [m] + double resting{0.0}; // at rest + double furthest{0.0}; // the furthest the first one got along +z [m] + glm::dvec3 first{0.0}; // where the bodies came to rest + glm::dvec3 second{0.0}; + double second_yaw{0.0}; +}; + +// a coach upright at Speed along +z into another one standing Distance ahead of it, turned by the Angle, offset +// Across; the step Dt +hit_outcome run_into(double const Speed, double const Angle, double const Across = 0.0, double const Dt = 0.01, double const Distance = 40.0) { + slider first; + first.body.begin(leaving(Speed, dm::cause::end_of_track), coach(), ballast); + first.speed = Speed; + slider second; + auto standing{leaving(0.0, dm::cause::end_of_track)}; + standing.position = glm::dvec3{Across, 0.0, Distance}; + standing.front = glm::dvec3{std::sin(Angle), 0.0, std::cos(Angle)}; + second.body.begin(standing, coach(), ballast); + hit_outcome result; + for (int step = 0; step * Dt < 30.0; ++step) { + result.most = std::max(result.most, touch(first, second)); + slide_on(first, Dt); + slide_on(second, Dt); + result.furthest = std::max(result.furthest, first.body.base().z); + if (first.body.at_rest() && second.body.at_rest()) { + break; + } + } + result.resting = touch(first, second); + result.first = first.body.base(); + result.second = second.body.base(); + result.second_yaw = second.body.yaw(); + return result; +} + +} // namespace + +TEST_CASE("derail motion: the footprint of a body and two bodies in each other") { + dm::pose upright; + auto const print{dm::footprint_of(upright, 24.5, 2.8, 4.0)}; + CHECK(print.half_length == doctest::Approx(12.25 - dm::buffer_length)); + CHECK(print.half_width == doctest::Approx(1.4)); + CHECK(print.low == doctest::Approx(0.0)); + CHECK(print.high == doctest::Approx(4.0)); + // on its side to the left: as wide on the ground as it is high, all of it to the left, as low as it is wide + dm::pose lying; + lying.left = glm::dvec3{0.0, -1.0, 0.0}; + lying.up = glm::dvec3{1.0, 0.0, 0.0}; + lying.position = glm::dvec3{0.0, 1.4, 0.0}; + auto const side{dm::footprint_of(lying, 24.5, 2.8, 4.0)}; + CHECK(side.half_width == doctest::Approx(2.0)); + CHECK(side.centre.x == doctest::Approx(2.0)); + CHECK(side.high - side.low == doctest::Approx(2.8)); + // side by side 2.5 m apart: 0.3 m in each other, out of the first to the left (+x) + auto beside{print}; + beside.centre.x = 2.5; + auto const hit{dm::collide(print, beside)}; + REQUIRE(hit.has_value()); + CHECK(hit->depth == doctest::Approx(0.3)); + CHECK(hit->normal.x == doctest::Approx(1.0)); + // apart, or one over the other: no contact + beside.centre.x = 3.0; + CHECK_FALSE(dm::collide(print, beside).has_value()); + beside.centre.x = 2.5; + beside.low = 3.9; + beside.high = 7.0; + CHECK_FALSE(dm::collide(print, beside).has_value()); + // the lying one beside the upright one, low as it is: they hit + CHECK(dm::collide(print, side).has_value()); +} + +TEST_CASE("derail motion: an impulse never adds energy") { + // two bodies meeting at all kinds of points and angles, turning or not, one of them on the rails or not + auto worst{-1e9}; + for (int index = 0; index < 400; ++index) { + auto const draw = [index](int Which) { return std::sin(index * 12.9898 + Which * 78.233) * 0.5 + 0.5; }; + dm::contact hit; + auto const angle{draw(1) * 2.0 * std::numbers::pi}; + hit.normal = glm::dvec3{std::cos(angle), 0.0, std::sin(angle)}; + hit.point = glm::dvec3{draw(2) * 20.0 - 10.0, 0.0, draw(3) * 6.0 - 3.0}; + hit.depth = 0.1; + dm::contact_body first{40e3, glm::dvec3{0.0}, glm::dvec3{draw(4) * 40.0 - 20.0, 0.0, draw(5) * 40.0 - 20.0}, draw(6) - 0.5, 50.0}; + dm::contact_body second{80e3, glm::dvec3{draw(7) * 6.0, 0.0, draw(8) * 6.0}, glm::dvec3{draw(9) * 10.0 - 5.0, 0.0, 0.0}, draw(10) - 0.5, 22.0}; + if (index % 3 == 0) { + second.guided = true; + second.guide = glm::dvec3{1.0, 0.0, 0.0}; + second.yaw_rate = 0.0; + } + auto const before{energy_of(first) + energy_of(second)}; + auto const impulse{dm::contact_impulse(hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit.point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit.point)}; + first.velocity += velocity; + first.yaw_rate += yawrate; + second.velocity += othervelocity; + second.yaw_rate += otheryawrate; + auto const after{energy_of(first) + energy_of(second)}; + worst = std::max(worst, after - before); + CHECK(after <= before * (1.0 + 1e-9) + 1e-6); + } + MESSAGE(std::format("the most energy an impulse added: {:.3g} J", worst)); +} + +TEST_CASE("derail motion: a body running into another one doesn't go through it") { + SUBCASE("head on into the side of one standing across: it stops at it, pushes it, never through") { + auto const result{run_into(20.0, 0.5 * std::numbers::pi)}; + MESSAGE(std::format("at 20 m/s into the side of a coach: {:.2f} m in at most, {:.3f} m at rest, its front got to z {:.1f} (the side of the other at {:.1f}), the other pushed to z {:.1f}", result.most, result.resting, result.furthest + 0.5 * coach().length, 40.0 - 0.5 * coach().width, result.second.z)); + CHECK(result.most < 0.6); + CHECK(result.resting < 0.05); + // the first one stays behind the other one: its middle never gets past the other's + CHECK(result.furthest < result.second.z); + // the other one is pushed on + CHECK(result.second.z > 40.5); + } + SUBCASE("glancing off the end of one standing in line, offset: it goes past it, pushed aside, not into it") { + auto const result{run_into(15.0, 0.0, 2.0)}; + MESSAGE(std::format("at 15 m/s, 2 m aside, into the end of a coach: {:.2f} m in at most, {:.3f} m at rest; at rest {:.1f} m apart across", result.most, result.resting, std::abs(result.second.x - result.first.x))); + CHECK(result.resting < 0.05); + CHECK(result.most < 0.6); + } + SUBCASE("the same with steps of 0.01, 0.03 and 0.05 s") { + auto const fine{run_into(20.0, 0.5 * std::numbers::pi, 0.0, 0.01)}; + for (auto const dt : {0.03, 0.05}) { + CAPTURE(dt); + auto const coarse{run_into(20.0, 0.5 * std::numbers::pi, 0.0, dt)}; + CHECK(coarse.second.z == doctest::Approx(fine.second.z).epsilon(0.03)); + CHECK(coarse.first.z == doctest::Approx(fine.first.z).epsilon(0.03)); + CHECK(coarse.resting < 0.05); + } + } +} + +TEST_CASE("derail motion: two bodies folded past a right angle stay apart") { + // a coach turned 100 degrees off the next one, their ends together at the joint (in each other by a metre at the + // start), sliding on: they push apart within half a second, at rest not in each other + slider first; + auto start{leaving(10.0, dm::cause::end_of_track)}; + first.body.begin(start, coach(), ballast); + first.speed = 10.0; + slider second; + auto const angle{100.0 * degree}; + auto other{leaving(5.0, dm::cause::end_of_track)}; + // its front end at the rear end of the first one, folded to the left + glm::dvec3 const front{std::sin(angle), 0.0, std::cos(angle)}; + other.front = front; + other.position = glm::dvec3{0.0, 0.0, -0.5 * coach().length} - front * (0.5 * coach().length - 1.0); + second.body.begin(other, coach(), ballast); + second.speed = 5.0; + auto most{0.0}; + for (int step = 0; step < 2000; ++step) { // 20 s in steps of 0.01 s + auto const depth{touch(first, second)}; + if (step > 50) { // after half a second + most = std::max(most, depth); + } + slide_on(first, 0.01); + slide_on(second, 0.01); + } + auto const resting{touch(first, second)}; + MESSAGE(std::format("folded 100 degrees: {:.2f} m in at most after half a second, {:.3f} m at rest", most, resting)); + CHECK(resting < 0.05); + CHECK(most < 0.1); +} + +TEST_CASE("derail motion: a body hitting one on the rails from the side") { + // a coach off the track at 10 m/s into the side of one standing on the rails (along x): the one on the rails takes + // none of it along them, the first stops against it (bounces off), and the push across the rails is over what + // its wheels hold + dm::contact hit; + hit.normal = glm::dvec3{0.0, 0.0, 1.0}; + hit.point = glm::dvec3{0.0, 0.0, 0.0}; + hit.depth = 0.05; + dm::contact_body first{40e3, glm::dvec3{0.0, 0.0, -10.0}, glm::dvec3{0.0, 0.0, 10.0}, 0.0, 50.0}; + dm::contact_body second{40e3, glm::dvec3{0.0, 0.0, 1.4}, glm::dvec3{0.0}, 0.0, 50.0, true, glm::dvec3{1.0, 0.0, 0.0}}; + auto const impulse{dm::contact_impulse(hit, first, second)}; + auto const [velocity, yawrate]{dm::impulse_change(first, -impulse, hit.point)}; + auto const [othervelocity, otheryawrate]{dm::impulse_change(second, impulse, hit.point)}; + CHECK(glm::length(othervelocity) == doctest::Approx(0.0)); + CHECK(first.velocity.z + velocity.z == doctest::Approx(-10.0 * dm::contact_restitution)); + // the push across the rails over a frame of 0.05 s against the wheels of a coach of 40 t on 4 axles + auto const ratio{dm::pull_ratio(std::abs(impulse.z) / 0.05, 0.5 * std::numbers::pi, 40e3, 4)}; + MESSAGE(std::format("the hit across the rails at 10 m/s: Y/Q {:.1f}", ratio)); + CHECK(ratio > 3.0 * dr::climbing_limit); + // a hit at an angle along the rails pushes it along them + hit.normal = glm::normalize(glm::dvec3{1.0, 0.0, 1.0}); + first.velocity = glm::dvec3{10.0, 0.0, 10.0}; + auto const slanted{dm::contact_impulse(hit, first, second)}; + CHECK(dm::impulse_change(second, slanted, hit.point).first.x > 0.5); +} diff --git a/tests/unit/test_derailment.cpp b/tests/unit/test_derailment.cpp new file mode 100644 index 000000000..cb23a5c5e --- /dev/null +++ b/tests/unit/test_derailment.cpp @@ -0,0 +1,501 @@ +#include "stdafx.h" +#include "doctest.h" +#include "physics/derailment.h" + +#include +#include + +// the criteria of derailment (physics/derailment.h): overturning by the lateral acceleration the cant doesn't +// balance, the flange climbing the rail by Nadal's Y/Q, either held over 2 m + +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the cant [rad] of the height of the outer rail [mm] on the standard gauge +double cant(double const Millimetres) { + return std::asin(Millimetres / 1000.0 / dr::contact_spacing(1.435)); +} + +// the centres of gravity the vehicles of data/fiz get without a CoGH of their own +// EU07 (4E): 80 t, a body 4.348 m high +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +// the 430W coal wagon: 20.5 t, a body 3.235 m high, 59.5 t of coal +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; +double const coal_wagon_loaded{dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 59500.0, 1.0, 0.0, 3.235)}; + +} // namespace + +TEST_CASE("derailment: Nadal's limit of Y/Q") { + // 70 degrees of the flange: 1.34 with a friction of 0.3, 1.2 with 0.36, the limit the criterion takes + CHECK(dr::nadal_limit(dr::flange_angle, 0.3) == doctest::Approx(1.342).epsilon(0.001)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.36) == doctest::Approx(dr::climbing_limit).epsilon(0.01)); + // a steeper flange holds more, a higher friction less + CHECK(dr::nadal_limit(dr::flange_angle + 0.05, 0.3) > dr::nadal_limit(dr::flange_angle, 0.3)); + CHECK(dr::nadal_limit(dr::flange_angle, 0.5) < dr::nadal_limit(dr::flange_angle, 0.3)); +} + +TEST_CASE("derailment: the centre of gravity") { + CHECK(eu07 == doctest::Approx(1.65).epsilon(0.01)); + CHECK(coal_wagon == doctest::Approx(1.13).epsilon(0.01)); + // the load raises it: a full coal wagon is near 2 m, the limit of the railways for a loaded wagon is 2 to 2.5 m + CHECK(coal_wagon_loaded == doctest::Approx(1.94).epsilon(0.01)); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) > coal_wagon); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 30000.0, 0.5, 0.0, 3.235) < coal_wagon_loaded); + CHECK(dr::loaded_centre_of_gravity(coal_wagon, 20500.0, 0.0, 0.0, 0.0, 3.235) == coal_wagon); + // a body height of 2 m or less is the floor, the older meaning of the key: a 4 m high body then + CHECK(dr::default_centre_of_gravity(1.2, dr::vehicle_class::unpowered) == doctest::Approx(1.4)); +} + +TEST_CASE("derailment: the overturning speed by the radius and the cant") { + struct expected { + char const *vehicle; + double centre; + double radius; + double cant; // mm + double speed; // km/h + }; + // EU07 overturns at 108 km/h in a 300 m curve without cant, as the legacy criterion had it near 112 km/h; at + // 119 km/h with a cant of 100 mm. a full coal wagon at 98 km/h, an empty one at 137 km/h + for (auto const &[name, centre, radius, height, speed] : { + expected{"EU07", eu07, 150.0, 0.0, 77.6}, + expected{"EU07", eu07, 300.0, 0.0, 107.8}, + expected{"EU07", eu07, 300.0, 100.0, 119.0}, + expected{"EU07", eu07, 600.0, 150.0, 175.8}, + expected{"430W empty", coal_wagon, 300.0, 0.0, 136.9}, + expected{"430W empty", coal_wagon, 300.0, 100.0, 145.9}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 0.0, 97.5}, + expected{"430W loaded", coal_wagon_loaded, 300.0, 100.0, 109.6}, + expected{"430W loaded", coal_wagon_loaded, 1200.0, 150.0, 230.5}, + }) { + CAPTURE(name); + CAPTURE(radius); + CAPTURE(height); + CHECK(dr::overturning_speed(radius, cant(height), centre, 1.435) / kmh == doctest::Approx(speed).epsilon(0.002)); + } + // on the faster side of 100 km/h, where the vibration is all there: v^2 / R - g sin(cant) + 0.05 g = g s / 2 h' + auto const leaning{eu07 + 0.4 * (eu07 - 0.5)}; + auto const limit{dr::gravity * 1.5 / (2.0 * leaning)}; + CHECK(dr::overturning_acceleration(eu07, 1.5) == doctest::Approx(limit)); + auto const speed{std::sqrt((limit - dr::vibration + dr::gravity * std::sin(cant(100.0))) * 300.0)}; + CHECK(dr::overturning_speed(300.0, cant(100.0), eu07, 1.435) == doctest::Approx(speed).epsilon(0.001)); + // the legacy criterion, the lateral acceleration over g times the gauge to the height of the vehicle, without cant + auto const legacy{std::sqrt(dr::gravity * 1.435 / 4.348 * 300.0)}; + CHECK(dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(legacy).epsilon(0.05)); + // faster on a wider curve, as its square root + CHECK(dr::overturning_speed(1200.0, 0.0, eu07, 1.435) / dr::overturning_speed(300.0, 0.0, eu07, 1.435) == doctest::Approx(2.0).epsilon(0.001)); + // the cant only helps + CHECK(dr::overturning_speed(300.0, cant(150.0), eu07, 1.435) > dr::overturning_speed(300.0, cant(60.0), eu07, 1.435)); + // no overturning on a straight track + CHECK(dr::overturning_speed(0.0, 0.0, eu07, 1.435) == 0.0); +} + +TEST_CASE("derailment: below the balancing speed the cant leans the vehicle into the curve") { + // 100 mm on the 1.5 m between the contact points of the wheels + CHECK(dr::unbalanced_acceleration(0.0, 300.0, cant(100.0)) == doctest::Approx(-dr::gravity * 0.1 / 1.5)); + // at the balancing speed nothing's left + auto const balanced{std::sqrt(dr::gravity * 0.1 / 1.5 * 300.0)}; + CHECK(dr::unbalanced_acceleration(balanced, 300.0, cant(100.0)) == doctest::Approx(0.0).epsilon(1e-9)); + // the sign of the radius and of the cant doesn't matter + CHECK(dr::unbalanced_acceleration(30.0, -300.0, -cant(100.0)) == doctest::Approx(dr::unbalanced_acceleration(30.0, 300.0, cant(100.0)))); +} + +TEST_CASE("derailment: the decision and the place don't depend on the step") { + // EU07 runs at a steady speed into a 300 m curve without cant 100 m ahead, the track checked at the end of each step + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.axles = 4; + eu07vehicle.length = 15.915; + eu07vehicle.axle_base = 3.05; + eu07vehicle.centre_of_gravity = eu07; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435)}; + constexpr double curve{100.0}; + + // where the vehicle overturns, if it does within 400 m + auto const run = [&](double const Speed, double const Step) -> std::optional { + dr::monitor monitor; + dr::track_state track; + auto distance{0.0}; + while (distance < 400.0) { + auto const travelled{Speed * Step}; + distance += travelled; + track.radius = distance >= curve ? 300.0 : 0.0; + if (monitor.update(eu07vehicle, track, Speed, travelled).result == dr::outcome::overturned) { + return distance; + } + } + return std::nullopt; + }; + + for (auto const step : {0.01, 0.05, 0.5}) { + CAPTURE(step); + // 5 % too fast: overturns 2 m into the curve, give or take the step it got there in + auto const fast{run(1.05 * critical, step)}; + REQUIRE(fast.has_value()); + CHECK(*fast >= curve + dr::window - 1.05 * critical * step - 1e-6); + CHECK(*fast <= curve + dr::window + 1.05 * critical * step + 1e-6); + // 5 % below it: never + CHECK_FALSE(run(0.95 * critical, step).has_value()); + } + auto const fine{run(1.05 * critical, 0.01)}; + auto const coarse{run(1.05 * critical, 0.5)}; + REQUIRE(fine.has_value()); + REQUIRE(coarse.has_value()); + CHECK(std::abs(coarse.value() - fine.value()) <= 1.05 * critical * 0.5); +} + +TEST_CASE("derailment: a peak shorter than the window doesn't derail") { + dr::stretch stretch; + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK_FALSE(stretch.update(false, 0.5)); + CHECK_FALSE(stretch.update(true, 1.5)); + CHECK(stretch.update(true, 0.5)); + CHECK(stretch.distance() == doctest::Approx(2.0)); +} + +TEST_CASE("derailment: a vehicle without a mass never derails") { + // a definition without M (or with all of it in the rotating masses) gives no forces, not a lifted wheel + dr::vehicle_state massless; + massless.mass = 0.0; + dr::track_state track; + track.radius = 150.0; + CHECK(dr::flange_forces(massless, track, 30.0).ratio() == 0.0); + dr::monitor monitor; + for (int step = 0; step < 10; ++step) { + CHECK(monitor.update(massless, track, 30.0, 1.0).result == dr::outcome::none); + } +} + +TEST_CASE("derailment: pushing a light wagon between heavy vehicles in a curve") { + // the empty 3WL (10.5 t, 2 axles 6 m apart, 9.87 m long) between two EU07 in a 150 m curve: the more the train + // pushes, the more the couplings push the wagon out of the curve, the higher its Y/Q + dr::vehicle_state wagon; + wagon.mass = 10500.0; + wagon.axles = 2; + wagon.length = 9.87; + wagon.axle_base = 6.0; + wagon.centre_of_gravity = dr::default_centre_of_gravity(3.0, dr::vehicle_class::unpowered); + dr::track_state track; + track.radius = 150.0; + auto const speed{20.0 * kmh}; + + auto const ratio = [&](dr::vehicle_state Vehicle, double const Compression) { + for (auto &end : Vehicle.ends) { + end.compression = Compression; + end.other_length = 15.915; + } + return dr::flange_forces(Vehicle, track, speed).ratio(); + }; + auto previous{ratio(wagon, 0.0)}; + // the leading axle guides the wagon with the friction of its inner wheel: over 0.3 even unpushed + CHECK(previous > dr::tread_friction); + CHECK(previous < 0.4); + for (auto const compression : {100e3, 300e3, 600e3, 1000e3}) { + CAPTURE(compression); + auto const pushed{ratio(wagon, compression)}; + CHECK(pushed > previous); + previous = pushed; + } + // a loaded 430W in its place is pushed out less + dr::vehicle_state loaded; + loaded.mass = 80000.0; + loaded.axles = 4; + loaded.length = 14.028; + loaded.axle_base = 2.0; + loaded.centre_of_gravity = coal_wagon_loaded; + CHECK(ratio(loaded, 600e3) < ratio(wagon, 600e3)); + // pulled, the couplings draw the wagon into the curve: the flange of the inner wheel then + auto pulled{wagon}; + for (auto &end : pulled.ends) { + end.compression = -600e3; + end.other_length = 15.915; + } + CHECK(dr::flange_forces(pulled, track, speed).lateral < 0.0); + // on a twisted track the wheel is lighter, so the same push comes nearer the limit + auto const twisted{[&] { + auto const flat{ratio(wagon, 600e3)}; + track.uneven_cross = 30.0; + auto const result{ratio(wagon, 600e3)}; + track.uneven_cross = 0.0; + return result > flat; + }()}; + CHECK(twisted); + // on a bent rail, with a twist of 50 mm, the wagon pushed with 300 kN climbs the rail over 2 m, without falling over + track.damage = dr::track_damage::railbend; + track.uneven_cross = 50.0; + dr::monitor monitor; + auto pushed{wagon}; + for (auto &end : pushed.ends) { + end.compression = 300e3; + end.other_length = 15.915; + } + CHECK(monitor.update(pushed, track, speed, 1.0).result == dr::outcome::none); + auto const verdict{monitor.update(pushed, track, speed, 1.0)}; + CAPTURE(verdict.flange_ratio); + CAPTURE(verdict.unloading); + CHECK(verdict.unloading < 1.0); + CHECK(verdict.result == dr::outcome::off_rails); +} + +TEST_CASE("derailment: the damage flags of the track make the ride rougher, not the curve sharper") { + // line 107 has damage 31 on every track, for the jolts. a 401Ka wagon creeping at 28 km/h through a 282 m curve + // with a cant of 179 mm, pulled by a freight train, stays on: in the 2026-11-15 run with the flags scaling the + // whole lateral acceleration it overturned into the curve + dr::vehicle_state wagon; + wagon.mass = 23000.0; + wagon.axles = 4; + wagon.length = 14.7; + wagon.axle_base = 1.8; + wagon.centre_of_gravity = dr::default_centre_of_gravity(4.2, dr::vehicle_class::unpowered); + for (auto &end : wagon.ends) { + end.compression = -200e3; + end.other_length = 14.7; + } + dr::track_state track; + track.radius = 282.0; + track.cant = std::asin(0.179 / 1.5); + auto const speed{28.0 * kmh}; + auto const smooth{dr::body_acceleration(wagon, track, speed)}; + track.damage = 31; + auto const rough{dr::body_acceleration(wagon, track, speed)}; + // the sway grows, by what a rough track adds to the sway at that speed + CHECK(rough > smooth); + CHECK(rough - smooth == doctest::Approx(1.1 * dr::body_vibration(speed))); + CHECK(dr::unloading_ratio(rough, wagon.centre_of_gravity, 1.5) < 0.5); + CHECK(dr::flange_forces(wagon, track, speed).ratio() < 0.8); + // at speed the rough track still lowers the overturning speed some, as the legacy criterion's factor did + { + dr::vehicle_state eu07vehicle; + eu07vehicle.mass = 80000.0; + eu07vehicle.centre_of_gravity = eu07; + dr::track_state good; + good.radius = 300.0; + auto worn{good}; + worn.damage = 31; + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) > dr::body_acceleration(eu07vehicle, good, 30.0)); + CHECK(dr::body_acceleration(eu07vehicle, worn, 30.0) - dr::body_acceleration(eu07vehicle, good, 30.0) == doctest::Approx(1.1 * dr::vibration)); + } +} + +TEST_CASE("derailment: the speed the flange climbs the rail at") { + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.axles = 4; + vehicle.length = 16.0; + vehicle.axle_base = 3.0; + vehicle.centre_of_gravity = 1.65; + dr::track_state track; + track.radius = 300.0; + SUBCASE("a lone vehicle on a good track overturns first: its Y/Q stays under the limit") { + CHECK_FALSE(dr::climbing_speed(vehicle, track).has_value()); + } + SUBCASE("on a twisted track it climbs, at the speed Y/Q reaches the limit") { + // 50 mm of cross level takes half the load off the wheel + track.uneven_cross = 50.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed > 0.0); + CHECK(dr::flange_forces(vehicle, track, *speed).ratio() >= dr::climbing_limit); + CHECK(dr::flange_forces(vehicle, track, *speed - 0.01).ratio() < dr::climbing_limit); + SUBCASE("the cant moves it up") { + track.cant = std::asin(0.1 / 1.5); + auto const canted{dr::climbing_speed(vehicle, track)}; + REQUIRE(canted.has_value()); + CHECK(*canted > *speed); + } + } + SUBCASE("pushed hard enough it climbs at a standstill: from the speed the cant balances") { + // an empty 3WL between heavy vehicles pushing 1 MN in a curve of 150 m, on 40 mm of cross level + vehicle.mass = 10500.0; + vehicle.axles = 2; + vehicle.length = 9.0; + vehicle.axle_base = 5.0; + vehicle.centre_of_gravity = 1.1; + vehicle.ends[0] = {1000000.0, 16.0}; + vehicle.ends[1] = {1000000.0, 16.0}; + track.radius = 150.0; + track.uneven_cross = 40.0; + auto const speed{dr::climbing_speed(vehicle, track)}; + REQUIRE(speed.has_value()); + CHECK(*speed == 0.0); + } +} + +TEST_CASE("derailment: the report of the log") { + dr::verdict verdict; + verdict.result = dr::outcome::overturned; + verdict.acceleration = 3.31; + verdict.unloading = 1.02; + verdict.flange_ratio = 0.55; + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.centre_of_gravity = 1.65; + vehicle.ends[1].compression = 50000.0; + dr::track_state track; + track.radius = -300.0; + track.damage = 31; + auto const text{dr::report(verdict, vehicle, track, 113.0 / 3.6, "track_7")}; + CHECK(text == + "overturned at 113 km/h on track track_7, curve radius 300 m, cant 0 mm: lateral acceleration 3.31 m/s2, wheel unloading 1.02, Y/Q 0.55 (mass 80.0 t, centre of gravity 1.65 m," + " couplings pushing 0 / 50 kN, track damage 31, cross level 0 mm)"); + verdict.result = dr::outcome::off_rails; + CHECK(dr::report(verdict, vehicle, track, 20.0, "").starts_with("derailed, the flange climbed the rail at 72 km/h on track (none),")); +} + +// physics.derailment.trustlimits: the speed limit of a track trusted, a verdict of the curve alone under it held back + +namespace { + +// EU07 alone, as the criteria see it +dr::vehicle_state eu07_alone() { + dr::vehicle_state vehicle; + vehicle.mass = 80000.0; + vehicle.axles = 4; + vehicle.length = 15.915; + vehicle.axle_base = 3.05; + vehicle.centre_of_gravity = eu07; + return vehicle; +} + +// the empty 3WL (10.5 t, 2 axles 6 m apart, 9.87 m long) between two EU07, pushed with the force [N] +dr::vehicle_state pushed_wagon(double const Compression) { + dr::vehicle_state wagon; + wagon.mass = 10500.0; + wagon.axles = 2; + wagon.length = 9.87; + wagon.axle_base = 6.0; + wagon.centre_of_gravity = dr::default_centre_of_gravity(3.0, dr::vehicle_class::unpowered); + for (auto &end : wagon.ends) { + end.compression = Compression; + end.other_length = 15.915; + } + return wagon; +} + +// the verdict of the monitor at the steady speed [km/h] once the vehicle ran 3 m on the track +dr::verdict verdict_at(dr::vehicle_state const &Vehicle, dr::track_state const &Track, double const Speed) { + dr::monitor monitor; + dr::verdict verdict; + for (int step = 0; step < 3; ++step) { + verdict = monitor.update(Vehicle, Track, Speed * kmh, 1.0); + } + return verdict; +} + +// what goes of that verdict on a track with the limit [km/h] +dr::outcome limited(dr::vehicle_state const &Vehicle, dr::track_state const &Track, double const Speed, double const Limit) { + auto const verdict{verdict_at(Vehicle, Track, Speed)}; + return dr::limited_verdict(verdict, dr::from_track_alone(verdict, Vehicle, Track, Speed * kmh), Speed * kmh, Limit).result; +} + +} // namespace + +TEST_CASE("derailment: the trusted speed of a speed limit") { + CHECK(dr::trusted_speed(140.0) == doctest::Approx(140.0 * dr::trusted_limit_factor + dr::trusted_limit_margin)); + CHECK(dr::trusted_speed(140.0) == doctest::Approx(159.0)); + CHECK(dr::trusted_speed(40.0) == doctest::Approx(49.0)); + // a closed track (0) is trusted to a crawl, one without a limit not at all + CHECK(dr::trusted_speed(0.0) == doctest::Approx(dr::trusted_limit_margin)); + CHECK_FALSE(dr::trusted_speed(-1.0).has_value()); +} + +TEST_CASE("derailment: a speed limit too high for the curve is trusted up to its trusted speed") { + // a 300 m curve without cant with a limit of 140 km/h, where EU07 overturns at 108 km/h: the data is wrong + auto const vehicle{eu07_alone()}; + dr::track_state track; + track.radius = 300.0; + REQUIRE(dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh < 120.0); + + SUBCASE("at 130 km/h, under the limit, it stays on the rails") { + auto const verdict{verdict_at(vehicle, track, 130.0)}; + REQUIRE(verdict.result == dr::outcome::overturned); + CHECK(dr::from_track_alone(verdict, vehicle, track, 130.0 * kmh)); + auto const held{dr::limited_verdict(verdict, true, 130.0 * kmh, 140.0)}; + CHECK(held.result == dr::outcome::none); + // with the values of the verdict, for the log + CHECK(held.unloading == verdict.unloading); + // and so just under the trusted speed of 159 km/h + CHECK(limited(vehicle, track, 158.5, 140.0) == dr::outcome::none); + } + SUBCASE("at 160 km/h, over the trusted speed, it overturns") { + CHECK(limited(vehicle, track, 160.0, 140.0) == dr::outcome::overturned); + CHECK(limited(vehicle, track, 190.0, 140.0) == dr::outcome::overturned); + } + SUBCASE("a track without a limit isn't trusted") { + CHECK(limited(vehicle, track, 130.0, -1.0) == dr::outcome::overturned); + } + SUBCASE("over a limit the curve takes the verdict goes as it was") { + // 100 km/h: trusted up to 115 km/h + CHECK(limited(vehicle, track, 130.0, 100.0) == dr::outcome::overturned); + CHECK(verdict_at(vehicle, track, 100.0).result == dr::outcome::none); + CHECK(limited(vehicle, track, 100.0, 100.0) == dr::outcome::none); + } + SUBCASE("no verdict stays none") { + dr::verdict none; + CHECK(dr::limited_verdict(none, true, 100.0 * kmh, 140.0).result == dr::outcome::none); + CHECK_FALSE(dr::from_track_alone(none, vehicle, track, 100.0 * kmh)); + } + SUBCASE("the damage flags of line 107 don't take the trust from a curve the speed alone overturns in") { + track.damage = 31; + CHECK(limited(vehicle, track, 130.0, 140.0) == dr::outcome::none); + } + SUBCASE("the log names the track as a defect of the scenery") { + auto const verdict{verdict_at(vehicle, track, 130.0)}; + auto const text{dr::held_back_report(verdict, vehicle, track, 130.0 * kmh, 140.0, "curve_7")}; + CHECK(text.starts_with("held on the rails on track curve_7 under its trusted speed of 159 km/h (speed limit 140 km/h, too high for the curve: a defect of the scenery): " + "overturned at 130 km/h on track curve_7, curve radius 300 m,")); + } +} + +TEST_CASE("derailment: what the couplings, a buckle or the damage of the track bring about goes under any limit") { + SUBCASE("a light wagon pushed hard in a 190 m curve at 60 km/h, with a limit of 60 km/h") { + // pushed with 1 MN the couplings throw it out of the curve, at a speed the curve alone takes + auto const wagon{pushed_wagon(1000e3)}; + dr::track_state track; + track.radius = 190.0; + auto const verdict{verdict_at(wagon, track, 60.0)}; + REQUIRE(verdict.result != dr::outcome::none); + CHECK_FALSE(dr::from_track_alone(verdict, wagon, track, 60.0 * kmh)); + CHECK(limited(wagon, track, 60.0, 60.0) == verdict.result); + // not pushed it runs on + CHECK(verdict_at(pushed_wagon(0.0), track, 60.0).result == dr::outcome::none); + } + SUBCASE("a pushed wagon climbing a bent, twisted rail") { + // as in the case of the pushed light wagon: 300 kN in a 150 m curve at 20 km/h, the rail bent, a twist of 50 mm + auto const wagon{pushed_wagon(300e3)}; + dr::track_state track; + track.radius = 150.0; + track.damage = dr::track_damage::railbend; + track.uneven_cross = 50.0; + auto const verdict{verdict_at(wagon, track, 20.0)}; + REQUIRE(verdict.result == dr::outcome::off_rails); + CHECK_FALSE(dr::from_track_alone(verdict, wagon, track, 20.0 * kmh)); + CHECK(limited(wagon, track, 20.0, 40.0) == dr::outcome::off_rails); + } + SUBCASE("a buckle of a straight track") { + // EU07 at 80 km/h over a buckle bending a straight track with a limit of 100 km/h by 1/150 m + auto const vehicle{eu07_alone()}; + dr::track_state track; + track.buckle_curvature = 1.0 / 150.0; + auto const verdict{verdict_at(vehicle, track, 80.0)}; + REQUIRE(verdict.result == dr::outcome::overturned); + CHECK_FALSE(dr::from_track_alone(verdict, vehicle, track, 80.0 * kmh)); + CHECK(limited(vehicle, track, 80.0, 100.0) == dr::outcome::overturned); + } + SUBCASE("a worn track tipping over a vehicle the curve alone doesn't overturn") { + // 3 km/h under the overturning speed of EU07 on a good track the damage flags of line 107 make the sway + // overturn it: a limit over that speed doesn't hold it on the rails + auto const vehicle{eu07_alone()}; + dr::track_state track; + track.radius = 300.0; + auto const speed{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh - 3.0}; + REQUIRE(verdict_at(vehicle, track, speed).result == dr::outcome::none); + track.damage = 31; + auto const verdict{verdict_at(vehicle, track, speed)}; + REQUIRE(verdict.result == dr::outcome::overturned); + CHECK_FALSE(dr::from_track_alone(verdict, vehicle, track, speed * kmh)); + CHECK(limited(vehicle, track, speed, 140.0) == dr::outcome::overturned); + } +} diff --git a/tests/unit/test_derailment_vehicle.cpp b/tests/unit/test_derailment_vehicle.cpp new file mode 100644 index 000000000..9a3e857f1 --- /dev/null +++ b/tests/unit/test_derailment_vehicle.cpp @@ -0,0 +1,419 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "physics/derailment.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" + +#include + +// a vehicle too fast in a curve with physics.derailment of eu07.ini: the criteria of physics/derailment.h checked by +// physics::Vehicle::check_derailment(), and what the vehicle comes to off the rails + +using test::definition; +using test::vehicle; +namespace dr = derailment; + +namespace { + +constexpr double kmh{1.0 / 3.6}; + +// the given model of derailment for the test, restored after it +class model_setting { +public: + explicit model_setting(global_settings::derailment_model Model) : m_previous{Global.derailment} { Global.derailment = Model; } + ~model_setting() { Global.derailment = m_previous; } + model_setting(model_setting const &) = delete; + model_setting &operator=(model_setting const &) = delete; + +private: + global_settings::derailment_model m_previous; +}; + +// the centres of gravity of EU07 (4E) and of the 430W coal wagon of data/fiz, without a CoGH of their own +double const eu07{dr::default_centre_of_gravity(4.348, dr::vehicle_class::powered)}; +double const coal_wagon{dr::default_centre_of_gravity(3.235, dr::vehicle_class::unpowered)}; + +} // namespace + +TEST_CASE("derailment: a vehicle too fast in a curve") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + + SUBCASE("below the overturning speed it runs on") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->Derailed() == dr::outcome::none); + } + SUBCASE("over it, it falls over and slides to a stop on its side") { + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 5.0}; + CHECK(eu07vehicle->centre_of_gravity() == doctest::Approx(eu07)); + // 2 m at 113 km/h is 0.07 s + for (int step = 0; step < 10; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); + CHECK_FALSE(eu07vehicle->lineBreaker.IsClosed()); + // not stopped dead as the legacy model has it: it slows down at half of g on the 80 of its 96 t + auto const start{eu07vehicle->V()}; + CHECK(start > 0.95 * (critical + 5.0) * kmh); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + auto const deceleration{(start - eu07vehicle->V()) / 1.0}; + CHECK(deceleration == doctest::Approx(0.5 * dr::gravity * 80.0 / 96.0).epsilon(0.05)); + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->V() == doctest::Approx(0.0)); + } + SUBCASE("a higher centre of gravity of its definition overturns it slower") { + vehicle high{definition::fiz("4e_v1/4e").set("Dimensions", "CoGH", 2.2), critical - 5.0}; + CHECK(high->centre_of_gravity() == doctest::Approx(2.2)); + for (int step = 0; step < 50; ++step) { + high.step(curve); + } + CHECK(high->Derailed() == dr::outcome::overturned); + } + SUBCASE("the same with steps of 0.01 and 0.05 s") { + for (auto const dt : {0.01, 0.05}) { + CAPTURE(dt); + auto const steps{static_cast(std::lround(1.0 / dt))}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (auto step = 0; step < steps; ++step) { + eu07vehicle.step(curve, dt); + } + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); + vehicle slower{definition::fiz("4e_v1/4e"), critical - 2.0}; + for (auto step = 0; step < steps; ++step) { + slower.step(curve, dt); + } + CHECK(slower->Derailed() == dr::outcome::none); + } + } + SUBCASE("a load raises the centre of gravity") { + vehicle wagon{definition::fiz("430w_v2/430w")}; + auto const empty{wagon->centre_of_gravity()}; + CHECK(empty == doctest::Approx(coal_wagon)); + wagon->AssignLoad("coal", 59.5f); + wagon->ComputeMass(); + CHECK(wagon->centre_of_gravity() > empty + 0.5); + } +} + +TEST_CASE("derailment: the model of eu07.ini") { + test::track curve; + curve.radius = 300.0; + SUBCASE("off: no derailment at any speed") { + model_setting const off{global_settings::derailment_model::off}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + } + SUBCASE("old: the legacy draw stops the vehicle dead") { + model_setting const old{global_settings::derailment_model::old}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + eu07vehicle.step(curve); + } + // far over its threshold the draw comes out at once + CHECK(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->Derailed() == dr::outcome::none); + CHECK(eu07vehicle->V() == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the brake hoses tear") { + model_setting const physical{global_settings::derailment_model::physical}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + eu07vehicle->Couplers[VehicleEnd::rear].CouplingFlag = Coupling::coupler | Coupling::brakeHose; + test::track curve; + curve.radius = 300.0; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); + CHECK(eu07vehicle->brakes.alarmChain); +} + +TEST_CASE("derailment: a stopped derailed vehicle stays put on a gradient") { + // the friction of the ballast holds it, rather than the vehicle creeping and stopping in turn in every step, which + // kept the physics of its whole train awake (the run of line 107 went at half the speed after a derailment) + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.01; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); + REQUIRE(eu07vehicle->V() == 0.0); + auto still{true}; + for (int step = 0; step < 500; ++step) { + eu07vehicle.step(curve); + still = still && eu07vehicle->V() == 0.0 && eu07vehicle->AccS() == 0.0; + } + CHECK(still); +} + +TEST_CASE("derailment: a repaired vehicle is back on the rails") { + // resetconsist (the debug panel's "Stop and repair consist") clears the damage flags; the state of the criteria + // has to go with them, or a vehicle once derailed by the criteria slides on with their friction after a later + // derailment of any other kind, and the friction of the ballast keeps holding it once it stops + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + curve.gradient = 0.02; + vehicle repaired{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 2000; ++step) { + repaired.step(curve); + } + REQUIRE(repaired->Derailed() == dr::outcome::overturned); + REQUIRE(repaired->V() == 0.0); + repaired->repair_damage(); + CHECK(repaired->DamageFlag.Empty()); + CHECK(repaired->Derailed() == dr::outcome::none); + CHECK(repaired->DerailmentDistance() == 0.0); + CHECK(repaired->OffsetTrackH() == 0.0); + CHECK(repaired->OffsetTrackV() == 0.0); + + SUBCASE("a derailment of the legacy kind stops it dead, as one never derailed") { + test::track straight; + vehicle fresh{definition::fiz("4e_v1/4e"), 60.0}; + repaired->SetV(fresh->V()); + repaired->SetAccS(0.0); + repaired->Derail(TOO_HIGH_SPEED); + fresh->Derail(TOO_HIGH_SPEED); + REQUIRE(repaired->Derailed() == dr::outcome::none); + auto const start{fresh->V()}; + REQUIRE(start > 10.0); + for (int step = 0; step < 150; ++step) { + repaired.step(straight); + fresh.step(straight); + } + // the legacy model takes g off a derailed vehicle and holds it with a friction 1e20 times its own: 1.1 s from + // 39 km/h. with the friction of the overturned one (half of g on 80 of 96 t) it would still go at 23 km/h + CHECK(fresh->V() == doctest::Approx(0.0).epsilon(0.01)); + CHECK(repaired->V() == doctest::Approx(fresh->V()).epsilon(0.01)); + } + SUBCASE("the friction of the ballast doesn't hold it any more") { + // unbraked on the gradient of 20 per mille it rolls away, at g / 50 less the running resistance + test::track straight; + straight.gradient = 0.02; + for (int step = 0; step < 300; ++step) { + repaired.step(straight); + } + CHECK(std::abs(repaired->V()) > 0.4); + CHECK(std::abs(repaired->V()) < 3.0 * 0.02 * dr::gravity); + } + SUBCASE("too fast in a curve again it derails again, by the criteria") { + repaired->SetV(150.0 * kmh); + curve.gradient = 0.0; + for (int step = 0; step < 20; ++step) { + repaired.step(curve); + } + CHECK(repaired->Derailed() == dr::outcome::overturned); + } +} + +TEST_CASE("derailment: SetDamage taking the derailment off puts the vehicle back on the rails") { + model_setting const physical{global_settings::derailment_model::physical}; + test::track curve; + curve.radius = 300.0; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 150.0}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->Derailed() == dr::outcome::overturned); + // another flag taken off leaves it derailed + eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::engine}.Bits(), 1); + eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::engine}.Bits(), -1); + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); + CHECK(eu07vehicle->RunCommand(VehicleCommand::setDamage, DamageSet{VehicleDamage::derailed}.Bits(), -1)); + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->Derailed() == dr::outcome::none); +} + +TEST_CASE("derailment: monitor tells again on the same track after a repair") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + REQUIRE(eu07vehicle->derailment_reports() == 1); + eu07vehicle->repair_damage(); + CHECK_FALSE(eu07vehicle->derailment_reported.has_value()); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->derailment_reports() == 2); +} + +TEST_CASE("derailment: monitor, the legacy draw decides and the log tells what the criteria would do") { + model_setting const monitor{global_settings::derailment_model::monitor}; + test::track curve; + curve.radius = 300.0; + curve.name = "curve_1"; + auto const critical{dr::overturning_speed(300.0, 0.0, eu07, 1.435) / kmh}; + // over the speed the criteria overturn the EU07 at, under the threshold of the legacy draw (112 km/h) + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), critical + 2.0}; + REQUIRE(critical + 2.0 < 112.0); + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->Derailed() == dr::outcome::none); + // once on a track, however long it stays over the criteria + CHECK(eu07vehicle->derailment_reports() == 1); + REQUIRE(eu07vehicle->derailment_reported.has_value()); + CHECK(*eu07vehicle->derailment_reported == &curve.name); + // and once more on the next one + test::track next{curve}; + next.name = "curve_2"; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(next); + } + CHECK(eu07vehicle->derailment_reports() == 2); + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + + SUBCASE("under the criteria nothing is told") { + vehicle slower{definition::fiz("4e_v1/4e"), critical - 5.0}; + for (int step = 0; step < 100; ++step) { + slower.step(curve); + } + CHECK(slower->derailment_reports() == 0); + } + SUBCASE("far over the legacy threshold the legacy draw derails it, the legacy way") { + vehicle faster{definition::fiz("4e_v1/4e"), 160.0}; + for (int step = 0; step < 600; ++step) { + faster.step(curve); + } + CHECK(faster->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(faster->Derailed() == dr::outcome::none); + CHECK(faster->V() == doctest::Approx(0.0).epsilon(0.01)); + } +} + +TEST_CASE("derailment: the names of the models in eu07.ini") { + using model = global_settings::derailment_model; + CHECK(derailment_model_of("new") == model::physical); + CHECK(derailment_model_of("old") == model::old); + CHECK(derailment_model_of("off") == model::off); + CHECK(derailment_model_of("no") == model::off); + CHECK(derailment_model_of("monitor") == model::monitor); + // a name it doesn't know is the default: monitor, the legacy draw decides and the criteria go to the log, until the + // speed limits of the bundled sceneries are checked against them + CHECK(derailment_model_of("physical") == model::monitor); + CHECK(derailment_model_of("") == model::monitor); + CHECK(global_settings{}.derailment == model::monitor); + CHECK_FALSE(global_settings{}.track_check); + // written back the way it's read + for (auto const value : {model::off, model::old, model::physical, model::monitor}) { + CHECK(derailment_model_of(name_of(value)) == value); + } + CHECK(name_of(model::physical) == "new"); +} + +namespace { + +// physics.derailment.trustlimits for the test, restored after it +class trust_setting { +public: + explicit trust_setting(bool Trust) : m_previous{Global.derailment_trust_limits} { Global.derailment_trust_limits = Trust; } + ~trust_setting() { Global.derailment_trust_limits = m_previous; } + trust_setting(trust_setting const &) = delete; + trust_setting &operator=(trust_setting const &) = delete; + +private: + bool m_previous; +}; + +} // namespace + +TEST_CASE("derailment: the speed limit of the track trusted") { + // a 300 m curve without cant with a limit of 140 km/h, trusted up to 159 km/h; EU07 overturns there at 108 km/h + model_setting const physical{global_settings::derailment_model::physical}; + CHECK(global_settings{}.derailment_trust_limits); + test::track curve; + curve.radius = 300.0; + curve.velocity = 140.0; + curve.name = "curve_bad_limit"; + + SUBCASE("under the trusted speed it stays on the rails, the log names the track once") { + trust_setting const trust{true}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 130.0}; + for (int step = 0; step < 300; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->Derailed() == dr::outcome::none); + CHECK(eu07vehicle->derailment_reports() == 1); + REQUIRE(eu07vehicle->derailment_reported.has_value()); + CHECK(*eu07vehicle->derailment_reported == &curve.name); + } + SUBCASE("over it, it overturns") { + trust_setting const trust{true}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 165.0}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); + CHECK(eu07vehicle->derailment_reports() == 0); + } + SUBCASE("on a track without a limit it overturns") { + trust_setting const trust{true}; + curve.velocity = -1.0; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 130.0}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); + } + SUBCASE("trustlimits no: the criteria decide at any speed, as before") { + trust_setting const trust{false}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 130.0}; + for (int step = 0; step < 20; ++step) { + eu07vehicle.step(curve); + } + CHECK(eu07vehicle->Derailed() == dr::outcome::overturned); + CHECK(eu07vehicle->derailment_reports() == 0); + } + SUBCASE("the same with steps of 0.01 and 0.05 s") { + trust_setting const trust{true}; + for (auto const dt : {0.01, 0.05}) { + CAPTURE(dt); + auto const steps{static_cast(std::lround(1.0 / dt))}; + vehicle held{definition::fiz("4e_v1/4e"), 155.0}; + vehicle overturned{definition::fiz("4e_v1/4e"), 163.0}; + for (auto step = 0; step < steps; ++step) { + held.step(curve, dt); + overturned.step(curve, dt); + } + CHECK(held->Derailed() == dr::outcome::none); + CHECK(overturned->Derailed() == dr::outcome::overturned); + } + } + SUBCASE("monitor tells what the criteria find, as before") { + model_setting const monitor{global_settings::derailment_model::monitor}; + trust_setting const trust{true}; + vehicle eu07vehicle{definition::fiz("4e_v1/4e"), 110.0}; + for (int step = 0; step < 100; ++step) { + eu07vehicle.step(curve); + } + CHECK_FALSE(eu07vehicle->DamageFlag.HasAll(VehicleDamage::derailed)); + CHECK(eu07vehicle->derailment_reports() == 1); + } +} diff --git a/tests/unit/test_diesel.cpp b/tests/unit/test_diesel.cpp index c4ea147d3..1ca7e9ab5 100644 --- a/tests/unit/test_diesel.cpp +++ b/tests/unit/test_diesel.cpp @@ -3,7 +3,7 @@ #include "scenario.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // characterisation of the diesel engines besides their drive, recorded in golden traces (data/golden/diesel/): // the heat of the engine, its oil and its water circuits, which keep a too cold or too hot engine from starting @@ -15,15 +15,15 @@ namespace { std::vector heat() { return { - {"Ts", [](auto const &M) { return M.dizel_heat.Ts; }}, - {"To", [](auto const &M) { return M.dizel_heat.To; }}, - {"Twy", [](auto const &M) { return M.dizel_heat.Twy; }}, - {"Twy2", [](auto const &M) { return M.dizel_heat.Twy2; }}, - {"PA", [](auto const &M) { return M.dizel_heat.PA ? 1.0 : 0.0; }}, + {"Ts", [](auto const &M) { return M.diesel.heat.Ts; }}, + {"To", [](auto const &M) { return M.diesel.heat.To; }}, + {"Twy", [](auto const &M) { return M.diesel.heat.Twy; }}, + {"Twy2", [](auto const &M) { return M.diesel.heat.Twy2; }}, + {"PA", [](auto const &M) { return M.diesel.heat.PA ? 1.0 : 0.0; }}, {"WaterHeater", [](auto const &M) { return M.WaterHeater.is_active ? 1.0 : 0.0; }}, {"WaterPump", [](auto const &M) { return M.WaterPump.is_active ? 1.0 : 0.0; }}, - {"zaluzje1", [](auto const &M) { return M.dizel_heat.zaluzje1 ? 1.0 : 0.0; }}, - {"zaluzje2", [](auto const &M) { return M.dizel_heat.zaluzje2 ? 1.0 : 0.0; }}, + {"zaluzje1", [](auto const &M) { return M.diesel.heat.zaluzje1 ? 1.0 : 0.0; }}, + {"zaluzje2", [](auto const &M) { return M.diesel.heat.zaluzje2 ? 1.0 : 0.0; }}, }; } @@ -43,12 +43,12 @@ TEST_CASE("diesel: an engine too cold to start, warmed by its heater") { auto &locomotive{scenario.cab()}; locomotive.dizel_HeatSet(-10.f); CHECK(scenario.start_up() == starts); - CHECK(locomotive.dizel_heat.PA != starts); + CHECK(locomotive.diesel.heat.PA != starts); CHECK(locomotive.WaterHeater.is_active); scenario.act("heating"); scenario.wait(1200.0); - CHECK_FALSE(locomotive.dizel_heat.PA); - CHECK(locomotive.dizel_heat.Twy > 50.f); + CHECK_FALSE(locomotive.diesel.heat.PA); + CHECK(locomotive.diesel.heat.Twy > 50.f); CHECK(scenario.start_up()); scenario.check(); } @@ -70,13 +70,13 @@ TEST_CASE("diesel: an engine started hot, and run at full power") { auto &locomotive{scenario.cab()}; locomotive.dizel_HeatSet(88.f); CHECK(scenario.start_up() == starts); - CHECK(locomotive.dizel_heat.PA != starts); + CHECK(locomotive.diesel.heat.PA != starts); if (starts) { scenario.get_going(); scenario.full_power(300.0); CHECK(locomotive.Vel > 50.0); - CHECK(locomotive.dizel_heat.zaluzje1); - CHECK(locomotive.dizel_heat.Twy < locomotive.dizel_heat.water.config.temp_max); + CHECK(locomotive.diesel.heat.zaluzje1); + CHECK(locomotive.diesel.heat.Twy < locomotive.diesel.heat.water.config.temp_max); } scenario.check(); } @@ -92,33 +92,33 @@ TEST_CASE("diesel: the 214M railbus's torque converter, gears and retarder") { auto &railbus{scenario.cab()}; scenario.get_going(); scenario.full_power(60.0); - CHECK(railbus.MainCtrlPos == 5); - CHECK(railbus.eimic_real == doctest::Approx(1.0)); - CHECK(railbus.hydro_TC_Lockup); - CHECK(railbus.ScndCtrlActualPos == railbus.ScndCtrlPosNo); + CHECK(railbus.MainCtrlPos() == 5); + CHECK(railbus.EimicReal() == doctest::Approx(1.0)); + CHECK(railbus.torqueConverter.lockedUp); + CHECK(railbus.ScndCtrlActualPos == railbus.ScndCtrlPosNo()); struct position { double eimic; bool retarder; bool air; }; - auto number{railbus.MainCtrlPos}; + auto number{railbus.MainCtrlPos()}; for (auto const &[eimic, retarder, air] : {position{1.0, false, false}, position{0.0, false, false}, position{-1.0, true, false}, position{0.0, false, true}}) { --number; CAPTURE(number); scenario.act(std::format("position {}", number)); railbus.DecMainCtrl(1); scenario.wait(8.0); - CHECK(railbus.eimic_real == doctest::Approx(eimic)); - CHECK((railbus.hydro_R_Fill > 0.99) == retarder); - CHECK((railbus.hydro_R_Torque > 1000.0) == retarder); - CHECK((railbus.BrakePress > 2.0) == air); + CHECK(railbus.EimicReal() == doctest::Approx(eimic)); + CHECK((railbus.retarder.fill > 0.99) == retarder); + CHECK((railbus.retarder.torque > 1000.0) == retarder); + CHECK((railbus.brakes.cylinderPressure > 2.0) == air); } scenario.act("position 0"); railbus.DecMainCtrl(1); scenario.wait(30.0); CHECK(railbus.Vel == doctest::Approx(0.0)); // the gearbox shifted down as the railbus slowed - CHECK(railbus.ScndCtrlActualPos < railbus.ScndCtrlPosNo); + CHECK(railbus.ScndCtrlActualPos < railbus.ScndCtrlPosNo()); scenario.check(); } @@ -130,7 +130,7 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button scenario.add("21xm_v1/214ma", 1); REQUIRE(scenario.start_up()); auto &railbus{scenario.cab()}; - REQUIRE(railbus.SpeedCtrl); + REQUIRE(railbus.SpeedCtrl()); scenario.get_going(); scenario.full_power(10.0); scenario.act("speed control on"); @@ -159,9 +159,9 @@ TEST_CASE("diesel: the 214M railbus's speed control, up to the speed of a button railbus.SpeedCtrlButton(2); scenario.wait(5.0); // the retarder does it at this speed, the air isn't needed - CHECK(railbus.eimic_real == doctest::Approx(-1.0)); - CHECK(railbus.hydro_R_Fill == doctest::Approx(1.0)); - CHECK(railbus.BrakePress < 0.1); + CHECK(railbus.EimicReal() == doctest::Approx(-1.0)); + CHECK(railbus.retarder.fill == doctest::Approx(1.0)); + CHECK(railbus.brakes.cylinderPressure < 0.1); CHECK_FALSE(railbus.SpeedCtrlUnit.BrakeInterventionBraking); scenario.wait(60.0); CHECK(railbus.Vel == doctest::Approx(40.0).epsilon(0.05)); @@ -193,7 +193,7 @@ TEST_CASE("diesel: the SM42's shunt mode, switched on and off with one move of t CHECK(sm42.ShuntMode); scenario.get_going(); scenario.act("shunting power"); - sm42.AnPos = 0.5; + sm42.SetAnPos(0.5); CHECK(sm42.IncMainCtrl(1)); scenario.wait(60.0); CHECK(sm42.Vel > 1.0); diff --git a/tests/unit/test_dimmer.cpp b/tests/unit/test_dimmer.cpp index d4d2e2663..4bfb230ca 100644 --- a/tests/unit/test_dimmer.cpp +++ b/tests/unit/test_dimmer.cpp @@ -31,15 +31,15 @@ TEST_CASE("dimmer: a position outside the list reads as a plain one, neither off for (auto const position : {-1, 2, 100}) { CAPTURE(position); - cab->modernDimmerPosition = position; + cab->SetDimmerPosition(position); auto const entry{cab->currentDimPosition()}; CHECK_FALSE(entry.isOff); CHECK_FALSE(entry.isDimmed); CHECK_FALSE(entry.isHighBeam); } - cab->modernDimmerPosition = 0; + cab->SetDimmerPosition(0); CHECK(cab->currentDimPosition().isOff); - cab->modernDimmerPosition = 1; + cab->SetDimmerPosition(1); CHECK(cab->currentDimPosition().isDimmed); } @@ -57,15 +57,15 @@ TEST_CASE("dimmer: a DefaultPos past the end of the list starts the dimmer at it CHECK(cab->modernDimmerDefaultPosition == 1); // the cab puts the modern dimmer to its default position when it's entered (TTrain::set_cab_controls()) - cab->modernDimmerPosition = cab->modernDimmerDefaultPosition; + cab->SetDimmerPosition(cab->modernDimmerDefaultPosition); CHECK(cab->currentDimPosition().isDimmed); } TEST_CASE("dimmer: without the modern dimmer a DefaultPos past the end of the list puts the dimmer at its last position") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed}), 7).set("Switches", "ModernDimmer", "No")}; - REQUIRE_FALSE(cab->enableModernDimmer); + REQUIRE_FALSE(cab->enableModernDimmer()); - CHECK(cab->modernDimmerPosition == 1); + CHECK(cab->DimmerPosition() == 1); CHECK(cab->currentDimPosition().isDimmed); } @@ -74,39 +74,39 @@ TEST_CASE("dimmer: an empty list leaves the dimmer at 0, reading as a plain posi REQUIRE(cab->dimPositions.empty()); CHECK(cab->modernDimmerDefaultPosition == 0); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); CHECK(cab->clampDimmerPosition(1) == 0); CHECK_FALSE(cab->currentDimPosition().isOff); CHECK_FALSE(cab->stepDimmerPosition(1)); CHECK_FALSE(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); } TEST_CASE("dimmer: stepping stays within the list") { SUBCASE("without cycling it stops at the ends") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)}; CHECK_FALSE(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); CHECK(cab->stepDimmerPosition(1)); CHECK(cab->stepDimmerPosition(1)); - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); CHECK_FALSE(cab->stepDimmerPosition(1)); - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); } SUBCASE("with cycling it goes around to the other end") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0, true)}; CHECK(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); CHECK(cab->stepDimmerPosition(1)); - CHECK(cab->modernDimmerPosition == 0); + CHECK(cab->DimmerPosition() == 0); } SUBCASE("a position past the end steps from the last one") { vehicle cab{dimmer_list(nlohmann::ordered_json::array({plain, dimmed, off}), 0)}; - cab->modernDimmerPosition = 9; + cab->SetDimmerPosition(9); CHECK(cab->stepDimmerPosition(-1)); - CHECK(cab->modernDimmerPosition == 1); - cab->modernDimmerPosition = 9; + CHECK(cab->DimmerPosition() == 1); + cab->SetDimmerPosition(9); CHECK(cab->stepDimmerPosition(1)); // can't go further, but comes back into the list - CHECK(cab->modernDimmerPosition == 2); + CHECK(cab->DimmerPosition() == 2); } } diff --git a/tests/unit/test_door_closure.cpp b/tests/unit/test_door_closure.cpp index c92d8fef8..4c80670f0 100644 --- a/tests/unit/test_door_closure.cpp +++ b/tests/unit/test_door_closure.cpp @@ -50,13 +50,13 @@ TEST_CASE("door closure: a unit with permits, locked, released by the permit and CHECK(consist_closure(scenario) == door_closure_t::locked); scenario.act("permit left"); - cab.PermitDoors(side::left, true); + cab.PermitDoors(VehicleSide::left, true); scenario.wait(2.0); CHECK(last.door_closure() == door_closure_t::released); CHECK(consist_closure(scenario) == door_closure_t::released); scenario.act("the last car opens its own door"); - last.OperateDoors(side::left, true, range_t::local); + last.OperateDoors(VehicleSide::left, true, range_t::local); scenario.wait(5.0); // the cab's own doors stay closed, the train is open all the same CHECK(cab.door_closure() == door_closure_t::released); @@ -64,15 +64,15 @@ TEST_CASE("door closure: a unit with permits, locked, released by the permit and CHECK(consist_closure(scenario) == door_closure_t::open); scenario.act("close, the steps stay out under the permit"); - last.OperateDoors(side::left, false, range_t::local); - cab.OperateDoors(side::left, false); + last.OperateDoors(VehicleSide::left, false, range_t::local); + cab.OperateDoors(VehicleSide::left, false); scenario.wait(10.0); - CHECK(last.Doors.instances[side::left].position <= 0.f); + CHECK(last.Doors.instances[VehicleSide::left].position <= 0.f); // a step out isn't a closed door CHECK(consist_closure(scenario) == door_closure_t::open); scenario.act("revoke the permit"); - cab.PermitDoors(side::left, false); + cab.PermitDoors(VehicleSide::left, false); scenario.wait(10.0); CHECK(consist_closure(scenario) == door_closure_t::locked); } @@ -90,11 +90,11 @@ TEST_CASE("door closure: the doors of a unit without permits are released at a s CHECK(middle.door_closure() == door_closure_t::locked); CHECK(consist_closure(scenario) == door_closure_t::released); scenario.act("open right"); - cab.OperateDoors(side::right, true); + cab.OperateDoors(VehicleSide::right, true); scenario.wait(10.0); CHECK(consist_closure(scenario) == door_closure_t::open); scenario.act("close right"); - cab.OperateDoors(side::right, false); + cab.OperateDoors(VehicleSide::right, false); scenario.wait(10.0); CHECK(consist_closure(scenario) == door_closure_t::released); } @@ -105,8 +105,8 @@ TEST_CASE("door closure: a locomotive has no doors to signal, its coach does") { scenario.start_up(); CHECK(scenario.cab().door_closure() == door_closure_t::none); scenario.act("open right"); - scenario.cab().PermitDoors(side::right, true); - scenario.cab().OperateDoors(side::right, true); + scenario.cab().PermitDoors(VehicleSide::right, true); + scenario.cab().OperateDoors(VehicleSide::right, true); scenario.wait(10.0); CHECK(scenario.vehicle(1).door_closure() == door_closure_t::open); CHECK(consist_closure(scenario) == door_closure_t::open); diff --git a/tests/unit/test_door_component.cpp b/tests/unit/test_door_component.cpp new file mode 100644 index 000000000..7840d9010 --- /dev/null +++ b/tests/unit/test_door_component.cpp @@ -0,0 +1,91 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "physics/components/devices.h" + +// the doors of a vehicle as a part of their own (physics::door_data::Update()), stepped without a vehicle + +namespace { + +// a door one metre wide, opened and closed from the cab at a metre a second, without a step or a lock +physics::door_data cab_controlled_doors() { + physics::door_data doors; + doors.open_control = control_t::driver; + doors.close_control = control_t::driver; + doors.range = 1.f; + doors.open_rate = 1.f; + doors.close_rate = 1.f; + return doors; +} + +void run(physics::door_data &Doors, physics::door_data::StepInputs const &Inputs, double Seconds) { + for (auto time{0.0}; time < Seconds; time += 0.05) { + Doors.Update(Inputs, 0.05); + } +} + +physics::door_data::StepInputs standing_powered() { + physics::door_data::StepInputs inputs; + inputs.powered = true; + return inputs; +} + +} // namespace + +TEST_CASE("door component: a door opened from the cab opens at its rate, and closes when asked to") { + auto doors{cab_controlled_doors()}; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + run(doors, standing_powered(), 0.5); + CHECK(door.position > 0.f); + CHECK(door.position < 1.f); + CHECK_FALSE(door.is_closed); + run(doors, standing_powered(), 1.0); + CHECK(door.is_open); + CHECK(door.position == doctest::Approx(1.f)); + CHECK(doors.instances[VehicleSide::right].is_closed); + door.remote_close = true; + run(doors, standing_powered(), 1.5); + CHECK(door.is_closed); + CHECK(door.position == doctest::Approx(0.f)); +} + +TEST_CASE("door component: without the voltage it works on, a door doesn't move") { + auto doors{cab_controlled_doors()}; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + auto inputs{standing_powered()}; + inputs.powered = false; + run(doors, inputs, 2.0); + CHECK(door.is_closed); + CHECK(door.position == doctest::Approx(0.f)); +} + +TEST_CASE("door component: the lock holds the doors closed over its speed") { + auto doors{cab_controlled_doors()}; + doors.has_lock = true; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + auto inputs{standing_powered()}; + inputs.velocity = doors.doorLockSpeed + 5.0; + run(doors, inputs, 2.0); + CHECK(doors.is_locked); + CHECK(door.is_closed); + CHECK(doors.Closure() == door_closure_t::locked); +} + +TEST_CASE("door component: doors that close after a while close by themselves, unless the passengers are getting in") { + auto doors{cab_controlled_doors()}; + doors.auto_duration = 1.f; + doors.auto_include_remote = true; + auto &door{doors.instances[VehicleSide::left]}; + door.remote_open = true; + run(doors, standing_powered(), 1.5); + REQUIRE(door.is_open); + auto exchanging{standing_powered()}; + exchanging.exchangingLoad = true; + run(doors, exchanging, 3.0); + CHECK(door.is_open); + run(doors, standing_powered(), 3.0); + CHECK(door.is_closed); +} diff --git a/tests/unit/test_door_wings.cpp b/tests/unit/test_door_wings.cpp index 290260f6a..12eae8193 100644 --- a/tests/unit/test_door_wings.cpp +++ b/tests/unit/test_door_wings.cpp @@ -2,9 +2,10 @@ #include "doctest.h" #include "vehicle/doorwings.h" +#include "utilities/parser.h" // the poses of the animated door wings (eu07/maszyna#512): a wing of the main model and its namesake in the low -// poly interior get the same pose, worked out once from the door position of the mover +// poly interior get the same pose, worked out once from the door position of the physics TEST_CASE("door wings: only the door animations move wings") { CHECK(door_wings::is_wing(0x010)); // TAnim::TypeSet for the doors @@ -52,3 +53,155 @@ TEST_CASE("door wings: a folding wing turns one way and its larger wing twice as CHECK(closed.larger == 0.f); CHECK(closed.step == 0.f); } + +// a wing with its own kind of animation (eu07/maszyna#70): animdoor: in the .mmd, for vehicles whose doors on one side +// aren't all alike, e.g. 111Ainw with folding doors at one end and wider ones at the other + +namespace { + +// the spec of the .fiz the entries start from: folding doors which turn by 80 degrees +door_wings::wing_spec const fizdoors{0, door_wings::fold_type, 80.f, 0.f}; + +// reads the entry after animdoor: from the text, starting from the spec of the .fiz +std::string read(std::string const &Entry, door_wings::wing_spec &Spec) { + Spec = fizdoors; + cParser parser(Entry, cParser::buffer_TEXT); + return door_wings::read_spec(parser, Spec); +} + +} // namespace + +TEST_CASE("door wings: the kinds of animation are named as DoorOpenMethod of the .fiz") { + CHECK(door_wings::type_from_name("Shift") == door_wings::shift_type); + CHECK(door_wings::type_from_name("Rotate") == door_wings::rotate_type); + CHECK(door_wings::type_from_name("Fold") == door_wings::fold_type); + CHECK(door_wings::type_from_name("Plug") == door_wings::plug_type); + // in any letter case + CHECK(door_wings::type_from_name("plug") == door_wings::plug_type); + CHECK(door_wings::type_from_name("SHIFT") == door_wings::shift_type); + // the same numbers as physics::door_data::type + CHECK(door_wings::shift_type == 1); + CHECK(door_wings::rotate_type == 2); + CHECK(door_wings::fold_type == 3); + CHECK(door_wings::plug_type == 4); + CHECK_FALSE(door_wings::type_from_name("Roll").has_value()); + CHECK_FALSE(door_wings::type_from_name("").has_value()); +} + +TEST_CASE("door wings: an animdoor entry gives the wing its own kind, range and plug shift") { + door_wings::wing_spec spec; + CHECK(read("3 { type: Plug range: 0.9 rangeout: 0.06 } endmodels", spec).empty()); + CHECK(spec.number == 3); + CHECK(spec.type == door_wings::plug_type); + CHECK(spec.range == doctest::Approx(0.9f)); + CHECK(spec.range_out == doctest::Approx(0.06f)); +} + +TEST_CASE("door wings: the keys an animdoor entry leaves out keep the values of the .fiz") { + door_wings::wing_spec spec; + SUBCASE("only the kind") { + CHECK(read("2 { type: Rotate }", spec).empty()); + CHECK(spec.number == 2); + CHECK(spec.type == door_wings::rotate_type); + CHECK(spec.range == 80.f); + CHECK(spec.range_out == 0.f); + } + SUBCASE("only the range, keys in any letter case and order") { + CHECK(read("1 { Range: -95 }", spec).empty()); + CHECK(spec.type == door_wings::fold_type); + CHECK(spec.range == -95.f); + } + SUBCASE("nothing") { + CHECK(read("4 { }", spec).empty()); + CHECK(spec.number == 4); + CHECK(spec.type == fizdoors.type); + CHECK(spec.range == fizdoors.range); + } +} + +TEST_CASE("door wings: a faulty animdoor entry says what is wrong with it") { + door_wings::wing_spec spec; + CHECK(read("3 type: Shift range: 0.65", spec) == "no { after the wing number"); + CHECK(read("3 { type: Roll range: 0.65 }", spec) == "unknown door type \"Roll\""); + CHECK(read("3 { type: Shift range: 0,65 }", spec) == "bad number \"0,65\" for \"range:\""); + CHECK(read("3 { type: Shift range: wide }", spec) == "bad number \"wide\" for \"range:\""); + CHECK(read("3 { kind: Shift }", spec) == "no } after the keys, \"kind:\" is none of them"); + CHECK(read("3 { type: Shift range: }", spec) == "no value for \"range:\""); + CHECK(read("3 { type: Shift range: 0.65", spec) == "no } after the keys"); +} + +TEST_CASE("door wings: an animdoor entry without its } leaves the entries after it to the .mmd") { + // the first token that is neither a key nor the value of one ends the entry, and is read next by the caller + auto const next{[](std::string const &Text) { + door_wings::wing_spec spec{fizdoors}; + cParser parser(Text, cParser::buffer_TEXT); + auto const error{door_wings::read_spec(parser, spec)}; + std::vector rest; + std::string token; + do { + token.clear(); + parser.getTokens(1, false); + parser >> token; + if (false == token.empty()) { + rest.emplace_back(token); + } + } while (false == token.empty()); + return std::pair{error, rest}; + }}; + { + auto const [error, rest]{next("3 { type: Plug range: 0.9\nsounds: horn.wav\nlights: 1\nendmodels")}; + CHECK(error == "no } after the keys, \"sounds:\" is none of them"); + CHECK(rest == std::vector{"sounds:", "horn.wav", "lights:", "1", "endmodels"}); + } + { + auto const [error, rest]{next("3 { type: Plug range: endmodels")}; + CHECK(error == "no } after the keys, \"endmodels\" is none of them"); + CHECK(rest == std::vector{"endmodels"}); + } + { + // a whole entry leaves the rest as it is + auto const [error, rest]{next("3 { type: Plug range: 0.9 } sounds: horn.wav endmodels")}; + CHECK(error.empty()); + CHECK(rest == std::vector{"sounds:", "horn.wav", "endmodels"}); + } +} + +TEST_CASE("door wings: the parsed keys go into the spec, pairs of a key and its value") { + door_wings::wing_spec spec{fizdoors}; + CHECK(door_wings::parse_spec({"type:", "Shift", "range:", "0.65"}, spec).empty()); + CHECK(spec.type == door_wings::shift_type); + CHECK(spec.range == doctest::Approx(0.65f)); + CHECK(door_wings::parse_spec({"rangeout:"}, spec) == "no value for \"rangeout:\""); + CHECK(door_wings::parse_spec({}, spec).empty()); +} + +TEST_CASE("door wings: only the wings with an entry animate in their own way, the latest entry counts") { + std::vector specs; + CHECK(door_wings::find(specs, 1) == nullptr); + door_wings::store(specs, {3, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {4, door_wings::shift_type, 0.65f, 0.f}); + door_wings::store(specs, {3, door_wings::plug_type, 0.9f, 0.06f}); + CHECK(specs.size() == 2); + CHECK(door_wings::find(specs, 1) == nullptr); + CHECK(door_wings::find(specs, 2) == nullptr); + REQUIRE(door_wings::find(specs, 3) != nullptr); + CHECK(door_wings::find(specs, 3)->type == door_wings::plug_type); + CHECK(door_wings::find(specs, 3)->range == 0.9f); + REQUIRE(door_wings::find(specs, 4) != nullptr); + CHECK(door_wings::find(specs, 4)->type == door_wings::shift_type); +} + +TEST_CASE("door wings: a wing with its own range is as far along it as the door of its side") { + // folding doors of the .fiz turn by 80 degrees; the wide wing slides by 0.9 m + CHECK(door_wings::wing_position(0.f, 80.f, 0.9f) == 0.f); + CHECK(door_wings::wing_position(40.f, 80.f, 0.9f) == doctest::Approx(0.45f)); + CHECK(door_wings::wing_position(80.f, 80.f, 0.9f) == doctest::Approx(0.9f)); + // a wing turning the other way + CHECK(door_wings::wing_position(20.f, 80.f, -100.f) == doctest::Approx(-25.f)); + // no doors in the .fiz: the wing stays closed + CHECK(door_wings::wing_position(0.f, 0.f, 0.9f) == 0.f); + // the pose of the plug wing at the end of its range + auto const open{door_wings::plug(door_wings::wing_position(80.f, 80.f, 0.9f), 0.06f)}; + CHECK(open.x == doctest::Approx(0.06f)); + CHECK(open.z == doctest::Approx(0.87f)); +} diff --git a/tests/unit/test_driver_figure.cpp b/tests/unit/test_driver_figure.cpp new file mode 100644 index 000000000..a9b59599f --- /dev/null +++ b/tests/unit/test_driver_figure.cpp @@ -0,0 +1,119 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/driverfigure.h" + +// the driver figures of the lowpoly interior (eu07/maszyna#535): in a vehicle with one desk for both directions the +// player's figure follows the selected direction of travel, so a player who only moves the reverser is seen facing the +// way the vehicle goes, the way the AI is, which changes the cab instead + +using driver_figure::cab_place; +using driver_figure::shown; +using driver_figure::single_desk; + +namespace { + +// the cabs of 401da_v2/401da.mmd: the same model and the same seat for both directions +cab_place const desk_401da{"interior/401da-207.t3d", glm::vec3{-0.908f, 3.324f, -1.543f}, glm::vec3{-0.908f, 3.324f, -1.543f}}; + +// tem2_v2/tem2a.mmd: the cab 2 has another standing position, but the same seat +cab_place const tem2_cab1{"kabina-tem2a.t3d", glm::vec3{-1.27f, 3.594f, -5.61f}, glm::vec3{-1.235f, 3.203f, -5.114f}}; +cab_place const tem2_cab2{"kabina-tem2a.t3d", glm::vec3{1.27f, 3.594f, -4.72f}, glm::vec3{-1.235f, 3.203f, -5.114f}}; + +// sm42_v1/6d.mmd: one cab with two desks, the seat of the cab 2 is on the other side +cab_place const sm42_cab1{"6d_kabina.t3d", glm::vec3{0.99f, 3.454f, -3.311f}, glm::vec3{-1.15f, 3.58f, -2.83f}}; +cab_place const sm42_cab2{"6d_kabina.t3d", glm::vec3{-0.99f, 3.454f, -3.311f}, glm::vec3{1.15f, 3.58f, -2.83f}}; + +// a vehicle with a cab at each end +cab_place const end_cab1{"kabina_a.t3d", glm::vec3{-0.8f, 2.5f, 7.0f}, glm::vec3{-0.8f, 2.4f, 7.2f}}; +cab_place const end_cab2{"kabina_a.t3d", glm::vec3{0.8f, 2.5f, -7.0f}, glm::vec3{0.8f, 2.4f, -7.2f}}; + +} // namespace + +TEST_CASE("driver figure: joint cabs with one model and one seat are a single desk") { + CHECK(single_desk(true, desk_401da, desk_401da)); + CHECK(single_desk(true, tem2_cab1, tem2_cab2)); +} + +TEST_CASE("driver figure: without jointcabs: the cabs are never a single desk") { + CHECK_FALSE(single_desk(false, desk_401da, desk_401da)); + CHECK_FALSE(single_desk(false, tem2_cab1, tem2_cab2)); +} + +TEST_CASE("driver figure: two desks in one cab, or two cabs, are not a single desk") { + CHECK_FALSE(single_desk(true, sm42_cab1, sm42_cab2)); + CHECK_FALSE(single_desk(true, end_cab1, end_cab2)); +} + +TEST_CASE("driver figure: the cabs with different models are not a single desk") { + auto cab2{desk_401da}; + cab2.model = "interior/401da-207_b.t3d"; + CHECK_FALSE(single_desk(true, desk_401da, cab2)); + cab2.model = "none"; + CHECK_FALSE(single_desk(true, desk_401da, cab2)); + auto nomodel{desk_401da}; + nomodel.model = "none"; + CHECK_FALSE(single_desk(true, nomodel, nomodel)); + nomodel.model.clear(); + CHECK_FALSE(single_desk(true, nomodel, nomodel)); +} + +TEST_CASE("driver figure: the seat is the sitting position, or the position without one") { + cab_place standing{"cab.t3d", glm::vec3{-1.15f, 3.32f, -4.23f}, std::nullopt}; + REQUIRE(standing.seat().has_value()); + CHECK(standing.seat()->x == doctest::Approx(-1.15)); + CHECK(single_desk(true, standing, standing)); + + // the same sitting position decides, whatever the standing ones (sm31_v1/411d.mmd) + cab_place const sm31_cab1{"cab.t3d", glm::vec3{-1.15f, 3.32f, -4.23f}, glm::vec3{-1.13f, 3.21f, -4.77f}}; + cab_place const sm31_cab2{"cab.t3d", glm::vec3{1.15f, 3.32f, -4.23f}, glm::vec3{-1.13f, 3.21f, -4.77f}}; + CHECK(single_desk(true, sm31_cab1, sm31_cab2)); + + // the cab 1 sits on the standing spot of the cab 2, which has its own seat elsewhere + cab_place const cab2{"cab.t3d", glm::vec3{-1.15f, 3.32f, -4.23f}, glm::vec3{1.15f, 3.21f, -4.77f}}; + CHECK_FALSE(single_desk(true, standing, cab2)); +} + +TEST_CASE("driver figure: a cab without any driver position is not a single desk") { + cab_place const noseat{"interior/401da-207.t3d", std::nullopt, std::nullopt}; + CHECK_FALSE(single_desk(true, desk_401da, noseat)); + CHECK_FALSE(single_desk(true, noseat, desk_401da)); + CHECK_FALSE(single_desk(true, noseat, noseat)); +} + +TEST_CASE("driver figure: the seats count as one within a centimetre") { + auto cab2{desk_401da}; + cab2.sitting_position->x += 0.005f; + CHECK(single_desk(true, desk_401da, cab2)); + cab2.sitting_position->x += 0.02f; + CHECK_FALSE(single_desk(true, desk_401da, cab2)); +} + +TEST_CASE("driver figure: the figure of the occupied cab shows when it doesn't follow the direction") { + for (auto const direction : {-1, 0, 1}) { + CAPTURE(direction); + CHECK(shown(1, direction, false) == 1); + CHECK(shown(-1, direction, false) == -1); + } +} + +TEST_CASE("driver figure: following the direction, the figure faces the way the vehicle goes") { + CHECK(shown(1, 1, true) == 1); + CHECK(shown(1, -1, true) == -1); // the player reversing without changing the cab + CHECK(shown(-1, -1, true) == -1); // the cab changed, driving on in the cab's own direction + CHECK(shown(-1, 1, true) == 1); +} + +TEST_CASE("driver figure: without a direction selected the figure of the occupied cab shows") { + CHECK(shown(1, 0, true) == 1); + CHECK(shown(-1, 0, true) == -1); +} + +TEST_CASE("driver figure: no figure without an occupied cab") { + for (auto const follows : {false, true}) { + CAPTURE(follows); + CHECK(shown(0, 1, follows) == 0); + CHECK(shown(0, -1, follows) == 0); + CHECK(shown(0, 0, follows) == 0); + } +} diff --git a/tests/unit/test_drivingaid.cpp b/tests/unit/test_drivingaid.cpp new file mode 100644 index 000000000..438100981 --- /dev/null +++ b/tests/unit/test_drivingaid.cpp @@ -0,0 +1,176 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "real_vehicles.h" + +#include "vehicle/drivingaid.h" +#include "physics/brakes.h" + +#include +#include +#include + +// the numbers of the driving aid panel's throttle and brakes lines: the ED braking shows (eu07/maszyna#558) and +// the local brake is left out where the cab has no control of it (eu07/maszyna#555) + +using test::definition; +using test::vehicle; + +namespace { + +// the cab controls of the vehicles here, as their cab definitions (.mmd) have them: the Vectron has a local brake +// lever and a joint controller whose braking range is its ED lever, the Traxx and the EU07 a local brake lever, +// the SM42 a joint controller whose braking range is the local brake, none of the 45 Elf cabs either of them +constexpr drivingaid::cab_controls vectron_cab{true, true}; +constexpr drivingaid::cab_controls lever_cab{true, false}; +constexpr drivingaid::cab_controls jointctrl_cab{false, true}; +constexpr drivingaid::cab_controls elf_cab{false, false}; + +drivingaid::readout read(vehicle &Vehicle, drivingaid::cab_controls const &Cab) { + return drivingaid::compute(drivingaid::from_vehicles(Vehicle.physics(), Vehicle.physics(), Cab)); +} + +// what the panel showed before: the throttle and brakes numbers, and the local brake always +drivingaid::readout before(physics::Vehicle const &Physics) { + drivingaid::readout result; + result.throttle_first = Physics.EIMCtrlType > 0 ? std::max(0, static_cast(100.4 * Physics.EimicReal())) : Physics.MainCtrlPos(); + result.throttle_second = Physics.EIMCtrlType > 0 ? Physics.MainCtrlPos() : Physics.ScndCtrlPos(); + result.brake_first = Physics.UniCtrlIntegratedBrakeCtrl ? std::max(0.0, -100.0 * Physics.EimicReal()) : Physics.brakes.HandlePositionSmooth(); + result.local_brake = Physics.brakes.IndependentPosition() * LocalBrakePosNo; + return result; +} + +test::track const line{0.15, 0.0, test::catenary_3kv}; + +} // namespace + +TEST_CASE("driving aid: the Vectron's ED lever shows as a negative throttle step, and its ED braking") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 80.0 /* km/h */, "vectron", 1}; + REQUIRE(vectron->brakes.electrodynamic.splitFromPneumatic); + REQUIRE(vectron->brakes.electrodynamic.controllerPositions == 15); + REQUIRE(vectron->EIMCtrlType == 0); + + // lever at zero: the master controller, as before, and no ED braking + auto const idle{read(vectron, vectron_cab)}; + CHECK(idle.throttle_first == vectron->MainCtrlPos()); + CHECK_FALSE(idle.ed_percent.has_value()); + CHECK(idle.show_local_brake); + + // six steps of the ED lever, as the cab's joint controller shows them + for (int step = 0; step < 6; ++step) { + REQUIRE(vectron->IncDynamicBrakeLevel(1.f)); + } + vectron.run(1.0, line); + REQUIRE(vectron->Vel > 15.0); // above Vh1, where the ED brake has its full demand + auto const braking{read(vectron, vectron_cab)}; + CHECK(braking.throttle_first == -6); + REQUIRE(vectron->EimicReal() == doctest::Approx(-0.4)); + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == 40); + // the train brake handle and the local brake, as before + CHECK(braking.brake_first == doctest::Approx(vectron->brakes.HandlePositionSmooth())); + CHECK(braking.show_local_brake); + CHECK(braking.local_brake == doctest::Approx(0.0)); + + // the joint controller's braking range is the ED lever, so it isn't a local brake control + CHECK_FALSE(read(vectron, jointctrl_cab).show_local_brake); +} + +TEST_CASE("driving aid: the Traxx's ED braking from its master controller") { + vehicle traxx{definition::fiz("e186_v2/eu47"), 80.0 /* km/h */, "traxx", 1}; + REQUIRE(traxx->EIMCtrlType == 1); + REQUIRE_FALSE(traxx->brakes.electrodynamic.splitFromPneumatic); + + CHECK_FALSE(read(traxx, lever_cab).ed_percent.has_value()); + // B+: the braking demand ramps towards full + traxx->SetMainCtrlPos(0); + traxx.run(3.0, line); + REQUIRE(traxx->EimicReal() < -0.2); + auto const braking{read(traxx, lever_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * traxx->EimicReal())); + // the drive demand stays at zero while braking, with the controller position next to it, as before + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK(braking.show_local_brake); +} + +TEST_CASE("driving aid: the Elf leaves out the local brake it has no control of, and shows its ED braking") { + vehicle elf{definition::fiz("elf_v1/21we-a"), 60.0 /* km/h */, "elf", 1}; + REQUIRE(elf->EIMCtrlType == 2); + // the definition has a local brake (LocalBrake=PneumaticBrake, LocBrakeHandle=FD1), the cab no control of it + REQUIRE(elf->brakes.config.localKind == TLocalBrake::PneumaticBrake); + + auto const idle{read(elf, elf_cab)}; + CHECK_FALSE(idle.show_local_brake); + CHECK_FALSE(idle.ed_percent.has_value()); + + // the controller at its lowest braking position: the demand ramps towards full braking + elf->SetMainCtrlPos(0); + elf.run(2.0, line); + REQUIRE(elf->EimicReal() < -0.1); + auto const braking{read(elf, elf_cab)}; + REQUIRE(braking.ed_percent.has_value()); + CHECK(*braking.ed_percent == std::lround(-100.0 * elf->EimicReal())); + CHECK(braking.throttle_first == 0); + CHECK(braking.throttle_second == 0); + CHECK_FALSE(braking.show_local_brake); + + // applied after all (the AI, or the keys), it shows + elf->brakes.SetIndependentPosition(0.3); + auto const applied{read(elf, elf_cab)}; + CHECK(applied.show_local_brake); + CHECK(applied.local_brake == doctest::Approx(3.0)); +} + +TEST_CASE("driving aid: a vehicle without an EIM controller shows what it did") { + vehicle eu07{definition::fiz("4e_v1/4e"), 60.0 /* km/h */, "eu07", 1}; + eu07->SetMainCtrlPos(5); + eu07->brakes.SetIndependentPosition(0.2); + auto const readout{read(eu07, lever_cab)}; + CHECK(readout.throttle_first == 5); + CHECK(readout.throttle_second == eu07->ScndCtrlPos()); + CHECK(readout.local_brake == doctest::Approx(2.0)); + CHECK(readout.show_local_brake); + CHECK_FALSE(readout.ed_percent.has_value()); + + // the SM42's local brake is the braking range of its joint controller + vehicle sm42{definition::fiz("sm42_v1/6d1"), 0.0, "sm42", 1}; + CHECK(read(sm42, jointctrl_cab).show_local_brake); + CHECK_FALSE(read(sm42, elf_cab).show_local_brake); +} + +TEST_CASE("driving aid: the integrated universal controller shows the ED demand as its brake number, once") { + drivingaid::input input; + input.eim = true; + input.eimctrltype = 3; + input.integratedbrake = true; + input.eimic_real = -0.35; + input.brakectrlpos = 2.0; + auto const readout{drivingaid::compute(input)}; + CHECK(readout.brake_first == doctest::Approx(35.0)); + CHECK_FALSE(readout.ed_percent.has_value()); + CHECK(readout.throttle_first == 0); +} + +TEST_CASE("driving aid: every real vehicle with a local brake control shows the numbers it showed before") { + // with the ED lever of a split ED brake at zero, the change only adds the ED part and leaves out the local brake + // of a cab without a control of it + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + vehicle real{definition::fiz(path), 40.0 /* km/h */, "real", 1}; + for (auto const &[mainctrl, localbrake, eimic] : {std::tuple{0, 0.0, 0.0}, std::tuple{1, 0.4, -0.25}, std::tuple{1, 0.0, 0.6}}) { + real->SetMainCtrlPos(std::min(mainctrl, real->MainCtrlPosNo)); + real->brakes.SetIndependentPosition(localbrake); + real->SetEimicReal(eimic); + auto const now{read(real, lever_cab)}; + auto const was{before(real.physics())}; + CHECK(now.throttle_first == was.throttle_first); + CHECK(now.throttle_second == was.throttle_second); + CHECK(now.brake_first == doctest::Approx(was.brake_first)); + CHECK(now.local_brake == doctest::Approx(was.local_brake)); + CHECK(now.show_local_brake); + } + } +} diff --git a/tests/unit/test_dynamic_brake_diesel.cpp b/tests/unit/test_dynamic_brake_diesel.cpp new file mode 100644 index 000000000..d936ea5d1 --- /dev/null +++ b/tests/unit/test_dynamic_brake_diesel.cpp @@ -0,0 +1,264 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" +#include "real_vehicles.h" + +#include "physics/brakes.h" + +// the dynamic brake of the diesel-electric vehicles (Engine: EDBrake=, MaSzyna-EU07/maszyna#82): the traction motors +// brake into resistors while the engine runs, with the force of the definition (EDBrakeFmax, the power limit +// EDBrakePmax, the fade below EDBrakeV1 down to EDBrakeV0), set either by the negative range of the integrated +// controller (EDBrake=Controller, the BR285's TRAXX controller) or by a lever of its own (EDBrake=Lever, the +// SplitEDPneumaticBrake one, with the master controller at zero) + +using test::definition; +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector dynamic_brake() { + return { + {"EDLevel", [](auto const &M) { return M.DEDynamicBrake.level; }}, + {"EDForce", [](auto const &M) { return M.DEDynamicBrake.force; }}, + {"DynamicBrakeFlag", [](auto const &M) { return M.brakes.electrodynamic.on ? 1.0 : 0.0; }}, + {"eimic_real", [](auto const &M) { return M.EimicReal(); }}, + {"DynamicBrakeCtrlPos", [](auto const &M) { return M.brakes.electrodynamic.controllerPosition; }}, + }; +} + +// the BR285 with its dynamic brake: 150 kN up to the power limit of 2000 kW (48 km/h), fading out under 6 km/h +definition br285_braking() { + return definition::fiz("br285_v1/br285") + .set("Engine", "EDBrake", "Controller") + .set("Engine", "EDBrakeFmax", 150) + .set("Engine", "EDBrakePmax", 2000) + .set("Engine", "EDBrakeV0", 2) + .set("Engine", "EDBrakeV1", 6); +} + +// a resistor brake of a locomotive with direct current motors, on the ST44 (M62): a lever of 8 steps, the force +// growing with the speed up to 120 kN at 40 km/h, the resistors taking 1200 kW +definition st44_braking() { + return definition::fiz("st44_v2/m62-1151") + .set("Cntrl", "DBPN", 8) + .set("Engine", "EDBrake", "Lever") + .set("Engine", "EDBrakeFmax", 120) + .set("Engine", "EDBrakePmax", 1200) + .set("Engine", "EDBrakeV0", 0) + .set("Engine", "EDBrakeV1", 40); +} + +// the force of the brakes above at full effort at the speed of the vehicle +double br285_limit(physics::Vehicle const &Vehicle) { + return std::min(150000.0, 2000000.0 / std::abs(Vehicle.V())) * std::clamp((Vehicle.Vel - 2.0) / 4.0, 0.0, 1.0); +} +double st44_limit(physics::Vehicle const &Vehicle) { + return std::min(120000.0, 1200000.0 / std::abs(Vehicle.V())) * std::clamp(Vehicle.Vel / 40.0, 0.0, 1.0); +} + +// the controller of the BR285 down to the given position, a step a time +void controller_to(physics::Vehicle &Locomotive, int Position) { + while (Locomotive.MainCtrlPos() > Position && Locomotive.DecMainCtrl(1)) {} + while (Locomotive.MainCtrlPos() < Position && Locomotive.IncMainCtrl(1)) {} +} + +} // namespace + +TEST_CASE("diesel-electric dynamic brake: none without its definition") { + // no game vehicle defines it: the diesel-electric ones load without, the BR285's braking positions brake nothing + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::vehicle vehicle{definition::fiz(path)}; + CHECK(vehicle->DEDynamicBrake.source == physics::Vehicle::diesel_electric_dynamic_brake::control::none); + } + scenario scenario{"dynamic brake/diesel electric/br285 without", motion() + traction() + dynamic_brake()}; + scenario.add("br285_v1/br285", 1); + REQUIRE(scenario.start_up()); + auto &locomotive{scenario.cab()}; + scenario.get_going(); + scenario.full_power(40.0); + auto const speed{locomotive.Vel}; + REQUIRE(speed > 30.0); + scenario.act("braking range"); + controller_to(locomotive, 0); + scenario.wait(15.0); + CHECK(locomotive.EimicReal() == doctest::Approx(-1.0)); + CHECK(locomotive.Ft() == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); + // coasting: braking with the power of the resistors above, it would lose more than 30 km/h + CHECK(locomotive.Vel > speed - 12.0); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: the BR285's controller") { + // the braking positions of the TRAXX controller: EB+ raises the braking effort, EB holds it, EB- lowers it. + // the force is limited by the power of the resistors at speed, holds below that, fades out at the stop; the + // air brake stays off + scenario scenario{"dynamic brake/diesel electric/br285", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(br285_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == physics::Vehicle::diesel_electric_dynamic_brake::control::controller); + CHECK(locomotive.DEDynamicBrake.max_force == doctest::Approx(150000.0)); + CHECK(locomotive.DEDynamicBrake.max_power == doctest::Approx(2000000.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + REQUIRE(locomotive.Vel > 60.0); + + scenario.act("EB+"); + controller_to(locomotive, 0); + scenario.wait(10.0); + CHECK(locomotive.EimicReal() == doctest::Approx(-1.0)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.brakes.electrodynamic.on); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft() == doctest::Approx(br285_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.Im > 0.0); + CHECK(locomotive.EngineVoltage == doctest::Approx(0.0)); + CHECK(locomotive.brakes.cylinderPressure < 0.1); + + scenario.act("EB- to half"); + controller_to(locomotive, 2); + for (int i = 0; i < 20 && locomotive.EimicReal() < -0.5; ++i) { + scenario.wait(1.0); + } + scenario.act("EB"); + controller_to(locomotive, 1); + scenario.wait(2.0); + auto const held{locomotive.EimicReal()}; + CHECK(held == doctest::Approx(-0.5).epsilon(0.35)); + scenario.wait(5.0); + CHECK(locomotive.EimicReal() == doctest::Approx(held)); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(-held).epsilon(0.01)); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + // under the power limit the force holds + REQUIRE(locomotive.Vel < 40.0); + REQUIRE(locomotive.Vel > 6.0); + CHECK(-locomotive.Ft() == doctest::Approx(150000.0).epsilon(0.01)); + for (int i = 0; i < 120 && locomotive.Vel > 4.0; ++i) { + scenario.wait(1.0); + } + // fading out + CHECK(-locomotive.Ft() < 150000.0 * 0.6); + for (int i = 0; i < 120 && locomotive.Vel > 1.5; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.Ft() == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); + // it doesn't hold the train: the air brake does + CHECK(locomotive.Vel > 0.1); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: a resistor brake with its own lever") { + // on a locomotive with direct current motors the lever sets the excitation of the motors: the force grows with + // the speed, up to the limit of the current, then of the resistors' power. it works only with the master + // controller at zero and the engine running + scenario scenario{"dynamic brake/diesel electric/st44 lever", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking(), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.source == physics::Vehicle::diesel_electric_dynamic_brake::control::lever); + CHECK(locomotive.brakes.electrodynamic.splitFromPneumatic); + CHECK(locomotive.brakes.electrodynamic.controllerPositions == 8); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(90.0); + REQUIRE(locomotive.Vel > 50.0); + + scenario.act("lever with power on"); + CHECK(locomotive.DynamicBrakeLevelSet(1.0)); + scenario.wait(5.0); + // the master controller at a power position keeps it off + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft() > 0.0); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); + + scenario.act("power off"); + scenario.notch_back(0); + scenario.wait(4.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.brakes.electrodynamic.on); + CHECK(-locomotive.Ft() == doctest::Approx(st44_limit(locomotive)).epsilon(0.01)); + CHECK(locomotive.ShowCurrent(0) > 0.0); + + scenario.act("half the lever"); + locomotive.DecDynamicBrakeLevel(4.0f); + CHECK(locomotive.brakes.electrodynamic.controllerPosition == doctest::Approx(0.5)); + for (int i = 0; i < 300 && locomotive.Vel > 20.0; ++i) { + scenario.wait(1.0); + } + REQUIRE(locomotive.Vel < 21.0); + REQUIRE(locomotive.Vel > 10.0); + // on the rising part, half the excitation + CHECK(-locomotive.Ft() == doctest::Approx(0.5 * st44_limit(locomotive)).epsilon(0.01)); + + scenario.act("engine off"); + locomotive.MainSwitch(false); + scenario.wait(1.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(0.0)); + CHECK(locomotive.Ft() == doctest::Approx(0.0)); + CHECK_FALSE(locomotive.brakes.electrodynamic.on); + scenario.check(); +} + +TEST_CASE("diesel-electric dynamic brake: blended with the locomotive's air brake") { + // EDBrakeBlending: the LSt valve lets the train brake off the locomotive while the dynamic brake takes over + // (Hamulec->SetED with the share of the force it gives); without, both brake + for (auto const blending : {false, true}) { + CAPTURE(blending); + scenario scenario{std::format("dynamic brake/diesel electric/st44 blending {}", blending), motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(st44_braking().set("Engine", "EDBrakeBlending", blending ? "Yes" : "No"), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.blending == blending); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(150.0); + scenario.notch_back(0); + scenario.act("dynamic and train brake"); + locomotive.DynamicBrakeLevelSet(1.0); + locomotive.BrakeLevelSet(locomotive.brakes.driverValve->GetPos(bh_FB)); + scenario.wait(6.0); + REQUIRE(locomotive.Vel > 15.0); + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + CHECK(locomotive.brakePipe.Pressure() < 4.6); + CHECK((locomotive.brakes.cylinderPressure < 0.2) == blending); + scenario.check(); + } +} + +TEST_CASE("diesel-electric dynamic brake: without a fade it brings the vehicle to rest") { + // EDBrakeV0 = EDBrakeV1 = 0 (the defaults): the whole force down to the stop. near it no more than what stops the + // vehicle within the step, or the force turned round each time the speed crossed zero and the vehicle never + // came to rest, the air brake being off + scenario scenario{"dynamic brake/diesel electric/br285 no fade", motion() + traction() + brakes() + dynamic_brake()}; + scenario.train().add(definition::fiz("br285_v1/br285").set("Engine", "EDBrake", "Controller").set("Engine", "EDBrakeFmax", 150), 1); + auto &locomotive{scenario.cab()}; + REQUIRE(locomotive.DEDynamicBrake.fade_low == doctest::Approx(0.0)); + REQUIRE(locomotive.DEDynamicBrake.fade_high == doctest::Approx(0.0)); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(30.0); + REQUIRE(locomotive.Vel > 10.0); + + scenario.act("EB+ to the stop"); + controller_to(locomotive, 0); + for (int i = 0; i < 120 && locomotive.V() != 0.0; ++i) { + scenario.wait(1.0); + } + CHECK(locomotive.brakes.cylinderPressure < 0.1); + // at rest, and staying there: no speed either way, no force + for (int i = 0; i < 5; ++i) { + scenario.wait(1.0); + CHECK(locomotive.V() == 0.0); + CHECK(locomotive.Ft() == doctest::Approx(0.0)); + } + CHECK(locomotive.DEDynamicBrake.level == doctest::Approx(1.0)); + scenario.check(); +} diff --git a/tests/unit/test_editor_http.cpp b/tests/unit/test_editor_http.cpp index ffdfe9959..a3abfc6b7 100644 --- a/tests/unit/test_editor_http.cpp +++ b/tests/unit/test_editor_http.cpp @@ -91,6 +91,21 @@ bool proxied() { } // namespace +TEST_CASE("editor http: a build with an http client has it at run time") { +#if defined(_WIN32) || defined(EU07_WITH_CURL) + // WinHTTP comes with Windows. libcurl isn't linked, it's loaded when first needed: a build made with its headers runs + // on a system that has it, so the tests below don't quietly skip a libcurl that failed to load + CHECK(editor_http::available()); +#else + CHECK_FALSE(editor_http::available()); + editor_http::client client; + std::vector data; + std::string error; + CHECK_FALSE(client.get("http://127.0.0.1/", data, error, []() { return false; })); + CHECK_FALSE(error.empty()); +#endif +} + TEST_CASE("editor http: a request a service doesn't answer is given up as soon as a stop is asked for") { if (false == editor_http::available() || proxied()) return; // a build with no http client, or a proxy in the way diff --git a/tests/unit/test_editor_switch_drives.cpp b/tests/unit/test_editor_switch_drives.cpp new file mode 100644 index 000000000..aeff9c7e2 --- /dev/null +++ b/tests/unit/test_editor_switch_drives.cpp @@ -0,0 +1,171 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorSwitchDrives.hpp" + +#include +#include +#include +#include +#include + +namespace { + +// a track of the scenery: its name as written, and whether the editor removed it +struct track +{ + std::string name; + bool removed{false}; +}; + +// the scenery as the game finds its tracks: Paths finds a name as written or lower case, the later of two tracks of a name; a track +// deleted takes its name away (editor_track::retire()), Retired lists those names +struct scenery +{ + std::vector tracks; + std::vector retired; + int lookups{0}; // of the whole sequence + + std::optional find(std::string const &Name) const + { + auto const name{switch_drives::game_name(Name)}; + if (std::ranges::find(retired, name) != retired.end()) + return std::nullopt; + std::optional found; + for (auto const &entry : tracks) + if (switch_drives::game_name(entry.name) == name) + found = entry.removed; // the later one + return found; + } + + std::vector standing() + { + ++lookups; + std::vector names; + for (auto const &entry : tracks) + if (false == entry.removed) + names.push_back(entry.name); + return names; + } + + switch_drives::standing_switches lookup() + { + return switch_drives::standing_switches{[this](std::string const &Name) { return find(Name); }, [this] { return standing(); }}; + } + + // deletes the later track of the name, as the editor does + void erase_later(std::string const &Name) + { + auto const name{switch_drives::game_name(Name)}; + for (auto entry{tracks.rbegin()}; entry != tracks.rend(); ++entry) + if (switch_drives::game_name(entry->name) == name && false == entry->removed) + { + entry->removed = true; + retired.push_back(name); + return; + } + } +}; + +} // namespace + +TEST_CASE("switch drives: a name is found as the game finds it") +{ + CHECK(switch_drives::game_name("Zwr\\12A") == "zwr/12a"); + CHECK(switch_drives::game_name("zwr_1") == "zwr_1"); + + scenery line{{{"Zwr1"}, {"zwr2", true}}, {}}; + auto switches{line.lookup()}; + CHECK(switches.stands("Zwr1")); + CHECK(switches.stands("ZWR1")); + // one the name finds, removed, doesn't stand + CHECK_FALSE(switches.stands("zwr2")); + CHECK_FALSE(switches.stands("zwr3")); +} + +TEST_CASE("switch drives: two switches of one name, the later deleted, leave the drive throwing the earlier") +{ + // an older scenery has two tracks of the name; the drive set to it throws the one the game finds + scenery line{{{"zwr7"}, {"other"}, {"Zwr7"}}, {}}; + line.erase_later("zwr7"); + REQUIRE_FALSE(line.find("zwr7").has_value()); // the name went with the track deleted + { + auto switches{line.lookup()}; + // the earlier one still stands: the drive isn't stray, and a hint to delete it would delete a working drive + CHECK(switches.stands("zwr7")); + CHECK(switches.stands("ZWR7")); + CHECK(switches.any_stands({"zwr7"})); + CHECK_FALSE(switches.stands("zwr8")); + // the tracks of the scenery are read once, however many names find none + CHECK(line.lookups == 1); + } + // both deleted: the drive throws nothing now + line.erase_later("zwr7"); + auto switches{line.lookup()}; + CHECK_FALSE(switches.stands("zwr7")); + CHECK_FALSE(switches.any_stands({"zwr7"})); +} + +TEST_CASE("switch drives: the drive of a double switch stands while one of its four switches does") +{ + scenery line{{{"dkw1a"}, {"dkw1b"}, {"dkw1c"}, {"dkw1d"}}, {}}; + std::vector const names{"dkw1a", "dkw1b", "dkw1c", "dkw1d"}; + for (auto const *name : {"dkw1a", "dkw1b", "dkw1c"}) + { + line.erase_later(name); + CHECK(line.lookup().any_stands(names)); + } + line.erase_later("dkw1d"); + CHECK_FALSE(line.lookup().any_stands(names)); +} + +TEST_CASE("switch drives: the switches of a template are read once while the templates stay the same") +{ + switch_drives::template_switches templates; + std::map reads; + std::map> files{{"napedy/naped_l.inc", {""}}, {"napedy/dkw.inc", {"a", "b", "c", "d"}}, {"podsypka.inc", {}}}; + auto const read = [&reads, &files](std::string const &File, std::vector &Suffixes) { + ++reads[File]; + auto const found{files.find(File)}; + if (found == files.end()) + return false; + Suffixes = found->second; + return true; + }; + + SUBCASE("read once in a revision") + { + CHECK(templates.of("napedy/naped_l.inc", 1, 10, read) == std::vector{""}); + CHECK(templates.of("napedy/naped_l.inc", 1, 11, read) == std::vector{""}); + CHECK(templates.of("napedy/dkw.inc", 1, 12, read).size() == 4); + CHECK(templates.of("podsypka.inc", 1, 12, read).empty()); + CHECK(templates.of("podsypka.inc", 1, 13, read).empty()); + CHECK(reads["napedy/naped_l.inc"] == 1); + CHECK(reads["napedy/dkw.inc"] == 1); + CHECK(reads["podsypka.inc"] == 1); + } + + SUBCASE("a template changed is read again in the next revision") + { + CHECK(templates.of("napedy/naped_l.inc", 1, 10, read) == std::vector{""}); + // saved in the editor, or changed on the disk and rescanned: no drive any more + files["napedy/naped_l.inc"] = {}; + CHECK(templates.of("napedy/naped_l.inc", 1, 11, read) == std::vector{""}); + CHECK(templates.of("napedy/naped_l.inc", 2, 11, read).empty()); + CHECK(reads["napedy/naped_l.inc"] == 2); + } + + SUBCASE("a file that can't be read is tried again in a later frame") + { + CHECK(templates.of("napedy/nowy.inc", 1, 10, read).empty()); + // each include of it asks in the same frame: read once + CHECK(templates.of("napedy/nowy.inc", 1, 10, read).empty()); + CHECK(reads["napedy/nowy.inc"] == 1); + CHECK(templates.of("napedy/nowy.inc", 1, 11, read).empty()); + CHECK(reads["napedy/nowy.inc"] == 2); + // there now, with the same revision: no rescan needed + files["napedy/nowy.inc"] = {""}; + CHECK(templates.of("napedy/nowy.inc", 1, 12, read) == std::vector{""}); + CHECK(templates.of("napedy/nowy.inc", 1, 13, read) == std::vector{""}); + CHECK(reads["napedy/nowy.inc"] == 3); + } +} diff --git a/tests/unit/test_elf_controller.cpp b/tests/unit/test_elf_controller.cpp index 212ed51d0..f3b9a21c6 100644 --- a/tests/unit/test_elf_controller.cpp +++ b/tests/unit/test_elf_controller.cpp @@ -3,9 +3,11 @@ #include "consist.h" #include "drive.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" +#include #include +#include #include // the master controller of the Elf (EIMCtrlType 2): its positions, and the emergency brake position below @@ -26,10 +28,14 @@ enum class data { plain, emergency, emergency_old_layout }; // controller's eimic is worked out there) struct elf { explicit elf(bool Emergency) : elf({Emergency ? data::emergency : data::plain}) {} - explicit elf(std::initializer_list Units) { + // HoldingBrakeDelay, when given, goes to every car as SBDReleaseDelay + explicit elf(std::initializer_list Units, std::optional HoldingBrakeDelay = std::nullopt) { for (auto const units : Units) { for (auto const *car : {"elf_v1/21we-a", "elf_v1/21we-b", "elf_v1/21we-c"}) { auto cardefinition{definition::fiz(car)}; + if (HoldingBrakeDelay) { + cardefinition.set("Cntrl", "SBDReleaseDelay", *HoldingBrakeDelay); + } if (units != data::plain) { cardefinition.set("Cntrl", "EIMCtrlMainEmergency", "Yes"); } @@ -50,29 +56,29 @@ struct elf { for (int i = 0; i < 3 && cab().DirActive <= 0; ++i) { cab().DirectionForward(); } - while (cab().MainCtrlPos < cab().MainCtrlNoPowerPos() && cab().IncMainCtrl(1)) { + while (cab().MainCtrlPos() < cab().MainCtrlNoPowerPos() && cab().IncMainCtrl(1)) { // up to neutral } test::release_brakes(cab()); recharge(); - charged = cab().PipePress > 4.5; + charged = cab().brakePipe.Pressure() > 4.5; } // the pipe charged again after an emergency stop: the Elf locks its emptied pipe off the brake handle (LPOn, // LPOff) until the unlock button (UBB1, the first universal brake button) is held, the handle at running void recharge() { - cab().BrakeLevelSet(cab().Handle->GetPos(bh_RP)); + cab().BrakeLevelSet(cab().brakes.driverValve->GetPos(bh_RP)); cab().UniversalBrakeButton(0, 1); wait(30.0); cab().UniversalBrakeButton(0, 0); wait(30.0); } - TMoverParameters &cab() { return unit[0].mover(); } - TMoverParameters &car(std::size_t Index) { return unit[Index].mover(); } + physics::Vehicle &cab() { return unit[0].physics(); } + physics::Vehicle &car(std::size_t Index) { return unit[Index].physics(); } // the driver moves the controller notch by notch, which the cab sends on to the coupled vehicles void set_controller(int Position) { - while (cab().MainCtrlPos < Position && cab().IncMainCtrl(1)) { + while (cab().MainCtrlPos() < Position && cab().IncMainCtrl(1)) { } - while (cab().MainCtrlPos > Position && cab().DecMainCtrl(1)) { + while (cab().MainCtrlPos() > Position && cab().DecMainCtrl(1)) { } } void wait(double Seconds) { test::drive(test::driving(unit), line, Seconds); } @@ -88,62 +94,62 @@ TEST_CASE("elf controller: without EIMCtrlMainEmergency the positions stay as th elf unit{false}; REQUIRE(unit.ready); REQUIRE(unit.charged); - auto &mover{unit.cab()}; - CHECK_FALSE(mover.EIMCtrlMainEmergency); - CHECK(mover.EIMCtrlEmergencyPositions() == 0); - CHECK(mover.MainCtrlPosNo == 4); - CHECK(mover.MainCtrlNoPowerPos() == 3); - CHECK(mover.MainCtrlPos == 3); + auto &physics{unit.cab()}; + CHECK_FALSE(physics.EIMCtrlMainEmergency()); + CHECK(physics.EIMCtrlEmergencyPositions() == 0); + CHECK(physics.MainCtrlPosNo == 4); + CHECK(physics.MainCtrlNoPowerPos() == 3); + CHECK(physics.MainCtrlPos() == 3); // the lowest position brakes fully, without emptying the pipe - mover.MainCtrlPos = 0; - CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + physics.SetMainCtrlPos(0); + CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.wait(10.0); - CHECK(mover.eimic == doctest::Approx(-1.0)); - CHECK(mover.PipePress > 4.5); + CHECK(physics.eimic == doctest::Approx(-1.0)); + CHECK(physics.brakePipe.Pressure() > 4.5); } TEST_CASE("elf controller: EIMCtrlMainEmergency shifts the positions up by the emergency brake one") { elf unit{true}; REQUIRE(unit.ready); REQUIRE(unit.charged); - auto &mover{unit.cab()}; - CHECK(mover.EIMCtrlMainEmergency); - CHECK(mover.EIMCtrlEmergencyPositions() == 1); - CHECK(mover.MainCtrlPosNo == 5); - CHECK(mover.MainCtrlNoPowerPos() == 4); - CHECK(mover.MainCtrlPos == 4); - CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + auto &physics{unit.cab()}; + CHECK(physics.EIMCtrlMainEmergency()); + CHECK(physics.EIMCtrlEmergencyPositions() == 1); + CHECK(physics.MainCtrlPosNo == 5); + CHECK(physics.MainCtrlNoPowerPos() == 4); + CHECK(physics.MainCtrlPos() == 4); + CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); SUBCASE("the neutral position neither drives nor brakes") { unit.wait(5.0); - CHECK(mover.eimic == doctest::Approx(0.0)); + CHECK(physics.eimic == doctest::Approx(0.0)); } SUBCASE("the full braking position, formerly 0, brakes fully without emptying the pipe") { - mover.MainCtrlPos = 1; + physics.SetMainCtrlPos(1); unit.wait(10.0); - CHECK(mover.eimic == doctest::Approx(-1.0)); - CHECK(mover.PipePress > 4.5); + CHECK(physics.eimic == doctest::Approx(-1.0)); + CHECK(physics.brakePipe.Pressure() > 4.5); } SUBCASE("the braking position, formerly 1, ramps the braking up") { - mover.MainCtrlPos = 2; + physics.SetMainCtrlPos(2); unit.wait(1.0); - CHECK(mover.eimic < 0.0); - CHECK(mover.eimic > -1.0); - CHECK(mover.PipePress > 4.5); + CHECK(physics.eimic < 0.0); + CHECK(physics.eimic > -1.0); + CHECK(physics.brakePipe.Pressure() > 4.5); } SUBCASE("the emergency brake position brakes fully at once and empties the pipe") { - mover.MainCtrlPos = 0; - CHECK(mover.IsMainCtrlEmergencyPos()); + physics.SetMainCtrlPos(0); + CHECK(physics.IsMainCtrlEmergencyPos()); // a single step of the physics unit.unit.step(unit.line); - CHECK(mover.eimic == doctest::Approx(-1.0)); + CHECK(physics.eimic == doctest::Approx(-1.0)); unit.wait(10.0); - CHECK(mover.PipePress < 0.5); - CHECK(mover.BrakePress > 1.0); + CHECK(physics.brakePipe.Pressure() < 0.5); + CHECK(physics.brakes.cylinderPressure > 1.0); // out of it the pipe charges again - mover.MainCtrlPos = mover.MainCtrlNoPowerPos(); - CHECK_FALSE(mover.IsMainCtrlEmergencyPos()); + physics.SetMainCtrlPos(physics.MainCtrlNoPowerPos()); + CHECK_FALSE(physics.IsMainCtrlEmergencyPos()); unit.recharge(); - CHECK(mover.PipePress > 4.5); + CHECK(physics.brakePipe.Pressure() > 4.5); } } @@ -152,31 +158,31 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency with the old MCPN gets its posit CHECK(car->MainCtrlPosNo == 5); CHECK(car->MainCtrlNoPowerPos() == 4); // DirChangeMaxPos=3 of the file, the old neutral, moves up with the positions - CHECK(car->MainCtrlMaxDirChangePos == 4); + CHECK(car->MainCtrlMaxDirChangePos() == 4); } TEST_CASE("elf controller: EIMCtrlMainEmergency leaves DirChangeMaxPos of the files updated for it alone") { vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "EIMCtrlMainEmergency", "Yes").set("Cntrl", "MCPN", 5).set("Cntrl", "DirChangeMaxPos", 4)}; CHECK(car->MainCtrlPosNo == 5); - CHECK(car->MainCtrlMaxDirChangePos == 4); + CHECK(car->MainCtrlMaxDirChangePos() == 4); } TEST_CASE("elf controller: the reverser works at the neutral shifted by EIMCtrlMainEmergency") { // the key added to the old files, DirChangeMaxPos=3 in them elf unit{{data::emergency_old_layout}}; REQUIRE(unit.ready); - auto &mover{unit.cab()}; - REQUIRE(mover.MainCtrlPos == mover.MainCtrlNoPowerPos()); - REQUIRE(mover.DirActive == 1); - CHECK(mover.DirectionBackward()); - CHECK(mover.DirActive == 0); - CHECK(mover.DirectionForward()); - CHECK(mover.DirActive == 1); + auto &physics{unit.cab()}; + REQUIRE(physics.MainCtrlPos() == physics.MainCtrlNoPowerPos()); + REQUIRE(physics.DirActive == 1); + CHECK(physics.DirectionBackward()); + CHECK(physics.DirActive == 0); + CHECK(physics.DirectionForward()); + CHECK(physics.DirActive == 1); // not in the power position - unit.set_controller(mover.MainCtrlNoPowerPos() + 1); - REQUIRE(mover.MainCtrlPos == 5); - CHECK_FALSE(mover.DirectionBackward()); - CHECK(mover.DirActive == 1); + unit.set_controller(physics.MainCtrlNoPowerPos() + 1); + REQUIRE(physics.MainCtrlPos() == 5); + CHECK_FALSE(physics.DirectionBackward()); + CHECK(physics.DirActive == 1); } TEST_CASE("elf controller: the emergency brake position vents the pipe only from the vehicle driven from") { @@ -185,12 +191,12 @@ TEST_CASE("elf controller: the emergency brake position vents the pipe only from REQUIRE(unit.charged); // the rear car, with its own cab, has its controller in the emergency brake position, the driven one not auto &rear{unit.car(2)}; - rear.MainCtrlPos = 0; + rear.SetMainCtrlPos(0); CHECK(rear.IsMainCtrlEmergencyPos()); CHECK_FALSE(rear.IsCabMaster()); unit.wait(10.0); - CHECK(unit.cab().PipePress > 4.5); - CHECK(rear.PipePress > 4.5); + CHECK(unit.cab().brakePipe.Pressure() > 4.5); + CHECK(rear.brakePipe.Pressure() > 4.5); } TEST_CASE("elf controller: an Elf with the emergency brake position leading one without it") { @@ -199,27 +205,27 @@ TEST_CASE("elf controller: an Elf with the emergency brake position leading one REQUIRE(unit.charged); auto &lead{unit.cab()}; auto &other{unit.car(3)}; - REQUIRE_FALSE(other.EIMCtrlMainEmergency); + REQUIRE_FALSE(other.EIMCtrlMainEmergency()); // neutral of the lead is neutral of the other - CHECK(lead.MainCtrlPos == 4); - CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos()); + CHECK(lead.MainCtrlPos() == 4); + CHECK(other.MainCtrlPos() == other.MainCtrlNoPowerPos()); SUBCASE("power") { unit.set_controller(5); - CHECK(other.MainCtrlPos == 4); + CHECK(other.MainCtrlPos() == 4); } SUBCASE("full braking") { unit.set_controller(1); - CHECK(other.MainCtrlPos == 0); + CHECK(other.MainCtrlPos() == 0); unit.wait(10.0); - CHECK(lead.PipePress > 4.5); + CHECK(lead.brakePipe.Pressure() > 4.5); } SUBCASE("the emergency brake: the other one at its full braking, the pipe vented by the lead") { unit.set_controller(0); REQUIRE(lead.IsMainCtrlEmergencyPos()); - CHECK(other.MainCtrlPos == 0); + CHECK(other.MainCtrlPos() == 0); unit.wait(10.0); - CHECK(lead.PipePress < 0.5); - CHECK(other.PipePress < 0.5); + CHECK(lead.brakePipe.Pressure() < 0.5); + CHECK(other.brakePipe.Pressure() < 0.5); } } @@ -229,20 +235,20 @@ TEST_CASE("elf controller: an Elf without the emergency brake position leading o REQUIRE(unit.charged); auto &lead{unit.cab()}; auto &other{unit.car(3)}; - REQUIRE(other.EIMCtrlMainEmergency); - CHECK(lead.MainCtrlPos == 3); - CHECK(other.MainCtrlPos == other.MainCtrlNoPowerPos()); + REQUIRE(other.EIMCtrlMainEmergency()); + CHECK(lead.MainCtrlPos() == 3); + CHECK(other.MainCtrlPos() == other.MainCtrlNoPowerPos()); SUBCASE("power") { unit.set_controller(4); - CHECK(other.MainCtrlPos == 5); + CHECK(other.MainCtrlPos() == 5); } SUBCASE("the full braking of the lead is the full braking of the other, not its emergency brake") { unit.set_controller(0); - CHECK(other.MainCtrlPos == 1); + CHECK(other.MainCtrlPos() == 1); CHECK_FALSE(other.IsMainCtrlEmergencyPos()); unit.wait(10.0); - CHECK(lead.PipePress > 4.5); - CHECK(other.PipePress > 4.5); + CHECK(lead.brakePipe.Pressure() > 4.5); + CHECK(other.brakePipe.Pressure() > 4.5); } } @@ -251,6 +257,280 @@ TEST_CASE("elf controller: EIMCtrlMainEmergency leaves the other controllers alo vehicle impuls{definition::fiz("impuls_v1/31we-a_pr").set("Cntrl", "EIMCtrlMainEmergency", "Yes"), 60.0, "impuls", 1}; CHECK(impuls->EIMCtrlEmergencyPositions() == 0); CHECK(impuls->MainCtrlPosNo == 10); - impuls->MainCtrlPos = 0; + impuls->SetMainCtrlPos(0); CHECK_FALSE(impuls->IsMainCtrlEmergencyPos()); } + +// the holding brake of the Elf (SBD) lets go only once power has been demanded for SBDReleaseDelay (eu07/maszyna#556): +// the release waits the initial delay of the controller (IniCDelay) instead of going at the first percent of the +// demand. TDynamicObject::Update() works the holding brake out, its MED isn't in the tests, so they do here what it +// does with it: physics::Vehicle::UpdateStopBrakeRelease() of the cab with its demand after every step and, where the +// brake matters, the brake's share of every car on its cylinders (LocalBrakePosAEIM) + +namespace { + +constexpr double step_time{0.01}; // of a step of the tests, see test::consist::step() +constexpr double elf_delay{1.0}; // IniCDelay of the Elf with a cab + +// the time from the start to the first step with the holding brake let go, the brake worked out after every step; +// Act runs before every step with the time so far. negative when it holds all the time +template double release_time(elf &Unit, double Seconds, Action Act) { + auto &cab{Unit.cab()}; + auto const steps{std::lround(Seconds / step_time)}; + for (long i = 0; i < steps; ++i) { + auto const time{i * step_time}; + Act(time); + Unit.unit.step(Unit.line); + if (cab.UpdateStopBrakeRelease(cab.EimicReal(), step_time)) { + return time; + } + } + return -1.0; +} + +// the holding brake of TDynamicObject::Update() at standstill: brakes.holding.deceleration (SBD) times the mass of the train, shared out +// by the axles, each car's share made a position of its brake valve (LocalBrakePosAEIM) as there. at standstill the +// electric brake makes no part of it +void hold(elf &Unit, bool Hold) { + auto mass{0.0}; + auto axles{0}; + for (std::size_t i = 0; i < Unit.unit.size(); ++i) { + mass += Unit.car(i).TotalMass(); + axles += Unit.car(i).NAxles(); + } + auto const force{Unit.cab().brakes.holding.deceleration * mass}; + for (std::size_t i = 0; i < Unit.unit.size(); ++i) { + auto &car{Unit.car(i)}; + auto const nmax{((car.brakes.config.pressureToForce * car.brakes.config.maxCylinderPressure[0] - car.brakes.config.cylinders.springForce) * car.brakes.config.cylinders.leverRatio[0] - car.brakes.config.cylinders.slackAdjusterForce) * car.brakes.config.cylinders.count * car.brakes.config.cylinders.riggingEfficiency}; + auto const fmax{nmax * car.brakes.distributor->GetFC(nmax / (car.NAxles() * car.brakes.config.blocksPerAxle), car.brakes.blending.referenceSpeed) * 1000}; + auto position{Hold ? force * car.NAxles() / axles / fmax : 0.0}; + if (position > 0.009) { + auto const slack{(car.brakes.config.cylinders.slackAdjusterForce / car.brakes.config.cylinders.leverRatio[0] + car.brakes.config.cylinders.springForce) / (car.brakes.config.pressureToForce * car.brakes.config.maxCylinderPressure[0])}; + position = slack + (1 - slack) * position; + } + else { + position = 0.0; + } + car.brakes.SetIndependentPositionEim(position); + } +} + +// how a start of the Elf goes with its holding brake +struct start { + double release{-1.0}; // the time the holding brake let go + double moving{-1.0}; // the time the train got above 0.5 km/h + double running{-1.0}; // the time it got above 10 km/h + double demand{0.0}; // of the controller when the brake let go + double pressure{0.0}; // in the brake cylinders of the cab car then +}; + +// the brake applied at standstill, then Act before every step with the time from the start; the brake let go as +// TDynamicObject::Update() lets it go (in ShuntMode, until above 1 km/h) +template start start_off(elf &Unit, double Seconds, Action Act) { + auto &cab{Unit.cab()}; + // the train stands held, its cylinders filled + hold(Unit, true); + Unit.wait(10.0); + start result; + result.pressure = cab.brakes.cylinderPressure; + auto shuntmode{true}; + auto const steps{std::lround(Seconds / step_time)}; + for (long i = 0; i < steps && result.running < 0.0; ++i) { + auto const time{i * step_time}; + Act(time); + Unit.unit.step(Unit.line); + auto const released{cab.UpdateStopBrakeRelease(cab.EimicReal(), step_time)}; + if (cab.Vel > 1.0) { + shuntmode = false; + } + hold(Unit, shuntmode && false == released); + if (released && result.release < 0.0) { + result.release = time; + result.demand = cab.EimicReal(); + } + if (cab.Vel > 0.5 && result.moving < 0.0) { + result.moving = time; + } + if (cab.Vel > 10.0) { + result.running = time; + } + } + return result; +} + +void flick(elf &Unit, double Time) { + Unit.set_controller(Time < 0.5 * step_time ? 4 : 3); +} + +} // namespace + +TEST_CASE("elf holding brake: without SBDReleaseDelay it lets go at the first demand, as it always did") { + vehicle car{definition::fiz("elf_v1/21we-a")}; + CHECK(car->brakes.holding.deceleration == doctest::Approx(0.6)); + CHECK(car->brakes.holding.releaseDelay == 0.0); + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); + CHECK_FALSE(car->UpdateStopBrakeRelease(-0.5, step_time)); + CHECK(car->UpdateStopBrakeRelease(0.001, step_time)); + CHECK(car->UpdateStopBrakeRelease(0.01, step_time)); + // and holds again at no demand + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); +} + +TEST_CASE("elf holding brake: SBDReleaseDelay holds it for that long of a demand") { + vehicle car{definition::fiz("elf_v1/21we-a").set("Cntrl", "SBDReleaseDelay", 1.0)}; + REQUIRE(car->brakes.holding.releaseDelay == doctest::Approx(1.0)); + // the demand rises above 0 in the step of time 0 + long held{0}; + while (held < 500 && false == car->UpdateStopBrakeRelease(0.01, step_time)) { + ++held; + } + CHECK(held * step_time == doctest::Approx(1.0).epsilon(0.015)); + // it holds again once there's no demand, and waits the whole delay again for the next one + CHECK_FALSE(car->UpdateStopBrakeRelease(0.0, step_time)); + CHECK(car->brakes.holding.releaseTimer == 0.0); + CHECK_FALSE(car->UpdateStopBrakeRelease(0.01, step_time)); +} + +TEST_CASE("elf holding brake: the controller held at power") { + SUBCASE("without SBDReleaseDelay the brake lets go at the first step of the power position, at 1%") { + elf unit{{data::plain}}; + REQUIRE(unit.ready); + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + CHECK(release == doctest::Approx(0.0)); + CHECK(unit.cab().EimicReal() == doctest::Approx(0.01)); + } + SUBCASE("with SBDReleaseDelay=1.0 it lets go as the demand starts to ramp up, about 1 s on") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + // the 1% of the first step is all there is until then + auto const demand{cab.EimicReal()}; + // the step the ramp of the demand starts at + auto rampstart{release}; + while (cab.EimicReal() < 0.0101 && rampstart < 5.0) { + rampstart += step_time; + unit.unit.step(unit.line); + } + MESSAGE("held: release " << release << " s at " << demand << ", ramp from " << rampstart << " s"); + CHECK(release == doctest::Approx(1.0).epsilon(0.015)); + CHECK(demand == doctest::Approx(0.01).epsilon(0.02)); + // it lets go within a step of the ramp's start + CHECK(std::abs(release - rampstart) <= 1.5 * step_time); + } +} + +TEST_CASE("elf holding brake: the controller flicked to power once and back to holding the power") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double Time) { flick(unit, Time); })}; + MESSAGE("flick: release " << release << " s, demand " << cab.EimicReal()); + CHECK(release == doctest::Approx(1.0).epsilon(0.015)); + // the demand stays at the 1% of the flick + CHECK(cab.EimicReal() == doctest::Approx(0.01).epsilon(0.02)); +} + +TEST_CASE("elf holding brake: a demand dropped to zero before the delay starts the count again") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + // power for 0.5 s, the braking position for 0.2 s (no demand), then power again + auto const release{release_time(unit, 5.0, [&unit](double Time) { unit.set_controller(Time > 0.495 && Time < 0.695 ? 2 : 4); })}; + MESSAGE("restart: release " << release << " s"); + CHECK(release == doctest::Approx(1.7).epsilon(0.01)); + CHECK(cab.EimicReal() > 0.0); +} + +TEST_CASE("elf holding brake: it comes back when the demand drops to zero at standstill") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto const release{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + REQUIRE(release > 0.0); + // the braking position takes the demand off: the brake holds from the next step + unit.set_controller(2); + unit.unit.step(unit.line); + CHECK(cab.EimicReal() <= 0.0); + CHECK_FALSE(cab.UpdateStopBrakeRelease(cab.EimicReal(), step_time)); + // and power demanded again waits the delay again + auto const again{release_time(unit, 5.0, [&unit](double) { unit.set_controller(4); })}; + CHECK(again == doctest::Approx(1.0).epsilon(0.015)); +} + +TEST_CASE("elf holding brake: two Elfs coupled let it go as one does") { + elf one{{data::plain}, elf_delay}; + elf two{{data::plain, data::plain}, elf_delay}; + REQUIRE(one.ready); + REQUIRE(two.ready); + REQUIRE(two.unit.size() == 6); + auto const oneheld{release_time(one, 5.0, [&one](double) { one.set_controller(4); })}; + auto const twoheld{release_time(two, 5.0, [&two](double) { two.set_controller(4); })}; + CHECK(oneheld == doctest::Approx(1.0).epsilon(0.015)); + CHECK(twoheld == doctest::Approx(oneheld)); + // no demand for a while, which holds the brake, then the flick + CHECK(release_time(one, 5.0, [&one](double) { one.set_controller(2); }) < 0.0); + CHECK(release_time(two, 5.0, [&two](double) { two.set_controller(2); }) < 0.0); + auto const oneflicked{release_time(one, 5.0, [&one](double Time) { flick(one, Time); })}; + auto const twoflicked{release_time(two, 5.0, [&two](double Time) { flick(two, Time); })}; + CHECK(oneflicked == doctest::Approx(1.0).epsilon(0.015)); + CHECK(twoflicked == doctest::Approx(oneflicked)); +} + +TEST_CASE("elf holding brake: the train doesn't move before the brake lets go, and starts off after it") { + // the driver and the AI both put the controller to power and keep it there: TController::CheckTimeControllers() + // drops it to holding the power once there's a demand, but IncSpeedEIM() puts it back to power in the same update + // of the AI, so the physics sees it held + elf now{{data::plain}}; + elf delayed{{data::plain}, elf_delay}; + REQUIRE(now.ready); + REQUIRE(delayed.ready); + auto const before{start_off(now, 60.0, [&now](double) { now.set_controller(4); })}; + auto const after{start_off(delayed, 60.0, [&delayed](double) { delayed.set_controller(4); })}; + MESSAGE("held brake " << before.pressure << " bar in the cab car"); + MESSAGE("without the delay: release " << before.release << " s at " << before.demand << ", moving " << before.moving << " s, 10 km/h " << before.running << " s"); + MESSAGE("with the delay: release " << after.release << " s at " << after.demand << ", moving " << after.moving << " s, 10 km/h " << after.running << " s"); + CHECK(before.pressure > 1.0); + CHECK(before.release == doctest::Approx(0.0)); + CHECK(after.release == doctest::Approx(1.0).epsilon(0.015)); + // held until then, at the 1% of the first step + CHECK(after.demand == doctest::Approx(0.01).epsilon(0.05)); + CHECK(after.moving > after.release); + // both start off, the delayed one at most the delay later + REQUIRE(before.running > 0.0); + REQUIRE(after.running > 0.0); + CHECK(after.running >= before.running); + CHECK(after.running <= before.running + elf_delay + 0.05); +} + +TEST_CASE("elf holding brake: the flick to power doesn't move the train before the brake lets go") { + elf unit{{data::plain}, elf_delay}; + REQUIRE(unit.ready); + auto const flicked{start_off(unit, 10.0, [&unit](double Time) { flick(unit, Time); })}; + MESSAGE("flick: release " << flicked.release << " s, moving " << flicked.moving << " s, speed " << unit.cab().Vel << " km/h after 10 s"); + CHECK(flicked.release == doctest::Approx(1.0).epsilon(0.015)); + CHECK((flicked.moving < 0.0 || flicked.moving > flicked.release)); +} + +TEST_CASE("elf holding brake: the force of the motors at 1% against the holding brake") { + // the numbers for the report: the holding force of the train (SBD times its mass), and what the motors of the cab + // car make at the 1% of the first step of the controller with no brake holding them back + elf unit{{data::plain}}; + REQUIRE(unit.ready); + auto &cab{unit.cab()}; + auto mass{0.0}; + auto powered{0}; + for (std::size_t i = 0; i < unit.unit.size(); ++i) { + mass += unit.car(i).TotalMass(); + powered += unit.car(i).NPoweredAxles() > 0 ? 1 : 0; + } + unit.set_controller(4); + unit.unit.step(unit.line); + unit.set_controller(3); + unit.wait(5.0); + auto const holding{cab.brakes.holding.deceleration * mass}; + MESSAGE("mass " << mass << " kg, holding " << holding << " N, cars with motors " << powered << ", demand " << cab.EimicReal() << ", cab car Ft " << cab.Ft() + << " N, Fful " << cab.inductionMotor.state.fullForce << " kN, speed " << cab.Vel << " km/h after 5 s"); + CHECK(cab.EimicReal() == doctest::Approx(0.01).epsilon(0.02)); + CHECK(cab.Ft() * powered < 0.1 * holding); +} diff --git a/tests/unit/test_engine_shutdown.cpp b/tests/unit/test_engine_shutdown.cpp index 9230330f4..e5ccbec74 100644 --- a/tests/unit/test_engine_shutdown.cpp +++ b/tests/unit/test_engine_shutdown.cpp @@ -11,7 +11,7 @@ namespace { // the shunter with its engine started from the cab and idling test::vehicle running_shunter() { test::vehicle shunter{test::definition::load("diesel_shunter")}; - shunter->CabOccupied = 1; + shunter->SetCabOccupied(1); shunter->CabActivisation(); shunter->BatterySwitch(true); shunter->OilPumpSwitch(true); @@ -27,21 +27,21 @@ TEST_CASE("engine shutdown: the shunter starts with the starter button") { auto shunter{running_shunter()}; REQUIRE(shunter->EngineType == TEngineType::DieselEngine); REQUIRE(shunter->FuelPump.start_type == start_t::automatic); - CHECK(shunter->Mains); + CHECK(shunter->lineBreaker.IsClosed()); CHECK(shunter->FuelPump.is_active); - CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); + CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } TEST_CASE("engine shutdown: neither the fuel pump switch nor the battery switch stop the engine") { auto shunter{running_shunter()}; shunter->FuelPumpSwitchOff(true, range_t::local); // the pump started automatically ignores its switch shunter.run(10.0); - CHECK(shunter->Mains); + CHECK(shunter->lineBreaker.IsClosed()); shunter->BatterySwitch(false); shunter.run(10.0); - CHECK(shunter->Power110vIsAvailable); // the converter run by the engine keeps feeding the fuel pump - CHECK(shunter->Mains); - CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); + CHECK(shunter->lowVoltage.Is110vAvailable()); // the converter run by the engine keeps feeding the fuel pump + CHECK(shunter->lineBreaker.IsClosed()); + CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } TEST_CASE("engine shutdown: the command opening the main circuit stops the engine and it stays stopped") { @@ -49,7 +49,7 @@ TEST_CASE("engine shutdown: the command opening the main circuit stops the engin REQUIRE(shunter->MainCircuitOpensWithStarterOnly()); // the cab passes the command on with only the starter button CHECK(shunter->MainSwitch(false)); shunter.run(20.0); - CHECK_FALSE(shunter->Mains); + CHECK_FALSE(shunter->lineBreaker.IsClosed()); CHECK_FALSE(shunter->FuelPump.is_active); CHECK(shunter->enrot == 0.0); } @@ -61,8 +61,8 @@ TEST_CASE("engine shutdown: the engine starts again after it was stopped") { REQUIRE(shunter->enrot == 0.0); shunter->MainSwitch(true); shunter.run(15.0); - CHECK(shunter->Mains); - CHECK(shunter->enrot > 0.9 * shunter->dizel_nmin); + CHECK(shunter->lineBreaker.IsClosed()); + CHECK(shunter->enrot > 0.9 * shunter->diesel.minRevolutions); } TEST_CASE("engine shutdown: vehicles without a diesel keep ignoring the command with only the button closing the circuit") { diff --git a/tests/unit/test_engine_start.cpp b/tests/unit/test_engine_start.cpp index c721e5a1a..d8ecfe529 100644 --- a/tests/unit/test_engine_start.cpp +++ b/tests/unit/test_engine_start.cpp @@ -27,19 +27,19 @@ definition sn61(bool const Joint = true) { // pressure built up, and the controller at the first position giving the engines fuel, which a mechanical diesel // starts at: everything but the engines ready to start void prepare(consist &Train) { - auto &cab{Train[0].mover()}; + auto &cab{Train[0].physics()}; cab.BatterySwitch(true); cab.CabActivisation(); cab.OilPumpSwitch(true); cab.FuelPumpSwitch(true); - while (cab.RList[cab.MainCtrlPos].R == 0.0 && cab.IncMainCtrl(1)) { + while (cab.RList[cab.MainCtrlPos()].R == 0.0 && cab.IncMainCtrl(1)) { // up to the first position with fuel } Train.run(20.0); } -bool running(TMoverParameters const &Vehicle) { - return Vehicle.Mains && Vehicle.enrot > 0.5 * Vehicle.dizel_nmin; +bool running(physics::Vehicle const &Vehicle) { + return Vehicle.lineBreaker.IsClosed() && Vehicle.enrot > 0.5 * Vehicle.diesel.minRevolutions; } // the time step of the train in the loops below @@ -51,7 +51,7 @@ int steps(double const Seconds) { } // the switch of Engine held closed for Seconds, then let go, in steps of the train -void hold(consist &Train, engine_start::remote_switch &Switch, TMoverParameters *Engine, double const Seconds, bool const Closesonrelease = false) { +void hold(consist &Train, engine_start::remote_switch &Switch, physics::Vehicle *Engine, double const Seconds, bool const Closesonrelease = false) { for (auto step = 0; step < steps(Seconds); ++step) { Switch.update(Engine, true, false, dt, Closesonrelease); Train.step({}, dt); @@ -63,87 +63,87 @@ void hold(consist &Train, engine_start::remote_switch &Switch, TMoverParameters TEST_CASE("engine start: the joint start is the default, and JointEngineStart=No keeps the cab's switch to its vehicle") { consist train; - auto const &joint{train.add(sn61(), 1).mover()}; - auto const &separate{train.add(sn61(false)).mover()}; - CHECK(joint.JointEngineStart); - CHECK_FALSE(separate.JointEngineStart); + auto const &joint{train.add(sn61(), 1).physics()}; + auto const &separate{train.add(sn61(false)).physics()}; + CHECK(joint.lineBreaker.config.jointStart); + CHECK_FALSE(separate.lineBreaker.config.jointStart); CHECK(joint.MainSwitchRange() == range_t::consist); CHECK(separate.MainSwitchRange() == range_t::local); } TEST_CASE("engine start: the vehicles in multiple, counted from the cab's own one, those behind the cab first") { consist train; - auto &first{train.add(sn61(), 1).mover()}; - auto &second{train.add(sn61()).mover()}; - auto &third{train.add(sn61()).mover()}; + auto &first{train.add(sn61(), 1).physics()}; + auto &second{train.add(sn61()).physics()}; + auto &third{train.add(sn61()).physics()}; CHECK(engine_start::engine(first, first, 1) == &first); CHECK(engine_start::engine(first, first, 2) == &second); CHECK(engine_start::engine(first, first, 3) == &third); CHECK(engine_start::engine(first, first, 4) == nullptr); CHECK(engine_start::engine(first, first, 0) == nullptr); // from the rear cab of the first railcar the others are in front of the cab, in the same order - first.CabOccupied = -1; + first.SetCabOccupied(-1); CHECK(engine_start::engine(first, first, 2) == &second); CHECK(engine_start::engine(first, first, 3) == &third); // from the middle one, the one behind its cab comes first - second.CabOccupied = 1; + second.SetCabOccupied(1); CHECK(engine_start::engine(second, second, 2) == &third); CHECK(engine_start::engine(second, second, 3) == &first); - second.CabOccupied = -1; + second.SetCabOccupied(-1); CHECK(engine_start::engine(second, second, 2) == &first); CHECK(engine_start::engine(second, second, 3) == &third); } TEST_CASE("engine start: only the vehicles with an engine and under control through the cable count") { consist train; - auto &first{train.add(sn61(), 1).mover()}; + auto &first{train.add(sn61(), 1).physics()}; // a vehicle without an engine between the railcars is passed over - auto &trailer{train.add(definition::fiz("ed72_v1/5bs-ra")).mover()}; - auto &second{train.add(sn61()).mover()}; + auto &trailer{train.add(definition::fiz("ed72_v1/5bs-ra")).physics()}; + auto &second{train.add(sn61()).physics()}; REQUIRE(trailer.Power < 0.01); CHECK(engine_start::engine(first, first, 2) == &second); // the vehicle with the cab doesn't drive itself: its engine is in the vehicle it controls, which isn't counted twice - trailer.CabOccupied = 1; + trailer.SetCabOccupied(1); CHECK(engine_start::engine(trailer, first, 1) == &first); CHECK(engine_start::engine(trailer, first, 2) == &second); CHECK(engine_start::engine(trailer, first, 3) == nullptr); // coupled without the control cable, the other railcar isn't under the cab's control consist apart; - auto &alone{apart.add(sn61(), 1).mover()}; - apart.add(sn61(), 0, coupling::coupler | coupling::brakehose); + auto &alone{apart.add(sn61(), 1).physics()}; + apart.add(sn61(), 0, Coupling::coupler | Coupling::brakeHose); CHECK(engine_start::engine(alone, alone, 2) == nullptr); } TEST_CASE("engine start: by default the cab's switch starts and stops the engines of all the vehicles in multiple") { consist train; - auto &first{train.add(sn61(), 1).mover()}; - auto const &second{train.add(sn61()).mover()}; + auto &first{train.add(sn61(), 1).physics()}; + auto const &second{train.add(sn61()).physics()}; prepare(train); - REQUIRE_FALSE(first.Mains); - REQUIRE_FALSE(second.Mains); + REQUIRE_FALSE(first.lineBreaker.IsClosed()); + REQUIRE_FALSE(second.lineBreaker.IsClosed()); first.MainSwitch(true, first.MainSwitchRange()); train.run(15.0); CHECK(running(first)); CHECK(running(second)); first.MainSwitch(false, first.MainSwitchRange()); train.run(5.0); - CHECK_FALSE(first.Mains); - CHECK_FALSE(second.Mains); + CHECK_FALSE(first.lineBreaker.IsClosed()); + CHECK_FALSE(second.lineBreaker.IsClosed()); } TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch") { consist train; - auto &first{train.add(sn61(false), 1).mover()}; - auto &second{train.add(sn61(false)).mover()}; - auto &third{train.add(sn61(false)).mover()}; + auto &first{train.add(sn61(false), 1).physics()}; + auto &second{train.add(sn61(false)).physics()}; + auto &third{train.add(sn61(false)).physics()}; prepare(train); // the cab's own switch starts its own engine only first.MainSwitch(true, first.MainSwitchRange()); train.run(15.0); REQUIRE(running(first)); - CHECK_FALSE(second.Mains); - CHECK_FALSE(third.Mains); + CHECK_FALSE(second.lineBreaker.IsClosed()); + CHECK_FALSE(third.lineBreaker.IsClosed()); // the second one's switch, mainb_*, starts the second engine engine_start::remote_switch switchb; @@ -155,7 +155,7 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch hold(train, switchb, engineb, 2.0); // past the SN61's delay of 1.5 s train.run(15.0); CHECK(running(second)); - CHECK_FALSE(third.Mains); + CHECK_FALSE(third.lineBreaker.IsClosed()); // and the third one's, mainc_*, the third hold(train, switchc, enginec, 2.0); train.run(15.0); @@ -164,12 +164,12 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch // the switches open their own vehicles' circuits only CHECK(engine_start::remote_switch::open(second)); train.run(5.0); - CHECK_FALSE(second.Mains); + CHECK_FALSE(second.lineBreaker.IsClosed()); CHECK(running(first)); CHECK(running(third)); first.MainSwitch(false, first.MainSwitchRange()); train.run(5.0); - CHECK_FALSE(first.Mains); + CHECK_FALSE(first.lineBreaker.IsClosed()); CHECK(running(third)); CHECK_FALSE(engine_start::remote_switch::open(second)); // already stopped } @@ -177,15 +177,15 @@ TEST_CASE("engine start: with JointEngineStart=No each engine has its own switch TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's delay, with the vehicle ready") { consist train; train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0"), 1); - auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0")).mover()}; - REQUIRE(second.InitialCtrlDelay == doctest::Approx(2.0)); + auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "2.0")).physics()}; + REQUIRE(second.InitialCtrlDelay() == doctest::Approx(2.0)); engine_start::remote_switch switchb; // without the battery the switch does nothing, however long it's held hold(train, switchb, &second, 5.0); train.run(5.0); - CHECK_FALSE(second.Mains); - CHECK_FALSE(second.dizel_startup); + CHECK_FALSE(second.lineBreaker.IsClosed()); + CHECK_FALSE(second.diesel.startupRequested); prepare(train); // let go too early @@ -207,7 +207,7 @@ TEST_CASE("engine start: the switch of another vehicle is held for the vehicle's TEST_CASE("engine start: a switch closing on release, as an electric locomotive's impulse switch, waits to be let go") { consist train; train.add(sn61(false), 1); - auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "1.0")).mover()}; + auto &second{train.add(sn61(false).set("Cntrl", "IniCDelay", "1.0")).physics()}; prepare(train); engine_start::remote_switch switchb; // held past the delay, the circuit stays open while the switch is held @@ -233,8 +233,8 @@ TEST_CASE("engine start: an engine stopping on its own stops the others only whe for (auto const joint : {true, false}) { CAPTURE(joint); consist train; - auto &first{train.add(sn61(joint), 1).mover()}; - auto const &second{train.add(sn61(joint)).mover()}; + auto &first{train.add(sn61(joint), 1).physics()}; + auto const &second{train.add(sn61(joint)).physics()}; prepare(train); engine_start::remote_switch switchb; first.MainSwitch(true, first.MainSwitchRange()); @@ -245,7 +245,7 @@ TEST_CASE("engine start: an engine stopping on its own stops the others only whe // the first one's fuel cut off, its engine stops first.FuelPump.is_disabled = true; train.run(15.0); - CHECK_FALSE(first.Mains); + CHECK_FALSE(first.lineBreaker.IsClosed()); CHECK(first.enrot == 0.0); // started on their own, the others keep running CHECK(running(second) == (false == joint)); @@ -259,9 +259,9 @@ TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the consist train; // the middle railcar keeps the joint start, as a .fiz without the key does. what a vehicle without the cab relays // goes on away from the cab, so it's the third one that would stop - auto &first{train.add(sn61(false), 1).mover()}; - auto &second{train.add(sn61()).mover()}; - auto &third{train.add(sn61(false)).mover()}; + auto &first{train.add(sn61(false), 1).physics()}; + auto &second{train.add(sn61()).physics()}; + auto &third{train.add(sn61(false)).physics()}; prepare(train); engine_start::remote_switch switchb; engine_start::remote_switch switchc; @@ -275,7 +275,7 @@ TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the // mainb_off CHECK(engine_start::remote_switch::open(second)); train.run(30.0); - CHECK_FALSE(second.Mains); + CHECK_FALSE(second.lineBreaker.IsClosed()); CHECK(second.enrot == 0.0); CHECK(running(first)); CHECK(running(third)); @@ -284,15 +284,15 @@ TEST_CASE("engine start: an engine stopped from its own switch doesn't stop the TEST_CASE("engine start: the stopped engine of the cab's vehicle doesn't stop the one started from its switch") { consist train; // the cab's railcar keeps the joint start, its engine stopped - auto &first{train.add(sn61(), 1).mover()}; - auto &second{train.add(sn61(false)).mover()}; + auto &first{train.add(sn61(), 1).physics()}; + auto &second{train.add(sn61(false)).physics()}; prepare(train); - REQUIRE_FALSE(first.Mains); + REQUIRE_FALSE(first.lineBreaker.IsClosed()); // mainb_on engine_start::remote_switch switchb; hold(train, switchb, engine_start::engine(first, first, 2), 2.0); train.run(15.0); CHECK(running(second)); - CHECK_FALSE(first.Mains); + CHECK_FALSE(first.lineBreaker.IsClosed()); CHECK(first.enrot == 0.0); } diff --git a/tests/unit/test_equipment_faults.cpp b/tests/unit/test_equipment_faults.cpp new file mode 100644 index 000000000..d87d803a1 --- /dev/null +++ b/tests/unit/test_equipment_faults.cpp @@ -0,0 +1,56 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +// the faults of the equipment the scenery or the network sets on a vehicle (physics::Vehicle::SetEquipmentFaults(), +// TDynamicObject::Damage() with the number of a message) + +TEST_CASE("equipment faults: the number of a message comes back as it went in") { + auto const faults{EquipmentFaultSet::FromBits(0x2A)}; + CHECK(faults.HasAll(EquipmentFault::control)); + CHECK(faults.HasAll(EquipmentFault::compressor)); + CHECK(faults.HasAll(EquipmentFault::emergencyBrake)); + CHECK_FALSE(faults.HasAny(EquipmentFault::differentialRelay | EquipmentFault::converter | EquipmentFault::camshaft)); + CHECK(faults.Bits() == 0x2A); +} + +TEST_CASE("equipment faults: the fault of the control opens the line contactors and holds the start until it clears") { + test::vehicle loco{test::definition::fiz("4e_v1/4e")}; + auto const delay{loco->InitialCtrlDelay()}; + loco->lineContactors.Close(); + loco->SetEquipmentFaults(EquipmentFault::control); + CHECK(loco->equipmentFaults.HasAll(EquipmentFault::control)); + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->InitialCtrlDelay() > 100000000.0); + // set again, it doesn't move the delay further + loco->SetEquipmentFaults(EquipmentFault::control); + CHECK(loco->InitialCtrlDelay() < 200000000.0); + loco->SetEquipmentFaults({}); + CHECK(loco->equipmentFaults.Empty()); + CHECK(loco->InitialCtrlDelay() == doctest::Approx(delay)); +} + +TEST_CASE("equipment faults: the fault of the compressor moves its pressures out of reach, and back") { + test::vehicle loco{test::definition::fiz("4e_v1/4e")}; + auto const minpressure{loco->air.compressor.config.minPressure}; + auto const maxpressure{loco->air.compressor.config.maxPressure}; + REQUIRE(minpressure > 0.0); + loco->SetEquipmentFaults(EquipmentFault::compressor); + CHECK(loco->air.compressor.config.minPressure < 0.0); + CHECK(loco->air.compressor.config.maxPressure < 0.0); + loco->SetEquipmentFaults({}); + CHECK(loco->air.compressor.config.minPressure == doctest::Approx(minpressure)); + CHECK(loco->air.compressor.config.maxPressure == doctest::Approx(maxpressure)); +} + +TEST_CASE("equipment faults: the fault of the camshaft holds the steps of the controller until it clears") { + test::vehicle loco{test::definition::fiz("4e_v1/4e")}; + auto const delay{loco->CtrlDelay}; + auto const downdelay{loco->CtrlDownDelay}; + loco->SetEquipmentFaults(EquipmentFault::camshaft); + CHECK(loco->CtrlDelay > 100000000.0); + CHECK(loco->CtrlDownDelay > 100000000.0); + loco->SetEquipmentFaults({}); + CHECK(loco->CtrlDelay == doctest::Approx(delay)); + CHECK(loco->CtrlDownDelay == doctest::Approx(downdelay)); +} diff --git a/tests/unit/test_est3al2_relay.cpp b/tests/unit/test_est3al2_relay.cpp new file mode 100644 index 000000000..b3f730558 --- /dev/null +++ b/tests/unit/test_est3al2_relay.cpp @@ -0,0 +1,145 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "physics/brakes.h" + +#include +#include + +using test::definition; +using test::vehicle; + +// the fill and release times of the brake cylinder of an ESt3 distributor with the AL2 load relay (TNESt3 with +// TPrzekCiagly), in G and in P, with the empty/loaded lever in each of its three positions. bb43f559e made the +// relay's impulse chamber 1 l and scaled the cylinder nozzles to the times of table 3-9 of the ESt3 data; before it +// they were set by eye. this pins what the valve does today, so a change of the relay or of the nozzles shows + +namespace { + +// a Fas 413S four-axle freight wagon (pkp/413s_v1/413s.fiz of the game data): ESt3AL2, 100 l reservoir, one +// 16" cylinder, the empty/medium/loaded lever at 1.5/2.6/3.8 bar, brake delays G and P. not among the converted +// real vehicles of tests/unit/data/fiz, so its lines are set over the test wagon +definition fas_413s() { + return definition::load("wagon") + .set("Param", "M", 25300) + .set("Param", "Vmax", 100) + .set("Load", "MaxLoad", 56) + .set("Load", "LoadQ", "tonns") + .set("Load", "LoadAccepted", "coal,gravel") + .set("Dimensions", "L", 14.4) + .set("Wheels", "D", 0.92) + .set("Wheels", "Axle", "2'2'") + .set("Wheels", "Ad", 2.0) + .set("Wheels", "Bd", 8.5) + .set("Brake", "BrakeValve", "ESt3AL2") + .set("Brake", "Size", 100) + .set("Brake", "MBF", 144) + .set("Brake", "MaxBP", 3.8) + .set("Brake", "TareMaxBP", 1.5) + .set("Brake", "MedMaxBP", 2.6) + .set("Brake", "BCN", 1) + .set("Brake", "BCR", 0.2032) + .set("Brake", "BCD", 0.14) + .set("Brake", "BCM", 11.75) + .set("Brake", "NBpA", 4) + .set("Brake", "BM", "P10-Bg") + .set("Brake", "BCS", 2.7) + .set("Brake", "BSA", 16.0) + .set("Brake", "BVV", 100) + .set("Brake", "BRE", 0.8) + .set("Cntrl", "BrakeDelays", "GP") + .remove("Cntrl", "MaxBPMass"); +} + +struct times { + double charged; // in the cylinder after charging [bar] + double applied; // in the cylinder 60 s after the emergency application [bar] + double fill; // from the pipe emptied to 95% of applied [s] + double release; // from the pipe back at 5 bar to 0.4 bar in the cylinder [s] +}; + +// charges the wagon, empties the pipe at once (an emergency application) and fills it again at once, stepping +// the physics in 0.01 s steps as the game does +times measure(int const Delay, int const Lever) { + test::reseed_random(); + vehicle wagon{fas_413s()}; + REQUIRE(wagon->brakes.config.distributorType == TBrakeValve::ESt3AL2); + if (wagon->brakes.delaySetting != Delay) { + REQUIRE(wagon->BrakeDelaySwitch(Delay)); + } + // an empty wagon starts with the lever at empty (physics::Vehicle::CheckLocomotiveParameters) + REQUIRE(wagon->brakes.loadSetting == 1); + while (wagon->brakes.loadSetting < Lever) { + REQUIRE(wagon->IncBrakeMult()); + } + REQUIRE(wagon->brakes.loadSetting == Lever); + + times result{}; + wagon.hold_brake_pipe(5.0); + wagon.run(180.0); + result.charged = wagon->brakes.cylinderPressure; + + double constexpr step{0.01}; + std::vector cylinder; + wagon.hold_brake_pipe(0.0); + for (int i = 0; i < 6000; ++i) { + wagon.step(); + cylinder.push_back(wagon->brakes.cylinderPressure); + } + result.applied = cylinder.back(); + result.fill = -1.0; + for (std::size_t i = 0; i < cylinder.size(); ++i) { + if (cylinder[i] >= 0.95 * result.applied) { + result.fill = static_cast(i + 1) * step; + break; + } + } + + wagon.hold_brake_pipe(5.0); + result.release = -1.0; + for (int i = 0; i < 18000; ++i) { + wagon.step(); + if (wagon->brakes.cylinderPressure <= 0.4) { + result.release = static_cast(i + 1) * step; + break; + } + } + return result; +} + +} // namespace + +TEST_CASE("ESt3AL2: fill and release times of the cylinder of a 413S wagon, G and P, empty, medium and loaded") { + struct expected { + char const *name; + int delay; + int lever; // LoadFlag: 1 empty, 2 medium, 3 loaded + double applied; // [bar] + double fill; // [s] + double release; // [s] + }; + // measured on staging 5a24a1048, held to 1% (the pressure) and 5% (the times). the fill time is to 95% of the + // pressure 60 s after the pipe was emptied, the release time down to 0.4 bar. both count from a step of the pipe, + // 5 to 0 bar and back at once, not from the rate of a driver's brake valve or of a test bench. for comparison only, + // UIC 540 asks for G fill 18-30 s, release 45-60 s, P fill 3-5 s, release 15-20 s: the fill times are within, the + // release times shorter. the emergency application gives the cylinder 0.19-0.27 bar more than the lever's + // TareMaxBP, MedMaxBP and MaxBP (1.5, 2.6, 3.8 bar) + for (auto const &[name, delay, lever, applied, fill, release] : { + expected{"G empty", bdelay_G, 1, 1.736, 22.81, 33.89}, + expected{"G medium", bdelay_G, 2, 2.870, 21.98, 40.82}, + expected{"G loaded", bdelay_G, 3, 3.991, 21.15, 43.98}, + expected{"P empty", bdelay_P, 1, 1.737, 3.84, 10.98}, + expected{"P medium", bdelay_P, 2, 2.871, 3.71, 13.18}, + expected{"P loaded", bdelay_P, 3, 3.995, 3.62, 14.19}, + }) { + CAPTURE(name); + auto const measured{measure(delay, lever)}; + INFO(std::format("{}: charged {:.3f} bar, applied {:.3f} bar, fill {:.2f} s, release {:.2f} s", name, measured.charged, measured.applied, measured.fill, + measured.release)); + CHECK(measured.charged < 0.05); + CHECK(measured.applied == doctest::Approx(applied).epsilon(0.01)); + CHECK(measured.fill == doctest::Approx(fill).epsilon(0.05)); + CHECK(measured.release == doctest::Approx(release).epsilon(0.05)); + } +} diff --git a/tests/unit/test_event_conditions.cpp b/tests/unit/test_event_conditions.cpp new file mode 100644 index 000000000..d7c1b8e12 --- /dev/null +++ b/tests/unit/test_event_conditions.cpp @@ -0,0 +1,172 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/comparison.h" +#include "utilities/parser.h" +#include "world/Event.h" + +#include +#include +#include +#include +#include + +// the lines logged while capture is on, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +// the condition block of the multiple and updatevalues events (world/eventconditions.cpp): the scenery editor writes +// the conditions of the events back with export_as_text(), and what it writes has to read back as the same conditions + +namespace { + +// the conditions are a part of the event, open to its kinds only +struct event_kind : basic_event { + using basic_event::event_conditions; +}; +using conditions = event_kind::event_conditions; + +// the log capture is on while the object lives, so a failed REQUIRE doesn't leave it on for the cases after it +class log_capture { +public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; +}; + +// the conditions of an event text, read the way the events read them: the parser stands on the word 'condition' +conditions read(std::string const &Text) { + cParser parser(Text, cParser::buffer_TEXT); + parser.getTokens(); + REQUIRE(parser.peek() == "condition"); + conditions result; + result.deserialize(parser, "test"); + // the reading stops at the next keyword of the event and leaves it for the event + CHECK(parser.peek() == "endevent"); + return result; +} + +std::string write(conditions const &Conditions) { + std::ostringstream output; + Conditions.export_as_text(output); + return output.str(); +} + +// the conditions written and read again +conditions write_and_read(conditions const &Conditions) { + return read(write(Conditions) + "endevent"); +} + +void check_same(conditions const &Read, conditions const &Expected) { + CHECK(Read.flags == Expected.flags); + CHECK(Read.probability == Expected.probability); + CHECK(Read.memcompare_pass == Expected.memcompare_pass); + CHECK(Read.memcompare_text == Expected.memcompare_text); + CHECK(Read.memcompare_text_operator == Expected.memcompare_text_operator); + CHECK(Read.memcompare_value1 == Expected.memcompare_value1); + CHECK(Read.memcompare_value1_operator == Expected.memcompare_value1_operator); + CHECK(Read.memcompare_value2 == Expected.memcompare_value2); + CHECK(Read.memcompare_value2_operator == Expected.memcompare_value2_operator); +} + +comparison_operator const operators[]{comparison_operator::equal, comparison_operator::not_equal, comparison_operator::lt, + comparison_operator::gt, comparison_operator::lt_eq, comparison_operator::gt_eq}; +comparison_pass const passes[]{comparison_pass::all, comparison_pass::any, comparison_pass::none}; + +} // namespace + +TEST_CASE("event conditions: each comparison operator and pass is written as the word that reads back as it") { + for (auto const op : operators) { + CAPTURE(to_string(op)); + CHECK(comparison_operator_from_string(to_string(op)) == op); + } + CHECK(to_string(comparison_operator::gt_eq) == ">="); + for (auto const pass : passes) { + CAPTURE(to_string(pass)); + CHECK(comparison_pass_from_string(to_string(pass)) == pass); + } +} + +TEST_CASE("event conditions: memcompareex is written as the pass, then the operator before each compared value") { + auto const conditions{read("condition memcompareex any != Blokada >= 1 < 2.5 endevent")}; + CHECK(conditions.memcompare_pass == comparison_pass::any); + CHECK(conditions.memcompare_text == "Blokada"); + CHECK(conditions.memcompare_text_operator == comparison_operator::not_equal); + CHECK(conditions.memcompare_value1_operator == comparison_operator::gt_eq); + CHECK(conditions.memcompare_value2_operator == comparison_operator::lt); + CHECK(write(conditions) == "condition memcompareex any != Blokada >= 1.000000 < 2.500000 "); + check_same(write_and_read(conditions), conditions); +} + +TEST_CASE("event conditions: memcompareex reads back the same for every pass, operator and left out value") { + for (auto const pass : passes) { + for (auto const op : operators) { + for (unsigned int used{0}; used < 8; ++used) { + std::string text{"condition memcompareex " + to_string(pass)}; + text += (used & 1) ? " " + to_string(op) + " Zajety_tor" : std::string{" *"}; + text += (used & 2) ? " " + to_string(op) + " -3.25" : std::string{" *"}; + text += (used & 4) ? " " + to_string(op) + " 1250" : std::string{" *"}; + text += " endevent"; + CAPTURE(text); + auto const conditions{read(text)}; + CHECK(conditions.flags == used); + if (used == 0) { + // nothing compared is no condition, and no condition is written + CHECK(write(conditions).empty()); + continue; + } + check_same(write_and_read(conditions), conditions); + } + } + } +} + +TEST_CASE("event conditions: the old memcompare is written as memcompareex all with == and reads back the same") { + auto const conditions{read("condition memcompare Wolny * 3 endevent")}; + CHECK(write(conditions) == "condition memcompareex all == Wolny * == 3.000000 "); + check_same(write_and_read(conditions), conditions); + + auto const all{read("condition memcompare Wolny 1 0 endevent")}; + check_same(write_and_read(all), all); +} + +TEST_CASE("event conditions: the track and probability conditions read back along with the comparison") { + auto const conditions{read("condition trackoccupied trackfree probability 0.25 memcompareex none <= 3 * > -1.5 endevent")}; + CHECK(conditions.flags == (basic_event::flags::track_busy | basic_event::flags::track_free | basic_event::flags::probability | + basic_event::flags::text | basic_event::flags::value2)); + check_same(write_and_read(conditions), conditions); + + auto const probability{read("condition probability 0.5 endevent")}; + CHECK(write(probability) == "condition probability 0.5 "); + check_same(write_and_read(probability), probability); +} + +TEST_CASE("event conditions: an event without conditions writes none") { + CHECK(write(conditions{}).empty()); +} + +TEST_CASE("event conditions: a word the reader doesn't know is logged with the event and skipped") { + log_capture const capture; + // a name after trackfree: the track test takes the targets of the event, the name is skipped + auto const result{read("condition trackfree SomeTrack endevent")}; + auto lines{unit_tests_logged_lines()}; + + CHECK(result.flags == basic_event::flags::track_free); + REQUIRE(lines.size() == 1); + // the parser may give the word in lower case + auto &line{lines.front()}; + std::ranges::transform(line, line.begin(), [](unsigned char const Char) { return static_cast(std::tolower(Char)); }); + CHECK(line.find("\"test\"") != std::string::npos); + CHECK(line.find("\"sometrack\"") != std::string::npos); + CHECK(line.find("unknown word") != std::string::npos); +} + +TEST_CASE("event conditions: the known words log nothing") { + log_capture const capture; + auto const result{read("condition trackoccupied probability 0.5 memcompareex any == 1 * * endevent")}; + auto const lines{unit_tests_logged_lines()}; + + CHECK(result.flags == (basic_event::flags::track_busy | basic_event::flags::probability | basic_event::flags::text)); + CHECK(lines.empty()); +} diff --git a/tests/unit/test_fcfuh_default.cpp b/tests/unit/test_fcfuh_default.cpp new file mode 100644 index 000000000..bd5120915 --- /dev/null +++ b/tests/unit/test_fcfuh_default.cpp @@ -0,0 +1,153 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include +#include +#include + +using test::definition; +using test::vehicle; + +// the figure of the voltage by the frequency of an induction motor drive in the dynamic brake (fcfuH) takes the +// one of the traction (fcfu) when the definition has none. the loader took it by writing fcfu out with +// std::to_string() and reading the text back as the default of fcfuH (eu07/maszyna#99); it assigns it now + +namespace { + +// a figure read from a line the way physics::Vehicle::LoadFIZ_EngineInductionMotor() reads fcfu +double read_fcfu(std::string const &Text) { + double fcfu{0.0}; + extract_value(fcfu, "fcfu", "fcfu=" + Text, ""); + return fcfu; +} + +// fcfuH missing, the way the loader took it before: the figure written out with six decimals in the C locale +// (the game never sets another) and read back +double fcfuh_before(double const Fcfu) { + double fcfuh{-1.0}; + extract_value(fcfuh, "fcfuH", "", std::to_string(Fcfu)); + return fcfuh; +} + +// the bits of the value, which tell -0.0 from 0.0 too +std::uint64_t bits(double const Value) { + std::uint64_t result; + std::memcpy(&result, &Value, sizeof(result)); + return result; +} + +// the value with all its digits, for the message +std::string exact(double const Value) { + char text[64]; + std::snprintf(text, sizeof(text), "%.17g", Value); + return text; +} + +// a generator of its own (splitmix64), for the same numbers on every platform +struct numbers { + std::uint64_t state{0x2545f4914f6cdd1dull}; + std::uint64_t next() { + auto value{state += 0x9e3779b97f4a7c15ull}; + value = (value ^ (value >> 30)) * 0xbf58476d1ce4e5b9ull; + value = (value ^ (value >> 27)) * 0x94d049bb133111ebull; + return value ^ (value >> 31); + } +}; + +// the decimal text of Integer / 10^Decimals, as a definition could hold it +std::string decimal(std::uint64_t const Integer, int const Decimals, bool const Negative) { + auto digits{std::to_string(Integer)}; + if (Decimals > 0) { + if (digits.size() <= static_cast(Decimals)) { + digits.insert(0, Decimals + 1 - digits.size(), '0'); + } + digits.insert(digits.size() - Decimals, "."); + } + return (Negative ? "-" : "") + digits; +} + +} // namespace + +TEST_CASE("fcfuH: the figure of the traction is the same, assigned or written out and read back, for every figure of up to six decimals") { + // any decimal figure of up to six decimals: the value read from it lies within half a millionth of it, so + // std::to_string() writes the figure itself and the text reads back to the very same value. checked over the + // figures the game's definitions use (33.5 to 81.5) and the ones around them, and over many others, of up + // to six decimals and up to 18 digits, of either sign + auto compared{0}; + auto const check{[&](std::string const &Text) { + auto const fcfu{read_fcfu(Text)}; + auto const before{fcfuh_before(fcfu)}; + if (bits(before) != bits(fcfu)) { + FAIL_CHECK("fcfu=" << Text << " was " << exact(before) << " as fcfuH, now " << exact(fcfu)); + } + ++compared; + }}; + // every figure of up to two decimals, from -10 to 200 + for (auto hundredths{-1000}; hundredths <= 20000; ++hundredths) { + check(decimal(static_cast(std::abs(hundredths)), 2, hundredths < 0)); + } + // every figure of up to six decimals around the ones of the game's definitions + for (auto const figure : {33.5, 40.1, 43.7, 45.18, 46.8, 47.6, 48.9, 49.0, 81.5}) { + auto const millionths{static_cast(figure * 1e6 + 0.5)}; + for (auto offset{-2000}; offset <= 2000; ++offset) { + check(decimal(static_cast(millionths + offset), 6, false)); + } + } + // figures of 0 to 6 decimals and 1 to 18 digits + numbers random; + for (auto decimals{0}; decimals <= 6; ++decimals) { + for (auto digits{1}; digits <= 18; ++digits) { + std::uint64_t limit{1}; + for (auto digit{0}; digit < digits; ++digit) { + limit *= 10; + } + for (auto sample{0}; sample < 400; ++sample) { + check(decimal(random.next() % limit, decimals, (sample & 1) != 0)); + } + } + } + // the way of writing it doesn't matter, only the value + for (auto const text : {"4.76e1", "47.60", "+47.6", "0047.6", "476e-1", "0", "-0", "1e15", "-1e-6", "1e300"}) { + check(text); + } + // nor does a figure the stream can't read, which reads as 0 + for (auto const text : {"abc", "-", "x47.6"}) { + check(text); + } + CHECK(compared > 70000); +} + +TEST_CASE("fcfuH: where the two ways part, figures no definition has") { + // no definition of the game has such a figure (they have one or two decimals, from 33.5 to 81.5). more than + // six decimals: std::to_string() rounded the value to six, the figure is taken as it's written now + CHECK(fcfuh_before(read_fcfu("0.1234567")) == read_fcfu("0.123457")); + CHECK(fcfuh_before(read_fcfu("1e-7")) == 0.0); + CHECK(read_fcfu("1e-7") == 1e-7); + // a figure past the largest value reads as infinite (with MSVC; the largest value with GCC): written out it + // was "inf", which the stream doesn't read, so the dynamic brake got 0 where it gets the traction's figure now + auto const huge{read_fcfu("1e999")}; + CHECK(huge > 1e300); + if (std::isinf(huge)) { + CHECK(fcfuh_before(huge) == 0.0); + } +} + +TEST_CASE("fcfuH: the loader gives the dynamic brake the traction's figure when the definition has none") { + for (auto const fcfu : {"43.7", "45.18", "49", "0.000001", "1e2"}) { + CAPTURE(fcfu); + // the EU47's definition has fcfu only + vehicle eu47{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu)}; + CHECK(eu47->inductionMotor.converter.voltsPerHertz == read_fcfu(fcfu)); + CHECK(bits(eu47->inductionMotor.converter.brakingVoltsPerHertz) == bits(eu47->inductionMotor.converter.voltsPerHertz)); + CHECK(bits(eu47->inductionMotor.converter.brakingVoltsPerHertz) == bits(fcfuh_before(read_fcfu(fcfu)))); + // its own figure is kept + vehicle own{definition::fiz("e186_v2/eu47").set("Engine", "fcfu", fcfu).set("Engine", "fcfuH", "40.1")}; + CHECK(own->inductionMotor.converter.voltsPerHertz == read_fcfu(fcfu)); + CHECK(own->inductionMotor.converter.brakingVoltsPerHertz == read_fcfu("40.1")); + } +} diff --git a/tests/unit/test_feed_pipe.cpp b/tests/unit/test_feed_pipe.cpp new file mode 100644 index 000000000..50a7441de --- /dev/null +++ b/tests/unit/test_feed_pipe.cpp @@ -0,0 +1,175 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "physics/vehicle.h" +#include "physics/brakes.h" +#include "consist.h" +#include "vehicle.h" + +// the air exchange through the main reservoir hoses between the vehicles of a train (physics::Vehicle::UpdatePipeCouplers()). +// taken in one explicit step of 0.01 s, a hose carried about 1.5 times the air which evens out the pipes on its ends, +// and the vehicles' own main reservoirs fed the pipe in the same step: the pipes of the middle vehicles of a multiple +// unit, or of locomotives in multiple traction, kept jumping 0.8 bar to and fro between the steps, with the main +// reservoirs all at the same pressure + +namespace { + +using test::definition; + +// an EN57 of Units units, driven from the front cab +void en57(test::consist &Train, int const Units) { + for (int i = 0; i < Units; ++i) { + Train.add(definition::fiz("en57_v1/5bgb"), i == 0 ? 1 : 0); + Train.add(definition::fiz("en57_v1/6ba_840")); + Train.add(definition::fiz("en57_v1/5bgb")); + } +} + +// Count SM40 shunters in multiple traction, driven from the first +void sm40(test::consist &Train, int const Count) { + for (int i = 0; i < Count; ++i) { + Train.add(definition::fiz("sm40_v1/sm40"), i == 0 ? 1 : 0); + } +} + +// a locomotive and Cars passenger cars, whose main reservoir pipe only the locomotive feeds +void passenger_train(test::consist &Train, int const Cars) { + Train.add(definition::fiz("ep09_v2/104e")); + for (int i = 0; i < Cars; ++i) { + Train.add(definition::fiz("11xa_v2/93a")); + } + Train[0].hold_brake_pipe(5.0); +} + +// the largest difference [bar] of a main reservoir pipe of the train from Pressure, over Seconds of steps of Dt +double off_pressure(test::consist &Train, double const Pressure, double const Seconds, double const Dt = 0.01) { + auto off{0.0}; + auto const steps{static_cast(std::lround(Seconds / Dt))}; + for (int step = 0; step < steps; ++step) { + Train.step({}, Dt); + for (std::size_t i = 0; i < Train.size(); ++i) { + off = std::max(off, std::abs(Train[i]->mainPipe.Pressure() - Pressure)); + } + } + return off; +} + +struct evening_out { + double time{60.0}; // [s] until the main reservoirs of the train's ends are within 0.05 bar + double zigzag{0.0}; // [bar] the largest step of a main reservoir pipe back and forth, between steps the other way +}; + +// the train standing, the main reservoir of its first vehicle Pressure [bar], those of the rest 1 bar below, stepping +// by Dt until they even out through the main reservoir pipe +template +evening_out even_out(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + for (std::size_t i = 0; i < train.size(); ++i) { + auto &physics{train[i].physics()}; + REQUIRE(physics.air.config.mainReservoirVolume > 0.0); + auto const pressure{i == 0 ? Pressure : Pressure - 1.0}; + physics.air.Fill(pressure * physics.air.config.mainReservoirVolume); + physics.air.SetPressureForTest(pressure); + physics.mainPipe.reservoir->CreatePress(pressure); + physics.mainPipe.reservoir->Act(); + physics.mainPipe.SetPressure(pressure); + } + evening_out result; + auto const &first{train[0].physics()}; + auto const &last{train[train.size() - 1].physics()}; + std::vector previous(train.size()); + std::vector change(train.size()); + for (std::size_t i = 0; i < train.size(); ++i) { + previous[i] = train[i]->mainPipe.Pressure(); + } + auto time{0.0}; + while (time < 60.0) { + train.step({}, Dt); + time += Dt; + for (std::size_t i = 0; i < train.size(); ++i) { + auto const step{train[i]->mainPipe.Pressure() - previous[i]}; + if (step * change[i] < 0.0) { + // turned back + result.zigzag = std::max(result.zigzag, std::min(std::abs(step), std::abs(change[i]))); + } + change[i] = step; + previous[i] = train[i]->mainPipe.Pressure(); + } + if (std::abs(first.air.MainReservoirPressure() - last.air.MainReservoirPressure()) < 0.05) { + result.time = time; + break; + } + } + return result; +} + +// the time [s] until the main reservoir pipe of the train's last vehicle, emptied with all the others which have no +// main reservoir of their own, is within 0.2 bar of the first vehicle's, which holds its main reservoir at Pressure [bar] +template +double charging_time(Builder Train, int const Count, double const Pressure, double const Dt) { + test::consist train; + Train(train, Count); + train[0].hold_main_reservoir(Pressure); + for (std::size_t i = 1; i < train.size(); ++i) { + auto &physics{train[i].physics()}; + REQUIRE(physics.air.config.mainReservoirVolume == 0.0); + physics.mainPipe.reservoir->CreatePress(0.0); + physics.mainPipe.reservoir->Act(); + physics.mainPipe.SetPressure(0.0); + } + auto const &first{train[0].physics()}; + auto const &last{train[train.size() - 1].physics()}; + auto time{0.0}; + while ((last.mainPipe.Pressure() < 1.0 || std::abs(last.mainPipe.Pressure() - first.mainPipe.Pressure()) > 0.2) && time < 60.0) { + train.step({}, Dt); + time += Dt; + } + return time; +} + +} // namespace + +TEST_CASE("main reservoir pipe: the pipes of a three unit EN57 stand at the pressure of its main reservoirs") { + test::consist train; + en57(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.0); + } + // the pipes filling up from the reservoirs + train.run(60.0); + CHECK(off_pressure(train, 7.0, 1.0) < 0.01); + // the exchange through the hoses of the 21 m cars takes 2 sub-steps of a step of 0.01 s + CHECK(train[1]->ScndPipeCouplersSubsteps(0.01) == 2); +} + +TEST_CASE("main reservoir pipe: the pipes of locomotives in multiple traction stand at the pressure of their main reservoirs") { + test::consist train; + sm40(train, 3); + for (std::size_t i = 0; i < train.size(); ++i) { + train[i].hold_main_reservoir(7.5); + } + train.run(60.0); + CHECK(off_pressure(train, 7.5, 1.0) < 0.01); +} + +TEST_CASE("main reservoir pipe: the main reservoirs of a multiple unit even out as with a short step") { + auto const converged{even_out(en57, 3, 7.0, 0.001)}; + auto const usual{even_out(en57, 3, 7.0, 0.01)}; + CAPTURE(converged.time); + CAPTURE(usual.time); + CAPTURE(usual.zigzag); + CHECK(converged.time < 60.0); + CHECK(usual.time == doctest::Approx(converged.time).epsilon(0.1)); + // the pipes go along with the reservoirs, without jumping to and fro between the steps + CHECK(usual.zigzag < 0.05); +} + +TEST_CASE("main reservoir pipe: a passenger train, whose exchange was stable in one step, fills its pipe as with a short step") { + auto const converged{charging_time(passenger_train, 10, 9.0, 0.001)}; + auto const usual{charging_time(passenger_train, 10, 9.0, 0.01)}; + CAPTURE(converged); + CAPTURE(usual); + CHECK(converged < 60.0); + CHECK(usual == doctest::Approx(converged).epsilon(0.05)); +} diff --git a/tests/unit/test_field_shunting.cpp b/tests/unit/test_field_shunting.cpp new file mode 100644 index 000000000..4c9793294 --- /dev/null +++ b/tests/unit/test_field_shunting.cpp @@ -0,0 +1,99 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" + +#include "vehicle/fieldshunting.h" + +// the field shunting of the diesel-electric locomotives, set by the driver or by the shunting relays, and the switch +// of the SU45 and the SP45 that lets the relays shunt the field ("załączenie bocznikowania", eu07/maszyna#167) + +using test::definition; +using test::scenario; +using namespace test::channels; + +TEST_CASE("field shunting: who shunts the field of a diesel-electric, by AutoRelay, FieldShuntSwitch and the switch") { + using enum fieldshunting::control; + struct setting { + int type; // AutoRelay: 0 No, 1 Yes, 2 Optional + bool fieldshuntswitch; // FieldShuntSwitch + bool flag; // the switch, AutoRelayFlag + fieldshunting::control expected; + }; + for (auto const &[type, fieldshuntswitch, flag, expected] : + {setting{0, false, false, manual}, setting{1, false, true, automatic}, + // AutoRelay=Optional alone, as before: off, the driver shunts by hand + setting{2, false, true, automatic}, setting{2, false, false, manual}, + // with FieldShuntSwitch=Yes the switch of the field shunting: off, nobody + setting{2, true, true, automatic}, setting{2, true, false, off}, + // FieldShuntSwitch=Yes without the switch (AutoRelay=Yes or No) changes nothing + setting{1, true, true, automatic}, setting{0, true, false, manual}, + // AutoRelaySwitch from a coupled vehicle turns the flag of every one off, as before + setting{1, false, false, manual}, setting{1, true, false, manual}}) { + CAPTURE(type); + CAPTURE(fieldshuntswitch); + CAPTURE(flag); + CHECK(fieldshunting::diesel_electric(type, fieldshuntswitch, flag) == expected); + CHECK(fieldshunting::has_switch(type, fieldshuntswitch) == (type == 2 && fieldshuntswitch)); + } +} + +TEST_CASE("field shunting: the SU45 with its switch, off at full power and switched on and off on the move") { + // the SU45 (RelayType 45) given the switch (AutoRelay=Optional, FieldShuntSwitch=Yes) its cab has, with a coach: + // off, the field stays full and the second controller can't shunt it; on, the relays shunt it as they do with + // AutoRelay=Yes; off again, the shunting drops + scenario scenario{"traction/field shunting switch/su45", motion() + traction()}; + scenario.train().add(definition::fiz("su45_v2/301d").set("Cntrl", "AutoRelay", "Optional").set("Cntrl", "FieldShuntSwitch", "Yes"), 1); + scenario.add("bdhpumn_v3/bdhpumn"); + REQUIRE(scenario.start_up()); + auto &su45{scenario.driver().controlling}; + REQUIRE(su45.AutoRelayType() == 2); + REQUIRE(su45.FieldShuntSwitch()); + // the driver switches it on as the AI does, getting the locomotive ready + CHECK(su45.AutoRelayFlag()); + scenario.act("field shunting off"); + CHECK(su45.AutoRelaySwitch(false)); + scenario.get_going(); + scenario.full_power(120.0); + CHECK(su45.IsMainCtrlMaxPowerPos()); + CHECK(su45.lineContactors.IsClosed()); + CHECK(su45.ScndCtrlPos() == 0); + CHECK_FALSE(su45.IncScndCtrl(1)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos() == 0); + // over 50 km/h, where the relays of the SU45 let the third stage in + CHECK(su45.Vel > 50.0); + scenario.act("field shunting on"); + CHECK(su45.AutoRelaySwitch(true)); + scenario.wait(30.0); + CHECK(su45.ScndCtrlPos() == su45.ScndCtrlPosNo()); + scenario.act("field shunting off on the move"); + CHECK(su45.AutoRelaySwitch(false)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos() == 0); + scenario.check(); +} + +TEST_CASE("field shunting: a diesel-electric with AutoRelay=Optional alone shunts by hand with the switch off, as before") { + // the SU45 with AutoRelay=Optional but no FieldShuntSwitch: the switch is the old one, off hands the shunting to the + // second controller, and the start-up (as the AI) leaves it off + scenario scenario{"traction/field shunting switch/su45 optional alone", motion() + traction()}; + scenario.train().add(definition::fiz("su45_v2/301d").set("Cntrl", "AutoRelay", "Optional"), 1); + scenario.add("bdhpumn_v3/bdhpumn"); + REQUIRE(scenario.start_up()); + auto &su45{scenario.driver().controlling}; + REQUIRE(su45.AutoRelayType() == 2); + REQUIRE_FALSE(su45.FieldShuntSwitch()); + CHECK_FALSE(su45.AutoRelayFlag()); + scenario.get_going(); + scenario.full_power(120.0); + CHECK(su45.IsMainCtrlMaxPowerPos()); + CHECK(su45.lineContactors.IsClosed()); + // over 50 km/h: the relays don't shunt, the driver does + CHECK(su45.Vel > 50.0); + CHECK(su45.ScndCtrlPos() == 0); + scenario.act("field shunting by hand"); + CHECK(su45.IncScndCtrl(1)); + scenario.wait(1.0); + CHECK(su45.ScndCtrlPos() == 1); + scenario.check(); +} diff --git a/tests/unit/test_figures.cpp b/tests/unit/test_figures.cpp index c8b575d50..1d9fa63c8 100644 --- a/tests/unit/test_figures.cpp +++ b/tests/unit/test_figures.cpp @@ -15,24 +15,24 @@ using test::vehicle; TEST_CASE("figures: a run split into parts by the events, each from the last step of the part before") { vehicle eu07{definition::fiz("4e_v1/4e")}; test::figures figures; - auto &mover{eu07.mover()}; - mover.V = 10.0; - mover.PipePress = 5.0; - figures.sample(0.0, mover); + auto &physics{eu07.physics()}; + physics.SetV(10.0); + physics.brakePipe.SetPressure(5.0); + figures.sample(0.0, physics); figures.mark("brake"); figures.mark("hard"); for (int i = 1; i <= 10; ++i) { - mover.V = 10.0 - i; - mover.DistCounter += 0.005; - mover.PipePress = 3.5; - mover.BrakePress = 0.4 * i; - figures.sample(i, mover); + physics.SetV(10.0 - i); + physics.SetDistCounter(physics.DistCounter() + 0.005); + physics.brakePipe.SetPressure(3.5); + physics.brakes.cylinderPressure = 0.4 * i; + figures.sample(i, physics); } figures.mark("release"); - mover.PipePress = 4.0; - figures.sample(11.0, mover); - mover.PipePress = 5.0; - figures.sample(12.0, mover); + physics.brakePipe.SetPressure(4.0); + figures.sample(11.0, physics); + physics.brakePipe.SetPressure(5.0); + figures.sample(12.0, physics); auto const lines{figures.lines()}; auto const has{[&lines](std::string const &Line) { return std::ranges::find(lines, Line) != lines.end(); }}; diff --git a/tests/unit/test_fiz.cpp b/tests/unit/test_fiz.cpp index f25632dee..2cf5c8246 100644 --- a/tests/unit/test_fiz.cpp +++ b/tests/unit/test_fiz.cpp @@ -23,26 +23,26 @@ TEST_CASE("fiz: every real vehicle loads and keeps its parameters") { test::reseed_random(); vehicle real{definition::fiz(path)}; test::trace trace{"fiz/" + path, test::channels::parameters(), 1}; - trace.sample(0.0, real.mover()); + trace.sample(0.0, real.physics()); // what every vehicle has, the rest of its parameters are in the golden trace - CHECK(real->Mass > 0.0); - CHECK(real->TotalMass >= real->Mass); - CHECK(real->Vmax > 0.0); - CHECK(real->NAxles > 0); - CHECK(real->WheelDiameter > 0.0); - CHECK(real->NPoweredAxles <= real->NAxles); + CHECK(real->Mass() > 0.0); + CHECK(real->TotalMass() >= real->Mass()); + CHECK(real->Vmax() > 0.0); + CHECK(real->NAxles() > 0); + CHECK(real->WheelDiameter() > 0.0); + CHECK(real->NPoweredAxles() <= real->NAxles()); trace.check(); } } TEST_CASE("fiz: changes made by a test reach the vehicle") { auto const eu07{definition::fiz("4e_v1/4e")}; - CHECK(vehicle{eu07}->Mass == doctest::Approx(80000.0)); - CHECK(vehicle{definition{eu07}.set("Param", "M", 90000)}->Mass == doctest::Approx(90000.0)); + CHECK(vehicle{eu07}->Mass() == doctest::Approx(80000.0)); + CHECK(vehicle{definition{eu07}.set("Param", "M", 90000)}->Mass() == doctest::Approx(90000.0)); // a key the file doesn't have is added to its section - CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->MaxBrakePress[3] == doctest::Approx(3.5)); + CHECK(vehicle{definition{eu07}.set("Brake", "MaxBP", 3.5)}->brakes.config.maxCylinderPressure[3] == doctest::Approx(3.5)); // removing a key brings its default back - CHECK(vehicle{definition{eu07}.remove("Param", "Vmax")}->Vmax != doctest::Approx(125.0)); + CHECK(vehicle{definition{eu07}.remove("Param", "Vmax")}->Vmax() != doctest::Approx(125.0)); } namespace { diff --git a/tests/unit/test_gauge_scale.cpp b/tests/unit/test_gauge_scale.cpp index 04fa645bb..2e4d7ddd6 100644 --- a/tests/unit/test_gauge_scale.cpp +++ b/tests/unit/test_gauge_scale.cpp @@ -84,10 +84,10 @@ TEST_CASE("main ctrl act: the marker of a diesel locomotive with a scaletable: f for (auto const *path : {"st44_v2/m62-1151", "sm42_v1/6d1", "su45_v2/301d"}) { CAPTURE(path); consist train; - auto &locomotive{train.add(definition::fiz(path), 1).mover()}; + auto &locomotive{train.add(definition::fiz(path), 1).physics()}; REQUIRE((locomotive.EngineType == TEngineType::DieselElectric || locomotive.EngineType == TEngineType::DieselEngine)); REQUIRE(locomotive.EIMCtrlType == 0); - locomotive.MainCtrlPos = 5; + locomotive.SetMainCtrlPos(5); CHECK(locomotive.MainCtrlActualPos == 0); CHECK(main_ctrl_act::position(locomotive, true) == doctest::Approx(5.0)); // one with a controller of the EIM kind keeps its actual position itself @@ -101,10 +101,10 @@ TEST_CASE("main ctrl act: the marker of a diesel locomotive without a scaletable for (auto const *path : {"st44_v2/m62-1151", "sm42_v1/6d1", "su45_v2/301d"}) { CAPTURE(path); consist train; - auto &locomotive{train.add(definition::fiz(path), 1).mover()}; + auto &locomotive{train.add(definition::fiz(path), 1).physics()}; REQUIRE(locomotive.EIMCtrlType == 0); - locomotive.MainCtrlPos = 5; - locomotive.ScndCtrlPos = 1; + locomotive.SetMainCtrlPos(5); + locomotive.SetScndCtrlPos(1); for (auto const coupled : {false, true}) { CAPTURE(coupled); locomotive.CoupledCtrl = coupled; @@ -117,10 +117,10 @@ TEST_CASE("main ctrl act: the marker of an electric locomotive shows its actual for (auto const scaletable : {false, true}) { CAPTURE(scaletable); consist train; - auto &locomotive{train.add(definition::fiz("et22_v3/201e-w"), 1).mover()}; - locomotive.MainCtrlPos = 10; + auto &locomotive{train.add(definition::fiz("et22_v3/201e-w"), 1).physics()}; + locomotive.SetMainCtrlPos(10); locomotive.MainCtrlActualPos = 3; - locomotive.ScndCtrlPos = 2; + locomotive.SetScndCtrlPos(2); locomotive.ScndCtrlActualPos = 1; locomotive.CoupledCtrl = false; CHECK(main_ctrl_act::position(locomotive, scaletable) == doctest::Approx(3.0)); diff --git a/tests/unit/test_gauge_wrap.cpp b/tests/unit/test_gauge_wrap.cpp new file mode 100644 index 000000000..629183369 --- /dev/null +++ b/tests/unit/test_gauge_wrap.cpp @@ -0,0 +1,55 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/gaugewrap.h" +#include "vehicle/gaugepositions.h" + +#include +#include + +// a light preset selector with Wrap=Yes turned on past its last position to the first one, or back past the first one +// to the last (eu07/maszyna#464): the EN57AKM selector has 0 as its first position and A1 as its last one, and the +// knob, rather than jump between them with no sound, turns on to the next position as it does between any two others + +TEST_CASE("gauge wrap: a knob whose positions make a full turn turns on past its end") { + CHECK(gauge_wrap::full_turn(-0.08333f, 12) == 12); // E186, BR285: 12 positions, 30 degrees each + CHECK(gauge_wrap::full_turn(-0.0625f, 16) == 16); // E189: 16 positions + CHECK(gauge_wrap::full_turn(-0.167f, 6) == 6); // EN57AL Zachodniopomorskie: a sixth given as 0.167 +} + +TEST_CASE("gauge wrap: a knob with a free position in its turn turns on across it (eu07/maszyna#464)") { + // EN57AKM: 7 positions, 45 degrees each, A1 at 270 degrees, 0 at 0 degrees: 90 degrees on from A1 to 0 + CHECK(gauge_wrap::full_turn(0.125f, 7) == 8); + // the way on is half a turn at most + CHECK(gauge_wrap::full_turn(0.25f, 3) == 4); + CHECK_FALSE(gauge_wrap::full_turn(0.125f, 4).has_value()); +} + +TEST_CASE("gauge wrap: a switch whose positions don't make a full turn doesn't turn on past its end") { + CHECK_FALSE(gauge_wrap::full_turn(0.1f, 12).has_value()); // the positions would overlap in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.15f, 6).has_value()); // 6.67 positions in a turn + CHECK_FALSE(gauge_wrap::full_turn(0.f, 6).has_value()); // no motion + CHECK_FALSE(gauge_wrap::full_turn(0.5f, 1).has_value()); // nothing to turn to +} + +TEST_CASE("gauge wrap: turned round, the knob stands the same one turn earlier or later") { + // EN57AKM, from A1 (value 6) on to 0: from -2 up to 0, 90 degrees the way it was turned + CHECK(gauge_wrap::turned_round(6.f, 8, true) == doctest::Approx(-2.f)); + // from 0 back to A1 (value 6): from 8 down to 6 + CHECK(gauge_wrap::turned_round(0.f, 8, false) == doctest::Approx(8.f)); + // the angle stays: value * scale differs by one full turn + CHECK((6.f - gauge_wrap::turned_round(6.f, 8, true)) * 0.125f == doctest::Approx(1.f)); +} + +TEST_CASE("gauge wrap: turned round, the knob sounds the position it reaches (eu07/maszyna#464)") { + // the EN57AKM selector has a sound for each position 0-7, as values of the gauge + std::map sounds{{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}}; + auto const reached{[&sounds](float const From, float const To) { + auto const position{gauge_positions::last_reached(sounds, static_cast(std::round(100.f * From)), static_cast(std::round(100.f * To)))}; + return position != sounds.end() ? position->second : -1; + }}; + // A1 (6) on to 0 + CHECK(reached(gauge_wrap::turned_round(6.f, 8, true), 0.f) == 0); + // 0 back to A1 (6) + CHECK(reached(gauge_wrap::turned_round(0.f, 8, false), 6.f) == 6); +} diff --git a/tests/unit/test_genset.cpp b/tests/unit/test_genset.cpp new file mode 100644 index 000000000..b6211fa35 --- /dev/null +++ b/tests/unit/test_genset.cpp @@ -0,0 +1,660 @@ +#include "stdafx.h" +#include "doctest.h" +#include "consist.h" +#include "drive.h" +#include "golden.h" + +#include "physics/brakes.h" + +// the genset of a dual-mode vehicle (eu07/maszyna#536): a second source of the traction circuit of an induction +// motor vehicle next to its pantographs, which the traction selector picks. the vehicle is the game's E6ACT +// (Dragon 2) with the genset of the E6ACTad "last mile" set in the test: 520 kW, the rest assumed + +using test::consist; +using test::definition; +using test::track; +using test::vehicle; +using traction_mode = physics::Vehicle::traction_mode; + +namespace { + +definition dragon() { + return definition::fiz("e6act_v2/e6acta"); +} + +definition dragon_genset() { + return dragon() + .set("Power", "GensetPower", 520) + .set("Power", "GensetVoltage", 3000) + .set("Power", "GensetIdleRPM", 700) + .set("Power", "GensetMaxRPM", 1800) + .set("Power", "GensetStartTime", 8) + .set("Power", "GensetSpinUpTime", 3) + .set("Power", "GensetPmaxRatio", 0.85); +} + +// the power the traction of dragon_genset() may take at full revolutions [kW] +double const genset_traction_power{520.0 * 0.85}; + +track const no_wire{0.15, 0.0, 0.0}; +track const wire{0.15, 0.0, test::catenary_3kv}; + +// the battery, the cab and a direction, as the driver begins +void wake(physics::Vehicle &Cab) { + Cab.BatterySwitch(true); + Cab.CabActivisation(); + for (int i = 0; i < 3 && Cab.DirActive <= 0; ++i) { + Cab.DirectionForward(); + } +} + +// the vigilance and the cab signalling acknowledged, as test::drive() does once a second +void attend(physics::Vehicle &Cab) { + if (Cab.SecuritySystem.is_cabsignal_blinking() && Cab.SecuritySystem.has_separate_acknowledge()) { + Cab.SecuritySystem.cabsignal_reset(); + } + if (Cab.SecuritySystem.is_blinking()) { + Cab.SecuritySystemReset(); + } +} + +void run(vehicle &Vehicle, double const Seconds, track const &Track = no_wire) { + test::drive(test::driving(Vehicle), Track, Seconds); +} + +// the line breaker closed, which it does only with the controller at zero, and after the relays are reset +void close_line_breaker(physics::Vehicle &Cab) { + while (Cab.DecMainCtrl(2)) { + // down to zero + } + Cab.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload); + Cab.MainSwitch(true); +} + +// gets the vehicle ready to run on its genset, as test::start_up() does on the pantographs: the selector on the +// genset, the genset started, the line breaker closed once it runs, the converter and the compressor, the air, the +// brakes released. one round of the driver's actions a second; returns whether the vehicle got ready +bool start_on_genset(vehicle &Vehicle, track const &Track = no_wire, double const Seconds = 300.0) { + auto &cab{Vehicle.physics()}; + for (auto second = 0; second < Seconds; ++second) { + wake(cab); + cab.TractionModeSwitch(traction_mode::genset); + cab.GensetSwitch(true); + if (false == cab.lineBreaker.IsClosed()) { + if (cab.MainSwitchCheck()) { + close_line_breaker(cab); + } + } + else { + cab.ConverterSwitch(true); + cab.CompressorSwitch(true); + } + run(Vehicle, 1.0, Track); + if (cab.lineBreaker.IsClosed() && cab.converter.IsRunning() && cab.mainPipe.Pressure() >= 4.5) { + // and the brakes let go + test::release_brakes(cab); + for (auto wait = 0; wait < 120 && cab.brakes.cylinderPressure > 0.05; ++wait) { + run(Vehicle, 1.0, Track); + } + return cab.brakes.cylinderPressure <= 0.05; + } + } + return false; +} + +// the main controller to its full power position +void notch_up(physics::Vehicle &Cab) { + for (int i = 0; i < 60 && false == Cab.IsMainCtrlMaxPowerPos(); ++i) { + Cab.IncMainCtrl(1); + } +} + +// the power at the wheels [kW] +double wheel_power(physics::Vehicle const &Vehicle) { + return std::abs(Vehicle.Ft() * Vehicle.V()) / 1000.0; +} + +// one step of 0.01 s, acknowledging the vigilance once a second +void step(vehicle &Vehicle, long const Step, track const &Track = no_wire) { + if (Step % 100 == 0) { + attend(Vehicle.physics()); + } + Vehicle.step(Track); +} + +} // namespace + +TEST_CASE("genset: a vehicle without the keys has none and stays on the catenary") { + vehicle dragon6{dragon(), 0.0, "plain", 1}; + auto &cab{dragon6.physics()}; + CHECK(cab.Genset.power == 0.0); + CHECK_FALSE(cab.Genset.fitted()); + CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.TractionMode() == traction_mode::catenary); + CHECK_FALSE(cab.GensetSelected()); + REQUIRE(test::start_up(test::driving(dragon6), wire)); + CHECK(cab.pantographCircuit.SupplyVoltage() > 2900.0); + CHECK(cab.TractionSupplyVoltage() == std::max(cab.GetTrainsetHighVoltage(), cab.pantographCircuit.SupplyVoltage())); + CHECK(cab.TractionSupplyMinVoltage() == cab.EnginePowerSource.CollectorParameters.MinV); + CHECK(cab.GensetTractionPowerLimit() == std::numeric_limits::max()); + // a start request does nothing without a genset + cab.GensetSwitch(true); + run(dragon6, 20.0, wire); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.voltage == 0.0); + CHECK(cab.TractionMode() == traction_mode::catenary); +} + +TEST_CASE("genset: the keys reach the vehicle") { + vehicle dragon6{dragon_genset()}; + auto const &genset{dragon6->Genset}; + CHECK(genset.fitted()); + CHECK(genset.power == 520.0); + CHECK(genset.voltage_nominal == 3000.0); + CHECK(genset.revolutions_idle == doctest::Approx(700.0 / 60.0)); + CHECK(genset.revolutions_max == doctest::Approx(30.0)); + CHECK(genset.start_time == 8.0); + CHECK(genset.spinup_time == 3.0); + CHECK(genset.traction_share == 0.85); + CHECK(genset.start_type == start_t::manual); + CHECK(dragon6->TractionMode() == traction_mode::catenary); + // the pantographs stay what they were + CHECK(dragon6->EnginePowerSource.SourceType == TPowerSource::CurrentCollector); + CHECK(dragon6->EnginePowerSource.CollectorParameters.MinV == 2000.0); + + SUBCASE("started on its own") { + vehicle automatic{dragon_genset().set("Cntrl", "GensetStart", "Automatic")}; + CHECK(automatic->Genset.start_type == start_t::automatic); + } + SUBCASE("the defaults") { + vehicle defaults{dragon().set("Power", "GensetPower", 520)}; + auto const &plain{defaults->Genset}; + CHECK(plain.fitted()); + CHECK(plain.voltage_nominal == doctest::Approx(0.65 * 4600.0)); // of the pantographs' MaxVoltage + CHECK(plain.revolutions_idle == doctest::Approx(10.0)); + CHECK(plain.revolutions_max == doctest::Approx(30.0)); + CHECK(plain.start_time == 8.0); + CHECK(plain.spinup_time == 3.0); + CHECK(plain.traction_share == 1.0); + } +} + +TEST_CASE("genset: the keys are ignored on other than induction motor vehicles") { + for (auto const *path : {"4e_v1/4e", "br285_v1/br285"}) { + CAPTURE(path); + vehicle other{definition::fiz(path).set("Power", "GensetPower", 520)}; + CHECK_FALSE(other->Genset.fitted()); + CHECK_FALSE(other->TractionModeSwitch(traction_mode::genset)); + CHECK(other->TractionMode() == traction_mode::catenary); + } +} + +TEST_CASE("genset: the selector moves only with the line breaker open") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + REQUIRE(cab.lineBreaker.IsClosed()); + CHECK_FALSE(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.TractionMode() == traction_mode::catenary); + run(dragon6, 2.0, wire); + CHECK(cab.lineBreaker.IsClosed()); + cab.MainSwitch(false); + REQUIRE_FALSE(cab.lineBreaker.IsClosed()); + CHECK(cab.TractionModeSwitch(traction_mode::genset)); + CHECK(cab.GensetSelected()); + CHECK(cab.TractionModeSwitch(traction_mode::catenary)); + CHECK(cab.TractionMode() == traction_mode::catenary); +} + +TEST_CASE("genset: started, it closes the line breaker without a catenary") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + wake(cab); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + cab.GensetSwitch(true); + run(dragon6, 7.0); + CHECK(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.voltage == 0.0); + CHECK_FALSE(cab.MainSwitchCheck()); + run(dragon6, 2.0); + CHECK(cab.Genset.is_active); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK(cab.Genset.revolutions == cab.Genset.revolutions_idle); + CHECK(cab.Genset.voltage == 3000.0); + // the line breaker gets ready MainInitTime after the voltage came + for (auto second = 0; second < 10 && false == cab.lineBreaker.IsClosed(); ++second) { + if (cab.MainSwitchCheck()) { + close_line_breaker(cab); + } + run(dragon6, 1.0); + } + REQUIRE(cab.lineBreaker.IsClosed()); + CHECK(cab.pantographCircuit.SupplyVoltage() == 0.0); + dragon6.step(no_wire); + CHECK(cab.EngineVoltage == 3000.0); + CHECK(cab.MainCircuitPowered()); + run(dragon6, 5.0); + CHECK(cab.lineBreaker.IsClosed()); +} + +TEST_CASE("genset: on the catenary position the genset feeds nothing") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + wake(cab); + cab.GensetSwitch(true); + run(dragon6, 20.0); + REQUIRE(cab.Genset.is_active); + CHECK(cab.TractionMode() == traction_mode::catenary); + CHECK_FALSE(cab.MainSwitchCheck()); + close_line_breaker(cab); + CHECK_FALSE(cab.lineBreaker.IsClosed()); + dragon6.step(no_wire); + CHECK(cab.EngineVoltage == 0.0); + CHECK(cab.TractionSupplyVoltage() == 0.0); + // running isolated, at idle + CHECK(cab.Genset.revolutions == cab.Genset.revolutions_idle); +} + +TEST_CASE("genset: on the genset position the catenary feeds nothing") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + wake(cab); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + // the pantographs up under the wire, the genset stopped: the line breaker never closes + CHECK_FALSE(test::start_up(test::driving(dragon6), wire, 120.0)); + REQUIRE(cab.pantographCircuit.SupplyVoltage() > 2900.0); + CHECK_FALSE(cab.lineBreaker.IsClosed()); + CHECK_FALSE(cab.MainSwitchCheck()); + dragon6.step(wire); + CHECK(cab.EngineVoltage == 0.0); + CHECK(cab.TractionSupplyVoltage() == 0.0); +} + +TEST_CASE("genset: the power at the wheels stays within the genset's") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(start_on_genset(dragon6)); + notch_up(cab); + auto peak{0.0}; + auto revolutions{0.0}; + auto over{0L}; + auto step_count{0L}; + for (; step_count < 60000 && cab.Vel < 80.0 && cab.lineBreaker.IsClosed(); ++step_count) { + step(dragon6, step_count); + auto const power{wheel_power(cab)}; + peak = std::max(peak, power); + revolutions = std::max(revolutions, cab.Genset.revolutions); + if (power > genset_traction_power * 1.02) { + ++over; + } + } + CAPTURE(step_count); + CAPTURE(peak); + CHECK(cab.lineBreaker.IsClosed()); + CHECK(cab.Vel >= 80.0); + CHECK(over == 0); + CHECK(peak <= genset_traction_power * 1.02); + CHECK(peak >= genset_traction_power * 0.95); // the limit bites + CHECK(revolutions >= 0.95 * cab.Genset.revolutions_max); +} + +TEST_CASE("genset: the revolutions follow the demand, so the power builds up") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(start_on_genset(dragon6)); + // at idle with nothing asked of it + CHECK(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); + CHECK(cab.GensetTractionPowerLimit() == doctest::Approx(genset_traction_power * 700.0 / 1800.0).epsilon(0.001)); + notch_up(cab); + // the demand of the traction builds up at the pace of the inverters, the revolutions follow it + auto step_count{0L}; + for (; step_count < 3000 && cab.inductionMotor.forceShare < 0.99; ++step_count) { + step(dragon6, step_count); + } + CAPTURE(step_count); + REQUIRE(cab.inductionMotor.forceShare >= 0.99); + run(dragon6, 3.0); + auto const after3{cab.Genset.available_power()}; + CAPTURE(after3); + // first order: 1 - exp(-1) of the way from idle to full in the time constant at the least + CHECK(after3 > 520.0 * 0.75); + run(dragon6, 9.0); + CHECK(cab.Genset.available_power() > 520.0 * 0.95); + CHECK(cab.GensetTractionPowerLimit() == doctest::Approx(cab.Genset.available_power() * 0.85)); + // notched down it goes back to idle + while (cab.DecMainCtrl(2)) { + // down to zero + } + run(dragon6, 20.0); + CHECK(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle).epsilon(0.01)); +} + +TEST_CASE("genset: running from the catenary is the same with the keys") { + // the values of a run of each one, every step + struct values { + std::vector force; + std::vector speed; + std::vector voltage; + std::vector current; + std::vector demand; + }; + auto const record = [](values &Values) { + return std::vector{ + {"Ft", [&Values](physics::Vehicle const &Vehicle) { Values.force.push_back(Vehicle.Ft()); return Vehicle.Ft(); }}, + {"V", [&Values](physics::Vehicle const &Vehicle) { Values.speed.push_back(Vehicle.V()); return Vehicle.V(); }}, + {"EngineVoltage", [&Values](physics::Vehicle const &Vehicle) { Values.voltage.push_back(Vehicle.EngineVoltage); return Vehicle.EngineVoltage; }}, + {"Itot", [&Values](physics::Vehicle const &Vehicle) { Values.current.push_back(Vehicle.Itot); return Vehicle.Itot; }}, + {"eimv_pr", [&Values](physics::Vehicle const &Vehicle) { Values.demand.push_back(Vehicle.inductionMotor.forceShare); return Vehicle.inductionMotor.forceShare; }}, + }; + }; + auto const drive = [&record](definition const &Definition, values &Values) { + test::reseed_random(); + vehicle dragon6{Definition, 0.0, "test", 1}; + // not checked against a recorded one: the runs are compared with each other + test::trace trace{"genset/catenary", record(Values), 1, false}; + dragon6.record(trace); + test::drive_cycle(test::driving(dragon6), wire, trace); + }; + values plain; + values genset; + drive(dragon(), plain); + drive(dragon_genset(), genset); + REQUIRE(plain.speed.size() > 10000); + REQUIRE(genset.speed.size() == plain.speed.size()); + CHECK(*std::ranges::max_element(plain.speed) > 10.0); + // the first step they differ in, if any + auto const first_difference = [](std::vector const &Left, std::vector const &Right) { + return std::ranges::mismatch(Left, Right).in1 - Left.begin(); + }; + auto const size{static_cast(plain.speed.size())}; + CHECK(first_difference(plain.force, genset.force) == size); + CHECK(first_difference(plain.speed, genset.speed) == size); + CHECK(first_difference(plain.voltage, genset.voltage) == size); + CHECK(first_difference(plain.current, genset.current) == size); + CHECK(first_difference(plain.demand, genset.demand) == size); +} + +TEST_CASE("genset: stopped, it opens the line breaker") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(start_on_genset(dragon6)); + REQUIRE(cab.Genset.revolutions == doctest::Approx(cab.Genset.revolutions_idle)); + cab.GensetSwitch(false); + auto step_count{0L}; + for (; step_count < 1000 && cab.lineBreaker.IsClosed(); ++step_count) { + step(dragon6, step_count); + } + // coasting down from idle, the voltage falls to half, the undervoltage limit, in spinup_time * ln 2 + auto const seconds{step_count * 0.01}; + CAPTURE(seconds); + CHECK_FALSE(cab.lineBreaker.IsClosed()); + CHECK(seconds == doctest::Approx(3.0 * std::log(2.0)).epsilon(0.05)); + CHECK_FALSE(cab.Genset.is_active); + // and it doesn't close again + for (auto second = 0; second < 20; ++second) { + close_line_breaker(cab); + run(dragon6, 1.0); + } + CHECK_FALSE(cab.lineBreaker.IsClosed()); + // coasting down to a stop, with the time constant spinup_time + CHECK(cab.Genset.revolutions < 0.01 * cab.Genset.revolutions_idle); + CHECK(cab.Genset.voltage < 0.01 * cab.Genset.voltage_nominal); +} + +TEST_CASE("genset: automatic start follows the selector") { + vehicle dragon6{dragon_genset().set("Cntrl", "GensetStart", "Automatic"), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + wake(cab); + run(dragon6, 10.0); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + run(dragon6, 1.0); + CHECK(cab.Genset.is_cranking); + run(dragon6, 8.0); + CHECK(cab.Genset.is_active); + // the start switch does nothing to it + CHECK_FALSE(cab.GensetSwitch(false)); + run(dragon6, 1.0); + CHECK(cab.Genset.is_active); + REQUIRE(cab.TractionModeSwitch(traction_mode::catenary)); + dragon6.step(no_wire); + CHECK_FALSE(cab.Genset.is_active); +} + +TEST_CASE("genset: no battery, no start") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + cab.BatterySwitch(false); + REQUIRE(cab.TractionModeSwitch(traction_mode::genset)); + cab.GensetSwitch(true); + run(dragon6, 20.0); + CHECK_FALSE(cab.lowVoltage.Is24vAvailable()); + CHECK_FALSE(cab.Genset.is_cranking); + CHECK_FALSE(cab.Genset.is_active); + CHECK(cab.Genset.revolutions == 0.0); + // and with it, it starts + wake(cab); + run(dragon6, 10.0); + CHECK(cab.Genset.is_active); +} + +TEST_CASE("genset: the pantographs' pressure switch leaves the genset's line breaker alone") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(start_on_genset(dragon6)); + cab.pantographAir.SetForTest(0.0, true); + cab.PantPressureSwitchCheck(); + CHECK(cab.lineBreaker.IsClosed()); + } + SUBCASE("on the pantographs it opens the line breaker, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + REQUIRE(cab.lineBreaker.IsClosed()); + // the pressure switch looks at the voltage through the couplers, not the pantographs' + cab.pantographAir.SetForTest(0.0, true); + cab.PantPressureSwitchCheck(); + CHECK_FALSE(cab.lineBreaker.IsClosed()); + } +} + +namespace { + +// what braking showed of the current of the traction circuit +struct braking { + double lowest_current{0.0}; // [A], negative going back to the source + bool electrodynamic{false}; // whether the electrodynamic brake took part + double speed_lost{0.0}; // [km/h] in the 20 s of braking +}; + +// up to 60 km/h at full power, then braking with the train brake for 20 s, which the E6ACT blends with the +// electrodynamic one +braking brake_from_60(vehicle &Dragon, track const &Track) { + auto &cab{Dragon.physics()}; + notch_up(cab); + for (auto step_count = 0L; step_count < 60000 && cab.Vel < 60.0; ++step_count) { + step(Dragon, step_count, Track); + } + REQUIRE(cab.Vel >= 60.0); + while (cab.DecMainCtrl(2)) { + // down to zero + } + run(Dragon, 2.0, Track); + cab.DynamicBrakeSwitch(true); + cab.BrakeLevelSet(cab.brakes.driverValve->GetPos(bh_FB)); + braking result; + auto const speed{cab.Vel}; + for (auto step_count = 0L; step_count < 2000; ++step_count) { + step(Dragon, step_count, Track); + result.lowest_current = std::min(result.lowest_current, cab.Itot); + result.electrodynamic |= cab.inductionMotor.forceShare < 0.0 && cab.inductionMotor.state.lineCurrent < 0.0; + } + result.speed_lost = speed - cab.Vel; + return result; +} + +} // namespace + +TEST_CASE("genset: braking electrodynamically on the genset sends nothing back") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + REQUIRE(start_on_genset(dragon6)); + auto const braked{brake_from_60(dragon6, no_wire)}; + REQUIRE(braked.electrodynamic); + CHECK(braked.lowest_current >= -1e-6); + CHECK(braked.speed_lost > 5.0); + CHECK(dragon6->lineBreaker.IsClosed()); + } + SUBCASE("on the catenary the same braking feeds the line, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + test::release_brakes(dragon6.physics()); + run(dragon6, 5.0, wire); + auto const braked{brake_from_60(dragon6, wire)}; + REQUIRE(braked.electrodynamic); + CHECK(braked.lowest_current < -10.0); + CHECK(braked.speed_lost > 5.0); + } +} + +TEST_CASE("genset: one genset feeds the next car through the high voltage coupling") { + // both able to join the control and the high voltage lines: 35 of the E6ACT, + control 4 + high voltage 8 + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; + auto &second{train.add(dragon().set("BuffCoupl", "AllowedFlag", 47)).physics()}; + REQUIRE(first.Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::highVoltage)); + wake(first); + REQUIRE(first.TractionModeSwitch(traction_mode::genset)); + first.GensetSwitch(true); + train.run(5.0, no_wire); + CHECK(second.GetTrainsetHighVoltage() == 0.0); + train.run(10.0, no_wire); + REQUIRE(first.Genset.is_active); + CHECK(second.GetTrainsetHighVoltage() > 2900.0); + CHECK(second.pantographCircuit.SupplyVoltage() == 0.0); + // the second one, on its catenary position with the pantographs down, takes it as the catenary's + second.BatterySwitch(true); + train.run(10.0, no_wire); + second.RelayReset(relay_t::maincircuitground | relay_t::tractionnmotoroverload | relay_t::primaryconverteroverload, range_t::local); + CHECK(second.MainSwitchCheck()); + second.MainSwitch(true, range_t::local); + CHECK(second.lineBreaker.IsClosed()); + // stopped, the genset takes the voltage away + first.GensetSwitch(false); + train.run(30.0, no_wire); + CHECK(second.GetTrainsetHighVoltage() < 1.0); + CHECK_FALSE(second.lineBreaker.IsClosed()); +} + +TEST_CASE("genset: the selector command travels along the train") { + // two locomotives in multiple: the control line, no permanent coupling + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; + REQUIRE(first.Couplers[VehicleEnd::rear].CouplingFlag.HasAny(Coupling::control)); + wake(first); + train.run(1.0, no_wire); + CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK(first.GensetSelected()); + CHECK(second.GensetSelected()); + first.GensetSwitch(true, range_t::consist); + CHECK(first.Genset.is_enabled); + CHECK(second.Genset.is_enabled); + first.TractionModeSwitch(traction_mode::catenary, range_t::consist); + CHECK_FALSE(second.GensetSelected()); + // the unit range keeps to the permanent couplings, which locomotives in multiple don't have + first.TractionModeSwitch(traction_mode::genset, range_t::unit); + CHECK(first.GensetSelected()); + CHECK_FALSE(second.GensetSelected()); +} + +TEST_CASE("genset: a selector command refused with the line breaker closed isn't passed on") { + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 1).physics()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; + REQUIRE(test::start_up(test::driving(train), wire)); + REQUIRE(first.lineBreaker.IsClosed()); + // the second one's line breaker opened by itself, the lead's is closed + second.MainSwitch(false, range_t::local); + REQUIRE_FALSE(second.lineBreaker.IsClosed()); + CHECK_FALSE(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK_FALSE(first.GensetSelected()); + CHECK_FALSE(second.GensetSelected()); + // with the lead's open it goes along + first.MainSwitch(false, range_t::local); + CHECK(first.TractionModeSwitch(traction_mode::genset, range_t::consist)); + CHECK(first.GensetSelected()); + CHECK(second.GensetSelected()); +} + +TEST_CASE("genset: a lead which starts its genset on its own passes the start switch on") { + auto const coupling{Coupling::coupler | Coupling::brakeHose | Coupling::mainHose | Coupling::control}; + consist train; + auto &first{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47).set("Cntrl", "GensetStart", "Automatic"), 1).physics()}; + auto &second{train.add(dragon_genset().set("BuffCoupl", "AllowedFlag", 47), 0, coupling).physics()}; + wake(first); + train.run(1.0, no_wire); + // ignored by the lead, so its cab switch doesn't move, but the car behind starts on it + CHECK_FALSE(first.GensetSwitch(true, range_t::consist)); + CHECK_FALSE(first.Genset.is_enabled); + CHECK(second.Genset.is_enabled); + CHECK_FALSE(first.GensetSwitch(false, range_t::consist)); + CHECK_FALSE(second.Genset.is_enabled); +} + +TEST_CASE("genset: on the genset the pantographs carry no traction current") { + SUBCASE("on the genset") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(start_on_genset(dragon6)); + notch_up(cab); + run(dragon6, 10.0); + REQUIRE(cab.Itot > 50.0); + CHECK(cab.CatenaryCurrent() == 0.0); + // only a heating fed straight from the pantographs takes from the wire + cab.TotalCurrent = 40.0; + cab.HeatingPowerSource.SourceType = TPowerSource::CurrentCollector; + CHECK(cab.CatenaryCurrent() == 40.0); + cab.HeatingPowerSource.SourceType = TPowerSource::Main; + CHECK(cab.CatenaryCurrent() == 0.0); + } + SUBCASE("on the catenary the traction current goes through them, the check the genset is spared") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + REQUIRE(test::start_up(test::driving(dragon6), wire)); + test::release_brakes(cab); + run(dragon6, 5.0, wire); + notch_up(cab); + for (auto step_count = 0L; step_count < 60000 && cab.Vel < 30.0; ++step_count) { + step(dragon6, step_count, wire); + } + CAPTURE(cab.Vel); + REQUIRE(cab.Itot > 50.0); + CHECK(cab.CatenaryCurrent() == std::abs(cab.Itot) * cab.IsVehicleEIMBrakingFactor() + cab.TotalCurrent); + CHECK(cab.CatenaryCurrent() > 50.0); + } +} + +TEST_CASE("genset: a scenery command reaches the selector") { + vehicle dragon6{dragon_genset(), 0.0, "test", 1}; + auto &cab{dragon6.physics()}; + wake(cab); + // as a scenery's PutValues event gives it, one at a time + cab.PutCommand("TractionMode", 1, 0, cab.Loc()); + dragon6.step(no_wire); + CHECK(cab.GensetSelected()); + CHECK(cab.CommandIn.Command == VehicleCommand::none); + cab.PutCommand("GensetSwitch", 1, 0, cab.Loc()); + dragon6.step(no_wire); + CHECK(cab.Genset.is_enabled); + run(dragon6, 10.0); + CHECK(cab.Genset.is_active); + cab.PutCommand("TractionMode", 0, 0, cab.Loc()); + dragon6.step(no_wire); + CHECK_FALSE(cab.GensetSelected()); +} diff --git a/tests/unit/test_handover.cpp b/tests/unit/test_handover.cpp index ff4a0df82..ed06f3461 100644 --- a/tests/unit/test_handover.cpp +++ b/tests/unit/test_handover.cpp @@ -25,24 +25,24 @@ vehicle cab_vehicle() { TEST_CASE("handover: the horn the AI was sounding goes quiet (eu07/maszyna#511)") { auto cab{cab_vehicle()}; - SUBCASE("low tone") { cab->WarningSignal = 1; } - SUBCASE("high tone") { cab->WarningSignal = 2; } - SUBCASE("both tones") { cab->WarningSignal = 1 | 2; } - REQUIRE(cab->WarningSignal != 0); + SUBCASE("low tone") { cab->SetWarningSignal(1); } + SUBCASE("high tone") { cab->SetWarningSignal(2); } + SUBCASE("both tones") { cab->SetWarningSignal(1 | 2); } + REQUIRE(cab->WarningSignal() != 0); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK(cab->WarningSignal == 0); + CHECK(cab->WarningSignal() == 0); } TEST_CASE("handover: sanding the AI started stops") { auto cab{cab_vehicle()}; cab->Sandbox(true); // the way the AI sands, bypassing the sanding button - REQUIRE(cab->SandDose); + REQUIRE(cab->SandDose()); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK_FALSE(cab->SandDose); + CHECK_FALSE(cab->SandDose()); } TEST_CASE("handover: sanding the player or the automatic system asked for goes on") { @@ -52,60 +52,60 @@ TEST_CASE("handover: sanding the player or the automatic system asked for goes o cab->SandboxAutoAllow(true); cab->SandboxAuto(true); } - REQUIRE(cab->SandDose); + REQUIRE(cab->SandDose()); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK(cab->SandDose); + CHECK(cab->SandDose()); } TEST_CASE("handover: the departure signal the AI was giving stops") { auto cab{cab_vehicle()}; cab->signal_departure(true); - REQUIRE(cab->DepartureSignal); + REQUIRE(cab->DepartureSignal()); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK_FALSE(cab->DepartureSignal); + CHECK_FALSE(cab->DepartureSignal()); } TEST_CASE("handover: the brake releaser the AI was holding lets go") { auto cab{cab_vehicle()}; cab->BrakeReleaser(1); - REQUIRE(cab->Hamulec->Releaser()); + REQUIRE(cab->brakes.distributor->Releaser()); - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK_FALSE(cab->Hamulec->Releaser()); + CHECK_FALSE(cab->brakes.distributor->Releaser()); } TEST_CASE("handover: nothing the AI didn't latch changes") { auto cab{cab_vehicle()}; - handover::release_ai_controls(cab.mover(), cab.mover()); + handover::release_ai_controls(cab.physics(), cab.physics()); - CHECK(cab->WarningSignal == 0); - CHECK_FALSE(cab->SandDose); - CHECK_FALSE(cab->DepartureSignal); - CHECK_FALSE(cab->Hamulec->Releaser()); + CHECK(cab->WarningSignal() == 0); + CHECK_FALSE(cab->SandDose()); + CHECK_FALSE(cab->DepartureSignal()); + CHECK_FALSE(cab->brakes.distributor->Releaser()); } TEST_CASE("handover: the light selector moves to the position giving the head lights the AI has set") { auto cab{cab_vehicle()}; - REQUIRE(cab->LightsPos == 1); // untouched selector: lights off + REQUIRE(cab->LightsPos() == 1); // untouched selector: lights off SUBCASE("Pc1") { - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); } SUBCASE("lights off") { - CHECK(handover::light_selector_position(cab.mover(), end::front, 0, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), 0, allheadlights) == 1); } SUBCASE("vehicle without the upper headlight, which the AI's Pc1 can't light") { auto const inventory{allheadlights & ~light::headlight_upper}; - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1 & inventory, inventory) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1 & inventory, inventory) == 2); } SUBCASE("no position matches: the selector stays") { - CHECK(handover::light_selector_position(cab.mover(), end::front, light::headlight_left, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); } } @@ -118,37 +118,37 @@ TEST_CASE("handover: the light selector stays within its table") { std::fill(std::begin(table) + cab->LightsPosNo, std::end(table), 0); } cab->LightsPosNo = 100; - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1, allheadlights) == 2); - CHECK(handover::light_selector_position(cab.mover(), end::front, light::headlight_left, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), light::headlight_left, allheadlights) == 1); } SUBCASE("table other than the front or rear one: the selector stays") { - CHECK(handover::light_selector_position(cab.mover(), -1, pc1, allheadlights) == 1); - CHECK(handover::light_selector_position(cab.mover(), 2, pc1, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), -1, pc1, allheadlights) == 1); + CHECK(handover::light_selector_position(cab.physics(), 2, pc1, allheadlights) == 1); } } TEST_CASE("handover: the light selector already matching the lights stays") { auto cab{cab_vehicle()}; - cab->LightsPos = 2; // Pc1 + cab->SetLightsPos(2); // Pc1 - CHECK(handover::light_selector_position(cab.mover(), end::front, pc1, allheadlights) == 2); + CHECK(handover::light_selector_position(cab.physics(), NumberOf(VehicleEnd::front), pc1, allheadlights) == 2); } TEST_CASE("handover: the headlight dimmer leaves the off position when the head lights are lit") { auto cab{cab_vehicle()}; - REQUIRE(cab->enableModernDimmer); + REQUIRE(cab->enableModernDimmer()); REQUIRE(cab->dimPositions.size() == 5); - cab->modernDimmerPosition = 2; // off, left there by the player before the AI took over + cab->SetDimmerPosition(2); // off, left there by the player before the AI took over SUBCASE("to the default position") { - CHECK(handover::dimmer_position(cab.mover(), true) == 3); + CHECK(handover::dimmer_position(cab.physics(), true) == 3); } SUBCASE("to the first regular position, when the default one is off as well") { cab->modernDimmerDefaultPosition = 2; - CHECK(handover::dimmer_position(cab.mover(), true) == 3); + CHECK(handover::dimmer_position(cab.physics(), true) == 3); } SUBCASE("unless the head lights are off anyway") { - CHECK(handover::dimmer_position(cab.mover(), false) == 2); + CHECK(handover::dimmer_position(cab.physics(), false) == 2); } } @@ -156,14 +156,14 @@ TEST_CASE("handover: the headlight dimmer in any other position stays") { auto cab{cab_vehicle()}; for (auto const position : {0, 1, 3, 4}) { CAPTURE(position); - cab->modernDimmerPosition = position; - CHECK(handover::dimmer_position(cab.mover(), true) == position); + cab->SetDimmerPosition(position); + CHECK(handover::dimmer_position(cab.physics(), true) == position); } } TEST_CASE("handover: a vehicle without the modern dimmer keeps its dimmer state") { vehicle wagon{definition::load("wagon")}; - REQUIRE_FALSE(wagon->enableModernDimmer); + REQUIRE_FALSE(wagon->enableModernDimmer()); - CHECK(handover::dimmer_position(wagon.mover(), true) == wagon->modernDimmerPosition); + CHECK(handover::dimmer_position(wagon.physics(), true) == wagon->DimmerPosition()); } diff --git a/tests/unit/test_hardware_info.cpp b/tests/unit/test_hardware_info.cpp new file mode 100644 index 000000000..73023ca23 --- /dev/null +++ b/tests/unit/test_hardware_info.cpp @@ -0,0 +1,236 @@ +#include "stdafx.h" +#include "doctest.h" +#include "utilities/hardwareinfo.h" + +// what the log says of the machine at startup (utilities/hardwareinfo.h): the names of real GPUs, as DXGI and the +// OpenGL drivers give them, and the text of /proc on Linux +using namespace hardware; + +TEST_CASE("hardware info: NVIDIA GPUs are discrete") +{ + CHECK(classify_gpu(vendor_nvidia, "NVIDIA GeForce RTX 3060") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_nvidia, "NVIDIA GeForce MX150") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_nvidia, "NVIDIA RTX A2000 Laptop GPU") == gpu_kind::discrete); +} + +TEST_CASE("hardware info: Intel GPUs are integrated, except the Arc cards and Iris Xe MAX") +{ + CHECK(classify_gpu(vendor_intel, "Intel(R) UHD Graphics 630") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) HD Graphics 4600") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Iris(R) Xe Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) Graphics") == gpu_kind::integrated); // Meteor Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) 140V GPU (16GB)") == gpu_kind::integrated); // Lunar Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B390 GPU") == gpu_kind::integrated); // Panther Lake + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B370 GPU") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A310 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A380 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A370M Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B570 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) A770 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) B580 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Arc(TM) Pro A60 Graphics") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_intel, "Intel(R) Iris(R) Xe MAX Graphics") == gpu_kind::discrete); +} + +TEST_CASE("hardware info: AMD cards are discrete, the APUs integrated, the rest unknown") +{ + CHECK(classify_gpu(vendor_amd, "AMD Radeon RX 6600") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "Radeon RX 580 Series") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon Pro W6600") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon VII") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD FirePro W5100") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) Vega 8 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon 780M Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) R7 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) RX Vega 11 Graphics") == gpu_kind::integrated); // Raven Ridge + CHECK(classify_gpu(vendor_amd, "AMD Radeon(TM) RX Vega 10 Graphics") == gpu_kind::integrated); + CHECK(classify_gpu(vendor_amd, "Radeon RX Vega") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "AMD Radeon RX Vega 56") == gpu_kind::discrete); + CHECK(classify_gpu(vendor_amd, "Radeon RX Vega M GH Graphics") == gpu_kind::discrete); // Kaby Lake G, own memory + CHECK(classify_gpu(vendor_amd, "AMD Radeon R7 370") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_amd, "AMD Radeon HD 7850") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_amd_alt, "AMD Radeon(TM) Graphics") == gpu_kind::integrated); +} + +TEST_CASE("hardware info: other vendors are unknown, software renderers software") +{ + CHECK(classify_gpu(0x15ad, "VMware SVGA 3D") == gpu_kind::unknown); + CHECK(classify_gpu(0x5143, "Qualcomm(R) Adreno(TM) X1-85 GPU") == gpu_kind::unknown); + CHECK(classify_gpu(vendor_microsoft, "Microsoft Basic Render Driver") == gpu_kind::software); +} + +TEST_CASE("hardware info: the OpenGL vendor and renderer strings") +{ + // Windows drivers + CHECK(vendor_from_gl("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2") == vendor_nvidia); + CHECK(vendor_from_gl("ATI Technologies Inc.", "AMD Radeon RX 6600") == vendor_amd); + CHECK(vendor_from_gl("Intel", "Intel(R) UHD Graphics 630") == vendor_intel); + // Mesa names the maker in the renderer + CHECK(vendor_from_gl("Mesa", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)") == vendor_intel); + CHECK(vendor_from_gl("X.Org", "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7, DRM 3.49)") == vendor_amd); + CHECK(vendor_from_gl("Mesa", "llvmpipe (LLVM 15.0.7, 256 bits)") == 0); + + CHECK(classify_gl("NVIDIA Corporation", "NVIDIA GeForce RTX 3060/PCIe/SSE2") == gpu_kind::discrete); + CHECK(classify_gl("Intel", "Intel(R) UHD Graphics 630") == gpu_kind::integrated); + CHECK(classify_gl("ATI Technologies Inc.", "AMD Radeon(TM) Graphics") == gpu_kind::integrated); + CHECK(classify_gl("X.Org", "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7, DRM 3.49)") == gpu_kind::integrated); + CHECK(classify_gl("AMD", "AMD Radeon RX 6600 (radeonsi, navi23, LLVM 17.0.6, DRM 3.57)") == gpu_kind::discrete); + CHECK(classify_gl("Intel", "Mesa Intel(R) Arc(tm) A770 Graphics (DG2)") == gpu_kind::discrete); + CHECK(classify_gl("Mesa", "llvmpipe (LLVM 15.0.7, 256 bits)") == gpu_kind::software); + CHECK(classify_gl("Microsoft Corporation", "GDI Generic") == gpu_kind::software); + CHECK(classify_gl("nouveau", "NV138") == gpu_kind::unknown); +} + +namespace { +gpu_adapter adapter(std::string Description, std::uint32_t const VendorId, bool const Software = false) +{ + gpu_adapter result; + result.description = std::move(Description); + result.vendor_id = VendorId; + result.software = Software; + return result; +} +} // namespace + +TEST_CASE("hardware info: a warning when OpenGL runs on the integrated GPU beside a dedicated one") +{ + std::vector const laptop{adapter("Intel(R) UHD Graphics 630", vendor_intel), adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}; + + auto const warnings{gl_warnings(laptop, "Intel", "Intel(R) UHD Graphics 630")}; + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().starts_with("hardware: warning: ")); + CHECK(warnings.front().find("Intel(R) UHD Graphics 630") != std::string::npos); + CHECK(warnings.front().find("NVIDIA GeForce GTX 1650") != std::string::npos); + + // on the dedicated one all is well + CHECK(gl_warnings(laptop, "NVIDIA Corporation", "NVIDIA GeForce GTX 1650/PCIe/SSE2").empty()); + // a desktop with the integrated GPU only, or a GPU that can't be told, says nothing + CHECK(gl_warnings({adapter("Intel(R) UHD Graphics 630", vendor_intel)}, "Intel", "Intel(R) UHD Graphics 630").empty()); + CHECK(gl_warnings({adapter("AMD Radeon HD 7850", vendor_amd), adapter("Intel(R) HD Graphics 4600", vendor_intel)}, "Intel", "Intel(R) HD Graphics 4600").empty()); + // Linux lists no adapters + CHECK(gl_warnings({}, "Intel", "Mesa Intel(R) UHD Graphics 620 (KBL GT2)").empty()); + // an AMD APU beside an AMD card + CHECK(gl_warnings({adapter("AMD Radeon(TM) Graphics", vendor_amd), adapter("AMD Radeon RX 6600M", vendor_amd)}, "ATI Technologies Inc.", "AMD Radeon(TM) Graphics").size() == 1); + // a Ryzen 2400G with the monitor on the motherboard beside a GeForce, a Panther Lake laptop running GL on the B390 + CHECK(gl_warnings({adapter("AMD Radeon(TM) RX Vega 11 Graphics", vendor_amd), adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}, "ATI Technologies Inc.", "AMD Radeon(TM) RX Vega 11 Graphics").size() == 1); + CHECK(gl_warnings({adapter("Intel(R) Arc(TM) B390 GPU", vendor_intel), adapter("NVIDIA GeForce RTX 5060 Laptop GPU", vendor_nvidia)}, "Intel", "Intel(R) Arc(TM) B390 GPU").size() == 1); +} + +TEST_CASE("hardware info: a warning when OpenGL draws on the cpu") +{ + auto const warnings{gl_warnings({adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}, "Microsoft Corporation", "GDI Generic")}; + REQUIRE(warnings.size() == 1); + CHECK(warnings.front().find("GDI Generic") != std::string::npos); +} + +TEST_CASE("hardware info: a warning for a cpu without AVX2 only when the build needs it") +{ + cpu_info cpu; + cpu.avx2 = 0; + CHECK(cpu_warnings(cpu, true).size() == 1); + CHECK(cpu_warnings(cpu, false).empty()); + cpu.avx2 = 1; + CHECK(cpu_warnings(cpu, true).empty()); + cpu.avx2 = -1; // can't tell: no warning + CHECK(cpu_warnings(cpu, true).empty()); +} + +TEST_CASE("hardware info: sizes") +{ + CHECK(format_size(0) == "0 MiB"); + CHECK(format_size(128ULL * 1024 * 1024) == "128 MiB"); + CHECK(format_size(1023ULL * 1024 * 1024) == "1023 MiB"); + CHECK(format_size(1024ULL * 1024 * 1024) == "1.0 GiB"); + CHECK(format_size(12ULL * 1024 * 1024 * 1024) == "12.0 GiB"); + CHECK(format_size(17'058'000'000ULL) == "15.9 GiB"); +} + +TEST_CASE("hardware info: names") +{ + CHECK(tidy_name(" Intel(R) Core(TM) i5-4430 CPU @ 3.00GHz") == "Intel(R) Core(TM) i5-4430 CPU @ 3.00GHz"); + CHECK(tidy_name("AMD Ryzen 5 5600X 6-Core Processor ") == "AMD Ryzen 5 5600X 6-Core Processor"); + CHECK(tidy_name("") == ""); +} + +TEST_CASE("hardware info: /proc/cpuinfo") +{ + // two cores with two threads each, one package; the flags of the first processor count + auto const cpu{parse_cpuinfo("processor\t: 0\n" + "model name\t: Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz\n" + "physical id\t: 0\n" + "core id\t\t: 0\n" + "cpu cores\t: 2\n" + "flags\t\t: fpu vme sse sse2 avx avx2 bmi2\n" + "\n" + "processor\t: 1\n" + "model name\t: Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz\n" + "physical id\t: 0\n" + "core id\t\t: 1\n" + "\n" + "processor\t: 2\n" + "physical id\t: 0\n" + "core id\t\t: 0\n" + "\n" + "processor\t: 3\n" + "physical id\t: 0\n" + "core id\t\t: 1\n")}; + CHECK(cpu.model == "Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz"); + CHECK(cpu.logical_cores == 4); + CHECK(cpu.physical_cores == 2); + CHECK(cpu.avx2 == 1); + + // no core ids (some virtual machines): the cores of the package; no avx2 in the flags + auto const vm{parse_cpuinfo("processor : 0\nmodel name : Some CPU\ncpu cores : 4\nflags : sse sse2 avx\n")}; + CHECK(vm.physical_cores == 4); + CHECK(vm.avx2 == 0); + + // nothing known + auto const empty{parse_cpuinfo("")}; + CHECK(empty.model.empty()); + CHECK(empty.logical_cores == 0); + CHECK(empty.physical_cores == 0); + CHECK(empty.avx2 == -1); +} + +TEST_CASE("hardware info: /proc/meminfo") +{ + auto const memory{parse_meminfo("MemTotal: 16303064 kB\nMemFree: 1234567 kB\nMemAvailable: 8151532 kB\n")}; + CHECK(memory.total == 16303064ULL * 1024); + CHECK(memory.available == 8151532ULL * 1024); + CHECK(parse_meminfo("").total == 0); +} + +TEST_CASE("hardware info: the lines of the log") +{ + cpu_info cpu; + cpu.model = "AMD Ryzen 5 5600X 6-Core Processor"; + cpu.physical_cores = 6; + cpu.logical_cores = 12; + cpu.avx2 = 1; + CHECK(format_cpu(cpu) == "hardware: cpu: AMD Ryzen 5 5600X 6-Core Processor, 6 cores, 12 threads, avx2 yes"); + CHECK(format_cpu(cpu_info{}) == "hardware: cpu: unknown, avx2 unknown"); + + memory_info memory; + memory.total = 16ULL * 1024 * 1024 * 1024; + memory.available = 7ULL * 1024 * 1024 * 1024; + CHECK(format_memory(memory) == "hardware: ram: 16.0 GiB total, 7.0 GiB available"); + CHECK(format_memory(memory_info{}) == "hardware: ram: unknown total"); + + gpu_adapter gpu{adapter("NVIDIA GeForce GTX 1650", vendor_nvidia)}; + gpu.device_id = 0x1f82; + gpu.dedicated_video_memory = 4ULL * 1024 * 1024 * 1024; + gpu.shared_system_memory = 8ULL * 1024 * 1024 * 1024; + gpu.outputs = 1; + CHECK(format_adapter(1, gpu) == "hardware: gpu 1: NVIDIA GeForce GTX 1650 (vendor 0x10de, device 0x1f82), 4.0 GiB dedicated, 8.0 GiB shared, 1 outputs, discrete"); + + CHECK(format_gl("Intel", "Intel(R) UHD Graphics 630") == "hardware: opengl gpu: Intel(R) UHD Graphics 630 (Intel), integrated"); + + gl_memory_info gl; + gl.dedicated = 4ULL * 1024 * 1024 * 1024; + gl.available = 3ULL * 1024 * 1024 * 1024; + CHECK(format_gl_memory(gl) == "hardware: opengl gpu memory: 4.0 GiB dedicated, 3.0 GiB free"); + gl.dedicated = 0; + CHECK(format_gl_memory(gl) == "hardware: opengl gpu memory: 3.0 GiB free"); + CHECK(format_gl_memory(gl_memory_info{}) == "hardware: opengl gpu memory: unknown"); +} diff --git a/tests/unit/test_horn.cpp b/tests/unit/test_horn.cpp index 18e5c5322..4c9fd7fb3 100644 --- a/tests/unit/test_horn.cpp +++ b/tests/unit/test_horn.cpp @@ -55,67 +55,67 @@ int const allhorns{horn::low | horn::high | 4}; TEST_CASE("horn: a pneumatic horn sounds on the air of the main reservoir only") { auto vehicle{horn_vehicle(test::definition::load("wagon"))}; - REQUIRE(vehicle->HornSupply == horn_supply::air); // the default + REQUIRE(vehicle->HornSupply() == horn_supply::air); // the default - vehicle->Compressor = 6.5; + vehicle->air.SetPressureForTest(6.5); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); - vehicle->Compressor = 0.0; // the reservoir is empty + vehicle->air.SetPressureForTest(0.0); // the reservoir is empty CHECK(vehicle->SoundingHorns(allhorns) == 0); } TEST_CASE("horn: a vehicle without a main reservoir takes the horn air from the main pipe") { test::vehicle vehicle{test::definition::load("wagon")}; - REQUIRE(vehicle->VeselVolume == 0.0); + REQUIRE(vehicle->air.config.mainReservoirVolume == 0.0); - vehicle->ScndPipePress = 5.0; + vehicle->mainPipe.SetPressure(5.0); CHECK(vehicle->SoundingHorns(horn::low) == horn::low); - vehicle->ScndPipePress = 0.0; + vehicle->mainPipe.SetPressure(0.0); CHECK(vehicle->SoundingHorns(horn::low) == 0); } TEST_CASE("horn: an electric horn sounds on the low voltage, whatever the air") { auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "HornType", "Electric"))}; - REQUIRE(vehicle->HornSupply == horn_supply::electric); + REQUIRE(vehicle->HornSupply() == horn_supply::electric); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); // the third horn follows the others unless told otherwise - vehicle->Compressor = 0.0; - vehicle->Power24vIsAvailable = true; + vehicle->air.SetPressureForTest(0.0); + vehicle->lowVoltage.Set24vAvailableForTest(true); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); - vehicle->Power24vIsAvailable = false; + vehicle->lowVoltage.Set24vAvailableForTest(false); CHECK(vehicle->SoundingHorns(allhorns) == 0); } TEST_CASE("horn: the third horn can have a supply of its own, an electric horn of a diesel say") { auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "Horn3Type", "Electric"))}; - REQUIRE(vehicle->HornSupply == horn_supply::air); + REQUIRE(vehicle->HornSupply() == horn_supply::air); REQUIRE(vehicle->Horn3Supply == horn_supply::electric); - vehicle->Compressor = 0.0; - vehicle->Power24vIsAvailable = true; + vehicle->air.SetPressureForTest(0.0); + vehicle->lowVoltage.Set24vAvailableForTest(true); CHECK(vehicle->SoundingHorns(allhorns) == 4); - vehicle->Compressor = 6.5; - vehicle->Power24vIsAvailable = false; + vehicle->air.SetPressureForTest(6.5); + vehicle->lowVoltage.Set24vAvailableForTest(false); CHECK(vehicle->SoundingHorns(allhorns) == (horn::low | horn::high)); } TEST_CASE("horn: a vehicle without any air, a road vehicle say, sounds its pneumatic horn as before") { // no main reservoir and no main pipe connection at either end test::vehicle vehicle{test::definition::load("wagon").set("BuffCoupl", "AllowedFlag", 3)}; - REQUIRE(vehicle->VeselVolume == 0.0); - vehicle->ScndPipePress = 0.0; + REQUIRE(vehicle->air.config.mainReservoirVolume == 0.0); + vehicle->mainPipe.SetPressure(0.0); CHECK(vehicle->SoundingHorns(allhorns) == allhorns); } TEST_CASE("horn: a pneumatic horn sounds from the threshold pressure up") { auto vehicle{horn_vehicle(test::definition::load("wagon"))}; - vehicle->Compressor = TMoverParameters::HornMinPressure; + vehicle->air.SetPressureForTest(physics::Vehicle::HornMinPressure); CHECK(vehicle->SoundingHorns(horn::low) == horn::low); - vehicle->Compressor = TMoverParameters::HornMinPressure - 0.01; + vehicle->air.SetPressureForTest(physics::Vehicle::HornMinPressure - 0.01); CHECK(vehicle->SoundingHorns(horn::low) == 0); } TEST_CASE("horn: an electric horn sounds on 110 V too") { auto vehicle{horn_vehicle(test::definition::load("wagon").set("Cntrl", "HornType", "Electric"))}; - vehicle->Power110vIsAvailable = true; + vehicle->lowVoltage.Set110vAvailableForTest(true); CHECK(vehicle->SoundingHorns(horn::high) == horn::high); } diff --git a/tests/unit/test_ini_only_settings.cpp b/tests/unit/test_ini_only_settings.cpp new file mode 100644 index 000000000..83303aad4 --- /dev/null +++ b/tests/unit/test_ini_only_settings.cpp @@ -0,0 +1,154 @@ +#include "stdafx.h" +#include "doctest.h" + +// the settings only eu07.ini sets (utilities/inionlysettings.h): a config block of a scenery is read by the parser of +// eu07.ini (global_settings::ConfigParse with config_source::scenery), which keeps these as eu07.ini set them, and puts +// them back before FinalizeConfig() acts on any. here the keeping, as ConfigParse does it around the keys of a scenery + +#include "utilities/Globals.h" +#include "utilities/inionlysettings.h" + +#include +#include +#include +#include +#include + +namespace { + +bool listed(std::vector const &Keys, std::string_view const Key) { + return std::ranges::find(Keys, Key) != Keys.end(); +} + +} // namespace + +TEST_CASE("ini only settings: a scenery's config block doesn't give its scripts all libraries") { + auto const settings{std::make_unique()}; + settings->lua_fulllibraries = false; + ini_only_settings const ini{*settings}; + // "config lua.fulllibraries yes endconfig" in the .scn + settings->lua_fulllibraries = true; + auto const changed{ini.restore(*settings)}; + CHECK_FALSE(settings->lua_fulllibraries); + CHECK(changed == std::vector{"lua.fulllibraries"}); +} + +TEST_CASE("ini only settings: a scenery switches a runtime off, but not on") { + auto const python{[](global_settings &Settings) -> bool & { return Settings.python_enabled; }}; + auto const luascreens{[](global_settings &Settings) -> bool & { return Settings.luascreens_enabled; }}; + auto const wasm{[](global_settings &Settings) -> bool & { return Settings.wasm_enabled; }}; + auto const fulllibraries{[](global_settings &Settings) -> bool & { return Settings.lua_fulllibraries; }}; + using setting = bool &(*)(global_settings &); + for (auto const &[key, switched] : {std::pair{"python.enabled", python}, {"luascreens.enabled", luascreens}, + {"wasm.enabled", wasm}, {"lua.fulllibraries", fulllibraries}}) { + CAPTURE(key); + { + // on in eu07.ini, off in the scenery: off, and nothing in the log + auto const settings{std::make_unique()}; + switched(*settings) = true; + ini_only_settings const ini{*settings}; + // "config python.enabled no endconfig" in the .scn, as the release honoured it + switched(*settings) = false; + CHECK(ini.restore(*settings).empty()); + CHECK_FALSE(switched(*settings)); + } + { + // off in eu07.ini, on in the scenery: back off, and told + auto const settings{std::make_unique()}; + switched(*settings) = false; + ini_only_settings const ini{*settings}; + switched(*settings) = true; + CHECK(ini.restore(*settings) == std::vector{key}); + CHECK_FALSE(switched(*settings)); + } + // as eu07.ini set it: kept, nothing told + for (auto const value : {false, true}) { + auto const settings{std::make_unique()}; + switched(*settings) = value; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(switched(*settings) == value); + } + } +} + +TEST_CASE("ini only settings: a scenery runs no program, opens no connection and switches no runtime back on") { + auto const settings{std::make_unique()}; + settings->luascreens_enabled = false; + settings->wasm_enabled = false; + settings->python_enabled = false; + ini_only_settings const ini{*settings}; + + settings->exec_on_exit = "cmd /c del something"; + settings->extcam_cmd = "evil.exe"; + settings->extcam_rec = "evil.exe"; + settings->screenshot_dir = "C:/Users/Public"; + settings->network_servers.emplace_back("tcp", "0.0.0.0:7424"); + settings->network_client.emplace("tcp", "example.com:7424"); + settings->motiontelemetry_conf.enable = true; + settings->motiontelemetry_conf.address = "example.com"; + settings->iFeedbackMode = 4; + settings->iFeedbackPort = 0x378; + settings->luascreens_enabled = true; + settings->wasm_enabled = true; + settings->python_enabled = true; +#ifdef WITH_UART + settings->uart_conf.enable = true; + settings->uart_conf.port = "COM1"; +#endif +#ifdef WITH_ZMQ + settings->zmq_address = "tcp://*:5555"; +#endif + // and a key a scenery may set + settings->fFriction = 0.5; + + auto const changed{ini.restore(*settings)}; + CHECK(settings->exec_on_exit.empty()); + CHECK(settings->extcam_cmd.empty()); + CHECK(settings->extcam_rec.empty()); + CHECK(settings->screenshot_dir.empty()); + CHECK(settings->network_servers.empty()); + CHECK_FALSE(settings->network_client.has_value()); + CHECK_FALSE(settings->motiontelemetry_conf.enable); + CHECK(settings->motiontelemetry_conf.address.empty()); + CHECK(settings->iFeedbackMode == 1); + CHECK(settings->iFeedbackPort == 0); + CHECK_FALSE(settings->luascreens_enabled); + CHECK_FALSE(settings->wasm_enabled); + CHECK_FALSE(settings->python_enabled); + for (auto const *key : {"execonexit", "extcam.cmd", "extcam.rec", "screenshotsdir", "network.server", "network.client", "motiontelemetry", + "feedbackmode", "feedbackport", "luascreens.enabled", "wasm.enabled", "python.enabled"}) { + CAPTURE(key); + CHECK(listed(changed, key)); + } +#ifdef WITH_UART + CHECK_FALSE(settings->uart_conf.enable); + CHECK(settings->uart_conf.port.empty()); + CHECK(listed(changed, "uart")); +#endif +#ifdef WITH_ZMQ + CHECK(settings->zmq_address.empty()); + CHECK(listed(changed, "zmq.address")); +#endif + // the rest is the scenery's to set + CHECK(settings->fFriction == doctest::Approx(0.5)); +} + +TEST_CASE("ini only settings: nothing changed, nothing to tell") { + auto const settings{std::make_unique()}; + settings->exec_on_exit = "notify.exe"; + ini_only_settings const ini{*settings}; + CHECK(ini.restore(*settings).empty()); + CHECK(settings->exec_on_exit == "notify.exe"); +} + +TEST_CASE("ini only settings: a scenery's config block doesn't change the period of the odometer states") { + auto const settings{std::make_unique()}; + settings->odometer_expiry = 730; + ini_only_settings const ini{*settings}; + // "config odometer.expiry 1 endconfig" in the .scn would drop the states of the vehicles not run yesterday + settings->odometer_expiry = 1; + auto const changed{ini.restore(*settings)}; + CHECK(settings->odometer_expiry == 730); + CHECK(changed == std::vector{"odometer.expiry"}); +} diff --git a/tests/unit/test_invariants.cpp b/tests/unit/test_invariants.cpp index 36c511863..e06421b2a 100644 --- a/tests/unit/test_invariants.cpp +++ b/tests/unit/test_invariants.cpp @@ -12,13 +12,13 @@ using test::vehicle; TEST_CASE("invariants: a vehicle in an impossible state, reported once with its time and the last event") { vehicle eu07{definition::fiz("4e_v1/4e")}; test::trace trace{"invariants/self test", test::channels::brakes()}; - trace.sample(0.0, eu07.mover()); + trace.sample(0.0, eu07.physics()); CHECK(trace.violations().empty()); trace.mark("overfilled"); - eu07->BrakePress = 50.0; - trace.sample(0.01, eu07.mover()); - trace.sample(0.02, eu07.mover()); + eu07->brakes.cylinderPressure = 50.0; + trace.sample(0.01, eu07.physics()); + trace.sample(0.02, eu07.physics()); REQUIRE(trace.violations().size() == 1); auto const &violation{trace.violations().front()}; CHECK(violation.find("brake cylinders") != std::string::npos); @@ -26,9 +26,9 @@ TEST_CASE("invariants: a vehicle in an impossible state, reported once with its CHECK(violation.find("after \"overfilled\"") != std::string::npos); CHECK(violation.find("BrakePress=50") != std::string::npos); - eu07->BrakePress = 0.0; - eu07->V = std::nan(""); - trace.sample(0.03, eu07.mover()); + eu07->brakes.cylinderPressure = 0.0; + eu07->SetV(std::nan("")); + trace.sample(0.03, eu07.physics()); CHECK(trace.violations().size() > 1); CHECK(trace.violations()[1].find("every value a number") != std::string::npos); } diff --git a/tests/unit/test_lights_preset_cablight.cpp b/tests/unit/test_lights_preset_cablight.cpp index 7c64c7d5a..e1dfcc827 100644 --- a/tests/unit/test_lights_preset_cablight.cpp +++ b/tests/unit/test_lights_preset_cablight.cpp @@ -21,7 +21,7 @@ TEST_CASE("lights preset cab light: a table without the column sets no position' .set("LightsList", "rows", {{0, 0}, {shunting, shunting}})}; REQUIRE(wagon->LightsPosNo == 2); - CHECK(wagon->Lights[end::front][1] == shunting); + CHECK(wagon->Lights[VehicleEnd::front][1] == shunting); CHECK_FALSE(wagon->LightsPresetCabLight(1).has_value()); CHECK_FALSE(wagon->LightsPresetCabLight(2).has_value()); } @@ -35,9 +35,9 @@ TEST_CASE("lights preset cab light: the third column turns the cab light off, on REQUIRE(wagon->LightsPosNo == 5); // the light columns read as before - CHECK(wagon->Lights[end::front][2] == shunting); - CHECK(wagon->Lights[end::rear][2] == shunting); - CHECK(wagon->Lights[end::rear][4] == 0); + CHECK(wagon->Lights[VehicleEnd::front][2] == shunting); + CHECK(wagon->Lights[VehicleEnd::rear][2] == shunting); + CHECK(wagon->Lights[VehicleEnd::rear][4] == 0); auto const off{wagon->LightsPresetCabLight(1)}; REQUIRE(off.has_value()); @@ -87,10 +87,10 @@ TEST_CASE("lights preset cab light: a stray note after the two columns is not re auto const rowend{text.find('\n', row)}; REQUIRE(rowend != std::string::npos); text.insert(rowend, " / A"); - TMoverParameters wagon(0.0, "wagon", "test", 0); + physics::Vehicle wagon(0.0, "wagon", "test", 0); REQUIRE(wagon.LoadFIZ_Text(text)); REQUIRE(wagon.LightsPosNo == 2); - CHECK(wagon.Lights[end::front][1] == 38); - CHECK(wagon.Lights[end::rear][1] == 38); + CHECK(wagon.Lights[VehicleEnd::front][1] == 38); + CHECK(wagon.Lights[VehicleEnd::rear][1] == 38); CHECK_FALSE(wagon.LightsPresetCabLight(2).has_value()); } diff --git a/tests/unit/test_lights_programmer.cpp b/tests/unit/test_lights_programmer.cpp index 8a31563d8..cb6e65103 100644 --- a/tests/unit/test_lights_programmer.cpp +++ b/tests/unit/test_lights_programmer.cpp @@ -11,18 +11,18 @@ namespace { int const pc1{light::headlight_left | light::headlight_upper | light::headlight_right}; int const tailmarkers{light::redmarker_left | light::redmarker_right}; -std::array const cablights{pc1, tailmarkers}; // Lights[end::front], Lights[end::rear] +ByEnd const cablights{pc1, tailmarkers}; // Lights[VehicleEnd::front], Lights[VehicleEnd::rear] // the lights at the vehicle's own end, placed the way TDynamicObject::RaLightsSet() places them -int lights_at(lights_programmer::consist_lights const &Lights, int const Direction, end const Side) { - auto const headend{Direction > 0 ? end::front : end::rear}; +int lights_at(lights_programmer::consist_lights const &Lights, int const Direction, VehicleEnd const Side) { + auto const headend{Direction > 0 ? VehicleEnd::front : VehicleEnd::rear}; return Side == headend ? Lights.head : Lights.rear; } struct setup { int cab; // CabOccupied of the vehicle with the programmer int direction; // its iDirection - std::array coupled; // vehicle coupled at its end::front / end::rear + ByEnd coupled; // vehicle coupled at its VehicleEnd::front / VehicleEnd::rear }; lights_programmer::consist_lights lights_for(setup const &Setup) { @@ -36,14 +36,14 @@ lights_programmer::consist_lights lights_for(setup const &Setup) { TEST_CASE("lights programmer: a lone vehicle gets the cab's front lights ahead of the cab and its back lights behind it") { for (auto const direction : {0, 1}) { CAPTURE(direction); - // cab 1 faces end::front + // cab 1 faces VehicleEnd::front auto const fromcab1{lights_for({1, direction, {false, false}})}; - CHECK(lights_at(fromcab1, direction, end::front) == pc1); - CHECK(lights_at(fromcab1, direction, end::rear) == tailmarkers); - // cab -1 faces end::rear + CHECK(lights_at(fromcab1, direction, VehicleEnd::front) == pc1); + CHECK(lights_at(fromcab1, direction, VehicleEnd::rear) == tailmarkers); + // cab -1 faces VehicleEnd::rear auto const fromcab2{lights_for({-1, direction, {false, false}})}; - CHECK(lights_at(fromcab2, direction, end::rear) == pc1); - CHECK(lights_at(fromcab2, direction, end::front) == tailmarkers); + CHECK(lights_at(fromcab2, direction, VehicleEnd::rear) == pc1); + CHECK(lights_at(fromcab2, direction, VehicleEnd::front) == tailmarkers); } } @@ -52,14 +52,14 @@ TEST_CASE("lights programmer: the end with the train coupled goes dark, not the // the end with the train goes dark, the free end shows the lights meant for it for (auto const direction : {0, 1}) { for (auto const cab : {1, -1}) { - for (auto const trainend : {end::front, end::rear}) { + for (auto const trainend : VehicleEnds) { CAPTURE(direction); CAPTURE(cab); CAPTURE(trainend); - std::array coupled{false, false}; + ByEnd coupled{false, false}; coupled[trainend] = true; - auto const freeend{trainend == end::front ? end::rear : end::front}; - auto const cabfront{cab > 0 ? end::front : end::rear}; + auto const freeend{trainend == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front}; + auto const cabfront{cab > 0 ? VehicleEnd::front : VehicleEnd::rear}; auto const lights{lights_for({cab, direction, coupled})}; @@ -71,13 +71,13 @@ TEST_CASE("lights programmer: the end with the train coupled goes dark, not the } TEST_CASE("lights programmer: 6Dg driven backwards from its second cab position pulls the train with its head lights lit (eu07/maszyna#395)") { - // the reported case: the train coupled behind the driver (end::front, which cab -1 has at its back), the - // locomotive running towards end::rear, the train in tow. the head lights stay lit, the end with the train goes dark; + // the reported case: the train coupled behind the driver (VehicleEnd::front, which cab -1 has at its back), the + // locomotive running towards VehicleEnd::rear, the train in tow. the head lights stay lit, the end with the train goes dark; // before the fix the couplings were looked up at the swapped ends and it was the other way round auto const lights{lights_for({-1, 1, {true, false}})}; - CHECK(lights_at(lights, 1, end::rear) == pc1); - CHECK(lights_at(lights, 1, end::front) == 0); + CHECK(lights_at(lights, 1, VehicleEnd::rear) == pc1); + CHECK(lights_at(lights, 1, VehicleEnd::front) == 0); } TEST_CASE("lights programmer: a vehicle coupled at both ends stays dark") { diff --git a/tests/unit/test_line_contactors.cpp b/tests/unit/test_line_contactors.cpp index fd7e24f08..1f8e8551b 100644 --- a/tests/unit/test_line_contactors.cpp +++ b/tests/unit/test_line_contactors.cpp @@ -9,8 +9,8 @@ namespace { test::vehicle locomotive(bool const Pressureswitch) { test::vehicle vehicle{test::definition::load("wagon").set("Engine", "PressureSwitch", Pressureswitch)}; - vehicle->StLinFlag = false; // the line contactors open - vehicle->PipePress = 5.0; + vehicle->lineContactors.Open(); // the line contactors open + vehicle->brakePipe.SetPressure(5.0); return vehicle; } @@ -18,42 +18,42 @@ test::vehicle locomotive(bool const Pressureswitch) { TEST_CASE("line contactors: with a pressure switch the lamp goes out with the start cut off") { auto vehicle{locomotive(true)}; - REQUIRE(vehicle->HasControlPressureSwitch); + REQUIRE(vehicle->protection.config.hasPressureSwitch); - vehicle->BrakePress = 1.5; // braked, the start can still be made + vehicle->brakes.cylinderPressure = 1.5; // braked, the start can still be made vehicle->MotorConnectorsCheck(); // updates the pressure switch - REQUIRE_FALSE(vehicle->ControlPressureSwitch); + REQUIRE_FALSE(vehicle->protection.PressureSwitchTripped()); CHECK(vehicle->LineContactorsLampLit()); - vehicle->BrakePress = 2.5; // the pressure switch cuts the start off + vehicle->brakes.cylinderPressure = 2.5; // the pressure switch cuts the start off vehicle->MotorConnectorsCheck(); - REQUIRE(vehicle->ControlPressureSwitch); + REQUIRE(vehicle->protection.PressureSwitchTripped()); CHECK_FALSE(vehicle->LineContactorsLampLit()); } TEST_CASE("line contactors: without a pressure switch the lamp goes out with the brakes applied, as before") { auto vehicle{locomotive(false)}; - vehicle->BrakePress = 0.5; + vehicle->brakes.cylinderPressure = 0.5; vehicle->MotorConnectorsCheck(); CHECK(vehicle->LineContactorsLampLit()); - vehicle->BrakePress = 1.5; + vehicle->brakes.cylinderPressure = 1.5; vehicle->MotorConnectorsCheck(); CHECK_FALSE(vehicle->LineContactorsLampLit()); } TEST_CASE("line contactors: closed contactors put the lamp out") { auto vehicle{locomotive(true)}; - vehicle->StLinFlag = true; + vehicle->lineContactors.Close(); CHECK_FALSE(vehicle->LineContactorsLampLit()); } TEST_CASE("line contactors: the ground relay and overload lamps follow the same rule") { // all the lamps of the main circuit go out together, with the pressure switch where it's fitted auto vehicle{locomotive(true)}; - vehicle->BrakePress = 1.5; + vehicle->brakes.cylinderPressure = 1.5; vehicle->MotorConnectorsCheck(); CHECK(vehicle->MainCircuitLampsEnabled()); - vehicle->BrakePress = 2.5; + vehicle->brakes.cylinderPressure = 2.5; vehicle->MotorConnectorsCheck(); CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); } @@ -66,7 +66,7 @@ namespace { // the diesel-electric locomotive with its engine running and the brakes released, the master controller at 0 test::vehicle diesel_electric() { test::vehicle vehicle{test::definition::load("diesel_electric")}; - vehicle->CabOccupied = 1; + vehicle->SetCabOccupied(1); vehicle->CabActivisation(); vehicle->BatterySwitch(true); vehicle->OilPumpSwitch(true); @@ -85,19 +85,19 @@ test::vehicle diesel_electric() { TEST_CASE("line contactors: on a diesel-electric the lamp is lit at 0 and goes out on a power position") { auto vehicle{diesel_electric()}; REQUIRE(vehicle->EngineType == TEngineType::DieselElectric); - REQUIRE(vehicle->Mains); - REQUIRE_FALSE(vehicle->ControlPressureSwitch); - CHECK_FALSE(vehicle->StLinFlag); + REQUIRE(vehicle->lineBreaker.IsClosed()); + REQUIRE_FALSE(vehicle->protection.PressureSwitchTripped()); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); vehicle->IncMainCtrl(1); vehicle.run(3.0); - CHECK(vehicle->StLinFlag); + CHECK(vehicle->lineContactors.IsClosed()); CHECK_FALSE(vehicle->LineContactorsLampLit()); vehicle->DecMainCtrl(1); vehicle.run(3.0); - CHECK_FALSE(vehicle->StLinFlag); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); } @@ -107,12 +107,12 @@ TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contac vehicle.run(1.0); vehicle->IncMainCtrl(1); vehicle.run(2.0); - REQUIRE(vehicle->StLinFlag); + REQUIRE(vehicle->lineContactors.IsClosed()); vehicle.hold_brake_pipe(2.5); // bar, below the 3.6 bar of the pressure switch vehicle.run(10.0); - REQUIRE(vehicle->ControlPressureSwitch); - CHECK_FALSE(vehicle->StLinFlag); + REQUIRE(vehicle->protection.PressureSwitchTripped()); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); // it went out here CHECK_FALSE(vehicle->MainCircuitLampsEnabled()); // the ground relay and overload lamps still go out with the start cut off @@ -120,11 +120,11 @@ TEST_CASE("line contactors: on a diesel-electric the lamp lights with the contac // they close again only on the first one vehicle.hold_brake_pipe(5.0); vehicle.run(60.0); - REQUIRE_FALSE(vehicle->ControlPressureSwitch); - CHECK_FALSE(vehicle->StLinFlag); + REQUIRE_FALSE(vehicle->protection.PressureSwitchTripped()); + CHECK_FALSE(vehicle->lineContactors.IsClosed()); CHECK(vehicle->LineContactorsLampLit()); vehicle->DecMainCtrl(1); vehicle.run(3.0); - CHECK(vehicle->StLinFlag); + CHECK(vehicle->lineContactors.IsClosed()); CHECK_FALSE(vehicle->LineContactorsLampLit()); } diff --git a/tests/unit/test_line_contactors_interlock.cpp b/tests/unit/test_line_contactors_interlock.cpp index a025d4a69..74e59d392 100644 --- a/tests/unit/test_line_contactors_interlock.cpp +++ b/tests/unit/test_line_contactors_interlock.cpp @@ -4,7 +4,7 @@ #include "drive.h" #include "vehicle.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" // the line contactors interlocked with the fans of the traction motors (eu07/maszyna#460): on the ET42 the fans of a // section run off its own converter, and with them switched off the line contactors of that section don't close. @@ -22,10 +22,10 @@ vehicle ready(std::string_view const Interlock) { loaded.set("Cntrl", "LineContactorsInterlock", std::string{Interlock}); } vehicle locomotive{loaded}; - locomotive->Mains = true; + locomotive->lineBreaker.Close(); locomotive->DirActive = 1; - locomotive->PipePress = 5.0; - locomotive->BrakePress = 0.0; + locomotive->brakePipe.SetPressure(5.0); + locomotive->brakes.cylinderPressure = 0.0; return locomotive; } @@ -34,15 +34,15 @@ test::track const line{0.15, 0.0, test::catenary_3kv}; } // namespace TEST_CASE("line contactors interlock: read from the Cntrl. section, none by default") { - CHECK(ready("")->LineContactorsInterlock == line_contactors_interlock::none); - CHECK(ready("Converter")->LineContactorsInterlock == line_contactors_interlock::converter); - CHECK(ready("MotorBlowers")->LineContactorsInterlock == line_contactors_interlock::motor_blowers); - CHECK(ready("Something")->LineContactorsInterlock == line_contactors_interlock::none); + CHECK(ready("")->lineContactors.config.interlock == line_contactors_interlock::none); + CHECK(ready("Converter")->lineContactors.config.interlock == line_contactors_interlock::converter); + CHECK(ready("MotorBlowers")->lineContactors.config.interlock == line_contactors_interlock::motor_blowers); + CHECK(ready("Something")->lineContactors.config.interlock == line_contactors_interlock::none); } TEST_CASE("line contactors interlock: without one the converter and the blowers don't matter, as before") { auto locomotive{ready("")}; - locomotive->ConverterFlag = false; + locomotive->converter.SetRunningForTest(false); for (auto &blower : locomotive->MotorBlowers) { blower.is_active = false; } @@ -51,21 +51,21 @@ TEST_CASE("line contactors interlock: without one the converter and the blowers TEST_CASE("line contactors interlock: on the converter, they close only with the vehicle's own converter running") { auto locomotive{ready("Converter")}; - locomotive->ConverterFlag = false; - locomotive->Power110vIsAvailable = true; // the 110 V from the other section doesn't run this one's fans + locomotive->converter.SetRunningForTest(false); + locomotive->lowVoltage.Set110vAvailableForTest(true); // the 110 V from the other section doesn't run this one's fans CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->ConverterFlag = true; + locomotive->converter.SetRunningForTest(true); CHECK(locomotive->MotorConnectorsCheck()); - locomotive->Mains = false; // the other conditions still hold + locomotive->lineBreaker.Open(); // the other conditions still hold CHECK_FALSE(locomotive->MotorConnectorsCheck()); } TEST_CASE("line contactors interlock: on the motor blowers, they close only with all of them running") { auto locomotive{ready("MotorBlowers")}; - locomotive->MotorBlowers[end::front].is_active = true; - locomotive->MotorBlowers[end::rear].is_active = false; + locomotive->MotorBlowers[VehicleEnd::front].is_active = true; + locomotive->MotorBlowers[VehicleEnd::rear].is_active = false; CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->MotorBlowers[end::rear].is_active = true; + locomotive->MotorBlowers[VehicleEnd::rear].is_active = true; CHECK(locomotive->MotorConnectorsCheck()); } @@ -80,10 +80,10 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to blower.is_enabled = true; // switched on by the driver blower.is_active = false; // the vehicle stands } - REQUIRE(locomotive->MotorBlowers[end::front].start_type == start_t::manual); + REQUIRE(locomotive->MotorBlowers[VehicleEnd::front].start_type == start_t::manual); CHECK(locomotive->MotorConnectorsCheck()); - auto &rear{locomotive->MotorBlowers[end::rear]}; + auto &rear{locomotive->MotorBlowers[VehicleEnd::rear]}; SUBCASE("switched off, it holds the contactors open") { rear.is_disabled = true; CHECK_FALSE(locomotive->MotorConnectorsCheck()); @@ -95,16 +95,16 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to SUBCASE("off the converter, it needs the 110 V") { rear.start_type = start_t::converter; rear.is_enabled = false; // nothing for the driver to switch on - locomotive->Power110vIsAvailable = false; + locomotive->lowVoltage.Set110vAvailableForTest(false); CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->Power110vIsAvailable = true; + locomotive->lowVoltage.Set110vAvailableForTest(true); CHECK(locomotive->MotorConnectorsCheck()); } SUBCASE("off the battery, it needs the 24 V") { rear.start_type = start_t::battery; - locomotive->Power24vIsAvailable = false; + locomotive->lowVoltage.Set24vAvailableForTest(false); CHECK_FALSE(locomotive->MotorConnectorsCheck()); - locomotive->Power24vIsAvailable = true; + locomotive->lowVoltage.Set24vAvailableForTest(true); CHECK(locomotive->MotorConnectorsCheck()); } SUBCASE("one without a start velocity still has to run") { @@ -117,23 +117,23 @@ TEST_CASE("line contactors interlock: a blower starting with the speed needs to namespace { -bool blowers_run(TMoverParameters const &Mover) { - return Mover.MotorBlowers[end::front].is_active && Mover.MotorBlowers[end::rear].is_active; +bool blowers_run(physics::Vehicle const &Physics) { + return Physics.MotorBlowers[VehicleEnd::front].is_active && Physics.MotorBlowers[VehicleEnd::rear].is_active; } // the driver's first power position, held until the line contactors close (their delay, the pressure switch) bool close_line_contactors(test::driven const &Driven) { Driven.controlling.IncMainCtrl(1); - for (int i = 0; i < 30 && false == Driven.controlling.StLinFlag; ++i) { + for (int i = 0; i < 30 && false == Driven.controlling.lineContactors.IsClosed(); ++i) { test::drive(Driven, line, 1.0); } - return Driven.controlling.StLinFlag; + return Driven.controlling.lineContactors.IsClosed(); } // the brakes released and the cylinders empty enough for the pressure switch to let the vehicle start void release(test::driven const &Driven) { test::release_brakes(Driven.cab); - for (int i = 0; i < 90 && (Driven.controlling.BrakePress > 0.1 || Driven.controlling.PipePress < 4.8); ++i) { + for (int i = 0; i < 90 && (Driven.controlling.brakes.cylinderPressure > 0.1 || Driven.controlling.brakePipe.Pressure() < 4.8); ++i) { test::drive(Driven, line, 1.0); } } @@ -153,58 +153,58 @@ TEST_CASE("line contactors interlock: with blowers starting with the speed the v .set("Engine", "MotorBlowersStartVelocity", 5.0) .set("Engine", "MotorBlowersSustainTime", 10.0), 0.0, "test", 1}; - auto &mover{eu07.mover()}; - REQUIRE(mover.LineContactorsInterlock == line_contactors_interlock::motor_blowers); - REQUIRE(mover.MotorBlowers[end::front].min_start_velocity == doctest::Approx(5.0)); - REQUIRE(mover.MotorBlowers[end::rear].sustain_time == doctest::Approx(10.0)); + auto &physics{eu07.physics()}; + REQUIRE(physics.lineContactors.config.interlock == line_contactors_interlock::motor_blowers); + REQUIRE(physics.MotorBlowers[VehicleEnd::front].min_start_velocity == doctest::Approx(5.0)); + REQUIRE(physics.MotorBlowers[VehicleEnd::rear].sustain_time == doctest::Approx(10.0)); auto driven{test::driving(eu07)}; REQUIRE(test::start_up(driven, line)); release(driven); // standing, the blowers don't run; the line contactors close all the same and the motors take current REQUIRE(std::abs(eu07.speed()) < 0.1); - REQUIRE_FALSE(blowers_run(mover)); + REQUIRE_FALSE(blowers_run(physics)); CHECK(close_line_contactors(driven)); - CHECK(std::abs(mover.Im) > 0.5); + CHECK(std::abs(physics.Im) > 0.5); // the blowers come on once the vehicle moves for (int i = 0; i < 6; ++i) { - mover.IncMainCtrl(1); + physics.IncMainCtrl(1); test::drive(driven, line, 2.0); } for (int i = 0; i < 60 && eu07.speed() < 10.0; ++i) { test::drive(driven, line, 1.0); } REQUIRE(eu07.speed() >= 10.0); - CHECK(blowers_run(mover)); - CHECK(mover.StLinFlag); + CHECK(blowers_run(physics)); + CHECK(physics.lineContactors.IsClosed()); // a stop longer than the blowers keep running for - while (mover.DecMainCtrl(1)) { + while (physics.DecMainCtrl(1)) { // down to zero } - driven.cab.BrakeLevelSet(driven.cab.Handle->GetPos(bh_FB)); + driven.cab.BrakeLevelSet(driven.cab.brakes.driverValve->GetPos(bh_FB)); for (int i = 0; i < 120 && std::abs(eu07.speed()) > 0.1; ++i) { test::drive(driven, line, 1.0); } REQUIRE(std::abs(eu07.speed()) <= 0.1); test::drive(driven, line, 15.0); - REQUIRE_FALSE(blowers_run(mover)); - REQUIRE_FALSE(mover.StLinFlag); + REQUIRE_FALSE(blowers_run(physics)); + REQUIRE_FALSE(physics.lineContactors.IsClosed()); // and the vehicle starts again release(driven); CHECK(close_line_contactors(driven)); - CHECK(std::abs(mover.Im) > 0.5); + CHECK(std::abs(physics.Im) > 0.5); for (int i = 0; i < 6; ++i) { - mover.IncMainCtrl(1); + physics.IncMainCtrl(1); test::drive(driven, line, 2.0); } for (int i = 0; i < 60 && eu07.speed() < 10.0; ++i) { test::drive(driven, line, 1.0); } CHECK(eu07.speed() >= 10.0); - CHECK(blowers_run(mover)); + CHECK(blowers_run(physics)); } TEST_CASE("line contactors interlock: a blower starting with the speed, switched off on the way, opens the contactors") { @@ -214,44 +214,44 @@ TEST_CASE("line contactors interlock: a blower starting with the speed, switched .set("Engine", "MotorBlowersStartVelocity", 5.0) .set("Engine", "MotorBlowersSustainTime", 10.0), 0.0, "test", 1}; - auto &mover{eu07.mover()}; + auto &physics{eu07.physics()}; auto driven{test::driving(eu07)}; REQUIRE(test::start_up(driven, line)); release(driven); REQUIRE(close_line_contactors(driven)); // the switch of the rear blower: off, the contactors open and stay open, standing as well as later - REQUIRE(mover.MotorBlowersSwitchOff(true, end::rear)); + REQUIRE(physics.MotorBlowersSwitchOff(true, VehicleEnd::rear)); test::drive(driven, line, 2.0); - CHECK_FALSE(mover.StLinFlag); - CHECK(std::abs(mover.Im) < 0.5); - while (mover.DecMainCtrl(1)) { + CHECK_FALSE(physics.lineContactors.IsClosed()); + CHECK(std::abs(physics.Im) < 0.5); + while (physics.DecMainCtrl(1)) { // down to zero } test::drive(driven, line, 2.0); CHECK_FALSE(close_line_contactors(driven)); // back on, the vehicle starts - REQUIRE(mover.MotorBlowersSwitchOff(false, end::rear)); - while (mover.DecMainCtrl(1)) { + REQUIRE(physics.MotorBlowersSwitchOff(false, VehicleEnd::rear)); + while (physics.DecMainCtrl(1)) { // down to zero } test::drive(driven, line, 2.0); CHECK(close_line_contactors(driven)); - CHECK(std::abs(mover.Im) > 0.5); + CHECK(std::abs(physics.Im) > 0.5); } TEST_CASE("line contactors interlock: held by the local converter switch only where they wait for that converter") { // what the AI driver looks at to switch the converter of a section back on (TController, the converteron hint) auto interlocked{ready("Converter")}; CHECK_FALSE(interlocked->LineContactorsHeldByLocalConverterSwitch()); - interlocked->ConverterAllowLocal = false; + interlocked->converter.SetLocalSwitch(false); CHECK(interlocked->LineContactorsHeldByLocalConverterSwitch()); for (auto const *other : {"", "MotorBlowers"}) { CAPTURE(other); auto locomotive{ready(other)}; - locomotive->ConverterAllowLocal = false; + locomotive->converter.SetLocalSwitch(false); CHECK_FALSE(locomotive->LineContactorsHeldByLocalConverterSwitch()); } } @@ -262,16 +262,16 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of et42.add(definition::fiz("et42_v2/112e-b").set("Cntrl", "LineContactorsInterlock", "Converter")); auto driven{test::driving(et42)}; REQUIRE(test::start_up(driven, line)); - auto &front{et42[0].mover()}; - auto &rear{et42[1].mover()}; - REQUIRE(front.ConverterFlag); - REQUIRE(rear.ConverterFlag); + auto &front{et42[0].physics()}; + auto &rear{et42[1].physics()}; + REQUIRE(front.converter.IsRunning()); + REQUIRE(rear.converter.IsRunning()); // the fans of the rear section switched off with its own switch, the 110 V of the front one still reaches it - rear.ConverterAllowLocal = false; + rear.converter.SetLocalSwitch(false); test::drive(driven, line, 2.0); - REQUIRE_FALSE(rear.ConverterFlag); - CHECK(rear.Power110vIsAvailable); + REQUIRE_FALSE(rear.converter.IsRunning()); + CHECK(rear.lowVoltage.Is110vAvailable()); test::release_brakes(driven.cab); for (int i = 0; i < 3 && driven.cab.DirActive <= 0; ++i) { @@ -280,36 +280,36 @@ TEST_CASE("line contactors interlock: the ET42 section with its fans switched of test::drive(driven, line, 20.0); driven.controlling.IncMainCtrl(1); // as the AI does, it waits at the first position for the contactors (their delay, the pressure switch) - for (int i = 0; i < 90 && false == front.StLinFlag; ++i) { + for (int i = 0; i < 90 && false == front.lineContactors.IsClosed(); ++i) { test::drive(driven, line, 1.0); } - CHECK(front.StLinFlag); - CHECK_FALSE(rear.StLinFlag); + CHECK(front.lineContactors.IsClosed()); + CHECK_FALSE(rear.lineContactors.IsClosed()); // the fans back on, the section starts too - rear.ConverterAllowLocal = true; + rear.converter.SetLocalSwitch(true); test::drive(driven, line, 10.0); - REQUIRE(rear.ConverterFlag); - CHECK(rear.StLinFlag); + REQUIRE(rear.converter.IsRunning()); + CHECK(rear.lineContactors.IsClosed()); // and the fans switched off on the way open its line contactors again - rear.ConverterAllowLocal = false; + rear.converter.SetLocalSwitch(false); test::drive(driven, line, 2.0); - CHECK_FALSE(rear.StLinFlag); - CHECK(front.StLinFlag); + CHECK_FALSE(rear.lineContactors.IsClosed()); + CHECK(front.lineContactors.IsClosed()); } TEST_CASE("louvres: closed until the main reservoir reaches the pressure that opens them") { vehicle et22{definition::fiz("et22_v3/201e-w")}; CHECK(et22->LouvresOpenPressure == doctest::Approx(5.0)); // by default - et22->Compressor = 4.9; + et22->air.SetPressureForTest(4.9); CHECK(et22->LouvresClosed()); - et22->Compressor = 5.0; + et22->air.SetPressureForTest(5.0); CHECK_FALSE(et22->LouvresClosed()); vehicle given{definition::fiz("et22_v3/201e-w").set("Cntrl", "LouvresOpenPressure", 4.0)}; - given->Compressor = 4.5; + given->air.SetPressureForTest(4.5); CHECK_FALSE(given->LouvresClosed()); - given->Compressor = 3.9; + given->air.SetPressureForTest(3.9); CHECK(given->LouvresClosed()); } diff --git a/tests/unit/test_linebreaker.cpp b/tests/unit/test_linebreaker.cpp index 126e3307c..55f637bf9 100644 --- a/tests/unit/test_linebreaker.cpp +++ b/tests/unit/test_linebreaker.cpp @@ -9,14 +9,15 @@ using test::consist; using test::definition; +using linebreaker::state; namespace { // the line breaker lever of the EP05 (main_sw), a single two-state lever, the way TTrain works it: the state // the cab keeps of the line breaker follows the vehicle, the breaker closes while the lever is on and can close struct lever { - TMoverParameters &mover; - int breaker{0}; // as TTrain::m_linebreakerstate: 0 open, 1 closed + physics::Vehicle &physics; + state breaker{state::open}; // as TTrain::m_linebreakerstate bool on{false}; void press() { @@ -26,8 +27,8 @@ struct lever { break; case linebreaker::toggle::open: on = false; - if (breaker == 1 && mover.MainSwitch(false)) { - breaker = 0; + if (breaker == state::closed && physics.MainSwitch(false)) { + breaker = state::open; } break; default: @@ -36,14 +37,14 @@ struct lever { } // TTrain::Update() void update() { - if (breaker == 0 && mover.Mains) { - breaker = 1; + if (breaker == state::open && physics.lineBreaker.IsClosed()) { + breaker = state::closed; } - if (breaker == 1 && false == mover.Mains) { - breaker = 0; + if (breaker == state::closed && false == physics.lineBreaker.IsClosed()) { + breaker = state::open; } - if (on && breaker == 0 && mover.MainSwitchCheck()) { - breaker = mover.MainSwitch(true) ? 1 : 0; + if (on && breaker == state::open && physics.MainSwitchCheck()) { + breaker = physics.MainSwitch(true) ? state::closed : state::open; } } }; @@ -53,34 +54,34 @@ struct lever { TEST_CASE("line breaker: a press of the toggle closes an open breaker and opens a closed one") { using enum linebreaker::toggle; for (auto const latching : {false, true}) { - CHECK(linebreaker::pressed(0, latching, false) == close); - CHECK(linebreaker::pressed(1, latching, true) == open); - CHECK(linebreaker::pressed(1, latching, false) == open); + CHECK(linebreaker::pressed(state::open, latching, false) == close); + CHECK(linebreaker::pressed(state::closed, latching, true) == open); + CHECK(linebreaker::pressed(state::closed, latching, false) == open); // freshly closed, the cab finishes closing it first - CHECK(linebreaker::pressed(2, latching, true) == none); + CHECK(linebreaker::pressed(state::closing, latching, true) == none); } // a lever left on over an open breaker goes off; push buttons have no position to keep - CHECK(linebreaker::pressed(0, true, true) == open); - CHECK(linebreaker::pressed(0, false, true) == close); + CHECK(linebreaker::pressed(state::open, true, true) == open); + CHECK(linebreaker::pressed(state::open, false, true) == close); } TEST_CASE("line breaker: the EP05's lever goes off with the converter overload relay tripped (eu07/maszyna#394)") { consist train; - auto &ep05{train.add(definition::fiz("ep05_v2/ep05"), 1).mover()}; + auto &ep05{train.add(definition::fiz("ep05_v2/ep05"), 1).physics()}; test::track const line{0.15, 0.0, test::catenary_3kv}; auto const driver{test::driving(train)}; REQUIRE(test::start_up(driver, line)); - REQUIRE(ep05.Mains); - REQUIRE(ep05.ConverterFlag); - lever ws{ep05, 1, true}; + REQUIRE(ep05.lineBreaker.IsClosed()); + REQUIRE(ep05.converter.IsRunning()); + lever ws{ep05, state::closed, true}; // the converter overload relay knocks the line breaker out, as the cab does it when the converter is // switched on together with the compressor; the lever stays on - ep05.ConvOvldFlag = true; + ep05.converter.Overload(); ep05.MainSwitch(false, range_t::local); ws.update(); - REQUIRE_FALSE(ep05.Mains); - REQUIRE(ws.breaker == 0); + REQUIRE_FALSE(ep05.lineBreaker.IsClosed()); + REQUIRE(ws.breaker == state::open); CHECK(ws.on); // with the relay tripped the breaker doesn't close test::drive(driver, line, 5.0); @@ -92,7 +93,7 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ws.press(); CHECK(ws.on); ws.update(); - CHECK_FALSE(ep05.Mains); + CHECK_FALSE(ep05.lineBreaker.IsClosed()); ws.press(); CHECK_FALSE(ws.on); @@ -100,15 +101,15 @@ TEST_CASE("line breaker: the EP05's lever goes off with the converter overload r ep05.ConverterSwitch(false, range_t::local); test::drive(driver, line, 1.0); CHECK(ep05.RelayReset(relay_t::primaryconverteroverload, range_t::local)); - CHECK_FALSE(ep05.ConvOvldFlag); + CHECK_FALSE(ep05.converter.IsOverloaded()); ws.update(); - CHECK_FALSE(ep05.Mains); // the lever is off + CHECK_FALSE(ep05.lineBreaker.IsClosed()); // the lever is off ws.press(); ws.update(); - CHECK(ep05.Mains); - CHECK(ws.breaker == 1); + CHECK(ep05.lineBreaker.IsClosed()); + CHECK(ws.breaker == state::closed); // and the next press opens it ws.press(); CHECK_FALSE(ws.on); - CHECK_FALSE(ep05.Mains); + CHECK_FALSE(ep05.lineBreaker.IsClosed()); } diff --git a/tests/unit/test_loads.cpp b/tests/unit/test_loads.cpp index b4a9da62a..ee35a6e2a 100644 --- a/tests/unit/test_loads.cpp +++ b/tests/unit/test_loads.cpp @@ -23,10 +23,10 @@ TEST_CASE("loads: the pantographs of an electric vehicle set up by the amount of vehicle et42{definition::fiz("et42_v2/112e-a")}; CHECK(et42->AssignLoad("pantstate", static_cast(amount))); CHECK(et42->DoubleTr == ((amount & 4) != 0 ? -1 : 1)); - CHECK(et42->Pantographs[end::front].valve.is_enabled == frontraised); - CHECK(et42->Pantographs[end::rear].valve.is_enabled == rearraised); + CHECK(et42->pantographs[VehicleEnd::front].valve.is_enabled == frontraised); + CHECK(et42->pantographs[VehicleEnd::rear].valve.is_enabled == rearraised); // the load itself stays as it was - CHECK(et42->LoadAmount == doctest::Approx(0.0)); + CHECK(et42->LoadAmount() == doctest::Approx(0.0)); } // a vehicle without a current collector takes no such load vehicle wagon{definition::fiz("3wl_v2/3wl")}; @@ -35,23 +35,23 @@ TEST_CASE("loads: the pantographs of an electric vehicle set up by the amount of TEST_CASE("loads: a load assigned, of one kind at a time, up to the vehicle's capacity, and emptied") { vehicle wagon{definition::fiz("3wl_v2/3wl")}; - auto const empty{wagon->TotalMass}; + auto const empty{wagon->TotalMass()}; REQUIRE(wagon->AssignLoad("coal", 10.f)); - CHECK(wagon->LoadTypeChange); + CHECK(wagon->LoadTypeChange()); CHECK(wagon->LoadType.name == "coal"); - CHECK(wagon->TotalMass > empty); + CHECK(wagon->TotalMass() > empty); // more of the same: the amount set, not added, and no more than the vehicle takes - wagon->LoadTypeChange = false; + wagon->TakeLoadTypeChange(); REQUIRE(wagon->AssignLoad("coal", 1000.f)); - CHECK_FALSE(wagon->LoadTypeChange); - CHECK(wagon->LoadAmount == doctest::Approx(wagon->MaxLoad)); + CHECK_FALSE(wagon->LoadTypeChange()); + CHECK(wagon->LoadAmount() == doctest::Approx(wagon->MaxLoad())); // another kind can't be added to a load, nor can an unknown one be loaded CHECK_FALSE(wagon->AssignLoad("ruda", 5.f)); CHECK(wagon->LoadType.name == "coal"); // emptied, with no name REQUIRE(wagon->AssignLoad("")); - CHECK(wagon->LoadTypeChange); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadTypeChange()); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LoadType.name.empty()); CHECK_FALSE(wagon->AssignLoad("unknown", 5.f)); CHECK(wagon->AssignLoad("ruda", 5.f)); @@ -61,56 +61,56 @@ TEST_CASE("loads: the steps of loading and unloading") { // most of the game's wagons may be overloaded (OverLoadFactor), the 3WL not vehicle wagon{definition::fiz("3wl_v2/3wl").set("Load", "OverLoadFactor", 1.5)}; REQUIRE(wagon->AssignLoad("coal", 10.f)); - auto const capacity{wagon->MaxLoad * (1.0 + wagon->OverLoadFactor)}; + auto const capacity{wagon->MaxLoad() * (1.0 + wagon->OverLoadFactor)}; SUBCASE("no speed of the change: done at once") { CHECK(wagon->LoadingDone(0.0, "coal")); - CHECK(wagon->LoadStatus == 4); + CHECK(wagon->LoadStatus() == 4); } SUBCASE("no load, or another one, named: done when it was") { - wagon->LoadStatus = 1; + wagon->SetLoadStatusForTest(1); CHECK_FALSE(wagon->LoadingDone(1.0, "")); CHECK_FALSE(wagon->LoadingDone(1.0, "ruda")); - wagon->LoadStatus = 4; + wagon->SetLoadStatusForTest(4); CHECK(wagon->LoadingDone(1.0, "")); } SUBCASE("unloading, step by step, what was asked or all of it, the name going with the last of it") { wagon->CommandIn.Value1 = 4.0; // asked to unload wagon->LastLoadChangeTime = 2.0; // at 1 a second CHECK_FALSE(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadStatus == 2); - CHECK(wagon->LoadAmount == doctest::Approx(8.0)); + CHECK(wagon->LoadStatus() == 2); + CHECK(wagon->LoadAmount() == doctest::Approx(8.0)); CHECK(wagon->LastLoadChangeTime == doctest::Approx(0.0)); // nothing done since the last step CHECK_FALSE(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(8.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(8.0)); wagon->LastLoadChangeTime = 2.0; CHECK(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(6.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(6.0)); wagon->CommandIn.Value1 = 100.0; wagon->LastLoadChangeTime = 10.0; CHECK(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(0.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(0.0)); CHECK(wagon->LoadType.name.empty()); } SUBCASE("loading, step by step, up to what was asked or what the vehicle takes, slower when overloaded") { wagon->CommandIn.Value1 = 5.0; wagon->LastLoadChangeTime = 2.0; CHECK_FALSE(wagon->LoadingDone(1.0, "coal")); - CHECK(wagon->LoadStatus == 1); - CHECK(wagon->LoadAmount == doctest::Approx(12.0)); + CHECK(wagon->LoadStatus() == 1); + CHECK(wagon->LoadAmount() == doctest::Approx(12.0)); wagon->LastLoadChangeTime = 3.0; CHECK(wagon->LoadingDone(1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(15.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(15.0)); wagon->CommandIn.Value1 = 1000.0; wagon->LastLoadChangeTime = 1000.0; CHECK(wagon->LoadingDone(1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(capacity)); - CHECK(capacity == doctest::Approx(2.5 * wagon->MaxLoad)); + CHECK(wagon->LoadAmount() == doctest::Approx(capacity)); + CHECK(capacity == doctest::Approx(2.5 * wagon->MaxLoad())); // over the vehicle's own capacity, the change goes at half the speed wagon->CommandIn.Value1 = 1000.0; wagon->LastLoadChangeTime = 4.0; CHECK_FALSE(wagon->LoadingDone(-1.0, "coal")); - CHECK(wagon->LoadAmount == doctest::Approx(capacity - 2.0)); + CHECK(wagon->LoadAmount() == doctest::Approx(capacity - 2.0)); } } diff --git a/tests/unit/test_log_files.cpp b/tests/unit/test_log_files.cpp new file mode 100644 index 000000000..8a0aac6f3 --- /dev/null +++ b/tests/unit/test_log_files.cpp @@ -0,0 +1,35 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/logfiles.h" + +#include + +// the files the log is written to, and which of them a run deletes when it starts + +TEST_CASE("log files: without multiplelogs the run writes the shared log.txt and errors.txt") +{ + CHECK(log_file_name(log_file::log, false, "td", "20261112_1200123") == "log.txt"); + CHECK(log_file_name(log_file::errors, false, "td", "20261112_1200123") == "errors.txt"); +} + +TEST_CASE("log files: with multiplelogs the run writes its own in logs/, named after the scenery and the time") +{ + CHECK(log_file_name(log_file::log, true, "autotest_case", "20261112_1200123") == "logs/log (autotest_case) 20261112_1200123.txt"); + CHECK(log_file_name(log_file::errors, true, "autotest_case", "20261112_1200123") == "logs/errors (autotest_case) 20261112_1200123.txt"); +} + +TEST_CASE("log files: without multiplelogs the start deletes the shared files it is going to write") +{ + // errors.txt is made at the first error only: one of the run before must not stay behind a run without errors + auto const stale{stale_log_files(false)}; + CHECK(stale.size() == 2); + for (auto const kind : {log_file::log, log_file::errors}) + CHECK(std::ranges::count(stale, log_file_name(kind, false, "td", "20261112_1200123")) == 1); +} + +TEST_CASE("log files: with multiplelogs the start keeps the shared log.txt and errors.txt of the last ordinary run") +{ + // the scenario tests run with multiplelogs; the logs of the player's last game in the game folder stay + CHECK(stale_log_files(true).empty()); +} diff --git a/tests/unit/test_lua_sandbox.cpp b/tests/unit/test_lua_sandbox.cpp new file mode 100644 index 000000000..bc0753162 --- /dev/null +++ b/tests/unit/test_lua_sandbox.cpp @@ -0,0 +1,535 @@ +#include "stdafx.h" +#include "doctest.h" + +// the sandbox the Lua states of the game share (scripting/luasandbox.cpp): the scenery scripts (lua in the .scn, +// scripting/lua.cpp) and the script screens (scripting/luaprogram.cpp, tested with the screens in +// test_script_screen_host.cpp). a script gets base, table, string, math and bit, and of os only the clock; it reaches +// no files, no programs, no ffi, loads no code of its own and no precompiled chunk, and a scenery reads its scripts +// only from its own folder + +#ifdef WITH_LUA + +#include "scripting/luasandbox.h" +#include "scratch.h" + +#include +#include +#include +#include +#include + +namespace { + +// a state with the libraries of the scenery scripts +class sandboxed_state { + public: + sandboxed_state() : m_state{luaL_newstate()} { + lua_sandbox::open_safe_libraries(m_state); + lua_sandbox::open_clock_library(m_state); + } + ~sandboxed_state() { lua_close(m_state); } + sandboxed_state(sandboxed_state const &) = delete; + sandboxed_state &operator=(sandboxed_state const &) = delete; + + lua_State *get() const { return m_state; } + + // runs the code, which returns one value, and gives that value as text ("nil", "true", a number, a string), or + // "error: " and the message + std::string run(std::string_view const Code) const { + auto const top{lua_gettop(m_state)}; + std::string result; + if (false == lua_sandbox::load_text_chunk(m_state, Code, "test") || 0 != lua_pcall(m_state, 0, 1, 0)) { + result = std::string{"error: "} + lua_tostring(m_state, -1); + } else if (lua_isnil(m_state, -1)) { + result = "nil"; + } else if (lua_isboolean(m_state, -1)) { + result = lua_toboolean(m_state, -1) ? "true" : "false"; + } else { + auto const *text{lua_tostring(m_state, -1)}; + result = text != nullptr ? text : "?"; + } + lua_settop(m_state, top); + return result; + } + + private: + lua_State *m_state; +}; + +bool contains(std::string_view const Text, std::string_view const Part) { + return Text.find(Part) != std::string_view::npos; +} + +} // namespace + +TEST_CASE("lua sandbox: no library that reaches files, programs, ffi or the debugger, and nothing that loads code") { + sandboxed_state const lua; + for (auto const *name : {"io", "ffi", "debug", "package", "jit", "require", "module", "dofile", "loadfile", "load", "loadstring", + "newproxy", "string.dump", "os.execute", "os.exit", "os.remove", "os.rename", "os.getenv", "os.tmpname", + "os.setlocale"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return {}", name)) == "nil"); + } + // what the scripts did with them fails, as a Lua error + CHECK(contains(lua.run("return io.open('eu07.ini')"), "attempt to index global 'io' (a nil value)")); + CHECK(contains(lua.run("return os.execute('cmd')"), "attempt to call field 'execute' (a nil value)")); + CHECK(contains(lua.run("return require('ffi')"), "attempt to call global 'require' (a nil value)")); +} + +TEST_CASE("lua sandbox: the libraries a script gets work") { + sandboxed_state const lua; + CHECK(lua.run("return math.floor(2.5) + #string.rep('a', 3) + bit.band(7, 4) + #table.concat({ 'a', 'b' })") == "11"); + CHECK(lua.run("return ('%d-%s'):format(7, 'x')") == "7-x"); + CHECK(lua.run("local ok, error = pcall(function() error('boom') end) return (not ok) and error:find('boom') ~= nil") == "true"); + CHECK(lua.run("local n = 0 for _, v in ipairs({ 1, 2, 3 }) do n = n + v end return n") == "6"); + CHECK(lua.run("return tostring(tonumber('12') + select('#', 1, 2))") == "14"); +} + +TEST_CASE("lua sandbox: os reads the clock, and nothing else") { + sandboxed_state const lua; + CHECK(lua.run("return type(os.time()) == 'number' and os.time() > 0") == "true"); + CHECK(lua.run("return type(os.clock()) == 'number'") == "true"); + CHECK(lua.run("return os.difftime(10, 4)") == "6"); + CHECK(lua.run("return os.time({ year = 2020, month = 1, day = 2, hour = 12 }) > 0") == "true"); + CHECK(lua.run("return os.date('!%Y-%m-%d', 0)") == "1970-01-01"); + CHECK(lua.run("return os.date('!*t', 86400 * 365).year") == "1971"); + CHECK(lua.run("return #os.date()") != "0"); + // a lone % at the end and %% are text + CHECK(lua.run("return os.date('!100%%', 0)") == "100%"); + CHECK(lua.run("return os.date('!100%', 0)") == "100%"); + // conversions the Microsoft C library doesn't know end the program there: refused before + CHECK(contains(lua.run("return os.date('%Q')"), "os.date: unknown conversion '%Q'")); + CHECK(contains(lua.run("return os.date('%#c')"), "os.date: unknown conversion '%#'")); + CHECK(contains(lua.run("return os.date('%Ey')"), "os.date: unknown conversion '%E'")); + // the table holds only the clock + CHECK(lua.run("local n = 0 for _ in pairs(os) do n = n + 1 end return n") == "4"); +} + +TEST_CASE("lua sandbox: all libraries opened over the sandbox are whole again (lua.fulllibraries)") { + sandboxed_state const lua; + luaL_openlibs(lua.get()); + for (auto const *name : {"io.open", "os.execute", "os.getenv", "os.date", "require", "loadstring", "dofile", "string.dump", "debug.traceback"}) { + CAPTURE(name); + CHECK(lua.run(std::format("return type({})", name)) == "function"); + } + CHECK(lua.run("return type(require('ffi'))") == "table"); + CHECK(lua.run("return rawequal(os, package.loaded.os)") == "true"); +} + +TEST_CASE("lua sandbox: precompiled code isn't loaded") { + // real LuaJIT bytecode, from a state with all libraries + auto *full{luaL_newstate()}; + luaL_openlibs(full); + // luaL_dostring is a || of two calls, a bool in C++ + REQUIRE_FALSE(luaL_dostring(full, "return string.dump(function() return 42 end)")); + std::size_t length{0}; + auto const *bytes{lua_tolstring(full, -1, &length)}; + std::string const bytecode{bytes, length}; + lua_close(full); + REQUIRE(false == bytecode.empty()); + CHECK(bytecode.front() == '\x1b'); + + sandboxed_state const lua; + auto const top{lua_gettop(lua.get())}; + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), bytecode, "compiled.lua")); + CHECK(contains(lua_tostring(lua.get(), -1), "compiled.lua: precompiled scripts aren't loaded")); + lua_settop(lua.get(), top); + // nor in a text that only starts with the marker + CHECK_FALSE(lua_sandbox::load_text_chunk(lua.get(), std::string_view{"\x1bLJ\x02 return 1"}, "fake.lua")); + lua_settop(lua.get(), top); +} + +TEST_CASE("lua sandbox: a scenery reads its scripts only from its own folder") { + test::scratch_folder const root{"lua_sandbox_paths"}; + root.write("outside.lua", "return 1"); + root.write("scenery/test.lua", "return 2"); + root.write("scenery/scripts/module.lua", "return 3"); + root.write("scenery/folder.lua/inner.lua", "return 4"); + auto const folder{root.path("scenery") + "/"}; + + CHECK(lua_sandbox::read_script_file(folder, "test.lua") == std::optional{"return 2"}); + CHECK(lua_sandbox::read_script_file(folder, "scripts/module.lua") == std::optional{"return 3"}); + // '\' separates the folders on Linux too, as in the rest of the scenery's paths + CHECK(lua_sandbox::with_forward_slashes("a\\b/c\\d.lua") == "a/b/c/d.lua"); + CHECK(lua_sandbox::read_script_file(folder, "scripts\\module.lua") == std::optional{"return 3"}); + for (auto const &path : {std::string{"../outside.lua"}, std::string{"scripts/../../outside.lua"}, std::string{"..\\outside.lua"}, + std::string{"scripts\\..\\..\\outside.lua"}, std::string{"scripts/..\\../outside.lua"}, + root.path("outside.lua"), std::string{"/outside.lua"}, std::string{"\\outside.lua"}, std::string{"C:outside.lua"}, + std::string{"missing.lua"}, std::string{"folder.lua"}, std::string{"scripts"}, std::string{}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_script_file(folder, path).has_value()); + } +} + +TEST_CASE("lua sandbox: a script larger than the limit isn't read") { + test::scratch_folder const root{"lua_sandbox_size"}; + root.write("scenery/limit.lua", std::string(static_cast(lua_sandbox::max_script_file), ' ')); + root.write("scenery/over.lua", std::string(static_cast(lua_sandbox::max_script_file) + 1, ' ')); + auto const folder{root.path("scenery") + "/"}; + CHECK(lua_sandbox::read_script_file(folder, "limit.lua").has_value()); + CHECK_FALSE(lua_sandbox::read_script_file(folder, "over.lua").has_value()); +} + +TEST_CASE("lua sandbox: a scenery script runs in protected mode, and its errors name the file") { + test::scratch_folder const root{"lua_sandbox_run"}; + root.write("scenery/good.lua", "ran = (ran or 0) + 1"); + root.write("scenery/fails.lua", "ran = 10\nlocal x = nil\nx.field = 1\nran = 20"); + root.write("scenery/files.lua", "local f = io.open('eu07.ini')"); + root.write("scenery/system.lua", "os.execute('cmd /c echo pwned')"); + root.write("scenery/syntax.lua", "this is not lua"); + root.write("scenery/compiled.lua", std::string_view{"\x1bLJ\x02 bytes"}); + auto const folder{root.path("scenery") + "/"}; + + sandboxed_state const lua; + auto *L{lua.get()}; + auto const top{lua_gettop(L)}; + + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "1"); + + auto const fails{lua_sandbox::run_script_file(L, folder, "fails.lua")}; + REQUIRE(fails.has_value()); + CHECK(contains(*fails, "fails.lua:3:")); + // it stopped at the error + CHECK(lua.run("return ran") == "10"); + + auto const files{lua_sandbox::run_script_file(L, folder, "files.lua")}; + REQUIRE(files.has_value()); + CHECK(contains(*files, "files.lua:1: attempt to index global 'io' (a nil value)")); + + auto const system{lua_sandbox::run_script_file(L, folder, "system.lua")}; + REQUIRE(system.has_value()); + CHECK(contains(*system, "system.lua:1: attempt to call field 'execute' (a nil value)")); + + auto const syntax{lua_sandbox::run_script_file(L, folder, "syntax.lua")}; + REQUIRE(syntax.has_value()); + CHECK(contains(*syntax, "syntax.lua:1:")); + + auto const compiled{lua_sandbox::run_script_file(L, folder, "compiled.lua")}; + REQUIRE(compiled.has_value()); + CHECK(contains(*compiled, "compiled.lua: precompiled scripts aren't loaded")); + + auto const outside{lua_sandbox::run_script_file(L, folder, "../good.lua")}; + REQUIRE(outside.has_value()); + CHECK(contains(*outside, "outside the folder")); + + // nothing left on the stack, and the state still works + CHECK(lua_gettop(L) == top); + CHECK_FALSE(lua_sandbox::run_script_file(L, folder, "good.lua").has_value()); + CHECK(lua.run("return ran") == "11"); +} + +TEST_CASE("lua sandbox: eu07.read_file reads a file of the scenery folder, and nothing outside it") { + test::scratch_folder const root{"lua_sandbox_read"}; + root.write("outside.txt", "secret"); + root.write("scenery/data.txt", "line 1\nline 2"); + root.write("scenery/sub/more.txt", "more"); + root.write("scenery/folder/inner.txt", "inner"); + auto const folder{std::filesystem::path{root.path("scenery")}}; + + CHECK(lua_sandbox::read_file(folder, "data.txt", 100) == std::optional{"line 1\nline 2"}); + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 100) == std::optional{"more"}); + CHECK(lua_sandbox::read_file(folder, "sub\\more.txt", 100) == std::optional{"more"}); + // the limit is the caller's + CHECK(lua_sandbox::read_file(folder, "sub/more.txt", 4).has_value()); + CHECK_FALSE(lua_sandbox::read_file(folder, "sub/more.txt", 3).has_value()); + for (auto const &path : {std::string{"../outside.txt"}, std::string{"sub/../../outside.txt"}, std::string{"..\\outside.txt"}, + std::string{"sub\\..\\..\\outside.txt"}, root.path("outside.txt"), std::string{"/outside.txt"}, + std::string{"\\outside.txt"}, std::string{"C:outside.txt"}, std::string{"missing.txt"}, + std::string{"folder"}, std::string{}, std::string{"data.txt\0x", 10}}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::read_file(folder, path, 100).has_value()); + } +} + +TEST_CASE("lua sandbox: the paths a script may write to") { + for (auto const *path : {"state.txt", "saves/state.txt", "saves\\state.txt", "a/b/c/d/e/f/g/h/file.txt", "con_log.txt", "comx.txt", + "com10.txt", "nul_state", ".hidden", "stan poci\xc4\x85gu.txt", "a..b"}) { + CAPTURE(path); + CHECK(lua_sandbox::is_safe_write_path(path)); + } + for (auto const &path : {std::string{}, std::string{".."}, std::string{"../x.txt"}, std::string{"a/../../x.txt"}, std::string{"..\\x.txt"}, + std::string{"/x.txt"}, std::string{"\\x.txt"}, std::string{"C:x.txt"}, std::string{"C:\\x.txt"}, + std::string{"x.txt:stream"}, std::string{"a//b.txt"}, std::string{"a/"}, std::string{"./x.txt"}, + std::string{"a/./x.txt"}, std::string{"con"}, std::string{"CON.txt"}, std::string{"saves/nul.dat"}, + std::string{"Com1"}, std::string{"lpt9.log"}, std::string{"aux"}, std::string{"prn.x.y"}, + std::string{"conin$"}, std::string{"CONOUT$.txt"}, std::string{"con .txt"}, std::string{"ab"}, std::string{"a\"b"}, std::string{"a|b"}, std::string{"a?b"}, std::string{"a*b"}, + std::string{"x."}, std::string{"x "}, std::string{"dir./x"}, std::string{"a\tb"}, std::string{"a\nb"}, + std::string{"a\0b", 3}, std::string{"a/b/c/d/e/f/g/h/i/file.txt"}, + std::string(lua_sandbox::max_data_path + 1, 'x')}) { + CAPTURE(path); + CHECK_FALSE(lua_sandbox::is_safe_write_path(path)); + } + CHECK(lua_sandbox::is_safe_write_path(std::string(lua_sandbox::max_data_path, 'x'))); +} + +TEST_CASE("lua sandbox: a script writes into its data folder only, and reads back what it wrote") { + test::scratch_folder const root{"lua_sandbox_write"}; + root.write("outside.txt", "kept"); + auto const data{root.root() / "data" / "td"}; + + // the folder is made with the first file + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=1").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=1"}); + // replaced, not appended + CHECK_FALSE(lua_sandbox::write_data_file(data, "state.txt", "runs=2").has_value()); + CHECK(lua_sandbox::read_file(data, "state.txt", lua_sandbox::max_data_file) == std::optional{"runs=2"}); + // any bytes, and the folders of the path + std::string const bytes{"a\0b\r\n\xff", 6}; + CHECK_FALSE(lua_sandbox::write_data_file(data, "saves\\day 1/bin.dat", bytes).has_value()); + CHECK(lua_sandbox::read_file(data, "saves/day 1/bin.dat", lua_sandbox::max_data_file) == std::optional{bytes}); + CHECK_FALSE(lua_sandbox::write_data_file(data, "empty.txt", "").has_value()); + CHECK(lua_sandbox::read_file(data, "empty.txt", lua_sandbox::max_data_file) == std::optional{""}); + + // nothing outside the folder + for (auto const *path : {"../outside.txt", "../../outside.txt", "..\\outside.txt", "saves/../../outside.txt", "nul", "con.txt", "x:y"}) { + CAPTURE(path); + auto const error{lua_sandbox::write_data_file(data, path, "overwritten")}; + REQUIRE(error.has_value()); + CHECK(contains(*error, "not a path to write to")); + } + CHECK(lua_sandbox::write_data_file(data, root.path("outside.txt"), "overwritten").has_value()); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"kept"}); + // a folder isn't replaced by a file + auto const folder{lua_sandbox::write_data_file(data, "saves", "x")}; + REQUIRE(folder.has_value()); + CHECK(contains(*folder, "not a file")); + CHECK(std::filesystem::is_directory(data / "saves")); + // no folder (the game knows no folder of the player), nothing written + CHECK(lua_sandbox::write_data_file(std::filesystem::path{}, "state.txt", "x").has_value()); +} + +TEST_CASE("lua sandbox: the limits of a data folder") { + test::scratch_folder const root{"lua_sandbox_limits"}; + auto const data{root.root() / "data"}; + std::string const full(static_cast(lua_sandbox::max_data_file), 'x'); + + SUBCASE("a file") { + CHECK_FALSE(lua_sandbox::write_data_file(data, "full.txt", full).has_value()); + CHECK(lua_sandbox::read_file(data, "full.txt", lua_sandbox::max_data_file).has_value()); + auto const over{lua_sandbox::write_data_file(data, "full.txt", full + "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "larger than")); + // the file stays as it was + CHECK(std::filesystem::file_size(data / "full.txt") == lua_sandbox::max_data_file); + } + SUBCASE("the bytes of the folder") { + auto const files{static_cast(lua_sandbox::max_data_folder / lua_sandbox::max_data_file)}; + for (int idx = 0; idx < files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("part{}.dat", idx), full).has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.dat", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "more than")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.dat")); + // a file replaced counts with its new size: as large again fits, and a smaller one makes room + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", full).has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "part0.dat", "small").has_value()); + CHECK_FALSE(lua_sandbox::write_data_file(data, "one_more.dat", "x").has_value()); + } + SUBCASE("the files of the folder") { + for (std::size_t idx = 0; idx < lua_sandbox::max_data_files; ++idx) { + REQUIRE_FALSE(lua_sandbox::write_data_file(data, std::format("sub{}/file{}.txt", idx % 4, idx), "x").has_value()); + } + auto const over{lua_sandbox::write_data_file(data, "one_more.txt", "x")}; + REQUIRE(over.has_value()); + CHECK(contains(*over, "files already")); + CHECK_FALSE(std::filesystem::exists(data / "one_more.txt")); + // one that is there is still replaced + CHECK_FALSE(lua_sandbox::write_data_file(data, "sub0/file0.txt", "y").has_value()); + } +} + +TEST_CASE("lua sandbox: a link in the data folder doesn't lead a write out of it") { + test::scratch_folder const root{"lua_sandbox_link"}; + root.write("outside/kept.txt", "kept"); + auto const data{root.root() / "data"}; + std::filesystem::create_directories(data); + std::error_code error; + std::filesystem::create_directory_symlink(root.root() / "outside", data / "link", error); + if (error) { + // Windows makes links only for an administrator or in developer mode + MESSAGE("no folder link made (" << error.message() << "), not tested"); + return; + } + auto const written{lua_sandbox::write_data_file(data, "link/kept.txt", "overwritten")}; + REQUIRE(written.has_value()); + CHECK(contains(*written, "outside the data folder")); + CHECK(lua_sandbox::read_file(root.root(), "outside/kept.txt", 100) == std::optional{"kept"}); +} + +TEST_CASE("lua sandbox: the data folder of a scenery") { + std::filesystem::path const root{"user/scenery_data"}; + CHECK(lua_sandbox::scenery_data_folder(root, "td.scn") == root / "td"); + CHECK(lua_sandbox::scenery_data_folder(root, "Td.SCN") == root / "Td"); + CHECK(lua_sandbox::scenery_data_folder(root, "lines\\l107.scn") == root / "lines/l107"); + CHECK(lua_sandbox::scenery_data_folder(root, "test.scm") == root / "test.scm"); + for (auto const *scenery : {"", ".scn", "../td.scn", "/td.scn", "C:td.scn", "con.scn"}) { + CAPTURE(scenery); + CHECK(lua_sandbox::scenery_data_folder(root, scenery).empty()); + } + CHECK(lua_sandbox::scenery_data_folder(std::filesystem::path{}, "td.scn").empty()); +} + +TEST_CASE("lua sandbox: the file functions of a scenery script") { + test::scratch_folder const root{"lua_sandbox_api"}; + root.write("outside.txt", "secret"); + root.write("scenery/settings.txt", "speed=40"); + lua_sandbox::file_folders folders{root.path("scenery") + "/", root.root() / "data" / "td"}; + + sandboxed_state const lua; + // next to eu07.events, as the scenery state has it + REQUIRE_FALSE(luaL_dostring(lua.get(), "eu07 = { events = { marker = 1 } }")); + lua_sandbox::open_file_library(lua.get(), &folders); + auto const top{lua_gettop(lua.get())}; + + CHECK(lua.run("return eu07.events.marker") == "1"); + CHECK(lua.run("return eu07.read_file('settings.txt')") == "speed=40"); + CHECK(lua.run("return eu07.read_file('../outside.txt')") == "nil"); + CHECK(lua.run("return eu07.read_file('missing.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.write_file('state.txt', 'runs=' .. 1)") == "true"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "runs=1"); + // the scenery folder and the data folder are apart + CHECK(lua.run("return eu07.read_file('state.txt')") == "nil"); + CHECK(lua.run("return eu07.read_data_file('../../scenery/settings.txt')") == "nil"); + // a number is written as its text + CHECK(lua.run("return eu07.write_file('number.txt', 42)") == "true"); + CHECK(lua.run("return eu07.read_data_file('number.txt')") == "42"); + // a refused write gives nil and the reason + CHECK(lua.run("local ok, reason = eu07.write_file('../outside.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil ../outside.txt: not a path to write to (a relative path of portable names, at most 200 bytes and 8 folders deep, without '..')"); + CHECK(lua.run("local ok, reason = eu07.write_file('big.txt', string.rep('x', 1024 * 1024 + 1)) return reason") == + "big.txt: larger than 1048576 bytes"); + CHECK(lua_sandbox::read_file(root.root(), "outside.txt", 100) == std::optional{"secret"}); + // the arguments are checked + CHECK(contains(lua.run("return eu07.write_file('x.txt')"), "bad argument #2")); + CHECK(contains(lua.run("return eu07.read_file()"), "bad argument #1")); + CHECK(contains(lua.run("return eu07.write_file({}, 'x')"), "bad argument #1")); + + // the folders are read on every call: without a data folder nothing is written or read there + folders.data.clear(); + CHECK(lua.run("local ok, reason = eu07.write_file('state.txt', 'x') return tostring(ok) .. ' ' .. reason") == + "nil state.txt: no folder to write to (the game knows no folder of the player)"); + CHECK(lua.run("return eu07.read_data_file('state.txt')") == "nil"); + CHECK(lua_gettop(lua.get()) == top); +} + +TEST_CASE("lua sandbox: the file functions make eu07 when there is none") { + lua_sandbox::file_folders const folders; + sandboxed_state const lua; + lua_sandbox::open_file_library(lua.get(), &folders); + CHECK(lua.run("return type(eu07.read_file) .. type(eu07.write_file) .. type(eu07.read_data_file)") == "functionfunctionfunction"); + CHECK(lua.run("return eu07.read_file('x.txt')") == "nil"); +} + +TEST_CASE("lua sandbox: no userdata of the script's own, whose __gc would run without the hooks") { + sandboxed_state const lua; + CHECK(lua.run("return newproxy") == "nil"); + // a table's __gc isn't called (Lua 5.1, LuaJIT): no other way to a finalizer of the script's own + CHECK(lua.run("collected = false setmetatable({}, { __gc = function() collected = true end }) collectgarbage() collectgarbage() return collected") == + "false"); +} + +namespace { + +// two objects of the simulation, of which a script holds handles +int memcell_object{1}; +int track_object{2}; + +// eu07.test_memcell(handle): the number of the memcell object, nil for none; eu07.test_track(handle) likewise +int test_memcell(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::memcell)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +int test_track(lua_State *L) { + auto const *object{lua_sandbox::check_handle(L, 1, lua_sandbox::handle_kind::track)}; + if (object == nullptr) { + lua_pushnil(L); + } else { + lua_pushnumber(L, *object); + } + return 1; +} + +// a state with the handles, the functions above, and the globals memcell, track (handles), memcell2 (the memcell's +// handle pushed again) and light (a light userdata, which a script can't make, as the game gave them before) +class handle_state : public sandboxed_state { + public: + handle_state() { + auto *L{get()}; + lua_sandbox::open_handles(L); + lua_register(L, "test_memcell", test_memcell); + lua_register(L, "test_track", test_track); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(L, "memcell2"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &track_object); + lua_setglobal(L, "track"); + // the address of the memcell as a handle of another kind: told apart all the same + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::track, &memcell_object); + lua_setglobal(L, "memcell_as_track"); + lua_pushlightuserdata(L, &memcell_object); + lua_setglobal(L, "light"); + lua_sandbox::push_handle(L, lua_sandbox::handle_kind::event, nullptr); + lua_setglobal(L, "none"); + } +}; + +} // namespace + +TEST_CASE("lua sandbox: a handle of the scenery api reaches the object of its kind") { + handle_state const lua; + CHECK(lua.run("return test_memcell(memcell)") == "1"); + CHECK(lua.run("return test_track(track)") == "2"); + CHECK(lua.run("return type(memcell)") == "userdata"); + // what the find functions give for a missing object, and what the functions take as no object + CHECK(lua.run("return none") == "nil"); + CHECK(lua.run("return test_memcell(nil)") == "nil"); + CHECK(lua.run("return test_memcell()") == "nil"); + // one object, one handle: equal, and the same key of a table + CHECK(lua.run("return rawequal(memcell, memcell2)") == "true"); + CHECK(lua.run("local t = { [memcell] = 'cell' } return t[memcell2]") == "cell"); + CHECK(lua.run("return rawequal(memcell, memcell_as_track)") == "false"); + // the handle of a dropped handle is made again + REQUIRE_FALSE(luaL_dostring(lua.get(), "memcell = nil memcell2 = nil collectgarbage() collectgarbage()")); + lua_sandbox::push_handle(lua.get(), lua_sandbox::handle_kind::memcell, &memcell_object); + lua_setglobal(lua.get(), "memcell"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a handle of another kind, or anything else, is a Lua error and not an object") { + handle_state const lua; + // a track where a memcell goes (memcell_update(track_find(...)) once wrote into a track as a memcell). not a tail + // call, which LuaJIT gives no function name in the message + CHECK(contains(lua.run("local r = test_memcell(track) return r"), "bad argument #1 to 'test_memcell' (eu07.memcell expected, got userdata)")); + CHECK(contains(lua.run("local r = test_track(memcell) return r"), "bad argument #1 to 'test_track' (eu07.track expected, got userdata)")); + CHECK(contains(lua.run("return test_memcell(memcell_as_track)"), "eu07.memcell expected")); + CHECK(contains(lua.run("return test_memcell(light)"), "eu07.memcell expected, got userdata")); + for (auto const *value : {"1", "'memcell'", "{}", "true", "false", "print", "coroutine.create(function() end)"}) { + CAPTURE(value); + CHECK(contains(lua.run(std::format("return test_memcell({})", value)), "eu07.memcell expected")); + } + // the error is the script's: caught by pcall, and the state goes on + CHECK(lua.run("return (pcall(test_memcell, track))") == "false"); + CHECK(lua.run("return test_memcell(memcell)") == "1"); +} + +TEST_CASE("lua sandbox: a script can't reach the metatable of a handle") { + handle_state const lua; + CHECK(lua.run("return getmetatable(memcell)") == "false"); + CHECK(contains(lua.run("local r = setmetatable(memcell, {}) return r"), "bad argument #1 to 'setmetatable' (table expected, got userdata)")); + // no field to read or write + CHECK(contains(lua.run("return memcell.x"), "attempt to index")); + CHECK(contains(lua.run("memcell.x = 1"), "attempt to index")); +} + +#endif diff --git a/tests/unit/test_mains_before_pantographs.cpp b/tests/unit/test_mains_before_pantographs.cpp index e9c70bb4c..99e79ec65 100644 --- a/tests/unit/test_mains_before_pantographs.cpp +++ b/tests/unit/test_mains_before_pantographs.cpp @@ -26,7 +26,7 @@ test::definition ep05(bool const Mainsfirst) { // battery and cab on, direction set and the relays reset, the pantographs on the main reservoir's air void prepare(test::vehicle &Loco) { Loco.hold_main_reservoir(6.0); - Loco->bPantKurek3 = true; + Loco->pantographAir.ConnectToMainReservoir(true); Loco->BatterySwitch(true); Loco->CabActivisation(); for (int i = 0; i < 3 && Loco->DirActive <= 0; ++i) { @@ -39,7 +39,7 @@ void prepare(test::vehicle &Loco) { void raise_pantograph(test::vehicle &Loco, test::track const &Track = line) { Loco->OperatePantographsValve(operation_t::enable); - Loco->OperatePantographValve(end::rear, operation_t::enable); + Loco->OperatePantographValve(VehicleEnd::rear, operation_t::enable); Loco.run(5.0, Track); } @@ -57,9 +57,9 @@ void switch_auxiliaries_on(test::vehicle &Loco) { // what the main reservoir gains over the given time [bar]; the compressor of the locomotive adds some 0.07 bar a second double reservoir_gain(test::vehicle &Loco, double const Seconds, test::track const &Track) { - auto const before{Loco->CompressedVolume}; + auto const before{Loco->air.CompressedVolume()}; Loco.run(Seconds, Track); - return (Loco->CompressedVolume - before) / Loco->VeselVolume; + return (Loco->air.CompressedVolume() - before) / Loco->air.config.mainReservoirVolume; } // the locomotive started up the way the driver does it, the brakes released, then the master controller taken to the @@ -69,7 +69,7 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const test::release_brakes(Driven.cab); test::drive(Driven, line, 20.0); // until the pressure switch lets the line contactors close - for (int i = 0; i < 120 && Loco->ControlPressureSwitch; ++i) { + for (int i = 0; i < 120 && Loco->protection.PressureSwitchTripped(); ++i) { test::drive(Driven, line, 1.0); } for (int i = 0; i < Position; ++i) { @@ -77,10 +77,10 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const test::drive(Driven, line, 1.0); } test::drive(Driven, line, 2.0); - REQUIRE(Loco->MainCtrlPos == Position); + REQUIRE(Loco->MainCtrlPos() == Position); REQUIRE(Loco->MainCtrlActualPos == Position); REQUIRE(Loco->RList[Position].R > 0.0); // a resistance position - REQUIRE(Loco->StLinFlag); + REQUIRE(Loco->lineContactors.IsClosed()); REQUIRE(std::abs(Loco->Im) > 10.0); } @@ -88,55 +88,55 @@ void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const TEST_CASE("mains before pantographs: without the flag the line breaker needs the pantographs' voltage, as before") { test::vehicle loco{ep05(false), 0.0, "test", 1}; - REQUIRE_FALSE(loco->PantographsRequireMains); + REQUIRE_FALSE(loco->lineBreaker.config.pantographsRequireIt); prepare(loco); close_line_breaker(loco); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.IsClosed()); raise_pantograph(loco); - CHECK(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); close_line_breaker(loco); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.IsClosed()); // the pantographs stay up with the line breaker open, and the line breaker opens without voltage loco->MainSwitch(false); loco.run(2.0, line); - CHECK(loco->Pantographs[end::rear].is_active); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); close_line_breaker(loco); - REQUIRE(loco->Mains); - loco->OperatePantographValve(end::rear, operation_t::disable); + REQUIRE(loco->lineBreaker.IsClosed()); + loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(2.0, line); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.IsClosed()); } TEST_CASE("mains before pantographs: with the flag the pantographs rise only through the closed line breaker") { test::vehicle loco{ep05(true), 0.0, "test", 1}; - REQUIRE(loco->PantographsRequireMains); + REQUIRE(loco->lineBreaker.config.pantographsRequireIt); prepare(loco); // the pantographs stay down while the line breaker is open raise_pantograph(loco); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == 0.0); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == 0.0); // the line breaker closes without voltage, and the pantograph rises through it close_line_breaker(loco); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.IsClosed()); raise_pantograph(loco); - CHECK(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); - CHECK(loco->Mains); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); + CHECK(loco->lineBreaker.IsClosed()); // opening the line breaker drops the pantograph, which stays down until the line breaker closes again loco->MainSwitch(false); loco.run(2.0, line); - CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); - CHECK(loco->PantographVoltage == 0.0); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == 0.0); // a pantograph lowered under the closed line breaker leaves it closed close_line_breaker(loco); raise_pantograph(loco); - REQUIRE(loco->Pantographs[end::rear].is_active); - loco->OperatePantographValve(end::rear, operation_t::disable); + REQUIRE(loco->pantographs[VehicleEnd::rear].is_active); + loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); - CHECK_FALSE(loco->Pantographs[end::rear].is_active); - CHECK(loco->Mains); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->lineBreaker.IsClosed()); } TEST_CASE("mains before pantographs: with the flag the line breaker still needs the battery") { @@ -144,7 +144,7 @@ TEST_CASE("mains before pantographs: with the flag the line breaker still needs loco.hold_main_reservoir(6.0); loco.run(2.0, line); close_line_breaker(loco); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.IsClosed()); } TEST_CASE("mains before pantographs: with the flag the driver's start-up gets the locomotive ready") { @@ -152,8 +152,8 @@ TEST_CASE("mains before pantographs: with the flag the driver's start-up gets th test::vehicle loco{ep05(true), 0.0, "test", 1}; auto driven{test::driving(loco)}; REQUIRE(test::start_up(driven, line)); - CHECK(loco->Mains); - CHECK(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(test::is_ready(driven)); } @@ -164,93 +164,93 @@ TEST_CASE("mains before pantographs: with the flag the converter and the compres test::vehicle loco{ep05(true), 0.0, "test", 1}; prepare(loco); close_line_breaker(loco); - REQUIRE(loco->Mains); - REQUIRE(loco->PantographVoltage == 0.0); + REQUIRE(loco->lineBreaker.IsClosed()); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == 0.0); switch_auxiliaries_on(loco); - REQUIRE(loco->ConverterAllow); - REQUIRE(loco->CompressorAllow); + REQUIRE(loco->converter.IsAllowed()); + REQUIRE(loco->air.compressor.IsAllowed()); // the line breaker closed on the battery, the pantographs down: there's nothing to run them on CHECK(reservoir_gain(loco, 20.0, line) < 0.01); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->ConverterFlag); - CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->converter.IsRunning()); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); + CHECK_FALSE(loco->air.compressor.IsRunning()); // the pantograph up: the converter starts, and the compressor on its 110 V raise_pantograph(loco); - REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); - CHECK(loco->ConverterFlag); - CHECK(loco->Power110vIsAvailable); - CHECK(loco->CompressorFlag); + CHECK(loco->converter.IsRunning()); + CHECK(loco->lowVoltage.Is110vAvailable()); + CHECK(loco->air.compressor.IsRunning()); // the voltage gone they stop, behind the line breaker which stays closed auto const *track{&line}; SUBCASE("the pantograph lowered again") { - loco->OperatePantographValve(end::rear, operation_t::disable); + loco->OperatePantographValve(VehicleEnd::rear, operation_t::disable); loco.run(5.0, line); - REQUIRE_FALSE(loco->Pantographs[end::rear].is_active); + REQUIRE_FALSE(loco->pantographs[VehicleEnd::rear].is_active); } SUBCASE("no voltage in the catenary") { track = &dead; loco.run(5.0, dead); - REQUIRE(loco->Pantographs[end::rear].is_active); + REQUIRE(loco->pantographs[VehicleEnd::rear].is_active); } SUBCASE("the voltage in the catenary below the one the locomotive works on") { track = &weak; loco.run(5.0, weak); - REQUIRE(loco->PantographVoltage == doctest::Approx(weak.voltage)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(weak.voltage)); } CHECK(reservoir_gain(loco, 10.0, *track) < 0.01); - CHECK(loco->Mains); + CHECK(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->ConverterFlag); - CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->converter.IsRunning()); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); + CHECK_FALSE(loco->air.compressor.IsRunning()); } TEST_CASE("mains before pantographs: with the flag whatever else the main circuit feeds waits for the traction voltage too") { // a compressor on the main circuit rather than the converter's 110 V, the motor blowers, the blowers of the starting // resistors, the heating test::vehicle loco{ep05(true).set("Brake", "CompressorPower", "Main"), 0.0, "test", 1}; - REQUIRE(loco->CompressorPower == 0); + REQUIRE(loco->air.compressor.config.supply == physics::CompressorSupply::mainCircuit); REQUIRE(loco->HeatingPowerSource.SourceType == TPowerSource::Main); prepare(loco); close_line_breaker(loco); - REQUIRE(loco->Mains); + REQUIRE(loco->lineBreaker.IsClosed()); loco->CompressorSwitch(true); - loco->MotorBlowersSwitch(true, end::front); - loco->RVentForceOn = true; + loco->MotorBlowersSwitch(true, VehicleEnd::front); + loco->SetRVentForceOn(true); loco->HeatingSwitch(true); loco.hold_main_reservoir(-1.0); CHECK(reservoir_gain(loco, 10.0, line) < 0.01); - CHECK_FALSE(loco->CompressorFlag); - CHECK_FALSE(loco->MotorBlowers[end::front].is_active); + CHECK_FALSE(loco->air.compressor.IsRunning()); + CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); - CHECK_FALSE(loco->Heating); + CHECK_FALSE(loco->trainHeating.IsOn()); SUBCASE("nor do they run on a voltage below the one the locomotive works on") { raise_pantograph(loco, weak); - REQUIRE(loco->PantographVoltage == doctest::Approx(weak.voltage)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(weak.voltage)); CHECK(reservoir_gain(loco, 10.0, weak) < 0.01); - CHECK(loco->Mains); - CHECK_FALSE(loco->CompressorFlag); - CHECK_FALSE(loco->MotorBlowers[end::front].is_active); + CHECK(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->air.compressor.IsRunning()); + CHECK_FALSE(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot == 0.0); - CHECK_FALSE(loco->Heating); + CHECK_FALSE(loco->trainHeating.IsOn()); } SUBCASE("with the voltage they do") { raise_pantograph(loco); - REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); - CHECK(loco->CompressorFlag); - CHECK(loco->MotorBlowers[end::front].is_active); + CHECK(loco->air.compressor.IsRunning()); + CHECK(loco->MotorBlowers[VehicleEnd::front].is_active); CHECK(loco->RventRot > 0.0); - CHECK(loco->Heating); + CHECK(loco->trainHeating.IsOn()); } } @@ -259,20 +259,20 @@ TEST_CASE("mains before pantographs: without the flag the converter and the comp prepare(loco); raise_pantograph(loco); close_line_breaker(loco); - REQUIRE(loco->Mains); + REQUIRE(loco->lineBreaker.IsClosed()); switch_auxiliaries_on(loco); CHECK(reservoir_gain(loco, 10.0, line) > 0.1); CHECK(loco->MainCircuitPowered()); - CHECK(loco->ConverterFlag); - CHECK(loco->Power110vIsAvailable); - CHECK(loco->CompressorFlag); + CHECK(loco->converter.IsRunning()); + CHECK(loco->lowVoltage.Is110vAvailable()); + CHECK(loco->air.compressor.IsRunning()); // too low a voltage opens the line breaker, and they stop with it loco.run(5.0, weak); - CHECK_FALSE(loco->Mains); + CHECK_FALSE(loco->lineBreaker.IsClosed()); CHECK_FALSE(loco->MainCircuitPowered()); - CHECK_FALSE(loco->ConverterFlag); - CHECK_FALSE(loco->Power110vIsAvailable); - CHECK_FALSE(loco->CompressorFlag); + CHECK_FALSE(loco->converter.IsRunning()); + CHECK_FALSE(loco->lowVoltage.Is110vAvailable()); + CHECK_FALSE(loco->air.compressor.IsRunning()); } // the undervoltage trip was also what cut the traction motors off when the voltage went: the line contactors open @@ -287,48 +287,48 @@ TEST_CASE("mains before pantographs: with the flag the line contactors open when // the voltage goes: the line breaker holds, the pantograph stays up, the motors are cut off test::drive(driven, dead, 3.0); - CHECK(loco->Mains); - CHECK(loco->Pantographs[end::rear].is_active); - CHECK_FALSE(loco->NoVoltRelay); - CHECK_FALSE(loco->StLinFlag); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK_FALSE(loco->protection.UndervoltageHolds()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); // the voltage back, with the master controller still where it was: the camshaft went down to zero and stays // there, the motors still cut off; the converter is back on its own test::drive(driven, line, 10.0); - REQUIRE(loco->PantographVoltage == doctest::Approx(test::catenary_3kv)); - REQUIRE(loco->MainCtrlPos == 5); - CHECK(loco->Mains); - CHECK(loco->ConverterFlag); - CHECK_FALSE(loco->NoVoltRelay); - CHECK_FALSE(loco->StLinFlag); + REQUIRE(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->MainCtrlPos() == 5); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->converter.IsRunning()); + CHECK_FALSE(loco->protection.UndervoltageHolds()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 0); CHECK(loco->Im == 0.0); SUBCASE("the master controller back at zero: the start goes as usual") { - while (loco->MainCtrlPos > 0 && loco->DecMainCtrl(1)) { + while (loco->MainCtrlPos() > 0 && loco->DecMainCtrl(1)) { // down to zero } - REQUIRE(loco->MainCtrlPos == 0); + REQUIRE(loco->MainCtrlPos() == 0); test::drive(driven, line, 1.0); - CHECK(loco->NoVoltRelay); - CHECK_FALSE(loco->StLinFlag); + CHECK(loco->protection.UndervoltageHolds()); + CHECK_FALSE(loco->lineContactors.IsClosed()); for (int i = 0; i < 3; ++i) { loco->IncMainCtrl(1); test::drive(driven, line, 2.0); } - CHECK(loco->StLinFlag); + CHECK(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 3); CHECK(std::abs(loco->Im) > 10.0); } SUBCASE("the master controller back at the first position, where the line contactors close on a start") { - while (loco->MainCtrlPos > 1 && loco->DecMainCtrl(1)) { + while (loco->MainCtrlPos() > 1 && loco->DecMainCtrl(1)) { // down to the first position } - REQUIRE(loco->MainCtrlPos == 1); + REQUIRE(loco->MainCtrlPos() == 1); test::drive(driven, line, 2.0); - CHECK(loco->NoVoltRelay); - CHECK(loco->StLinFlag); + CHECK(loco->protection.UndervoltageHolds()); + CHECK(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 1); } } @@ -339,13 +339,13 @@ TEST_CASE("mains before pantographs: without the flag the line breaker opens whe get_under_power(loco, driven, 5); test::drive(driven, dead, 3.0); - CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->Im == 0.0); // and stays open with the voltage back test::drive(driven, line, 10.0); - CHECK_FALSE(loco->Mains); - CHECK_FALSE(loco->StLinFlag); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->lineContactors.IsClosed()); CHECK(loco->MainCtrlActualPos == 0); CHECK(loco->Im == 0.0); } diff --git a/tests/unit/test_motor_param_bounds.cpp b/tests/unit/test_motor_param_bounds.cpp new file mode 100644 index 000000000..8226fad46 --- /dev/null +++ b/tests/unit/test_motor_param_bounds.cpp @@ -0,0 +1,57 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include + +#include + +using test::definition; +using test::vehicle; + +// the field shunting step a position of the master controller selects (RList, its sixth column ScndAct) indexes the +// motor parameter table, MotorParam, which has MotorParametersArraySize + 1 entries. The loader takes ScndAct from the +// .fiz as it is, so the readers of the table (physics::Vehicle::Momentum(), MomentumF(), TController::ESMVelocity()) +// go through motor_param(), which keeps the index inside the table + +namespace { + +// the RList rows of the EP09 with the ScndAct of the first position replaced +nlohmann::ordered_json ep09_rlist_with_scndact(std::string const &Scndact) { + std::ifstream file{std::string{EU07_UNIT_TESTS_DATA} + "/fiz/ep09_v2/104e.json"}; + REQUIRE(file.good()); + // '=' rather than braces: GCC takes a json in braces for an initializer list, an array holding it + auto const ep09 = nlohmann::ordered_json::parse(file); + auto rows = ep09.at("RList").at("rows"); + REQUIRE(rows.size() > 1); + rows[1][5] = Scndact; + return rows; +} + +} // namespace + +TEST_CASE("motor parameters: the ScndAct of an RList row is read from the .fiz as it is") { + vehicle ep09{definition::fiz("ep09_v2/104e")}; + // the first position of the EP09 runs on field shunting step 2 + CHECK(ep09->RList[1].ScndAct == 2); + CHECK(&ep09->motor_param(ep09->RList[1].ScndAct) == &ep09->MotorParam[2]); + + // a .fiz giving a step beyond the table: nothing checks it on loading + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + CHECK(broken->RList[1].ScndAct == 20); + CHECK(broken->RList[1].ScndAct > MotorParametersArraySize); +} + +TEST_CASE("motor parameters: motor_param() keeps a step from the .fiz inside the table") { + vehicle broken{definition::fiz("ep09_v2/104e").set("RList", "rows", ep09_rlist_with_scndact("20"))}; + auto const &table{broken->MotorParam}; + // past the end: the last entry, rather than memory beyond the table + CHECK(&broken->motor_param(broken->RList[1].ScndAct) == &table[MotorParametersArraySize]); + CHECK(&broken->motor_param(MotorParametersArraySize + 1) == &table[MotorParametersArraySize]); + // below the start: the first entry + CHECK(&broken->motor_param(-1) == &table[0]); + // inside the table: the entry itself + for (int step = 0; step <= MotorParametersArraySize; ++step) { + CHECK(&broken->motor_param(step) == &table[step]); + } +} diff --git a/tests/unit/test_odometer.cpp b/tests/unit/test_odometer.cpp index 067e31037..ffb420bc3 100644 --- a/tests/unit/test_odometer.cpp +++ b/tests/unit/test_odometer.cpp @@ -4,9 +4,23 @@ #include "utilities/Globals.h" #include "vehicle/odometer.h" +#include +#include +#include #include #include +#include +#include +#include #include +#include +#include +#include +#ifdef _WIN32 +#include +#else +#include +#endif // the odometer of a vehicle, kept between the sessions (eu07/maszyna#72): one state the cab's counters and the // python screens show, saved in one store, taking over the states the python screens kept in their own files @@ -54,8 +68,8 @@ TEST_CASE("odometer: a vehicle counts the distance it runs either way, as the se test::vehicle vehicle{test::definition::load("wagon"), velocity}; vehicle->Odometer.begin(123456.0, odometer::origin::saved); vehicle.run(10.0); - CHECK(vehicle->DistCounter > 0.05); - CHECK(vehicle->Odometer.km - 123456.0 == doctest::Approx(vehicle->DistCounter)); + CHECK(vehicle->DistCounter() > 0.05); + CHECK(vehicle->Odometer.km - 123456.0 == doctest::Approx(vehicle->DistCounter())); CHECK(vehicle->Odometer.start == 123456.0); CHECK(vehicle->Odometer.moved()); } @@ -355,13 +369,146 @@ TEST_CASE("odometer: two simulations saving one file keep each other's states") } CHECK(files == 1); } - SUBCASE("a store with nothing recorded since doesn't write") { + SUBCASE("a store with nothing recorded since doesn't write, once the file showed what it saved") { + REQUIRE(odometer::save(second, path)); write_file(path, "1 replaced by hand\n"); REQUIRE(odometer::save(second, path)); CHECK(load().size() == 1); } } +namespace { + +odometer::store load_store(std::filesystem::path const &Path) { + odometer::store store; + std::ifstream input{Path, std::ios::binary}; + store.read(input); + return store; +} + +// a comment line added to the file; a save that writes the file drops it +void mark(std::filesystem::path const &Path) { + std::ofstream{Path, std::ios::binary | std::ios::app} << "# not written since\n"; +} + +bool marked(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str().find("# not written since") != std::string::npos; +} + +// the save of Late reads the file before the save of Early writes it, and puts its own file in place after: Late +// writes the file as it was before Early's save, Early's states are gone from it +void interleave(odometer::store &Early, odometer::store &Late, std::filesystem::path const &Path) { + auto const view{Path.parent_path() / "late_view" / Path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(Path, view, std::filesystem::copy_options::overwrite_existing); + REQUIRE(odometer::save(Early, Path)); + REQUIRE(odometer::save(Late, view)); + std::filesystem::rename(view, Path); +} + +} // namespace + +TEST_CASE("odometer: a save another simulation's save put its file over is written again") { + scratch_directory directory{"odometer_lost_save"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + first.record("first only", run(70.0, 1000.0)); + second.record("second only", run(80.0, 1000.0)); + + interleave(second, first, path); + // the race of the two saves: the second one's state is gone from the file + REQUIRE_FALSE(load_store(path).find("second only").has_value()); + REQUIRE(load_store(path).find("first only").has_value()); + + // the second one's next save, nothing recorded since, finds the file without its state and writes it again + CHECK_FALSE(second.modified()); + REQUIRE(odometer::save(second, path)); + auto const saved{load_store(path)}; + CHECK(saved.size() == 3); + CHECK(saved.find("second only").value_or(0.0) == doctest::Approx(81.0)); + CHECK(saved.find("first only").value_or(0.0) == doctest::Approx(71.0)); + CHECK(saved.find("shared").value_or(0.0) == 1000.0); + + // both find their states in the file now: their next saves don't write it + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); + CHECK(load_store(path).size() == 3); +} + +TEST_CASE("odometer: two simulations with different states of a vehicle settle on the newer one") { + scratch_directory directory{"odometer_lost_save_conflict"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "1000 shared\n~20000 guessed by both\n"); + auto first{load_store(path)}; + auto second{load_store(path)}; + // the first one ran the shared vehicle further, and the made up one further from its made up state; the second + // one has a known state of the made up one, from a cab's counter + first.record("shared", run(1000.0, 10000.0)); + second.record("shared", run(1000.0, 5000.0)); + odometer::reading guessed; + guessed.begin(20000.0, odometer::origin::guessed); + guessed.run(9000.0); + first.record("guessed by both", guessed); + odometer::reading seeded; + seeded.begin(300.0, odometer::origin::counter); + second.record("guessed by both", seeded); + + // the second one's save is lost to the first one's, which holds the made up state + interleave(second, first, path); + REQUIRE(load_store(path).guessed("guessed by both")); + + // the second one writes its known state again. the first one takes it, and the second one the larger state of + // the shared vehicle the first one saved + REQUIRE(odometer::save(second, path)); + REQUIRE(odometer::save(first, path)); + auto const settled{load_store(path)}; + CHECK(settled.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + CHECK(settled.find("guessed by both").value_or(0.0) == 300.0); + CHECK_FALSE(settled.guessed("guessed by both")); + CHECK(first.find("guessed by both").value_or(0.0) == 300.0); + CHECK(second.find("shared").value_or(0.0) == doctest::Approx(1010.0)); + + // neither one keeps writing the file over to have its own state there + mark(path); + for (auto round{0}; round < 3; ++round) { + REQUIRE(odometer::save(first, path)); + REQUIRE(odometer::save(second, path)); + } + CHECK(marked(path)); +} + +TEST_CASE("odometer: a save with nothing recorded since doesn't write the file again") { + scratch_directory directory{"odometer_saved_once"}; + auto const path{directory.path / "eu07_odometers.txt"}; + odometer::store store; + // states the file holds rounded to its digits + store.record("known", run(1000.0, 1234.56789)); + odometer::reading guessed; + guessed.begin(12345.678912, odometer::origin::guessed); + guessed.run(98.76543); + store.record("guessed", guessed); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(store.modified()); + + // the next save finds the file holding the states, rounded as they are: it doesn't write it + mark(path); + REQUIRE(odometer::save(store, path)); + CHECK(marked(path)); + // and the saves after it don't look at the file any more + std::filesystem::remove(path); + REQUIRE(odometer::save(store, path)); + CHECK_FALSE(std::filesystem::exists(path)); +} + TEST_CASE("odometer: a test run neither reads nor saves the player's store") { if (false == Global.test.enabled) CHECK(odometer::persistent()); @@ -532,3 +679,467 @@ TEST_CASE("odometer: the files of both kinds of python screens are read, by the CHECK_FALSE(odometer::legacy_state(vehicles, "EU07-425", scripts).has_value()); CHECK_FALSE(odometer::legacy_state(vehicles, "", scripts).has_value()); } + +// the day a state was last updated, kept in the file so the vehicles not run for long are dropped from it (review of +// eu07/maszyna#283: the file grew with every vehicle ever run). the tests give the day, the clock of the machine +// doesn't matter + +namespace { + +constexpr odometer::day today{std::chrono::year{2026} / 11 / 21}; + +odometer::day days_ago(int const Days) { + return today - std::chrono::days{Days}; +} + +odometer::day days_on(int const Days) { + return today + std::chrono::days{Days}; +} + +odometer::store read_text(std::string const &Text, odometer::day const Today = today) { + std::stringstream file{Text}; + odometer::store store; + store.read(file, Today); + return store; +} + +std::string read_file(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + std::stringstream content; + content << input.rdbuf(); + return content.str(); +} + +std::string written(odometer::store const &Store) { + std::stringstream text; + Store.write(text); + return text.str(); +} + +// the reader of the builds before the stamps, as it was (2f127688, odometer::store::read): the states it gets +struct old_state { + double km; + bool guessed; +}; + +std::optional old_line(std::string const &Line, std::string &Name) { + auto const separator{Line.find_first_of(" \t")}; + if (separator == std::string::npos) + return std::nullopt; + auto number{Line.substr(0, separator)}; + auto const guessed{false == number.empty() && number.front() == '~'}; + if (guessed) + number.erase(0, 1); + std::size_t used{0}; + double km{0.0}; + try { + km = std::stod(number, &used); + } catch (std::exception const &) { + return std::nullopt; + } + Name = Line.substr(separator + 1); + if (used != number.size() || false == std::isfinite(km) || km < 0.0 || Name.empty()) + return std::nullopt; + return old_state{km, guessed}; +} + +std::map old_read(std::string const &Text) { + std::map states; + std::stringstream input{Text}; + std::string line; + while (std::getline(input, line)) { + if (false == line.empty() && line.back() == '\r') + line.pop_back(); + if (line.empty() || line.front() == '#') + continue; + std::string name; + if (auto const state{old_line(line, name)}; state.has_value()) + states[name] = *state; + } + return states; +} + +odometer::reading guessed_run(double const Km, double const Metres) { + odometer::reading reading; + reading.begin(Km, odometer::origin::guessed); + reading.run(Metres); + return reading; +} + +} // namespace + +TEST_CASE("odometer: a file of the builds before the stamps is read whole, its states updated the day it's read") { + std::string const unstamped{"# odometer states of the vehicles: , ~ for one counted from a made up state\n" + "1000.0000 EU07-424\n" + "~20000.0000 SM42-001\n" + "42.5000 loco with spaces\n"}; + auto const store{read_text(unstamped)}; + REQUIRE(store.size() == 3); + CHECK(store.find("EU07-424").value() == 1000.0); + CHECK(store.guessed("SM42-001")); + CHECK(store.find("loco with spaces").value() == 42.5); + for (auto const *name : {"EU07-424", "SM42-001", "loco with spaces"}) { + CAPTURE(name); + CHECK(store.updated(name) == today); + } + CHECK_FALSE(store.updated("EU07-425").has_value()); + + // saved, all of them are written with the day they were read, none dropped + scratch_directory directory{"odometer_unstamped"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, unstamped); + auto loaded{read_text(read_file(path))}; + loaded.record("EU07-424", run(1000.0, 1000.0), today); + REQUIRE(odometer::save(loaded, path, today)); + auto const text{read_file(path)}; + CHECK(text.find("# updated 2026-11-21\n") != std::string::npos); + auto const after{read_text(text, days_on(10))}; + CHECK(after.size() == 3); + CHECK(after.find("EU07-424").value() == doctest::Approx(1001.0)); + CHECK(after.find("SM42-001").value() == 20000.0); + CHECK(after.updated("SM42-001") == today); +} + +TEST_CASE("odometer: the day a state was last updated is written with it and read back") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(10)); + store.record("ET22-001", run(5.0, 1000.0), days_ago(400)); + auto const text{written(store)}; + // grouped by the day, the oldest first, by the name in a group + CHECK(text.find("# updated 2025-10-17\n6.0000 ET22-001\n" + "# updated 2026-11-11\n1001.0000 EU07-424\n~20001.0000 SM42-001\n" + "# updated 2026-11-21\n42.5000 loco with spaces\n") + != std::string::npos); + + auto const read{read_text(text)}; + CHECK(read.size() == 4); + CHECK(read.updated("EU07-424") == days_ago(10)); + CHECK(read.updated("SM42-001") == days_ago(10)); + CHECK(read.guessed("SM42-001")); + CHECK(read.updated("loco with spaces") == today); + CHECK(read.updated("ET22-001") == days_ago(400)); + CHECK(read.find("loco with spaces").value() == doctest::Approx(42.5)); + // the store read writes the same file again + CHECK(written(read) == text); +} + +TEST_CASE("odometer: a build before the stamps reads the file with them as it read its own") { + odometer::store store; + store.record("EU07-424", run(1000.0, 1000.0), days_ago(10)); + store.record("loco with spaces", run(42.0, 500.0), today); + store.record("SM42-001", guessed_run(20000.0, 1000.0), days_ago(300)); + auto const old{old_read(written(store))}; + REQUIRE(old.size() == 3); + CHECK(old.at("EU07-424").km == doctest::Approx(1001.0)); + CHECK_FALSE(old.at("EU07-424").guessed); + CHECK(old.at("loco with spaces").km == doctest::Approx(42.5)); + CHECK(old.at("SM42-001").km == doctest::Approx(20001.0)); + CHECK(old.at("SM42-001").guessed); +} + +TEST_CASE("odometer: a stamp later than the day is kept as written, a malformed one doesn't make a state expire") { + auto const store{read_text("# updated 2099-01-01\n1 future\n" + "# updated 2025-01-01\n2 dated\n" + "# a comment between\n3 after a comment\n" + "# updated nonsense\n4 malformed\n" + "# updated 2026-02-30\n5 no such day\n" + "# updated 2025-1-01\n6 short\n" + "# updated 2025-01-01 \r\n7 trailing space\n" + "#updated 2024-01-01\n8 not a stamp\n")}; + odometer::day const newyear{std::chrono::year{2025} / 1 / 1}; + CHECK(store.size() == 8); + // a clock set back doesn't move it back (review of #435: the next session with the right clock dropped them all) + CHECK(store.updated("future") == odometer::day{std::chrono::year{2099} / 1 / 1}); + CHECK(store.updated("dated") == newyear); + CHECK(store.updated("after a comment") == newyear); + CHECK(store.updated("malformed") == today); + CHECK(store.updated("no such day") == today); + CHECK(store.updated("short") == today); + CHECK(store.updated("trailing space") == newyear); + CHECK(store.updated("not a stamp") == newyear); +} + +TEST_CASE("odometer: a state is updated the day it's recorded, one left as it was keeps its day") { + auto store{read_text("# updated 2026-08-13\n300 known\n")}; + REQUIRE(store.updated("known") == days_ago(100)); + store.record("known", started(300.0), today); + CHECK(store.updated("known") == days_ago(100)); + store.record("known", run(300.0, 1000.0), today); + CHECK(store.updated("known") == today); +} + +TEST_CASE("odometer: of two stores merged, the later day of a state is kept, whichever state is newer") { + auto const other{read_text("# updated 2026-11-01\n100 known\n# updated 2026-11-20\n200 other\n")}; + auto mine{read_text("# updated 2026-11-10\n150 known\n# updated 2026-11-15\n250 other\n")}; + mine.merge(other); + CHECK(mine.find("known").value() == 150.0); + CHECK(mine.updated("known") == days_ago(11)); + CHECK(mine.find("other").value() == 250.0); + CHECK(mine.updated("other") == days_ago(1)); + auto const newer{read_text("# updated 2026-11-01\n500 known\n")}; + mine.merge(newer); + CHECK(mine.find("known").value() == 500.0); + CHECK(mine.updated("known") == days_ago(11)); +} + +TEST_CASE("odometer: a save drops the states not updated for longer than a year, the other simulations' too") { + CHECK(odometer::expiry() == std::chrono::days{365}); + scratch_directory directory{"odometer_expiry"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2026-11-21\n300 fresh\n"); + auto store{read_text(read_file(path))}; + // another simulation saved meanwhile, with a state as old as one of this one's + write_file(path, "# updated 2025-11-20\n100 over a year\n" + "# updated 2025-11-21\n200 a year\n" + "# updated 2025-06-01\n5 old of another\n" + "# updated 2026-11-21\n300 fresh\n6 fresh of another\n"); + store.record("run today", run(70.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today)); + + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 4); + CHECK_FALSE(saved.find("over a year").has_value()); + CHECK_FALSE(saved.find("old of another").has_value()); + CHECK(saved.find("a year").value() == 200.0); + CHECK(saved.updated("a year") == days_ago(365)); + CHECK(saved.find("fresh").value() == 300.0); + CHECK(saved.find("fresh of another").value() == 6.0); + CHECK(saved.find("run today").value() == doctest::Approx(71.0)); + // gone from the store of the simulation too + CHECK_FALSE(store.find("over a year").has_value()); + CHECK(store.size() == 4); + + SUBCASE("the one of a year drops too once the file was updated a day later, in the session that reads it") { + // the session goes on the next day: measured from the day the file had when the session read it + store.record("run today", run(71.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + // the next session + auto next{read_text(read_file(path), days_on(1))}; + next.record("run today", run(72.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const later{read_text(read_file(path), days_on(1))}; + CHECK(later.size() == 3); + CHECK_FALSE(later.find("a year").has_value()); + CHECK(later.updated("run today") == days_on(1)); + } + SUBCASE("a store with nothing recorded since doesn't write the file only to drop them") { + REQUIRE(odometer::save(store, path, today)); + mark(path); + REQUIRE(odometer::save(store, path, days_on(1))); + CHECK(marked(path)); + CHECK(read_text(read_file(path), days_on(1)).find("a year").has_value()); + } +} + +TEST_CASE("odometer: a save lost to another simulation's save is written again with its stamps") { + scratch_directory directory{"odometer_lost_save_stamps"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2026-06-01\n1000 shared\n"); + auto first{read_text(read_file(path))}; + auto second{read_text(read_file(path))}; + first.record("shared", run(1000.0, 5000.0), today); + first.record("first only", run(70.0, 1000.0), today); + second.record("second only", run(80.0, 1000.0), days_ago(1)); + + // the second one reads the file before the first one writes it, and puts its own in place after + auto const view{directory.path / "late_view" / path.filename()}; + std::filesystem::create_directories(view.parent_path()); + std::filesystem::copy_file(path, view); + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, view, today)); + std::filesystem::rename(view, path); + REQUIRE_FALSE(read_text(read_file(path)).find("first only").has_value()); + + REQUIRE(odometer::save(first, path, today)); + REQUIRE(odometer::save(second, path, today)); + auto const saved{read_text(read_file(path))}; + CHECK(saved.size() == 3); + CHECK(saved.find("shared").value() == doctest::Approx(1005.0)); + CHECK(saved.updated("shared") == today); + CHECK(saved.find("first only").value() == doctest::Approx(71.0)); + CHECK(saved.updated("first only") == today); + CHECK(saved.find("second only").value() == doctest::Approx(81.0)); + CHECK(saved.updated("second only") == days_ago(1)); +} + +// a wrong clock, the period of eu07.ini (odometer.expiry) and the log of what's dropped (review of eu07/maszyna#435) + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +odometer::day const backintime{std::chrono::year{2000} / 1 / 1}; + +int process_id() { +#ifdef _WIN32 + return _getpid(); +#else + return static_cast(getpid()); +#endif +} + +class log_capture { +public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + std::size_t count(std::string_view const Text) const { + auto const lines{unit_tests_logged_lines()}; + return static_cast(std::ranges::count_if(lines, [Text](std::string const &Line) { return Line.find(Text) != std::string::npos; })); + } +}; + +std::string const stamped_file{"# updated 2025-12-01\n100 a year ago\n" + "# updated 2026-11-11\n200 driven\n" + "# updated 2026-11-21\n300 fresh\n"}; + +} // namespace + +TEST_CASE("odometer: a clock set back doesn't move the days of the states back, nor drops them then") { + scratch_directory directory{"odometer_clock_back"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // a dead battery of the clock: the session starts on 2000-01-01 + auto back{read_text(read_file(path), backintime)}; + CHECK(back.updated("a year ago") == days_ago(355)); + back.record("driven", run(200.0, 1000.0), backintime); + CHECK(back.updated("driven") == days_ago(10)); + REQUIRE(odometer::save(back, path, backintime)); + auto const written{read_file(path)}; + CHECK(written.find("# updated 2000-01-01") == std::string::npos); + CHECK(read_text(written).size() == 3); + + // the next session with the right clock drops none of them + auto right{read_text(written, days_on(1))}; + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_ago(10)); + CHECK(after.find("driven").value() == doctest::Approx(201.0)); +} + +TEST_CASE("odometer: a clock set forward doesn't drop the states not run in that session") { + scratch_directory directory{"odometer_clock_forward"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, stamped_file); + // two years ahead: measured from the day the file had when the session read it + auto ahead{read_text(read_file(path), days_on(730))}; + ahead.record("driven", run(200.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + // the later saves of the session too, which find its own states of that day in the file + ahead.record("driven", run(201.0, 1000.0), days_on(730)); + REQUIRE(odometer::save(ahead, path, days_on(730))); + CHECK(read_text(read_file(path), days_on(730)).size() == 3); + + // the next session with the right clock: the day ahead is kept as written, nothing drops + auto right{read_text(read_file(path), days_on(1))}; + CHECK(right.updated("driven") == days_on(730)); + right.record("fresh", run(300.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(right, path, days_on(1))); + auto const after{read_text(read_file(path), days_on(1))}; + CHECK(after.size() == 3); + CHECK(after.updated("a year ago") == days_ago(355)); + CHECK(after.updated("driven") == days_on(730)); +} + +TEST_CASE("odometer: a player back after a break keeps the states in the session he comes back in") { + scratch_directory directory{"odometer_break"}; + auto const path{directory.path / "eu07_odometers.txt"}; + // the last session was 500 days ago + write_file(path, "# updated 2024-05-19\n10 too old\n" + "# updated 2025-01-31\n20 older\n" + "# updated 2025-07-09\n30 last run\n40 not run since\n"); + REQUIRE(odometer::day{std::chrono::year{2025} / 7 / 9} == days_ago(500)); + auto back{read_text(read_file(path))}; + back.record("last run", run(30.0, 1000.0), today); + REQUIRE(odometer::save(back, path, today)); + auto const first{read_text(read_file(path))}; + // more than a year before the last session: gone, as that session would have dropped it the next day + CHECK_FALSE(first.find("too old").has_value()); + CHECK(first.find("older").has_value()); + CHECK(first.find("not run since").has_value()); + CHECK(first.updated("last run") == today); + + // the session after: not run for a year before the last one, they drop + auto next{read_text(read_file(path), days_on(1))}; + next.record("last run", run(31.0, 1000.0), days_on(1)); + REQUIRE(odometer::save(next, path, days_on(1))); + auto const second{read_text(read_file(path), days_on(1))}; + CHECK(second.size() == 1); + CHECK(second.find("last run").has_value()); +} + +TEST_CASE("odometer: the period is the one eu07.ini gives, 0 keeps every state") { + auto const text{"# updated 2000-01-01\n1 long ago\n# updated 2026-10-21\n2 a month ago\n# updated 2026-11-21\n3 fresh\n"}; + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{0}) == 0); + CHECK(store.size() == 3); + } + { + auto store{read_text(text)}; + CHECK(store.expire(today, std::chrono::days{30}) == 2); + CHECK(store.find("fresh").has_value()); + } + { + // and a save with it + scratch_directory directory{"odometer_never"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, text); + auto store{read_text(read_file(path))}; + store.record("fresh", run(3.0, 1000.0), today); + REQUIRE(odometer::save(store, path, today, std::chrono::days{0})); + CHECK(read_text(read_file(path)).size() == 3); + } + + // odometer.expiry in eu07.ini, a year unless set (the parser of eu07.ini, Globals.cpp, isn't in the build of + // the unit tests) + CHECK(std::make_unique()->odometer_expiry == 365); + // the store of the simulation takes it from the settings, a negative one as 0 + auto const kept{Global.odometer_expiry}; + Global.odometer_expiry = 90; + CHECK(odometer::expiry() == std::chrono::days{90}); + Global.odometer_expiry = 0; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = -5; + CHECK(odometer::expiry() == std::chrono::days{0}); + Global.odometer_expiry = kept; +} + +TEST_CASE("odometer: the states dropped are logged once, by the save that writes the file without them") { + scratch_directory directory{"odometer_dropped_log"}; + auto const path{directory.path / "eu07_odometers.txt"}; + write_file(path, "# updated 2025-01-01\n1 long ago\n# updated 2026-11-21\n2 fresh\n"); + auto store{read_text(read_file(path))}; + store.record("fresh", run(2.0, 1000.0), today); + constexpr std::string_view dropped{"not updated for 365 days dropped"}; + log_capture const log; + + // the file aside can't be written: each save fails, none logs the states dropped + auto temporary{path}; + temporary += "." + std::to_string(process_id()) + ".tmp"; + std::filesystem::create_directories(temporary / "blocked"); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK_FALSE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 0); + CHECK(read_text(read_file(path)).find("long ago").has_value()); + + std::filesystem::remove_all(temporary); + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); + CHECK_FALSE(read_text(read_file(path)).find("long ago").has_value()); + // the save after, which finds the file as written, doesn't log them again + REQUIRE(odometer::save(store, path, today, std::chrono::days{365})); + CHECK(log.count(dropped) == 1); +} diff --git a/tests/unit/test_oil_pump.cpp b/tests/unit/test_oil_pump.cpp index a5f623233..674930af2 100644 --- a/tests/unit/test_oil_pump.cpp +++ b/tests/unit/test_oil_pump.cpp @@ -12,7 +12,7 @@ using test::vehicle; TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and stops once the engine runs") { vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Manual")}; REQUIRE(loco->OilPump.start_type == start_t::manual); - loco->Power24vIsAvailable = true; // battery on + loco->lowVoltage.Set24vAvailableForTest(true); // battery on loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); // not switched on yet @@ -21,7 +21,7 @@ TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->Mains = true; // engine started + loco->lineBreaker.Close(); // engine started loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); } @@ -29,25 +29,25 @@ TEST_CASE("oil pump: the pre-lubrication pump works before the engine start and TEST_CASE("oil pump: the pump started with the engine start procedure stops once the engine runs") { vehicle loco{definition::load("cab_vehicle").set("Cntrl", "OilStart", "Automatic")}; REQUIRE(loco->OilPump.start_type == start_t::automatic); - loco->Power24vIsAvailable = true; + loco->lowVoltage.Set24vAvailableForTest(true); - loco->dizel_startup = true; // starter button pressed + loco->diesel.startupRequested = true; // starter button pressed loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->dizel_startup = false; // start procedure done, the pump keeps working until the engine runs + loco->diesel.startupRequested = false; // start procedure done, the pump keeps working until the engine runs loco->OilPumpCheck(0.01); CHECK(loco->OilPump.is_active); - loco->Mains = true; + loco->lineBreaker.Close(); loco->OilPumpCheck(0.01); CHECK_FALSE(loco->OilPump.is_active); } TEST_CASE("oil pump: without power the pump and its lamp stay off") { vehicle loco{definition::load("cab_vehicle")}; - loco->Power24vIsAvailable = false; - loco->Power110vIsAvailable = false; + loco->lowVoltage.Set24vAvailableForTest(false); + loco->lowVoltage.Set110vAvailableForTest(false); loco->OilPump.is_enabled = true; loco->OilPumpCheck(0.01); diff --git a/tests/unit/test_parser.cpp b/tests/unit/test_parser.cpp index 2584218d0..58f3bb980 100644 --- a/tests/unit/test_parser.cpp +++ b/tests/unit/test_parser.cpp @@ -696,6 +696,70 @@ TEST_CASE("parser: read line by line, a line starting with include is the direct CHECK(rest(word, false, "\n\r") == "one|two"); } +namespace { + +// the lines of a file, read the way the vehicle's .fiz is (physics::Vehicle::LoadFIZ_Parse): line by line while the +// parser is ok +std::string fiz_lines(cParser &Parser) { + std::string joined; + while (Parser.ok()) { + auto const line{Parser.getToken(false, "\n\r")}; + if (line.empty()) { + continue; + } + if (false == joined.empty()) { + joined += '|'; + } + joined += line; + } + return joined; +} + +} // namespace + +TEST_CASE("parser: a file which ends right after the end of an include is read through, the included file too") { + // the shape of the .fiz files of the wagons (pkp/yb_v1/b84_pl_1.fiz): the directive, the file and its parameters + // each on a line of their own, and no line break after the end. the change of MaSzyna-EU07/maszyna#100 broke on these + test::scratch_folder const folder{"parser_include_at_end"}; + folder.write("yb.fiz.inc", "Mass=(p1)\r\nVmax=(p2)\r\nLength=20\r\n"); + folder.write("ended.fiz", "include\r\nyb.fiz.inc\r\n160\r\n80\r\nend"); + folder.write("newline.fiz", "include\r\nyb.fiz.inc\r\n160\r\n80\r\nend\r\n"); + + cParser ended("ended.fiz", cParser::buffer_FILE, folder.path()); + CHECK(fiz_lines(ended) == "Mass=160|Vmax=80|Length=20"); + cParser newline("newline.fiz", cParser::buffer_FILE, folder.path()); + CHECK(fiz_lines(newline) == "Mass=160|Vmax=80|Length=20"); + + SUBCASE("the end of the data shows once the included file is read through, not when its directive is") { + folder.write("pair.inc", "x y"); + cParser parser("include pair.inc end", cParser::buffer_TEXT, folder.path()); + CHECK(parser.getToken() == "x"); + CHECK_FALSE(parser.eof()); + CHECK(parser.getToken() == "y"); + CHECK(parser.eof()); + CHECK(parser.ok()); + CHECK(parser.getToken().empty()); + CHECK_FALSE(parser.ok()); + // the same as for a text with the included tokens in place of the directive + cParser same("x y", cParser::buffer_TEXT); + CHECK(same.getToken() == "x"); + CHECK_FALSE(same.eof()); + CHECK(same.getToken() == "y"); + CHECK(same.eof()); + } + SUBCASE("a reader which stops at the end of the data reads the whole included file") { + folder.write("map.inc", "alpha One\nbeta Two"); + for (auto const *const text : {"include map.inc end", "include map.inc end\n"}) { + CAPTURE(text); + cParser parser(text, cParser::buffer_TEXT, folder.path()); + std::map map; + deserialize_map(map, parser); + CHECK(map["alpha"] == "One"); + CHECK(map["beta"] == "Two"); + } + } +} + TEST_CASE("parser: an include can name several files to pick one from at random") { test::scratch_folder const folder{"parser_random_include"}; folder.write("only.inc", "chosen"); diff --git a/tests/unit/test_pressure_switch.cpp b/tests/unit/test_pressure_switch.cpp new file mode 100644 index 000000000..1a50a0931 --- /dev/null +++ b/tests/unit/test_pressure_switch.cpp @@ -0,0 +1,295 @@ +#include "stdafx.h" +#include "doctest.h" +#include "drive.h" + +#include "physics/brakes.h" + +// the pressure switch of the EP05 (git.eu07.pl eu07/maszyna#48). the pressure switch of the simulator is two +// conditions in one: it cuts the traction motors off above 2 bar in the brake cylinders and below 3.6 bar in the +// brake pipe. the EP05 takes current whatever the pressure in its brake cylinders (Engine: PressureSwitchBrakeCylinder=No +// leaves the brake pipe half alone), and an emergency brake application made with the master controller on a power +// position opens its line breaker (Cntrl. EmergencyBrakeMainOff=), which on this locomotive +// drops the pantographs too, as they stay up only through the closed line breaker (Cntrl. PantRequiresMain) + +namespace { + +constexpr test::track line{0.15, 0.0, test::catenary_3kv}; + +// the brake pipe pressure taken for an emergency application in these tests [bar]: below the 2.8 bar the FV4a +// gives on its last service position, above what is left in the pipe once it's vented +constexpr double emergency_pressure{2.5}; + +struct keys { + bool brakecylinder{true}; // Engine: PressureSwitchBrakeCylinder + bool mainoff{false}; // Cntrl. EmergencyBrakeMainOff + bool mainsfirst{true}; // Cntrl. PantRequiresMain, which the game's EP05 has +}; + +test::definition ep05(keys const &Keys) { + auto definition{test::definition::fiz("ep05_v2/ep05")}; + if (Keys.mainsfirst) { + // the game's definition got it after the one of the tests was converted + definition.set("Cntrl", "PantRequiresMain", "Yes"); + } + if (false == Keys.brakecylinder) { + definition.set("Engine", "PressureSwitchBrakeCylinder", "No"); + } + if (Keys.mainoff) { + definition.set("Cntrl", "EmergencyBrakeMainOff", emergency_pressure); + } + return definition; +} + +// the locomotive started up the way the driver does it and its brakes released, until the pressure switch lets go +void get_ready(test::vehicle &Loco, test::driven const &Driven) { + REQUIRE(test::start_up(Driven, line)); + test::release_brakes(Driven.cab); + test::drive(Driven, line, 20.0); + for (int i = 0; i < 120 && Loco->protection.PressureSwitchTripped(); ++i) { + test::drive(Driven, line, 1.0); + } + REQUIRE_FALSE(Loco->protection.PressureSwitchTripped()); + REQUIRE(Loco->lineBreaker.IsClosed()); + REQUIRE(Loco->pantographs[VehicleEnd::rear].is_active); +} + +// the master controller taken to the given position a notch a second +void notch_up(test::vehicle &Loco, test::driven const &Driven, int const Position) { + while (Loco->MainCtrlPos() < Position && Loco->IncMainCtrl(1)) { + test::drive(Driven, line, 1.0); + } + test::drive(Driven, line, 2.0); + REQUIRE(Loco->MainCtrlPos() == Position); +} + +void get_under_power(test::vehicle &Loco, test::driven const &Driven, int const Position) { + get_ready(Loco, Driven); + notch_up(Loco, Driven, Position); + REQUIRE(Loco->lineContactors.IsClosed()); + REQUIRE(std::abs(Loco->Im) > 10.0); +} + +// the independent brake applied in full: 3.8 bar in the brake cylinders of the locomotive (Brake: MaxBP) +void apply_independent_brake(test::vehicle &Loco, test::driven const &Driven) { + Loco->IncLocalBrakeLevel(LocalBrakePosNo); + test::drive(Driven, line, 20.0); + REQUIRE(Loco->brakes.cylinderPressure == doctest::Approx(3.8).epsilon(0.03)); + REQUIRE(Loco->brakePipe.Pressure() > 4.8); +} + +void emergency_application(test::vehicle &Loco, test::driven const &Driven) { + Loco->BrakeLevelSet(Loco->brakes.driverValve->GetPos(bh_EB)); + test::drive(Driven, line, 10.0); + REQUIRE(Loco->brakePipe.Pressure() < 1.0); +} + +} // namespace + +TEST_CASE("pressure switch: the keys are off by default") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + CHECK(loco->protection.config.hasPressureSwitch); + CHECK(loco->protection.config.pressureSwitchWatchesCylinders); + CHECK(loco->lineBreaker.config.emergencyOffPressure == 0.0); + + test::vehicle changed{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + CHECK(changed->protection.config.hasPressureSwitch); + CHECK_FALSE(changed->protection.config.pressureSwitchWatchesCylinders); + CHECK(changed->lineBreaker.config.emergencyOffPressure == doctest::Approx(emergency_pressure)); +} + +TEST_CASE("pressure switch: with the brake cylinders at 3.8 bar the EP05 takes no current, as before") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_ready(loco, driven); + apply_independent_brake(loco, driven); + CHECK(loco->protection.PressureSwitchTripped()); + CHECK_FALSE(loco->MainCircuitLampsEnabled()); + + notch_up(loco, driven, 3); + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->Im == 0.0); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); +} + +TEST_CASE("pressure switch: without its brake cylinder half the EP05 takes current with the brake cylinders at 3.8 bar") { + test::vehicle loco{ep05({.brakecylinder = false}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_ready(loco, driven); + apply_independent_brake(loco, driven); + CHECK_FALSE(loco->protection.PressureSwitchTripped()); + // the lamps of the main circuit tell the start can be made + CHECK(loco->MainCircuitLampsEnabled()); + CHECK(loco->LineContactorsLampLit()); + + notch_up(loco, driven, 3); + CHECK(loco->lineContactors.IsClosed()); + CHECK(loco->MainCtrlActualPos == 3); + CHECK(std::abs(loco->Im) > 100.0); + CHECK(loco->brakes.cylinderPressure == doctest::Approx(3.8).epsilon(0.03)); + MESSAGE("current with 3.8 bar in the brake cylinders, position 3: " << std::abs(loco->Im) << " A"); +} + +TEST_CASE("pressure switch: without its brake cylinder half the brake pipe still cuts the traction motors off") { + test::vehicle loco{ep05({.brakecylinder = false}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + SUBCASE("a service application") { + loco->BrakeLevelSet(loco->brakes.driverValve->GetPos(bh_FB)); + test::drive(driven, line, 15.0); + REQUIRE(loco->brakePipe.Pressure() < 3.6); + REQUIRE(loco->brakePipe.Pressure() > 3.0); + } + SUBCASE("an emergency application") { + emergency_application(loco, driven); + } + CHECK(loco->protection.PressureSwitchTripped()); + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->Im == 0.0); + // nothing else lets go without the other key + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); +} + +TEST_CASE("pressure switch: an emergency application with the master controller on a power position opens the line breaker and drops the pantographs") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + SUBCASE("made with the brake handle") { + loco->BrakeLevelSet(loco->brakes.driverValve->GetPos(bh_EB)); + } + SUBCASE("made with the emergency brake of the train") { + loco->AlarmChainSwitch(true); + } + test::drive(driven, line, 10.0); + REQUIRE(loco->brakePipe.Pressure() < emergency_pressure); + REQUIRE(loco->MainCtrlPos() == 5); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->pantographs[VehicleEnd::front].is_active); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == 0.0); + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->Im == 0.0); + + // the line breaker doesn't close again while the master controller is where it was + loco->MainSwitch(true); + test::drive(driven, line, 2.0); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); +} + +TEST_CASE("pressure switch: an emergency application with the master controller at zero leaves the line breaker and the pantographs alone") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + while (loco->DecMainCtrl(1)) { + // down to zero + } + test::drive(driven, line, 2.0); + REQUIRE(loco->MainCtrlPos() == 0); + + emergency_application(loco, driven); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); + CHECK(loco->Im == 0.0); + + // and the master controller moved with the pipe empty is the same as the application made with it moved + loco->IncMainCtrl(1); + test::drive(driven, line, 2.0); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK_FALSE(loco->pantographs[VehicleEnd::rear].is_active); +} + +TEST_CASE("pressure switch: a service application with the master controller on a power position doesn't open the line breaker") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + // the last service position of the FV4a, 2.8 bar in the pipe + loco->BrakeLevelSet(5.0); + auto lowest{loco->brakePipe.Pressure()}; + for (int second = 0; second < 60; ++second) { + test::drive(driven, line, 1.0); + lowest = std::min(lowest, loco->brakePipe.Pressure()); + } + MESSAGE("the lowest brake pipe pressure of the service application: " << lowest << " bar"); + REQUIRE(lowest < 3.0); + CHECK(lowest > emergency_pressure); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + // the pressure switch has cut the motors off + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: without the key an emergency application leaves the line breaker closed and the pantographs up, as before") { + test::vehicle loco{ep05({}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + emergency_application(loco, driven); + REQUIRE(loco->MainCtrlPos() == 5); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); + // the pressure switch cuts the motors off + CHECK(loco->protection.PressureSwitchTripped()); + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: where the pantographs don't hang on the line breaker the emergency application opens only the line breaker") { + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true, .mainsfirst = false}), 0.0, "test", 1}; + REQUIRE_FALSE(loco->lineBreaker.config.pantographsRequireIt); + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + + emergency_application(loco, driven); + CHECK_FALSE(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); + CHECK_FALSE(loco->lineContactors.IsClosed()); + CHECK(loco->Im == 0.0); +} + +TEST_CASE("pressure switch: after the emergency application the driver's start-up gets the locomotive going again") { + // test::start_up() takes the AI's steps of TController::PrepareEngine(): the master controller to zero, the relays + // reset, the line breaker closed. the pantograph switches stay as they were, so the pantograph rises with the line + // breaker + test::vehicle loco{ep05({.brakecylinder = false, .mainoff = true}), 0.0, "test", 1}; + auto driven{test::driving(loco)}; + get_under_power(loco, driven, 5); + emergency_application(loco, driven); + REQUIRE_FALSE(loco->lineBreaker.IsClosed()); + REQUIRE_FALSE(loco->pantographs[VehicleEnd::rear].is_active); + REQUIRE(loco->pantographs[VehicleEnd::rear].valve.is_enabled); + + // with the brake pipe still empty + REQUIRE(test::start_up(driven, line, 60.0)); + CHECK(loco->MainCtrlPos() == 0); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + CHECK(loco->pantographCircuit.SupplyVoltage() == doctest::Approx(test::catenary_3kv)); + REQUIRE(loco->brakePipe.Pressure() < emergency_pressure); + // and it stays so + test::drive(driven, line, 30.0); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->pantographs[VehicleEnd::rear].is_active); + + // the brakes released (the AI fills an emptied pipe with the releaser held, TController::control_releaser()), + // the pressure switch lets the start be made + test::release_brakes(driven.cab); + for (int i = 0; i < 180 && loco->protection.PressureSwitchTripped(); ++i) { + loco->BrakeReleaser(loco->brakePipe.Pressure() < 3.0 ? 1 : 0); + test::drive(driven, line, 1.0); + } + loco->BrakeReleaser(0); + REQUIRE_FALSE(loco->protection.PressureSwitchTripped()); + notch_up(loco, driven, 3); + CHECK(loco->lineBreaker.IsClosed()); + CHECK(loco->lineContactors.IsClosed()); + CHECK(std::abs(loco->Im) > 10.0); +} diff --git a/tests/unit/test_pullee.cpp b/tests/unit/test_pullee.cpp new file mode 100644 index 000000000..8a8388aae --- /dev/null +++ b/tests/unit/test_pullee.cpp @@ -0,0 +1,449 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" +#include "consist.h" +#include "drive.h" +#include "real_vehicles.h" + +#include "vehicle/pulleemode.h" + +using test::definition; +using test::vehicle; + +// the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a +// train, physics::Vehicle::PulleeModeSwitch(). the trains here are an EU07 and the vehicle behind it, coupled with +// the hook and the brake hose alone, as with coupling 3 of a scenery. every test has both sides: what the vehicle +// does as it is (unchanged by the mode being there), and what it does prepared for hauling. +// pressures in bar, the brake pipe runs at 5.0 + +namespace { + +constexpr CouplingSet hook_and_brake_hose{Coupling::coupler | Coupling::brakeHose}; + +// an EU07 with nobody in it, its brake pipe held by the test the way a driver's valve would hold it, and the +// vehicle it hauls. Velocity as of a trainset of a scenery [km/h]: not 0, the vehicles are ready to depart, +// 0, they stand braked (brake pipe at 3.5, hand and spring brakes on, batteries off) +struct hauled_train { + test::consist train; + vehicle &locomotive; + vehicle &hauled; + + hauled_train(definition const &Hauled, double const Velocity, bool const Pullee) + : locomotive{train.add(definition::fiz("4e_v1/4e"), 0, test::consist::full_coupling, Velocity)}, hauled{train.add(Hauled, 0, hook_and_brake_hose, Velocity)} { + if (Pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + locomotive.hold_brake_pipe(5.0); + } + + void run(double const Seconds) { train.run(Seconds); } +}; + +// no air in the main reservoir and the feed pipe, as after standing dead for some hours +void drain_feed_air(physics::Vehicle &Vehicle) { + Vehicle.mainPipe.reservoir->CreatePress(0.0); + Vehicle.mainPipe.reservoir->Act(); + Vehicle.air.Fill(0.0); +} + +// whether the real vehicle can go in a train at all: the road vehicles can't, nor can the draisine, which has no coupler +bool can_be_hauled(std::string const &Path) { + vehicle probe{definition::fiz(Path)}; + return (probe->CategoryFlag & 1) != 0 && probe->Couplers[VehicleEnd::front].CouplerType != TCouplerType::NoCoupler; +} + +} // namespace + +TEST_CASE("pullee: the parameter H among the ones after the coupling of a vehicle asks for the mode") { + CHECK(pullee_mode::requested("H")); + CHECK(pullee_mode::requested("h")); + CHECK(pullee_mode::requested("BG.H")); + CHECK(pullee_mode::requested("H.BG")); + CHECK(pullee_mode::requested("BP.WF10.h.TA")); + CHECK(pullee_mode::requested("HX")); // letters after it are for later + // the parameters the sceneries have: brakes, wheels (their H is the hunting of a bogie), temperatures, load + CHECK_FALSE(pullee_mode::requested("")); + CHECK_FALSE(pullee_mode::requested("BG")); + CHECK_FALSE(pullee_mode::requested("WH25")); + CHECK_FALSE(pullee_mode::requested("BR.WF5R10P50H25.TA.L50")); + CHECK_FALSE(pullee_mode::requested("0")); +} + +TEST_CASE("pullee: a dead Vectron vents the brake pipe of the train hauling it, prepared for hauling it doesn't") { + // the Vectron applies the emergency brake while none of its cabs is active (InactiveCabFlag bit 1), which a + // vehicle hauled with the hook and the brake hose never has + auto const vectron{definition::fiz("vectron_v1/wariant_7w")}; + SUBCASE("as it is") { + hauled_train train{vectron, 60.0, false}; + REQUIRE((train.hauled->InactiveCabFlag & activation::emergencybrake) != 0); + REQUIRE_FALSE(train.hauled->PulleeMode()); + train.run(120.0); + CHECK(train.hauled->brakes.emergencyValve.flow > 0.0); + CHECK(train.locomotive->brakePipe.Pressure() < 4.95); // the pipe sags although the locomotive keeps feeding it + CHECK(train.hauled->brakes.cylinderPressure > 0.4); + CHECK(train.hauled.speed() < 30.0); + } + SUBCASE("prepared for hauling") { + hauled_train train{vectron, 60.0, true}; + train.run(120.0); + CHECK(train.hauled->brakes.emergencyValve.flow == 0.0); + CHECK(train.locomotive->brakePipe.Pressure() > 4.99); + CHECK(train.hauled->brakes.cylinderPressure < 0.1); + CHECK(train.hauled->Fb() < 1.0); + CHECK(train.hauled.speed() > 40.0); // running resistance alone + } +} + +TEST_CASE("pullee: an EU07 with a driver can't release the brakes of a dead Vectron, and hauls one prepared for hauling") { + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + test::consist train; + // a trainset ready to depart, as with velocity 0.1 in a scenery + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 1, test::consist::full_coupling, 0.1)}; + auto &hauled{train.add(definition::fiz("vectron_v1/wariant_7w"), 0, hook_and_brake_hose, 0.1)}; + if (pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + test::track const track{0.15, 0.0, test::catenary_3kv}; + auto driven{test::driving(train)}; + REQUIRE(test::start_up(driven, track, 600.0)); + test::release_brakes(driven.cab); + // the driver of a train switches on the batteries of the vehicles not controlled from the cab, TController::CheckVehicles() + hauled->BatterySwitch(true); + test::drive(driven, track, 60.0); + if (false == pullee) { + // the Vectron has emptied the brake pipe, and both locomotives stand on an emergency application + CHECK(hauled->lowVoltage.IsBatteryOn()); + CHECK(locomotive->brakePipe.Pressure() < 1.0); + CHECK(locomotive->brakes.cylinderPressure > 3.0); + CHECK(hauled->brakes.cylinderPressure > 3.0); + continue; + } + CHECK_FALSE(hauled->lowVoltage.IsBatteryOn()); + CHECK(locomotive->brakePipe.Pressure() > 4.9); + CHECK(locomotive->brakes.cylinderPressure < 0.1); + CHECK(hauled->brakes.cylinderPressure < 0.1); + // the driver notches up watching the ammeter + for (int i = 0; i < 3 && driven.cab.DirActive <= 0; ++i) { + driven.cab.DirectionForward(); + } + for (int second = 0; second < 60; second += 5) { + if (std::abs(driven.controlling.Im) < 350.0 && false == driven.controlling.IsMainCtrlMaxPowerPos()) { + driven.controlling.IncMainCtrl(1); + } + test::drive(driven, track, 5.0); + } + CHECK(hauled.speed() > 20.0); + } +} + +TEST_CASE("pullee: the spring brake of a dead locomotive without air stops the train, prepared for hauling it gives no force") { + // the spring brake is held off by the air of the feed pipe, which on a dead locomotive is what its main + // reservoir has left. the EU47 and the EP09 have the spring brake alone, the Vectron the emergency brake too + for (auto const *path : {"e186_v2/eu47", "ep09_v2/104e", "vectron_v1/wariant_7w"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, pullee}; + auto const &hauled{train.hauled.physics()}; + REQUIRE(hauled.brakes.spring.maxForce > 0.0); + drain_feed_air(train.hauled.physics()); + train.run(60.0); + // no air came from anywhere: the cylinder of the spring brake is empty either way + REQUIRE(hauled.brakes.spring.pressure < 0.1); + if (pullee) { + CHECK(hauled.Fb() < 1.0); + CHECK(train.hauled.speed() > 45.0); + } + else { + CHECK(hauled.Fb() > 30000.0); + CHECK(std::abs(train.hauled.speed()) < 1.0); + } + } + } +} + +TEST_CASE("pullee: a dead EU47 starts to drag once its main reservoir has leaked down, prepared for hauling it never does") { + // from a standing start the reservoir has 4.4 bar, and the spring brake comes on below 3.5 (MinFP) + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{definition::fiz("e186_v2/eu47"), 0.0, pullee}; + auto &hauled{train.hauled.physics()}; + // what the driver of the train does on its inspection, TController::AutoRewident() + hauled.DecManualBrakeLevel(ManualBrakePosNo); + hauled.brakes.spring.activate = false; + train.run(180.0); + // charged and released: nothing holds it yet + CHECK(hauled.brakes.cylinderPressure < 0.1); + CHECK(hauled.Fb() < 1.0); + train.run(1020.0); // 20 minutes since the start + CHECK(hauled.mainPipe.Pressure() < hauled.brakes.spring.minForcePressure); + if (pullee) { + CHECK(hauled.Fb() < 1.0); + } + else { + CHECK(hauled.Fb() > 5000.0); + } + } +} + +TEST_CASE("pullee: a vehicle prepared for hauling brakes and releases with the train, and its spring brake stays off after") { + // the distributor stays on the brake pipe. with air in the feed pipe and without: the cylinders fill from the + // auxiliary reservoir, and the spring brake, with no air to hold it off, still gives nothing after the release + for (auto const *path : {"vectron_v1/wariant_7w", "e6act_v2/e6acta", "ep09_v2/104e", "e186_v2/eu47"}) { + for (auto const feedair : {true, false}) { + CAPTURE(path); + CAPTURE(feedair); + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, true}; + auto const &hauled{train.hauled.physics()}; + if (false == feedair) { + drain_feed_air(train.hauled.physics()); + } + train.run(30.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); + // a full service application + train.locomotive.hold_brake_pipe(3.5); + train.run(20.0); + CHECK(hauled.brakes.cylinderPressure > 2.0); + CHECK(hauled.Fb() > 30000.0); + train.locomotive.hold_brake_pipe(5.0); + train.run(90.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); + CHECK(hauled.Fb() < 1.0); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + } + } +} + +TEST_CASE("pullee: the spring brake of an Impuls prepared for hauling doesn't call the emergency brake") { + // SpringBrakeDriveEmergencyVel=2: above 2 km/h an applied spring brake vents the brake pipe. the emergency + // brake of the inactive cab (InactiveCabFlag) is taken out of the definition, so that it's the spring brake's + auto const impuls{definition::fiz("impuls_v1/31we-a_pr").set("Cntrl", "InactiveCabFlag", 0)}; + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + hauled_train train{impuls, 60.0, pullee}; + auto const &hauled{train.hauled.physics()}; + REQUIRE(hauled.InactiveCabFlag == 0); + REQUIRE(hauled.brakes.spring.driveEmergencySpeed == doctest::Approx(2.0)); + drain_feed_air(train.hauled.physics()); + train.run(10.0); + REQUIRE(hauled.Vel > 2.0); + REQUIRE(hauled.brakes.spring.isActive); + if (pullee) { + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); + } + else { + CHECK(hauled.brakes.emergencyValve.flow > 0.0); + } + } +} + +TEST_CASE("pullee: the brake valves in the cab of a vehicle prepared for hauling move no air") { + // with somebody in the cab: nobody is put there by a scenery, but the valves are cut out whoever sits down. + // the Elf has the MHZ_K5P driver's valve, the EU47 the MHZ_6P, the Vectron the MHZ_K8P, the EP09 and the EU07 the FV4a + for (auto const *path : {"elf_v1/21we-a", "e186_v2/eu47", "vectron_v1/wariant_7w", "ep09_v2/104e", "4e_v1/4e"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + vehicle driven{definition::fiz(path), 0.1, "test", 1}; + // the emergency brake of the inactive cab is another matter, see above + driven->InactiveCabFlag = 0; + if (pullee) { + REQUIRE(driven->PulleeModeSwitch(true)); + } + // the local brake a driver keeps a standing vehicle on is let go + driven->DecLocalBrakeLevel(LocalBrakePosNo); + driven.run(20.0); + REQUIRE(driven->brakes.cylinderPressure < 0.1); + auto const charged{driven->brakePipe.Pressure()}; + // full service braking with the driver's valve + driven->BrakeLevelSet(driven->brakes.driverValve->GetPos(bh_FB)); + driven.run(10.0); + if (pullee) { + CHECK(driven->brakes.driverValveFlow == 0.0); + CHECK(driven->brakePipe.Pressure() > charged - 0.1); + CHECK(driven->brakes.cylinderPressure < 0.1); + } + else { + CHECK(driven->brakePipe.Pressure() < charged - 0.5); + CHECK(driven->brakes.cylinderPressure > 1.0); + } + // and the emergency position + driven->BrakeLevelSet(driven->brakes.driverValve->GetPos(bh_EB)); + driven.run(10.0); + if (pullee) { + CHECK(driven->brakes.driverValveFlow == 0.0); + CHECK(driven->brakePipe.Pressure() > charged - 0.1); + } + else { + CHECK(driven->brakePipe.Pressure() < 1.0); + } + } + } +} + +TEST_CASE("pullee: the local brake of a vehicle prepared for hauling stays released") { + for (auto const *path : {"vectron_v1/wariant_7w", "4e_v1/4e", "ep09_v2/104e"}) { + for (auto const pullee : {false, true}) { + CAPTURE(path); + CAPTURE(pullee); + test::reseed_random(); + vehicle driven{definition::fiz(path), 0.1, "test", 1}; + driven->InactiveCabFlag = 0; + driven.hold_brake_pipe(5.0); + if (pullee) { + REQUIRE(driven->PulleeModeSwitch(true)); + } + // applied with the lever, as on a vehicle left on standby, and asked for by the brake computer of a unit + // (what the MED of TDynamicObject writes; the lever of a Vectron does nothing without it) + driven->IncLocalBrakeLevel(LocalBrakePosNo); + driven->brakes.SetIndependentPositionEim(1.0); + driven.run(20.0); + if (pullee) { + CHECK(driven->brakes.cylinderPressure < 0.1); + } + else { + CHECK(driven->brakes.cylinderPressure > 1.0); + } + } + } +} + +TEST_CASE("pullee: entering the mode lets go of the hand brake and the spring brake switch, and switches the battery off") { + SUBCASE("a locomotive standing braked, its spring brake switched on") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w")}; + REQUIRE(vectron->brakes.spring.activate); + REQUIRE_FALSE(vectron->PulleeMode()); + CHECK(vectron->PulleeModeSwitch(true)); + CHECK(vectron->PulleeMode()); + CHECK_FALSE(vectron->brakes.spring.activate); + // already in it + CHECK_FALSE(vectron->PulleeModeSwitch(true)); + } + SUBCASE("a unit standing with its hand brake on") { + vehicle en57{definition::fiz("en57_v1/5bgb")}; + REQUIRE(en57->brakes.HandBrakePosition() > 0); + CHECK(en57->PulleeModeSwitch(true)); + CHECK(en57->brakes.HandBrakePosition() == 0); + } + SUBCASE("a locomotive ready to depart, its battery on") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.1}; + REQUIRE(vectron->lowVoltage.IsBatteryOn()); + CHECK(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->lowVoltage.IsBatteryOn()); + } +} + +TEST_CASE("pullee: the battery and the cabs of a vehicle prepared for hauling stay off, until it leaves the mode") { + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; + REQUIRE(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->BatterySwitch(true)); + CHECK_FALSE(vectron->lowVoltage.IsBatteryOn()); + CHECK_FALSE(vectron->CabActivisation()); + CHECK_FALSE(vectron->CabActivisation(true)); + CHECK(vectron->CabActive == 0); + vectron.run(5.0); + // the vigilance device and the cab signalling of a cab never activated stay out of it + CHECK_FALSE(vectron->SecuritySystem.is_braking()); + CHECK(vectron->brakes.emergencyValve.flow == 0.0); + + REQUIRE(vectron->PulleeModeSwitch(false)); + CHECK_FALSE(vectron->PulleeMode()); + CHECK(vectron->BatterySwitch(true)); + CHECK(vectron->lowVoltage.IsBatteryOn()); + CHECK(vectron->CabActivisation()); + CHECK(vectron->CabActive == 1); + // a vehicle driven from isn't one to haul + CHECK_FALSE(vectron->PulleeModeSwitch(true)); + CHECK_FALSE(vectron->PulleeMode()); +} + +TEST_CASE("pullee: a cab activated on a dead battery calls the emergency brake, which the mode keeps from happening") { + // the vigilance device of an activated cab brakes when it has no power + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + vehicle vectron{definition::fiz("vectron_v1/wariant_7w"), 0.0, "test", 1}; + vectron->InactiveCabFlag = 0; + if (pullee) { + REQUIRE(vectron->PulleeModeSwitch(true)); + } + CHECK(vectron->CabActivisation() == (false == pullee)); + vectron.run(0.5); + CHECK(vectron->SecuritySystem.is_braking() == (false == pullee)); + CHECK((vectron->brakes.emergencyValve.flow > 0.0) == (false == pullee)); + } +} + +TEST_CASE("pullee: the battery and cab commands of the train's driver pass a vehicle prepared for hauling by") { + // coupled with the control cable too, which a hauled vehicle normally isn't + for (auto const pullee : {false, true}) { + CAPTURE(pullee); + test::reseed_random(); + test::consist train; + auto &locomotive{train.add(definition::fiz("4e_v1/4e"), 1)}; + auto &hauled{train.add(definition::fiz("4e_v1/4e"))}; + auto &last{train.add(definition::fiz("4e_v1/4e"))}; + if (pullee) { + REQUIRE(hauled->PulleeModeSwitch(true)); + } + REQUIRE_FALSE(hauled->lowVoltage.IsBatteryOn()); + locomotive->BatterySwitch(true); + locomotive->CabActivisation(); + train.run(2.0); + CHECK(hauled->lowVoltage.IsBatteryOn() == (false == pullee)); + CHECK(hauled->CabActive == (pullee ? 0 : 1)); + // the vehicle behind it gets them either way + CHECK(last->lowVoltage.IsBatteryOn()); + CHECK(last->CabActive == 1); + } +} + +TEST_CASE("pullee: every real vehicle prepared for hauling runs free behind a locomotive, with no air of its own") { + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + if (false == can_be_hauled(path)) { + continue; + } + test::reseed_random(); + hauled_train train{definition::fiz(path), 60.0, true}; + auto const &hauled{train.hauled.physics()}; + drain_feed_air(train.hauled.physics()); + train.run(60.0); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); + CHECK(hauled.Fb() < 1.0); + CHECK(train.locomotive->brakePipe.Pressure() > 4.99); + CHECK(train.hauled.speed() > 40.0); + } +} + +TEST_CASE("pullee: every real vehicle standing braked releases once prepared for hauling and charged") { + for (auto const &path : test::real_vehicles()) { + CAPTURE(path); + test::reseed_random(); + if (false == can_be_hauled(path)) { + continue; + } + test::reseed_random(); + // hand brakes on, spring brakes switched on, cylinders half full, the pipe at 3.5 + hauled_train train{definition::fiz(path), 0.0, true}; + auto const &hauled{train.hauled.physics()}; + CHECK(hauled.brakes.HandBrakePosition() == 0); + CHECK_FALSE(hauled.brakes.spring.activate); + CHECK_FALSE(hauled.lowVoltage.IsBatteryOn()); + train.run(180.0); + CHECK(hauled.brakes.emergencyValve.flow == 0.0); + CHECK(hauled.brakes.cylinderPressure < 0.1); + // the cylinders of a few are still letting out the last of their air (6Dg, SM42, 810: 15-72 N) + CHECK(hauled.Fb() < 500.0); + } +} diff --git a/tests/unit/test_queries.cpp b/tests/unit/test_queries.cpp index d42232c2e..65f12b72d 100644 --- a/tests/unit/test_queries.cpp +++ b/tests/unit/test_queries.cpp @@ -16,23 +16,23 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") REQUIRE(wagon->Power < 0.1); struct damage { - int flag; + DamageSet flag; char const *locomotive; char const *wagon; }; for (auto const &[flag, locomotivetext, wagontext] : { - damage{0, "OK", "OK"}, - damage{dtrain_thinwheel, "Thin wheel", "Load shifted"}, - damage{dtrain_wheelwear, "Wheel wear", "Wheel wear"}, - damage{dtrain_bearing, "Bearing damaged", "Bearing damaged"}, - damage{dtrain_coupling, "Coupler broken", "Coupler broken"}, - damage{dtrain_loaddamage, "Ventilator damaged", "Load damaged"}, - damage{dtrain_loaddestroyed, "Engine damaged", "LOAD DESTROYED"}, - damage{dtrain_axle, "Axle broken", "Axle broken"}, - damage{dtrain_out, "DERAILED", "DERAILED"}, + damage{{}, "OK", "OK"}, + damage{VehicleDamage::thinWheel, "Thin wheel", "Load shifted"}, + damage{VehicleDamage::wheelWear, "Wheel wear", "Wheel wear"}, + damage{VehicleDamage::bearing, "Bearing damaged", "Bearing damaged"}, + damage{VehicleDamage::coupling, "Coupler broken", "Coupler broken"}, + damage{VehicleDamage::loadDamage, "Ventilator damaged", "Load damaged"}, + damage{VehicleDamage::loadDestroyed, "Engine damaged", "LOAD DESTROYED"}, + damage{VehicleDamage::axle, "Axle broken", "Axle broken"}, + damage{VehicleDamage::derailed, "DERAILED", "DERAILED"}, // the last flag of the list wins - damage{dtrain_bearing | dtrain_axle, "Axle broken", "Axle broken"}, - damage{255, "WRECKED", "WRECKED"}, + damage{VehicleDamage::bearing | VehicleDamage::axle, "Axle broken", "Axle broken"}, + damage{DamageSet::FromBits(255), "WRECKED", "WRECKED"}, }) { CAPTURE(flag); locomotive->DamageFlag = flag; @@ -41,8 +41,8 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") CHECK(wagon->EngineDescription(0) == wagontext); } // flat wheels count as worn ones - wagon->DamageFlag = 0; - wagon->WheelFlat = 6.0; + wagon->DamageFlag = {}; + wagon->SetWheelFlat(6.0); CHECK(wagon->EngineDescription(0) == "Wheel wear"); // nothing else is described CHECK(wagon->EngineDescription(1) == "Invalid qualifier"); @@ -51,7 +51,7 @@ TEST_CASE("queries: the damage of a vehicle as the driver's panel describes it") TEST_CASE("queries: the ammeters of a vehicle without power show the current of the ones it controls") { vehicle unpowered{definition::fiz("en57_v1/6ba_840")}; vehicle powered{definition::fiz("en57_v1/5bgb")}; - unpowered->Attach(end::rear, end::front, &powered.mover(), coupling::control, true, false); + unpowered->Attach(VehicleEnd::rear, VehicleEnd::front, &powered.physics(), Coupling::control, true, false); powered->Power = 600.0; powered->Itot = 321.7; unpowered->Power = 0.0; diff --git a/tests/unit/test_radio.cpp b/tests/unit/test_radio.cpp index b65cc2ced..45e86d540 100644 --- a/tests/unit/test_radio.cpp +++ b/tests/unit/test_radio.cpp @@ -7,22 +7,22 @@ TEST_CASE("radio: a radio switched on with the low voltage works") { test::vehicle vehicle{test::definition::load("wagon")}; - vehicle->Radio = true; - SUBCASE("24 V") { vehicle->Power24vIsAvailable = true; } - SUBCASE("110 V") { vehicle->Power110vIsAvailable = true; } + vehicle->SetRadio(true); + SUBCASE("24 V") { vehicle->lowVoltage.Set24vAvailableForTest(true); } + SUBCASE("110 V") { vehicle->lowVoltage.Set110vAvailableForTest(true); } CHECK(vehicle->RadioPowered()); } TEST_CASE("radio: a radio switched off or without the low voltage doesn't") { test::vehicle vehicle{test::definition::load("wagon")}; SUBCASE("switched off") { - vehicle->Radio = false; - vehicle->Power24vIsAvailable = true; + vehicle->SetRadio(false); + vehicle->lowVoltage.Set24vAvailableForTest(true); } SUBCASE("batteries off") { - vehicle->Radio = true; - vehicle->Power24vIsAvailable = false; - vehicle->Power110vIsAvailable = false; + vehicle->SetRadio(true); + vehicle->lowVoltage.Set24vAvailableForTest(false); + vehicle->lowVoltage.Set110vAvailableForTest(false); } CHECK_FALSE(vehicle->RadioPowered()); } @@ -32,27 +32,27 @@ TEST_CASE("radio: a radio switched off or without the low voltage doesn't") { TEST_CASE("radio: the radio fuse is closed by default") { test::vehicle vehicle{test::definition::load("wagon")}; - CHECK(vehicle->RadioFuse); + CHECK(vehicle->RadioFuse()); } TEST_CASE("radio: an opened radio fuse cuts the radio off") { test::vehicle vehicle{test::definition::load("wagon")}; - vehicle->Radio = true; - vehicle->Power24vIsAvailable = true; - vehicle->RadioFuse = false; + vehicle->SetRadio(true); + vehicle->lowVoltage.Set24vAvailableForTest(true); + vehicle->SetRadioFuse(false); CHECK_FALSE(vehicle->RadioPowered()); - vehicle->RadioFuse = true; + vehicle->SetRadioFuse(true); CHECK(vehicle->RadioPowered()); } TEST_CASE("radio: opening the radio fuse at a standstill resets the radio-stop, as switching the radio off does") { test::vehicle loco{test::definition::fiz("4e_v1/4e")}; - loco->Battery = true; - loco->Radio = true; + loco->lowVoltage.SetBatteryOnForTest(true); + loco->SetRadio(true); REQUIRE(loco->RadiostopSwitch(true)); loco->SecuritySystemCheck(0.1); - CHECK(loco->RadioStopFlag); - loco->RadioFuse = false; + CHECK(loco->RadioStopFlag()); + loco->SetRadioFuse(false); loco->SecuritySystemCheck(0.1); - CHECK_FALSE(loco->RadioStopFlag); + CHECK_FALSE(loco->RadioStopFlag()); } diff --git a/tests/unit/test_region_file.cpp b/tests/unit/test_region_file.cpp new file mode 100644 index 000000000..346823ae3 --- /dev/null +++ b/tests/unit/test_region_file.cpp @@ -0,0 +1,207 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" +#include "scene/regionfile.h" +#include "scene/sn_utils.h" + +#include +#include +#include +#include + +// the region file (.sbt), the static geometry of a scenery the game caches beside it: a file cut short or +// damaged is turned down before any of it is used, and the game writes it so that it is never left cut short + +namespace { + +std::uint32_t constexpr header{0x37305545}; // EU07 +std::uint32_t constexpr version{0x32544253}; // SBT2 +std::uint32_t constexpr sectionlimit{500 * 500}; + +struct section { + std::uint32_t index; + std::string data; +}; + +// the file as basic_region::serialize() lays it out: the section size covers the index, the size and the data +std::string region(std::vector
const &Sections, std::uint32_t const Header = header, std::uint32_t const Version = version) { + std::ostringstream output; + sn_utils::ls_uint32(output, Header); + sn_utils::ls_uint32(output, Version); + sn_utils::ls_uint32(output, static_cast(Sections.size())); + for (auto const §ion : Sections) { + sn_utils::ls_uint32(output, section.index); + sn_utils::ls_uint32(output, static_cast(scene::region_file::section_header_size + section.data.size())); + output << section.data; + } + return output.str(); +} + +std::string check(std::string const &File) { + std::istringstream input{File}; + return scene::region_file::check_layout(input, header, version, sectionlimit); +} + +// what a writer throws when it gives up +class writer_failure : public std::runtime_error { + public: + using std::runtime_error::runtime_error; +}; + +std::string read(std::filesystem::path const &Path) { + std::ifstream input{Path, std::ios::binary}; + return {std::istreambuf_iterator{input}, std::istreambuf_iterator{}}; +} + +} // namespace + +TEST_CASE("region file: a file laid out whole is accepted, with no sections or with many") { + CHECK(check(region({})) == ""); + CHECK(check(region({{0, ""}, {7, std::string(100, 'x')}, {sectionlimit - 1, std::string(3, '\0')}})) == ""); +} + +TEST_CASE("region file: a file cut short anywhere is turned down") { + auto const file{region({{12, std::string(40, 'a')}, {13, std::string(7, 'b')}, {250, std::string(64, 'c')}})}; + REQUIRE(check(file) == ""); + for (std::size_t length{0}; length < file.size(); ++length) { + CAPTURE(length); + CHECK(check(file.substr(0, length)) != ""); + } + // the count of the sections is checked against those present, and the length against where the last one ends + CHECK(check(file.substr(0, file.size() - 64 - 8)).find("ends after 2 of its 3 sections") != std::string::npos); + CHECK(check(file.substr(0, file.size() / 2)).find("ends inside section") != std::string::npos); +} + +TEST_CASE("region file: a file of another type or version is turned down") { + CHECK(check(region({{1, "x"}}, header, version + 1)).find("unrecognized type or version") != std::string::npos); + CHECK(check(region({{1, "x"}}, header + 1, version)).find("unrecognized type or version") != std::string::npos); + CHECK(check("EU0").find("unrecognized type or version") != std::string::npos); +} + +TEST_CASE("region file: sections the region can't hold, held twice, or of impossible sizes are turned down") { + CHECK(check(region({{sectionlimit, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{0xffffffffu, "x"}})).find("out of the 250000") != std::string::npos); + CHECK(check(region({{5, "x"}, {5, "y"}})).find("more than once") != std::string::npos); + + // a size smaller than the header of the section + auto file{region({{5, "abcd"}})}; + file[16] = 7; + file[17] = 0; + file[18] = 0; + file[19] = 0; + CHECK(check(file).find("less than its header takes") != std::string::npos); + // a size reaching past the end of the file + file[16] = 13; + CHECK(check(file).find("ends inside section 5") != std::string::npos); + // a size falling short of it + file[16] = 11; + CHECK(check(file).find("bytes past its last section") != std::string::npos); + // more sections than a region has + auto many{region({})}; + for (std::size_t byte{8}; byte < 12; ++byte) { + many[byte] = static_cast(0xff); + } + CHECK(check(many).find("more than the 250000") != std::string::npos); +} + +TEST_CASE("region file: the header of a section is read and checked") { + std::uint32_t index{0}; + std::uint32_t size{0}; + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size) == ""); + CHECK(index == 42); + CHECK(size == 11); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12, 6)}; + CHECK(scene::region_file::read_section_header(input, sectionlimit, index, size).find("ends inside a section header") != std::string::npos); + } + { + std::istringstream input{region({{42, "abc"}}).substr(12)}; + CHECK(scene::region_file::read_section_header(input, 42, index, size).find("out of the 42") != std::string::npos); + } +} + +TEST_CASE("region file: a string cut short by the end of the data ends there, rather than being read on forever") { + std::istringstream input{std::string{"abc"}}; + CHECK(sn_utils::d_str(input) == "abc"); + CHECK(input.fail()); + CHECK(sn_utils::d_str(input) == ""); + + std::istringstream whole{std::string{"abc\0def", 7}}; + CHECK(sn_utils::d_str(whole) == "abc"); + CHECK(whole.good()); +} + +TEST_CASE("region file: the bytes left in the data are known, so a count it can't hold is turned down before anything is made for it") { + std::istringstream input{std::string(100, 'x')}; + CHECK(sn_utils::remaining(input) == 100); + sn_utils::ld_uint32(input); + CHECK(sn_utils::remaining(input) == 96); + // asking doesn't move the reading on + CHECK(sn_utils::ld_uint32(input) == 0x78787878); + input.seekg(0, std::ios::end); + CHECK(sn_utils::remaining(input) == 0); + sn_utils::ld_uint32(input); + CHECK(input.fail()); + CHECK(sn_utils::remaining(input) == 0); +} + +TEST_CASE("region file: the file is written through a temporary one, which replaces the previous file when complete") { + test::scratch_folder folder{"region_file"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + auto const write = [&file](std::string const &Content) { + return scene::region_file::write_through_temporary(file.string(), [&Content](std::ostream &Output) { Output << Content; }); + }; + + SUBCASE("a new file") { + CHECK(write("first") == ""); + CHECK(read(file) == "first"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a previous file is replaced, a longer one entirely") { + REQUIRE(write("a much longer first version") == ""); + CHECK(write("second") == ""); + CHECK(read(file) == "second"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } + SUBCASE("a temporary file left by a write cut short earlier is written over") { + folder.write("scenery.sbt.tmp", "left over from a crash, longer than what follows"); + CHECK(write("third") == ""); + CHECK(read(file) == "third"); + CHECK_FALSE(std::filesystem::exists(temporary)); + } +} + +TEST_CASE("region file: a write which fails leaves the previous file, or none, and no temporary file") { + test::scratch_folder folder{"region_file_failed"}; + auto const file{folder.root() / "scenery.sbt"}; + auto const temporary{folder.root() / "scenery.sbt.tmp"}; + folder.write("scenery.sbt", "previous"); + + SUBCASE("the writer gives up half way") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + throw writer_failure("out of memory"); + })}; + CHECK(error.find("out of memory") != std::string::npos); + } + SUBCASE("the stream fails") { + auto const error{scene::region_file::write_through_temporary(file.string(), [](std::ostream &Output) { + Output << "half of the"; + Output.setstate(std::ios::badbit); + })}; + CHECK(error.find("can't write to file") != std::string::npos); + } + CHECK(read(file) == "previous"); + CHECK_FALSE(std::filesystem::exists(temporary)); + + SUBCASE("the temporary file can't be made") { + auto const missing{folder.root() / "no such folder" / "scenery.sbt"}; + auto const error{scene::region_file::write_through_temporary(missing.string(), [](std::ostream &Output) { Output << "x"; })}; + CHECK(error.find("can't write to file") != std::string::npos); + CHECK_FALSE(std::filesystem::exists(missing)); + } +} diff --git a/tests/unit/test_ring_room.cpp b/tests/unit/test_ring_room.cpp new file mode 100644 index 000000000..835072f75 --- /dev/null +++ b/tests/unit/test_ring_room.cpp @@ -0,0 +1,143 @@ +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorRingRoom.hpp" + +#include + +// the room a road leaving the side of a roundabout takes of the ring (eu07/maszyna GH#349): with the ring's bend +// counted, as many roads fit on a small roundabout as there's room for between their edges +namespace { + +double constexpr pi{3.14159265358979323846}; +// as the road editor has them: a junction takes the road it's made on past where the edges meet by the corner room, +// and between two junctions there's at least the shortest road left +double constexpr kCornerRoom{4.0}; +double constexpr kShortestRoad{2.0}; +// the roads the editor builds unless told otherwise: a lane each way, 3.5 m each, and a roundabout of a single lane +double constexpr kRoadHalfwidth{3.5}; +double constexpr kRingHalfwidth{1.75}; + +glm::dvec2 at(double const Radius, double const Angle) { return glm::dvec2{std::cos(Angle), std::sin(Angle)} * Radius; } +glm::dvec2 ahead(double const Angle) { return {-std::sin(Angle), std::cos(Angle)}; } + +// room of a road leaving the ring of the radius at the angle, turned from the way straight out by the slant (to the way ahead) +double room(double const Radius, double const Slant, bool const Ahead, double const Halfwidth = kRingHalfwidth, double const Branchhalfwidth = kRoadHalfwidth) { + double const angle{0.3}; + auto const outwards{at(1.0, angle)}; + auto const direction{outwards * std::cos(Slant) + ahead(angle) * std::sin(Slant)}; + return editor_ring::edge_room(glm::dvec2{0.0}, Radius, at(Radius, angle), direction, Ahead ? ahead(angle) : -ahead(angle), Halfwidth, Branchhalfwidth); +} + +// where the edges of two straight roads meet, measured along the first one, as the editor has it for a road leaving a straight road. +// Lean: the second one leans towards the side measured (the angle between them there is the acute one) +double straight_reach(double const Halfwidth, double const Branchhalfwidth, double const Angle, bool const Lean) { + return (Branchhalfwidth + (Lean ? 1.0 : -1.0) * Halfwidth * std::cos(Angle)) / std::sin(Angle); +} + +// whether the roads leaving straight out, evenly all around the ring, each get a junction: the junctions with what's left between them. +// Bend: the room measured on the ring, rather than as on a straight road; Shortest: the shortest piece left between two junctions. +// Arcs: a junction next to the end of an arc of the ring takes the rest of the arc when less than the shortest piece would be left +// of it, so in the worst case it grows by as much +bool fit(double const Radius, int const Roads, bool const Bend, double const Shortest, bool const Arcs) { + auto const side{Bend ? room(Radius, 0.0, true) : straight_reach(kRingHalfwidth, kRoadHalfwidth, pi / 2.0, true)}; + auto const junction{2.0 * (side + kCornerRoom)}; + return Roads * (junction + Shortest + (Arcs ? Shortest : 0.0)) <= 2.0 * pi * Radius; +} +bool fit(double const Radius, int const Roads, bool const Bend) { return fit(Radius, Roads, Bend, kShortestRoad, false); } +// as the editor has it now, wherever the roads join the ring +bool fits(double const Radius, int const Roads) { return fit(Radius, Roads, true, editor_ring::shortest_piece, true); } + +} // namespace + +TEST_CASE("ring room: on a very large ring the room is the one of a straight road") { + for (double const slant : {0.0, pi / 12.0, pi / 6.0, pi / 4.0, pi / 3.0}) { + CAPTURE(slant); + double const angle{pi / 2.0 - slant}; + CHECK(room(1.0e6, slant, true) == doctest::Approx(straight_reach(kRingHalfwidth, kRoadHalfwidth, angle, true)).epsilon(1e-4)); + CHECK(room(1.0e6, slant, false) == doctest::Approx(straight_reach(kRingHalfwidth, kRoadHalfwidth, angle, false)).epsilon(1e-4)); + } +} + +TEST_CASE("ring room: a road leaving straight out meets the outer edge where the circle reaches its edge") { + for (double const radius : {8.0, 15.0, 40.0}) { + CAPTURE(radius); + double const expected{radius * std::asin(kRoadHalfwidth / (radius + kRingHalfwidth))}; + CHECK(room(radius, 0.0, true) == doctest::Approx(expected)); + CHECK(room(radius, 0.0, false) == doctest::Approx(expected)); + // never more than on a straight road + CHECK(room(radius, 0.0, true) < kRoadHalfwidth); + } +} + +TEST_CASE("ring room: a slanted road takes less on the side it leans away from") { + for (double const radius : {8.0, 15.0, 50.0}) { + for (double const slant : {pi / 6.0, pi / 4.0}) { + CAPTURE(radius); + CAPTURE(slant); + auto const towards{room(radius, slant, true)}; + auto const away{room(radius, slant, false)}; + CHECK(away >= 0.0); + CHECK(away < towards); + // the editor took the room of the acute corner on both sides + CHECK(towards < straight_reach(kRingHalfwidth, kRoadHalfwidth, pi / 2.0 - slant, true)); + } + } + // on a straight road the obtuse corner takes less than the acute one too + CHECK(room(1.0e6, pi / 4.0, false) < room(1.0e6, pi / 4.0, true)); + // leaving the smallest ring as sharply as the editor allows, 30 degrees off it, the edge on the side the road leans away from + // is outside the ring all along: there's no point to measure to, and the editor keeps the room it took before + CHECK(room(8.0, pi / 3.0, false) < 0.0); + CHECK(room(8.0, pi / 3.0, true) > 0.0); + CHECK(room(15.0, pi / 3.0, false) >= 0.0); +} + +TEST_CASE("ring room: none for a road going inwards") { + CHECK(room(15.0, pi * 0.75, true) < 0.0); + CHECK(room(15.0, pi, true) < 0.0); + CHECK(editor_ring::edge_room(glm::dvec2{0.0}, 0.0, glm::dvec2{1.0, 0.0}, glm::dvec2{1.0, 0.0}, glm::dvec2{0.0, 1.0}, 1.0, 1.0) < 0.0); +} + +TEST_CASE("ring room: a road wider than the ring is round still meets its edge, sooner than on a straight road") { + // two lanes each way on the smallest roundabout: the edge of the road starts outside the ring + double const halfwidth{7.0}; + double const radius{8.0}; + double const expected{radius * std::atan2(halfwidth, std::sqrt((radius + kRingHalfwidth) * (radius + kRingHalfwidth) - halfwidth * halfwidth))}; + CHECK(room(radius, 0.0, true, kRingHalfwidth, halfwidth) == doctest::Approx(expected)); + CHECK(room(radius, 0.0, true, kRingHalfwidth, halfwidth) < halfwidth); +} + +TEST_CASE("ring room: roads joined to roundabouts of the radii the editor allows") { + // the smallest roundabout took two roads; three were too many for it + CHECK(fit(8.0, 2, false)); + CHECK_FALSE(fit(8.0, 3, false)); + CHECK(fit(8.0, 3, true)); + // four roads from 11 m + CHECK(fit(11.0, 4, true)); + CHECK(fit(15.0, 4, true)); + // six from 16 m, where they took 17 m before + CHECK_FALSE(fit(16.0, 6, false)); + CHECK(fit(16.0, 6, true)); + CHECK(fit(25.0, 6, true)); + // and more on the large ones + CHECK(fit(50.0, 8, true)); + CHECK(fit(200.0, 30, true)); +} + +TEST_CASE("ring room: a short piece of the ring is left between junctions, so small roundabouts take three or four roads") { + // the ring goes on past a piece of it, which can be much shorter than a road of its own + CHECK(editor_ring::shortest_piece < kShortestRoad); + CHECK(editor_ring::shortest_piece > 0.25); // further apart than ends taken for joined + // with the shortest road left between them, and a junction growing by as much next to the end of an arc, three roads + // didn't always fit on the smallest roundabout, nor four on one of 10 m + CHECK_FALSE(fit(8.0, 3, true, kShortestRoad, true)); + CHECK_FALSE(fit(10.0, 4, true, kShortestRoad, false)); + // they do now, wherever they join the ring + CHECK(fits(8.0, 3)); + CHECK(fits(10.0, 4)); + CHECK(fits(9.6, 4)); + // four on the smallest one would take smaller corners + CHECK_FALSE(fits(8.0, 4)); + // and the larger ones take more + CHECK(fits(15.0, 6)); + CHECK(fits(25.0, 8)); +} diff --git a/tests/unit/test_road_escape.cpp b/tests/unit/test_road_escape.cpp new file mode 100644 index 000000000..31fbc1a21 --- /dev/null +++ b/tests/unit/test_road_escape.cpp @@ -0,0 +1,44 @@ +// Esc in the road window (GH#348): the first one gives up what is going on, the next one goes back to the selection + +#include "stdafx.h" +#include "doctest.h" +#include "editor/editorRoad.hpp" + +namespace { + +constexpr int select_tool{0}; +constexpr int build_tool{1}; +constexpr int place_tool{2}; + +} // namespace + +TEST_CASE("Esc with the build tool and no road being drawn goes back to the selection") { + CHECK(editor_road::tool_after_escape(build_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while a road is being drawn or led out of a road or a junction keeps the build tool") { + CHECK(editor_road::tool_after_escape(build_tool, true, false) == build_tool); +} + +TEST_CASE("Esc with the place tool goes back to the selection, the tool has nothing being drawn") { + CHECK(editor_road::tool_after_escape(place_tool, false, false) == select_tool); +} + +TEST_CASE("Esc while the selected points are dragged up or down keeps the tool, the drag is given up") { + CHECK(editor_road::tool_after_escape(select_tool, false, true) == select_tool); + CHECK(editor_road::tool_after_escape(build_tool, false, true) == build_tool); +} + +TEST_CASE("Esc with the selection tool stays with it") { + CHECK(editor_road::tool_after_escape(select_tool, false, false) == select_tool); +} + +TEST_CASE("two Esc presses from the build tool in the middle of a road: the road given up, then the selection") { + auto tool{build_tool}; + bool drawing{true}; + tool = editor_road::tool_after_escape(tool, drawing, false); + drawing = false; // what the first Esc gives up + CHECK(tool == build_tool); + tool = editor_road::tool_after_escape(tool, drawing, false); + CHECK(tool == select_tool); +} diff --git a/tests/unit/test_road_surface_type.cpp b/tests/unit/test_road_surface_type.cpp new file mode 100644 index 000000000..dfe7e14a1 --- /dev/null +++ b/tests/unit/test_road_surface_type.cpp @@ -0,0 +1,161 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "editor/editorRoadLimits.hpp" +#include "utilities/parser.h" + +#include +#include + +// the type of a road's surface (eu07/maszyna GH#347): a dirt road, a track between fields, can be laid out tighter than +// a paved one; the type is saved with the road, and the roads made before the types load and save as they did + +namespace { + +// what the scenery entry of a road says about its surface, read the way road_node::import_from() reads it: +// a road which doesn't say what it's made of is paved +struct surface_read +{ + std::string material{"asphaltdark1"}; + road_surface_type type{road_surface_type::paved}; + float texturelength{4.f}; + bool bad{false}; // an unknown type was named + std::string next; // the token which follows the read properties +}; + +surface_read read(std::string const &Entry) { + surface_read result; + cParser parser(Entry, cParser::buffer_TEXT); + auto token{parser.getToken()}; + while (false == token.empty() && token != "endroad") { + if (token == "surface") { + result.material = parser.getToken(); + } + else if (token == "surfacetype") { + if (false == road_surface::from_name(parser.getToken(), result.type)) + result.bad = true; + } + else if (token == "texlength") { + parser.getTokens(); + parser >> result.texturelength; + } + else { + result.next = token; + break; + } + token = parser.getToken(); + } + return result; +} + +// the appearance part of the scenery entry, written the way road_node::export_as_text_() writes it +std::string write(std::string const &Material, road_surface_type const Type, float const Texturelength) { + std::ostringstream output; + output << "surface " << Material << ' ' << "texlength " << Texturelength << ' '; + output << road_surface::entry(Type); + output << "side left shoulder 1.5 grass "; + return output.str(); +} + +} // namespace + +TEST_CASE("road surface type: a paved road keeps the limits every road had before the types") { + // the values editorRoad.cpp had as kTightestRadius, kShortestRoad, kSharpestBranch and in editor_road::plan() + auto const paved{road_limits_for(road_surface_type::paved)}; + CHECK(paved.tightest_radius == doctest::Approx(6.0)); + CHECK(paved.shortest_road == doctest::Approx(2.0)); + CHECK(paved.sharpest_branch == doctest::Approx(glm::radians(30.0))); + CHECK(paved.tied_lead == doctest::Approx(0.1)); + CHECK(paved.widest_turn == doctest::Approx(glm::radians(170.0))); +} + +TEST_CASE("road surface type: a dirt road is laid out more freely in every respect") { + auto const paved{road_limits_for(road_surface_type::paved)}; + auto const dirt{road_limits_for(road_surface_type::dirt)}; + // a bend a tractor makes on a single lane track + CHECK(dirt.tightest_radius < paved.tightest_radius); + CHECK(dirt.tightest_radius > 0.0); + CHECK(dirt.shortest_road < paved.shortest_road); + CHECK(dirt.shortest_road > 0.0); + CHECK(dirt.sharpest_branch < paved.sharpest_branch); + CHECK(dirt.sharpest_branch > 0.0); + // an end may lead off square to the way to the other end, but not away from it + CHECK(dirt.tied_lead < paved.tied_lead); + CHECK(dirt.tied_lead >= 0.0); + // a hairpin: the arc may turn past a half circle + CHECK(dirt.widest_turn > glm::radians(180.0)); + CHECK(dirt.widest_turn < glm::radians(360.0)); +} + +TEST_CASE("road surface type: no bend is tighter than the road is wide") { + auto const paved{road_limits_for(road_surface_type::paved)}; + auto const dirt{road_limits_for(road_surface_type::dirt)}; + // a single 3 m lane: the limit of the type + CHECK(editor_road_limits::tightest_bend(dirt, 1.5) == doctest::Approx(dirt.tightest_radius)); + // the layout the tool starts with, a 3.5 m lane each way: the inner edge 3.5 m from the axis keeps its room from the centre + CHECK(editor_road_limits::tightest_bend(dirt, 3.5) == doctest::Approx(3.5 + editor_road_limits::inner_edge_room)); + CHECK(editor_road_limits::tightest_bend(dirt, 3.5) > dirt.tightest_radius); + // a paved road of that layout keeps the limit it had + CHECK(editor_road_limits::tightest_bend(paved, 3.5) == doctest::Approx(paved.tightest_radius)); + // and a wide one is held to its width + CHECK(editor_road_limits::tightest_bend(paved, 7.0) == doctest::Approx(7.0 + editor_road_limits::inner_edge_room)); +} + +TEST_CASE("road surface type: the types go by their scenery names") { + for (auto const type : {road_surface_type::paved, road_surface_type::dirt}) { + CAPTURE(road_surface::name(type)); + road_surface_type read{type == road_surface_type::paved ? road_surface_type::dirt : road_surface_type::paved}; + CHECK(road_surface::from_name(road_surface::name(type), read)); + CHECK(read == type); + } + CHECK(std::string{road_surface::name(road_surface_type::paved)} == "paved"); + CHECK(std::string{road_surface::name(road_surface_type::dirt)} == "dirt"); + // an unknown name changes nothing + road_surface_type type{road_surface_type::dirt}; + CHECK_FALSE(road_surface::from_name("gravel", type)); + CHECK(type == road_surface_type::dirt); + CHECK_FALSE(road_surface::from_name("", type)); + CHECK(type == road_surface_type::dirt); +} + +TEST_CASE("road surface type: a paved road is saved as the roads were before the types") { + CHECK(road_surface::entry(road_surface_type::paved).empty()); + CHECK(write("asphaltdark1", road_surface_type::paved, 4.f) == "surface asphaltdark1 texlength 4 side left shoulder 1.5 grass "); + // and an entry of a road made before the types reads paved, with what follows read as before + auto const old{read("surface asphalt2 texlength 6 side left shoulder 1.5 grass endroad")}; + CHECK(old.type == road_surface_type::paved); + CHECK(old.material == "asphalt2"); + CHECK(old.texturelength == doctest::Approx(6.f)); + CHECK(old.next == "side"); + CHECK_FALSE(old.bad); +} + +TEST_CASE("road surface type: a dirt road is saved with its type and read back") { + auto const text{write(road_surface::default_material(road_surface_type::dirt), road_surface_type::dirt, 5.f)}; + CHECK(text == "surface droga_polna texlength 5 surfacetype dirt side left shoulder 1.5 grass "); + auto const back{read(text)}; + CHECK(back.type == road_surface_type::dirt); + CHECK(back.material == "droga_polna"); + CHECK(back.texturelength == doctest::Approx(5.f)); + CHECK(back.next == "side"); + CHECK_FALSE(back.bad); + // and written again it's the same + CHECK(write(back.material, back.type, back.texturelength) == text); + // the type is read wherever it stands among the properties, and an explicit paved reads as the default + CHECK(read("surfacetype dirt surface droga_polna endroad").type == road_surface_type::dirt); + CHECK(read("surface asphaltdark1 surfacetype paved endroad").type == road_surface_type::paved); +} + +TEST_CASE("road surface type: an unknown type leaves the road paved") { + auto const back{read("surface asphaltdark1 surfacetype cobbles texlength 4 side")}; + CHECK(back.bad); + CHECK(back.type == road_surface_type::paved); + // the unknown name is taken as the value of the type, not as the next property + CHECK(back.texturelength == doctest::Approx(4.f)); + CHECK(back.next == "side"); +} + +TEST_CASE("road surface type: a road made dirt or paved gets the surface of the type") { + CHECK(std::string{road_surface::default_material(road_surface_type::paved)} == "asphaltdark1"); + CHECK(std::string{road_surface::default_material(road_surface_type::dirt)} == "droga_polna"); +} diff --git a/tests/unit/test_script_screen_drawing.cpp b/tests/unit/test_script_screen_drawing.cpp index ff822b02d..a68857ebe 100644 --- a/tests/unit/test_script_screen_drawing.cpp +++ b/tests/unit/test_script_screen_drawing.cpp @@ -5,6 +5,7 @@ #include #include +#include #include // the drawing the Lua screens get from the game: fonts read as scripts/led_util.py reads them, text and images @@ -85,6 +86,44 @@ TEST_CASE("script screen drawing: a description without glyphs, or one wider tha CHECK_FALSE(font->find(U'w').lit(4, 0)); } +TEST_CASE("script screen drawing: a glyph wider than the largest image is skipped") { + auto const pixels{image(2, 1, {})}; + auto const font{bitmap_font::parse(pixels, 2, 1, "//\nw5000\nv1\nx2147483647\n")}; + REQUIRE(font.has_value()); + // not in the font: the fallback, its first glyph + CHECK(font->find(U'w').width() == 1); + CHECK(font->find(U'x').width() == 1); + CHECK(font->find(U'v').width() == 1); + // the largest one is taken + auto const widest{bitmap_font::parse(pixels, 2, 1, "//\nw4096\n")}; + REQUIRE(widest.has_value()); + CHECK(widest->find(U'w').width() == 4096); +} + +TEST_CASE("script screen drawing: a font of too many glyphs, too many columns or too large an image is refused") { + auto const pixels{image(2, 1, {})}; + // more glyphs than any font has + std::string many{"//\n"}; + for (char32_t character = 0x100; character < 0x100 + 5000; ++character) { + // the character in UTF-8 (two bytes up to 0x7FF, three above), then its width + if (character < 0x800) { + many += static_cast(0xC0 | (character >> 6)); + } + else { + many += static_cast(0xE0 | (character >> 12)); + many += static_cast(0x80 | ((character >> 6) & 0x3F)); + } + many += static_cast(0x80 | (character & 0x3F)); + many += "0\n"; + } + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, many).has_value()); + // glyphs side by side much wider than the largest image + CHECK_FALSE(bitmap_font::parse(pixels, 2, 1, "//\na4000\nb4000\nc4000\n").has_value()); + // an image taller than the largest one + std::vector const tall(static_cast(1) * 5000 * 4, 255); + CHECK_FALSE(bitmap_font::parse(tall, 1, 5000, "//\na1\n").has_value()); +} + TEST_CASE("script screen drawing: text is drawn from x rightwards and returns where it ends") { auto const pixels{image(4, 1, {{0, 0}, {1, 0}, {3, 0}})}; auto const font{bitmap_font::parse(pixels, 4, 1, "//\na2\nb1\n")}; diff --git a/tests/unit/test_script_screen_host.cpp b/tests/unit/test_script_screen_host.cpp index 355b9b9e8..519e928de 100644 --- a/tests/unit/test_script_screen_host.cpp +++ b/tests/unit/test_script_screen_host.cpp @@ -2,23 +2,27 @@ #include "doctest.h" // the script screen host (scripting/scriptscreens.cpp) with the real runtimes: a script reads its input, draws an -// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped; -// a Lua script can't reach files, the system or precompiled code. the Lua cases need WITH_LUA, the WebAssembly ones -// WITH_WASM +// image that goes to the screen's texture, bottom row first, and sends a command; a script stuck in a loop is stopped, +// even when it catches the error; a Lua script can't reach files, the system, precompiled code or the metatables of the +// api; what a call may send, log, read or make is capped. the Lua cases need WITH_LUA, the WebAssembly ones WITH_WASM #include "scripting/scriptscreens.h" +#include "scripting/scriptscreenprogram.h" #include "input/command.h" #include "interfaces/ITexture.h" #include "utilities/Globals.h" #include "utilities/dictionary.h" +#include #include #include #include #include #include #include +#include #include +#include #include #include #include @@ -142,6 +146,47 @@ void refresh(script_screen_queue &Queue, std::shared_ptr const &S Queue.submit(Screen, std::move(Input), Vehicle); } +// runs frames for a while: long enough for the worker to load and run a screen that was submitted +void run_frames(script_screen_queue &Queue) { + for (int frame = 0; frame < 40; ++frame) { + Queue.update(); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } +} + +// the limits of the sandbox (scripting/scriptscreenprogram.h), as the tests expect them +constexpr std::size_t commands_per_call{64}; +constexpr std::size_t log_lines_per_call{32}; +constexpr std::size_t log_line_length{1024}; +constexpr std::size_t screen_file_size{16 * 1024 * 1024}; + +} // namespace + +// the lines logged while the object lives, kept by the engine stubs (engine_stubs.cpp) +void unit_tests_log_capture(bool Enabled); +std::vector unit_tests_logged_lines(); + +namespace { + +class log_capture { + public: + log_capture() { unit_tests_log_capture(true); } + ~log_capture() { unit_tests_log_capture(false); } + log_capture(log_capture const &) = delete; + log_capture &operator=(log_capture const &) = delete; + + // the lines logged so far with the text in them + std::vector lines_with(std::string_view const Text) const { + std::vector result; + for (auto &line : unit_tests_logged_lines()) { + if (line.find(Text) != std::string::npos) { + result.push_back(std::move(line)); + } + } + return result; + } +}; + } // namespace TEST_CASE("script screens: a language that doesn't run gets no screens") { @@ -202,21 +247,54 @@ constexpr std::array spin_module{ 0x64, 0x65, 0x72, 0x00, 0x02, 0x0a, 0x15, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x09, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x41, 0x00, 0x0b}; +// "flood": screen_render sends the command "cmdtest" 1000 times (with the parameters (i, 0)), then logs a line of +// 4000 'a' 100 times, and returns 0: +// (import "eu07" "command" (func $command (param i32 i32 i32 i32))) +// (import "eu07" "log" (func $log (param i32 i32))) +// (memory (export "memory") 1) +// (data (i32.const 0) "cmdtest") +// (func (export "screen_width") (result i32) i32.const 2) +// (func (export "screen_height") (result i32) i32.const 2) +// (func (export "screen_render") (result i32) (local $i i32) +// ;; for i in 0..1000: (call $command (i32.const 0) (i32.const 7) (local.get $i) (i32.const 0)) +// ;; for i in 0..4000: (i32.store8 (i32.add (local.get $i) (i32.const 64)) (i32.const 97)) +// ;; for i in 0..100: (call $log (i32.const 64) (i32.const 4000)) +// (i32.const 0)) +constexpr std::array flood_module{ + 0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00, 0x01, 0x11, 0x03, 0x60, 0x04, 0x7f, 0x7f, 0x7f, + 0x7f, 0x00, 0x60, 0x02, 0x7f, 0x7f, 0x00, 0x60, 0x00, 0x01, 0x7f, 0x02, 0x1b, 0x02, 0x04, 0x65, + 0x75, 0x30, 0x37, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x00, 0x00, 0x04, 0x65, 0x75, + 0x30, 0x37, 0x03, 0x6c, 0x6f, 0x67, 0x00, 0x01, 0x03, 0x04, 0x03, 0x02, 0x02, 0x02, 0x05, 0x03, + 0x01, 0x00, 0x01, 0x07, 0x39, 0x04, 0x06, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x02, 0x00, 0x0c, + 0x73, 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x77, 0x69, 0x64, 0x74, 0x68, 0x00, 0x02, 0x0d, 0x73, + 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x00, 0x03, 0x0d, 0x73, + 0x63, 0x72, 0x65, 0x65, 0x6e, 0x5f, 0x72, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x00, 0x04, 0x0a, 0x81, + 0x01, 0x03, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x04, 0x00, 0x41, 0x02, 0x0b, 0x75, 0x01, 0x01, 0x7f, + 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe8, 0x07, 0x4e, 0x0d, 0x01, + 0x41, 0x00, 0x41, 0x07, 0x20, 0x00, 0x41, 0x00, 0x10, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, + 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, + 0xa0, 0x1f, 0x4e, 0x0d, 0x01, 0x20, 0x00, 0x41, 0xc0, 0x00, 0x6a, 0x41, 0xe1, 0x00, 0x3a, 0x00, + 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, 0x00, 0x21, 0x00, + 0x02, 0x40, 0x03, 0x40, 0x20, 0x00, 0x41, 0xe4, 0x00, 0x4e, 0x0d, 0x01, 0x41, 0xc0, 0x00, 0x41, + 0xa0, 0x1f, 0x10, 0x01, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x21, 0x00, 0x0c, 0x00, 0x0b, 0x0b, 0x41, + 0x00, 0x0b, 0x0b, 0x0d, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x07, 0x63, 0x6d, 0x64, 0x74, 0x65, 0x73, + 0x74}; + } // namespace TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to its vehicle") { sent_commands().clear(); script_folder const folder{"wasm_paint"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); REQUIRE(queue.runs(script_language::wasm)); recording_texture texture; - auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; REQUIRE(screen != nullptr); // the same key, the same screen - CHECK(queue.acquire(request(script_language::wasm, module, "cab", &texture)) == screen); + CHECK(queue.acquire(request(script_language::wasm, module_path, "cab", &texture)) == screen); refresh(queue, screen, speed(5.0), 42); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0 && false == sent_commands().empty(); })); @@ -243,13 +321,13 @@ TEST_CASE("wasm screens: a cab screen draws from its input and sends commands to TEST_CASE("wasm screens: the image goes up again when the texture is made anew, and waits while it isn't there") { sent_commands().clear(); script_folder const folder{"wasm_reupload"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); recording_texture texture; texture.ready = false; - auto const screen{queue.acquire(request(script_language::wasm, module, "cab", &texture))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "cab", &texture))}; refresh(queue, screen, speed(9.0), 1); REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); queue.update(); @@ -272,12 +350,12 @@ TEST_CASE("wasm screens: the image goes up again when the texture is made anew, TEST_CASE("wasm screens: a screen outside the cab draws, but its commands are dropped") { sent_commands().clear(); script_folder const folder{"wasm_sign"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; script_screen_queue queue; REQUIRE(queue.init()); recording_texture texture; - auto const screen{queue.acquire(request(script_language::wasm, module, "sign", &texture, script_screen_kind::external))}; + auto const screen{queue.acquire(request(script_language::wasm, module_path, "sign", &texture, script_screen_kind::external))}; refresh(queue, screen, speed(3.0), 0); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); queue.update(); @@ -310,13 +388,13 @@ TEST_CASE("wasm screens: a screen stuck in a loop is stopped, and the others kee TEST_CASE("wasm screens: the screens outlive the queue without harm") { script_folder const folder{"wasm_outlive"}; - auto const module{folder.write("paint.wasm", paint_module)}; + auto const module_path{folder.write("paint.wasm", paint_module)}; std::shared_ptr screen; recording_texture texture; { script_screen_queue queue; REQUIRE(queue.init()); - screen = queue.acquire(request(script_language::wasm, module, "cab", &texture)); + screen = queue.acquire(request(script_language::wasm, module_path, "cab", &texture)); refresh(queue, screen, speed(4.0), 1); REQUIRE(run_until(queue, [&texture] { return texture.uploads > 0; })); } @@ -325,6 +403,60 @@ TEST_CASE("wasm screens: the screens outlive the queue without harm") { screen.reset(); } +TEST_CASE("wasm screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"wasm_flood"}; + auto const module{folder.write("flood.wasm", flood_module)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the first ones go, the rest is dropped + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + + auto const lines{log.lines_with("aaaaaaaaaa")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < module.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("wasm screens: a module larger than the limit isn't loaded") { + // the screen of "paint", with a custom section that makes the file larger than a screen may read + std::vector bytes(paint_module.begin(), paint_module.end()); + auto const payload{screen_file_size}; + auto size{static_cast(payload + 2)}; // the name: its length and one letter + bytes.push_back(0x00); + do { + auto const low{static_cast(size & 0x7f)}; + size >>= 7; + bytes.push_back(size != 0 ? static_cast(low | 0x80) : low); + } while (size != 0); + bytes.push_back(0x01); + bytes.push_back('x'); + bytes.resize(bytes.size() + payload, 0); + + script_folder const folder{"wasm_large"}; + auto const module{folder.write("large.wasm", bytes)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::wasm, module, "large", &texture))}; + refresh(queue, screen, speed(1.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + queue.exit(); +} + #endif #ifdef WITH_LUA @@ -750,4 +882,558 @@ TEST_CASE("lua screens: an image read after led_post has its post-processing don queue.exit(); } +namespace { + +// scripts that catch the error of the instruction limit and go on looping +constexpr std::string_view pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(spin) end end } +)"}; + +constexpr std::string_view nested_pcall_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do pcall(function() while true do pcall(spin) end end) end end } +)"}; + +constexpr std::string_view xpcall_spin_script{R"( +local function spin() while true do end end +local function handler() while true do end end +return { render = function(state) while true do xpcall(spin, handler) end end } +)"}; + +constexpr std::string_view coroutine_spin_script{R"( +local function spin() while true do end end +return { render = function(state) while true do coroutine.resume(coroutine.create(spin)) end end } +)"}; + +// white when the metatable of an image can't be reached, and its __gc can't be called +constexpr std::string_view metatable_script{R"( +local image = eu07.image(1, 1) +local metatable = getmetatable(image) +local locked = type(metatable) ~= "table" +-- only where the metatable is locked: an unlocked one would destroy the image twice +local collected = locked and pcall(function() return metatable.__gc(image) end) +local usable = image:width() == 1 +return { + render = function(state) + return eu07.image(1, 1, (locked and not collected and usable) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when string.rep refuses a result over the limit and makes the ones under it +constexpr std::string_view repeat_script{R"( +local huge = pcall(string.rep, "x", 64 * 1024 * 1024) +local method = pcall(function() return ("ab"):rep(16 * 1024 * 1024) end) +local endless = pcall(string.rep, "x", 1e300) +local fits = #string.rep("x", 1024 * 1024) == 1024 * 1024 and ("ab"):rep(3) == "ababab" and ("x"):rep(0) == "" and ("x"):rep(-1) == "" +return { + render = function(state) + return eu07.image(1, 1, (not huge and not method and not endless and fits) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when an image larger than a screen can be isn't decoded, and a small one is +constexpr std::string_view large_png_script{R"( +local sprite = pcall(eu07.sprite, "large") +local font = pcall(eu07.font, "large") +local small = pcall(eu07.sprite, "small") +return { + render = function(state) + return eu07.image(1, 1, (not sprite and not font and small) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a long command name first, then too many commands and log lines for one call +constexpr std::string_view flood_script{R"( +return { + render = function(state) + eu07.command("cmdtest" .. ("q"):rep(100), 1, 0) + for i = 0, 999 do eu07.command("cmdtest", i, 0) end + for i = 1, 100 do eu07.log(("y"):rep(5000)) end + return eu07.image(1, 1) + end +} +)"}; + +// white when a file larger than a screen may read, and a folder, read as nothing +constexpr std::string_view large_file_script{R"( +local large = eu07.read_file("large.bin") +local folder = eu07.read_file("data") +local small = eu07.read_file("data/small.txt") +return { + render = function(state) + return eu07.image(1, 1, (large == nil and folder == nil and small == "small") and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a white image of the size, as a .png +std::vector white_png(int const Width, int const Height) { + std::vector const pixels(static_cast(Width) * Height * 4, 255); + std::vector result; + auto const append{[](void *Target, void *Data, int const Size) { + auto *bytes{static_cast(Data)}; + static_cast *>(Target)->insert(static_cast *>(Target)->end(), bytes, bytes + Size); + }}; + stbi_write_png_to_func(append, &result, Width, Height, 4, pixels.data(), Width * 4); + return result; +} + +// runs the script of a screen once; the first pixel of what it drew, or -1 when it drew nothing (after a wait) +int first_pixel(std::string const &Script, std::string const &Key) { + script_screen_queue queue; + REQUIRE(queue.init()); + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, Script, Key, &texture))}; + refresh(queue, screen, speed(0.0), 1); + auto const drawn{run_until(queue, [&texture] { return texture.uploads > 0; })}; + queue.exit(); + return drawn && false == texture.pixels.empty() ? texture.pixels[0] : -1; +} + +} // namespace + +TEST_CASE("lua screens: a script catching the instruction limit with pcall, xpcall or a coroutine is stopped all the same") { + script_folder const folder{"lua_pcall_spin"}; + auto const painting{folder.write("paint.lua", paint_script)}; + for (auto const &[name, code] : {std::pair{"pcall.lua", pcall_spin_script}, std::pair{"nested.lua", nested_pcall_spin_script}, + std::pair{"xpcall.lua", xpcall_spin_script}, std::pair{"coroutine.lua", coroutine_spin_script}}) { + CAPTURE(name); + auto const spinning{folder.write(name, code)}; + // a worker stuck for good would keep the queue's destructor waiting: such a queue is left behind, so the test + // fails instead of hanging the run + auto *queue{new script_screen_queue}; // NOSONAR see above + REQUIRE(queue->init()); + + recording_texture stuck; + recording_texture working; + auto const first{queue->acquire(request(script_language::lua, spinning, "spin", &stuck))}; + auto const second{queue->acquire(request(script_language::lua, painting, "paint", &working))}; + refresh(*queue, first, speed(1.0), 1); + refresh(*queue, second, speed(2.0), 1); + + auto const stopped{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(stopped); + if (false == stopped) { + // the stuck worker doesn't touch the textures, and nothing uploads to them any more + continue; + } + CHECK(stuck.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above + } +} + +TEST_CASE("lua screens: xpcall passes the arguments, and the error to its handler") { + script_folder const folder{"lua_xpcall"}; + constexpr std::string_view script{R"( +local ok1, sum = xpcall(function(a, b) return a + b end, function(e) return "handled" end, 2, 3) +local ok2, handled = xpcall(function() error("boom") end, function(e) return "handled: " .. tostring(e) end) +local ok3 = xpcall(function() error("boom") end, function(e) error("again") end) +local good = ok1 and sum == 5 and not ok2 and handled:find("handled: .*boom") ~= nil and not ok3 +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + CHECK(first_pixel(folder.write("xpcall.lua", script), "xpcall") == 255); +} + +TEST_CASE("lua screens: the metatables of the api objects can't be reached from a script") { + script_folder const folder{"lua_metatable"}; + CHECK(first_pixel(folder.write("metatable.lua", metatable_script), "metatable") == 255); +} + +TEST_CASE("lua screens: string.rep makes no string over the limit") { + script_folder const folder{"lua_rep"}; + CHECK(first_pixel(folder.write("rep.lua", repeat_script), "rep") == 255); +} + +TEST_CASE("lua screens: a .png larger than a screen image isn't decoded") { + script_folder const folder{"lua_large_png"}; + folder.write("large.png", white_png(5000, 1)); + folder.write("large.txt", std::string_view{"//\na1\n"}); + folder.write("small.png", white_png(2, 2)); + CHECK(first_pixel(folder.write("png.lua", large_png_script), "png") == 255); +} + +TEST_CASE("lua screens: the commands and the log lines of one call are capped") { + sent_commands().clear(); + log_capture const log; + script_folder const folder{"lua_flood"}; + auto const script{folder.write("flood.lua", flood_script)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "flood", &texture))}; + refresh(queue, screen, speed(0.0), 3); + REQUIRE(run_until(queue, [] { return false == sent_commands().empty(); })); + queue.update(); + // the long name is dropped, of the rest the first ones go + CHECK(sent_commands().size() == commands_per_call); + CHECK(sent_commands().front().first.param1 == 0.0); + CHECK(sent_commands().back().first.param1 == static_cast(commands_per_call - 1)); + // the command of the long name didn't get as far as the engine's command names + CHECK(log.lines_with("not found").empty()); + + auto const lines{log.lines_with("yyyyyyyyyy")}; + REQUIRE(false == lines.empty()); + CHECK(lines.size() <= log_lines_per_call); + auto const longest{std::ranges::max(lines, {}, [](std::string const &Line) { return Line.size(); })}; + CHECK(longest.size() < script.size() + log_line_length + 100); + queue.exit(); +} + +TEST_CASE("lua screens: a file larger than the limit, or a folder, reads as nothing") { + script_folder const folder{"lua_large_file"}; + folder.write("large.bin", std::string(screen_file_size + 1, 'x')); + folder.write("data/small.txt", std::string_view{"small"}); + CHECK(first_pixel(folder.write("file.lua", large_file_script), "file") == 255); +} + +TEST_CASE("lua screens: a script larger than the limit isn't loaded") { + script_folder const folder{"lua_large_script"}; + std::string code{"return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end }\n--"}; + code.append(screen_file_size, 'x'); + auto const script{folder.write("large.lua", code)}; + script_screen_queue queue; + REQUIRE(queue.init()); + + recording_texture texture; + auto const screen{queue.acquire(request(script_language::lua, script, "large", &texture))}; + refresh(queue, screen, speed(0.0), 1); + run_frames(queue); + CHECK_FALSE(queue.due(*screen)); + CHECK(texture.uploads == 0); + queue.exit(); +} + +namespace { + +// white when the script gets no userdata of its own (newproxy), and a table's __gc isn't called: no finalizer of the +// script's, which LuaJIT would run without the hook +constexpr std::string_view finalizer_script{R"( +local collected = false +setmetatable({}, { __gc = function() collected = true end }) +collectgarbage() +collectgarbage() +local good = newproxy == nil and ffi == nil and require == nil and not collected +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// a table whose metatable fails, loops, or gives render: the game reads the table in protected mode +constexpr std::string_view failing_index_script{R"( +return setmetatable({}, { __index = function() error("x") end }) +)"}; + +constexpr std::string_view looping_index_script{R"( +return setmetatable({}, { __index = function() while true do end end }) +)"}; + +constexpr std::string_view inherited_render_script{R"( +local base = { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +return setmetatable({}, { __index = base }) +)"}; + +// starts, then fails when render is read for a refresh +constexpr std::string_view failing_later_script{R"( +local started = false +return setmetatable({}, { __index = function(t, key) + if key == "init" then return function() started = true end end + if key == "render" then + if started then error("render can't be read any more") end + return function() end + end +end }) +)"}; + +// white when the pattern functions refuse what may take too long, and do what doesn't +constexpr std::string_view pattern_script{R"( +local long = ("a"):rep(1000000) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("may take too long", 1, true) ~= nil +end +local slow = refused(string.find, long, ".-b") + and refused(function() return long:find(".-b") end) + and refused(string.match, long, "(a*)b") + and refused(string.gsub, long, "a-b", "") + and refused(function() for x in long:gmatch("a-b") do end end) + and refused(string.find, ("a"):rep(1000), "a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?a?aaaaaaaaaaaaaaaaaaaaaaaaaaaaaab") + and refused(string.find, long, ("a"):rep(1000) .. "b", 1, true) +-- %b walks to the end of the subject from each opening character that nothing closes +local open = ("("):rep(1000000) +slow = slow and refused(string.find, open, '%b()') + and refused(string.gsub, open, '%b()', "") + and refused(function() for x in open:gmatch('%b()') do end end) +-- what a screen does: lines of a file, fields of a line, a plain search, short subjects +local text = ("key=value\n"):rep(10000) +local lines = 0 +for line in text:gmatch("[^\n]+") do lines = lines + 1 end +local key, value = ("speed=120"):match("^(%w+)=(%d+)$") +local spaced = select(2, (("a b c "):rep(100)):gsub("%s+", " ")) +local found = long:find("aaab", 1, true) == nil and (long .. "b"):find("ab", 1, true) == 1000000 +local calls = select(2, (("call(a, b) "):rep(10000)):gsub('%b()', "")) +local fast = lines == 10000 and key == "speed" and value == "120" and spaced == 300 and found and calls == 10000 + and ("x = 1"):find("=") == 3 and ("abc"):gsub("b", "%0%0") == "abbc" +return { + render = function(state) + return eu07.image(1, 1, (slow and fast) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when what makes a large string in one call is refused past the memory of a screen +constexpr std::string_view large_result_script{R"( +local mega = ("x"):rep(1024 * 1024) +local function refused(...) + local ok, message = pcall(...) + return not ok and message:find("over the memory of a screen", 1, true) ~= nil +end +local parts = {} +for i = 1, 200 do parts[i] = mega end +local format = refused(string.format, ("%s"):rep(200), unpack(parts)) +local concat = refused(table.concat, parts) +local gsub = refused(string.gsub, mega, "", ("y"):rep(1000)) +local gsub_table = refused(string.gsub, mega, ".", { x = ("y"):rep(1000) }) +local fits = #table.concat({ mega, mega }, ",") == 2 * 1024 * 1024 + 1 and #string.format("%s%s", mega, mega) == 2 * 1024 * 1024 + and select(2, mega:gsub("x", "yy")) == 1024 * 1024 +return { + render = function(state) + return eu07.image(1, 1, (format and concat and gsub and gsub_table and fits) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when gsub takes a table with a metatable as Lua does (the metatable doesn't get to the library as an argument), +// and a line is trimmed: with the usual idiom on a long line of words, without a pattern on a long run of spaces +constexpr std::string_view gsub_metatable_trim_script{R"( +local upper = setmetatable({}, { __index = function(_, k) return k:upper() end }) +local replaced, count = ("one two"):gsub("%w+", upper) +local line = ("word next\tone "):rep(700) +local trimmed = (" " .. line .. " "):match("^%s*(.-)%s*$") +local ok, message = pcall(string.match, "x" .. (" "):rep(1000000) .. "x", "^%s*(.-)%s*$") +local refused = not ok and message:find("may take too long", 1, true) ~= nil +local function trim(s) + local first = s:find("%S") + if not first then return "" end + return s:sub(first, #s - s:reverse():find("%S") + 1) +end +local spaced = trim(" x" .. (" "):rep(1000000) .. "x ") +local good = replaced == "ONE TWO" and count == 2 and trimmed == line:sub(1, -2) and refused + and #spaced == 1000002 and trim(" ") == "" and trim(" a b ") == "a b" +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// white when the images a screen holds are held to its memory, and the images it dropped don't count. an image of +// 4096 x 4096 is 64 MB, half the memory of a screen: the second one kept is refused, and the 4 dropped ones (twice +// the memory) would be refused too if the dropped ones counted. no more of them: each is filled pixel by pixel, slowly +// in the coverage build (GCC -O0 --coverage), and with 20 of them the screen sometimes didn't draw in its 20 s there +constexpr std::string_view image_memory_script{R"( +local kept = {} +local ok, message = pcall(function() + for i = 1, 100 do kept[i] = eu07.image(4096, 4096) end +end) +local refused = not ok and message:find("memory limit exceeded", 1, true) ~= nil and #kept < 100 +kept = nil +local dropped = pcall(function() + for i = 1, 4 do local image = eu07.image(4096, 4096) end +end) +return { + render = function(state) + return eu07.image(1, 1, (refused and dropped) and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// holds more and more memory, a little at a time +constexpr std::string_view growing_script{R"( +local kept = {} +for i = 1, 10000000 do kept[i] = ("x"):rep(1000) .. i end +return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +)"}; + +// the memory limit of the Lua screens made while it lives, in place of max_screen_memory: a test that fills the memory +// of a screen stays small +class screen_memory_limit { + public: + explicit screen_memory_limit(std::size_t const Bytes) { script_screens::set_lua_screen_memory_limit(Bytes); } + ~screen_memory_limit() { script_screens::set_lua_screen_memory_limit(script_screens::max_screen_memory); } + screen_memory_limit(screen_memory_limit const &) = delete; + screen_memory_limit &operator=(screen_memory_limit const &) = delete; +}; + +constexpr std::size_t small_screen_memory{32 * 1024 * 1024}; + +// with small_screen_memory: a concatenation of 80 MB in one operation, from a string of 8 MB, refused as it is made, in +// the pcall, as the instruction hook would see it only once it is made +constexpr std::string_view one_concatenation_script{R"( +local a = ("x"):rep(1024 * 1024) +for i = 1, 3 do a = a .. a end +local ok, message = pcall(function() return #(a .. a .. a .. a .. a .. a .. a .. a .. a .. a) end) +local refused = #a == 8 * 1024 * 1024 and not ok and message:find("not enough memory", 1, true) ~= nil +a = nil +return { + render = function(state) + return eu07.image(1, 1, refused and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// doubles a string to 2 GB, 64 times small_screen_memory, in some fifty instructions: fewer than the thousand after +// which the instruction hook looks at the heap +constexpr std::string_view doubling_script{R"( +local s = ("x"):rep(1024 * 1024) +for i = 1, 11 do s = s .. s end +return { render = function(state) return eu07.image(1, 1, { 255, 255, 255 }) end } +)"}; + +// white when a coroutine yields across xpcall, and xpcall without a handler is an error +constexpr std::string_view xpcall_yield_script{R"( +local resume = coroutine.wrap(function() + local ok, value = xpcall(function() + coroutine.yield(1) + return 2 + end, function(e) return e end) + coroutine.yield(ok and value) + local caught, handled = xpcall(function() + coroutine.yield(3) + error("boom") + end, function(e) return "handled: " .. e end) + coroutine.yield(not caught and handled:find("handled: .*boom") ~= nil) +end) +local first, second, third, fourth = resume(), resume(), resume(), resume() +local missing = not pcall(xpcall, print) +local good = first == 1 and second == 2 and third == 3 and fourth == true and missing +return { + render = function(state) + return eu07.image(1, 1, good and { 255, 255, 255 } or { 0, 0, 0 }) + end +} +)"}; + +// loads the script as a screen next to a working one: the working one draws, the script's screen draws nothing, and +// nothing hangs or ends the program +void check_switched_off(script_folder const &Folder, std::string const &Name, std::string_view const Code) { + auto const painting{Folder.write("paint.lua", paint_script)}; + auto const failing{Folder.write(Name, Code)}; + auto *queue{new script_screen_queue}; // NOSONAR a stuck worker would keep the destructor waiting, see above + REQUIRE(queue->init()); + recording_texture switched_off; + recording_texture working; + auto const first{queue->acquire(request(script_language::lua, failing, Name, &switched_off))}; + auto const second{queue->acquire(request(script_language::lua, painting, "paint", &working))}; + refresh(*queue, first, speed(1.0), 1); + refresh(*queue, second, speed(2.0), 1); + auto const drawn{run_until(*queue, [&working] { return working.uploads > 0; })}; + CHECK(drawn); + if (false == drawn) { + return; + } + run_frames(*queue); + CHECK(switched_off.uploads == 0); + CHECK_FALSE(queue->due(*first)); + queue->exit(); + delete queue; // NOSONAR see above +} + +} // namespace + +TEST_CASE("lua screens: a script makes no finalizer of its own") { + script_folder const folder{"lua_finalizer"}; + CHECK(first_pixel(folder.write("finalizer.lua", finalizer_script), "finalizer") == 255); +} + +TEST_CASE("lua screens: the table of a script is read in protected mode") { + log_capture const log; + script_folder const folder{"lua_index"}; + SUBCASE("a metatable that fails") { + check_switched_off(folder, "failing.lua", failing_index_script); + CHECK_FALSE(log.lines_with("reading render and init failed").empty()); + } + SUBCASE("a metatable that loops") { + check_switched_off(folder, "looping.lua", looping_index_script); + CHECK_FALSE(log.lines_with("instruction limit exceeded").empty()); + } + SUBCASE("a metatable that fails once the screen runs") { + check_switched_off(folder, "later.lua", failing_later_script); + CHECK_FALSE(log.lines_with("render can't be read any more").empty()); + } + SUBCASE("a metatable that gives render") { + CHECK(first_pixel(folder.write("inherited.lua", inherited_render_script), "inherited") == 255); + } +} + +TEST_CASE("lua screens: the pattern functions refuse what may take too long, and do the rest") { + script_folder const folder{"lua_patterns"}; + auto const started{std::chrono::steady_clock::now()}; + CHECK(first_pixel(folder.write("patterns.lua", pattern_script), "patterns") == 255); + // the refused calls take no time, the others little + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10)); +} + +TEST_CASE("lua screens: what makes a large string in one call is held to the memory of a screen") { + script_folder const folder{"lua_large_result"}; + CHECK(first_pixel(folder.write("large.lua", large_result_script), "large") == 255); +} + +TEST_CASE("lua screens: gsub with a table that has a metatable, and the trim of a long line") { + script_folder const folder{"lua_gsub_metatable_trim"}; + auto const started{std::chrono::steady_clock::now()}; + CHECK(first_pixel(folder.write("trim.lua", gsub_metatable_trim_script), "trim") == 255); + CHECK(std::chrono::steady_clock::now() - started < std::chrono::seconds(10)); +} + +TEST_CASE("lua screens: the images a screen holds are held to its memory") { + script_folder const folder{"lua_image_memory"}; + CHECK(first_pixel(folder.write("images.lua", image_memory_script), "images") == 255); +} + +TEST_CASE("lua screens: a screen holding more than its memory is switched off") { + log_capture const log; + script_folder const folder{"lua_growing"}; + check_switched_off(folder, "growing.lua", growing_script); + CHECK(log.lines_with("memory limit exceeded").size() + log.lines_with("not enough memory").size() > 0); +} + +TEST_CASE("lua screens: a string made over the memory in one operation is refused") { + screen_memory_limit const limit{small_screen_memory}; + script_folder const folder{"lua_one_concatenation"}; + CHECK(first_pixel(folder.write("concatenation.lua", one_concatenation_script), "concatenation") == 255); + CHECK(script_screens::lua_screen_memory_peak() <= 2 * small_screen_memory); +} + +TEST_CASE("lua screens: a string doubled in a loop stops at the memory of the screen, not at LuaJIT's own limit") { + log_capture const log; + screen_memory_limit const limit{small_screen_memory}; + script_folder const folder{"lua_doubling"}; + check_switched_off(folder, "doubling.lua", doubling_script); + CHECK(log.lines_with("not enough memory").size() + log.lines_with("memory limit exceeded").size() > 0); + // past the limit between two checks of the hook, but refused before twice the limit (its garbage included). with + // LuaJIT 2.0 on x64 and no allocator in front of LuaJIT's own, this went on to its own limit, over 1 GB + auto const peak{script_screens::lua_screen_memory_peak()}; + CAPTURE(peak); + CHECK(peak > small_screen_memory); + CHECK(peak <= 2 * small_screen_memory); +} + +TEST_CASE("lua screens: a coroutine yields across xpcall") { + script_folder const folder{"lua_xpcall_yield"}; + CHECK(first_pixel(folder.write("yield.lua", xpcall_yield_script), "yield") == 255); +} + #endif diff --git a/tests/unit/test_script_screens.cpp b/tests/unit/test_script_screens.cpp index 9e0bb7a92..af8678f2e 100644 --- a/tests/unit/test_script_screens.cpp +++ b/tests/unit/test_script_screens.cpp @@ -101,3 +101,146 @@ TEST_CASE("script screens: a screen reads files only below its own folder") { CHECK_FALSE(script_screens::is_safe_relative_path("\\windows")); CHECK_FALSE(script_screens::is_safe_relative_path("c:/windows/win.ini")); } + +TEST_CASE("script screens: the script of a screen is in the vehicle's folder, or from the game's, and not outside it") { + using script_screens::screen_script_path; + std::string const vehicle{"dynamic/pkp/ep07_v1/"}; + CHECK(screen_script_path(vehicle, "screen.lua") == "dynamic/pkp/ep07_v1/screen.lua"); + CHECK(screen_script_path(vehicle, "scripts/screen.lua") == "scripts/screen.lua"); + // a backslash isn't a folder to the game (substr_path), so the name goes in the vehicle's folder + CHECK(screen_script_path(vehicle, "lua\\screen.lua") == "dynamic/pkp/ep07_v1/lua\\screen.lua"); + + CHECK_FALSE(screen_script_path(vehicle, "../../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "scripts/../../screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "..\\..\\screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "/screen.lua").has_value()); + CHECK_FALSE(screen_script_path(vehicle, "c:/games/screen.lua").has_value()); + CHECK_FALSE(screen_script_path("../outside/", "screen.lua").has_value()); +} + +TEST_CASE("script screens: the steps a Lua pattern function may take at worst") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // a plain search: the subject (and one past it) times the pattern + CHECK(lua_pattern_cost("abc", 999, true, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost(".-b", 999, true, true) == doctest::Approx(1000.0 * 3)); + // a pattern without special characters is searched plainly as well + CHECK(lua_pattern_cost("abc", 999, false, true) == doctest::Approx(1000.0 * 3)); + CHECK(lua_pattern_cost("", 999, false, true) == doctest::Approx(1000.0)); + // from every position, times the subject for each repetition but a last one + CHECK(lua_pattern_cost(".-b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("a*", 999, false, true) == doctest::Approx(1000.0 * 2)); + CHECK(lua_pattern_cost("(a+)", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("a+$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 3)); + CHECK(lua_pattern_cost("(%d+):(%d+)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 11)); + CHECK(lua_pattern_cost("[^\n]+", 999, false, false) == doctest::Approx(1000.0 * 5)); + CHECK(lua_pattern_cost("[%]x]*y", 999, false, true) == doctest::Approx(1000.0 * 1000 * 7)); + CHECK(lua_pattern_cost("%bxyz", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + // %b goes along the subject on its own: it counts where it ends the pattern too + CHECK(lua_pattern_cost("%b()", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); + CHECK(lua_pattern_cost("(%b())", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%b().*", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("(a)%1x", 999, false, true) == doctest::Approx(1000.0 * 1000 * 6)); + CHECK(lua_pattern_cost("%f[%w]%w+", 999, false, true) == doctest::Approx(1000.0 * 9)); + // '?' doubles + CHECK(lua_pattern_cost("a?a?b", 999, false, true) == doctest::Approx(1000.0 * 4 * 5)); + // '^' anchors find, match and gsub to the first position; gmatch takes it as a character + CHECK(lua_pattern_cost("^.-b", 999, false, true) == doctest::Approx(1000.0 * 4)); + CHECK(lua_pattern_cost("^.-b", 999, false, false) == doctest::Approx(1000.0 * 1000 * 4)); + // a malformed pattern is the library's to refuse + CHECK(lua_pattern_cost("[a", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%", 999, false, true) > 0.0); + CHECK(lua_pattern_cost("%b", 999, false, true) > 0.0); + + // the review's case, and what a screen does + CHECK(lua_pattern_cost(".-b", 1'000'000, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("[^\n]+", 1'000'000, false, false) < max_pattern_cost); + CHECK(lua_pattern_cost("^(%w+)=(%d+)$", 1'000, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("%s+$", 4'000, false, true) < max_pattern_cost); + std::string optional; + for (int idx = 0; idx < 30; ++idx) { + optional += "a?"; + } + CHECK(lua_pattern_cost(optional + std::string(30, 'a'), 100, false, true) > max_pattern_cost); +} + +TEST_CASE("script screens: a repetition followed by what always matches doesn't multiply") { + using script_screens::lua_pattern_cost; + // the first %s* of the trim: past it, (.-)%s*$ matches from wherever it stopped, so it's tried once + CHECK(lua_pattern_cost("^%s*(.-)%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 12)); + CHECK(lua_pattern_cost("^%s*(.*)", 999, false, true) == doctest::Approx(8.0)); + CHECK(lua_pattern_cost("a*.-$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 5)); + // what may not match still multiplies + CHECK(lua_pattern_cost("^%s*(.*%S)", 999, false, true) == doctest::Approx(1000.0 * 1000 * 10)); + CHECK(lua_pattern_cost("^%s*x%s*$", 999, false, true) == doctest::Approx(1000.0 * 1000 * 9)); + // '$' is the end only at the end of the pattern + CHECK(lua_pattern_cost("a*$b", 999, false, true) == doctest::Approx(1000.0 * 1000 * 4)); +} + +TEST_CASE("script screens: %b counts the way from an opening character to the one that closes it") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + // nothing closes: from each character to the end of the subject, the subject squared; whatever follows the %b + auto const open{std::string(1'000'000, '(')}; + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}, false, false) > max_pattern_cost); + CHECK(lua_pattern_cost("(%b())", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b().*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()x*", std::string_view{open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open + open}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 10'000), false, true) > max_pattern_cost); + // the same with a hundred thousand of them, more than the openings held at a time + CHECK(lua_pattern_cost("%b()", std::string_view{open}.substr(0, 100'000), false, true) > max_pattern_cost); + // tried once from each position: the positions and the ways from the three openings, 2 + 5 + 2 + std::string_view const calls{"a(b)c(d(e))"}; + CHECK(lua_pattern_cost("%b()", calls, false, true) == doctest::Approx((12.0 + 9.0) * 4)); + CHECK(lua_pattern_cost("(%b())", calls, false, true) == doctest::Approx((12.0 + 9.0) * 6)); + // tried from the first position only, or after a repetition: the longest way of one try, and one + CHECK(lua_pattern_cost("^%b()", calls, false, true) == doctest::Approx(6.0 * 5)); + CHECK(lua_pattern_cost(".-%b()", calls, false, true) == doctest::Approx(12.0 * 12 * 6 * 6)); + // the same character opens and closes: to the next one + CHECK(lua_pattern_cost("%b\"\"", std::string_view{"a\"b\"c\""}, false, true) == doctest::Approx((7.0 + 5.0) * 4)); + // none in the subject: nothing to go along + CHECK(lua_pattern_cost("%b()", std::string_view{"abc"}, false, true) == doctest::Approx(4.0 * 4)); + // a long text of short calls is cheap, and so is one opening left unclosed in it + std::string text; + while (text.size() < 100'000) { + text += "call(a, b) "; + } + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + text[9] = ' '; + CHECK(lua_pattern_cost("%b()", std::string_view{text}, false, true) < max_pattern_cost); + // nested deep, the ways add up to the subject squared again + auto const nested{std::string(20'000, '(') + std::string(20'000, ')')}; + CHECK(lua_pattern_cost("%b()x", std::string_view{nested}, false, true) > max_pattern_cost); + // malformed: the function raises its error + CHECK(lua_pattern_cost("%b(", std::string_view{open}, false, true) > 0.0); +} + +TEST_CASE("script screens: a repetition right before the final $ counts its longest run in the subject") { + using script_screens::lua_pattern_cost; + using script_screens::max_pattern_cost; + std::string words; + while (words.size() < 10'000) { + words += "word next\tone "; + } + // a line of 10 KB trimmed: the subject times the longest run of spaces (2), where the length alone gives the + // subject squared + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 3 * 12)); + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{words}, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("^%s*(.-)%s*$", words.size(), false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%s+$", std::string_view{words}, false, true) < max_pattern_cost); + CHECK(lua_pattern_cost("%d*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * 1 * 4)); + CHECK(lua_pattern_cost("x*$", std::string_view{"axxxa"}, false, true) == doctest::Approx(6.0 * 4 * 3)); + CHECK(lua_pattern_cost("%%*$", std::string_view{"a%%%a"}, false, true) == doctest::Approx(6.0 * 4 * 4)); + // a long run is still the subject squared: "x", 10 000 spaces, "x" takes the trim about 10^8 steps, and a + // megabyte of them hours + auto const spaces{"x" + std::string(10'000, ' ') + "x"}; + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{spaces}, false, true) > max_pattern_cost); + auto const megabyte{"x" + std::string(1'000'000, ' ') + "x"}; + CHECK(lua_pattern_cost("^%s*(.-)%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost); + CHECK(lua_pattern_cost("%s*$", std::string_view{megabyte}, false, true) > max_pattern_cost); + // a set or '.' isn't gone through: the whole subject + CHECK(lua_pattern_cost("[ ]*$", std::string_view{words}, false, true) == doctest::Approx((words.size() + 1.0) * (words.size() + 1.0) * 5)); + CHECK(lua_pattern_cost(".-b", std::string(1'000'000, 'a'), false, true) > max_pattern_cost); +} diff --git a/tests/unit/test_signal_passing.cpp b/tests/unit/test_signal_passing.cpp new file mode 100644 index 000000000..16d3cd9eb --- /dev/null +++ b/tests/unit/test_signal_passing.cpp @@ -0,0 +1,128 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/signalpassing.h" + +// when a signal in the AI's speed table counts as passed by the train (TController::CheckSignalPassed): the test +// mode reports a signal at stop passed that way as "passed at danger", the blackbox records every passed signal. a +// train set or standing past a signal at the start of a scenario didn't pass it; within 5 m of the signal the test +// mode used to report it all the same. + +namespace { + +// a point of the speed table the way TSpeedPos keeps it: found by the scan of the route, then updated as the head +// moves on (TController::TableCheck: UpdateDistance, Update, CheckSignalPassed) +struct table_point { + double distance; // ahead of the head [m], negative behind it + bool seen_ahead; + bool elapsed{false}; + int passes{0}; // reports of the point passed + + table_point(double const Distance, bool const Standing) + : distance(Distance), seen_ahead(signal_passing::seen_ahead_when_found(Distance, Standing)) { + move(0.0); // the first update comes with the next check of the table, the train hasn't moved yet + } + + // the head moves Metres on, and the table updates the point + void move(double const Metres) { + distance -= Metres; + auto const elapsedbefore{elapsed}; + elapsed = elapsed || distance < 0.0; + seen_ahead = signal_passing::seen_ahead_on_update(distance, seen_ahead); + if (signal_passing::passed_now(elapsedbefore, elapsed, seen_ahead)) { + ++passes; + } + } + + // the head moves Metres on in steps of a metre + void run(double const Metres) { + for (int moved{0}; moved < Metres; ++moved) { + move(1.0); + } + } +}; + +auto constexpr standing{true}; +auto constexpr moving{false}; + +} // namespace + +TEST_CASE("signal passing: a train standing past a signal when its table is traced hasn't passed it") { + auto behind{0.0}; + // 1-4.5 m: reported as passed at danger before; 20 m: the train standing across the signal of #409 + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("1 m") { behind = 1.0; } + SUBCASE("2 m") { behind = 2.0; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("4 m") { behind = 4.0; } + SUBCASE("4.9 m") { behind = 4.9; } + SUBCASE("20 m") { behind = 20.0; } + CAPTURE(behind); + + table_point signal{-behind, standing}; + CHECK_FALSE(signal.seen_ahead); + // standing there a while, then pulling away from it + for (auto check{0}; check < 10; ++check) { + signal.move(0.0); + } + signal.run(200.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train standing short of a signal passes it when it moves on") { + auto ahead{0.0}; + SUBCASE("at the signal") { ahead = 0.0; } + SUBCASE("0.5 m") { ahead = 0.5; } + SUBCASE("10 m") { ahead = 10.0; } + SUBCASE("150 m") { ahead = 150.0; } + CAPTURE(ahead); + + table_point signal{ahead, standing}; + CHECK(signal.seen_ahead); + signal.move(0.0); + CHECK(signal.passes == 0); + signal.run(ahead + 50.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a moving train passing a signal its table finds just behind the head passes it") { + // the table traced anew in motion, the head right at the signal: the distance is found in steps of a metre, + // so a signal just ahead may come out a little behind + auto behind{0.0}; + SUBCASE("0.5 m") { behind = 0.5; } + SUBCASE("3 m") { behind = 3.0; } + SUBCASE("at the tolerance") { behind = signal_passing::moving_tolerance; } + CAPTURE(behind); + + table_point signal{-behind, moving}; + CHECK(signal.seen_ahead); + CHECK(signal.passes == 1); + signal.run(100.0); + CHECK(signal.passes == 1); +} + +TEST_CASE("signal passing: a signal found further behind a moving train than the tolerance wasn't passed by it") { + table_point signal{-(signal_passing::moving_tolerance + 0.5), moving}; + CHECK_FALSE(signal.seen_ahead); + signal.run(100.0); + CHECK(signal.passes == 0); +} + +TEST_CASE("signal passing: a train that overruns a signal and stops past it passes it once") { + // the overrun counts while the train moves; a table traced again with the train standing 3 m past the signal + // (a change of direction and back, a new order) doesn't count it again + table_point approach{150.0, moving}; + approach.run(153.0); + CHECK(approach.passes == 1); + + table_point traced_again{-3.0, standing}; + traced_again.run(50.0); + CHECK(traced_again.passes == 0); +} + +TEST_CASE("signal passing: the report of a pass needs the point to become elapsed in this very update") { + CHECK(signal_passing::passed_now(false, true, true)); + CHECK_FALSE(signal_passing::passed_now(true, true, true)); // elapsed before + CHECK_FALSE(signal_passing::passed_now(false, false, true)); // still ahead + CHECK_FALSE(signal_passing::passed_now(false, true, false)); // the head never had it ahead +} diff --git a/tests/unit/test_sleeper_models.cpp b/tests/unit/test_sleeper_models.cpp new file mode 100644 index 000000000..05d90ab32 --- /dev/null +++ b/tests/unit/test_sleeper_models.cpp @@ -0,0 +1,67 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "world/TrackSleepers.h" + +#include +#include +#include + +// the models of sleepers and timbers the track editor lists (world/TrackSleepers.h), found by the names of the files in a +// folder. a file named with a character the code page lacks is left out, rather than throwing out of the scan (GE#560) + +namespace { + +void write_model(std::filesystem::path const &Path, std::string const &Content) { + std::filesystem::create_directories(Path.parent_path()); + std::ofstream file{Path, std::ios::binary}; + file << Content; +} + +// whether the name can be turned into the narrow names of the code page: on Windows a Chinese character can't be with any +// of the single byte pages, where the narrow names are UTF-8 it can +bool narrow_name(std::filesystem::path const &Path) { + try { + static_cast(Path.generic_string()); + return true; + } catch (std::exception const &) { + return false; + } +} + +} // namespace + +TEST_CASE("sleeper models: a file named outside of the code page is left out, the rest is listed") { + test::scratch_folder const folder{"sleeper_models"}; + auto const root{folder.root()}; + write_model(root / "pkp" / "podklad_a.t3d", "Name: podklad\n"); + write_model(root / "pkp" / "podrozjazd_b.t3d", "Name: begin\nName: main\nName: end\n"); + auto const odd{root / "pkp" / std::filesystem::path{u8"podklad_\u4e2d.t3d"}}; + write_model(odd, "Name: podklad\n"); + // nor any other model of the folder named so, looked at before its name tells it's no sleeper + write_model(root / "drzewa" / std::filesystem::path{u8"drzewo_\u4e2d.e3d"}, ""); + write_model(root / "drzewa" / "drzewo.e3d", ""); + REQUIRE(std::filesystem::exists(odd)); + + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(root)); + + auto const listed{narrow_name(odd)}; + REQUIRE(models.size() == (listed ? 3u : 2u)); + // the timbers first, then by the name + CHECK(models[0].name == "pkp/podrozjazd_b"); + CHECK(models[0].timber); + CHECK(models[1].name == "pkp/podklad_a"); + CHECK_FALSE(models[1].timber); + if (listed) { + CHECK(models[2].name.find("pkp/podklad_") == 0); + } +} + +TEST_CASE("sleeper models: a folder missing lists none") { + test::scratch_folder const folder{"sleeper_models_missing"}; + std::vector models; + REQUIRE_NOTHROW(models = track_sleepers::pack_models(folder.root() / "missing")); + CHECK(models.empty()); +} diff --git a/tests/unit/test_smoke.cpp b/tests/unit/test_smoke.cpp index 281b5dbf6..2ff88b209 100644 --- a/tests/unit/test_smoke.cpp +++ b/tests/unit/test_smoke.cpp @@ -28,19 +28,19 @@ test::vehicle diesel() { TEST_CASE("smoke: a vehicle taken off the tracks puffs no more (#90)") { auto vehicle{diesel()}; - SUBCASE("engine starting") { vehicle->dizel_spinup = true; } + SUBCASE("engine starting") { vehicle->diesel.spinningUp = true; } SUBCASE("engine idling") { vehicle->DirAbsolute = 0; } SUBCASE("engine under load") { vehicle->DirAbsolute = 1; vehicle->Im = 400.0; } // on the tracks the engine puffs - REQUIRE(smoke::vehicle_spawn_count(vehicle.mover(), true, source, update) >= 1.f); + REQUIRE(smoke::vehicle_spawn_count(vehicle.physics(), true, source, update) >= 1.f); // gone through a portal, the pending particles are dropped too auto pending{source}; pending.pending = 5.f; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), false, pending, update) == 0.f); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), false, pending, update) == 0.f); } TEST_CASE("smoke: a road vehicle back on the road from the pool puffs again") { @@ -48,11 +48,11 @@ TEST_CASE("smoke: a road vehicle back on the road from the pool puffs again") { // waiting in the pool, the count stays at zero update after update auto rate{source}; for (auto i{0}; i < 10; ++i) { - rate.pending = smoke::vehicle_spawn_count(vehicle.mover(), false, rate, update); + rate.pending = smoke::vehicle_spawn_count(vehicle.physics(), false, rate, update); } REQUIRE(rate.pending == 0.f); - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, rate, update) >= 1.f); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, rate, update) >= 1.f); } TEST_CASE("smoke: the engine adds to the steady rate of the source") { @@ -61,51 +61,51 @@ TEST_CASE("smoke: the engine adds to the steady rate of the source") { auto const steady{source.rate * update}; // the rate of a source of the scenery vehicle->EnginePower = 0.0; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, source, update) == doctest::Approx(steady)); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, source, update) == doctest::Approx(steady)); vehicle->EnginePower = 400.0; - auto const working{smoke::vehicle_spawn_count(vehicle.mover(), true, source, update)}; + auto const working{smoke::vehicle_spawn_count(vehicle.physics(), true, source, update)}; CHECK(working > steady); // the faster the starting engine turns, the more it puffs - vehicle->dizel_spinup = true; + vehicle->diesel.spinningUp = true; vehicle->enrot = 100.0; - auto const slow{smoke::vehicle_spawn_count(vehicle.mover(), true, source, update)}; + auto const slow{smoke::vehicle_spawn_count(vehicle.physics(), true, source, update)}; vehicle->enrot = 400.0; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, source, update) > slow); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, source, update) > slow); } TEST_CASE("smoke: the pending particles never outgrow the room of the source") { auto vehicle{diesel()}; - vehicle->dizel_spinup = true; + vehicle->diesel.spinningUp = true; vehicle->enrot = 100000.0; auto rate{source}; rate.pending = 99.f; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, rate, 10.0) == rate.limit); + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, rate, 10.0) == rate.limit); } TEST_CASE("smoke: an engine the starter turns lets out no smoke until it fires (#523)") { auto vehicle{diesel()}; - vehicle->dizel_spinup = true; + vehicle->diesel.spinningUp = true; auto pending{source}; pending.pending = 5.f; - vehicle->dizel_FiringCountdown = 0.5; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) == 0.f); + vehicle->diesel.firingCountdown = 0.5; + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, pending, update) == 0.f); - vehicle->dizel_FiringCountdown = 0.0; - CHECK(smoke::vehicle_spawn_count(vehicle.mover(), true, pending, update) >= 1.f); + vehicle->diesel.firingCountdown = 0.0; + CHECK(smoke::vehicle_spawn_count(vehicle.physics(), true, pending, update) >= 1.f); } namespace { // the locomotive's engine started the way the AI starts it, a second at a time, until it runs (Mains) bool start_engine(test::driven const &Driven, test::track const &Track) { - for (int second = 0; second < 120 && false == Driven.controlling.Mains; ++second) { + for (int second = 0; second < 120 && false == Driven.controlling.lineBreaker.IsClosed(); ++second) { test::start_up(Driven, Track, 1.0); } - return Driven.controlling.Mains; + return Driven.controlling.lineBreaker.IsClosed(); } } // namespace @@ -118,17 +118,17 @@ TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDela { // SmokeDelay set in the .fiz of the locomotive test::vehicle locomotive{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 2)}; - REQUIRE(locomotive->dizel_SmokeDelay == doctest::Approx(2.0)); + REQUIRE(locomotive->diesel.smokeDelay == doctest::Approx(2.0)); auto const driven{test::driving(locomotive)}; REQUIRE(start_engine(driven, track)); // the engine started less than a second ago: the starter still turns it - CHECK(locomotive->dizel_FiringCountdown > 0.5); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f); + CHECK(locomotive->diesel.firingCountdown > 0.5); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) == 0.f); // it has fired since test::drive(driven, track, 3.0); - CHECK(locomotive->Mains); - CHECK(locomotive->dizel_FiringCountdown == 0.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + CHECK(locomotive->lineBreaker.IsClosed()); + CHECK(locomotive->diesel.firingCountdown == 0.0); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } { // a longer delay from the .fiz @@ -136,9 +136,9 @@ TEST_CASE("smoke: a real diesel smokes only once its engine has fired, SmokeDela auto const driven{test::driving(locomotive)}; REQUIRE(start_engine(driven, track)); test::drive(driven, track, 3.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) == 0.f); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) == 0.f); test::drive(driven, track, 3.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } } } @@ -149,13 +149,13 @@ TEST_CASE("smoke: without SmokeDelay in its .fiz a diesel smokes as soon as the test::track const track{}; // a locomotive which has the delay, loaded first, doesn't hand it on to the next one: the value is the vehicle's own test::vehicle delayed{test::definition{test::definition::fiz(path)}.set("Engine", "SmokeDelay", 3)}; - REQUIRE(delayed->dizel_SmokeDelay == doctest::Approx(3.0)); + REQUIRE(delayed->diesel.smokeDelay == doctest::Approx(3.0)); test::vehicle locomotive{test::definition::fiz(path)}; - REQUIRE(locomotive->dizel_SmokeDelay == 0.0); - CHECK(delayed->dizel_SmokeDelay == doctest::Approx(3.0)); + REQUIRE(locomotive->diesel.smokeDelay == 0.0); + CHECK(delayed->diesel.smokeDelay == doctest::Approx(3.0)); auto const driven{test::driving(locomotive)}; REQUIRE(start_engine(driven, track)); - CHECK(locomotive->dizel_FiringCountdown == 0.0); - CHECK(smoke::vehicle_spawn_count(locomotive.mover(), true, source, update) >= 1.f); + CHECK(locomotive->diesel.firingCountdown == 0.0); + CHECK(smoke::vehicle_spawn_count(locomotive.physics(), true, source, update) >= 1.f); } } diff --git a/tests/unit/test_speed_control.cpp b/tests/unit/test_speed_control.cpp new file mode 100644 index 000000000..5878fb64d --- /dev/null +++ b/tests/unit/test_speed_control.cpp @@ -0,0 +1,401 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scenario.h" +#include "drive.h" + +#include + +// the cruise control (tempomat, SpeedCtrl) and the secondary controller (ScndCtrl) of the vehicles which have one +// of them or both (eu07/maszyna#69). on the vehicles with the cruise control alone the secondary controller is +// its switch, as it always was; on those whose secondary controller shunts the field of the traction motors +// (the 6Dg, the ST45 and the BR285 among them) the cruise control has a switch of its own, apart from it + +using test::scenario; +using namespace test::channels; + +namespace { + +std::vector cruise() { + return { + {"SpeedCtrlActive", [](auto const &M) { return M.SpeedCtrlUnit.IsActive ? 1.0 : 0.0; }}, + {"SpeedCtrlStandby", [](auto const &M) { return M.SpeedCtrlUnit.Standby ? 1.0 : 0.0; }}, + {"SpeedCtrlValue", [](auto const &M) { return M.SpeedCtrlValue; }}, + {"eimic", [](auto const &M) { return M.eimic; }}, + {"eimicSpeedCtrl", [](auto const &M) { return M.eimicSpeedCtrl(); }}, + {"eimic_real", [](auto const &M) { return M.EimicReal(); }}, + }; +} + +// the universal controller (EIMCtrlType 3) of the 6Dg: 3 no power, 4 lowers the demand, 5 holds it, 6 raises it +constexpr int dg_no_power{3}; +constexpr int dg_lower{4}; +constexpr int dg_hold{5}; +constexpr int dg_raise{6}; + +void move_to(physics::Vehicle &Vehicle, int const Position) { + while (Vehicle.MainCtrlPos() < Position && Vehicle.IncMainCtrl(1)) { + // all the work is done in the condition + } + while (Vehicle.MainCtrlPos() > Position && Vehicle.DecMainCtrl(1)) { + // all the work is done in the condition + } + REQUIRE(Vehicle.MainCtrlPos() == Position); +} + +// the 6Dg started up, its brakes released, its controller through the no power and lowering positions to holding, +// for the line contactors to close +void get_6dg_going(scenario &Scenario) { + auto &loco{Scenario.cab()}; + REQUIRE(Scenario.start_up()); + Scenario.get_going(); + move_to(loco, dg_no_power); + for (int second = 0; second < 180 && loco.brakes.cylinderPressure > 0.1; ++second) { + Scenario.wait(1.0); + } + REQUIRE(loco.brakes.cylinderPressure <= 0.1); + move_to(loco, dg_lower); + Scenario.wait(1.0); + move_to(loco, dg_hold); + Scenario.wait(5.0); + REQUIRE(loco.lineContactors.IsClosed()); +} + +} // namespace + +// the vehicles with the field shunting alone, and those with the cruise control alone: as before the split + +TEST_CASE("speed control: the field shunting of the vehicles without a cruise control, as before") { + // the EU07's and the SM42's shunting by hand, the SU45's by itself (RelayType 45, from position 11 of its + // controller on); none has a cruise control, and the secondary controller shunts the field + SUBCASE("EU07 and SM42, by hand") { + for (auto const *path : {"4e_v1/4e", "sm42_v1/6d1"}) { + CAPTURE(path); + scenario scenario{std::string{"speed control/shunting/"} + path, motion() + traction() + cruise()}; + scenario.add(path, 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl()); + REQUIRE_FALSE(loco.AutoRelayFlag()); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(60.0); + auto const speed{loco.Vel}; + scenario.act("shunt"); + CHECK(loco.IncScndCtrl(1)); + CHECK(loco.ScndCtrlPos() == 1); + scenario.wait(10.0); + CHECK(loco.Vel > speed); + CHECK(loco.ScndCtrlPos() == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.act("shunt off"); + CHECK(loco.DecScndCtrl(2)); + CHECK(loco.ScndCtrlPos() == 0); + scenario.wait(5.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } + } + SUBCASE("SU45, by itself") { + scenario scenario{"speed control/shunting/su45_v2/301d", motion() + traction() + cruise()}; + scenario.add("su45_v2/301d", 1); + auto &loco{scenario.cab()}; + REQUIRE_FALSE(loco.SpeedCtrl()); + REQUIRE(loco.AutoRelayFlag()); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + auto most{0}; + for (int i = 0; i < 18; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos()); + } + CHECK(most == loco.ScndCtrlPosNo()); + // the driver can't move it + CHECK_FALSE(loco.DecScndCtrl(2)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.act("notch back"); + scenario.notch_back(0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos() == 0); + scenario.check(); + } +} + +TEST_CASE("speed control: the vehicles whose secondary controller is the cruise control's switch, as before") { + SUBCASE("Impuls: on at the speed of the moment, off by the controller") { + scenario scenario{"speed control/cruise/impuls_v1/31we-a_pr", motion() + traction() + cruise()}; + scenario.add("impuls_v1/31we-a_pr", 1).add("impuls_v1/31we-b_pr").add("impuls_v1/31we-c_pr").add("impuls_v1/31we-d_pr"); + auto &unit{scenario.cab()}; + REQUIRE(unit.SpeedCtrl()); + REQUIRE(unit.ScndCtrlPosNo() == 1); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(40.0); + scenario.act("cruise control on"); + CHECK(unit.IncScndCtrl(1)); + CHECK(unit.ScndCtrlPos() == 1); + CHECK(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == doctest::Approx(unit.Vel)); + auto const held{unit.SpeedCtrlValue}; + scenario.wait(60.0); + CHECK(unit.Vel == doctest::Approx(held).epsilon(0.05)); + scenario.act("cruise control off"); + CHECK(unit.DecScndCtrl(2)); + CHECK(unit.ScndCtrlPos() == 0); + CHECK_FALSE(unit.SpeedCtrlUnit.IsActive); + CHECK(unit.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + scenario.check(); + } + SUBCASE("EU47: the speed raised by tens while the controller is held up, set when it's let go") { + scenario scenario{"speed control/cruise/e186_v2/eu47", motion() + traction() + cruise()}; + scenario.add("e186_v2/eu47", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl()); + REQUIRE(loco.SpeedCtrlTypeTime()); + REQUIRE(loco.ScndCtrlPosNo() == 4); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.act("raise"); + while (loco.ScndCtrlPos() < 3 && loco.IncScndCtrl(1)) { + // all the work is done in the condition + } + REQUIRE(loco.ScndCtrlPos() == 3); + scenario.wait(10.0); + CHECK(loco.NewSpeed() > 0.0); + scenario.act("set"); + CHECK(loco.DecScndCtrl(1)); + scenario.wait(1.0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(loco.NewSpeed())); + CHECK(loco.SpeedCtrlUnit.IsActive); + scenario.full_power(60.0); + CHECK(loco.Vel == doctest::Approx(loco.SpeedCtrlValue).epsilon(0.1)); + scenario.act("off"); + CHECK(loco.DecScndCtrl(2)); + scenario.wait(1.0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + scenario.check(); + } +} + +// the vehicles with both: the field shunting as before, the cruise control on a switch of its own + +TEST_CASE("speed control: the field shunting of the vehicles with a cruise control besides, as before") { + SUBCASE("6Dg") { + scenario scenario{"speed control/both/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl()); + REQUIRE(loco.AutoRelayFlag()); + REQUIRE(loco.ScndCtrlPosNo() == 1); + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + // the shunt engages by itself at about 40 km/h (RelayType 0, by the current of the motors) + scenario.wait(10.0); + CHECK(loco.Vel < 35.0); + CHECK(loco.ScndCtrlPos() == 0); + scenario.wait(110.0); + CHECK(loco.Vel > 100.0); + CHECK(loco.ScndCtrlPos() == 1); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); + // the driver can't move the shunt + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.DecScndCtrl(2)); + scenario.check(); + } + SUBCASE("ST45") { + scenario scenario{"speed control/both/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(loco.SpeedCtrl()); + REQUIRE(loco.AutoRelayFlag()); + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(5.0); + // its relays (RelayType 45) engage the shunt from position 11 of the controller on, which the universal + // controller of the ST45, of 4 positions, never gets to: the shunt stays off + auto most{0}; + for (int i = 0; i < 9; ++i) { + scenario.wait(10.0); + most = std::max(most, loco.ScndCtrlPos()); + } + CHECK(loco.Vel > 130.0); + CHECK(most == 0); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); + // the speed buttons do nothing with the cruise control off + loco.SpeedCtrlButton(4); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + scenario.check(); + } +} + +TEST_CASE("speed control apart: which vehicles' cruise control has a switch of its own") { + struct kind { + char const *path; + bool separate; + }; + for (auto const &[path, separate] : { + // the secondary controller shunts the field: a switch of its own + kind{"6dg_v1/6dg", true}, kind{"st45_v2/301dd", true}, kind{"br285_v1/br285", true}, + // the secondary controller is the switch, the speed setter or the gears' selector of the automatic gearbox + kind{"21xm_v1/214ma", false}, kind{"21xm_v1/218ma_a_kd", false}, kind{"sa134_v1/218mc_a", false}, kind{"impuls_v1/31we-a_pr", false}, + kind{"elf_v1/21we-a", false}, kind{"e186_v2/eu47", false}, kind{"e6act_v2/e6acta", false}, kind{"en57akl_v1/akl_ra", false}, + // no cruise control + kind{"4e_v1/4e", false}, kind{"sm42_v1/6d1", false}, kind{"su45_v2/301d", false}, kind{"ep09_v2/104e", false}}) { + CAPTURE(path); + test::vehicle vehicle{test::definition::fiz(path)}; + CHECK(vehicle->IsSpeedCtrlSeparate() == separate); + CHECK_FALSE(vehicle->IsSpeedCtrlEngaged()); + } + // with a cruise control and no secondary controller, the switch is its own too + test::vehicle eu07{test::definition::fiz("4e_v1/4e").set("Cntrl", "SCPN", 0).set("SpeedControl", "SpeedCtrl", "Yes")}; + CHECK(eu07->IsSpeedCtrlSeparate()); +} + +namespace { + +// Seconds of the scenario going on, a second at a time, counting the seconds with the field shunted and not +void count_shunting(scenario &Scenario, physics::Vehicle const &Vehicle, int const Seconds, int &Shunted, int &Unshunted) { + for (int second = 0; second < Seconds; ++second) { + Scenario.wait(1.0); + ++(Vehicle.ScndCtrlPos() > 0 ? Shunted : Unshunted); + } +} + +} // namespace + +TEST_CASE("speed control apart: the 6Dg's cruise control on its own switch, the field shunting going on by itself") { + scenario scenario{"speed control apart/6dg_v1/6dg", motion() + traction() + cruise(), test::track{}}; + scenario.add("6dg_v1/6dg", 1); + auto &loco{scenario.cab()}; + get_6dg_going(scenario); + scenario.act("raise"); + move_to(loco, dg_raise); + scenario.wait(30.0); + REQUIRE(loco.Vel > 50.0); + REQUIRE(loco.ScndCtrlPos() == 1); // the shunt in + // the shunt is no cruise control: its buttons do nothing yet, the secondary controller can't switch it on + CHECK_FALSE(loco.IsSpeedCtrlEngaged()); + loco.SpeedCtrlButton(2); + CHECK(loco.SpeedCtrlValue == 0.0); + CHECK_FALSE(loco.IncScndCtrl(1)); + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + + scenario.act("cruise control on"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK_FALSE(loco.SpeedCtrlSwitch(true)); // on already + CHECK(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.IsSpeedCtrlEngaged()); + CHECK(loco.SpeedCtrlValue == doctest::Approx(std::round(loco.Vel)).epsilon(0.02)); + CHECK(loco.ScndCtrlPos() == 1); // the shunt as it was + auto const held{loco.SpeedCtrlValue}; + // the shunt goes by itself all the while, by the current of the motors, which the cruise control's demand sets + auto shunted{0}; + auto unshunted{0}; + count_shunting(scenario, loco, 60, shunted, unshunted); + CHECK(loco.Vel == doctest::Approx(held).epsilon(0.03)); + CHECK_FALSE(loco.SpeedCtrlUnit.Standby); + CHECK(loco.EimicReal() < loco.eimic); // the cruise control holding the power back + + scenario.act("two steps up"); + loco.SpeedCtrlInc(); + loco.SpeedCtrlInc(); + auto const higher{loco.SpeedCtrlValue}; + CHECK(higher == doctest::Approx(held + 10.0).epsilon(0.1)); + count_shunting(scenario, loco, 60, shunted, unshunted); + CHECK(loco.Vel == doctest::Approx(higher).epsilon(0.03)); + CHECK(loco.lineContactors.IsClosed()); + CHECK(shunted > 0); + CHECK(unshunted > 0); + CHECK_FALSE(loco.IncScndCtrl(1)); // still not the driver's + + scenario.act("button 30"); + loco.SpeedCtrlButton(0); + CHECK(loco.SpeedCtrlValue == doctest::Approx(30.0)); + scenario.wait(60.0); + // it brakes down with the air (BrakeIntervention), which opens the line contactors (the pressure switch), and + // they close again only through the first power position of the controller, as without the cruise control + CHECK(loco.Vel < 35.0); + CHECK_FALSE(loco.lineContactors.IsClosed()); + scenario.act("controller to the first power position and back up"); + move_to(loco, dg_lower); + scenario.wait(2.0); + move_to(loco, dg_raise); + scenario.wait(60.0); + CHECK(loco.lineContactors.IsClosed()); + CHECK(loco.Vel == doctest::Approx(30.0).epsilon(0.05)); + CHECK(loco.ScndCtrlPos() == 0); // out at this speed + + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + CHECK_FALSE(loco.SpeedCtrlSwitch(false)); // off already + CHECK_FALSE(loco.SpeedCtrlUnit.IsActive); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.EimicReal() == doctest::Approx(loco.eimic)); // the controller's demand again + scenario.check(); +} + +TEST_CASE("speed control apart: the ST45's cruise control on its own switch, with its buttons and the power limit") { + scenario scenario{"speed control apart/st45_v2/301dd", motion() + traction() + cruise(), test::track{}}; + scenario.add("st45_v2/301dd", 1); + auto &loco{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(0.0); + REQUIRE(loco.Vel < 50.0); + scenario.act("cruise control on, button 60"); + CHECK(loco.SpeedCtrlSwitch(true)); + CHECK(loco.SpeedCtrlUnit.IsActive); + loco.SpeedCtrlButton(4); + CHECK(loco.SpeedCtrlValue == doctest::Approx(60.0)); + scenario.wait(90.0); + CHECK(loco.Vel == doctest::Approx(60.0).epsilon(0.03)); + CHECK(loco.lineContactors.IsClosed()); + scenario.act("step up, power down"); + loco.SpeedCtrlInc(); + CHECK(loco.SpeedCtrlValue == doctest::Approx(65.0)); + CHECK(loco.SpeedCtrlPowerDec()); + CHECK(loco.SpeedCtrlUnit.DesiredPower == doctest::Approx(0.9)); + scenario.wait(60.0); + CHECK(loco.Vel == doctest::Approx(65.0).epsilon(0.03)); + CHECK(loco.EimicReal() <= 0.9 + 1e-9); + scenario.act("cruise control off"); + CHECK(loco.SpeedCtrlSwitch(false)); + // off, its buttons do nothing + loco.SpeedCtrlButton(6); + loco.SpeedCtrlInc(); + CHECK_FALSE(loco.SpeedCtrlPowerInc()); + CHECK(loco.SpeedCtrlValue == 0.0); + scenario.wait(5.0); + CHECK(loco.ScndCtrlPos() == 0); + scenario.check(); +} + +TEST_CASE("speed control apart: the switch of a cruise control without one of its own is the secondary controller, as before") { + // the 214M railbus: on, its first position; off, back to zero + scenario scenario{"speed control apart/21xm_v1/214ma", motion() + traction() + cruise(), test::track{}}; + scenario.add("21xm_v1/214ma", 1); + auto &railbus{scenario.cab()}; + REQUIRE(scenario.start_up()); + scenario.get_going(); + scenario.full_power(20.0); + scenario.act("cruise control on"); + CHECK(railbus.SpeedCtrlSwitch(true)); + CHECK(railbus.ScndCtrlPos() == 1); + CHECK(railbus.SpeedCtrlUnit.IsActive); + CHECK(railbus.IsSpeedCtrlEngaged()); + scenario.wait(10.0); + scenario.act("cruise control off"); + CHECK(railbus.SpeedCtrlSwitch(false)); + CHECK(railbus.ScndCtrlPos() == 0); + CHECK_FALSE(railbus.SpeedCtrlUnit.IsActive); + CHECK_FALSE(railbus.IsSpeedCtrlEngaged()); + scenario.wait(5.0); + scenario.check(); +} diff --git a/tests/unit/test_start_sample.cpp b/tests/unit/test_start_sample.cpp new file mode 100644 index 000000000..00e7fc781 --- /dev/null +++ b/tests/unit/test_start_sample.cpp @@ -0,0 +1,34 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "audio/startsample.h" + +#include + +// the sample a sound with a start offset (startoffset:, or the random one of motors, motor blowers and +// the running noise) begins to play from, in the 16 bit mono buffers the sound files are loaded into + +TEST_CASE("start_sample: a fraction of the samples of the buffer, two bytes each") { + CHECK(audio::start_sample(0.5f, 1000) == 250); + CHECK(audio::start_sample(0.25f, 88200) == 11025); + CHECK(audio::start_sample(0.999f, 1000) == 499); +} + +TEST_CASE("start_sample: no offset starts at the first sample") { + CHECK(audio::start_sample(0.f, 1000) == 0); + CHECK(audio::start_sample(-0.5f, 1000) == 0); + CHECK(audio::start_sample(std::numeric_limits::quiet_NaN(), 1000) == 0); +} + +TEST_CASE("start_sample: the end of the buffer is its last sample, not past it") { + // OpenAL takes an offset at or past the end of the buffer for AL_INVALID_VALUE + CHECK(audio::start_sample(1.f, 1000) == 499); + CHECK(audio::start_sample(1.5f, 1000) == 499); + CHECK(audio::start_sample(1.f, 2) == 0); +} + +TEST_CASE("start_sample: a buffer of unknown or no size starts at 0") { + CHECK(audio::start_sample(0.5f, 0) == 0); + CHECK(audio::start_sample(0.5f, 1) == 0); + CHECK(audio::start_sample(0.5f, -4) == 0); +} diff --git a/tests/unit/test_station_names.cpp b/tests/unit/test_station_names.cpp new file mode 100644 index 000000000..0bcc7953a --- /dev/null +++ b/tests/unit/test_station_names.cpp @@ -0,0 +1,295 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/utilities.h" +#include "world/stationnames.h" +#include "world/timetablereader.h" + +#include +#include +#include + +// the names of the stations (MaSzyna-EU07/maszyna#94): the timetable keeps a name as its file spells it, with its polish +// letters, for showing; the W4 stop points of the scenery, spelled in their own files, still find their station whatever +// the spelling; the form the announcement files, the scenery events and the scripts get stays the ascii one. +// the texts are windows-1250, written as bytes: the build reads the sources in any code page + +using timetable::same_station; +using timetable::station_ascii; +using timetable::station_caption; +using timetable::station_key; +using timetable::stop_point_is_for; + +namespace { + +// Biała_Podlaska, Łódź_Żabieniec, Częstochowa_Osobowa in windows-1250 +std::string const biala{"Bia\xB3" "a_Podlaska"}; +std::string const lodz{"\xA3\xF3" "d\x9F_\xAF" "abieniec"}; +std::string const czestochowa{"Cz\xEAstochowa_Osobowa"}; +// the 18 polish letters in windows-1250, as in test_win1250.cpp +std::string const letters1250{"\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF"}; + +// a timetable with polish letters in the relation and in the names of the stations +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "[________________________________________________|__________________]\n" + "[ | Bia\xB3" "a_Podlaska ]\n" + "[ Relacja pociagu | \xA3\xF3" "d\x9F_\xAF" "abieniec ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Bia\xB3" "a_Podlaska 1 | | ]\n" + "[ | | R2,H 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Cz\xEAstochowa_Osobowa 1 12.54 | 7 ]\n" + "[ | 40 | po 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | \xA3\xF3" "d\x9F_\xAF" "abieniec 2 13.01 | 6 ]\n" + "[ | | R3 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +Mtable::timetable_data read(std::string const &Text) { + std::istringstream input{Text}; + Mtable::timetable_data data; + data.TrainName = "file"; + REQUIRE(Mtable::read_timetable(input, data) == 0); + return data; +} + +// the text of a W4 as the driver gets it: a putvalues event cuts what follows # when the scenery is read +// (putvalues_event::deserialize_), a memory cell keeps the whole of its text +std::string text_seen(std::string Text, bool const Event) { + if (auto const hash{Text.find('#')}; Event && hash != std::string::npos) { + Text.erase(hash); + } + return Text; +} + +// the comparison of a W4 text with the next stop of the timetable as TController::TableUpdateStopPoint() made it before +// the names kept their letters: the text of a putvalues event lost its polish letters too when the scenery was read; +// 32 is the sizeof( std::string ) the code had for the length +bool matched_before(std::string const &Text, bool const Event, std::string const &Nextstop) { + auto text{text_seen(Text, Event)}; + if (Event) { + win1250_to_ascii(text); + } + return ToLower(text).compare(19, 32, ToLower(Nextstop)) == 0; +} + +bool matched_now(std::string const &Text, bool const Event, std::string const &Nextstop) { + return stop_point_is_for(text_seen(Text, Event), Nextstop); +} + +} // namespace + +TEST_CASE("station names: the ascii form takes the marks off the polish letters and nothing else") { + CHECK(station_ascii(biala) == "Biala_Podlaska"); + CHECK(station_ascii(lodz) == "Lodz_Zabieniec"); + CHECK(station_ascii(czestochowa) == "Czestochowa_Osobowa"); + CHECK(station_ascii(letters1250) == "ACELNOSZZacelnoszz"); + // a name without them stays, the case, the underscores and the spaces included + CHECK(station_ascii("Warszawa_Zachodnia") == "Warszawa_Zachodnia"); + CHECK(station_ascii("Nowy Targ") == "Nowy Targ"); + // what win1250_to_ascii() always made of a name: letters of other languages stay as they are + auto ostrava{std::string{"Ostrava_hl.n\xE1" "dra\x9E\xED"}}; + auto const expected{ostrava}; + CHECK(station_ascii(ostrava) == expected); + win1250_to_ascii(ostrava); + CHECK(ostrava == expected); +} + +TEST_CASE("station names: the file names of a station come from the ascii form, as before") { + // the announcement of a stop is /.ogg or sounds/sip/.ogg, of the name the timetable entry has + // as StationName; the files have no polish letters in their names + auto const data{read(timetable_text)}; + CHECK(data.TimeTable[2].StationName + ".ogg" == "Czestochowa_Osobowa.ogg"); + CHECK(data.TimeTable[3].StationName + ".ogg" == "Lodz_Zabieniec.ogg"); + // the destination board is looked up by the last station of the relation, through Bezogonkow() + CHECK(Bezogonkow(data.Relation2) == "Lodz_Zabieniec"); +} + +TEST_CASE("station names: a timetable with polish letters keeps them for showing") { + auto const data{read(timetable_text)}; + REQUIRE(data.StationCount == 3); + // as written + CHECK(data.RelationLabel1 == biala); + CHECK(data.RelationLabel2 == lodz); + CHECK(data.TimeTable[1].StationLabel == biala); + CHECK(data.TimeTable[2].StationLabel == czestochowa); + CHECK(data.TimeTable[3].StationLabel == lodz); + // what the player sees: utf-8, spaces for the underscores + CHECK(station_caption(data.TimeTable[1].StationLabel) == "Bia\xC5\x82" "a Podlaska"); + CHECK(station_caption(data.TimeTable[2].StationLabel) == "Cz\xC4\x99stochowa Osobowa"); + CHECK(station_caption(data.TimeTable[3].StationLabel) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + CHECK(station_caption(data.RelationLabel2) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + // the rest of the row reads as it did + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[2].Ah == 12); + CHECK(data.TimeTable[3].TrackNo == 2); +} + +TEST_CASE("station names: the name a timetable is matched and handed over by stays the ascii one") { + auto const data{read(timetable_text)}; + // TMTableEntry::StationName and the relation: what the W4 comparison, the announcement files, the scenery events + // (WhoIs) and the python screens get + CHECK(data.Relation1 == "Biala_Podlaska"); + CHECK(data.Relation2 == "Lodz_Zabieniec"); + CHECK(data.TimeTable[1].StationName == "Biala_Podlaska"); + CHECK(data.TimeTable[2].StationName == "Czestochowa_Osobowa"); + CHECK(data.TimeTable[3].StationName == "Lodz_Zabieniec"); + // the first station is still told to be the start of the relation by the two names being the same + CHECK(data.TimeTable[1].StationName == data.Relation1); +} + +TEST_CASE("station names: a timetable without polish letters has the same name in both forms") { + auto const plain{station_ascii(timetable_text)}; + auto const data{read(plain)}; + REQUIRE(data.StationCount == 3); + CHECK(data.RelationLabel1 == data.Relation1); + CHECK(data.RelationLabel2 == data.Relation2); + for (auto i{1}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].StationLabel == data.TimeTable[i].StationName); + } + // and reads the same as the one with the letters, but for the labels + auto const lettered{read(timetable_text)}; + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].StationName == lettered.TimeTable[i].StationName); + CHECK(data.TimeTable[i].Dh == lettered.TimeTable[i].Dh); + CHECK(data.TimeTable[i].Dm == lettered.TimeTable[i].Dm); + } + // the entry before the first station is the technical one in both forms + CHECK(data.TimeTable[0].StationName == "nowhere"); + CHECK(data.TimeTable[0].StationLabel == "nowhere"); +} + +TEST_CASE("station names: two spellings of a station have one key") { + // with and without the letters + CHECK(same_station(biala, "Biala_Podlaska")); + CHECK(same_station("Biala_Podlaska", biala)); + CHECK(same_station(lodz, "Lodz_Zabieniec")); + // some of the letters only (linia 107 has the W4 of Rzepedz spelled so) + CHECK(same_station("Rzep\xEA" "d\x9F", "Rzeped\x9F")); + // in any case, the letters with marks included (baltyk has BALTYK_GLOWNY in capitals in a timetable) + CHECK(same_station("BA\xA3TYK_G\xA3\xD3WNY", "Ba\xB3tyk_G\xB3\xF3wny")); + CHECK(same_station("BA\xA3TYK_G\xA3\xD3WNY", "baltyk_glowny")); + CHECK(same_station("ZAG\xD3RZ", "Zag\xF3rz")); + // with spaces or underscores + CHECK(same_station("Bia\xB3" "a Podlaska", biala)); + CHECK(same_station("Biala Podlaska", biala)); + CHECK(same_station("Biala Podlaska", "biala_podlaska")); + // the key itself + CHECK(station_key(biala) == "biala_podlaska"); + CHECK(station_key("Bia\xB3" "a Podlaska") == "biala_podlaska"); + CHECK(station_key(letters1250) == "acelnoszzacelnoszz"); + CHECK(station_key("").empty()); +} + +TEST_CASE("station names: different stations have different keys") { + CHECK_FALSE(same_station(biala, "Biala")); + CHECK_FALSE(same_station("Biala_Podlaska", "Biala_Podlaska_po")); + CHECK_FALSE(same_station("Lodz_Zabieniec", "Lodz_Kaliska")); + CHECK_FALSE(same_station("Gorna", "Dolna")); + CHECK_FALSE(same_station("Gorna", "")); + // no other separator stands for a space + CHECK_FALSE(same_station("Biala-Podlaska", "Biala_Podlaska")); + CHECK_FALSE(same_station("BialaPodlaska", "Biala_Podlaska")); + // letters of other languages aren't folded, as they never were + CHECK_FALSE(same_station("Ostrava_hl.n\xE1" "dra\x9E\xED", "Ostrava_hl.nadrazi")); + CHECK(same_station("Ostrava_hl.n\xE1" "dra\x9E\xED", "ostrava_hl.n\xE1" "dra\x9E\xED")); +} + +TEST_CASE("station names: a W4 finds the station of the timetable whatever the two spellings") { + auto const data{read(timetable_text)}; + // the next stop of the driver is the StationName of the entry + auto const &nextstop{data.TimeTable[1].StationName}; + // the W4 spelled with the letters, without them, in another case, with a space + CHECK(stop_point_is_for("PassengerStopPoint:" + biala, nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:BIA\xA3" "A_PODLASKA", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:biala_podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Bia\xB3" "a Podlaska", nextstop)); + CHECK(stop_point_is_for("PassengerStopPoint:Biala Podlaska", nextstop)); + // the usual W4 of a scenery, with the part which makes its event unique: the event cuts it as it's read + CHECK(matched_now("PassengerStopPoint:" + biala + "#W4-P1-T2-1", true, nextstop)); + CHECK(matched_now("PassengerStopPoint:Biala_Podlaska#W4-1", true, nextstop)); + // and the other way round: the timetable name as written against a W4 without the letters + CHECK(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", data.TimeTable[1].StationLabel)); + CHECK(stop_point_is_for("PassengerStopPoint:Lodz_Zabieniec", data.TimeTable[3].StationLabel)); + // another station, a text which isn't a W4 one + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala_Podlaska_po", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:" + lodz, nextstop)); + CHECK_FALSE(stop_point_is_for("Biala_Podlaska", nextstop)); + CHECK_FALSE(stop_point_is_for("passengerstoppoint:Biala_Podlaska", nextstop)); + CHECK_FALSE(stop_point_is_for("SetVelocity", nextstop)); + CHECK_FALSE(stop_point_is_for("", nextstop)); + // a memory cell keeps what follows the #: as before, it is a W4 only of a station which has that in its name + CHECK_FALSE(matched_now("PassengerStopPoint:Biala_Podlaska#W4-1", false, nextstop)); + CHECK(matched_now("PassengerStopPoint:Gorna#1", false, "Gorna#1")); + CHECK_FALSE(matched_now("PassengerStopPoint:Gorna", false, "Gorna#1")); + // a W4 without a name is for the end of the timetable, where the next stop has none either + CHECK(stop_point_is_for("PassengerStopPoint:", "")); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:", nextstop)); + CHECK_FALSE(stop_point_is_for("PassengerStopPoint:Biala_Podlaska", "")); +} + +TEST_CASE("station names: every W4 the driver matched before is matched now") { + // the next stops as the timetable gives them (ascii), and the special ones the driver has when there's no station + std::vector const nextstops{"Biala_Podlaska", "Lodz_Zabieniec", "Czestochowa_Osobowa", "BALTYK_GLOWNY", "Gorna", "Gorna#1", "Rzepedz", "", "nowhere", "[End of route]", + "Ostrava_hl.n\xE1" "dra\x9E\xED"}; + std::vector const names{biala, "Biala_Podlaska", "biala_podlaska", "BIA\xA3" "A_PODLASKA", "Bia\xB3" "a Podlaska", lodz, "Lodz_Zabieniec", czestochowa, + "Ba\xB3tyk_G\xB3\xF3wny", "Rzeped\x9F", "Rzep\xEA" "d\x9F", "Gorna", "Gorna#1", "Dolna", "", "nowhere", "Ostrava_hl.n\xE1" "dra\x9E\xED", + "Ostrava_hl.nadrazi", "Biala", "Biala_Podlaska_po"}; + auto matches{0}; + auto gained{0}; + for (auto const &nextstop : nextstops) { + for (auto const &name : names) { + for (auto const *suffix : {"", "#W4-1"}) { + auto const text{"PassengerStopPoint:" + name + suffix}; + for (auto const event : {true, false}) { + CAPTURE(nextstop); + CAPTURE(text); + CAPTURE(event); + auto const before{matched_before(text, event, nextstop)}; + auto const now{matched_now(text, event, nextstop)}; + // nothing is lost + CHECK((false == before || now)); + // and nothing changes for the spellings the comparison never told apart: a name without polish letters + // and without spaces + if (name == station_ascii(name) && name.find(' ') == std::string::npos) { + CHECK(before == now); + } + matches += (now ? 1 : 0); + gained += (now && false == before ? 1 : 0); + } + } + } + } + CHECK(matches > 0); + // what is new: a memory cell spelled with the polish letters, a space for an underscore + CHECK(gained > 0); + CHECK(matched_now("PassengerStopPoint:" + biala, false, "Biala_Podlaska")); + CHECK_FALSE(matched_before("PassengerStopPoint:" + biala, false, "Biala_Podlaska")); + CHECK(matched_now("PassengerStopPoint:Biala Podlaska", true, "Biala_Podlaska")); + CHECK_FALSE(matched_before("PassengerStopPoint:Biala Podlaska", true, "Biala_Podlaska")); + // and a name longer than the 32 characters the old comparison took of it + std::string const longname{"Bardzo_Dluga_Nazwa_Stacji_Wezlowej_Osobowej"}; + CHECK(matched_now("PassengerStopPoint:" + longname, true, longname)); + CHECK_FALSE(matched_before("PassengerStopPoint:" + longname, true, longname)); +} + +TEST_CASE("station names: the caption of a station is its name as written, in utf-8, with spaces") { + CHECK(station_caption(biala) == "Bia\xC5\x82" "a Podlaska"); + CHECK(station_caption(lodz) == "\xC5\x81\xC3\xB3" "d\xC5\xBA \xC5\xBB" "abieniec"); + CHECK(station_caption("Warszawa_Zachodnia") == "Warszawa Zachodnia"); + CHECK(station_caption("[End of route]") == "[End of route]"); + CHECK(station_caption("").empty()); + // a name already in utf-8 stays + CHECK(station_caption("Bia\xC5\x82" "a_Podlaska") == "Bia\xC5\x82" "a Podlaska"); +} diff --git a/tests/unit/test_switches.cpp b/tests/unit/test_switches.cpp index 72b1e47ce..444606524 100644 --- a/tests/unit/test_switches.cpp +++ b/tests/unit/test_switches.cpp @@ -7,10 +7,10 @@ TEST_CASE("switches: the train heating switch can spring back (MaSzyna-EU07/maszyna#85)") { SUBCASE("impulse") { test::vehicle vehicle{test::definition::load("cab_vehicle").set("Switches", "TrainHeating", "Impulse")}; - CHECK(vehicle->HeatingSwitchImpulse); // whichever the case it's written in + CHECK(vehicle->trainHeating.config.switchImpulse); // whichever the case it's written in } SUBCASE("a plain switch by default") { test::vehicle vehicle{test::definition::load("cab_vehicle")}; - CHECK_FALSE(vehicle->HeatingSwitchImpulse); + CHECK_FALSE(vehicle->trainHeating.config.switchImpulse); } } diff --git a/tests/unit/test_timetable.cpp b/tests/unit/test_timetable.cpp new file mode 100644 index 000000000..dff4ec6e4 --- /dev/null +++ b/tests/unit/test_timetable.cpp @@ -0,0 +1,339 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +#include "physics/vehicle.h" +#include "utilities/utilities.h" +#include "vehicle/timetableservice.h" +#include "world/timetablereader.h" + +#include +#include +#include +#include +#include + +// the timetables of the trains (.txt next to the scenery, world/timetablereader.cpp) and the service flags they +// give the AI driver (eu07/maszyna#95): the reader as it was, the flags of the header and of the stations, and what +// the driver does with them + +using timetable::service_flags; +using timetable::tristate; + +namespace { + +// a timetable the way the game's sceneries have them: the header, three stations, a speed change at the second one +std::string const timetable_text{ + " ___________________________________________________________________\n" + "[ Rodzaj i numer pociagu | Os1234 ]\n" + "[ Kategoria | Os ]\n" + "%FLAGS%" + "[________________________________________________|__________________]\n" + "[ | Gorna ]\n" + "[ Relacja pociagu | Dolna ]\n" + "[________________________________________________|__________________]\n" + "[ Wymagany % ciezaru hamujacego | 60% ]\n" + "[________________________________________________|__________________]\n" + "[ Seria i obciazenie lokomotywy | EN57 120 ]\n" + "[________________________________________________|__________________]\n" + "[ 1.13 | 60 | Gorna 1 | | ]\n" + "[ | | %WARE1% 1 12.47 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 5.06 |_____| Srodkowa 1 12.54 | 7 ]\n" + "[ | 40 | %WARE2% 1 12.55 | ]\n" + "[ | |----------------------------------1---------|--------]\n" + "[ 9.16 | | Dolna 2 13.01 | 6 ]\n" + "[ | | %WARE3% 2 | | ]\n" + "[_______|_____|__________________________________2_________|________]\n"}; + +std::string replaced(std::string Text, std::string const &Key, std::string const &Value) { + for (auto at{Text.find(Key)}; at != std::string::npos; at = Text.find(Key, at + Value.size())) { + Text.replace(at, Key.size(), Value); + } + return Text; +} + +std::string timetable_with(std::string const &Flags, std::string const &Ware1, std::string const &Ware2, std::string const &Ware3) { + return replaced(replaced(replaced(replaced(timetable_text, "%FLAGS%", Flags), "%WARE1%", Ware1), "%WARE2%", Ware2), "%WARE3%", Ware3); +} + +struct read_result { + int error; + Mtable::timetable_data data; +}; + +read_result read(std::string const &Text) { + std::istringstream input{Text}; + read_result result; + result.data.TrainName = "file"; + result.error = Mtable::read_timetable(input, result.data); + return result; +} + +service_flags flags(tristate const Doors, tristate const Doorstep, tristate const Conductor, tristate const Braketest) { + return {Doors, Doorstep, Conductor, Braketest}; +} + +auto const unset{tristate::unset}; +auto const yes{tristate::yes}; +auto const no{tristate::no}; + +// what the timetable gives, but for the service flags: to compare a timetable with flags to one without +std::string contents(Mtable::timetable_data const &Data) { + auto text{std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}\n", Data.TrainName, Data.TrainCategory, Data.TrainLabel, Data.Relation1, Data.Relation2, Data.BrakeRatio, + Data.LocSeries, Data.LocLoad, Data.StationCount)}; + for (auto i{0}; i <= Data.StationCount; ++i) { + auto const &row{Data.TimeTable[i]}; + text += std::format("{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}\n", i, row.km, row.vmax, row.StationName, row.StationWare, row.TrackNo, row.Ah, row.Am, row.Dh, row.Dm, + row.tm, row.is_maintenance, row.radio_channel); + } + return text; +} + +std::string flags_text(service_flags const &Flags) { + auto const one{[](tristate const Flag) { return Flag == tristate::unset ? '-' : Flag == tristate::yes ? 'y' : 'n'; }}; + return {one(Flags.central_doors), one(Flags.doorstep), one(Flags.conductor), one(Flags.brake_test)}; +} + +} // namespace + +TEST_CASE("timetable: the reader reads a timetable the way it always did") { + auto const [error, data]{read(timetable_with("", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.Relation2 == "Dolna"); + CHECK(data.BrakeRatio == 60.0); + CHECK(data.LocSeries == "EN57"); + CHECK(data.LocLoad == 120.0); + REQUIRE(data.StationCount == 3); + + auto const &first{data.TimeTable[1]}; + CHECK(first.StationName == "Gorna"); + CHECK(first.km == doctest::Approx(1.13)); + CHECK(first.Ah == -1); // no arrival: LoadTTfile makes it a stop, the first station being the start of the relation + CHECK(first.Dh == 12); + CHECK(first.Dm == 47.f); + CHECK(first.StationWare == "R2,H"); + CHECK(first.radio_channel == 2); + + auto const &second{data.TimeTable[2]}; + CHECK(second.StationName == "Srodkowa"); + CHECK(second.Ah == 12); + CHECK(second.Am == 54.f); + CHECK(second.Dm == 55.f); + CHECK(second.tm == 7.f); + CHECK(second.StationWare == "po"); + CHECK(second.radio_channel == -1); + + auto const &last{data.TimeTable[3]}; + CHECK(last.StationName == "Dolna"); + CHECK(last.TrackNo == 2); + CHECK(last.Ah == 13); + CHECK(last.Dh == 13); // departure as the arrival, for the delay + CHECK(last.radio_channel == 3); + // 60 km/h up to the change at the second station, 40 km/h after it + CHECK(data.TimeTable[1].vmax == 60.f); + CHECK(data.TimeTable[2].vmax == 60.f); + CHECK(data.TimeTable[3].vmax == 40.f); + // a timetable without flags leaves all of them to the vehicles + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } +} + +TEST_CASE("timetable: the row Flagi of the header sets the flags of the whole train") { + auto const [error, data]{read(timetable_with("[ Flagi AI | kierownik=nie, proba_hamulca=nie ]\n", "R2,H", "po", "R3"))}; + + CHECK(error == 0); + CHECK(data.Flags == flags(unset, unset, no, no)); + // every station has them + for (auto i{0}; i <= data.StationCount; ++i) { + CAPTURE(i); + CHECK(data.TimeTable[i].flags == data.Flags); + } + // and the rest of the header reads as before + CHECK(data.TrainName == "Os1234"); + CHECK(data.TrainCategory == "Os"); + CHECK(data.Relation1 == "Gorna"); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a station's flags hold from that station on") { + auto const [error, data]{read(timetable_with("[ Flagi AI | proba_hamulca=nie ]\n", "R2,H", "po,stopien=nie,drzwi_centralne=tak", "R3,stopien=tak"))}; + + CHECK(error == 0); + CHECK(data.TimeTable[1].flags == flags(unset, unset, unset, no)); + CHECK(data.TimeTable[2].flags == flags(yes, no, unset, no)); + CHECK(data.TimeTable[3].flags == flags(yes, yes, unset, no)); + // the flags are taken out of the station ware, the rest of it stays + CHECK(data.TimeTable[2].StationWare == "po"); + CHECK(data.TimeTable[3].StationWare == "R3"); + CHECK(data.TimeTable[3].radio_channel == 3); +} + +TEST_CASE("timetable: the flags change nothing else the timetable gives") { + auto const plain{read(timetable_with("", "R2,H", "po", "R3"))}; + auto const flagged{read(timetable_with("[ Flagi AI | kierownik=nie ]\n", "kierownik=tak,R2,H", "po,drzwi_centralne=tak", "R3,stopien=nie,proba_hamulca=nie"))}; + + CHECK(flagged.error == plain.error); + CHECK(contents(flagged.data) == contents(plain.data)); +} + +TEST_CASE("timetable: entries which aren't flags stay in the station ware") { + service_flags read_flags; + SUBCASE("no flags: the list as it was, empty entries too") { + CHECK(timetable::extract_flags("po,,R2", read_flags) == "po,,R2"); + CHECK(timetable::extract_flags("", read_flags).empty()); + CHECK(read_flags.empty()); + } + SUBCASE("an unknown key stays, a known one with an unknown value is dropped") { + CHECK(timetable::extract_flags("po,foo=1,kierownik=moze,R2", read_flags) == "po,foo=1,R2"); + CHECK(read_flags.empty()); + } + SUBCASE("keys and values in either case, 1 and 0 for tak and nie") { + CHECK(timetable::extract_flags("Kierownik=NIE,STOPIEN=1,ph", read_flags) == "ph"); + CHECK(read_flags == flags(unset, yes, no, unset)); + } +} + +TEST_CASE("timetable: a truncated timetable is an error, not a hang") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + // cut in the middle of a station, in the middle of the header, right after the top line: the reader used to go + // on reading past the end of the file forever + for (auto const cut : {text.find("Srodkowa"), text.find("Wymagany"), text.find("Rodzaj")}) { + CAPTURE(cut); + auto const [error, data]{read(text.substr(0, cut))}; + CHECK(error == Mtable::timetable_truncated); + } + // cut between two stations: the row the reader expects isn't there + auto const [error, data]{read(text.substr(0, text.find("[ 9.16")))}; + CHECK(error == -4); + CHECK(data.StationCount == 3); +} + +TEST_CASE("timetable: a timetable longer than the table is an error") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const begin{text.find("[ 5.06")}; + auto const end{text.find("[ 9.16")}; + auto const station{text.substr(begin, end - begin)}; + std::string stations; + for (auto i{0}; i < Mtable::MaxTTableSize; ++i) { + stations += station; + } + auto const [error, data]{read(text.substr(0, begin) + stations + text.substr(end))}; + CHECK(error == Mtable::timetable_too_long); + CHECK(data.StationCount == Mtable::MaxTTableSize); +} + +TEST_CASE("timetable: the reader starts from an empty table, whatever the data held before") { + auto const text{timetable_with("", "R2,H", "po", "R3")}; + auto const [error, fresh]{read(text)}; + REQUIRE(error == 0); + // a count past the table, a negative one, a stale one: the reader used to go on from it and index out of the table + for (auto const count : {Mtable::MaxTTableSize, Mtable::MaxTTableSize + 7, -3, 2}) { + CAPTURE(count); + std::istringstream input{text}; + Mtable::timetable_data data; + data.TrainName = "file"; + data.StationCount = count; + data.TimeTable[fresh.StationCount + 1].StationName = "stale"; + CHECK(Mtable::read_timetable(input, data) == 0); + CHECK(contents(data) == contents(fresh)); + CHECK(data.TimeTable[fresh.StationCount + 1].StationName == "nowhere"); + } +} + +TEST_CASE("timetable: the entry whose flags hold at the stop and on the way") { + // before the timetable is loaded, and with none + CHECK(timetable::stop_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(0, 0) == 0); + CHECK(timetable::run_flags_entry(1, 0) == 0); + // making for (or standing at) the first station: its flags at the stop, the header's on the way + CHECK(timetable::stop_flags_entry(1, 3) == 1); + CHECK(timetable::run_flags_entry(1, 3) == 0); + // after the departure from the second station + CHECK(timetable::stop_flags_entry(3, 3) == 3); + CHECK(timetable::run_flags_entry(3, 3) == 2); + // past the end of the timetable + CHECK(timetable::stop_flags_entry(4, 3) == 3); + CHECK(timetable::run_flags_entry(5, 3) == 3); +} + +TEST_CASE("timetable: the AI opens the doors from the cab as the vehicle and the timetable say") { + test::vehicle unit{test::definition::load("wagon")}; + auto const central{flags(yes, unset, unset, unset)}; + auto const notcentral{flags(no, unset, unset, unset)}; + + unit->Doors.open_control = control_t::driver; + CHECK(timetable::opens_doors(unit.physics(), {})); + CHECK(timetable::opens_doors(unit.physics(), notcentral)); // the driver's doors open only from the cab + unit->Doors.open_control = control_t::conductor; + CHECK(timetable::opens_doors(unit.physics(), {})); + // doors of mixed control are left to the passengers, unless the timetable has the driver open them all + unit->Doors.open_control = control_t::mixed; + CHECK_FALSE(timetable::opens_doors(unit.physics(), {})); + CHECK_FALSE(timetable::opens_doors(unit.physics(), notcentral)); + CHECK(timetable::opens_doors(unit.physics(), central)); + // the passengers' own doors and the automatic ones can't be opened from the cab + unit->Doors.open_control = control_t::passenger; + CHECK_FALSE(timetable::opens_doors(unit.physics(), central)); + unit->Doors.open_control = control_t::autonomous; + CHECK_FALSE(timetable::opens_doors(unit.physics(), central)); +} + +TEST_CASE("timetable: the doorsteps, the conductor and the brake test as the timetable says") { + // no flags: the doorsteps as they are, the conductor and the brake test as before + CHECK_FALSE(timetable::doorstep({}).has_value()); + CHECK(timetable::has_conductor({})); + CHECK(timetable::makes_brake_test({})); + + CHECK(timetable::doorstep(flags(unset, no, unset, unset)) == false); + CHECK(timetable::doorstep(flags(unset, yes, unset, unset)) == true); + CHECK_FALSE(timetable::has_conductor(flags(unset, unset, no, unset))); + CHECK(timetable::has_conductor(flags(unset, unset, yes, unset))); + CHECK_FALSE(timetable::makes_brake_test(flags(unset, unset, unset, no))); + CHECK(timetable::makes_brake_test(flags(unset, unset, unset, yes))); +} + +// reads every .txt file under the folder given in EU07_UNIT_TESTS_TIMETABLES (the scenery/ of the game), the way the +// game reads a timetable, and checks none of them has flags; EU07_UNIT_TESTS_TIMETABLES_DUMP names a file to write +// what was read to, to compare the reading of two builds +TEST_CASE("timetable: the timetables of the game, when asked for") { + auto const *source{std::getenv("EU07_UNIT_TESTS_TIMETABLES")}; + if (source == nullptr) { + return; + } + std::vector files; + for (auto const &entry : std::filesystem::recursive_directory_iterator{source}) { + if (entry.is_regular_file() && ToLower(entry.path().extension().string()) == ".txt") { + files.push_back(entry.path()); + } + } + std::ranges::sort(files); + std::string dump; + auto timetables{0}; + for (auto const &file : files) { + auto const name{std::filesystem::relative(file, source).generic_string()}; + CAPTURE(name); + std::ifstream input{file}; + Mtable::timetable_data data; + data.TrainName = file.stem().string(); + auto const error{Mtable::read_timetable(input, data)}; + if (error == 0 && data.StationCount > 0) { + ++timetables; + } + CHECK(data.Flags.empty()); + for (auto i{0}; i <= data.StationCount; ++i) { + CHECK(data.TimeTable[i].flags.empty()); + } + dump += std::format("== {} error {}\n", name, error) + contents(data); + } + MESSAGE(std::format("{} files, {} read as timetables", files.size(), timetables)); + if (auto const *output{std::getenv("EU07_UNIT_TESTS_TIMETABLES_DUMP")}; output != nullptr) { + std::ofstream{output, std::ios::binary} << dump; + } +} diff --git a/tests/unit/test_timetable_start.cpp b/tests/unit/test_timetable_start.cpp new file mode 100644 index 000000000..de00eba52 --- /dev/null +++ b/tests/unit/test_timetable_start.cpp @@ -0,0 +1,39 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "world/timetablestart.h" + +// the first row of a timetable is the station of departure, a stop the train waits at for its departure time, +// when it names the station the relation starts at. the loader then takes the departure time for the arrival +// one, which the row usually leaves out; a row without an arrival time is otherwise a station passed through + +TEST_CASE("timetable: the first row naming the station of the relation is the station of departure") { + CHECK(timetable::starts_at("Stacja1", "Stacja1")); + CHECK(timetable::starts_at("Zagorz", "Zagorz")); +} + +TEST_CASE("timetable: the station of departure written in capitals in the rows is still the one of the relation") { + // linia_107_poludnie.scn, Os33733: ZAGORZ in the rows, Zagorz in the relation (both with the polish letters + // stripped by the loader). taken for a station passed through, the AI left before its departure time and the + // train manager never gave the departure signal + CHECK(timetable::starts_at("ZAGORZ", "Zagorz")); + CHECK(timetable::starts_at("LEOSIN", "Leosin")); + CHECK(timetable::starts_at("Warszawa_Wschodnia", "WARSZAWA_WSCHODNIA")); +} + +TEST_CASE("timetable: a first row naming another station is not the station of departure") { + // a timetable which starts on the way, at a station the train passes through + CHECK_FALSE(timetable::starts_at("Tarnawa_Dolna", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Nowy_Zagorz", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Nowy_Zagorz")); + // a name which only begins like the other one + CHECK_FALSE(timetable::starts_at("Zagorz_Towarowy", "Zagorz")); + CHECK_FALSE(timetable::starts_at("Zagorz", "Zagorz_Towarowy")); +} + +TEST_CASE("timetable: the station names are compared as a whole, letters and the rest") { + CHECK_FALSE(timetable::starts_at("Stacja1", "Stacja2")); + CHECK_FALSE(timetable::starts_at("Stacja_1", "Stacja-1")); + CHECK_FALSE(timetable::starts_at("Stacja1", "")); + CHECK_FALSE(timetable::starts_at("", "Stacja1")); +} diff --git a/tests/unit/test_track_buckle.cpp b/tests/unit/test_track_buckle.cpp new file mode 100644 index 000000000..589ed125d --- /dev/null +++ b/tests/unit/test_track_buckle.cpp @@ -0,0 +1,322 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackBuckle.h" + +#include + +// the buckling of welded track in the heat, world/TrackBuckle.h: the shape the track takes, the force and the temperature of the rails, +// the limits it buckles at and the draws, repeated with the same seed + +namespace { + +double constexpr pi_squared{9.869604401089358}; + +int count_buckled(double const Rise, track_buckle::limits const &Limits, std::uint32_t const Seed, int const Passes) +{ + auto count{0}; + for (int pass = 1; pass <= Passes; ++pass) + { + auto const draw{track_buckle::draw(track_buckle::name_hash("tor_1234"), Seed, track_buckle::pass, static_cast(pass))}; + if (track_buckle::decide(Rise, Limits, true, draw) == track_buckle::verdict::under_train) + ++count; + } + return count; +} + +} // namespace + +TEST_CASE("the force in a rail held from growing longer is E*A*alpha*dT") +{ + // PLK ST-T1-A8 designs for 35 K, 665 kN in a 60E1 rail, with its own alpha of about 1.18e-5 + auto const force{track_buckle::thermal_force(track_buckle::area_60e1, 35.0)}; + CHECK(force == doctest::Approx(650e3).epsilon(0.03)); + CHECK(force == doctest::Approx(665e3).epsilon(0.03)); + // Kish, Samavedam: about 2.5 kips a rail for each degree F in a 136 lb rail (13.35 sq in), 20.0 kN/K + CHECK(track_buckle::thermal_force(13.35 * 6.4516e-4, 1.0) == doctest::Approx(20.0e3).epsilon(0.05)); + // lighter rails press less + CHECK(track_buckle::thermal_force(track_buckle::area_49e1, 35.0) < force); + CHECK(track_buckle::rail_area("49E1_rail") == track_buckle::area_49e1); + CHECK(track_buckle::rail_area("S42") == track_buckle::area_s42); + CHECK(track_buckle::rail_area("") == track_buckle::area_60e1); +} + +TEST_CASE("a rail is as warm as the air at night or under clouds, 17 K warmer in full sun") +{ + CHECK(track_buckle::rail_temperature(30.0, -10.0, 0.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 0.0) == doctest::Approx(47.0)); + CHECK(track_buckle::rail_temperature(30.0, 90.0, 1.0) == doctest::Approx(30.0)); + // rain cools as much as clouds + CHECK(track_buckle::rail_temperature(30.0, 90.0, 2.0) == doctest::Approx(30.0)); + CHECK(track_buckle::rail_temperature(30.0, 30.0, 0.0) == doctest::Approx(38.5)); + CHECK(track_buckle::rail_temperature(30.0, 60.0, 0.5) == doctest::Approx(30.0 + 17.0 * std::sin(60.0 * 3.141592653589793 / 180.0) * 0.5)); +} + +TEST_CASE("the limits of the grades meet the heat the tracks of PLK deform in") +{ + track_buckle::cwr track; + auto const average{track_buckle::limits_of(track, 0.0, 0.0)}; + // at the neutral 26 C under a train from rails at 58 C, by itself from 71 C: PLK, deformations with the rails above 70 C + CHECK(track.neutral + average.low == doctest::Approx(58.0)); + CHECK(track.neutral + average.high == doctest::Approx(71.0)); + // Kish, Samavedam: the chance of a buckle of a straight track grows fast from rails at 63 C with the neutral at 27 C, 36 K + CHECK(36.0 > average.low); + CHECK(36.0 < average.high); + // the design of PLK, 35 K, is short of where a good track buckles under a train + track.grade = track_buckle::grade::good; + CHECK(track_buckle::limits_of(track, 0.0, 0.0).low > 35.0); + // worked lately: weak whatever the grade + track.worked = true; + auto const worked{track_buckle::limits_of(track, 0.0, 0.0)}; + CHECK(worked.low == doctest::Approx(22.0)); + CHECK(worked.high == doctest::Approx(32.0)); + // curves and an uneven line lower them + track = {}; + CHECK(track_buckle::limits_of(track, 500.0, 0.0).low == doctest::Approx(29.0)); + CHECK(track_buckle::limits_of(track, -250.0, 0.0).low == doctest::Approx(26.0)); + CHECK(track_buckle::limits_of(track, 2000.0, 0.0).low == doctest::Approx(32.0)); + CHECK(track_buckle::limits_of(track, 0.0, 20.0).high == doctest::Approx(42.0)); + // FRA, the dynamic test: a 7.5 degree curve (233 m) with a 19 mm misalignment buckled under the train at 34 K + auto const fra{track_buckle::limits_of(track, 233.0, 19.0)}; + CHECK(34.0 > fra.low); + CHECK(34.0 < fra.high); +} + +TEST_CASE("below the lower limit a track never buckles, at the upper one it buckles by itself") +{ + track_buckle::limits const limits{32.0, 45.0}; + for (auto const draw : {0.0, 0.3, 0.999}) + { + CHECK(track_buckle::decide(31.9, limits, true, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(31.9, limits, false, draw) == track_buckle::verdict::none); + CHECK(track_buckle::decide(45.0, limits, false, draw) == track_buckle::verdict::by_itself); + // in between only under a train + CHECK(track_buckle::decide(44.0, limits, false, draw) == track_buckle::verdict::none); + } + CHECK(track_buckle::chance(32.0, limits) == doctest::Approx(0.0)); + CHECK(track_buckle::chance(38.5, limits) == doctest::Approx(0.5)); + CHECK(track_buckle::chance(50.0, limits) == doctest::Approx(1.0)); + // a train going slowly and not braking doesn't stir it up + CHECK_FALSE(track_buckle::stirs(30.0, false)); + CHECK(track_buckle::stirs(30.0, true)); + CHECK(track_buckle::stirs(60.0, false)); + CHECK_FALSE(track_buckle::stirs(3.0, true)); +} + +TEST_CASE("the share of the passes that buckle a track grows with the heat, and repeats with the seed") +{ + track_buckle::limits const limits{32.0, 45.0}; + auto const passes{4000}; + auto const quarter{count_buckled(32.0 + 0.25 * 13.0, limits, 7, passes)}; + auto const most{count_buckled(32.0 + 0.75 * 13.0, limits, 7, passes)}; + CHECK(quarter == doctest::Approx(0.25 * passes).epsilon(0.1)); + CHECK(most == doctest::Approx(0.75 * passes).epsilon(0.05)); + CHECK(count_buckled(31.0, limits, 7, passes) == 0); + // the same seed and track, the same passes + CHECK(count_buckled(38.0, limits, 7, passes) == count_buckled(38.0, limits, 7, passes)); + auto const key{track_buckle::name_hash("tor_1234")}; + CHECK(track_buckle::draw(key, 7, track_buckle::pass, 3) == track_buckle::draw(key, 7, track_buckle::pass, 3)); + // another seed, other draws + auto differ{0}; + for (std::uint64_t pass = 1; pass <= 100; ++pass) + if (track_buckle::draw(key, 7, track_buckle::pass, pass) != track_buckle::draw(key, 8, track_buckle::pass, pass)) + ++differ; + CHECK(differ == 100); + // and another track + CHECK(track_buckle::draw(track_buckle::name_hash("tor_1235"), 7, track_buckle::pass, 3) != track_buckle::draw(key, 7, track_buckle::pass, 3)); + // the draws spread over 0 to 1 + auto low{0}; + for (std::uint64_t pass = 1; pass <= 1000; ++pass) + { + auto const draw{track_buckle::draw(key, 7, track_buckle::pass, pass)}; + CHECK(draw >= 0.0); + CHECK(draw < 1.0); + if (draw < 0.5) + ++low; + } + CHECK(low == doctest::Approx(500).epsilon(0.1)); +} + +TEST_CASE("the heat buckles a track at one place in about 10 km, and wherever the bed was worked on") +{ + auto sites{0}; + auto const tracks{20000}; + for (int track = 0; track < tracks; ++track) + if (track_buckle::weak_spot(track_buckle::name_hash("t" + std::to_string(track)), 3, 500.0, false)) + ++sites; + // 500 m each, 10 000 km together: about 1000 + CHECK(sites == doctest::Approx(1000).epsilon(0.1)); + CHECK(track_buckle::weak_spot(track_buckle::name_hash("t1"), 3, 1.0, true)); +} + +TEST_CASE("the buckle has its amplitude in the middle, side lobes the other way and ends smoothly") +{ + track_buckle::shape const shape{0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(shape, 60.0) == doctest::Approx(0.4)); + CHECK(track_buckle::slope(shape, 60.0) == doctest::Approx(0.0)); + // the main lobe crosses the line one length apart + CHECK(track_buckle::offset(shape, 60.0 - 7.0) == doctest::Approx(0.0)); + CHECK(track_buckle::offset(shape, 60.0 + 7.0) == doctest::Approx(0.0)); + // the side lobes the other way, a quarter as far out + CHECK(track_buckle::offset(shape, 60.0 + 14.0) == doctest::Approx(-0.1)); + CHECK(track_buckle::offset(shape, 60.0 - 14.0) == doctest::Approx(-0.1)); + // into the straight track at the ends with no displacement, slope or curvature + CHECK(track_buckle::reach(shape) == doctest::Approx(21.0)); + for (auto const at : {-21.0 + 1e-6, 21.0 - 1e-6}) + { + CAPTURE(at); + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::slope(shape, 60.0 + at) == doctest::Approx(0.0)); + CHECK(track_buckle::bend(shape, 60.0 + at) == doctest::Approx(0.0)); + } + // nothing beyond + CHECK(track_buckle::offset(shape, 60.0 + 21.5) == 0.0); + CHECK(track_buckle::bend(shape, 60.0 - 30.0) == 0.0); + // symmetric + for (auto const at : {1.0, 4.0, 7.5, 12.0, 16.0, 20.0}) + CHECK(track_buckle::offset(shape, 60.0 + at) == doctest::Approx(track_buckle::offset(shape, 60.0 - at))); + // the largest curvature 11/9 pi^2 a / L^2 in the middle, bending back towards the line + auto const peak{track_buckle::peak_bend(0.4, 14.0)}; + CHECK(peak == doctest::Approx(11.0 / 9.0 * pi_squared * 0.4 / (14.0 * 14.0))); + CHECK(track_buckle::bend(shape, 60.0) == doctest::Approx(-peak)); + // none larger anywhere, and the curvature with no jumps + auto previous{track_buckle::bend(shape, 35.0)}; + for (auto step = 0; step <= 5000; ++step) + { + auto const at{35.0 + 0.01 * step}; + auto const bend{track_buckle::bend(shape, at)}; + CHECK(std::abs(bend) <= peak * 1.0001); + CHECK(std::abs(bend - previous) < 0.01 * peak); + previous = bend; + } + // the curvature as the displacement has it + auto const step{0.01}; + for (auto const at : {42.0, 50.5, 55.0, 61.0, 66.0, 73.0, 79.0}) + { + CAPTURE(at); + auto const slope{(track_buckle::offset(shape, at + step) - track_buckle::offset(shape, at - step)) / (2.0 * step)}; + auto const bend{(track_buckle::offset(shape, at + step) - 2.0 * track_buckle::offset(shape, at) + track_buckle::offset(shape, at - step)) / (step * step)}; + CHECK(track_buckle::slope(shape, at) == doctest::Approx(slope).epsilon(1e-4)); + CHECK(track_buckle::bend(shape, at) == doctest::Approx(bend).epsilon(1e-3)); + } + // to the left + track_buckle::shape const left{-0.4, 14.0, 60.0}; + CHECK(track_buckle::offset(left, 60.0) == doctest::Approx(-0.4)); + CHECK(track_buckle::bend(left, 60.0) == doctest::Approx(peak)); + // none + CHECK(track_buckle::offset(track_buckle::shape{}, 60.0) == 0.0); + CHECK_FALSE(track_buckle::active(track_buckle::shape{})); +} + +TEST_CASE("a bogie feels the curvature of the buckle averaged over its wheelbase, a body that of its pivots") +{ + track_buckle::shape const shape{0.3, 20.0, 50.0}; + auto const peak{track_buckle::peak_bend(0.3, 20.0)}; + CHECK(track_buckle::mean_bend(shape, 50.0, 0.0) == doctest::Approx(track_buckle::bend(shape, 50.0))); + // a bogie 2.5 m long, almost the whole of it + CHECK(std::abs(track_buckle::mean_bend(shape, 50.0, 2.5)) > 0.95 * peak); + // the mean of the curvature over the stretch, anywhere + for (auto const at : {32.0, 42.0, 50.0, 57.5, 64.0}) + { + CAPTURE(at); + auto sum{0.0}; + auto const parts{2500}; + for (int part = 0; part < parts; ++part) + sum += track_buckle::bend(shape, at - 1.25 + (part + 0.5) * 2.5 / parts); + CHECK(track_buckle::mean_bend(shape, at, 2.5) == doctest::Approx(sum / parts).epsilon(1e-3)); + } + // a body on the pivots 0 apart is a bogie + CHECK(track_buckle::body_bend(shape, 47.0, 0.0, 2.5) == doctest::Approx(track_buckle::mean_bend(shape, 47.0, 2.5))); + // a coach with its pivots 17 m apart over the main lobe: its pivots are on the flanks, which bend the other way + auto const across{track_buckle::body_bend(shape, 50.0, 17.0, 2.5)}; + CHECK(std::abs(across) < 0.5 * peak); + // the most the body feels, at any place, is less than a bogie does + auto most{0.0}; + for (auto step = 0; step <= 1200; ++step) + most = std::max(most, std::abs(track_buckle::body_bend(shape, 20.0 + 0.05 * step, 17.0, 2.5))); + CHECK(most < 0.95 * peak); + CHECK(most > 0.3 * peak); +} + +TEST_CASE("the equivalent radius of a buckle") +{ + // the default ones as sharp as the raised cosine lobes of the research note: 0.4 m by 18 m on a straight 41 m, 0.2 by 14 in a curve 50 m + CHECK(1.0 / track_buckle::peak_bend(track_buckle::straight_amplitude, track_buckle::straight_length) == doctest::Approx(41.0).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(track_buckle::curve_amplitude, track_buckle::curve_length) == doctest::Approx(49.6).epsilon(0.02)); + CHECK(1.0 / track_buckle::peak_bend(0.3, 20.0) == doctest::Approx(110.5).epsilon(0.01)); +} + +TEST_CASE("the entries buckle and cwr are read and written back") +{ + auto const buckle{track_buckle::read_buckle("400;18;60")}; + CHECK(buckle.amplitude == 400.f); + CHECK(buckle.length == 18.f); + CHECK(buckle.centre == 60.f); + CHECK(buckle.side == 0); + CHECK(track_buckle::write_buckle(buckle) == "buckle 400;18;60 "); + auto const left{track_buckle::read_buckle("250;;;-1")}; + CHECK(left.amplitude == 250.f); + CHECK(left.length < 0.f); + CHECK(left.centre < 0.f); + CHECK(left.side == -1); + CHECK(track_buckle::write_buckle(left) == "buckle 250;;;-1 "); + CHECK(track_buckle::read_buckle(track_buckle::write_buckle(left).substr(7)).side == -1); + // kept within bounds + auto const wild{track_buckle::read_buckle("5000;100;-5;3")}; + CHECK(wild.amplitude == 1000.f); + CHECK(wild.length == 60.f); + CHECK(wild.centre < 0.f); + CHECK(wild.side == 1); + CHECK(track_buckle::read_buckle("300;1").length == 4.f); + // none + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("0;18;60"))); + CHECK_FALSE(track_buckle::given(track_buckle::read_buckle("x"))); + CHECK(track_buckle::write_buckle(track_buckle::declared{}).empty()); + + auto const cwr{track_buckle::read_cwr("20;2;1")}; + CHECK(cwr.neutral == 20.f); + CHECK(cwr.grade == track_buckle::grade::weak); + CHECK(cwr.worked); + CHECK(track_buckle::write_cwr(cwr) == "cwr 20;2;1 "); + auto const partial{track_buckle::read_cwr("22")}; + CHECK(partial.neutral == 22.f); + CHECK(partial.grade == track_buckle::grade::average); + CHECK_FALSE(partial.worked); + CHECK(track_buckle::write_cwr(partial) == "cwr 22;1 "); + auto const bounded{track_buckle::read_cwr("99;7")}; + CHECK(bounded.neutral == 60.f); + CHECK(bounded.grade == 2); + // the default isn't written + CHECK(track_buckle::write_cwr(track_buckle::read_cwr("26;1;0")).empty()); +} + +TEST_CASE("a buckle is laid into its track away from the ends, out of a curve") +{ + auto const values{track_buckle::read_buckle("400;18;60")}; + auto const straight{track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.2)}; + CHECK(straight.centre == 60.0); + CHECK(straight.length == 18.0); + // the side drawn on a straight + CHECK(straight.amplitude == doctest::Approx(-0.4)); + CHECK(track_buckle::resolve(values, 200.0, 0, 0.0, 0.5, 0.7).amplitude == doctest::Approx(0.4)); + // out of a curve, whatever the draw + CHECK(track_buckle::resolve(values, 200.0, 1, 400.0, 0.5, 0.2).amplitude == doctest::Approx(0.4)); + CHECK(track_buckle::resolve(values, 200.0, -1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the side given wins + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;60;-1"), 200.0, 1, 400.0, 0.5, 0.7).amplitude == doctest::Approx(-0.4)); + // the centre kept away from the ends by the reach, 1.5 lengths, and a margin + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;5"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18;195"), 200.0, 0, 0.0, 0.5, 0.2).centre == doctest::Approx(171.0)); + // drawn where not given + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 0.0, 0.2).centre == doctest::Approx(29.0)); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400;18"), 200.0, 0, 0.0, 1.0, 0.2).centre == doctest::Approx(171.0)); + // the length by the shape of the track: a curve goes out less far and shorter + CHECK(track_buckle::resolve(track_buckle::read_buckle("200"), 200.0, 1, 400.0, 0.5, 0.2).length == track_buckle::curve_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 0, 0.0, 0.5, 0.2).length == track_buckle::straight_length); + CHECK(track_buckle::resolve(track_buckle::read_buckle("400"), 200.0, 1, 3000.0, 0.5, 0.2).length == track_buckle::straight_length); + // too short a track + CHECK_FALSE(track_buckle::active(track_buckle::resolve(values, 57.9, 0, 0.0, 0.5, 0.2))); + CHECK(track_buckle::active(track_buckle::resolve(values, 58.0, 0, 0.0, 0.5, 0.2))); + // the natural ones + CHECK(track_buckle::natural(true).amplitude == 200.f); + CHECK(track_buckle::natural(false).length == 14.f); +} diff --git a/tests/unit/test_track_buckle_derailment.cpp b/tests/unit/test_track_buckle_derailment.cpp new file mode 100644 index 000000000..98583743e --- /dev/null +++ b/tests/unit/test_track_buckle_derailment.cpp @@ -0,0 +1,135 @@ +#include "stdafx.h" +#include "doctest.h" +#include "physics/derailment.h" +#include "world/TrackBuckle.h" + +#include + +// a vehicle over a buckled track, by the criteria of derailment.h: the curvature of the buckle goes into the track +// under the vehicle as buckle_curvature (world/TrackBuckle.h: the body by the mean of its pivots, each bogie over its +// wheelbase), whole, as the curvature of the curve does + +namespace { + +// a four-axle coach: 42 t, 24.5 m over the buffers, the pivots 17.2 m and the axles of a bogie 2.5 m apart +derailment::vehicle_state coach() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 42000.0; + vehicle.axles = 4; + vehicle.length = 24.5; + vehicle.axle_base = 2.5; + vehicle.centre_of_gravity = 1.4; + return vehicle; +} +double constexpr pivots{17.2}; + +// a two-axle wagon: 25 t, 14 m over the buffers, the axles 9 m apart, which are its pivots +derailment::vehicle_state wagon() +{ + derailment::vehicle_state vehicle; + vehicle.mass = 25000.0; + vehicle.axles = 2; + vehicle.length = 14.0; + vehicle.axle_base = 9.0; + vehicle.centre_of_gravity = 1.6; + return vehicle; +} + +struct rolling_stock { + derailment::vehicle_state vehicle; + double pivots; + double base; // of the bogies, 0 without +}; +rolling_stock const four_axle{coach(), pivots, 2.5}; +rolling_stock const two_axle{wagon(), 9.0, 0.0}; + +// Outward: the side out of the curve of Radius (-1 left, 1 right), 0 on a straight track +derailment::outcome ride(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Speed, double const Step, rolling_stock const &Stock = four_axle) +{ + auto const &vehicle{Stock.vehicle}; + derailment::monitor monitor; + auto const velocity{Speed / 3.6}; + auto const reach{track_buckle::reach(Shape) + Stock.pivots}; + auto const start{Shape.centre - reach - 5.0}; + auto const advance{velocity * Step}; + auto const steps{static_cast(std::floor((2.0 * (reach + 5.0)) / advance))}; + for (auto step = 0; step <= steps; ++step) + { + auto const at{start + step * advance}; + derailment::track_state track; + track.radius = Radius; + auto const bend{track_buckle::body_bend(Shape, at, Stock.pivots, Stock.base)}; + // positive bending with the curve, whose centre is away from the outer side + track.buckle_curvature = (Outward != 0 ? -Outward * bend : bend); + auto const verdict{monitor.update(vehicle, track, velocity, velocity * Step)}; + if (verdict.result != derailment::outcome::none) + return verdict.result; + } + return derailment::outcome::none; +} + +// the lowest speed it leaves the rails at, km/h, to 0.5 km/h +double limit(track_buckle::shape const &Shape, double const Radius, int const Outward, double const Step, rolling_stock const &Stock = four_axle) +{ + auto low{5.0}; + auto high{300.0}; + while (high - low > 0.5) + { + auto const middle{0.5 * (low + high)}; + if (ride(Shape, Radius, Outward, middle, Step, Stock) != derailment::outcome::none) + high = middle; + else + low = middle; + } + return high; +} + +} // namespace + +TEST_CASE("a coach goes over a buckle slowly, and leaves the rails on it fast") +{ + // 0.3 m out over a main lobe of 20 m on a straight track: an equivalent radius of 110 m, felt by the body less + track_buckle::shape const shape{0.3, 20.0, 60.0}; + CHECK(ride(shape, 0.0, 0, 30.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 60.0, 0.01) == derailment::outcome::none); + CHECK(ride(shape, 0.0, 0, 140.0, 0.01) != derailment::outcome::none); + auto const speed{limit(shape, 0.0, 0, 0.01)}; + MESSAGE("coach over a buckle 0.3 m by 20 m on a straight track: off the rails from ", speed, " km/h"); + CHECK(speed > 60.0); + CHECK(speed < 140.0); + // the same with any step + CHECK(limit(shape, 0.0, 0, 0.002) == doctest::Approx(speed).epsilon(2.0 / speed)); + CHECK(limit(shape, 0.0, 0, 0.03) == doctest::Approx(speed).epsilon(2.0 / speed)); + // either way on a straight track + track_buckle::shape const left{-0.3, 20.0, 60.0}; + CHECK(limit(left, 0.0, 0, 0.01) == doctest::Approx(speed).epsilon(1.0 / speed)); + // a larger buckle derails it slower + auto const large{limit(track_buckle::shape{0.6, 20.0, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("0.6 m by 20 m: ", large, " km/h"); + CHECK(large < speed); + // the default one of a straight track, 0.4 m by 14 m + auto const natural{limit(track_buckle::shape{track_buckle::straight_amplitude, track_buckle::straight_length, 60.0}, 0.0, 0, 0.01)}; + MESSAGE("the default buckle of a straight track, 0.4 m by 14 m: ", natural, " km/h"); + CHECK(natural < speed); + // a body on two axles 9 m apart doesn't span the main lobe as one on bogies 17.2 m apart does: it follows the + // buckle closer, and goes off the rails slower + auto const short_wagon{limit(shape, 0.0, 0, 0.01, two_axle)}; + MESSAGE("a two-axle wagon over 0.3 m by 20 m: ", short_wagon, " km/h"); + CHECK(short_wagon < speed); + CHECK(ride(shape, 0.0, 0, 30.0, 0.01, two_axle) == derailment::outcome::none); +} + +TEST_CASE("a buckle out of a curve derails a coach slower than the same on a straight track") +{ + track_buckle::shape const shape{0.3, 20.0, 60.0}; + auto const straight{limit(shape, 0.0, 0, 0.01)}; + // a curve of 600 m without cant, the buckle to the right out of it (a curve to the left) + auto const curve{limit(track_buckle::shape{}, 600.0, 0, 0.01)}; + auto const outwards{limit(shape, 600.0, 1, 0.01)}; + MESSAGE("R 600 m: the curve alone from ", curve, " km/h, with the buckle out of it from ", outwards, " km/h, on a straight ", straight, " km/h"); + CHECK(outwards < straight); + CHECK(outwards < curve); + // one into the curve (not what the heat does) still lowers it, by its flanks which bend with the curve + CHECK(limit(track_buckle::shape{-0.3, 20.0, 60.0}, 600.0, 1, 0.01) < curve); +} diff --git a/tests/unit/test_track_check.cpp b/tests/unit/test_track_check.cpp new file mode 100644 index 000000000..f9f015f96 --- /dev/null +++ b/tests/unit/test_track_check.cpp @@ -0,0 +1,184 @@ +#include "stdafx.h" +#include "doctest.h" +#include "world/TrackCheck.h" + +#include +#include +#include +#include + +// physics.trackcheck: the geometry of the rail tracks of a scenery the criteria of derailment find suspicious, see +// world/TrackCheck.h + +namespace tc = track_check; + +namespace { + +bool has(tc::findings const &Found, tc::kind const Kind) { + return std::find(Found.kinds.begin(), Found.kinds.end(), Kind) != Found.kinds.end(); +} + +tc::track curve(double const Radius, double const Velocity, double const Cant = 0.0) { + tc::track track; + track.name = "t1"; + track.radius = Radius; + track.velocity = Velocity; + track.cant = {Cant, Cant}; + return track; +} + +double overturning(double const Radius, double const Cant = 0.0) { + auto const &eu07{tc::default_references().front().vehicle}; + return derailment::overturning_speed(Radius, std::asin(Cant / 1500.0), eu07.centre_of_gravity, 1.435) * 3.6; +} + +} // namespace + +TEST_CASE("trackcheck: the default vehicles") { + auto const &references{tc::default_references()}; + REQUIRE(references.size() == 2); + CHECK(references[0].name == "EU07"); + CHECK(references[0].vehicle.centre_of_gravity == doctest::Approx(1.65).epsilon(0.01)); + CHECK(references[1].vehicle.centre_of_gravity == doctest::Approx(1.42).epsilon(0.01)); + // the EU07 overturns at 108 km/h in a curve of 300 m without cant + CHECK(overturning(300.0) == doctest::Approx(108.0).epsilon(0.02)); +} + +TEST_CASE("trackcheck: the speed limit of a curve") { + auto const critical{overturning(300.0)}; + SUBCASE("under the speeds of the vehicles nothing") { + CHECK(tc::check(curve(300.0, critical - 10.0)).empty()); + } + SUBCASE("over the overturning speed of the EU07") { + auto const found{tc::check(curve(300.0, critical + 5.0))}; + CHECK(has(found, tc::kind::overturning)); + CHECK_FALSE(has(found, tc::kind::unlimited_curve)); + CHECK(found.defective()); + CHECK(found.text.find("over the overturning speed of EU07") != std::string::npos); + CHECK(found.text.find("speed limit 113 km/h") != std::string::npos); + } + SUBCASE("the cant raises it") { + CHECK(tc::check(curve(300.0, critical + 5.0, 100.0)).empty()); + } + SUBCASE("without a speed limit of its own it's no defect, the speed it takes is told") { + auto const found{tc::check(curve(300.0, -1.0))}; + CHECK(has(found, tc::kind::unlimited_curve)); + CHECK_FALSE(has(found, tc::kind::overturning)); + CHECK_FALSE(found.defective()); + CHECK_FALSE(tc::is_defect(tc::kind::unlimited_curve)); + CHECK(found.unlimited_speed == doctest::Approx(critical)); + CHECK(found.text.starts_with("no speed limit set (not a defect): the curve takes at most ")); + CHECK(found.text.find(" km/h, the overturning speed of EU07") != std::string::npos); + CHECK(found.text.find("speed limit none") != std::string::npos); + } + SUBCASE("nor anything when it takes them at the top speed of the EU07") { + CHECK(tc::check(curve(600.0, -1.0)).empty()); + } + SUBCASE("a tram loop of 30 m without a speed limit is no tight curve too fast") { + // the tram tracks of Tomaszewo (tramwaj106...): no category of their own, no speed limit + auto const found{tc::check(curve(30.0, -1.0))}; + CHECK(found.kinds == std::vector{tc::kind::unlimited_curve}); + CHECK(found.unlimited_speed == doctest::Approx(overturning(30.0))); + CHECK(found.unlimited_speed < 40.0); + } + SUBCASE("a closed track (speed 0) is not checked") { + CHECK(tc::check(curve(100.0, 0.0)).empty()); + } + SUBCASE("nor the speed of a switch") { + auto track{curve(150.0, 100.0)}; + track.plain = false; + CHECK(tc::check(track).empty()); + } + SUBCASE("the cant at the end with the less of it") { + auto track{curve(300.0, critical + 5.0, 100.0)}; + track.cant[0] = 0.0; + CHECK(has(tc::check(track), tc::kind::overturning)); + } +} + +TEST_CASE("trackcheck: the cant") { + SUBCASE("the same cant at both ends of a straight track") { + auto const found{tc::check(curve(0.0, 100.0, 60.0))}; + CHECK(has(found, tc::kind::cant_on_straight)); + CHECK(found.text.starts_with("cant 60 / 60 mm on a straight track")); + } + SUBCASE("a transition has it at one end only") { + auto track{curve(0.0, 100.0, 60.0)}; + track.cant[0] = 0.0; + CHECK(tc::check(track).empty()); + } + SUBCASE("a few mm are left alone") { + CHECK(tc::check(curve(0.0, 100.0, 4.0)).empty()); + } + SUBCASE("over 160 mm") { + auto const found{tc::check(curve(1000.0, 60.0, 170.0))}; + CHECK(has(found, tc::kind::cant_excess)); + CHECK(found.kinds.size() == 1); + CHECK(tc::check(curve(1000.0, 60.0, 150.0)).empty()); + } +} + +TEST_CASE("trackcheck: a tight curve") { + CHECK(has(tc::check(curve(30.0, 50.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(30.0, 30.0)), tc::kind::tight_curve)); + CHECK_FALSE(has(tc::check(curve(60.0, 50.0)), tc::kind::tight_curve)); +} + +TEST_CASE("trackcheck: the unevenness") { + auto track{curve(0.0, 100.0)}; + track.uneven.value = 14.f; + track.uneven.side = 20.f; + track.uneven.cross = 20.f; + CHECK(tc::check(track).empty()); + track.uneven.side = 40.f; + track.uneven.cross = 26.f; + auto const found{tc::check(track)}; + CHECK(has(found, tc::kind::uneven)); + CHECK(found.text.starts_with("uneven side 40, cross 26 mm out of range")); +} + +TEST_CASE("trackcheck: the scan of a scenery") { + std::vector tracks; + tracks.push_back(curve(300.0, 140.0)); + tracks.back().name = "fast"; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "worn"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0, 50.0)); + tracks.back().name = "leaning"; + tracks.back().damage = 31; + tracks.push_back(curve(0.0, 100.0)); + tracks.back().name = "fine"; + tracks.back().damage = 2; + tracks.push_back(curve(30.0, -1.0)); + tracks.back().name = "tram_1"; + tracks.push_back(curve(150.0, -1.0)); + tracks.back().name = "siding_1"; + + std::vector log; + auto const summary{tc::scan(tracks, [&](std::string const &Line) { log.push_back(Line); })}; + CHECK(summary.tracks == 6); + // the curves without a speed limit are told apart from the defects + CHECK(summary.suspicious == 2); + CHECK(summary.unlimited == 2); + CHECK(summary.slowest == doctest::Approx(overturning(30.0))); + CHECK(summary.count(tc::kind::overturning) == 1); + CHECK(summary.count(tc::kind::cant_on_straight) == 1); + CHECK(summary.count(tc::kind::tight_curve) == 0); + CHECK(summary.count(tc::kind::unlimited_curve) == 2); + // the damage flags are counted, not told track by track + CHECK(summary.damage.at(31) == 2); + CHECK(summary.damage.at(2) == 1); + REQUIRE(log.size() == 7); + CHECK(log[0].starts_with("trackcheck: fast: speed limit 140 km/h over the overturning speed of EU07")); + CHECK(log[1].starts_with("trackcheck: leaning: cant 50 / 50 mm on a straight track")); + CHECK(log[1].ends_with("damage 31)")); + CHECK(log[2].starts_with("trackcheck: tram_1: no speed limit set (not a defect): the curve takes at most ")); + CHECK(log[3].starts_with("trackcheck: siding_1: no speed limit set (not a defect)")); + CHECK(log[4] == "trackcheck: 6 rail tracks checked, 2 suspicious: overturning 1; flange climbing 0; cant on a straight 1; cant too high 0; tight curve too fast 0; uneven out of range 0"); + CHECK(log[5].starts_with("trackcheck: curves without a speed limit: 2 taking the reference vehicles under 125 km/h (not a defect), the slowest at ")); + CHECK(log[6] == "trackcheck: damage flags: 2 on 1; 31 on 2"); + for (auto const &line : log) { + CHECK(line.starts_with("trackcheck: ")); + } +} diff --git a/tests/unit/test_traction.cpp b/tests/unit/test_traction.cpp index 6da4ca506..15b00e0fe 100644 --- a/tests/unit/test_traction.cpp +++ b/tests/unit/test_traction.cpp @@ -9,7 +9,7 @@ #include "real_vehicles.h" #include "scenario.h" -#include "McZapkie/hamulce.h" +#include "physics/brakes.h" using test::definition; using test::vehicle; @@ -24,7 +24,7 @@ TEST_CASE("traction: every real powered vehicle started up, driven to full power CAPTURE(path); test::reseed_random(); vehicle real{definition::fiz(path), 0.0, "test", 1}; - if (false == test::is_powered(real.mover())) { + if (false == test::is_powered(real.physics())) { continue; } using namespace test::channels; @@ -33,9 +33,9 @@ TEST_CASE("traction: every real powered vehicle started up, driven to full power test::drive_cycle(test::driving(real), test::track{0.15, 0.0, test::catenary_3kv}, trace); // every vehicle getting its line breaker closed runs off and is braked to a stop. the SM31 and the TEM2 // barely move (COVERAGE.md); the cars of a unit taking their power from another car don't start alone - if (real->Mains) { + if (real->lineBreaker.IsClosed()) { auto const crawls{path == "sm31_v1/411d" || path == "tem2_v2/tem2a"}; - CHECK((real->DistCounter > 0.2 /* km */) != crawls); + CHECK((real->DistCounter() > 0.2 /* km */) != crawls); // but the road vehicle, which a minute of full service only slows down CHECK((real->Vel < 0.5) != (path == "road/man/nl293")); } @@ -51,7 +51,7 @@ using namespace test::channels; void stop(scenario &Scenario) { Scenario.notch_back(0); Scenario.act("brake"); - Scenario.cab().BrakeLevelSet(Scenario.cab().Handle->GetPos(bh_FB)); + Scenario.cab().BrakeLevelSet(Scenario.cab().brakes.driverValve->GetPos(bh_FB)); Scenario.wait(60.0); } @@ -72,11 +72,11 @@ TEST_CASE("traction: the line breaker opened by the catenary lost, and by too hi scenario.get_going(); auto &controlling{scenario.driver().controlling}; scenario.full_power(10.0); - REQUIRE(controlling.Mains); + REQUIRE(controlling.lineBreaker.IsClosed()); scenario.act("catenary lost"); scenario.line().voltage = 0.0; scenario.wait(5.0); - CHECK_FALSE(controlling.Mains); + CHECK_FALSE(controlling.lineBreaker.IsClosed()); CHECK(controlling.Im == doctest::Approx(0.0)); scenario.act("catenary back"); scenario.line().voltage = test::catenary_3kv; @@ -86,7 +86,7 @@ TEST_CASE("traction: the line breaker opened by the catenary lost, and by too hi scenario.act("overvoltage"); scenario.line().voltage = controlling.EnginePowerSource.CollectorParameters.MaxV + 300.0; scenario.wait(5.0); - CHECK(controlling.Mains == (controlling.EngineType == TEngineType::ElectricSeriesMotor && false == controlling.EnginePowerSource.CollectorParameters.OVP)); + CHECK(controlling.lineBreaker.IsClosed() == (controlling.EngineType == TEngineType::ElectricSeriesMotor && false == controlling.EnginePowerSource.CollectorParameters.OVP)); scenario.line().voltage = test::catenary_3kv; stop(scenario); scenario.check(); @@ -104,11 +104,11 @@ TEST_CASE("traction: the ET42 at the high current setting, its halves in series, CHECK(et42.CurrentSwitch(high) == high); // the relay takes the setting at the next step, with the controller at zero scenario.get_going(); - CHECK((et42.Imax == et42.ImaxHi) == high); + CHECK((et42.Imax == et42.ImaxHi()) == high); scenario.full_power(60.0); // at the high current setting the controller stops at the last series position: the halves' motors stay // in series, at half the voltage each, for a heavy start, and the train crawls - CHECK((et42.RList[et42.MainCtrlPos].Bn > 1) != high); + CHECK((et42.RList[et42.MainCtrlPos()].Bn > 1) != high); CHECK(et42.Vel > (high ? 30.0 : 90.0)); CHECK(et42.Vel < (high ? 50.0 : 110.0)); scenario.act("controller to zero"); @@ -154,14 +154,14 @@ TEST_CASE("traction: the field shunting relays of the diesel-electric locomotive CHECK(controlling.RelayType == relaytype); scenario.get_going(); scenario.full_power(120.0); - CHECK(controlling.ScndCtrlPos == controlling.ScndCtrlPosNo); + CHECK(controlling.ScndCtrlPos() == controlling.ScndCtrlPosNo()); auto expected{shunting.begin()}; for (auto const position : {11, 10, 7, 3}) { CAPTURE(position); scenario.act(std::format("notch back to {}", position)); scenario.notch_back(position); scenario.wait(15.0); - CHECK(controlling.ScndCtrlPos == *expected++); + CHECK(controlling.ScndCtrlPos() == *expected++); } stop(scenario); scenario.check(); @@ -183,11 +183,11 @@ TEST_CASE("traction: the stages of the EW58's electrodynamic brake, set by the p ew58.BrakeLevelSet(position); scenario.wait(6.0); CHECK(ew58.TUHEX_StageActual == stage); - CHECK(ew58.DynamicBrakeFlag); + CHECK(ew58.brakes.electrodynamic.on); CHECK(ew58.Im < 0.0); } scenario.act("release"); - ew58.BrakeLevelSet(ew58.Handle->GetPos(bh_RP)); + ew58.BrakeLevelSet(ew58.brakes.driverValve->GetPos(bh_RP)); scenario.wait(10.0); CHECK(ew58.TUHEX_StageActual == 0); scenario.check(); @@ -201,8 +201,8 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.get_going(); // the second controller of the EU47 sets the speed to hold (SpeedCtrlType=Time): position 2 keeps the speed // set, 3 raises it by 10 km/h every SpeedCtrlDelay, 4 sets the top speed, 1 lowers it, 0 drops it - REQUIRE(eu47.ScndCtrlPosNo == 4); - REQUIRE(eu47.SpeedCtrlTypeTime); + REQUIRE(eu47.ScndCtrlPosNo() == 4); + REQUIRE(eu47.SpeedCtrlTypeTime()); scenario.full_power(0.0); scenario.act("speed up"); for (int i = 0; i < 3; ++i) { @@ -227,7 +227,7 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.act("top speed"); eu47.IncScndCtrl(2); scenario.wait(5.0); - CHECK(eu47.SpeedCtrlValue == doctest::Approx(eu47.Vmax)); + CHECK(eu47.SpeedCtrlValue == doctest::Approx(eu47.Vmax())); scenario.act("speed control off"); while (eu47.DecScndCtrl(1)) { // down to zero @@ -240,9 +240,9 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam scenario.act("local brake"); eu47.IncLocalBrakeLevel(LocalBrakePosNo); scenario.wait(5.0); - CHECK(eu47.DynamicBrakeFlag); + CHECK(eu47.brakes.electrodynamic.on); CHECK(eu47.Im == doctest::Approx(0.0)); - CHECK(eu47.BrakePress > 2.0); + CHECK(eu47.brakes.cylinderPressure > 2.0); scenario.act("local brake off"); eu47.DecLocalBrakeLevel(LocalBrakePosNo); scenario.wait(10.0); @@ -252,12 +252,12 @@ TEST_CASE("traction: the induction motor drive's speed control, its electrodynam CAPTURE(voltage); scenario.line().voltage = voltage; scenario.act(std::format("service brake at {} V", static_cast(voltage))); - eu47.BrakeLevelSet(eu47.Handle->GetPos(bh_FB)); + eu47.BrakeLevelSet(eu47.brakes.driverValve->GetPos(bh_FB)); scenario.wait(6.0); - CHECK(eu47.DynamicBrakeFlag); + CHECK(eu47.brakes.electrodynamic.on); CHECK(eu47.Im < -100.0); CHECK((eu47.Vadd > 1.0) == (voltage > eu47.EnginePowerSource.CollectorParameters.MaxV)); - eu47.BrakeLevelSet(eu47.Handle->GetPos(bh_RP)); + eu47.BrakeLevelSet(eu47.brakes.driverValve->GetPos(bh_RP)); scenario.wait(6.0); } scenario.line().voltage = test::catenary_3kv; diff --git a/tests/unit/test_traction_tail.cpp b/tests/unit/test_traction_tail.cpp new file mode 100644 index 000000000..ca47d1763 --- /dev/null +++ b/tests/unit/test_traction_tail.cpp @@ -0,0 +1,69 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "utilities/parser.h" +#include "world/TractionTail.h" + +#include +#include + +// the optional entries of a traction node after "vis" / "unvis" (world/TractionTail.h): what the load reads, the save +// of the editor writes back, so an edited span keeps its own tension and the ends of its second messenger + +namespace { + +traction_tail read(std::string const &Text, glm::dvec3 const &Origin = glm::dvec3{0.0}) { + cParser parser(Text, cParser::buffer_TEXT); + traction_tail tail; + read_traction_tail(parser, Origin, tail); + return tail; +} + +std::string write(traction_tail const &Tail) { + std::ostringstream output; + write_traction_tail(output, Tail); + return output.str(); +} + +} // namespace + +TEST_CASE("traction tail: tension, rope2, parallel and type survive a load and a save") { + auto const loaded{read("parallel Other_Span type YwsC120-2C tension 1000 900 rope2 start 1 2 3 rope2 end 4.5 5 6 endtraction", glm::dvec3{10.0, 0.0, -20.0})}; + CHECK(loaded.parallel == "other_span"); + CHECK(loaded.type == "YwsC120-2C"); + CHECK(loaded.tension[0] == doctest::Approx(1000.0)); + CHECK(loaded.tension[1] == doctest::Approx(900.0)); + REQUIRE(loaded.rope2set[0]); + REQUIRE(loaded.rope2set[1]); + // the points get the origin of the scenery, as the points of the span do + CHECK(loaded.rope2[0].x == doctest::Approx(11.0)); + CHECK(loaded.rope2[0].z == doctest::Approx(-17.0)); + CHECK(loaded.rope2[1].x == doctest::Approx(14.5)); + + // written in the scenery's coordinates, read back without an origin: the same + auto const written{write(loaded)}; + auto const again{read(written + "endtraction")}; + CHECK(again.parallel == loaded.parallel); + CHECK(again.type == loaded.type); + CHECK(again.tension == loaded.tension); + CHECK(again.rope2set == loaded.rope2set); + for (int end = 0; end < 2; ++end) { + CAPTURE(end); + CHECK(again.rope2[end].x == doctest::Approx(loaded.rope2[end].x)); + CHECK(again.rope2[end].y == doctest::Approx(loaded.rope2[end].y)); + CHECK(again.rope2[end].z == doctest::Approx(loaded.rope2[end].z)); + } + CHECK(write(again) == written); +} + +TEST_CASE("traction tail: a span without the entries is written as before") { + CHECK(write(read("endtraction")).empty()); + // parallel and type alone, in the order and the form the save always wrote them + CHECK(write(read("parallel p2 type C120-2C endtraction")) == "parallel p2 type C120-2C "); + // one end of the second messenger only + auto const one{read("rope2 end 1 2 3 endtraction")}; + CHECK_FALSE(one.rope2set[0]); + CHECK(write(one) == "rope2 end 1 2 3 "); + // the tension of the messenger alone keeps the 0 of the contact wires (as in the type) + CHECK(write(read("tension 1200 0 endtraction")) == "tension 1200 0 "); +} diff --git a/tests/unit/test_uc_steps.cpp b/tests/unit/test_uc_steps.cpp index eb1b26fa4..889774d48 100644 --- a/tests/unit/test_uc_steps.cpp +++ b/tests/unit/test_uc_steps.cpp @@ -26,25 +26,25 @@ void get_ready(vehicle &Railbus, test::track const &Track) { for (int i = 0; i < 3 && Railbus->DirActive <= 0; ++i) { Railbus->DirectionForward(); } - while (Railbus->MainCtrlPos < hold && Railbus->IncMainCtrl(1)) { + while (Railbus->MainCtrlPos() < hold && Railbus->IncMainCtrl(1)) { ; } - while (Railbus->MainCtrlPos > hold && Railbus->DecMainCtrl(1)) { + while (Railbus->MainCtrlPos() > hold && Railbus->DecMainCtrl(1)) { ; } - REQUIRE(Railbus->MainCtrlPos == hold); + REQUIRE(Railbus->MainCtrlPos() == hold); Railbus.run(2.0, Track); REQUIRE(Railbus->eimic == doctest::Approx(0.0)); } void move_to(vehicle &Railbus, int const Position) { - while (Railbus->MainCtrlPos < Position && Railbus->IncMainCtrl(1)) { + while (Railbus->MainCtrlPos() < Position && Railbus->IncMainCtrl(1)) { ; } - while (Railbus->MainCtrlPos > Position && Railbus->DecMainCtrl(1)) { + while (Railbus->MainCtrlPos() > Position && Railbus->DecMainCtrl(1)) { ; } - REQUIRE(Railbus->MainCtrlPos == Position); + REQUIRE(Railbus->MainCtrlPos() == Position); } bool on_step(double const Value, double const Step) { @@ -56,7 +56,7 @@ bool on_step(double const Value, double const Step) { TEST_CASE("controls: the universal controller with CtrlValStep sets its power in whole steps") { test::track const line{0.15, 0.0}; vehicle railbus{definition::fiz("21xm_v1/214ma").set("UCList", "CtrlValStep", 0.05), 0.0, "test", 1}; - REQUIRE(railbus->UniCtrlValStep == doctest::Approx(0.05)); + REQUIRE(railbus->UniCtrlValStep() == doctest::Approx(0.05)); get_ready(railbus, line); // a tap on the raising position: one step at once, kept by the holding one @@ -104,7 +104,7 @@ TEST_CASE("controls: the universal controller with CtrlValStep sets its power in TEST_CASE("controls: the universal controller without CtrlValStep sets its power continuously, as before") { test::track const line{0.15, 0.0}; vehicle railbus{definition::fiz("21xm_v1/214ma"), 0.0, "test", 1}; - REQUIRE(railbus->UniCtrlValStep == 0.0); + REQUIRE(railbus->UniCtrlValStep() == 0.0); get_ready(railbus, line); // a tap moves it by 0.01, held it goes on at 0.15 a second after the initial delay move_to(railbus, raise); diff --git a/tests/unit/test_universal_drag.cpp b/tests/unit/test_universal_drag.cpp new file mode 100644 index 000000000..f520b694f --- /dev/null +++ b/tests/unit/test_universal_drag.cpp @@ -0,0 +1,143 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "vehicle/universaldrag.h" + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal with "drag: " +// in its definition is dragged with the mouse to any position between its ends and stays there when let go; a click +// and the keys move it to its ends. the mouse and TGauge are not part of the core library, the rules they follow are + +using universal_drag::direction; + +TEST_CASE("universal drag: the values of the drag key") { + CHECK(universal_drag::parse("up") == direction::up); + CHECK(universal_drag::parse("down") == direction::down); + CHECK(universal_drag::parse("left") == direction::left); + CHECK(universal_drag::parse("right") == direction::right); + // yes drags it up, as the sliders of the controllers + CHECK(universal_drag::parse("yes") == direction::up); + CHECK(universal_drag::parse("true") == direction::up); + CHECK(universal_drag::parse("1") == direction::up); + CHECK(universal_drag::parse("no") == direction::none); + CHECK(universal_drag::parse("false") == direction::none); + CHECK(universal_drag::parse("0") == direction::none); + CHECK(universal_drag::parse("none") == direction::none); + // a value it doesn't know is reported, and the control can't be dragged + CHECK_FALSE(universal_drag::parse("sideways").has_value()); + CHECK_FALSE(universal_drag::parse("").has_value()); + CHECK_FALSE(universal_drag::parse("Up").has_value()); +} + +TEST_CASE("universal drag: a push universal can't be dragged, it springs back when let go") { + CHECK(universal_drag::effective(direction::up, true) == direction::none); + CHECK(universal_drag::effective(direction::left, true) == direction::none); + CHECK(universal_drag::effective(direction::up, false) == direction::up); + CHECK(universal_drag::effective(direction::none, false) == direction::none); +} + +TEST_CASE("universal drag: the move of the cursor along the direction") { + auto const size{600.0}; + // the cursor's y grows downwards + CHECK(universal_drag::along(direction::up, 0.0, -60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::up, 0.0, 60.0, size) == doctest::Approx(-0.1)); + CHECK(universal_drag::along(direction::down, 0.0, 60.0, size) == doctest::Approx(0.1)); + CHECK(universal_drag::along(direction::left, -150.0, 0.0, size) == doctest::Approx(0.25)); + CHECK(universal_drag::along(direction::right, -150.0, 0.0, size) == doctest::Approx(-0.25)); + // the move across the direction doesn't count + CHECK(universal_drag::along(direction::up, 300.0, 0.0, size) == 0.0); + CHECK(universal_drag::along(direction::left, 0.0, 300.0, size) == 0.0); + // nothing to drag + CHECK(universal_drag::along(direction::none, 100.0, 100.0, size) == 0.0); + CHECK(universal_drag::along(direction::up, 0.0, -60.0, 0.0) == 0.0); +} + +TEST_CASE("universal drag: the position is kept between the ends") { + CHECK(universal_drag::clamp(-0.5) == 0.f); + CHECK(universal_drag::clamp(1.5) == 1.f); + CHECK(universal_drag::clamp(0.25) == doctest::Approx(0.25f)); +} + +TEST_CASE("universal drag: the keys and a click move the control to the end farther from its position") { + CHECK(universal_drag::toggled(0.f) == 1.f); + CHECK(universal_drag::toggled(1.f) == 0.f); + // a control left in between + CHECK(universal_drag::toggled(0.3f) == 1.f); + CHECK(universal_drag::toggled(0.7f) == 0.f); + // half way, as the two-state universals always did + CHECK(universal_drag::toggled(0.5f) == 0.f); +} + +TEST_CASE("universal drag: a drag takes the control to a position between its ends, where it stays") { + auto const size{600.0}; + universal_drag::drag drag{direction::up, 0.f}; + // the first position of the cursor is where the drag starts from, even if the hidden cursor was moved + CHECK_FALSE(drag.move(400.0, 500.0, size)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); + // up by a quarter of the size + CHECK(drag.move(400.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // sideways it stays + CHECK_FALSE(drag.move(700.0, 350.0, size)); + CHECK(drag.position() == doctest::Approx(0.25f)); + // back down a little + CHECK(drag.move(700.0, 380.0, size)); + CHECK(drag.position() == doctest::Approx(0.2f)); + CHECK_FALSE(drag.is_click()); + // let go: the position is what the drag left, the control keeps it + CHECK(drag.start() == 0.f); + CHECK(drag.position() == doctest::Approx(0.2f)); +} + +TEST_CASE("universal drag: the control stops at its ends, and moving back takes it back at once") { + auto const size{100.0}; + universal_drag::drag drag{direction::right, 0.9f}; + drag.move(0.0, 0.0, size); + CHECK(drag.move(50.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // further on it stays at the end + CHECK_FALSE(drag.move(200.0, 0.0, size)); + CHECK(drag.position() == 1.f); + // back: from the end, not from where the cursor went past it + CHECK(drag.move(190.0, 0.0, size)); + CHECK(drag.position() == doctest::Approx(0.9f)); + // and the other end + CHECK(drag.move(0.0, 0.0, size)); + CHECK(drag.position() == 0.f); +} + +TEST_CASE("universal drag: a press let go with the cursor barely moved is a click") { + auto const size{600.0}; + universal_drag::drag drag{direction::down, 0.4f}; + drag.move(10.0, 10.0, size); + // a jitter of the hand, under the travel of a click + drag.move(11.0, 13.0, size); + drag.move(10.0, 11.0, size); + CHECK(drag.is_click()); + // the click moves it to the end farther from it, as the key does + CHECK(universal_drag::toggled(drag.position()) == 1.f); + // a drag there and back is a drag, though it ends where it started + universal_drag::drag back{direction::down, 0.4f}; + back.move(0.0, 0.0, size); + back.move(0.0, 60.0, size); + back.move(0.0, 0.0, size); + CHECK_FALSE(back.is_click()); + CHECK(back.position() == doctest::Approx(0.4f)); +} + +TEST_CASE("universal drag: a drag starts from the position the control is set to") { + universal_drag::drag drag{direction::up, 0.6f}; + CHECK(drag.start() == doctest::Approx(0.6f)); + CHECK(drag.position() == doctest::Approx(0.6f)); + // a position out of the range is brought into it + CHECK(universal_drag::drag{direction::up, 3.f}.position() == 1.f); + CHECK(universal_drag::drag{direction::up, -1.f}.position() == 0.f); +} + +TEST_CASE("universal drag: a control which can't be dragged doesn't move") { + universal_drag::drag drag{direction::none, 0.f}; + drag.move(0.0, 0.0, 600.0); + CHECK_FALSE(drag.move(300.0, -300.0, 600.0)); + CHECK(drag.position() == 0.f); + CHECK(drag.is_click()); +} diff --git a/tests/unit/test_uphill_start.cpp b/tests/unit/test_uphill_start.cpp index d450af68b..e487fc703 100644 --- a/tests/unit/test_uphill_start.cpp +++ b/tests/unit/test_uphill_start.cpp @@ -101,3 +101,113 @@ TEST_CASE("uphill start: once ended, the top-up stays ended for the start") { state = {}; CHECK(brake_top_up(state, 0.5 * grade, grade, 1.5, application, application) == top_up_action::step); } + +// the rest of a start: when it begins, when it is given up, when the train brake may be released, when the release +// phase is over and how much power is applied against the releasing brake + +namespace { + +// the ST43 train standing at the signal on its train brake, asked to go +uphill_start::situation standing_train() { + uphill_start::situation now; + now.standing = true; + now.speed_up = true; + now.speed_asked = true; + now.train_brake_applied = true; + now.grade_force = grade; + return now; +} + +} // namespace + +TEST_CASE("uphill start: begins with the whole train at a stand on the train brake, asked to go") { + auto now{standing_train()}; + CHECK(uphill_start::begins(now)); + SUBCASE("not while the head stands for a moment and the train rolls back") { + now.consist_velocity = -0.8; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not without the train brake to hold the train") { + now.train_brake_applied = false; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not before the brakes of the train are charged") { + now.consist_charged = false; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not when not asked to go") { + now.speed_up = false; + CHECK_FALSE(uphill_start::begins(now)); + now.speed_up = true; + now.speed_asked = false; + CHECK_FALSE(uphill_start::begins(now)); + } + SUBCASE("not under way") { + now.standing = false; + CHECK_FALSE(uphill_start::begins(now)); + } +} + +TEST_CASE("uphill start: given up when the train as a whole rolls back, not its head") { + auto now{standing_train()}; + // the locomotive runs back into the slack, the rest of the train stands + now.velocity = -1.0; + now.consist_velocity = -0.1; + CHECK_FALSE(uphill_start::rolls_back(now)); + now.consist_velocity = -0.6; + CHECK(uphill_start::rolls_back(now)); +} + +TEST_CASE("uphill start: the train brake is released once the power holds the train") { + auto now{standing_train()}; + now.tractive_force = 1.05 * grade; + CHECK_FALSE(uphill_start::power_holds(now, 10.0)); + now.tractive_force = 1.15 * grade; + CHECK(uphill_start::power_holds(now, 10.0)); + SUBCASE("or the train is under way") { + now.tractive_force = 0.5 * grade; + now.velocity = 1.2; + CHECK(uphill_start::power_holds(now, 10.0)); + } + SUBCASE("or a locomotive that can't hold the train has had its time") { + now.tractive_force = 0.5 * grade; + CHECK_FALSE(uphill_start::power_holds(now, uphill_start::hold_time - 1.0)); + CHECK(uphill_start::power_holds(now, uphill_start::hold_time + 1.0)); + } +} + +TEST_CASE("uphill start: the release phase ends when the brakes are off, or after its time") { + auto now{standing_train()}; + CHECK_FALSE(uphill_start::released(now, 30.0)); + now.consist_released = true; + CHECK(uphill_start::released(now, 30.0)); + SUBCASE("a brake that doesn't come off ends it all the same") { + now.consist_released = false; + CHECK_FALSE(uphill_start::released(now, uphill_start::release_time - 1.0)); + CHECK(uphill_start::released(now, uphill_start::release_time + 1.0)); + } +} + +TEST_CASE("uphill start: against the releasing brake no more power is added than holds the train") { + // outside the release phase the start doesn't limit the power + CHECK(uphill_start::may_add_power(false, 3.0 * grade, grade)); + CHECK(uphill_start::may_add_power(true, 1.05 * grade, grade)); + CHECK_FALSE(uphill_start::may_add_power(true, 1.15 * grade, grade)); +} + +TEST_CASE("uphill start: on coarse notches the power stays on the first one that holds the train") { + // an EU07 at a standstill on 3 kV gives about 29, 52, 79 and 104 kN on notches 1-4 (eu07/maszyna#396): with a + // train of 300 t on 10 per mille, 29.4 kN of grade force, notch 2 jumps from 0.99 to 1.77 x the grade force + std::array const notches{29000.0, 52000.0, 79000.0, 104000.0}; + double const holding{300000.0 * 9.81 * 0.01}; + auto notch{0}; + auto force{0.0}; + // in the release phase, a notch added an update as long as power may be added + for (auto update{0}; update < 10; ++update) { + if (uphill_start::may_add_power(true, force, holding) && (notch < static_cast(notches.size()))) { + force = notches[notch++]; + } + } + CHECK(notch == 2); + CHECK(force / holding == doctest::Approx(1.77).epsilon(0.01)); +} diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 3bcb565a8..d9309fa46 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -7,8 +7,11 @@ #include "utilities/Globals.h" #include "utilities/utilities.h" +#include "utilities/uuid.hpp" #include +#include +#include #include // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their @@ -234,10 +237,39 @@ TEST_CASE("utilities: the seed a text stands for is its number, or its hash the // a number which isn't a seed is a word: negative, or too big CHECK(seed_of("-5") == 1448u); CHECK(seed_of("4294967296") == 3632702254u); + CHECK(seed_of("+5") == 1386u); + CHECK(seed_of("-0") == 1443u); // the bytes over ascii count as positive CHECK(seed_of("\xB9") == 185u); - // a word starting with digits is taken for the number in front of it - CHECK(seed_of("12abc") == 12u); + // leading zeros are the same number + CHECK(seed_of("007") == 7u); + CHECK(seed_of("00") == 0u); +} + +TEST_CASE("utilities: a seed is the whole text as a number, or the whole text as a word") { + // digits with something after them are a word, not the number in front of them + CHECK(seed_of("4242abc") == 386617702u); + CHECK(seed_of("4242abc") != 4242u); + CHECK(seed_of("12abc") == 46838433u); + CHECK(seed_of("0x10") == 1546855u); + // a space is part of the word as well: the settings and the command line give the seed without them + CHECK(seed_of("4242 ") == 49564196u); + CHECK(seed_of(" 4242") == 31151516u); + // so two words starting with the same digits stand for two seeds + CHECK(seed_of("12abc") != seed_of("12xyz")); +} + +TEST_CASE("utilities: randomseed and -seed give a seed, 0 too, and an empty text none") { + CHECK(seed_given("0") == std::optional{0u}); + CHECK(seed_given("00") == std::optional{0u}); + CHECK(seed_given("4242") == std::optional{4242u}); + CHECK(seed_given("hello") == std::optional{99162322u}); + CHECK(seed_given("4242abc") == std::optional{386617702u}); + CHECK_FALSE(seed_given("").has_value()); + // a seed which is given is not the same as none, whatever its number + CHECK(seed_given("0").has_value()); + // and the settings start without one, to be drawn + CHECK(std::make_unique()->random_seed_given == false); } TEST_CASE("utilities: a version 4 uuid is drawn from the random numbers of the simulation") { @@ -266,6 +298,21 @@ TEST_CASE("utilities: a version 4 uuid is drawn from the random numbers of the s CHECK(generate_uuid_v4() == first); } +TEST_CASE("utilities: the uuid of a scene node takes none of the random numbers of the simulation") { + // a node added to the scenery (or a memory cell the program makes before it) left the numbers drawn after it as + // they were: the physics of a run of a seed doesn't depend on how many nodes the scenery has + Global.random_engine.seed(11); + auto const before{Global.random_engine}; // NOSONAR: a copy of the simulation's engine to compare with; nothing secret is drawn + auto const first{UID::random()}; + auto const second{UID::random()}; + CHECK(Global.random_engine == before); + CHECK(first != second); + // the version and the variant of a version 4 uuid + CHECK((first.bytes[6] >> 4) == 4); + CHECK((first.bytes[8] >> 6) == 2); + CHECK(first.to_string().size() == 36); +} + TEST_CASE("utilities: a failure is drawn only over the threshold, the likelier the less the value is over it") { debug_mode const mode{false}; for (auto draw{0}; draw < 50; ++draw) { @@ -405,18 +452,18 @@ TEST_CASE("utilities: a text for the timetable loses its marks, control characte CHECK(Bezogonkow("Bia\xA3" "a_Podlaska", true) == "BiaLa Podlaska"); } -TEST_CASE("utilities: the polish letters from 0xB2 on lose their marks only in a build which makes one byte of the table's mark") { - // the table of Bezogonkow() has a plus-minus sign for 0xB1, written as the character in the source, a utf-8 file. - // MSVC puts it into the table as the one byte of the system's code page, and the table is as it was meant. - // GCC and Clang put the two bytes of utf-8 there, which moves the entries after it by one (see COVERAGE.md) - if (Bezogonkow("\xB1") == "\xB1") { - CHECK(Bezogonkow(kWin1250) == "ACELNOSZZacelnoszz"); - } - else { - // the first byte of the sign for 0xB1, the second for 0xB2, and each letter after them as the entry before its own - CHECK(Bezogonkow("\xB1\xB2") == "\xC2\xB1"); - CHECK(Bezogonkow(kWin1250) == "ALELDNSZZ,le,dnszl"); - } +TEST_CASE("utilities: the polish letters from 0xB2 on lose their marks in every build") { + // the table of Bezogonkow() has the plus-minus sign for 0xB1. it used to be written as the character in the source, + // a utf-8 file: GCC and Clang put the two bytes of utf-8 into the table, which moved the entries after it by one + // (the polish letters came out as "ALELDNSZZ,le,dnszl"). now it's the byte, and the table is the same everywhere + CHECK(Bezogonkow("\xB1") == "\xB1"); + CHECK(Bezogonkow("\xB1\xB2") == "\xB1,"); + CHECK(Bezogonkow(kWin1250) == "ACELNOSZZacelnoszz"); + // the last entry of the table, and the first: none is left out and none added + CHECK(Bezogonkow("\xFF") == "?"); + CHECK(Bezogonkow("\x80") == "E"); + // the letters of other languages the table knows (c-caron, e-caron, s-caron, u-ring, a-acute) + CHECK(Bezogonkow("\xE8\xEC\x9A\xF9\xE1") == "cesua"); } TEST_CASE("utilities: utf-8 is decoded into code points of one to four bytes") { @@ -697,11 +744,84 @@ TEST_CASE("utilities: the folders of the user's settings and of the cache are na #if defined(_WIN32) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("APPDATA") == nullptr)); CHECK(user_cache_path("x").empty() == (std::getenv("LOCALAPPDATA") == nullptr)); -#else +#elif defined(__APPLE__) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("HOME") == nullptr)); +#else + // the folders the XDG variables of this environment give, or the ones in the home folder + auto const expected{[](char const *Variable, char const *Fallback, char const *Filename) { + auto const base{xdg_base_directory(std::getenv(Variable), std::getenv("HOME"), Fallback)}; + return base.empty() ? std::filesystem::path{} : base / "MaSzyna" / Filename; + }}; + auto const config{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; + CHECK(user_config_path("eu07.ini") == (config.empty() ? std::filesystem::path{} : config / "eu07.ini")); + CHECK(user_cache_path("geoportal") == expected("XDG_CACHE_HOME", ".cache", "geoportal")); #endif } +TEST_CASE("utilities: the folders of the XDG base directory spec, as Linux finds them") { + using path = std::filesystem::path; + SUBCASE("the variable, when it is set to an absolute path") { + CHECK(xdg_base_directory("/srv/config", "/home/user", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", nullptr, ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", "", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/", "/home/user", ".cache") == path{"/"}); + } + SUBCASE("the folder in the home one, when the variable isn't set, is empty or holds a relative path") { + CHECK(xdg_base_directory(nullptr, "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("config", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("./cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + CHECK(xdg_base_directory("~/cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + } + SUBCASE("none, without the variable and without the home folder") { + CHECK(xdg_base_directory(nullptr, nullptr, ".config").empty()); + CHECK(xdg_base_directory("", "", ".cache").empty()); + CHECK(xdg_base_directory("relative", nullptr, ".cache").empty()); + } + SUBCASE("the settings and the cache: each of its own variable, the same home") { + auto const config{xdg_base_directory("/xdg/config", "/home/user", ".config")}; + auto const cache{xdg_base_directory(nullptr, "/home/user", ".cache")}; + CHECK(config / "MaSzyna" / "eu07.ini" == path{"/xdg/config/MaSzyna/eu07.ini"}); + CHECK(cache / "MaSzyna" / "geoportal" == path{"/home/user/.cache/MaSzyna/geoportal"}); + } +} + +TEST_CASE("utilities: the settings stay in ~/.config/MaSzyna while XDG_CONFIG_HOME has no MaSzyna folder") { + using path = std::filesystem::path; + // in the working folder, as the other tests do: a fixed name in the shared temp folder could be taken over by another user + auto const home{std::filesystem::current_path() / "eu07_unit_xdg_config_home"}; + std::filesystem::remove_all(home); + auto const homename{home.string()}; + // an absolute posix path which doesn't exist, on every system the tests run on + char const *const xdg{"/eu07_test_xdg_config_nowhere"}; + SUBCASE("without the old folder the settings go where XDG says") { + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + } + SUBCASE("the old folder is kept while the new one doesn't exist") { + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(xdg, homename.c_str()) == home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + // the old folder needs the home folder to be found + CHECK(xdg_config_folder(xdg, nullptr) == path{xdg} / "MaSzyna"); + } + SUBCASE("a file of that name isn't the old folder") { + std::filesystem::create_directories(home / ".config"); + std::ofstream{home / ".config" / "MaSzyna"} << "x"; + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + } +#ifndef _WIN32 + SUBCASE("the new folder is taken once it exists") { + auto const config{home / "xdg"}; + std::filesystem::create_directories(config / "MaSzyna"); + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + auto const configname{config.string()}; + CHECK(xdg_config_folder(configname.c_str(), homename.c_str()) == config / "MaSzyna"); + } +#endif + std::filesystem::remove_all(home); +} + // numbers ------------------------------------------------------------------------------------------------------------- TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one") { diff --git a/tests/unit/test_vehicle_command.cpp b/tests/unit/test_vehicle_command.cpp new file mode 100644 index 000000000..84701e416 --- /dev/null +++ b/tests/unit/test_vehicle_command.cpp @@ -0,0 +1,51 @@ +#include "stdafx.h" +#include "doctest.h" + +#include + +#include "physics/vehiclecommand.h" + +// the commands of the vehicles read from their text (events, scripts, the AI) and named for the log: every command +// has the name the scenery files have always used, and reads back as itself + +TEST_CASE("vehicle commands read back from their names") { + using enum VehicleCommand; + for (auto command{static_cast(mainController)}; command <= static_cast(setDamage); ++command) { + auto const value{static_cast(command)}; + auto const name{std::string{VehicleCommandName(value)}}; + CAPTURE(name); + REQUIRE_FALSE(name.empty()); + if (value == load || value == unload) { + continue; // these carry the name of the load after the = + } + CHECK(ParseVehicleCommand(name).command == value); + CHECK(ParseVehicleCommand(name).argument.empty()); + } +} + +TEST_CASE("vehicle commands: the empty text, an unknown one, the load") { + CHECK(ParseVehicleCommand("").command == VehicleCommand::none); + CHECK(ParseVehicleCommand("SetVelocity").command == VehicleCommand::unknown); // the AI's, not a vehicle's + CHECK(ParseVehicleCommand("mainctrl").command == VehicleCommand::unknown); // the names are compared exactly + CHECK(ParseVehicleCommand("MainCtrl").command == VehicleCommand::mainController); + CHECK(ParseVehicleCommand("SpeedCtrlUnit.Parking").command == VehicleCommand::speedControlParking); + + auto const load{ParseVehicleCommand("Load=Coal")}; + CHECK(load.command == VehicleCommand::load); + CHECK(load.argument == "Coal"); + auto const unload{ParseVehicleCommand("UnLoad=passengers")}; + CHECK(unload.command == VehicleCommand::unload); + CHECK(unload.argument == "passengers"); + + // a load without a name is a load of no name, not an exception: the vehicle loads nothing for it + auto const noname{ParseVehicleCommand("Load=")}; + CHECK(noname.command == VehicleCommand::load); + CHECK(noname.argument.empty()); + CHECK(ParseVehicleCommand("UnLoad= ").argument.empty()); + // a space after the = is skipped, as extract_value() does + CHECK(ParseVehicleCommand("Load= Coal").argument == "Coal"); + + CHECK(VehicleCommandName(VehicleCommand::none).empty()); + CHECK(VehicleCommandName(VehicleCommand::unknown).empty()); + CHECK(VehicleCommandName(VehicleCommand::integratedController) == "EIMIC"); +} diff --git a/tests/unit/test_vehicle_ends.cpp b/tests/unit/test_vehicle_ends.cpp new file mode 100644 index 000000000..b385b12ec --- /dev/null +++ b/tests/unit/test_vehicle_ends.cpp @@ -0,0 +1,63 @@ +#include "stdafx.h" +#include "doctest.h" + +#include "physics/vehicletypes.h" + +// the ends and the sides of a vehicle: the numbers the formats give them, the other one, the arrays indexed by them, +// the end of a cab and of a pantograph of the model + +TEST_CASE("vehicle ends and sides keep the numbers of the formats") { + CHECK(NumberOf(VehicleEnd::front) == 0); + CHECK(NumberOf(VehicleEnd::rear) == 1); + CHECK(NumberOf(VehicleSide::right) == 0); + CHECK(NumberOf(VehicleSide::left) == 1); + // a number goes through as it is, also the -1 and the 2 some fields hold for "none" + for (auto const number : {-1, 0, 1, 2}) { + CAPTURE(number); + CHECK(NumberOf(EndOf(number)) == number); + CHECK(NumberOf(SideOf(number)) == number); + } +} + +TEST_CASE("vehicle ends and sides: the other one") { + CHECK(Opposite(VehicleEnd::front) == VehicleEnd::rear); + CHECK(Opposite(VehicleEnd::rear) == VehicleEnd::front); + CHECK(Opposite(VehicleSide::right) == VehicleSide::left); + CHECK(Opposite(VehicleSide::left) == VehicleSide::right); + CHECK(VehicleEnds[0] == VehicleEnd::front); + CHECK(VehicleEnds[1] == VehicleEnd::rear); + CHECK(VehicleSides[0] == VehicleSide::right); + CHECK(VehicleSides[1] == VehicleSide::left); +} + +TEST_CASE("an array of the ends is indexed by the end and by its number alike") { + ByEnd values{10, 20}; + CHECK(values[VehicleEnd::front] == 10); + CHECK(values[VehicleEnd::rear] == 20); + CHECK(values[0] == 10); + CHECK(values[1] == 20); + values[VehicleEnd::rear] = 30; + CHECK(values[1] == 30); + BySide doors{}; + doors[VehicleSide::left] = true; + CHECK_FALSE(doors[VehicleSide::right]); + CHECK(doors[1]); +} + +TEST_CASE("the cab of a vehicle is at its front for cab 1, at its rear for cab -1") { + // the OFF position of the headlights dimmer puts out the headlights at the end of the active cab (A at the front, + // B at the rear); with the numbers of the ends taken for the numbers of the cabs, cab 1 put out B and cab -1 nothing + CHECK(CabEnd(1) == VehicleEnd::front); + CHECK(CabEnd(-1) == VehicleEnd::rear); + CHECK_FALSE(CabEnd(0).has_value()); +} + +TEST_CASE("the pantographs of a model count for the front and the rear in turn") { + // each pantograph has the voltage, the switch and the energy of its own end: the first one the front's, the second + // one the rear's. the energy meter took the voltage of the other one, the count of the pantographs touching the + // wire the switch of the front for both + CHECK(PantographEnd(0) == VehicleEnd::front); + CHECK(PantographEnd(1) == VehicleEnd::rear); + CHECK(PantographEnd(2) == VehicleEnd::front); + CHECK(PantographEnd(3) == VehicleEnd::rear); +} diff --git a/tests/unit/test_wheelslip.cpp b/tests/unit/test_wheelslip.cpp index 9b39e82c6..934f40f05 100644 --- a/tests/unit/test_wheelslip.cpp +++ b/tests/unit/test_wheelslip.cpp @@ -22,7 +22,7 @@ braking_result brake_to_stop_then_stand(vehicle &Coach, track const &Braking, tr Coach.hold_brake_pipe(3.5); // service braking // a skidding wagon brakes on the sliding adhesion only, give it time for (auto step = 0; step < 60000; ++step) { // 600 s in 0.01 s steps - result.skidded |= Coach->SlippingWheels; + result.skidded |= Coach->SlippingWheels(); if (auto const speed{std::abs(Coach.speed())}; speed > 0.0 && speed < 0.1) { // almost stopped; a skidding wagon is still skidding at this point result.stopped = true; @@ -36,7 +36,7 @@ braking_result brake_to_stop_then_stand(vehicle &Coach, track const &Braking, tr } // namespace -// the engine doesn't let a stopped, braked vehicle slip (the Vel > 0.1 trap in TMoverParameters::ComputeTotalForce), +// the engine doesn't let a stopped, braked vehicle slip (the Vel > 0.1 trap in physics::Vehicle::ComputeTotalForce), // so a wagon which stopped in a skid should be no different from one which stopped without it. it used to stay // skidding instead, with its brakes capped by the sliding adhesion, and slid or crept away (eu07/maszyna#479) TEST_CASE("wheelslip: a wagon which stopped in a skid holds like one which stopped without it") { @@ -58,5 +58,5 @@ TEST_CASE("wheelslip: a wagon which stopped in a skid holds like one which stopp CHECK(std::abs(normal.speed()) < 0.1); CHECK(std::abs(skidding.speed()) < 0.1); - CHECK_FALSE(skidding->SlippingWheels); + CHECK_FALSE(skidding->SlippingWheels()); } diff --git a/tests/unit/test_whole_file.cpp b/tests/unit/test_whole_file.cpp new file mode 100644 index 000000000..f1cd98b5c --- /dev/null +++ b/tests/unit/test_whole_file.cpp @@ -0,0 +1,59 @@ +#include "stdafx.h" +#include "doctest.h" +#include "scratch.h" + +#include "utilities/wholefile.h" + +#include +#include + +// the read of a whole file in one go (utilities/wholefile.cpp), which the loader of the binary models (.e3d) parses +// from memory: the bytes come as they are in the file, whatever they are + +using namespace std::string_view_literals; + +namespace { + +std::string_view content(whole_file const &File) { + return {File.data.get(), File.size}; +} + +} // namespace + +TEST_CASE("whole file: the bytes come as they are in the file, the line ends and the text end marks too") { + test::scratch_folder const folder{"whole_file"}; + // all the byte values, then a size which isn't a multiple of any buffer, so the end of the file is read as well + std::string bytes; + for (int i{0}; i < 256; ++i) { + bytes += static_cast(i); + } + bytes += "\r\n\n\r\x1a\x00\xff"sv; + std::string text; + while (text.size() < 70000) { + text += bytes; + } + text += "end"; + auto const path{folder.write("model.e3d", text)}; + + auto const file{read_whole_file(path)}; + REQUIRE(file.size == text.size()); + CHECK(content(file) == text); +} + +TEST_CASE("whole file: a small file is read whole") { + test::scratch_folder const folder{"whole_file_small"}; + auto const path{folder.write("e3d0.e3d", "E3D0")}; + auto const file{read_whole_file(path)}; + CHECK(content(file) == "E3D0"); +} + +TEST_CASE("whole file: an empty file and a file which isn't there give no data") { + test::scratch_folder const folder{"whole_file_none"}; + auto const empty{read_whole_file(folder.write("empty.e3d", ""))}; + CHECK(empty.size == 0); + CHECK(empty.data == nullptr); + + auto const missing{read_whole_file(folder.path("missing.e3d"))}; + CHECK(missing.size == 0); + CHECK(missing.data == nullptr); +} diff --git a/tests/unit/test_win1250.cpp b/tests/unit/test_win1250.cpp index f1d861e94..77fe35a5f 100644 --- a/tests/unit/test_win1250.cpp +++ b/tests/unit/test_win1250.cpp @@ -8,6 +8,8 @@ namespace std::string const kWin1250{"\xA5\xC6\xCA\xA3\xD1\xD3\x8C\x8F\xAF\xB9\xE6\xEA\xB3\xF1\xF3\x9C\x9F\xBF"}; std::string const kUtf8{"\xC4\x84\xC4\x86\xC4\x98\xC5\x81\xC5\x83\xC3\x93\xC5\x9A\xC5\xB9\xC5\xBB" "\xC4\x85\xC4\x87\xC4\x99\xC5\x82\xC5\x84\xC3\xB3\xC5\x9B\xC5\xBA\xC5\xBC"}; +// the name of a station the way a timetable has it: Biala_Podlaska with its l-stroke, in windows-1250 +std::string const kBiala{"Bia\xB3" "a_Podlaska"}; } // namespace TEST_CASE("win1250: the polish letters of a scenery file read as utf-8") { @@ -32,3 +34,82 @@ TEST_CASE("win1250: utf-8 written back the way a scenery file has it") { // the letters other than the polish ones turn into question marks CHECK(utf8_to_win1250("\xC3\xA9t\xC3\xA9") == "?t?"); } + +TEST_CASE("win1250: a text of a data file is turned into utf-8 for the user interface") { + // plain ascii stays + CHECK(data_text_to_utf8("tor 1, km 0.178") == "tor 1, km 0.178"); + CHECK(data_text_to_utf8("").empty()); + // windows-1250: the polish letters + CHECK(data_text_to_utf8(kWin1250) == kUtf8); + CHECK(data_text_to_utf8(kBiala) == "Bia\xC5\x82" "a_Podlaska"); + // and the letters of the other languages of the code page: a-acute, z-caron, i-acute, u-diaeresis, o-double-acute + CHECK(data_text_to_utf8("n\xE1" "dra\x9E\xED") == "n\xC3\xA1" "dra\xC5\xBE\xC3\xAD"); + CHECK(data_text_to_utf8("\xFC\xF5") == "\xC3\xBC\xC5\x91"); + // a character outside of the two-byte range (the euro sign), and a byte the code page has nothing for + CHECK(data_text_to_utf8("5 \x80") == "5 \xE2\x82\xAC"); + CHECK(data_text_to_utf8("a\x81" "b") == "a?b"); + // a text already in utf-8 stays as it is + CHECK(data_text_to_utf8(kUtf8) == kUtf8); + CHECK(data_text_to_utf8("Bia\xC5\x82" "a Podlaska") == "Bia\xC5\x82" "a Podlaska"); + CHECK(data_text_to_utf8("\xE2\x94\x82 60 \xE2\x94\x82") == "\xE2\x94\x82 60 \xE2\x94\x82"); + // capital letters with marks in a row make valid utf-8 by chance (O-acute and L-stroke: D3 A3), but of a + // cyrillic letter; they are read as the windows-1250 they are + CHECK(data_text_to_utf8("W\xD3\xA3KA") == "W\xC3\x93\xC5\x81KA"); + CHECK(data_text_to_utf8("R\xD3\xAF" "A") == "R\xC3\x93\xC5\xBB" "A"); + // line ends and tabs of a longer text stay + CHECK(data_text_to_utf8("jedna\n\tdruga \xB3") == "jedna\n\tdruga \xC5\x82"); + // what comes out is valid utf-8 + std::u32string decoded; + std::string all; + for (auto value{0x20}; value < 0x100; ++value) { + all += static_cast(value); + } + REQUIRE(utf8_to_utf32(data_text_to_utf8(all), decoded)); + CHECK(decoded.size() == all.size()); +} + +TEST_CASE("win1250: a name of a data file is shown in one line, with its letters") { + // what Bezogonkow() did for the user interface, but for the marks: control characters and, when asked, + // underscores turn into spaces + CHECK(data_name_to_utf8("a\tb\nc") == "a b c"); + CHECK(data_name_to_utf8(kBiala) == "Bia\xC5\x82" "a_Podlaska"); + CHECK(data_name_to_utf8(kBiala, true) == "Bia\xC5\x82" "a Podlaska"); + CHECK(data_name_to_utf8("Warszawa_Zachodnia", true) == "Warszawa Zachodnia"); + CHECK(data_name_to_utf8("Warszawa_Zachodnia") == "Warszawa_Zachodnia"); + CHECK(data_name_to_utf8("Bia\xC5\x82" "a_Podlaska\r", true) == "Bia\xC5\x82" "a Podlaska "); + // for a name without letters outside of ascii it gives what Bezogonkow() gave + for (auto const *name : {"Warszawa_Zachodnia", "Gorna", "tor 1\t2", "", "Os1234"}) { + CAPTURE(name); + CHECK(data_name_to_utf8(name) == Bezogonkow(name)); + CHECK(data_name_to_utf8(name, true) == Bezogonkow(name, true)); + } +} + +TEST_CASE("win1250: a column of the timetable panel is as wide in letters as it was in bytes") { + CHECK(utf8_length("") == 0); + CHECK(utf8_length("Gorna") == 5); + CHECK(utf8_length("Bia\xC5\x82" "a Podlaska") == 14); + CHECK(utf8_length(kUtf8) == 18); + CHECK(utf8_length("\xE2\x94\x82 60 \xE2\x94\x82") == 6); + // a byte which is no part of a valid sequence counts as a character + CHECK(utf8_length("a\xB3" "b") == 3); + CHECK(utf8_length("a\xC5") == 2); + + // filled with spaces + CHECK(utf8_fit("Gorna", 8) == "Gorna "); + CHECK(utf8_fit("", 3) == " "); + auto const caption{data_name_to_utf8(kBiala, true)}; + auto const fitted{utf8_fit(caption, 34)}; + CHECK(utf8_length(fitted) == 34); + CHECK(fitted.size() == 35); // one letter of two bytes + CHECK(fitted.starts_with(caption)); + // cut between the letters, never inside of one + CHECK(utf8_fit("Bia\xC5\x82" "a Podlaska", 4) == "Bia\xC5\x82"); + CHECK(utf8_fit("Bia\xC5\x82" "a Podlaska", 3) == "Bia"); + CHECK(utf8_fit(kUtf8, 2) == "\xC4\x84\xC4\x86"); + CHECK(utf8_fit("Gorna", 0).empty()); + // a name of ascii fits the way the panel cut it before + std::string const longname{"Bardzo_Dluga_Nazwa_Stacji_Wezlowej_Osobowej"}; + CHECK(utf8_fit(longname, 34) == (longname + " ").substr(0, 34)); + CHECK(utf8_fit("Gorna", 34) == (std::string{"Gorna"} + " ").substr(0, 34)); +} diff --git a/tests/unit/test_wipers.cpp b/tests/unit/test_wipers.cpp new file mode 100644 index 000000000..cc6c7042e --- /dev/null +++ b/tests/unit/test_wipers.cpp @@ -0,0 +1,50 @@ +#include "stdafx.h" +#include "doctest.h" +#include "vehicle.h" + +using test::definition; +using test::vehicle; + +// the first number of a WiperList row is the mask of the wipers working in that position of the wiper switch, +// bit n for the wiper n. it's a number: read as a character "5" was 53 and "12" was '1', the wiper 0 alone + +namespace { + +definition wiper_list(nlohmann::ordered_json const &Rows) { + return definition::load("cab_vehicle") + .set("WiperList", "rows", Rows) + .set("WiperList", "Size", static_cast(Rows.size())) + .set("WiperList", "Angle", 58); +} + +} // namespace + +TEST_CASE("wipers: the mask of the wipers of a WiperList row is read as a number") { + vehicle cab{wiper_list(nlohmann::ordered_json::array({ + {"0", "0.7", "0.0", "0.5"}, + {"5", "0.7", "7.0", "0.5"}, + {"12", "0.6", "0.7", "0.0"}, + {"15", "0.5", "0.5", "0.25"}, + }))}; + REQUIRE(cab->WiperListSize == 4); + + CHECK(cab->WiperList[0].byteSum == 0); + CHECK(cab->WiperList[1].byteSum == 5); + CHECK(cab->WiperList[2].byteSum == 12); + CHECK(cab->WiperList[3].byteSum == 15); + + // and the numbers after it still land in their own fields + CHECK(cab->WiperList[1].interval == doctest::Approx(7.0)); + CHECK(cab->WiperList[2].WiperSpeed == doctest::Approx(0.6)); + CHECK(cab->WiperList[3].outBackDelay == doctest::Approx(0.25)); +} + +TEST_CASE("wipers: a mask out of the range of a byte is clamped to it") { + vehicle cab{wiper_list(nlohmann::ordered_json::array({ + {"-1", "0.7", "0.0", "0.5"}, + {"300", "0.7", "0.0", "0.5"}, + }))}; + + CHECK(cab->WiperList[0].byteSum == 0); + CHECK(cab->WiperList[1].byteSum == 255); +} diff --git a/tests/unit/vehicle.cpp b/tests/unit/vehicle.cpp index e38999f7d..c90eb8d81 100644 --- a/tests/unit/vehicle.cpp +++ b/tests/unit/vehicle.cpp @@ -125,32 +125,32 @@ std::string definition::text() const { vehicle::vehicle(definition const &Definition, double Velocity, std::string const &Name, int Cab) : m_cab(Cab) { // the same steps as TDynamicObject::Init(), for a vehicle set the usual way round (iDirection 1) auto const typename_{Definition.type_name().empty() ? Name : Definition.type_name()}; - m_mover = std::make_unique(Velocity, typename_, Name, Cab); - if (false == m_mover->LoadFIZ_Text(Definition.text())) { + m_physics = std::make_unique(Velocity, typename_, Name, Cab); + if (false == m_physics->LoadFIZ_Text(Definition.text())) { throw definition_error("the test vehicle definition didn't load"); } - m_mover->AssignLoad("", 0.f); - m_mover->ComputeMass(); + m_physics->AssignLoad("", 0.f); + m_physics->ComputeMass(); auto const driveractive{Velocity != 0.0}; - if (false == m_mover->CheckLocomotiveParameters(driveractive, (Velocity > 0 ? 1 : -1) * Cab)) { + if (false == m_physics->CheckLocomotiveParameters(driveractive, (Velocity > 0 ? 1 : -1) * Cab)) { throw definition_error("parameters mismatch in the test vehicle definition"); } - m_mover->MainCtrlPos = m_mover->MainCtrlNoPowerPos(); - m_mover->LocalBrakePosA = 0.0; + m_physics->SetMainCtrlPos(m_physics->MainCtrlNoPowerPos()); + m_physics->brakes.SetIndependentPosition(0.0); if (driveractive) { - m_mover->BrakeCtrlPos = static_cast(std::floor(m_mover->Handle->GetPos(Cab == 0 ? bh_NP : bh_RP))); + m_physics->brakes.SetHandlePosition(static_cast(std::floor(m_physics->brakes.driverValve->GetPos(Cab == 0 ? bh_NP : bh_RP)))); // a driver keeps a vehicle on standby on its independent brake - if (Cab != 0 && m_mover->LocalBrake != TLocalBrake::ManualBrake && Velocity < 1.0) { - m_mover->IncLocalBrakeLevel(LocalBrakePosNo); - if (m_mover->EIMCtrlEmergency) { - m_mover->DecLocalBrakeLevel(1); + if (Cab != 0 && m_physics->brakes.config.localKind != TLocalBrake::ManualBrake && Velocity < 1.0) { + m_physics->IncLocalBrakeLevel(LocalBrakePosNo); + if (m_physics->EIMCtrlEmergency()) { + m_physics->DecLocalBrakeLevel(1); } } } else { - m_mover->BrakeCtrlPos = static_cast(std::floor(m_mover->Handle->GetPos(bh_NP))); + m_physics->brakes.SetHandlePosition(static_cast(std::floor(m_physics->brakes.driverValve->GetPos(bh_NP)))); } - m_mover->BrakeLevelSet(m_mover->BrakeCtrlPos); + m_physics->BrakeLevelSet(m_physics->brakes.HandlePosition()); } void vehicle::step(track const &Track, double Dt) { @@ -161,7 +161,7 @@ void vehicle::step(track const &Track, double Dt) { fast_move(Track, Dt, location); } forces(Dt); - move(Track, Dt, location, m_mover->PipePress); + move(Track, Dt, location, m_physics->brakePipe.Pressure()); } namespace { @@ -170,19 +170,23 @@ TTrackShape shape_of(track const &Track) { TTrackShape shape; shape.Len = 1000.0; shape.dHtrack = Track.gradient; + shape.R = Track.radius; + shape.dHrail = Track.cant; return shape; } -TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { +TTrackParam parameters_of(track const &Track, physics::Vehicle const &Physics) { TTrackParam param; param.Width = Track.width; param.friction = Track.friction; + param.Name = &Track.name; + param.Velmax = Track.velocity; // the vehicle's own kind of way: a road vehicle on rails derails as soon as it moves if (Track.category != 0) { param.CategoryFlag = Track.category; } else { - param.CategoryFlag = Mover.CategoryFlag != 0 ? Mover.CategoryFlag : 1; + param.CategoryFlag = Physics.CategoryFlag != 0 ? Physics.CategoryFlag : 1; } return param; } @@ -191,69 +195,71 @@ TTrackParam parameters_of(track const &Track, TMoverParameters const &Mover) { double vehicle::fast_move(track const &Track, double Dt, TLocation const &Location) { // TDynamicObject::FastUpdate(), the iterations of a frame before the last one - auto param{parameters_of(Track, *m_mover)}; - return m_mover->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); + auto param{parameters_of(Track, *m_physics)}; + param.DamageFlag = m_trackdamage; + return m_physics->FastComputeMovement(Dt, shape_of(Track), param, Location, TRotation{0.0, 0.0, 0.0}); } void vehicle::begin_step() { // the conditions the test keeps if (m_pipepressure >= 0.0) { - m_mover->Pipe->CreatePress(m_pipepressure); + m_physics->brakePipe.reservoir->CreatePress(m_pipepressure); } - if (m_reservoirpressure >= 0.0 && m_mover->VeselVolume > 0.0) { - m_mover->CompressedVolume = m_reservoirpressure * m_mover->VeselVolume; + if (m_reservoirpressure >= 0.0 && m_physics->air.config.mainReservoirVolume > 0.0) { + m_physics->air.Fill(m_reservoirpressure * m_physics->air.config.mainReservoirVolume); } // vehicle_table::update(), before the forces - m_mover->ComputeConstans(); + m_physics->ComputeConstans(); } void vehicle::forces(double Dt) { // TDynamicObject::UpdateForce() - m_mover->ComputeTotalForce(Dt); + m_physics->ComputeTotalForce(Dt); } double vehicle::move(track const &Track, double Dt, TLocation const &Location, double Trainpipe) { auto const shape{shape_of(Track)}; - auto const param{parameters_of(Track, *m_mover)}; + auto param{parameters_of(Track, *m_physics)}; + param.DamageFlag = m_trackdamage; TRotation const rotation{0.0, 0.0, 0.0}; // what TDynamicObject::Update() does before the movement. a raised pantograph touches the wire at once, // the game animates its rise - auto &mover{*m_mover}; - mover.PantFrontVolt = mover.Pantographs[end::front].is_active ? Track.voltage : 0.0; - mover.PantRearVolt = mover.Pantographs[end::rear].is_active ? Track.voltage : 0.0; + auto &physics{*m_physics}; + physics.pantographCircuit.SetFrontVoltage(physics.pantographs[VehicleEnd::front].is_active ? Track.voltage : 0.0); + physics.pantographCircuit.SetRearVoltage(physics.pantographs[VehicleEnd::rear].is_active ? Track.voltage : 0.0); TTractionParam traction; traction.TractionVoltage = - mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(mover.PantRearVolt), std::abs(mover.PantFrontVolt)) : 0.95 * mover.EnginePowerSource.MaxVoltage; + physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? std::max(std::abs(physics.pantographCircuit.RearVoltage()), std::abs(physics.pantographCircuit.FrontVoltage())) : 0.95 * physics.EnginePowerSource.MaxVoltage; traction.TractionFreq = 0; traction.TractionMaxCurrent = 7500; traction.TractionResistivity = 0.3; - mover.PantographVoltage = traction.TractionVoltage; + physics.pantographCircuit.SetSupplyVoltage(traction.TractionVoltage); if (m_cab != 0) { using enum TEngineType; // the driver's own vehicle, which gets the average pressure of the train's brake pipe - mover.EqvtPipePress = Trainpipe; - if (auto const diesel{mover.EngineType == DieselEngine || mover.EngineType == DieselElectric}; diesel && mover.EIMCtrlType > 0) { - mover.CheckEIMIC(Dt); - if (mover.SpeedCtrl) { - mover.CheckSpeedCtrl(Dt); + physics.brakes.equivalentPipePressure = Trainpipe; + if (auto const diesel{physics.EngineType == DieselEngine || physics.EngineType == DieselElectric}; diesel && physics.EIMCtrlType > 0) { + physics.CheckEIMIC(Dt); + if (physics.SpeedCtrl()) { + physics.CheckSpeedCtrl(Dt); } - mover.eimic_real = std::min(mover.eimic, mover.eimicSpeedCtrl); + physics.SetEimicReal(std::min(physics.eimic, physics.eimicSpeedCtrl())); } - if (mover.EngineType == ElectricInductionMotor) { + if (physics.EngineType == ElectricInductionMotor) { // the share of the electric and pneumatic brake over the train (TDynamicObject's MED) isn't here - mover.CheckEIMIC(Dt); - mover.CheckSpeedCtrl(Dt); - mover.eimic_real = std::min(mover.eimic, mover.eimicSpeedCtrl); + physics.CheckEIMIC(Dt); + physics.CheckSpeedCtrl(Dt); + physics.SetEimicReal(std::min(physics.eimic, physics.eimicSpeedCtrl())); } } // the whole frame's time, of all its iterations auto const frame{Dt * Track.iterations}; - auto const distance{m_mover->ComputeMovement(Dt, frame, shape, param, traction, Location, rotation)}; + auto const distance{m_physics->ComputeMovement(Dt, frame, shape, param, traction, Location, rotation)}; m_time += frame; if (m_trace != nullptr) { - m_trace->sample(m_time, *m_mover); + m_trace->sample(m_time, *m_physics); } return distance; } @@ -266,7 +272,7 @@ void vehicle::run(double Seconds, track const &Track, double Dt) { } } -// the physics reaches the vehicle next to it through TDynamicObject::MoverParameters only (neighbour_data). the +// the physics reaches the vehicle next to it through TDynamicObject::physics only (neighbour_data). the // tests can't make a TDynamicObject, whose constructor and members come with the rest of the engine, so the // neighbour is a zeroed block of its size with just that pointer set: enough for the physics, which reads nothing // else of it, and never used as a whole object @@ -274,9 +280,9 @@ static_assert(alignof(TDynamicObject) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__); namespace { -std::vector make_standin(TMoverParameters &Mover) { +std::vector make_standin(physics::Vehicle &Physics) { std::vector standin(sizeof(TDynamicObject)); // zeroed - reinterpret_cast(standin.data())->MoverParameters = &Mover; // NOSONAR see above + reinterpret_cast(standin.data())->physics = &Physics; // NOSONAR see above return standin; } @@ -286,18 +292,18 @@ TDynamicObject *as_neighbour(std::byte *Standin) { } // namespace -pair::pair(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, double Gap) { - auto const &first{First.mover()}; - auto const &second{Second.mover()}; +pair::pair(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, double Gap) { + auto const &first{First.physics()}; + auto const &second{Second.physics()}; // the first vehicle in the middle, its FirstEnd towards the second one - m_vehicles[0] = {&First, FirstEnd, 0.0, FirstEnd == end::front ? 1.0 : -1.0, make_standin(First.mover())}; - m_vehicles[1] = {&Second, SecondEnd, 0.5 * first.Dim.L + Gap + 0.5 * second.Dim.L, SecondEnd == end::front ? -1.0 : 1.0, make_standin(Second.mover())}; + m_vehicles[0] = {&First, FirstEnd, 0.0, FirstEnd == VehicleEnd::front ? 1.0 : -1.0, make_standin(First.physics())}; + m_vehicles[1] = {&Second, SecondEnd, 0.5 * first.Dim.L + Gap + 0.5 * second.Dim.L, SecondEnd == VehicleEnd::front ? -1.0 : 1.0, make_standin(Second.physics())}; } pair::~pair() { for (auto const &placed : m_vehicles) { // the vehicles outlive the pair, they mustn't point at its stand-ins - for (auto &neighbour : placed.owner->mover().Neighbours) { + for (auto &neighbour : placed.owner->physics().Neighbours) { neighbour = neighbour_data(); } } @@ -306,19 +312,22 @@ pair::~pair() { void pair::find_neighbours() { // as TDynamicObject::update_neighbours() for (auto const &placed : m_vehicles) { - placed.owner->mover().Loc = TLocation{placed.position, 0.0, 0.0}; + placed.owner->physics().SetLoc(TLocation{placed.position, 0.0, 0.0}); } for (int i = 0; i < 2; ++i) { auto const &self{m_vehicles[i]}; auto &other{m_vehicles[1 - i]}; // its stand-in is what this one points at - auto &mover{self.owner->mover()}; - auto const &othermover{other.owner->mover()}; - auto &neighbour{mover.Neighbours[self.end]}; + auto &physics{self.owner->physics()}; + auto const &otherPhysics{other.owner->physics()}; + auto &neighbour{physics.Neighbours[self.end]}; neighbour.vehicle = as_neighbour(other.standin.data()); - neighbour.vehicle_end = other.end; - neighbour.distance = static_cast(TMoverParameters::CouplerDist(&mover, &othermover) - mover.Couplers[self.end].adapter_length - - othermover.Couplers[other.end].adapter_length); - mover.Neighbours[1 - self.end] = neighbour_data(); + neighbour.vehicle_end = NumberOf(other.end); + neighbour.distance = static_cast(physics::Vehicle::CouplerDist(&physics, &otherPhysics) - physics.Couplers[self.end].adapter_length - + otherPhysics.Couplers[other.end].adapter_length); + physics.Neighbours[Opposite(self.end)] = neighbour_data(); + } + if (neighbours_found) { + neighbours_found(); } } @@ -329,9 +338,11 @@ void pair::step(track const &Track, double Dt) { placed.owner->forces(Dt); } for (auto &placed : m_vehicles) { - auto const &mover{placed.owner->mover()}; - placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, mover.PipePress); + auto const &physics{placed.owner->physics()}; + placed.position += placed.heading * placed.owner->move(Track, Dt, TLocation{placed.position, 0.0, 0.0}, physics.brakePipe.Pressure()); } + // vehicle_table::update_brake_pipes() + physics::Vehicle::UpdatePipeCouplers({&m_vehicles[0].owner->physics(), &m_vehicles[1].owner->physics()}, Dt); } void pair::run(double Seconds, track const &Track, double Dt) { @@ -343,13 +354,13 @@ void pair::run(double Seconds, track const &Track, double Dt) { } double pair::gap() const { - auto const &first{m_vehicles[0].owner->mover()}; - auto const &second{m_vehicles[1].owner->mover()}; + auto const &first{m_vehicles[0].owner->physics()}; + auto const &second{m_vehicles[1].owner->physics()}; return std::abs(m_vehicles[1].position - m_vehicles[0].position) - 0.5 * (first.Dim.L + second.Dim.L); } -int pair::coupling() const { - return m_vehicles[0].owner->mover().Couplers[m_vehicles[0].end].CouplingFlag; +CouplingSet pair::coupling() const { + return m_vehicles[0].owner->physics().Couplers[m_vehicles[0].end].CouplingFlag; } void reseed_random() { diff --git a/tests/unit/vehicle.h b/tests/unit/vehicle.h index e14f4e464..36b076cb3 100644 --- a/tests/unit/vehicle.h +++ b/tests/unit/vehicle.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -9,7 +10,7 @@ #include -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" namespace test { @@ -39,6 +40,10 @@ public: // sets the key of the section, adding either one when it's missing definition &set(std::string const &Section, std::string const &Key, nlohmann::ordered_json const &Value); + // a set of couplings, as the number the definition writes + definition &set(std::string const &Section, std::string const &Key, CouplingSet const Value) { + return set(Section, Key, Value.Bits()); + } // drops the whole section, with its rows, or one key of it definition &remove(std::string const &Section); definition &remove(std::string const &Section, std::string const &Key); @@ -66,6 +71,10 @@ struct track { int category{0}; int iterations{1}; double width{1.435}; + double radius{0.0}; // of a curve [m], 0 straight + double cant{0.0}; // [rad] + double velocity{-1.0}; // the speed limit [km/h], negative without one + std::string name; // for the log }; // the catenary of the Polish railways [V] @@ -80,8 +89,8 @@ class vehicle { public: explicit vehicle(definition const &Definition, double Velocity = 0.0, std::string const &Name = "test", int Cab = 0); - TMoverParameters &mover() { return *m_mover; } - TMoverParameters *operator->() { return m_mover.get(); } + physics::Vehicle &physics() { return *m_physics; } + physics::Vehicle *operator->() { return m_physics.get(); } // keeps the brake pipe at the given pressure [bar], as a locomotive coupled to the vehicle would; // a negative value leaves the pipe alone @@ -89,6 +98,9 @@ public: // keeps the main reservoir at the given pressure [bar], as a running compressor or a coupled vehicle // feeding it would; a negative value leaves it alone void hold_main_reservoir(double Pressure) { m_reservoirpressure = Pressure; } + // the track under this vehicle alone has the damage flags (dtrack_*) from now on: dtrack_norail runs it off the + // end of the track in its next step, as the legacy derailment has it + void damage_track(int Flags) { m_trackdamage = Flags; } // advances the physics by one frame of Track.iterations steps of Dt, the way the simulation loop does void step(track const &Track = {}, double Dt = 0.01); @@ -106,13 +118,14 @@ public: double move(track const &Track, double Dt, TLocation const &Location, double Trainpipe); // vehicle speed in kilometres per hour, negative when moving backwards - double speed() const { return m_mover->V * 3.6; } + double speed() const { return m_physics->V() * 3.6; } private: - std::unique_ptr m_mover; + std::unique_ptr m_physics; int m_cab{0}; double m_pipepressure{-1.0}; double m_reservoirpressure{-1.0}; + int m_trackdamage{0}; trace *m_trace{nullptr}; double m_time{0.0}; // of the simulation, since the vehicle got created }; @@ -122,12 +135,12 @@ private: // vehicles of a scene (vehicle_table::update()): each one finds its neighbour, then both take the forces, the // coupler and buffer ones among them (CouplerForce()), then both move and handle the collisions (CollisionDetect()). // they couple and part on their own, as the couplers let them; the speed of each runs along its own axis -// test::pair pair{moving, end::front, standing, end::rear, 1.0}; // 1 m apart +// test::pair pair{moving, VehicleEnd::front, standing, VehicleEnd::rear, 1.0}; // 1 m apart // pair.run(5.0); // for 5 s // CHECK(pair.coupled()); class pair { public: - pair(vehicle &First, int FirstEnd, vehicle &Second, int SecondEnd, double Gap); + pair(vehicle &First, VehicleEnd FirstEnd, vehicle &Second, VehicleEnd SecondEnd, double Gap); ~pair(); pair(pair const &) = delete; pair &operator=(pair const &) = delete; @@ -141,14 +154,18 @@ public: void run(double Seconds, track const &Track = {}, double Dt = 0.01); // distance between the facing couplers [m], negative while the buffers are pressed in double gap() const; - // type of the coupling between the vehicles, coupling::faux when they aren't coupled - int coupling() const; - bool coupled() const { return coupling() != coupling::faux; } + // type of the coupling between the vehicles, Coupling::none when they aren't coupled + CouplingSet coupling() const; + bool coupled() const { return false == coupling().Empty(); } + + // called after each finding of the neighbours, which it may change: stands in for the ends of vehicles off the track + // meeting where they are (TDynamicObject::update_neighbours() with physics.derailment new), not along the track + std::function neighbours_found; private: struct placement { vehicle *owner{nullptr}; - int end{0}; // the end facing the other vehicle + VehicleEnd end{VehicleEnd::front}; // the end facing the other vehicle double position{0.0}; // of the middle of the vehicle along the track [m] double heading{1.0}; // +1 when the vehicle runs forwards towards the growing position, -1 otherwise std::vector standin; // what the other vehicle sees as this one, see vehicle.cpp diff --git a/tools/fetch_dlss_sdk.cmake b/tools/fetch_dlss_sdk.cmake index c0fca521a..b0fcdee1a 100644 --- a/tools/fetch_dlss_sdk.cmake +++ b/tools/fetch_dlss_sdk.cmake @@ -16,6 +16,8 @@ endif() get_filename_component(DLSS_SDK_ROOT "${DLSS_SDK_ROOT}" ABSOLUTE) if(NOT DLSS_SDK_TAG) set(DLSS_SDK_TAG "v310.9.16") + # the commit the tag is expected at: a tag can be moved, a commit can't. another tag given by hand is taken as it is + set(DLSS_SDK_COMMIT "9981c6350dc58c0ce21f024fd65e31e851c31689") endif() if(NOT DLSS_SDK_PLATFORMS) if(CMAKE_HOST_WIN32) @@ -83,4 +85,10 @@ else() run_git(-C "${DLSS_SDK_ROOT}" sparse-checkout set --no-cone ${patterns}) run_git(-C "${DLSS_SDK_ROOT}" checkout) endif() +if(DLSS_SDK_COMMIT) + execute_process(COMMAND "${GIT_EXECUTABLE}" -C "${DLSS_SDK_ROOT}" rev-parse HEAD OUTPUT_VARIABLE checkedout OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE result) + if(NOT result EQUAL 0 OR NOT checkedout STREQUAL DLSS_SDK_COMMIT) + message(FATAL_ERROR "the DLSS SDK tag ${DLSS_SDK_TAG} is at the commit ${checkedout}, not at ${DLSS_SDK_COMMIT} as expected: check the release before building with it") + endif() +endif() message(STATUS "the DLSS SDK is in ${DLSS_SDK_ROOT}; configure with -DWITH_DLSS=ON") diff --git a/tools/rename/mover_to_physics.py b/tools/rename/mover_to_physics.py new file mode 100644 index 000000000..bc1b8885f --- /dev/null +++ b/tools/rename/mover_to_physics.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Renames the physics of a vehicle from TMoverParameters, "the mover", to physics::Vehicle. + +Run it from the root of the repository, on any branch, before merging a branch made before the rename into one +made after it (or the other way round): it turns the old names of the branch into the new ones, so the merge +doesn't conflict over them. Running it again changes nothing. + + python tools/rename/mover_to_physics.py # rename + python tools/rename/mover_to_physics.py --check # only list what it would change, exit 1 if anything + +What it renames, in the code and in the comments (never inside string literals, whose text the game shows, logs or +looks up): + + physics/mover.h physics/vehicle.h + TMoverParameters physics::Vehicle (the class is in namespace physics) + TDynamicObject::MoverParameters physics + mvOccupied, mvControlled occupied, controlled + mvSecond, mvThird secondUnit, thirdUnit + mvPantographUnit pantographUnit + mover, Mover, movers physics, Physics, vehicles (the locals and the parameters) + m_mover, othermover, ... m_physics, otherPhysics, ... + +The "movers" of the editor, the tracks a slide moves, keep their name (EDITOR_MOVERS below). + +One case is left to the hand: a member function of TDynamicObject whose local `mover` is its own `MoverParameters` +(`auto &mover { *MoverParameters };`) becomes `auto &physics { *physics };`, which the compiler stops at ("cannot be +used before it is initialized"). Drop the line and write `physics->` for `physics.` in the rest of the function. +""" + +import re +import subprocess +import sys +from pathlib import Path + +OLD_HEADER = "physics/mover.h" +NEW_HEADER = "physics/vehicle.h" +EXTENSIONS = (".cpp", ".h", ".hpp", ".inl", ".md", ".txt", ".cmake") +SKIP_PREFIXES = ("ref/", "build/", "tools/rename/") +# where a mover is a track moved by a slide of the editor, not the physics of a vehicle +EDITOR_MOVERS = {"application/editormode.h", "application/editormodeswitchslide.cpp"} + +# in the order they apply: the longer and the special forms first +RENAMES = [ + (r"\bmover\.h\b", "vehicle.h"), + (r"\bTMoverParameters::TMoverParameters\b", "physics::Vehicle::Vehicle"), + (r"\bTMoverParameters::~TMoverParameters\b", "physics::Vehicle::~Vehicle"), + (r"\bclass TMoverParameters;", "namespace physics { class Vehicle; }"), + (r"\bT_MoverParameters\b", "physics::Vehicle"), + (r"\bTMoverParameters\b", "physics::Vehicle"), + (r"\bMoverParameters\b", "physics"), + (r"\bmvOccupied\b", "occupied"), + (r"\bmvControlled\b", "controlled"), + (r"\bmvSecond\b", "secondUnit"), + (r"\bmvThird\b", "thirdUnit"), + (r"\bmvPantographUnit\b", "pantographUnit"), + (r"\bm_mover\b", "m_physics"), + (r"\bothermover\b", "otherPhysics"), + (r"\bcurrentMover\b", "currentPhysics"), + (r"\bfrom_movers\b", "from_vehicles"), + (r"\brenderMoverEventSounds\b", "renderPhysicsEventSounds"), + (r"\bmoverparam\b", "the physics"), + (r"\b_mover__(\d)\b", r"_vehicle__\1"), +] +LOCAL_RENAMES = [ + (r"\bmover's\b", "physics'"), + (r"\bmovers\b", "vehicles"), + (r"\bmover\b", "physics"), + (r"\bMover\b", "Physics"), +] + +# a comment, or a string or a character literal (raw strings included): the comments come first, so an apostrophe in +# one doesn't start a character literal +TOKEN = re.compile(r'//[^\n]*|/\*.*?\*/|R"([^()\\\s]{0,16})\(.*?\)\1"|"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'', re.S) + + +def tracked_files(): + names = subprocess.run(["git", "ls-files"], capture_output=True, text=True, check=True).stdout.split("\n") + for name in names: + if not name or name.startswith(SKIP_PREFIXES): + continue + if name.endswith(EXTENSIONS) or Path(name).name == "CMakeLists.txt": + yield name + + +def rename_outside_literals(text, renames): + """applies the renames to the code and the comments, not to the string and character literals""" + out = [] + last = 0 + for token in TOKEN.finditer(text): + out.append(apply(text[last:token.start()], renames)) + is_comment = token.group(0).startswith(("//", "/*")) + out.append(apply(token.group(0), renames) if is_comment else token.group(0)) + last = token.end() + out.append(apply(text[last:], renames)) + return "".join(out) + + +def apply(chunk, renames): + for pattern, replacement in renames: + chunk = re.sub(pattern, replacement, chunk) + return chunk + + +def rename_file(name, text): + is_code = name.endswith((".cpp", ".h", ".hpp", ".inl")) + # the header where it is included or listed + text = text.replace('"' + OLD_HEADER + '"', '"' + NEW_HEADER + '"') + text = text.replace(OLD_HEADER, NEW_HEADER) + renames = RENAMES + ([] if name in EDITOR_MOVERS else LOCAL_RENAMES) + if is_code: + text = rename_outside_literals(text, renames) + else: + text = apply(text, renames) + if name == NEW_HEADER: + text = wrap_in_namespace(text) + return text + + +def wrap_in_namespace(text): + """puts the class of the physics of a vehicle into namespace physics, once""" + if "\nnamespace physics\n{\n\nclass Vehicle\n" in text.replace("\r\n", "\n"): + return text + nl = "\r\n" if "\r\n" in text else "\n" + head = "class physics::Vehicle" + nl + "{" + start = text.find(head) + if start < 0: + return text + # the end of the class: the brace that closes the one after its name, the braces of the comments and the literals + # not counted + depth = 0 + end = None + i = start + len(head) - 1 + while i < len(text): + token = TOKEN.match(text, i) + if token is not None: + i = token.end() + continue + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if depth == 0: + end = text.index(";", i) + 1 + break + i += 1 + if end is None: + raise SystemExit("the end of class physics::Vehicle not found in " + NEW_HEADER) + body = text[start + len(head):end] + # inside the class it is just Vehicle: the constructor and the destructor + body = re.sub(r"(\n\s*)physics::Vehicle\(", r"\1Vehicle(", body) + body = re.sub(r"(\n\s*)~physics::Vehicle\(", r"\1~Vehicle(", body) + wrapped = "namespace physics" + nl + "{" + nl + nl + "class Vehicle" + nl + "{" + body + nl + nl + "} // namespace physics" + text = text[:start] + wrapped + text[end:] + # the types before the class point at it + forward = "namespace physics" + nl + "{" + nl + "class Vehicle;" + nl + "}" + nl + anchor = "class cParser;" + nl + if forward not in text and anchor in text: + text = text.replace(anchor, anchor + forward, 1) + return text + + +def main(): + check = "--check" in sys.argv + changed = [] + if Path(OLD_HEADER).exists(): + changed.append(OLD_HEADER + " -> " + NEW_HEADER) + if not check: + subprocess.run(["git", "mv", OLD_HEADER, NEW_HEADER], check=True) + for name in tracked_files(): + path = Path(name) + if not path.exists(): + continue + raw = path.read_bytes() + try: + text = raw.decode("utf-8") + except UnicodeDecodeError: + continue + renamed = rename_file(name, text) + if renamed != text: + changed.append(name) + if not check: + path.write_bytes(renamed.encode("utf-8")) + for name in changed: + print(name) + print(f"{len(changed)} file(s) {'to change' if check else 'changed'}") + return 1 if check and changed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/track_uneven_grade.py b/tools/track_uneven_grade.py index ba60be900..889e0ad0f 100644 --- a/tools/track_uneven_grade.py +++ b/tools/track_uneven_grade.py @@ -7,7 +7,7 @@ curves, speed and road crossings. The originals stay as they are, graded copies python track_uneven_grade.py scenery/baltyk_skm1.scn --out graded --route -107,2300 -4120,2491 --straight tor0290,tor0906 python track_uneven_grade.py scenery/mytracks.scm --root scenery --out graded --gain 1.2 -With no --out it only reports. See track_uneven_doc.md for the attribute. Python 3.8 or later, no other packages. +With no --out it only reports. See docs/track_uneven_doc.md for the attribute. Python 3.8 or later, no other packages. """ import argparse import collections diff --git a/utilities/Classes.h b/utilities/Classes.h index 89872d450..1291d8433 100644 --- a/utilities/Classes.h +++ b/utilities/Classes.h @@ -9,6 +9,8 @@ http://mozilla.org/MPL/2.0/. #ifndef ClassesH #define ClassesH + +#include "interfaces/ITexture.h" // null_handle, for the handles below //--------------------------------------------------------------------------- // Ra: zestaw klas do robienia wskaźników, aby uporządkować nagłówki //--------------------------------------------------------------------------- @@ -30,7 +32,7 @@ class TTraction; // drut class TTractionPowerSource; // zasilanie drutów class TCamera; class scenario_time; -class TMoverParameters; +namespace physics { class Vehicle; } class ui_layer; class editor_ui; class itemproperties_panel; diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 71ab7987c..4461e8278 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -18,6 +18,7 @@ http://mozilla.org/MPL/2.0/. #include "simulation/simulationenvironment.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" +#include "utilities/inionlysettings.h" #include "utilities/utilities.h" #include "world/catenary_span.h" #include "Console.h" @@ -244,6 +245,65 @@ bool global_settings::ConfigParseAudio(cParser& Parser, const std::string& token return true; } + return ConfigParseAudioDevice(Parser, token); +} + +bool global_settings::ConfigParseAudioDevice(cParser& Parser, const std::string& token) +{ + if (token == "sound.outputmode") + { + AudioOutputMode = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf") + { + AudioHrtf = Parser.getToken(true); + return true; + } + + if (token == "sound.hrtf.profile") + { + AudioHrtfProfile = Parser.getToken(false); + return true; + } + + if (token == "sound.resampler") + { + AudioResampler = Parser.getToken(false); + return true; + } + + if (token == "sound.limiter") + { + AudioLimiter = Parser.getToken(true); + return true; + } + + if (token == "sound.frequency") + { + ParseOneClamped(Parser, AudioFrequency, 0, 192000); + return true; + } + + if (token == "sound.doppler") + { + ParseOneClamped(Parser, AudioDoppler, 0.f, 10.f); + return true; + } + + if (token == "sound.efx.lowpass") + { + ParseOne(Parser, AudioLowpass); + return true; + } + + if (token == "sound.efx.airabsorption") + { + ParseOneClamped(Parser, AudioAirAbsorption, 0.f, 10.f); + return true; + } + return false; } @@ -358,7 +418,8 @@ bool global_settings::ConfigParseGraphics(cParser& Parser, const std::string& to else if (GfxRenderer == "vulkan14") GfxRenderer = "vulkan"; - if ((GfxRenderer != "default") && (GfxRenderer != "vulkan")) + // "null" draws nothing and loads no textures, for the test runs + if ((GfxRenderer != "default") && (GfxRenderer != "vulkan") && (GfxRenderer != "null")) { // the legacy OpenGL 2.1 renderer ("legacy", "simple" and other values) and the NVRHI renderer ("experimental") were removed WriteLog("eu07.ini: gfxrenderer \"" + GfxRenderer + "\" is no longer supported, using \"default\""); @@ -477,6 +538,13 @@ bool global_settings::ConfigParseInput(cParser& Parser, const std::string& token return true; } + if (token == "consistviews") + { + // no: [Shift]+[F4] cycles through the four views of the train it had before the views of its vehicles + ParseOne(Parser, ConsistViews); + return true; + } + if (token == "input.gamepad") { ParseOne(Parser, InputGamepad); @@ -579,6 +647,14 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + // the saved odometer states of the vehicles not run for this many days are dropped, 0 = never (vehicle/odometer.h) + if (token == "odometer.expiry") + { + ParseOne(Parser, odometer_expiry); + odometer_expiry = std::max(0, odometer_expiry); + return true; + } + if (token == "blackbox") { bool blackbox{false}; @@ -895,6 +971,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "driverfigure.followsdirection") + { + ParseOne(Parser, DriverFigureFollowsDirection, 1, false); + return true; + } + if (token == "ai.brakesetting.cw1") { ParseOne(Parser, AIBrakeSettingCw1, 1, false); @@ -931,7 +1013,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& { std::string text; ParseOne(Parser, text); - Global.random_seed = seed_of(text); + // nothing after the key gives no seed; anything else does, 0 too + if (auto const seed{seed_given(text)}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + } return true; } @@ -953,6 +1040,20 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.trackbuckling") + { + // off, scenery: the buckles of the scenery and its events, auto: also by the temperature of the rails + std::string mode; + ParseOne(Parser, mode, 1); + if (mode == "off" || mode == "no") + track_buckling = track_buckling_mode::off; + else if (mode == "auto") + track_buckling = track_buckling_mode::automatic; + else + track_buckling = track_buckling_mode::scenery; + return true; + } + if (token == "couplerphysics") { // yes: the player's train and the trains it closes in on, all: every train @@ -963,6 +1064,38 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& return true; } + if (token == "physics.derailment") + { + // new: the physical criteria (physics/derailment.h), old: the legacy draw, off: no derailment from the speed, + // monitor: the legacy draw, and the criteria to the log + std::string model; + ParseOne(Parser, model, 1); + derailment = derailment_model_of(model); + return true; + } + + if (token == "physics.derailment.trustlimits") + { + ParseOne(Parser, derailment_trust_limits, 1); + return true; + } + + if (token == "physics.trackcheck") + { + ParseOne(Parser, track_check, 1); + return true; + } + + if (token == "physics.collisions") + { + // new: the crush of the ends past the buffers (physics/collision.h), old: the legacy rule, monitor: the legacy + // rule, and the crush to the log + std::string model; + ParseOne(Parser, model, 1); + collisions = collision_model_of(model); + return true; + } + if (token == "controlcoupling.enginecheck") { ParseOne(Parser, control_coupling_engine_check, 1); @@ -1037,6 +1170,15 @@ bool global_settings::ConfigParseScriptScreens(cParser& Parser, std::string_view return true; } + // the scenery scripts (lua in the .scn) with all of LuaJIT's libraries, for a scenery that needs io, ffi or + // require: they then reach files and programs as the player does. from eu07.ini only: a config block of the + // scenery doesn't change it (utilities/inionlysettings.h) + if (token == "lua.fulllibraries") + { + ParseOne(Parser, lua_fulllibraries, 1); + return true; + } + if (token == "wasm.enabled") { ParseOne(Parser, wasm_enabled, 1); @@ -1349,6 +1491,12 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return true; } + if (token == "debug.perflog") + { + ParseOne(Parser, debug_perflog); + return true; + } + if (token == "debuglog") { std::string value; @@ -1536,8 +1684,10 @@ bool global_settings::ConfigParseDebug(cParser& Parser, const std::string& token return false; } -void global_settings::ConfigParse(cParser& Parser) +void global_settings::ConfigParse(cParser& Parser, config_source const Source) { + // what a scenery doesn't change, kept before its keys are read + std::optional const inionly{Source == config_source::scenery ? std::make_optional(*this) : std::nullopt}; std::string token; do @@ -1595,6 +1745,15 @@ void global_settings::ConfigParse(cParser& Parser) } while (true); + if (inionly.has_value()) + { + // put back before FinalizeConfig() acts on them (feedbackmode) + for (auto const key : inionly->restore(*this)) + { + ErrorLog("scenery config: \"" + std::string(key) + "\" is read from eu07.ini only, ignored"); + } + } + FinalizeConfig(); } @@ -2128,6 +2287,20 @@ global_settings::ConfigParse_gfx_sky( cParser &Parser, std::string_view const To else if( Token == "gfx.skyvisibility.tunnels" ) { readswitch( gfx_skyvisibility_tunnels ); } else if( Token == "gfx.tunnelflags" ) { readswitch( gfx_tunnelflags ); } else if( Token == "gfx.lights.range" ) { readvalue( gfx_lights_range, 0.f, 2000.f ); } + else if( Token == "moths" ) { readswitch( moths ); } + else if( Token == "moths.share" ) { readvalue( moths_share, 0.f, 1.f ); } + else if( Token == "moths.range" ) { readvalue( moths_range, 0.f, 500.f ); } + else if( Token == "moths.temperature" ) { readvalue( moths_temperature, -50.f, 50.f ); } + else if( Token == "deer" ) { readswitch( deer ); } + else if( Token == "deer.interval" ) { readvalue( deer_interval, 0.0f, 100000.0f ); } + else if( Token == "deer.distance" ) { readvalue( deer_distance, 100.0f, 10000.0f ); } + else if( Token == "deer.chance" ) { readvalue( deer_chance, 0.0f, 1.0f ); } + else if( Token == "deer.hornrange" ) { readvalue( deer_hornrange, 0.0f, 5000.0f ); } + else if( Token == "deer.reactiontime" ) { readvalue( deer_reactiontime, 0.0f, 60.0f ); } + else if( Token == "deer.reactiondistance" ) { readvalue( deer_reactiondistance, 0.0f, 1000.0f ); } + else if( Token == "deer.fleedistance" ) { + // of the test builds before deer.reactiontime, never in a release: its value is passed over + Parser.getTokens( 1 ); } else if( Token == "gfx.lights.shadows" ) { // no/low/medium/high, or the number of the level Parser.getTokens( 1 ); @@ -2343,8 +2516,19 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "fmradio.enabled", fmradio_enabled ); export_as_text( Output, "fmradio.cleansound", fmradio_cleansound ); export_as_text( Output, "fmradio.stations", fmradio_stations ); + export_as_text( Output, "sound.maxsources", audio_max_sources ); + export_as_text( Output, "sound.outputmode", AudioOutputMode ); + export_as_text( Output, "sound.hrtf", AudioHrtf ); + export_as_text( Output, "sound.hrtf.profile", AudioHrtfProfile ); + export_as_text( Output, "sound.resampler", AudioResampler ); + export_as_text( Output, "sound.limiter", AudioLimiter ); + export_as_text( Output, "sound.frequency", AudioFrequency ); + export_as_text( Output, "sound.doppler", AudioDoppler ); + export_as_text( Output, "sound.efx.lowpass", AudioLowpass ); + export_as_text( Output, "sound.efx.airabsorption", AudioAirAbsorption ); export_as_text( Output, "physicslog", WriteLogFlag ); export_as_text( Output, "physicslog.trains", WriteTrainLogFlag ); + export_as_text( Output, "odometer.expiry", odometer_expiry ); if( BlackBox ) { export_as_text( Output, "blackbox", *BlackBox ); } @@ -2354,6 +2538,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "physics.pipewake", physics_pipewake ); export_as_text( Output, "performance.multithreading", performance_multithreading ); export_as_text( Output, "debug.memorystats", debug_memorystats ); + export_as_text( Output, "debug.perflog", debug_perflog ); export_as_text( Output, "debuglog", iWriteLogEnabled ); export_as_text( Output, "multiplelogs", MultipleLogs ); export_as_text( Output, "crashdump.full", crashdump_full ); @@ -2364,6 +2549,7 @@ global_settings::export_as_text( std::ostream &Output ) const { << fMouseXScale << " " << fMouseYScale << "\n"; export_as_text( Output, "mousecontrol", InputMouse ); + export_as_text( Output, "consistviews", ConsistViews ); export_as_text( Output, "enabletraction", bEnableTraction ); export_as_text( Output, "loadtraction", bLoadTraction ); export_as_text( Output, "friction", fFriction ); @@ -2386,13 +2572,22 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "scenario.time.offset", ScenarioTimeOffset ); export_as_text( Output, "scenario.time.current", ScenarioTimeCurrent ); export_as_text( Output, "scenario.weather.temperature", AirTemperature ); + export_as_text( Output, "physics.trackbuckling", std::string{ + track_buckling == track_buckling_mode::off ? "off" : + track_buckling == track_buckling_mode::automatic ? "auto" : + "scenery" } ); export_as_text( Output, "ai.trainman", AITrainman ); + export_as_text( Output, "driverfigure.followsdirection", DriverFigureFollowsDirection ); export_as_text( Output, "controlcoupling.enginecheck", control_coupling_engine_check ); std::string couplerphysics { coupler_physics ? "yes" : "no" }; if( coupler_physics_all ) { couplerphysics = "all"; } export_as_text( Output, "couplerphysics", couplerphysics ); + export_as_text( Output, "physics.derailment", std::string{ name_of( derailment ) } ); + export_as_text( Output, "physics.derailment.trustlimits", derailment_trust_limits ); + export_as_text( Output, "physics.trackcheck", track_check ); + export_as_text( Output, "physics.collisions", std::string{ name_of( collisions ) } ); export_as_text( Output, "ai.brakesetting.cw1", AIBrakeSettingCw1 ); export_as_text( Output, "scalespeculars", ScaleSpecularValues ); export_as_text( Output, "gfxrenderer", GfxRenderer ); @@ -2681,6 +2876,17 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "gfx.skyvisibility.tunnels", gfx_skyvisibility_tunnels ); export_as_text( Output, "gfx.tunnelflags", gfx_tunnelflags ); export_as_text( Output, "gfx.lights.range", gfx_lights_range ); + export_as_text( Output, "moths", moths ); + export_as_text( Output, "moths.share", moths_share ); + export_as_text( Output, "moths.range", moths_range ); + export_as_text( Output, "moths.temperature", moths_temperature ); + export_as_text( Output, "deer", deer ); + export_as_text( Output, "deer.interval", deer_interval ); + export_as_text( Output, "deer.distance", deer_distance ); + export_as_text( Output, "deer.chance", deer_chance ); + export_as_text( Output, "deer.hornrange", deer_hornrange ); + export_as_text( Output, "deer.reactiontime", deer_reactiontime ); + export_as_text( Output, "deer.reactiondistance", deer_reactiondistance ); export_as_text( Output, "gfx.lights.shadows", std::string{ gfx_lights_shadows == 3 ? "high" : gfx_lights_shadows == 2 ? "medium" : gfx_lights_shadows == 1 ? "low" : "no" } ); export_as_text( Output, "gfx.lights.shadows.cab", gfx_lights_shadows_cab ); export_as_text( Output, "gfx.lights.shadows.lamps", gfx_lights_shadows_lamps ); @@ -2721,6 +2927,7 @@ global_settings::export_as_text( std::ostream &Output ) const { export_as_text( Output, "python.uploadmain", python_uploadmain ); export_as_text( Output, "python.mipmaps", python_mipmaps ); export_as_text( Output, "luascreens.enabled", luascreens_enabled ); + export_as_text( Output, "lua.fulllibraries", lua_fulllibraries ); export_as_text( Output, "wasm.enabled", wasm_enabled ); export_as_text( Output, "screens.cabframes", screens_cabframes ); export_as_text( Output, "screens.externalframes", screens_externalframes ); diff --git a/utilities/Globals.h b/utilities/Globals.h index 762a821bd..77cb66652 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -25,6 +25,12 @@ http://mozilla.org/MPL/2.0/. #include "input/zmq_input.h" #endif +// where the keys global_settings::ConfigParse reads come from +enum class config_source { + ini, // eu07.ini, and the file given with -ini + scenery // a config block of a scenery (.scn, .inc), read as it loads +}; + struct global_settings { // members // data items @@ -50,6 +56,9 @@ struct global_settings { bool ready_to_load{ false }; std::time_t starting_timestamp = 0; // starting time, in local timezone uint32_t random_seed = 0; + // whether random_seed was given (-seed, randomseed, the server of a network session) or is still to be drawn: + // 0 is a seed like any other, so it can't stand for none + bool random_seed_given{ false }; TCamera pCamera; // parametry kamery TCamera pDebugCamera; std::array FreeCameraInit; // pozycje kamery @@ -123,6 +132,9 @@ struct global_settings { bool ParserLogIncludes{ true }; // simulation bool RealisticControlMode{ false }; // controls ability to steer the vehicle from outside views + // odometer.expiry: the saved odometer state of a vehicle not run for longer than this many days is dropped from the + // store (vehicle/odometer.h); 0 = never + int odometer_expiry{ 365 }; bool bEnableTraction{ true }; float fFriction{ 1.f }; // mnożnik tarcia - KURS90 float FrictionWeatherFactor{ 1.f }; @@ -135,10 +147,11 @@ struct global_settings { std::string Weather{ "cloudy:" }; // current weather std::string Period{}; // time of the day, based on sun position bool FullPhysics{ true }; // full calculations performed for each simulation step - bool physics_sleepheld{ true }; // vehicles standing still and held by their brakes let their physics sleep, see TMoverParameters::accelerating() - bool physics_roadlod{ true }; // road vehicles far from the camera go by one step of the physics in a frame, see vehicle_table::update() - float physics_pipewake{ 0.001f }; // bar: air flowing along a pipe wakes the physics of a vehicle when it changes its pressure by more than this. 0: any flow does + bool physics_sleepheld{ false }; // vehicles standing still and held by their brakes let their physics sleep, see physics::Vehicle::accelerating() + bool physics_roadlod{ false }; // road vehicles far from the camera go by one step of the physics in a frame, see vehicle_table::update() + float physics_pipewake{ 0.f }; // bar: air flowing along a pipe wakes the physics of a vehicle when it changes its pressure by more than this. 0: any flow does bool performance_multithreading{ true }; // work split over the logical cores of the machine (worker_pool), as many as each job is worth + float debug_perflog{ 0.f }; // every so many seconds the times and the counts of the renderer (its debug panel) go to perf.txt beside the log; 0: never bool debug_memorystats{ false }; // the memory of the parts of the program in the debug panel, with new and delete counted (start_heap_counting()). slows the loading down bool bnewAirCouplers{ true }; float fMoveLight{ 0.f }; // numer dnia w roku albo -1 @@ -156,6 +169,7 @@ struct global_settings { bool bJoinEvents{ false }; // czy grupować eventy o tych samych nazwach int iHiddenEvents{ 1 }; // czy łączyć eventy z torami poprzez nazwę toru bool AITrainman{ true }; // virtual assistant performing consist coupling/decoupling and other maintenance tasks + bool DriverFigureFollowsDirection{ true }; // driverfigure.followsdirection: the player's lowpoly driver figure in a single desk vehicle faces the selected direction, no: the occupied cab as before eu07/maszyna#535 bool AIBrakeSettingCw1{ true }; // ai.brakesetting.cw1: the AI wagon inspector sets the brakes (G/P/R/Mg) by the instruction Cw-1, no: as before eu07/maszyna#350 // ui int PythonScreenUpdateRate{ 200 }; // delay between python-based screen updates, in milliseconds @@ -276,6 +290,16 @@ struct global_settings { bool fmradio_enabled{ true }; // allows cab radio receivers to play internet radio streams bool fmradio_cleansound{ false }; // disables simulation of the receiver speaker std::string fmradio_stations{ "fmradio.txt" }; // list of stations available to the receivers + // OpenAL Soft device and mixing options; the defaults leave the choice to the library, as before they existed + std::string AudioOutputMode{ "auto" }; // sound.outputmode: auto, mono, stereo, stereo-basic, uhj, headphones, quad, 5.1, 6.1, 7.1 + std::string AudioHrtf{ "auto" }; // sound.hrtf: auto, on, off + std::string AudioHrtfProfile; // sound.hrtf.profile: name of the HRTF data set, empty for the library's choice + std::string AudioResampler; // sound.resampler: name of the resampler, empty for the library's default + std::string AudioLimiter{ "auto" }; // sound.limiter: auto, on, off + int AudioFrequency{ 0 }; // sound.frequency: mixing rate in Hz, 0 for the device's + float AudioDoppler{ 0.25f }; // sound.doppler: strength of the Doppler effect + bool AudioLowpass{ false }; // sound.efx.lowpass: soundproofing also muffles the high frequencies + float AudioAirAbsorption{ 0.f }; // sound.efx.airabsorption: 0-10, high frequencies fade with distance // input float fMouseXScale{ 1.5f }; float fMouseYScale{ 0.2f }; @@ -283,6 +307,7 @@ struct global_settings { int iFeedbackPort{ 0 }; // dodatkowy adres dla informacji zwrotnych bool InputGamepad{ true }; // whether gamepad support is enabled bool InputMouse{ true }; // whether control pick mode can be activated + bool ConsistViews{ true }; // whether [Shift]+[F4] goes on to the orbit, shunting, coupling and trackside views of the train (eu07/maszyna#551) double fBrakeStep { 1.0 }; // krok zmiany hamulca innych niż FV4a dla klawiszy [Num3] i [Num9] double brake_speed { 3.0 }; // prędkość przesuwu hamulca dla FV4a // parametry kalibracyjne wejść z pulpitu @@ -335,12 +360,39 @@ struct global_settings { bool captureonstart = true; bool render_cab = true; bool crash_damage = true; - // the physical model of the couplings (McZapkie/couplerphysics.h): progressive buffers and draw gear with hysteresis, - // the play of the coupling, its yield and breaking; the legacy model of TMoverParameters::CouplerForce() without it. + // the buckling of welded track in the heat (physics.trackbuckling in eu07.ini, see world/TrackBuckle.h): off, none; scenery, the + // buckles the scenery enters and its trackbuckle events; automatic, also by the temperature of the rails at the weak places + enum class track_buckling_mode { off, scenery, automatic }; + track_buckling_mode track_buckling = track_buckling_mode::scenery; + // the physical model of the couplings (physics/couplerphysics.h): progressive buffers and draw gear with hysteresis, + // the play of the coupling, its yield and breaking; the legacy model of physics::Vehicle::CouplerForce() without it. // it covers the player's train and the trains it closes in on (vehicle_table::update_coupler_physics()), or every // train with coupler_physics_all bool coupler_physics = false; bool coupler_physics_all = false; + // a vehicle too fast in a curve (physics.derailment in eu07.ini): new, it overturns or its flange climbs the rail + // by the criteria of physics/derailment.h held over 2 m, and slides on with the friction of the ballast; old, the + // legacy draw of the lateral acceleration against the gauge to the height of the vehicle in every step, which stops + // it; off, it stays on the rails at any speed; monitor, the legacy draw decides and the log tells where the criteria + // would derail a vehicle (derailment monitor:, once for a vehicle on a track), for the run of a scenery as it was. + // monitor is the default until the speed limits of the bundled sceneries are checked against the criteria (some + // tracks allow more than the reference vehicle survives there): new is opt-in until then + enum class derailment_model { off, old, physical, monitor }; + derailment_model derailment = derailment_model::monitor; + // physics.derailment.trustlimits, with new: under the speed limit of a track (and 10 % and 5 km/h over it) the curve + // and the cant alone derail nothing, the limit is a defect of the scenery, told once in the log (derailment monitor: + // data:). what the couplings, a buckle or the damage of the track bring about derails at any speed, see + // derailment::limited_verdict(). no: the criteria decide at any speed + bool derailment_trust_limits = true; + // the collisions of rail vehicles past their buffers (physics.collisions in eu07.ini): new, the ends crush, a vehicle + // may ride up onto the other one or be pushed off the track (physics/collision.h); old, the legacy rule of the safe + // closing speed weighed by the masses; monitor, the legacy rule decides and the log tells what the crush would be + // (collision monitor:, once for a hit). the road vehicles of the traffic keep the legacy rule with any + enum class collision_model { old, physical, monitor }; + collision_model collisions = collision_model::physical; + // physics.trackcheck: the geometry of the rail tracks the criteria of derailment find suspicious, to the log once the + // scenery loaded (trackcheck:, see world/TrackCheck.h) + bool track_check = false; bool control_coupling_engine_check = true; // no multiple-unit control between electric and diesel traction vehicles (eu07/maszyna#520) bool gui_defaultwindows = true; bool gui_showtranscripts = true; @@ -363,6 +415,7 @@ struct global_settings { bool python_uploadmain = true; std::chrono::duration python_minframetime {0.01f}; bool luascreens_enabled{true}; // screens drawn by Lua scripts (luascreen:, luadestinationsign: in the .mmd) + bool lua_fulllibraries{false}; // the scenery scripts (lua in the .scn) get all of LuaJIT's libraries (io, os, ffi, require...), not only the sandboxed ones bool wasm_enabled{true}; // screens drawn by WebAssembly modules (wasmscreen:, wasmdestinationsign: in the .mmd) int screens_cabframes{4}; // the script screens in the cab are refreshed every so many rendered frames int screens_externalframes{30}; // the script screens outside the cab (destination signs) are refreshed every so many rendered frames @@ -444,7 +497,11 @@ struct global_settings { bool gfx_bufferstreaming = true; bool gfx_postfx_motionblur_enabled = true; // the colour pass writes the velocities of the pixels: for the motion blur, the temporal anti-aliasing or dlss - bool gfx_motion_vectors() const { return gfx_postfx_motionblur_enabled || gfx_taa() || gfx_dlss(); } + // the velocity target is there also without them: the windscreens (mat_rain_windscreen, mat_bugs_windscreen, mat_snow_windscreen) + // send the post-processing their drops and haze through it (not without the pipeline: no post-processing there). the renderers + // draw it and run the pass of the motion blur only in the frames which need it: with something moving and the motion blur on, + // with the anti-aliasing which takes it, or with a glass of the kind in the view (windscreen_water::wants_glass_requests()) + bool gfx_motion_vectors() const { return ( false == gfx_skippipeline ) || gfx_postfx_motionblur_enabled; } float gfx_postfx_motionblur_shutter = 0.01f; GLenum gfx_postfx_motionblur_format = GL_RG16F; GLenum gfx_format_color = GL_RGB16F; @@ -601,6 +658,21 @@ struct global_settings { // the sound and the driver bool gfx_tunnelflags { false }; float gfx_lights_range { 300.f }; // distance from the camera the lights of models and vehicles are taken from, metres + // moths flying about the lit lamps of the scenery (rendering/common/moths.cpp): a swarm (the model animals/cmy, animated by + // textures) at a part of the lamps shining downwards, picked by their places, in the warm months, within the range of the camera + bool moths { true }; + float moths_share { 0.4f }; // part of the lamps with a swarm, 0-1 + float moths_range { 80.f }; // distance from the camera the swarms are shown at, metres + float moths_temperature { 8.f }; // the lowest temperature of the air moths fly at, degrees Celsius + // deer at the tracks (world/deer.cpp): put on the path ahead of the train of the player, grazing, they run away from the horn + // or the train coming close. off unless turned on + bool deer { false }; + float deer_interval { 2000.0f }; // metres the train covers between the deer, 0 none + float deer_distance { 2000.0f }; // metres ahead of the train a deer is put at + float deer_chance { 1.0f }; // of a deer at each interval, 0-1 + float deer_hornrange { 600.0f }; // the horn sends away the deer within this many metres + float deer_reactiontime { 3.5f }; // a deer runs away from the train this many seconds of its speed away, seconds + float deer_reactiondistance { 20.0f }; // and from a slow or a standing train come this close, metres // shadows of the lamps (cube shadow maps), 0 none, 1 low, 2 medium, 3 high; see opengl46_local_shadows. for now the lamp of the // occupied cab, its shadows cast by the cab int gfx_lights_shadows { 2 }; @@ -731,9 +803,12 @@ struct global_settings { // methods void LoadIniFile( std::string asFileName ); void FinalizeConfig(); - void ConfigParse(cParser &parser); + // the keys of eu07.ini. Source: where they come from, eu07.ini or a config block of a scenery, which doesn't change + // the settings only eu07.ini sets (utilities/inionlysettings.h) + void ConfigParse(cParser &parser, config_source Source = config_source::ini); bool ConfigParseGeneral(cParser& Parser, const std::string& token); bool ConfigParseAudio(cParser& Parser, const std::string& token); + bool ConfigParseAudioDevice(cParser& Parser, const std::string& token); bool ConfigParseGraphics(cParser& Parser, const std::string& token); bool ConfigParseInput(cParser& Parser, const std::string& token); bool ConfigParseSimulation(cParser& Parser, const std::string& token); @@ -771,6 +846,37 @@ template <> void global_settings::export_as_text( std::ostream &Output, std::string const Key, bool const &Value ) const; +// the models of physics.collisions by their names in eu07.ini: new (the default, also for a name it doesn't know), old, +// monitor +inline global_settings::collision_model collision_model_of( std::string_view const Name ) { + if( Name == "old" ) { return global_settings::collision_model::old; } + if( Name == "monitor" ) { return global_settings::collision_model::monitor; } + return global_settings::collision_model::physical; +} +inline std::string_view name_of( global_settings::collision_model const Model ) { + switch( Model ) { + case global_settings::collision_model::old: { return "old"; } + case global_settings::collision_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} +// the models of physics.derailment by their names in eu07.ini: new, old, off or no, monitor (the default, also for a +// name it doesn't know) +inline global_settings::derailment_model derailment_model_of(std::string_view const Name) { + if( Name == "new" ) { return global_settings::derailment_model::physical; } + if( Name == "old" ) { return global_settings::derailment_model::old; } + if( Name == "off" || Name == "no" ) { return global_settings::derailment_model::off; } + return global_settings::derailment_model::monitor; +} +inline std::string_view name_of( global_settings::derailment_model const Model ) { + switch( Model ) { + case global_settings::derailment_model::old: { return "old"; } + case global_settings::derailment_model::off: { return "off"; } + case global_settings::derailment_model::monitor: { return "monitor"; } + default: { return "new"; } + } +} + extern global_settings& GetGlobalSettings(); #define Global (GetGlobalSettings()) diff --git a/utilities/Logs.cpp b/utilities/Logs.cpp index 7eb99ad7c..47852be26 100644 --- a/utilities/Logs.cpp +++ b/utilities/Logs.cpp @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/Logs.h" +#include "utilities/logfiles.h" #include "utilities/crashsignals.h" #include @@ -83,6 +84,12 @@ std::atomic &log_stopped() static std::atomic stopped{false}; return stopped; } +// set once the settings are read: the files are named by them (multiplelogs, the scenery) +std::atomic &log_files_open() +{ + static std::atomic open{false}; + return open; +} } // namespace void StopLogService() @@ -90,6 +97,11 @@ void StopLogService() log_stopped() = true; } +void OpenLogFiles() +{ + log_files_open() = true; +} + void LogService() { @@ -97,6 +109,13 @@ void LogService() for (bool last{false}; false == last;) { last = log_stopped(); + // what is logged before the settings are read waits for them, or it would open (and empty) the shared log.txt + // of a run that writes its own files in logs/. a start that stops before that writes it anyway + if (false == log_files_open() && false == last) + { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + continue; + } { // --- Obsługa InfoStack --- while (!InfoStack.empty()) @@ -115,7 +134,7 @@ void LogService() { if (!output.is_open()) { - std::string filename = Global.MultipleLogs ? "logs/log (" + filename_scenery() + ") " + filename_date() + ".txt" : "log.txt"; + std::string const filename { log_file_name(log_file::log, Global.MultipleLogs, filename_scenery(), filename_date()) }; output.open(filename, std::ios::trunc); crashdump_set_log_file(crashdump_log_file::log, filename); // the stack of a crash on Linux goes to the end of this file @@ -155,7 +174,7 @@ void LogService() if (!errors.is_open()) { - std::string filename = Global.MultipleLogs ? "logs/errors (" + filename_scenery() + ") " + filename_date() + ".txt" : "errors.txt"; + std::string const filename { log_file_name(log_file::errors, Global.MultipleLogs, filename_scenery(), filename_date()) }; errors.open(filename, std::ios::trunc); crashdump_set_log_file(crashdump_log_file::errors, filename); errors << "EU07.EXE " + Global.asVersion << "\n"; diff --git a/utilities/Logs.h b/utilities/Logs.h index 63727de9c..5fd5d4a56 100644 --- a/utilities/Logs.h +++ b/utilities/Logs.h @@ -26,6 +26,9 @@ enum class logtype : unsigned int { // writes the log until StopLogService(), and all of it that came before void LogService(); void StopLogService(); +// the settings are read: the log files can be named and written from now on; until then the log service keeps what +// is logged +void OpenLogFiles(); void WriteLog( const char *str, logtype const Type = logtype::generic, bool isError = false ); void Error( const std::string &asMessage, bool box = false ); void Error( const char* &asMessage, bool box = false ); diff --git a/utilities/Timer.h b/utilities/Timer.h index 7976d51d2..3eed6eb15 100644 --- a/utilities/Timer.h +++ b/utilities/Timer.h @@ -88,7 +88,7 @@ private: float m_accumulator { 0.f }; }; -// what resets TMoverParameters::LastSwitchingTime, which keeps the physics of a vehicle on for 5 s: counted over a second, +// what resets physics::Vehicle::LastSwitchingTime, which keeps the physics of a vehicle on for 5 s: counted over a second, // with the vehicle which did it most often, for the debug panel class switching_counter { @@ -98,7 +98,7 @@ public: compressor_off, mains, diesel, - // switch_physics( true ) of a vehicle whose physics was off, by TMoverParameters::wake_cause, in its order + // switch_physics( true ) of a vehicle whose physics was off, by physics::Vehicle::wake_cause, in its order wake, wake_mainpipe, wake_scndpipe, @@ -213,12 +213,12 @@ struct subsystem_stopwatches { unsigned int largestgroup { 0 }; unsigned int maingroups { 0 }; // rail vehicles standing still (below 0.01 km/h) with the physics on, and what keeps it on by the test of - // TMoverParameters::ComputeTotalForce(); a vehicle can have several of these + // physics::Vehicle::ComputeTotalForce(); a vehicle can have several of these struct awake_reasons { unsigned int vehicles { 0 }; unsigned int cab { 0 }; // CabActive unsigned int speed { 0 }; // Vel above 0.0001 km/h - unsigned int acceleration { 0 }; // AccS above 0.0001 m/s2, and not held by the brakes (TMoverParameters::accelerating()) + unsigned int acceleration { 0 }; // AccS above 0.0001 m/s2, and not held by the brakes (physics::Vehicle::accelerating()) unsigned int switching { 0 }; // LastSwitchingTime below 5 s unsigned int multipleunit { 0 }; // EZT, DMU unsigned int neighbour { 0 }; // a neighbour moving or accelerating diff --git a/utilities/asciiname.cpp b/utilities/asciiname.cpp new file mode 100644 index 000000000..30f5f5cf0 --- /dev/null +++ b/utilities/asciiname.cpp @@ -0,0 +1,203 @@ +/* +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 "utilities/asciiname.h" + +#include +#include +#include +#include +#include + +namespace +{ + +// the characters of Windows-1250 from 0x80 up; 0 where the code page has none +constexpr std::array cp1250{ + 0x20AC, 0x0000, 0x201A, 0x0000, 0x201E, 0x2026, 0x2020, 0x2021, 0x0000, 0x2030, 0x0160, 0x2039, 0x015A, 0x0164, 0x017D, 0x0179, + 0x0000, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, 0x0000, 0x2122, 0x0161, 0x203A, 0x015B, 0x0165, 0x017E, 0x017A, + 0x00A0, 0x02C7, 0x02D8, 0x0141, 0x00A4, 0x0104, 0x00A6, 0x00A7, 0x00A8, 0x00A9, 0x015E, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x017B, + 0x00B0, 0x00B1, 0x02DB, 0x0142, 0x00B4, 0x00B5, 0x00B6, 0x00B7, 0x00B8, 0x0105, 0x015F, 0x00BB, 0x013D, 0x02DD, 0x013E, 0x017C, + 0x0154, 0x00C1, 0x00C2, 0x0102, 0x00C4, 0x0139, 0x0106, 0x00C7, 0x010C, 0x00C9, 0x0118, 0x00CB, 0x011A, 0x00CD, 0x00CE, 0x010E, + 0x0110, 0x0143, 0x0147, 0x00D3, 0x00D4, 0x0150, 0x00D6, 0x00D7, 0x0158, 0x016E, 0x00DA, 0x0170, 0x00DC, 0x00DD, 0x0162, 0x00DF, + 0x0155, 0x00E1, 0x00E2, 0x0103, 0x00E4, 0x013A, 0x0107, 0x00E7, 0x010D, 0x00E9, 0x0119, 0x00EB, 0x011B, 0x00ED, 0x00EE, 0x010F, + 0x0111, 0x0144, 0x0148, 0x00F3, 0x00F4, 0x0151, 0x00F6, 0x00F7, 0x0159, 0x016F, 0x00FA, 0x0171, 0x00FC, 0x00FD, 0x0163, 0x02D9}; + +// the letters of Latin-1 from U+00C0 up, without their marks +constexpr std::array latin1{ + "a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i", + "d", "n", "o", "o", "o", "o", "o", "_", "o", "u", "u", "u", "u", "y", "th", "ss", + "a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i", + "d", "n", "o", "o", "o", "o", "o", "_", "o", "u", "u", "u", "u", "y", "th", "y"}; + +// the letters of Latin Extended-A, U+0100 to U+017F, in runs of the same plain letter +struct run +{ + int count; + std::string_view letter; +}; +constexpr std::array extended{{{6, "a"}, {8, "c"}, {4, "d"}, {10, "e"}, {8, "g"}, {4, "h"}, {10, "i"}, {2, "ij"}, {2, "j"}, {3, "k"}, {10, "l"}, + {9, "n"}, {6, "o"}, {2, "oe"}, {6, "r"}, {8, "s"}, {6, "t"}, {12, "u"}, {2, "w"}, {3, "y"}, {6, "z"}, {1, "s"}}}; + +std::string_view plain_letter(char32_t const Code) +{ + if (Code >= 0xC0 && Code < 0x100) + return latin1[Code - 0xC0]; + if (Code >= 0x100 && Code < 0x180) + { + auto left{static_cast(Code - 0x100)}; + for (auto const &letters : extended) + { + if (left < letters.count) + return letters.letter; + left -= letters.count; + } + } + return "_"; +} + +// the byte at the given place, as a number +std::uint32_t byte_at(std::string_view const Text, std::size_t const At) +{ + return static_cast(static_cast(Text[At])); +} + +// the length of the UTF-8 sequence the byte begins, with the bits of the character it holds; 0 for a byte which can't begin one +int sequence_length(std::uint32_t const Lead, char32_t &Code) +{ + if (Lead < 0x80) + { + Code = Lead; + return 1; + } + if (Lead < 0xC2 || Lead >= 0xF5) + return 0; + if (Lead < 0xE0) + { + Code = Lead & 0x1Fu; + return 2; + } + if (Lead < 0xF0) + { + Code = Lead & 0x0Fu; + return 3; + } + Code = Lead & 0x07u; + return 4; +} + +// the character of the UTF-8 sequence at the given place; false if there's no valid one +bool decode_one(std::string_view const Text, std::size_t const At, int const Length, char32_t &Code) +{ + if (At + Length > Text.size()) + return false; + for (int i = 1; i < Length; ++i) + { + auto const next{byte_at(Text, At + i)}; + if ((next & 0xC0u) != 0x80u) + return false; + Code = (Code << 6) | (next & 0x3Fu); + } + // the shortest form only, as UTF-8 has it + return false == ((Length == 3 && Code < 0x800) || (Length == 4 && (Code < 0x10000 || Code > 0x10FFFF))); +} + +// the characters of a valid UTF-8 text; false if it isn't one +bool decode_utf8(std::string_view const Text, std::vector &Codes) +{ + Codes.clear(); + std::size_t at{0}; + while (at < Text.size()) + { + char32_t code{0}; + auto const length{sequence_length(byte_at(Text, at), code)}; + if (length == 0 || false == decode_one(Text, at, length, code)) + return false; + Codes.push_back(code); + at += length; + } + return true; +} + +std::vector characters(std::string_view const Name) +{ + std::vector codes; + if (decode_utf8(Name, codes)) + return codes; + codes.clear(); + for (std::size_t at = 0; at < Name.size(); ++at) + { + auto const byte{byte_at(Name, at)}; + if (byte < 0x80) + codes.push_back(byte); + else + codes.push_back(cp1250[byte - 0x80] != 0 ? cp1250[byte - 0x80] : 0xFFFD); + } + return codes; +} + +void append_utf8(std::string &Output, char32_t const Code) +{ + if (Code < 0x80) + Output += static_cast(Code); + else if (Code < 0x800) + { + Output += static_cast(0xC0 | (Code >> 6)); + Output += static_cast(0x80 | (Code & 0x3F)); + } + else if (Code < 0x10000) + { + Output += static_cast(0xE0 | (Code >> 12)); + Output += static_cast(0x80 | ((Code >> 6) & 0x3F)); + Output += static_cast(0x80 | (Code & 0x3F)); + } + else + { + Output += static_cast(0xF0 | (Code >> 18)); + Output += static_cast(0x80 | ((Code >> 12) & 0x3F)); + Output += static_cast(0x80 | ((Code >> 6) & 0x3F)); + Output += static_cast(0x80 | (Code & 0x3F)); + } +} + +} // namespace + +namespace ascii_name +{ + +bool plain(std::string_view const Name) +{ + return std::ranges::all_of(Name, [](char const Character) { return static_cast(Character) < 0x80; }); +} + +std::string fold(std::string_view const Name) +{ + std::string result; + result.reserve(Name.size()); + for (auto const code : characters(Name)) + { + if (code < 0x80) + result += static_cast(std::tolower(static_cast(code))); + else + result += plain_letter(code); + } + return result; +} + +std::string readable(std::string_view const Name) +{ + std::string result; + result.reserve(Name.size() * 2); + for (auto const code : characters(Name)) + append_utf8(result, code); + return result; +} + +} // namespace ascii_name diff --git a/utilities/asciiname.h b/utilities/asciiname.h new file mode 100644 index 000000000..1e89b5bb7 --- /dev/null +++ b/utilities/asciiname.h @@ -0,0 +1,29 @@ +/* +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 + +#include +#include + +// names of the scenery written in plain ASCII. +// a name with letters outside of it is read as UTF-8 when it's valid UTF-8, otherwise as Windows-1250, +// the code page of the most of the sceneries +namespace ascii_name +{ + +// true if the name holds nothing but ASCII +bool plain(std::string_view Name); +// the name in ASCII, in lower case as the parser gives the names: the letters with marks lose them (ł -> l, ß -> ss), +// whatever else isn't ASCII becomes '_' +std::string fold(std::string_view Name); +// the name as UTF-8, to be shown or logged: a name which isn't valid UTF-8 is taken for Windows-1250 +std::string readable(std::string_view Name); + +} // namespace ascii_name diff --git a/utilities/comparison.h b/utilities/comparison.h index f0fc5d0af..1345e690b 100644 --- a/utilities/comparison.h +++ b/utilities/comparison.h @@ -48,11 +48,23 @@ to_string( comparison_operator const Operator ) { case lt: { return "<"; } case gt: { return ">"; } case lt_eq: { return "<="; } - case gt_eq: { return ">"; } + case gt_eq: { return ">="; } default: { return "??"; } } } +inline +std::string +to_string( comparison_pass const Pass ) { + switch( Pass ) { + using enum comparison_pass; + case all: { return "all"; } + case any: { return "any"; } + case none: { return "none"; } + default: { return "all"; } + } +} + inline comparison_pass comparison_pass_from_string( std::string const &Input ) { diff --git a/utilities/enumset.h b/utilities/enumset.h new file mode 100644 index 000000000..ae5dea20e --- /dev/null +++ b/utilities/enumset.h @@ -0,0 +1,130 @@ +/* +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/. +*/ + +// a set of the values of an enum class whose values are bits: what a coupling joins, the damage of a vehicle. the +// numbers of the files (their sums of the bits) come in only through FromBits() and go out through Bits() + +#pragma once + +#include + +// an enum is a kind of the sets by a specialisation of this, which also gives its operator | +template struct IsEnumSetKind : std::false_type +{ +}; + +template class EnumSet +{ + static_assert(std::is_enum_v, "a set of the values of an enum"); + +public: + constexpr EnumSet() = default; + constexpr EnumSet(Enum const value) : bits{static_cast(value)} {} // NOSONAR: a value is a set of one + // the set the number of a file gives (the sum of the numbers of the values) + static constexpr EnumSet FromBits(int const number) + { + EnumSet set; + set.bits = static_cast(number); + return set; + } + // every value: a set of any of them has one of these + static constexpr EnumSet All() + { + return FromBits(-1); + } + // the number of the set, for the files and the log + constexpr int Bits() const + { + return static_cast(bits); + } + constexpr bool Empty() const + { + return bits == 0; + } + // any value at all: as the old number was true when it wasn't zero + constexpr explicit operator bool() const + { + return bits != 0; + } + // all the values of the other set are in this one + constexpr bool HasAll(EnumSet const other) const + { + return (bits & other.bits) == other.bits; + } + // any of the values of the other set is in this one + constexpr bool HasAny(EnumSet const other) const + { + return (bits & other.bits) != 0; + } + // adds the values; returns whether any of them was missing (as SetFlag()) + constexpr bool Set(EnumSet const other) + { + if (HasAll(other)) + { + return false; + } + bits |= other.bits; + return true; + } + // takes the values away, where all of them are there; returns whether it did (as ClearFlag()) + constexpr bool Clear(EnumSet const other) + { + if (false == HasAll(other)) + { + return false; + } + bits &= ~other.bits; + return true; + } + // this set without the values of the other + constexpr EnumSet Without(EnumSet const other) const + { + return FromBits(static_cast(bits & ~other.bits)); + } + constexpr EnumSet &operator|=(EnumSet const other) + { + bits |= other.bits; + return *this; + } + constexpr EnumSet &operator&=(EnumSet const other) + { + bits &= other.bits; + return *this; + } + // the values in one of the sets and not in the other: what changed between them + constexpr EnumSet &operator^=(EnumSet const other) + { + bits ^= other.bits; + return *this; + } + friend constexpr EnumSet operator|(EnumSet left, EnumSet const right) + { + return left |= right; + } + friend constexpr EnumSet operator&(EnumSet left, EnumSet const right) + { + return left &= right; + } + friend constexpr EnumSet operator^(EnumSet left, EnumSet const right) + { + return left ^= right; + } + friend constexpr bool operator==(EnumSet const &left, EnumSet const &right) = default; + +private: + unsigned bits{0}; +}; + +// two values make a set of them, for the enums which are kinds of the sets +template + requires IsEnumSetKind::value +constexpr EnumSet operator|(Enum const left, Enum const right) +{ + return EnumSet{left} | EnumSet{right}; +} diff --git a/utilities/hardwareinfo.cpp b/utilities/hardwareinfo.cpp new file mode 100644 index 000000000..3124307ba --- /dev/null +++ b/utilities/hardwareinfo.cpp @@ -0,0 +1,441 @@ +/* +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 "utilities/hardwareinfo.h" + +#include +#include +#include +#include +#include + +namespace hardware { + +namespace { + +std::string lowercase(std::string_view Text) +{ + std::string result{Text}; + for (auto &c : result) + c = static_cast(std::tolower(static_cast(c))); + return result; +} + +bool contains(std::string_view Text, std::string_view What) +{ + return Text.find(What) != std::string_view::npos; +} + +void erase_all(std::string &Text, std::string_view What) +{ + auto at = Text.find(What); + while (at != std::string::npos) + { + Text.erase(at, What.size()); + at = Text.find(What, at); + } +} + +// the words of a GPU name, lowercase: without the (TM) and (R) marks, and without what follows them in parentheses +// (Mesa adds the driver and the chip: "AMD Radeon Graphics (radeonsi, renoir, LLVM 15.0.7)") +std::vector name_words(std::string_view Name) +{ + auto name{lowercase(Name)}; + erase_all(name, "(tm)"); + erase_all(name, "(r)"); + if (auto const parenthesis = name.find('('); parenthesis != std::string::npos) + name.erase(parenthesis); + std::vector words; + std::string word; + for (auto const c : name) + { + if (std::isalnum(static_cast(c))) + { + word += c; + } + else if (!word.empty()) + { + words.push_back(std::move(word)); + word.clear(); + } + } + if (!word.empty()) + words.push_back(std::move(word)); + return words; +} + +// whether the words hold First directly followed by Second +bool has_pair(std::vector const &Words, std::string_view First, std::string_view Second) +{ + for (std::size_t i = 0; i + 1 < Words.size(); ++i) + if (Words[i] == First && Words[i + 1] == Second) + return true; + return false; +} + +bool has_word(std::vector const &Words, std::string_view What) +{ + return std::ranges::find(Words, What) != Words.end(); +} + +bool is_number(std::string_view Word) +{ + return !Word.empty() && std::ranges::all_of(Word, [](char const c) { return std::isdigit(static_cast(c)) != 0; }); +} + +bool is_software_name(std::string_view Name) +{ + constexpr std::array markers{"llvmpipe", "softpipe", "swiftshader", "gdi generic", "software rasterizer", "basic render driver"}; + auto const name{lowercase(Name)}; + return std::ranges::any_of(markers, [&name](std::string_view const Marker) { return contains(name, Marker); }); +} + +gpu_kind classify_intel(std::vector const &Words) +{ + using enum gpu_kind; + // Iris Xe MAX (DG1) is a laptop card + for (std::size_t i = 0; i + 2 < Words.size(); ++i) + if (Words[i] == "iris" && Words[i + 1] == "xe" && Words[i + 2] == "max") + return discrete; + // the Arc cards have a letter and a number after "Arc" (A310, A770, B580) or are the Pro ones; the integrated Arc + // are "Arc Graphics" (Meteor Lake), "Arc 140V" (Lunar Lake) and "Arc B370", "Arc B390" (Panther Lake), the B3xx + // range, below the B570 and B580 cards + for (std::size_t i = 0; i + 1 < Words.size(); ++i) + { + if (Words[i] != "arc") + continue; + auto const &model{Words[i + 1]}; + if (model == "pro") + return discrete; + if (model.size() >= 2 && model[0] == 'b' && model[1] == '3') + return integrated; + if (model.size() >= 2 && std::isalpha(static_cast(model[0])) && std::isdigit(static_cast(model[1]))) + return discrete; + } + return integrated; +} + +// Raven Ridge and Picasso APUs: "Radeon RX Vega 11 Graphics", "Radeon RX Vega 10 Graphics". the RX Vega cards have +// no "Graphics" ("Radeon RX Vega 56"), and Kaby Lake G's own-memory chip has a letter ("Radeon RX Vega M GH Graphics") +bool is_rx_vega_apu(std::vector const &Words) +{ + if (Words.empty() || Words.back() != "graphics") + return false; + for (std::size_t i = 0; i + 2 < Words.size(); ++i) + if (Words[i] == "rx" && Words[i + 1] == "vega" && is_number(Words[i + 2])) + return true; + return false; +} + +gpu_kind classify_amd(std::vector const &Words) +{ + using enum gpu_kind; + if (is_rx_vega_apu(Words)) + return integrated; + if (has_word(Words, "rx") || has_word(Words, "firepro") || has_word(Words, "instinct") || has_pair(Words, "radeon", "pro") || has_pair(Words, "radeon", "vii")) + return discrete; + // the APUs are "Radeon Graphics", "Radeon Vega 8 Graphics", "Radeon R7 Graphics", "Radeon 780M Graphics"; the + // cards are named by their model ("Radeon RX 580 Series", "Radeon R7 370") + if (!Words.empty() && Words.back() == "graphics") + return integrated; + return unknown; +} + +std::string_view yes_no(int const Value) +{ + if (Value > 0) + return "yes"; + if (Value == 0) + return "no"; + return "unknown"; +} + +// "Key: value" of /proc/cpuinfo and /proc/meminfo +std::pair split_entry(std::string_view Line) +{ + auto const colon = Line.find(':'); + if (colon == std::string_view::npos) + return {}; + auto key{Line.substr(0, colon)}; + auto value{Line.substr(colon + 1)}; + while (!key.empty() && std::isspace(static_cast(key.back()))) + key.remove_suffix(1); + while (!value.empty() && std::isspace(static_cast(value.front()))) + value.remove_prefix(1); + while (!value.empty() && std::isspace(static_cast(value.back()))) + value.remove_suffix(1); + return {key, value}; +} + +template void for_each_line(std::string_view Text, Function &&Each) +{ + while (!Text.empty()) + { + auto const end = Text.find('\n'); + Each(Text.substr(0, end)); + if (end == std::string_view::npos) + break; + Text.remove_prefix(end + 1); + } +} + +std::uint64_t to_number(std::string_view Text) +{ + std::uint64_t result{0}; + for (auto const c : Text) + { + if (!std::isdigit(static_cast(c))) + break; + result = result * 10 + static_cast(c - '0'); + } + return result; +} + +// the state of reading /proc/cpuinfo, line by line +struct cpuinfo_reader +{ + cpu_info cpu; + std::set> cores; // (physical id, core id) + std::set> packages; + int cores_per_package{0}; + std::string package; + + void read(std::string_view Line); +}; + +void cpuinfo_reader::read(std::string_view const Line) +{ + auto const [key, value] = split_entry(Line); + if (key == "processor") + { + ++cpu.logical_cores; + package.clear(); + } + else if ((key == "model name" || key == "Model") && cpu.model.empty()) + { + cpu.model = tidy_name(value); + } + else if (key == "physical id") + { + package = value; + packages.emplace(value); + } + else if (key == "core id") + { + cores.emplace(package, value); + } + else if (key == "cpu cores" && cores_per_package == 0) + { + cores_per_package = static_cast(to_number(value)); + } + else if (key == "flags" && cpu.avx2 < 0) + { + auto const flags{name_words(value)}; + cpu.avx2 = has_word(flags, "avx2") ? 1 : 0; + } +} + +} // namespace + +std::string_view to_string(gpu_kind const Kind) +{ + using enum gpu_kind; + switch (Kind) + { + case integrated: + return "integrated"; + case discrete: + return "discrete"; + case software: + return "software"; + default: + return "unknown"; + } +} + +gpu_kind classify_gpu(std::uint32_t const VendorId, std::string_view const Name) +{ + using enum gpu_kind; + if (is_software_name(Name)) + return software; + auto const words{name_words(Name)}; + switch (VendorId) + { + case vendor_nvidia: + return discrete; + case vendor_intel: + return classify_intel(words); + case vendor_amd: + case vendor_amd_alt: + return classify_amd(words); + default: + return unknown; + } +} + +std::uint32_t vendor_from_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + // the vendor first; Mesa ("Mesa", "X.Org", "Collabora Ltd") and the D3D12 layer ("Microsoft Corporation") name + // the maker of the chip in the renderer + for (auto const &text : {lowercase(GlVendor), lowercase(GlRenderer)}) + { + if (contains(text, "nvidia") || contains(text, "geforce") || contains(text, "quadro")) + return vendor_nvidia; + if (contains(text, "ati technologies") || contains(text, "advanced micro devices") || contains(text, "radeon") || has_word(name_words(text), "amd")) + return vendor_amd; + if (contains(text, "intel")) + return vendor_intel; + } + return 0; +} + +bool is_software_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + return is_software_name(GlRenderer) || is_software_name(GlVendor); +} + +gpu_kind classify_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + if (is_software_gl(GlVendor, GlRenderer)) + return gpu_kind::software; + return classify_gpu(vendor_from_gl(GlVendor, GlRenderer), GlRenderer); +} + +std::string format_size(std::uint64_t const Bytes) +{ + constexpr std::uint64_t mebibyte{1024 * 1024}; + constexpr std::uint64_t gibibyte{1024 * mebibyte}; + if (Bytes < gibibyte) + return std::format("{} MiB", (Bytes + mebibyte / 2) / mebibyte); + return std::format("{:.1f} GiB", static_cast(Bytes) / static_cast(gibibyte)); +} + +std::string tidy_name(std::string_view const Name) +{ + std::string result; + for (auto const c : Name) + { + if (c == '\0') + break; + if (std::isspace(static_cast(c))) + { + if (!result.empty() && result.back() != ' ') + result += ' '; + continue; + } + result += c; + } + if (!result.empty() && result.back() == ' ') + result.pop_back(); + return result; +} + +cpu_info parse_cpuinfo(std::string_view const Text) +{ + cpuinfo_reader reader; + for_each_line(Text, [&reader](std::string_view const Line) { reader.read(Line); }); + auto cpu{std::move(reader.cpu)}; + if (!reader.cores.empty()) + cpu.physical_cores = static_cast(reader.cores.size()); + else if (reader.cores_per_package > 0) + cpu.physical_cores = reader.cores_per_package * static_cast(std::max(reader.packages.size(), 1)); + return cpu; +} + +memory_info parse_meminfo(std::string_view const Text) +{ + memory_info memory; + for_each_line(Text, [&memory](std::string_view const Line) { + auto const [key, value] = split_entry(Line); + // the values are in kB (kibibytes, whatever the unit says) + if (key == "MemTotal") + memory.total = to_number(value) * 1024; + else if (key == "MemAvailable") + memory.available = to_number(value) * 1024; + }); + return memory; +} + +std::string format_cpu(cpu_info const &Cpu) +{ + auto line{std::format("hardware: cpu: {}", Cpu.model.empty() ? std::string{"unknown"} : Cpu.model)}; + if (Cpu.physical_cores > 0) + line += std::format(", {} cores", Cpu.physical_cores); + if (Cpu.logical_cores > 0) + line += std::format(", {} threads", Cpu.logical_cores); + line += std::format(", avx2 {}", yes_no(Cpu.avx2)); + return line; +} + +std::string format_memory(memory_info const &Memory) +{ + auto line{std::format("hardware: ram: {} total", Memory.total > 0 ? format_size(Memory.total) : std::string{"unknown"})}; + if (Memory.available > 0) + line += std::format(", {} available", format_size(Memory.available)); + return line; +} + +std::string format_adapter(int const Index, gpu_adapter const &Adapter) +{ + return std::format("hardware: gpu {}: {} (vendor 0x{:04x}, device 0x{:04x}), {} dedicated, {} shared, {} outputs, {}", Index, Adapter.description, Adapter.vendor_id, Adapter.device_id, + format_size(Adapter.dedicated_video_memory), format_size(Adapter.shared_system_memory), Adapter.outputs, + Adapter.software ? to_string(gpu_kind::software) : to_string(classify_gpu(Adapter.vendor_id, Adapter.description))); +} + +std::string format_gl(std::string_view const GlVendor, std::string_view const GlRenderer) +{ + return std::format("hardware: opengl gpu: {} ({}), {}", GlRenderer, GlVendor, to_string(classify_gl(GlVendor, GlRenderer))); +} + +std::string format_gl_memory(gl_memory_info const &Memory) +{ + std::string line{"hardware: opengl gpu memory:"}; + if (Memory.dedicated > 0) + line += std::format(" {} dedicated", format_size(Memory.dedicated)); + if (Memory.available > 0) + line += std::format("{} {} free", Memory.dedicated > 0 ? "," : "", format_size(Memory.available)); + if (Memory.dedicated == 0 && Memory.available == 0) + line += " unknown"; + return line; +} + +std::vector gl_warnings(std::vector const &Adapters, std::string_view const GlVendor, std::string_view const GlRenderer) +{ + std::vector warnings; + auto const kind{classify_gl(GlVendor, GlRenderer)}; + if (kind == gpu_kind::software) + { + warnings.push_back(std::format("hardware: warning: OpenGL draws on the cpu ({}), the graphics driver is missing or not used", GlRenderer)); + return warnings; + } + if (kind != gpu_kind::integrated) + return warnings; + if (auto const discrete = std::ranges::find_if(Adapters, [](gpu_adapter const &Adapter) { + return !Adapter.software && classify_gpu(Adapter.vendor_id, Adapter.description) == gpu_kind::discrete; + }); + discrete != Adapters.end()) + { + warnings.push_back(std::format("hardware: warning: OpenGL runs on the integrated GPU ({}) though there is a dedicated one ({}); " + "choose High performance for the game in the Windows graphics settings or the GPU control panel, " + "and connect the monitor to the dedicated GPU", + GlRenderer, discrete->description)); + } + return warnings; +} + +std::vector cpu_warnings(cpu_info const &Cpu, bool const BuildNeedsAvx2) +{ + std::vector warnings; + if (BuildNeedsAvx2 && Cpu.avx2 == 0) + warnings.emplace_back("hardware: warning: the cpu has no AVX2, which this build of the game needs"); + return warnings; +} + +} // namespace hardware diff --git a/utilities/hardwareinfo.h b/utilities/hardwareinfo.h new file mode 100644 index 000000000..54fdbd02d --- /dev/null +++ b/utilities/hardwareinfo.h @@ -0,0 +1,114 @@ +/* +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 + +#include +#include +#include +#include + +// what the log says about the machine at startup: the cpu, the memory, the graphics adapters and the one OpenGL runs +// on. a bug report then shows whether the game ran on the integrated GPU of a laptop instead of the dedicated one. +// this part holds the rules and the text, which need nothing of the machine; the probing is in hardwareprobe.cpp +namespace hardware { + +// the PCI vendor ids of the graphics adapters +constexpr std::uint32_t vendor_nvidia{0x10de}; +constexpr std::uint32_t vendor_amd{0x1002}; +constexpr std::uint32_t vendor_amd_alt{0x1022}; // AMD's cpu id, shown by some APUs +constexpr std::uint32_t vendor_intel{0x8086}; +constexpr std::uint32_t vendor_microsoft{0x1414}; // Microsoft Basic Render Driver, the software adapter + +enum class gpu_kind { + unknown, // can't tell from the name; never taken for either of the other two + integrated, // part of the cpu, shares the system memory + discrete, // a card (or a chip) with its own memory + software, // drawn by the cpu (Microsoft Basic Render Driver, GDI Generic, llvmpipe) +}; + +std::string_view to_string(gpu_kind Kind); + +// whether a GPU is integrated or discrete, from its vendor and its name (the DXGI description or GL_RENDERER). +// conservative, by the names the vendors give their chips: +// - NVIDIA: discrete (PC NVIDIA graphics have been cards or laptop chips with their own memory since the nForce days) +// - Intel: discrete only for the Arc cards (Arc A380/A770/B580, Arc Pro A60) and Iris Xe MAX; the rest (HD, UHD, +// Iris, Arc Graphics, Arc 140V and Arc B370/B390 of Meteor/Lunar/Panther Lake) is integrated +// - AMD: discrete for Radeon RX/Pro/VII, FirePro and Instinct; integrated for the APU names, which have no model +// number before "Graphics" (Radeon(TM) Graphics, Radeon Vega 8 Graphics, Radeon 780M Graphics, Radeon 8060S +// Graphics), and Radeon RX Vega 11 Graphics of Raven Ridge; anything else (an old Radeon HD, R7 ...) is unknown, as +// both cards and APUs were named so +// - software renderers are software; any other vendor (virtual machines, Qualcomm) is unknown +gpu_kind classify_gpu(std::uint32_t VendorId, std::string_view Name); + +// the PCI vendor id behind the GL_VENDOR and GL_RENDERER strings (Mesa names the vendor in the renderer); 0 if none +std::uint32_t vendor_from_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// whether GL_VENDOR and GL_RENDERER name a renderer that draws on the cpu +bool is_software_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// the kind of the GPU an OpenGL context runs on +gpu_kind classify_gl(std::string_view GlVendor, std::string_view GlRenderer); + +// a graphics adapter of the system (on Windows, as DXGI lists it) +struct gpu_adapter { + std::string description; + std::uint32_t vendor_id{0}; + std::uint32_t device_id{0}; + std::uint64_t dedicated_video_memory{0}; // bytes + std::uint64_t shared_system_memory{0}; // bytes + int outputs{0}; // the monitors connected to it + bool software{false}; +}; + +struct cpu_info { + std::string model; + int logical_cores{0}; // 0: unknown + int physical_cores{0}; // 0: unknown + int avx2{-1}; // 1 yes, 0 no, -1 unknown +}; + +struct memory_info { + std::uint64_t total{0}; // bytes, 0: unknown + std::uint64_t available{0}; // bytes, 0: unknown +}; + +// what the context's driver says of its memory (GL_NVX_gpu_memory_info, GL_ATI_meminfo), in bytes, 0: not told +struct gl_memory_info { + std::uint64_t dedicated{0}; + std::uint64_t available{0}; +}; + +// a size for a person to read: "512 MiB", "7.9 GiB" +std::string format_size(std::uint64_t Bytes); + +// trims the padding cpuid and the registry leave in the cpu brand string, squeezes the runs of spaces +std::string tidy_name(std::string_view Name); + +// what /proc/cpuinfo says of the cpu: the model name, the processors (logical cores) and the distinct cores +cpu_info parse_cpuinfo(std::string_view Text); + +// what /proc/meminfo says of the memory: MemTotal and MemAvailable +memory_info parse_meminfo(std::string_view Text); + +// the lines of the log, every one starting with "hardware: " so a single grep finds them all +std::string format_cpu(cpu_info const &Cpu); +std::string format_memory(memory_info const &Memory); +std::string format_adapter(int Index, gpu_adapter const &Adapter); +std::string format_gl(std::string_view GlVendor, std::string_view GlRenderer); +std::string format_gl_memory(gl_memory_info const &Memory); + +// the warnings of the log about the GPU OpenGL runs on: on the cpu, or on an integrated GPU while the system has a +// discrete one (Adapters: as the system lists them; the software ones are passed over). nothing if all is well +std::vector gl_warnings(std::vector const &Adapters, std::string_view GlVendor, std::string_view GlRenderer); + +// the warning of the log about a cpu without AVX2 when the build needs it. nothing if all is well +std::vector cpu_warnings(cpu_info const &Cpu, bool BuildNeedsAvx2); + +} // namespace hardware diff --git a/utilities/hardwareprobe.cpp b/utilities/hardwareprobe.cpp new file mode 100644 index 000000000..b7574281b --- /dev/null +++ b/utilities/hardwareprobe.cpp @@ -0,0 +1,336 @@ +/* +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 "utilities/hardwareprobe.h" + +#include "utilities/hardwareinfo.h" +#include "utilities/Logs.h" + +#include +#include + +#if defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__) +#define EU07_HARDWARE_X86 1 +#ifdef _MSC_VER +#include +#else +#include +#endif +#endif + +#ifdef _WIN32 +#include +#endif + +namespace hardware { + +namespace { + +// the adapters log_system() found, for the warning of log_gl_context() +std::vector &system_adapters() +{ + static std::vector adapters; + return adapters; +} + +#ifdef EU07_HARDWARE_X86 +// the eax, ebx, ecx and edx the cpuid instruction gives for the provided leaf and subleaf +std::array cpuid(unsigned int const Leaf, unsigned int const Subleaf) +{ + std::array result{}; +#ifdef _MSC_VER + std::array registers{}; + __cpuidex(registers.data(), static_cast(Leaf), static_cast(Subleaf)); + for (std::size_t i = 0; i < result.size(); ++i) + result[i] = static_cast(registers[i]); +#else + __cpuid_count(Leaf, Subleaf, result[0], result[1], result[2], result[3]); +#endif + return result; +} + +// the brand string of the cpu ("AMD Ryzen 5 5600X 6-Core Processor"); empty if the cpu has none +std::string cpu_brand() +{ + if (cpuid(0x80000000u, 0)[0] < 0x80000004u) + return {}; + std::array brand{}; + for (unsigned int leaf = 0; leaf < 3; ++leaf) + { + auto const registers{cpuid(0x80000002u + leaf, 0)}; + std::memcpy(brand.data() + leaf * 16, registers.data(), 16); + } + return tidy_name(brand.data()); +} + +// whether the cpu has AVX2 and the system saves the AVX registers +int cpu_avx2() +{ +#ifdef _MSC_VER + if (cpuid(0, 0)[0] < 7) + return 0; + auto const features{cpuid(1, 0)}; + auto const osxsave{(features[2] & (1u << 27)) != 0}; + auto const avx{(features[2] & (1u << 28)) != 0}; + if (!osxsave || !avx) + return 0; + if ((_xgetbv(0) & 0x6) != 0x6) // the system saves xmm and ymm + return 0; + return (cpuid(7, 0)[1] & (1u << 5)) != 0 ? 1 : 0; +#else + // checks the system's support as well + __builtin_cpu_init(); + return __builtin_cpu_supports("avx2") ? 1 : 0; +#endif +} +#endif + +#ifdef _WIN32 +std::string narrow(wchar_t const *Text) +{ + auto const length{WideCharToMultiByte(CP_UTF8, 0, Text, -1, nullptr, 0, nullptr, nullptr)}; + if (length <= 1) + return {}; + std::string result(static_cast(length - 1), '\0'); + WideCharToMultiByte(CP_UTF8, 0, Text, -1, result.data(), length, nullptr, nullptr); + return result; +} + +std::string registry_cpu_name() +{ + char name[256]{}; + DWORD size{sizeof(name)}; + if (RegGetValueA(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", "ProcessorNameString", RRF_RT_REG_SZ, nullptr, name, &size) != ERROR_SUCCESS) + return {}; + return tidy_name(name); +} + +int physical_cores() +{ + DWORD length{0}; + GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &length); + if (length == 0) + return 0; + std::vector buffer(length); + auto *records{reinterpret_cast(buffer.data())}; + if (!GetLogicalProcessorInformationEx(RelationProcessorCore, records, &length)) + return 0; + int cores{0}; + for (DWORD offset = 0; offset < length;) + { + auto const *record{reinterpret_cast(buffer.data() + offset)}; + if (record->Size == 0) + break; + ++cores; + offset += record->Size; + } + return cores; +} + +cpu_info probe_cpu() +{ + cpu_info cpu; +#ifdef EU07_HARDWARE_X86 + cpu.model = cpu_brand(); + cpu.avx2 = cpu_avx2(); +#endif + if (cpu.model.empty()) + cpu.model = registry_cpu_name(); + cpu.logical_cores = static_cast(GetActiveProcessorCount(ALL_PROCESSOR_GROUPS)); + cpu.physical_cores = physical_cores(); + return cpu; +} + +memory_info probe_memory() +{ + memory_info memory; + MEMORYSTATUSEX status{}; + status.dwLength = sizeof(status); + if (GlobalMemoryStatusEx(&status)) + { + memory.total = status.ullTotalPhys; + memory.available = status.ullAvailPhys; + } + return memory; +} + +// the adapters DXGI lists, the software one left out. dxgi.dll is loaded only for this, so the game doesn't link it; +// from System32 only, so a proxy dxgi.dll left in the game folder (ReShade, ENB) isn't loaded with it +std::vector probe_adapters() +{ + std::vector adapters; + auto *library{LoadLibraryExW(L"dxgi.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)}; + if (library == nullptr) + { + WriteLog("hardware: gpus: dxgi.dll not found"); + return adapters; + } + using create_factory = HRESULT(WINAPI *)(REFIID, void **); + auto const create{reinterpret_cast(reinterpret_cast(GetProcAddress(library, "CreateDXGIFactory1")))}; + IDXGIFactory1 *factory{nullptr}; + if (create == nullptr || FAILED(create(__uuidof(IDXGIFactory1), reinterpret_cast(&factory))) || factory == nullptr) + { + WriteLog("hardware: gpus: can't create a DXGI factory"); + FreeLibrary(library); + return adapters; + } + IDXGIAdapter1 *adapter{nullptr}; + for (UINT index = 0; SUCCEEDED(factory->EnumAdapters1(index, &adapter)); ++index) + { + DXGI_ADAPTER_DESC1 description{}; + if (SUCCEEDED(adapter->GetDesc1(&description))) + { + gpu_adapter entry; + entry.description = tidy_name(narrow(description.Description)); + entry.vendor_id = description.VendorId; + entry.device_id = description.DeviceId; + entry.dedicated_video_memory = description.DedicatedVideoMemory; + entry.shared_system_memory = description.SharedSystemMemory; + entry.software = (description.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) != 0 || description.VendorId == vendor_microsoft; + IDXGIOutput *output{nullptr}; + while (SUCCEEDED(adapter->EnumOutputs(static_cast(entry.outputs), &output))) + { + output->Release(); + ++entry.outputs; + } + if (!entry.software) + adapters.push_back(std::move(entry)); + } + adapter->Release(); + } + factory->Release(); + FreeLibrary(library); + return adapters; +} +#else +std::string read_file(char const *Path) +{ + std::ifstream file{Path}; + if (!file) + return {}; + std::stringstream text; + text << file.rdbuf(); + return text.str(); +} + +cpu_info probe_cpu() +{ + auto cpu{parse_cpuinfo(read_file("/proc/cpuinfo"))}; +#ifdef EU07_HARDWARE_X86 + if (cpu.model.empty()) + cpu.model = cpu_brand(); + cpu.avx2 = cpu_avx2(); +#endif + if (cpu.logical_cores == 0) + cpu.logical_cores = static_cast(std::thread::hardware_concurrency()); + return cpu; +} + +memory_info probe_memory() +{ + return parse_meminfo(read_file("/proc/meminfo")); +} +#endif + +std::string gl_string(GLenum const Name) +{ + auto const *text{reinterpret_cast(glGetString(Name))}; + return text != nullptr ? std::string{text} : std::string{"unknown"}; +} + +bool has_gl_extension(std::string_view const Name) +{ + if (glGetStringi != nullptr) + { + GLint count{0}; + glGetIntegerv(GL_NUM_EXTENSIONS, &count); + for (GLint i = 0; i < count; ++i) + { + auto const *extension{reinterpret_cast(glGetStringi(GL_EXTENSIONS, static_cast(i)))}; + if (extension != nullptr && Name == extension) + return true; + } + return false; + } + // OpenGL ES 2: one string of them all + auto const *extensions{reinterpret_cast(glGetString(GL_EXTENSIONS))}; + return extensions != nullptr && std::string_view{extensions}.find(Name) != std::string_view::npos; +} + +gl_memory_info probe_gl_memory() +{ + // GL_NVX_gpu_memory_info and GL_ATI_meminfo tokens, in kilobytes + constexpr GLenum gpu_memory_info_dedicated_vidmem_nvx{0x9047}; + constexpr GLenum gpu_memory_info_current_available_vidmem_nvx{0x9049}; + constexpr GLenum texture_free_memory_ati{0x87fc}; + + gl_memory_info memory; + if (has_gl_extension("GL_NVX_gpu_memory_info")) + { + GLint kilobytes{0}; + glGetIntegerv(gpu_memory_info_dedicated_vidmem_nvx, &kilobytes); + memory.dedicated = static_cast(std::max(kilobytes, 0)) * 1024; + kilobytes = 0; + glGetIntegerv(gpu_memory_info_current_available_vidmem_nvx, &kilobytes); + memory.available = static_cast(std::max(kilobytes, 0)) * 1024; + } + else if (has_gl_extension("GL_ATI_meminfo")) + { + // the free memory of the texture pool, the largest free block, and the same of the auxiliary memory + std::array kilobytes{}; + glGetIntegerv(texture_free_memory_ati, kilobytes.data()); + memory.available = static_cast(std::max(kilobytes[0], 0)) * 1024; + } + // a driver that takes the queries amiss leaves an error the renderer would report as its own. each call takes one + // error off; a lost context may keep reporting one, hence the limit + constexpr int max_errors{32}; + for (int i = 0; i < max_errors && glGetError() != GL_NO_ERROR; ++i) + { + // nothing else to do + } + return memory; +} + +} // namespace + +void log_system() +{ + auto const cpu{probe_cpu()}; + WriteLog(format_cpu(cpu)); + // an AVX2 build on a cpu without it may die on an illegal instruction before this line; when it gets here (the + // start so far ran without an AVX2 or FMA instruction), the line names the cause of the crash that comes later +#ifdef __AVX2__ + constexpr bool build_needs_avx2{true}; +#else + constexpr bool build_needs_avx2{false}; +#endif + for (auto const &warning : cpu_warnings(cpu, build_needs_avx2)) + WriteLog(warning); + WriteLog(format_memory(probe_memory())); +#ifdef _WIN32 + auto &adapters{system_adapters()}; + adapters = probe_adapters(); + for (std::size_t index = 0; index < adapters.size(); ++index) + WriteLog(format_adapter(static_cast(index), adapters[index])); +#endif +} + +void log_gl_context() +{ + auto const vendor{gl_string(GL_VENDOR)}; + auto const renderer{gl_string(GL_RENDERER)}; + WriteLog(format_gl(vendor, renderer)); + if (auto const memory{probe_gl_memory()}; memory.dedicated > 0 || memory.available > 0) + WriteLog(format_gl_memory(memory)); + for (auto const &warning : gl_warnings(system_adapters(), vendor, renderer)) + WriteLog(warning); +} + +} // namespace hardware diff --git a/utilities/hardwareprobe.h b/utilities/hardwareprobe.h new file mode 100644 index 000000000..75cb1e405 --- /dev/null +++ b/utilities/hardwareprobe.h @@ -0,0 +1,22 @@ +/* +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 + +// writes the machine to the log at startup, every line starting with "hardware: " (see hardwareinfo.h) +namespace hardware { + +// the cpu, the memory and, on Windows, the graphics adapters DXGI lists +void log_system(); + +// the GPU the current OpenGL context runs on, its memory where the driver tells it, and a warning when it's the +// integrated GPU while the system has a dedicated one. after log_system(), with the context current +void log_gl_context(); + +} // namespace hardware diff --git a/utilities/inionlysettings.cpp b/utilities/inionlysettings.cpp new file mode 100644 index 000000000..fb8d8f58f --- /dev/null +++ b/utilities/inionlysettings.cpp @@ -0,0 +1,96 @@ +/* +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 "utilities/inionlysettings.h" + +namespace +{ + +// puts Kept back into Current, and adds Key to Changed when they differed +template void keep(Type_ &Current, Type_ const &Kept, std::string_view const Key, std::vector &Changed) +{ + if (false == (Current == Kept)) + { + Current = Kept; + Changed.push_back(Key); + } +} + +// a switch a scenery may turn off but not on: puts Kept back into Current, and adds Key to Changed, only when the +// scenery turned it on. turned off it stays so, as before these keys were kept +void keep_off(bool &Current, bool const Kept, std::string_view const Key, std::vector &Changed) +{ + if (Current && false == Kept) + { + Current = false; + Changed.push_back(Key); + } +} + +} // namespace + +ini_only_settings::ini_only_settings(global_settings const &Settings) + : m_exec_on_exit{Settings.exec_on_exit}, m_screenshot_dir{Settings.screenshot_dir}, m_extcam_cmd{Settings.extcam_cmd}, + m_extcam_rec{Settings.extcam_rec}, m_network_servers{Settings.network_servers}, m_network_client{Settings.network_client}, +#ifdef WITH_ZMQ + m_zmq_address{Settings.zmq_address}, +#endif + m_motiontelemetry{Settings.motiontelemetry_conf}, +#ifdef WITH_UART + m_uart{Settings.uart_conf}, +#endif + m_feedback_mode{Settings.iFeedbackMode}, m_feedback_port{Settings.iFeedbackPort}, m_python_enabled{Settings.python_enabled}, + m_luascreens_enabled{Settings.luascreens_enabled}, m_lua_fulllibraries{Settings.lua_fulllibraries}, m_wasm_enabled{Settings.wasm_enabled}, + m_odometer_expiry{Settings.odometer_expiry} +{ +} + +std::vector ini_only_settings::restore(global_settings &Settings) const +{ + std::vector changed; + keep(Settings.exec_on_exit, m_exec_on_exit, "execonexit", changed); + keep(Settings.screenshot_dir, m_screenshot_dir, "screenshotsdir", changed); + keep(Settings.extcam_cmd, m_extcam_cmd, "extcam.cmd", changed); + keep(Settings.extcam_rec, m_extcam_rec, "extcam.rec", changed); + keep(Settings.network_servers, m_network_servers, "network.server", changed); + keep(Settings.network_client, m_network_client, "network.client", changed); +#ifdef WITH_ZMQ + keep(Settings.zmq_address, m_zmq_address, "zmq.address", changed); +#endif + // the structures as a whole, told apart by what turns them on and where they lead + { + auto ¤t{Settings.motiontelemetry_conf}; + if (current.enable != m_motiontelemetry.enable || current.proto != m_motiontelemetry.proto || current.address != m_motiontelemetry.address || + current.port != m_motiontelemetry.port) + { + changed.emplace_back("motiontelemetry"); + } + current = m_motiontelemetry; + } +#ifdef WITH_UART + { + auto ¤t{Settings.uart_conf}; + if (current.enable != m_uart.enable || current.port != m_uart.port) + { + changed.emplace_back("uart"); + } + current = m_uart; + } +#endif + keep(Settings.iFeedbackMode, m_feedback_mode, "feedbackmode", changed); + keep(Settings.iFeedbackPort, m_feedback_port, "feedbackport", changed); + // a scenery may switch a runtime off, and keep its scripts in the sandbox + keep_off(Settings.python_enabled, m_python_enabled, "python.enabled", changed); + keep_off(Settings.luascreens_enabled, m_luascreens_enabled, "luascreens.enabled", changed); + keep_off(Settings.lua_fulllibraries, m_lua_fulllibraries, "lua.fulllibraries", changed); + keep_off(Settings.wasm_enabled, m_wasm_enabled, "wasm.enabled", changed); + keep(Settings.odometer_expiry, m_odometer_expiry, "odometer.expiry", changed); + return changed; +} diff --git a/utilities/inionlysettings.h b/utilities/inionlysettings.h new file mode 100644 index 000000000..6dba86927 --- /dev/null +++ b/utilities/inionlysettings.h @@ -0,0 +1,58 @@ +/* +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 + +#include "utilities/Globals.h" + +#include +#include +#include +#include +#include + +// the settings only eu07.ini sets. a scenery's config block is read by the parser of eu07.ini +// (state_serializer::deserialize_config, global_settings::ConfigParse), and with these keys it would run a program +// (execonexit, extcam.cmd, extcam.rec), write the screenshots elsewhere (screenshotsdir), open connections and ports +// (network.server, network.client, zmq.address, motiontelemetry, uart, feedbackmode, feedbackport), switch back on a +// script runtime the player switched off (python.enabled, luascreens.enabled, wasm.enabled), take its own scripts +// out of the sandbox (lua.fulllibraries) or drop the odometer states the player keeps (odometer.expiry). they keep +// what eu07.ini set; a scenery may still switch a runtime off, or keep its scripts in the sandbox when eu07.ini didn't, +// as it always could +class ini_only_settings +{ + public: + // what Settings holds now, as eu07.ini set it + explicit ini_only_settings(global_settings const &Settings); + + // puts back into Settings what changed since, and gives the keys of eu07.ini whose settings changed + std::vector restore(global_settings &Settings) const; + + private: + std::string m_exec_on_exit; + std::string m_screenshot_dir; + std::string m_extcam_cmd; + std::string m_extcam_rec; + std::vector> m_network_servers; + std::optional> m_network_client; +#ifdef WITH_ZMQ + std::string m_zmq_address; +#endif + motiontelemetry::conf_t m_motiontelemetry; +#ifdef WITH_UART + uart_input::conf_t m_uart; +#endif + int m_feedback_mode; + int m_feedback_port; + bool m_python_enabled; + bool m_luascreens_enabled; + bool m_lua_fulllibraries; + bool m_wasm_enabled; + int m_odometer_expiry; +}; diff --git a/utilities/logfiles.cpp b/utilities/logfiles.cpp new file mode 100644 index 000000000..7dd9a6745 --- /dev/null +++ b/utilities/logfiles.cpp @@ -0,0 +1,26 @@ +/* +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 "utilities/logfiles.h" + +#include + +std::string log_file_name(log_file const Kind, bool const MultipleLogs, std::string_view const Scenery, std::string_view const Date) +{ + std::string_view const name{Kind == log_file::errors ? "errors" : "log"}; + return MultipleLogs ? std::format("logs/{} ({}) {}.txt", name, Scenery, Date) : std::format("{}.txt", name); +} + +std::vector stale_log_files(bool const MultipleLogs) +{ + if (MultipleLogs) + return {}; + return {log_file_name(log_file::log, false, {}, {}), log_file_name(log_file::errors, false, {}, {})}; +} diff --git a/utilities/logfiles.h b/utilities/logfiles.h new file mode 100644 index 000000000..7c88ea436 --- /dev/null +++ b/utilities/logfiles.h @@ -0,0 +1,29 @@ +/* +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 + +#include +#include +#include + +// the files the log is written to, and which of them a run clears when it starts. kept apart from the log service so +// the unit tests can check them + +// the log of everything, and the list of the errors (made at the first error) +enum class log_file { log, errors }; + +// the name of a log file: the shared one in the game folder, or with multiplelogs the run's own in logs/, named after +// the scenery and the time +std::string log_file_name(log_file Kind, bool MultipleLogs, std::string_view Scenery, std::string_view Date); + +// the shared log files a run deletes when it starts: the ones it writes itself, that is without multiplelogs, so an +// errors.txt of an earlier run doesn't stay behind when this one logs no error. with multiplelogs the run writes files +// of its own in logs/, and the log.txt / errors.txt of the last ordinary run are kept +std::vector stale_log_files(bool MultipleLogs); diff --git a/utilities/motiontelemetry.cpp b/utilities/motiontelemetry.cpp index b0dd02dc1..c263c23ea 100644 --- a/utilities/motiontelemetry.cpp +++ b/utilities/motiontelemetry.cpp @@ -6,6 +6,7 @@ #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "simulation/simulation.h" +#include "physics/vehicle.h" #ifdef _WIN32 #include @@ -92,14 +93,14 @@ void motiontelemetry::update() if (conf.latposbased) local_acc.x -= glm::dot(acc, leftvector); else - local_acc.x -= t->Occupied()->AccN; + local_acc.x -= t->Occupied()->AccN(); - local_acc.y += glm::dot(acc, up) + t->Occupied()->AccVert * conf.axlebumpscale; + local_acc.y += glm::dot(acc, up) + t->Occupied()->AccVert() * conf.axlebumpscale; if (conf.fwdposbased) local_acc.z += glm::dot(acc, frontvector); else - local_acc.z += t->Occupied()->AccSVBased; + local_acc.z += t->Occupied()->AccSVBased(); local_acc /= 9.81; @@ -129,7 +130,7 @@ void motiontelemetry::update() glm::dvec3 rot(asin(-frontvector.y), atan2(frontvector.x, frontvector.z), asin(sinroll)); - double velocity = t->Occupied()->V; + double velocity = t->Occupied()->V(); double yaw_vel = (rot.y - last_yaw) / dt; last_yaw = rot.y; diff --git a/utilities/parser.h b/utilities/parser.h index 19fc34f18..fa4c2c597 100644 --- a/utilities/parser.h +++ b/utilities/parser.h @@ -62,10 +62,12 @@ class cParser //: public std::stringstream std::string out; readToken(out); return out == Value; }; + // the end of the data: of this text, and of the file included last in it, which an include directive at the very + // end of the text leaves to be read inline bool - eof() { - return mEofBit; }; + eof() const { + return mEofBit && ( mIncludeParser == nullptr || mIncludeParser->eof() ); }; inline bool ok() { diff --git a/utilities/translation.cpp b/utilities/translation.cpp index 1048dcfb8..0d007bbd8 100644 --- a/utilities/translation.cpp +++ b/utilities/translation.cpp @@ -15,7 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/translation.h" #include "utilities/Logs.h" #include "utilities/Globals.h" -#include "MOVER.h" +#include "physics/vehicle.h" void locale::init() { @@ -267,6 +267,8 @@ std::string locale::label_cab_control(std::string const &Label) { "fuelpump_sw:", STRN("fuel pump") }, { "oilpump_sw:", STRN("oil pump") }, { "oilfuelpump_sw:", STRN("oil and fuel pumps") }, + { "tractionmode_sw:", STRN("traction mode selector") }, + { "genset_sw:", STRN("diesel generator") }, { "motorblowersfront_sw:", STRN("motor blowers A") }, { "motorblowersrear_sw:", STRN("motor blowers B") }, { "motorblowersalloff_sw:", STRN("all motor blowers") }, @@ -417,25 +419,25 @@ std::string locale::label_cab_control(std::string const &Label) const std::string& locale::coupling_name(int c) { - static std::unordered_map coupling_names = + static std::unordered_map coupling_names = { - { coupling::faux, STRN("faux") }, - { coupling::coupler, STRN("coupler") }, - { coupling::brakehose, STRN("brake hose") }, - { coupling::control, STRN("control") }, - { coupling::highvoltage, STRN("high voltage") }, - { coupling::gangway, STRN("gangway") }, - { coupling::mainhose, STRN("main hose") }, - { coupling::heating, STRN("heating") }, - { coupling::permanent, STRN("permanent") }, - { coupling::power24v, STRN("power 24V") }, - { coupling::power110v, STRN("power 110V") }, - { coupling::power3x400v, STRN("power 3x400V") }, + { Coupling::none, STRN("faux") }, + { Coupling::coupler, STRN("coupler") }, + { Coupling::brakeHose, STRN("brake hose") }, + { Coupling::control, STRN("control") }, + { Coupling::highVoltage, STRN("high voltage") }, + { Coupling::gangway, STRN("gangway") }, + { Coupling::mainHose, STRN("main hose") }, + { Coupling::heating, STRN("heating") }, + { Coupling::permanent, STRN("permanent") }, + { Coupling::power24v, STRN("power 24V") }, + { Coupling::power110v, STRN("power 110V") }, + { Coupling::power3x400v, STRN("power 3x400V") }, }; static std::string unknown(STRN("unknown")); - auto it = coupling_names.find(static_cast(c)); + auto it = coupling_names.find(static_cast(c)); if (it != coupling_names.end()) return lookup_s(it->second); else diff --git a/utilities/uart.cpp b/utilities/uart.cpp index 632c2b4c6..84ec31419 100644 --- a/utilities/uart.cpp +++ b/utilities/uart.cpp @@ -9,6 +9,7 @@ #include "utilities/utilities.h" #include "simulation/simulationtime.h" #include "application/application.h" +#include "physics/vehicle.h" const char* const uart_baudrates_list[] = { "300", @@ -451,7 +452,7 @@ void uart_input::poll() GLFW_PRESS, // TODO: pass correct entity id once the missing systems are in place 0); - simulation::Train->Occupied()->eimic_analog = desiredpercent; + simulation::Train->Occupied()->SetEimicAnalog(desiredpercent); } } if( true == conf.scndenable ) { diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 9d5c614d7..1adb80a5b 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -16,6 +16,7 @@ Copyright (C) 2007-2014 Maciej Cierniak //#include //#include #include +#include #include #include //#ifndef WIN32 @@ -57,6 +58,33 @@ std::string Now() #endif } +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback) +{ + // as the spec has it: a variable which isn't set, is empty or holds a relative path counts as not set. absolute is + // said the way a posix system says it, so the answer is the same on every system the tests run on + if (Variable != nullptr && Variable[0] == '/') + return std::filesystem::path(Variable); + if (Home != nullptr && Home[0] != '\0') + return std::filesystem::path(Home) / Fallback; + return {}; +} + +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home) +{ + auto const base{xdg_base_directory(Variable, Home, ".config")}; + if (base.empty()) + return {}; + auto folder{base / "MaSzyna"}; + if (Home != nullptr && Home[0] != '\0') + { + auto legacy{std::filesystem::path(Home) / ".config" / "MaSzyna"}; + std::error_code error; + if (legacy != folder && false == std::filesystem::exists(folder, error) && std::filesystem::is_directory(legacy, error)) + return legacy; + } + return folder; +} + std::filesystem::path user_config_path(const std::string &filename) { namespace fs = std::filesystem; @@ -67,8 +95,17 @@ std::filesystem::path user_config_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Application Support" / "MaSzyna" / filename; #else - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".config" / "MaSzyna" / filename; + if (auto const folder{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; false == folder.empty()) + { + if (auto const wanted{xdg_base_directory(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"), ".config") / "MaSzyna"}; + folder != wanted) + { + // said once, so whoever set XDG_CONFIG_HOME knows why the settings aren't there + static std::once_flag told; + std::call_once(told, [&] { WriteLog(std::format("Settings kept in \"{}\", the folder of the earlier releases, since \"{}\" doesn't exist", folder.string(), wanted.string())); }); + } + return folder / filename; + } #endif return {}; // env var missing → caller falls back to CWD-relative filename } @@ -83,10 +120,8 @@ std::filesystem::path user_cache_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Caches" / "MaSzyna" / filename; #else - if (const char *cache = std::getenv("XDG_CACHE_HOME"); cache != nullptr && *cache != '\0') - return fs::path(cache) / "MaSzyna" / filename; - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".cache" / "MaSzyna" / filename; + if (auto const base{xdg_base_directory(std::getenv("XDG_CACHE_HOME"), std::getenv("HOME"), ".cache")}; false == base.empty()) + return base / "MaSzyna" / filename; #endif return {}; } @@ -158,6 +193,11 @@ void set_thread_random_engine(std::mt19937 *Engine) // NOSONAR: randomness of th t_random_engine = Engine; } +std::mt19937 *thread_random_engine() // NOSONAR: randomness of the simulation, not of anything security-relevant +{ + return t_random_engine; +} + double Random(double min, double max) { if (max < min) { std::swap(min, max); } // std::uniform_real_distribution requires min <= max (inverted bounds are UB) @@ -198,10 +238,19 @@ std::uint64_t true_random_seed() std::uint32_t seed_of(std::string const &Text) { - if (std::uint32_t number{}; std::from_chars(Text.data(), Text.data() + Text.size(), number).ec == std::errc{}) + auto const *const end{Text.data() + Text.size()}; + std::uint32_t number{}; + auto const [last, error]{std::from_chars(Text.data(), end, number)}; + if (error == std::errc{} && last == end) { return number; } + if (error == std::errc{}) + { + // digits with something after them are a word like any other, not the number in front of them: "4242abc" + // isn't seed 4242. said in the log, since whoever wrote it most likely meant a number + WriteLog(std::format("seed \"{}\" isn't a number, taken as a word", Text)); + } std::uint32_t hash{}; for (auto const character : Text) { @@ -210,6 +259,15 @@ std::uint32_t seed_of(std::string const &Text) return hash; } +std::optional seed_given(std::string const &Text) +{ + if (Text.empty()) + { + return std::nullopt; + } + return seed_of(Text); +} + std::string generate_uuid_v4() { std::uniform_int_distribution dist(0, 255); @@ -338,7 +396,7 @@ std::string ToUpper(std::string const &text) void win1250_to_ascii(std::string &Input) { - std::unordered_map const charmap{{165, 'A'}, {198, 'C'}, {202, 'E'}, {163, 'L'}, {209, 'N'}, {211, 'O'}, {140, 'S'}, {143, 'Z'}, {175, 'Z'}, + static std::unordered_map const charmap{{165, 'A'}, {198, 'C'}, {202, 'E'}, {163, 'L'}, {209, 'N'}, {211, 'O'}, {140, 'S'}, {143, 'Z'}, {175, 'Z'}, {185, 'a'}, {230, 'c'}, {234, 'e'}, {179, 'l'}, {241, 'n'}, {243, 'o'}, {156, 's'}, {159, 'z'}, {191, 'z'}}; std::unordered_map::const_iterator lookup; for (auto &input : Input) @@ -472,9 +530,126 @@ void win1250_to_utf32(std::string const &Text, std::u32string &Output) } } +namespace +{ +void append_utf8(std::string &Output, char32_t const Codepoint) +{ + if (Codepoint < 0x80) + { + Output += static_cast(Codepoint); + } + else if (Codepoint < 0x800) + { + Output += static_cast(0xC0 | (Codepoint >> 6)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } + else if (Codepoint < 0x10000) + { + Output += static_cast(0xE0 | (Codepoint >> 12)); + Output += static_cast(0x80 | ((Codepoint >> 6) & 0x3F)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } + else + { + Output += static_cast(0xF0 | (Codepoint >> 18)); + Output += static_cast(0x80 | ((Codepoint >> 12) & 0x3F)); + Output += static_cast(0x80 | ((Codepoint >> 6) & 0x3F)); + Output += static_cast(0x80 | (Codepoint & 0x3F)); + } +} +} // namespace + +std::string data_text_to_utf8(std::string const &Text) +{ + if (std::ranges::all_of(Text, [](char const Character) { return static_cast(Character) < 0x80; })) + { + return Text; + } + std::u32string codepoints; + // a text in windows-1250 can happen to be valid utf-8 as well: two capital letters with marks in a row, as the bytes + // D3 A3 of "WOLKA" with its marks, make a sequence of two bytes. such a pair decodes to a letter between U+0180 and + // U+07FF (cyrillic, greek and the like), which the texts of the data files, when they are in utf-8, don't have + if (utf8_to_utf32(Text, codepoints) && std::ranges::none_of(codepoints, [](char32_t const Codepoint) { return Codepoint >= 0x180 && Codepoint < 0x800; })) + { + return Text; + } + // the code page the data files are written in + win1250_to_utf32(Text, codepoints); + std::string output; + output.reserve(Text.size() + 8); + for (auto const codepoint : codepoints) + { + // the bytes the code page has no character for come as 0 + append_utf8(output, codepoint != 0 ? codepoint : U'?'); + } + return output; +} + +std::string data_name_to_utf8(std::string const &Name, bool const Underscorestospaces) +{ + auto name{data_text_to_utf8(Name)}; + // in utf-8 the bytes below 0x80 are characters of their own, never a part of another one + for (auto &character : name) + { + if (static_cast(character) < 0x20 || (Underscorestospaces && character == '_')) + { + character = ' '; + } + } + return name; +} + +namespace +{ +// number of bytes of the character of a text in utf-8 which starts at given position; 1 for a byte which starts no valid sequence +std::size_t utf8_character_size(std::string_view const Text, std::size_t const Position) +{ + auto const length{utf8_sequence_length(static_cast(Text[Position]))}; + if (length < 2 || Position + length > Text.size()) + { + return 1; + } + for (std::size_t offset = 1; offset < length; ++offset) + { + if ((static_cast(Text[Position + offset]) & std::byte{0xC0}) != std::byte{0x80}) + { + return 1; + } + } + return length; +} +} // namespace + +std::size_t utf8_length(std::string_view const Text) +{ + std::size_t length{0}; + for (std::size_t position = 0; position < Text.size(); position += utf8_character_size(Text, position)) + { + ++length; + } + return length; +} + +std::string utf8_fit(std::string_view const Text, std::size_t const Width) +{ + std::size_t length{0}; + std::size_t position{0}; + while (position < Text.size() && length < Width) + { + position += utf8_character_size(Text, position); + ++length; + } + std::string output{Text.substr(0, position)}; + output.append(Width - length, ' '); + return output; +} + // Ra: tymczasowe rozwiązanie kwestii zagranicznych (czeskich) napisów +// NOTE: the entry of 0xB1 (the plus-minus sign of windows-1250, left as it is) is written as its byte. written as the +// character it took two bytes in the builds which keep the texts of the sources in utf-8 (GCC, Clang, MSVC with /utf-8), +// and every entry after it was off by one char const charsetconversiontable[] = "E?,?\"_++?%Sstzz" - " ^^L$A|S^CS<--RZo±,l'uP.,as>L\"lz" + " ^^L$A|S^CS<--RZo\xB1,l'uP.,as>L\"lz" "RAAAALCCCEEEEIIDDNNOOOOxRUUUUYTB" "raaaalccceeeeiiddnnoooo-ruuuuyt?"; diff --git a/utilities/utilities.h b/utilities/utilities.h index aa457b3d3..588aff742 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/parser.h" +#include + /*rozne takie duperele do operacji na stringach w paszczalu, pewnie w delfi sa lepsze*/ /*konwersja zmiennych na stringi, funkcje matematyczne, logiczne, lancuchowe, I/O etc*/ @@ -25,7 +27,16 @@ template constexpr T sq(T v) return v * v; } -// returns the per-user config path for `filename` (platform-specific dir), +// a base folder of the XDG base directory spec, of the values of its variable (XDG_CONFIG_HOME, XDG_CACHE_HOME) and +// of HOME, either of them null when not set: the variable when it holds an absolute path, else `Fallback` (.config, +// .cache) in the home folder, else an empty path. what Linux uses; apart from the environment, so tests can call it +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback); +// the folder of the settings on Linux, of the values of XDG_CONFIG_HOME and HOME: MaSzyna in the base folder of the +// settings, but ~/.config/MaSzyna, where the releases which didn't read XDG_CONFIG_HOME kept them, while it exists and +// the new one doesn't, so the settings already there keep working. an empty path as xdg_base_directory +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home); +// returns the per-user config path for `filename` (platform-specific dir: %APPDATA%\MaSzyna, +// ~/Library/Application Support/MaSzyna, $XDG_CONFIG_HOME/MaSzyna or ~/.config/MaSzyna), // or an empty path if the home/appdata env var is unavailable std::filesystem::path user_config_path(const std::string &filename); // the per-user path for `filename` among the files kept only to be fetched again faster, which don't roam with the profile: @@ -73,17 +84,23 @@ int RandomInt(int min, int max); // the engine Random() draws from in the calling thread, in place of Global.random_engine, or none for that one again. the threads // of worker_pool have engines of their own: the one of the simulation can't be shared between threads void set_thread_random_engine(std::mt19937 *Engine); // NOSONAR: randomness of the simulation, not of anything security-relevant +// the engine set for the calling thread by set_thread_random_engine(), or none +std::mt19937 *thread_random_engine(); // NOSONAR: randomness of the simulation, not of anything security-relevant /// @author lxvia /// @brief Returns a random seed from the system's entropy source, if available. Otherwise, falls back to a clock-based seed. /// @return A random seed as 64 bit unsigned integer std::uint64_t true_random_seed(); -// The seed a word stands for. A number is taken as it is written; anything else is +// The seed a word stands for. A number is taken as it is written - the whole text, so +// "4242abc" is a word, not 4242 - and 0 is a seed like any other; anything else is // hashed the way Java's String.hashCode does it, so the same word gives the same // world on every platform and every build - which is the whole point of telling // somebody a seed. std::uint32_t seed_of(std::string const &Text); +// the seed a text of the settings (randomseed) or of the command line (-seed) gives: none for +// an empty text, else seed_of() it, 0 included +std::optional seed_given(std::string const &Text); std::string generate_uuid_v4(); double LocalRandom(double a, double b); @@ -183,6 +200,17 @@ std::string utf8_to_win1250(std::string const &Text); bool utf8_to_utf32(std::string const &Text, std::u32string &Output); // decodes windows-1250 (ansi) encoded text into unicode code points void win1250_to_utf32(std::string const &Text, std::u32string &Output); +// a text of the data files as utf-8, for the user interface. the files are in windows-1250, some of the newer ones in +// utf-8: a text which is valid utf-8 stays as it is, any other is read as windows-1250, every letter of the code page +// (not only the polish ones win1250_to_utf8() knows) turned into utf-8 +std::string data_text_to_utf8(std::string const &Text); +// the same for a name (of a station, a train, an event, a node, a file) shown in a line of the user interface: what +// Bezogonkow() is for, but the letters keep their marks. control characters become spaces and, when asked, underscores too +std::string data_name_to_utf8(std::string const &Name, bool Underscorestospaces = false); +// number of characters (code points) of a text in utf-8; a byte which isn't a part of a valid sequence counts as one +std::size_t utf8_length(std::string_view Text); +// a text in utf-8 cut or filled with spaces to given number of characters, for the columns of the fixed width +std::string utf8_fit(std::string_view Text, std::size_t Width); inline std::string extract_value(std::string const &Key, std::string const &Input) { diff --git a/utilities/uuid.hpp b/utilities/uuid.hpp index f68ad49bb..462169874 100644 --- a/utilities/uuid.hpp +++ b/utilities/uuid.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "utilities/utilities.h" #include "utilities/Globals.h" @@ -14,10 +15,17 @@ public: std::array bytes; + // the uuid of each scene node, which only the editor goes by. drawn from an engine of its own: from the one of the + // simulation (Global.random_engine) each node made took two of the numbers the run's seed gives, and a node added to + // the scenery, or made by the program before it (a memory cell of the scripting interface), changed every random + // number drawn after it, the physics of the vehicles among them static UID random() { + static std::mt19937 engine(static_cast(true_random_seed())); // NOSONAR: an identifier, not anything security-relevant + static std::mutex mutex; UID u; - uint64_t a = Global.random_engine(); - uint64_t b = Global.random_engine(); + std::scoped_lock lock(mutex); + uint64_t a = engine(); + uint64_t b = engine(); for (int i = 0; i < 8; ++i) u.bytes[i] = uint8_t(a >> (i * 8) & 0xFF); for (int i = 0; i < 8; ++i) u.bytes[8 + i] = uint8_t(b >> (i * 8) & 0xFF); diff --git a/utilities/wholefile.cpp b/utilities/wholefile.cpp new file mode 100644 index 000000000..573f0f1ab --- /dev/null +++ b/utilities/wholefile.cpp @@ -0,0 +1,43 @@ +/* +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 "utilities/wholefile.h" + +#include + +whole_file read_whole_file(std::string const &Path) +{ + whole_file result; + + auto *const file{std::fopen(Path.c_str(), "rb")}; + if (file == nullptr) + { + return result; + } + // without a buffer of its own the stream hands the read to the system in one piece, straight into the memory + std::setvbuf(file, nullptr, _IONBF, 0); +#ifdef _WIN32 + _fseeki64(file, 0, SEEK_END); + auto const length{_ftelli64(file)}; + _fseeki64(file, 0, SEEK_SET); +#else + fseeko(file, 0, SEEK_END); + auto const length{ftello(file)}; + fseeko(file, 0, SEEK_SET); +#endif + if (length > 0) + { + result.data.reset(new char[static_cast(length)]); + result.size = std::fread(result.data.get(), 1, static_cast(length), file); + } + std::fclose(file); + + return result; +} diff --git a/utilities/wholefile.h b/utilities/wholefile.h new file mode 100644 index 000000000..992ea8086 --- /dev/null +++ b/utilities/wholefile.h @@ -0,0 +1,26 @@ +/* +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 + +#include +#include +#include + +// the content of a whole file, kept in memory +struct whole_file +{ + std::unique_ptr data; + std::size_t size{0}; +}; + +// reads the whole file with one large read. a file stream reads a file which isn't in the system's cache yet from a +// hard disk in small pieces, slower (2026-11, .e3d files of a scenario: about 24 MB/s against 38 MB/s for one read). +// a file which can't be opened or is empty gives no data; a read which stops early gives what was read +whole_file read_whole_file(std::string const &Path); diff --git a/vehicle/Camera.cpp b/vehicle/Camera.cpp index fe1a85c9a..e7346b5bb 100644 --- a/vehicle/Camera.cpp +++ b/vehicle/Camera.cpp @@ -17,7 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "vehicle/Driver.h" #include "vehicle/DynObj.h" -#include "MOVER.h" +#include "physics/vehicle.h" //--------------------------------------------------------------------------- @@ -197,7 +197,7 @@ void TCamera::Update() auto movement { Velocity * -2.0 }; movement.y = -movement.y; if( auto const *owner { ( m_owner->Mechanik ? m_owner->Mechanik : m_owner->ctOwner ) }; owner && owner->Occupied() - && owner->Occupied()->CabOccupied < 0 ) { + && owner->Occupied()->CabOccupied() < 0 ) { movement *= -1.f; movement.y = -movement.y; } diff --git a/vehicle/Camera.h b/vehicle/Camera.h index 5e2f72810..a53aac497 100644 --- a/vehicle/Camera.h +++ b/vehicle/Camera.h @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #pragma once #include "input/command.h" -#include "vehicle/DynObj.h" +#include "utilities/Classes.h" //--------------------------------------------------------------------------- diff --git a/vehicle/Driver.cpp b/vehicle/Driver.cpp deleted file mode 100644 index de012f039..000000000 --- a/vehicle/Driver.cpp +++ /dev/null @@ -1,9407 +0,0 @@ -/* -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/. -*/ -/* - MaSzyna EU07 locomotive simulator - Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others - -*/ - -#include "stdafx.h" -#include "vehicle/Driver.h" - -#include "utilities/Globals.h" -#include "utilities/translation.h" -#include "utilities/Logs.h" -#include "utilities/physicslog.h" -#include "vehicle/Train.h" -#include "vehicle/brakesetting.h" -#include "vehicle/brakingcurve.h" -#include "vehicle/handover.h" -#include "world/mtable.h" -#include "vehicle/DynObj.h" -#include "world/Event.h" -#include "world/MemCell.h" -#include "world/RoadOrder.h" -#include "simulation/simulation.h" -#include "simulation/blackboxrecorder.h" -#include "simulation/simulationtime.h" -#include "simulation/simulationtest.h" -#include "world/Track.h" -#include "world/station.h" -#include "input/keyboardinput.h" - -#include -#include -#include - -#define LOGVELOCITY 0 -#define LOGORDERS 1 -#define LOGSTOPS 1 -#define LOGBACKSCAN 0 -#define LOGPRESS 0 - -// finds point of specified track nearest to specified event. returns: distance to that point from the specified end of the track -// TODO: move this to file with all generic routines, too easy to forget it's here and it may come useful -double -ProjectEventOnTrack( basic_event const *Event, TTrack const *Track, double const Direction ) { - - auto const segment = Track->CurrentSegment(); - auto const nearestpoint = segment->find_nearest_point( Event->input_location() ); - return Direction > 0 ? nearestpoint * segment->GetLength() : // measure from point1 - (1.0 - nearestpoint) * segment->GetLength(); // measure from point2 -}; - -double GetDistanceToEvent(TTrack const *track, basic_event const *event, double scan_dir, double start_dist, int iter = 0, bool back = false) -{ - if( track == nullptr ) { return start_dist; } - - auto const segment = track->CurrentSegment(); - auto const pos_event = event->input_location(); - double len1, len2; - double sd = scan_dir; - double seg_len = scan_dir > 0 ? 0.0 : 1.0; - double const dzielnik = 1.0 / segment->GetLength();// rozdzielczosc mniej wiecej 1m - int krok = 0; // krok obliczeniowy do sprawdzania czy odwracamy - len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); - do - { - len1 = len2; - seg_len += scan_dir > 0 ? dzielnik : -dzielnik; - len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); - ++krok; - } while (len1 > len2 && seg_len >= dzielnik && seg_len <= 1.0 - dzielnik); - //trzeba sprawdzić czy seg_len nie osiągnął skrajnych wartości, bo wtedy - // trzeba sprawdzić tor obok - if (1 == krok) - sd = -sd; // jeśli tylko jeden krok tzn, że event przy poprzednim sprawdzaym torze - if ((1 == krok || seg_len <= dzielnik || seg_len > 1.0 - dzielnik) && iter < 3) - { // przejście na inny tor - track = track->Connected(int(sd), sd); - start_dist += 1 == krok ? 0 : back ? -segment->GetLength() : segment->GetLength(); - if( track != nullptr - && track->eType == tt_Cross ) { - // NOTE: tracing through crossroads currently poses risk of tracing through wrong segment - // as it's possible to be performerd before setting a route through the crossroads - // as a stop-gap measure we don't trace through crossroads which should be reasonable in most cases - // TODO: establish route before the scan, or a way for the function to know which route to pick - return start_dist; - } - else { - return GetDistanceToEvent( track, event, sd, start_dist, ++iter, 1 == krok ? true : false ); - } - } - else - { // obliczenie mojego toru - seg_len -= scan_dir > 0 ? dzielnik : -dzielnik; //trzeba wrócić do pozycji len1 - seg_len = scan_dir < 0 ? 1 - seg_len : seg_len; - seg_len = back ? 1 - seg_len : seg_len; // odwracamy jeśli idzie do tyłu - start_dist -= back ? segment->GetLength() : 0; - return start_dist + segment->GetLength() * seg_len; - } -}; - -/* - -Moduł obsługujący sterowanie pojazdami (składami pociągów, samochodami). -Ma działać zarówno jako AI oraz przy prowadzeniu przez człowieka. W tym -drugim przypadku jedynie informuje za pomocą napisów o tym, co by zrobił -w tym pierwszym. Obejmuje zarówno maszynistę jak i kierownika pociągu -(dawanie sygnału do odjazdu). - -Przeniesiona tutaj została zawartość ai_driver.pas przerobiona na C++. -Również niektóre funkcje dotyczące składów z DynObj.cpp. - -Teoria jest wtedy kiedy wszystko wiemy, ale nic nie działa. -Praktyka jest wtedy, kiedy wszystko działa, ale nikt nie wie dlaczego. -Tutaj łączymy teorię z praktyką - tu nic nie działa i nikt nie wie dlaczego… - -*/ - -// zrobione: -// 0. pobieranie komend z dwoma parametrami -// 1. przyspieszanie do zadanej predkosci, ew. hamowanie jesli przekroczona -// 2. hamowanie na zadanym odcinku do zadanej predkosci (ze stabilizacja przyspieszenia) -// 3. wychodzenie z sytuacji awaryjnych: bezpiecznik nadmiarowy, poslizg -// 4. przygotowanie pojazdu do drogi, zmiana kierunku ruchu -// 5. dwa sposoby jazdy - manewrowy i pociagowy -// 6. dwa zestawy psychiki: spokojny i agresywny -// 7. przejscie na zestaw spokojny jesli wystepuje duzo poslizgow lub wybic nadmiarowego. -// 8. lagodne ruszanie (przedluzony czas reakcji na 2 pierwszych nastawnikach) -// 9. unikanie jazdy na oporach rozruchowych -// 10. logowanie fizyki //Ra: nie przeniesione do C++ -// 11. kasowanie czuwaka/SHP -// 12. procedury wspomagajace "patrzenie" na odlegle semafory -// 13. ulepszone procedury sterowania -// 14. zglaszanie problemow z dlugim staniem na sygnale S1 -// 15. sterowanie EN57 -// 16. zmiana kierunku //Ra: z przesiadką po ukrotnieniu -// 17. otwieranie/zamykanie drzwi -// 18. Ra: odczepianie z zahamowaniem i podczepianie -// 19. dla Humandriver: tasma szybkosciomierza - zapis do pliku! -// 20. wybór pozycji zaworu maszynisty w oparciu o zadane opoznienie hamowania - - -// do zrobienia: -// 1. kierownik pociagu -// 2. madrzejsze unikanie grzania oporow rozruchowych i silnika -// 3. unikanie szarpniec, zerwania pociagu itp -// 4. obsluga innych awarii -// 5. raportowanie problemow, usterek nie do rozwiazania -// 7. samouczacy sie algorytm hamowania - -// stałe -const double EasyReactionTime = 0.5; //[s] przebłyski świadomości dla zwykłej jazdy -const double HardReactionTime = 0.2; -const double EasyAcceleration = 0.85; //[m/ss] -const double HardAcceleration = 9.81; -const double PassengetTrainAcceleration = 0.40; -const double HeavyPassengetTrainAcceleration = 0.20; -const double CargoTrainAcceleration = 0.25; -const double HeavyCargoTrainAcceleration = 0.10; -const double PrepareTime = 2.0; //[s] przebłyski świadomości przy odpalaniu -const double FSOverchargePipePress = 5.2; -const double FSOverchargeTime = 2.0; -const double FSOverchargeCRP = 0.05; -const double FSMaxTime = 10.0; -const double DepartBlockedFSDelay = 10.0; -bool WriteLogFlag = false; -bool WriteTrainLogFlag = false; -double const deltalog = 0.05; // przyrost czasu - -std::string StopReasonTable[] = { - // przyczyny zatrzymania ruchu AI - "", // stopNone, //nie ma powodu - powinien jechać - "Off", // stopSleep, //nie został odpalony, to nie pojedzie - "Semaphore", // stopSem, //semafor zamknięty - "Time", // stopTime, //czekanie na godzinę odjazdu - "End of track", // stopEnd, //brak dalszej części toru - "Change direction", // stopDir, //trzeba stanąć, by zmienić kierunek jazdy - "Joining", // stopJoin, //zatrzymanie przy (p)odczepianiu - "Block", // stopBlock, //przeszkoda na drodze ruchu - "A command", // stopComm, //otrzymano taką komendę (niewiadomego pochodzenia) - "Out of station", // stopOut, //komenda wyjazdu poza stację (raczej nie powinna zatrzymywać!) - "Radiostop", // stopRadio, //komunikat przekazany radiem (Radiostop) - "External", // stopExt, //przesłany z zewnątrz - "Error", // stopError //z powodu błędu w obliczeniu drogi hamowania -}; - -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- -//--------------------------------------------------------------------------- - -TSpeedPos::TSpeedPos(TTrack *track, double dist, int flag) -{ - Set(track, dist, flag); -}; - -TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, TOrders order) -{ - Set(event, dist, length, order); -}; - -void TSpeedPos::Clear() -{ - iFlags = 0; // brak flag to brak reakcji - fVelNext = -1.0; // prędkość bez ograniczeń - fSectionVelocityDist = 0.0; //brak długości - fPointDist = 0.0; - fDist = 0.0; - bSeenAhead = false; - vPos = glm::dvec3(0, 0, 0); - trTrack = nullptr; // brak wskaźnika -}; - -void TSpeedPos::CommandCheck() -{ // sprawdzenie typu komendy w evencie i określenie prędkości - TCommandType command = evEvent->input_command(); - double value1 = evEvent->input_value(1); - double value2 = evEvent->input_value(2); - // the point of a PointVelocity limit is taken anew from the current command - iFlags &= ~spPointVelocity; - fPointDist = 0.0; - switch (command) - { - case TCommandType::cm_ShuntVelocity: - // prędkość manewrową zapisać, najwyżej AI zignoruje przy analizie tabelki - fVelNext = value1; // powinno być value2, bo druga określa "za"? - iFlags |= spShuntSemaphor; - break; - case TCommandType::cm_SetVelocity: - // w semaforze typu "m" jest ShuntVelocity dla Ms2 i SetVelocity dla S1 - // SetVelocity * 0 -> można jechać, ale stanąć przed - // SetVelocity 0 20 -> stanąć przed, potem można jechać 20 (SBL) - // SetVelocity -1 100 -> można jechać, przy następnym ograniczenie (SBL) - // SetVelocity 40 -1 -> PutValues: jechać 40 aż do minięcia (koniec ograniczenia( - fVelNext = value1; - iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL); - iFlags |= spSemaphor;// nie manewrowa, nie przystanek, nie zatrzymać na SBL, ale semafor - if (value1 == 0.0 && value2 != 0.0) // jeśli pierwsza zerowa - // a druga nie - { // S1 na SBL, można przejechać po zatrzymaniu (tu nie mamy prędkości ani odległości) - fVelNext = value2; // normalnie będzie zezwolenie na jazdę, aby się usunął z tabelki - iFlags |= spStopOnSBL; // flaga, że ma zatrzymać; na pewno nie zezwoli na manewry - } - break; - case TCommandType::cm_SectionVelocity: - // odcinek z ograniczeniem prędkości - fVelNext = value1; - fSectionVelocityDist = value2; - iFlags |= spSectionVel; - break; - case TCommandType::cm_RoadVelocity: - // prędkość drogowa (od tej pory będzie jako domyślna najwyższa) - fVelNext = value1; - iFlags |= spRoadVel; - break; - case TCommandType::cm_PassengerStopPoint: - // nie ma dostępu do rozkładu - // przystanek, najwyżej AI zignoruje przy analizie tabelki - fVelNext = 0.0; - iFlags |= spPassengerStopPoint; // niestety nie da się w tym miejscu współpracować z rozkładem -/* - // NOTE: not used for now as it might be unnecessary - // special case, potentially override any set speed limits if requested - // NOTE: we test it here because for the time being it's only used for passenger stops - if( TestFlag( iFlags, spDontApplySpeedLimit ) ) { - fVelNext = -1; - } -*/ - break; - case TCommandType::cm_SetProximityVelocity: - // musi zostać gdyż inaczej nie działają manewry - fVelNext = -1; - iFlags |= spProximityVelocity; - // fSectionVelocityDist = value2; - break; - case TCommandType::cm_PointVelocity: - // PointVelocity v d: the head has to be at v (-1: no limit) at the point d metres beyond the cell, - // the limit ends when the head passes that point. the cell is read until the head passes the cell, - // what it says then holds for the point (the warning disc of a level crossing, Osp1/Osp2) - fVelNext = value1; - fPointDist = std::max( value2, 0.0 ); - iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL | spSemaphor); // not a signal, even if the cell was one before - iFlags |= spPointVelocity; - break; - case TCommandType::cm_OutsideStation: - // w trybie manewrowym: skanować od niej wstecz i stanąć po wyjechaniu za sygnalizator i - // zmienić kierunek - // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) - fVelNext = -1; - iFlags |= spOutsideStation; // W5 - break; - case TCommandType::cm_EmergencyBrake: - fVelNext = -1; - break; - case TCommandType::cm_SecuritySystemMagnet: - fVelNext = -1; - break; - case TCommandType::cm_SignalAreaEnd: - // imposes no speed of its own, it only ends the reduced speed of the signal passed last - fVelNext = -1; - iFlags |= spSignalAreaEnd; - break; - default: - // inna komenda w evencie skanowanym powoduje zatrzymanie i wysłanie tej komendy - // nie manewrowa, nie przystanek, nie zatrzymać na SBL - // jak nieznana komenda w komórce sygnałowej, to zatrzymujemy - fVelNext = 0.0; -/* - fVelNext = ( - evEvent->is_command() ? 0.0 : // ask for a stop if we have a command for the vehicle - ( iFlags & ( spSemaphor | spShuntSemaphor )) != 0 ? fVelNext : // don't change semafor velocity - -1.0 ); // otherwise don't be a bother -*/ - // TODO: check whether clearing spShuntSemaphor flag doesn't cause problems - // potentially it can invalidate shunt semaphor used to transmit timetable or similar command - iFlags &= ~(spShuntSemaphor | spPassengerStopPoint | spStopOnSBL); - } -}; - -bool TSpeedPos::Update() -{ - if( fDist < 0.0 ) { - // trzeba zazanaczyć, że minięty - iFlags |= spElapsed; - } - else { - bSeenAhead = true; - } - if (iFlags & spTrack) { - // road/track - if (trTrack) { - // może być NULL, jeśli koniec toru (???) - fVelNext = trTrack->VelocityGet(); // aktualizacja prędkości (może być zmieniana eventem) - - if( trTrack->iCategoryFlag & 1 ) { - // railways - if( iFlags & spSwitch && (trTrack->GetSwitchState() & 1) != 0 != ((iFlags & spSwitchStatus) != 0) ) { - // jeśli odcinek zmienny - // czy stan się zmienił? - // Ra: zakładam, że są tylko 2 możliwe stany - iFlags ^= spSwitchStatus; - if ((iFlags & spElapsed) == 0) - { - // jeszcze trzeba skanowanie wykonać od tego toru - // problem jest chyba, jeśli zwrotnica się przełoży zaraz po zjechaniu z niej - // na Mydelniczce potrafi skanować na wprost mimo pojechania na bok - return true; - } - } - } - else { - // roads and others - if( iFlags & 0xF0000000 && (iFlags & 0xF0000000) > 0x10000000 ) { - // jeśli skrzyżowanie, ograniczyć prędkość przy skręcaniu - // ±1 to jazda na wprost, ±2 nieby też, ale z przecięciem głównej drogi - chyba że jest równorzędne... - // TODO: uzależnić prędkość od promienia; - // albo niech będzie ograniczona w skrzyżowaniu (velocity z ujemną wartością) - fVelNext = 30.0; - } - } - } - } - else if (iFlags & spEvent && ((iFlags & spElapsed) == 0 || fVelNext == 0.0)) { - // jeśli event - // ignore already passed signals, but keep an eye on overrun stops - // (a PointVelocity cell is latched when the head passes it, except at 0, which has to be released by the cell) - // odczyt komórki pamięci najlepiej by było zrobić jako notyfikację, - // czyli zmiana komórki wywoła jakąś podaną funkcję - CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości - } - return false; -}; - -std::string TSpeedPos::GetName() const -{ - if( iFlags & spTrack ) // jeśli tor - return trTrack->name(); - else if( iFlags & spEvent ) // jeśli event - return - evEvent->m_name - + " [" + std::to_string( static_cast( evEvent->input_value( 1 ) ) ) - + ", " + std::to_string( static_cast( evEvent->input_value( 2 ) ) ) - + "]"; - else - return ""; -} - -std::string TSpeedPos::TableText() const -{ // pozycja tabelki pr?dko?ci - if (iFlags & spEnabled) - { // o ile pozycja istotna - return to_hex_str(iFlags, 8) + " " + to_string(fDist, 1, 6) + - " " + (fVelNext == -1.0 ? " -" : to_string(static_cast(fVelNext), 0, 3)) + " " + GetName(); - } - return "Empty"; -} - -bool TSpeedPos::IsProperSemaphor(TOrders order) -{ // sprawdzenie czy semafor jest zgodny z trybem jazdy - if (order < Obey_train) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt - { - if (iFlags & (spSemaphor | spShuntSemaphor)) - return true; - else if (iFlags & spOutsideStation) - return true; - } - else if (order & Obey_train && iFlags & spSemaphor) - { - return true; - } - return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej -} - -// how far behind the head an event found in the scan may lie and still count as one the head had ahead [m] -constexpr double SeenAheadTolerance { 5.0 }; - -bool TSpeedPos::Set(basic_event *event, double dist, double length, TOrders order) -{ // zapamiętanie zdarzenia - fDist = dist; - // an event already behind the head when found (under a train set across a signal) wasn't passed by it. the - // distance is found in steps of a metre from the position of the memory cell, so a signal just ahead of the head - // may come out a few metres behind it: those still count as seen ahead. the price is that a train set less than - // the tolerance past a signal at stop is still reported to pass it; a train standing that close to a signal can't - // be told from one stopped just short of it, which really passes the signal if it goes on - bSeenAhead = ( dist >= -SeenAheadTolerance ); - iFlags = spEvent; - evEvent = event; - vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) - // ignore events located behind the consist, but with exception of stop points which may be needed to update freshly received timetable - if( dist + length < 0 - && event->input_command() != TCommandType::cm_PassengerStopPoint ) { - return false; - } - iFlags |= spEnabled; - CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości - // zależnie od trybu sprawdzenie czy jest tutaj gdzieś semafor lub tarcza manewrowa - // jeśli wskazuje stop wtedy wystawiamy true jako koniec sprawdzania - // WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " iFlags=" + AnsiString(iFlags) + " order="+AnsiString(order)); - if (order < Obey_train) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt - { - if (iFlags & (spSemaphor | spShuntSemaphor) && fVelNext == 0.0) - return true; - else if (iFlags & spOutsideStation) - return true; - } - else if (order & Obey_train && iFlags & spSemaphor && fVelNext == 0.0) - { - return true; - } - return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej -}; - -void TSpeedPos::Set(TTrack *track, double dist, int flag) -{ // zapamiętanie zmiany prędkości w torze - fDist = dist; // odległość do początku toru - trTrack = track; // TODO: (t) może być NULL i nie odczytamy końca poprzedniego :/ - if (trTrack) - { - iFlags = flag | (trTrack->eType == tt_Normal ? spTrack : spTrack | spSwitch ); // zapamiętanie kierunku wraz z typem - if (iFlags & spSwitch && trTrack->GetSwitchState() & 1) - iFlags |= spSwitchStatus; - fVelNext = trTrack->VelocityGet(); - if (trTrack->iDamageFlag & 128) - fVelNext = 0.0; // jeśli uszkodzony, to też stój - if (iFlags & spEnd) - fVelNext = trTrack->iCategoryFlag & 1 ? - 0.0 : - 20.0; // jeśli koniec, to pociąg stój, a samochód zwolnij - vPos = - iFlags & spReverse ? - trTrack->CurrentSegment()->FastGetPoint_1() : - trTrack->CurrentSegment()->FastGetPoint_0(); - } -}; - -//--------------------------------------------------------------------------- - -void TController::TableClear() -{ // wyczyszczenie tablicy - sSpeedTable.clear(); - iLast = -1; - iTableDirection = 0; // nieznany - tLast = nullptr; - fLastVel = -1.0; - SemNextIndex = npos; - SemNextStopIndex = npos; - eSignSkip = nullptr; // nic nie pomijamy -}; - -std::vector TController::CheckTrackEvent( TTrack *Track, double const fDirection ) const -{ // sprawdzanie eventów na podanym torze do podstawowego skanowania - std::vector events; - auto const &eventsequence { ( fDirection > 0 ? Track->m_events2 : Track->m_events1 ) }; - for( auto const &event : eventsequence ) { - if( event.second != nullptr - && event.second->m_passive ) { - events.emplace_back( event.second ); - } - } - return events; -} - -bool TController::TableAddNew() -{ // zwiększenie użytej tabelki o jeden rekord - sSpeedTable.emplace_back(); // add a new slot - iLast = sSpeedTable.size() - 1; - return true; // false gdy się nałoży -}; - -bool TController::TableNotFound(basic_event const *Event, double const Distance ) const -{ // sprawdzenie, czy nie został już dodany do tabelki (np. podwójne W4 robi problemy) - auto lookup = - std::find_if( - sSpeedTable.begin(), - sSpeedTable.end(), - [Event]( TSpeedPos const &speedpoint ){ - return true == TestFlag(speedpoint.iFlags, spEnabled | spEvent) && speedpoint.evEvent == Event; } ); - - if (Global.iWriteLogEnabled & 8 - && lookup != sSpeedTable.end() ) { - WriteLog( "Speed table for " + OwnerName() + " already contains event " + lookup->evEvent->m_name ); - } - - // ignore duplicates which seem to be reasonably apart from each other, on account of looping tracks - // NOTE: since supplied distance is only rough approximation of distance to the event, we're using large safety margin - return lookup == sSpeedTable.end() || Distance - lookup->fDist > 100.0; -}; - -void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) -{ // skanowanie trajektorii na odległość (fDistance) od (pVehicle) w kierunku przodu składu i - // uzupełnianie tabelki - // WriteLog("Starting TableTraceRoute"); - - TTrack *pTrack{ nullptr }; // zaczynamy od ostatniego analizowanego toru - double fTrackLength{ 0.0 }; // długość aktualnego toru (krótsza dla pierwszego) - double fCurrentDistance{ 0.0 }; // aktualna przeskanowana długość - double fLastDir{ 0.0 }; - - if (iTableDirection != iDirection ) { - // jeśli zmiana kierunku, zaczynamy od toru ze wskazanym pojazdem - TableClear(); -/* - // aktualna prędkość // changed to -1 to recognize speed limit, if any - fLastVel = -1.0; - sSpeedTable.clear(); - iLast = -1; - tLast = nullptr; //żaden nie sprawdzony - SemNextIndex = npos; - SemNextStopIndex = npos; -*/ - if( VelSignalLast == 0.0 ) { - // don't allow potential red light overrun keep us from reversing - VelSignalLast = -1.0; - } - iTableDirection = iDirection; // ustalenie w jakim kierunku jest wypełniana tabelka względem pojazdu - pTrack = pVehicle->GetTrack(); // odcinek, na którym stoi - fTrackLength = pVehicle->RaTranslationGet(); // pozycja na tym torze (odległość od Point1) - fLastDir = pVehicle->DirectionGet() * pVehicle->RaDirectionGet(); // ustalenie kierunku skanowania na torze - if( fLastDir < 0.0 ) { - // jeśli w kierunku Point2 toru - fTrackLength = pTrack->Length() - fTrackLength; // przeskanowana zostanie odległość do Point2 - } - // account for the fact tracing begins from active axle, not the actual front of the vehicle - // NOTE: position of the couplers is modified by track offset, but the axles ain't, so we need to account for this as well - fTrackLength -= glm::length( - pVehicle->AxlePositionGet() - - pVehicle->RearPosition() - + pVehicle->VectorLeft() * pVehicle->MoverParameters->OffsetTrackH ); - // aktualna odległość ma być ujemna gdyż jesteśmy na końcu składu - fCurrentDistance = -fLength - fTrackLength; - fTrackLength = pTrack->Length(); //skasowanie zmian w zmiennej żeby poprawnie liczyło w dalszych krokach - MoveDistanceReset(); // AI startuje 1s po zaczęciu jazdy i mógł już coś przejechać - } - else { - if( iTableDirection == 0 ) { return; } - // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table - if( SemNextIndex != npos - && SemNextIndex >= sSpeedTable.size() ) { - SemNextIndex = npos; - } - if( SemNextStopIndex != npos - && SemNextStopIndex >= sSpeedTable.size() ) { - SemNextStopIndex = npos; - } - // kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor) - if( SemNextStopIndex != npos - && sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) { - // znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor - // jeśli jest następny semafor to sprawdzamy czy to on nadał zero - if( OrderCurrentGet() & Obey_train - && sSpeedTable[SemNextStopIndex].iFlags & spSemaphor ) { - return; - } - else { - if( OrderCurrentGet() < Obey_train - && sSpeedTable[SemNextStopIndex].iFlags & (spSemaphor | spShuntSemaphor | spOutsideStation) ) { - return; - } - } - } - - auto const &lastspeedpoint = sSpeedTable[ iLast ]; - pTrack = lastspeedpoint.trTrack; - assert( pTrack != nullptr ); - // flaga ustawiona, gdy Point2 toru jest blizej - fLastDir = (lastspeedpoint.iFlags & spReverse) != 0 ? -1.0 : 1.0; - fCurrentDistance = lastspeedpoint.fDist; // aktualna odleglosc do jego Point1 - fTrackLength = pTrack->Length(); - } - - if( iTableDirection == 0 ) { - // don't bother - return; - } - - while (fCurrentDistance < fDistance) - { - if (pTrack != tLast) // ostatni zapisany w tabelce nie był jeszcze sprawdzony - { // jeśli tor nie był jeszcze sprawdzany - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table for " + OwnerName() + " tracing through track " + pTrack->name() ); - } - - auto const events { CheckTrackEvent( pTrack, fLastDir ) }; - for( auto *pEvent : events ) { - if( pEvent != nullptr && TableNotFound(pEvent, fCurrentDistance) ) // jeśli jest semafor na tym torze - { // trzeba sprawdzić tabelkę, bo dodawanie drugi raz tego samego przystanku nie jest korzystne - // jeśli nie ma - TableAddNew(); // zawsze jest true - - if (Global.iWriteLogEnabled & 8) - { - WriteLog("Speed table for " + OwnerName() + " found new event, " + pEvent->m_name); - } - auto &newspeedpoint = sSpeedTable[iLast]; - /* - if( newspeedpoint.Set( - pEvent, - fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ), - OrderCurrentGet() ) ) { - */ - // an order of a road junction or a level crossing lies on the lane it's on. it's measured along that lane: the search - // for the events beside the track goes in steps of about a metre, and misplaces the ones on lanes shorter than a few metres - auto const eventdistance{ - typeid( *pEvent ) == typeid( road_order ) ? - fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ) : - GetDistanceToEvent( pTrack, pEvent, fLastDir, fCurrentDistance ) }; - if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet())) - { - - fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować - SemNextStopIndex = iLast; - if (SemNextIndex == npos) - { - SemNextIndex = iLast; - } - if (Global.iWriteLogEnabled & 8) - { - WriteLog("(stop signal from " + (SemNextStopIndex != npos ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor") + ")"); - } - } - else - { - if (true == newspeedpoint.IsProperSemaphor(OrderCurrentGet()) && SemNextIndex == npos) - { - SemNextIndex = iLast; // sprawdzamy czy pierwszy na drodze - } - if (Global.iWriteLogEnabled & 8) - { - WriteLog("(forward signal for " + (SemNextIndex != npos ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor") + ")"); - } - } - } - } // event dodajemy najpierw, żeby móc sprawdzić, czy tor został dodany po odczytaniu prędkości następnego - - if( pTrack->VelocityGet() == 0.0 // zatrzymanie - || pTrack->iAction // jeśli tor ma własności istotne dla skanowania - || pTrack->VelocityGet() != fLastVel ) // następuje zmiana prędkości - { // odcinek dodajemy do tabelki, gdy jest istotny dla ruchu - TableAddNew(); - sSpeedTable[ iLast ].Set( - pTrack, fCurrentDistance, - fLastDir < 0 ? spEnabled | spReverse : spEnabled ); // dodanie odcinka do tabelki z flagą kierunku wejścia - if (pTrack->eType == tt_Cross) { - // na skrzyżowaniach trzeba wybrać segment, po którym pojedzie pojazd - // dopiero tutaj jest ustalany kierunek segmentu na skrzyżowaniu -/* - // NOTE: manual selection disabled due to multiplayer - int routewanted; - if( false == AIControllFlag ) { - routewanted = ( - input::keys[ GLFW_KEY_LEFT ] != GLFW_RELEASE ? 1 : - input::keys[ GLFW_KEY_RIGHT ] != GLFW_RELEASE ? 2 : - 3 ); - } - else { - routewanted = 1 + std::floor( Random( static_cast( pTrack->RouteCount() ) - 0.001 ) ); - } -*/ - auto const routewanted { pTrack->RouteDraw() }; - sSpeedTable[iLast].iFlags |= - (pTrack->CrossSegment(fLastDir < 0 ? tLast->iPrevDirection : tLast->iNextDirection, - /* - iRouteWanted ) - */ - routewanted) & - 0xf) - << 28; // ostatnie 4 bity pola flag - sSpeedTable[iLast].iFlags &= ~spReverse; // usunięcie flagi kierunku, bo może być błędna - if (sSpeedTable[iLast].iFlags < 0) { - sSpeedTable[iLast].iFlags |= spReverse; // ustawienie flagi kierunku na podstawie wybranego segmentu - } - if (int(fLastDir) * sSpeedTable[iLast].iFlags < 0) { - fLastDir = -fLastDir; - } -/* - if (AIControllFlag) { - // dla AI na razie losujemy kierunek na kolejnym skrzyżowaniu - iRouteWanted = 1 + Random(3); - } -*/ - } - } - else if ( (pTrack->fRadius != 0.0 // odległość na łuku lepiej aproksymować cięciwami - || tLast != nullptr && tLast->fRadius != 0.0) && - TableAddNew()) // koniec łuku też jest istotny - { // albo dla liczenia odległości przy pomocy cięciw - te usuwać po przejechaniu - // dodanie odcinka do tabelki - sSpeedTable[iLast].Set(pTrack, fCurrentDistance, fLastDir < 0 ? spEnabled | spCurve | spReverse : spEnabled | spCurve); - } - } - - fCurrentDistance += fTrackLength; // doliczenie kolejnego odcinka do przeskanowanej długości - tLast = pTrack; // odhaczenie, że sprawdzony - fLastVel = pTrack->VelocityGet(); // prędkość na poprzednio sprawdzonym odcinku - pTrack = pTrack->Connected( - pTrack->eType == tt_Cross ? sSpeedTable[iLast].iFlags >> 28 : static_cast(fLastDir), - fLastDir); // może być NULL - - if (pTrack != nullptr ) - { // jeśli kolejny istnieje - if( tLast != nullptr && tLast->VelocityGet() > 0 && (tLast->VelocityGet() < pTrack->VelocityGet() || pTrack->VelocityGet() < 0) ) { - - if (iLast != -1 && sSpeedTable[iLast].trTrack == tLast) - { - // if the track is already in the table we only need to mark it as relevant - sSpeedTable[iLast].iFlags |= spEnabled; - } - else - { - // otherwise add it - TableAddNew(); - sSpeedTable[iLast].Set(tLast, - fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track - (fLastDir > 0 ? pTrack->iPrevDirection : pTrack->iNextDirection) ? spEnabled : spEnabled | spReverse); - } - } - // zwiększenie skanowanej odległości tylko jeśli istnieje dalszy tor - fTrackLength = pTrack->Length(); - } - else - { // definitywny koniec skanowania, chyba że dalej puszczamy samochód po gruncie... - if( iLast == -1 - || ( false == TestFlag(sSpeedTable[iLast].iFlags, spEnabled | spEnd) - && sSpeedTable[iLast].trTrack != tLast ) ) { - // only if we haven't already marked end of the track and if the new track doesn't duplicate last one - if( TableAddNew() ) { - // zapisanie ostatniego sprawdzonego toru - sSpeedTable[iLast].Set( - tLast, fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track, - fLastDir < 0 ? spEnabled | spEnd | spReverse : spEnabled | spEnd); - } - } - else if( sSpeedTable[iLast].trTrack == tLast && false == TestFlag(sSpeedTable[iLast].trTrack->iCategoryFlag, 0x100) ) { - // otherwise just mark the last added track as the final one - // TODO: investigate exactly how we can wind up not marking the last existing track as actual end - // don't mark portals, as these aren't exactly track ends, but teleport devices - sSpeedTable[iLast].iFlags |= spEnabled | spEnd; - } - // to ostatnia pozycja, bo NULL nic nie da, a może się podpiąć obrotnica, czy jakieś transportery - return; - } - } - if( TableAddNew() ) { - // zapisanie ostatniego sprawdzonego toru - sSpeedTable[ iLast ].Set( - pTrack, fCurrentDistance, - fLastDir < 0 ? spNone | spReverse : spNone ); - } -}; - -void TController::TableCheck(double fDistance) -{ // przeliczenie odległości w tabelce, ewentualnie doskanowanie (bez analizy prędkości itp.) - if( iTableDirection != iDirection ) { - // jak zmiana kierunku, to skanujemy od końca składu - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); - TableSort(); - } - else if (iTableDirection) - { // trzeba sprawdzić, czy coś się zmieniło - auto const distance = MoveDistanceGet(); - for (auto &sp : sSpeedTable) { - // aktualizacja odległości dla wszystkich pozycji tabeli - sp.UpdateDistance(distance); - } - MoveDistanceReset(); // kasowanie odległości po aktualizacji tabelki - for( int i = 0; i < iLast; ++i ) - { // aktualizacja rekordów z wyjątkiem ostatniego - if (sSpeedTable[i].iFlags & spEnabled) // jeśli pozycja istotna - { - auto const passedbefore { TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) }; - if (sSpeedTable[i].Update()) - { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" ); - } - // usuwamy wszystko za tym torem - while (sSpeedTable.back().trTrack != sSpeedTable[i].trTrack) - { // usuwamy wszystko dopóki nie trafimy na tą zwrotnicę - sSpeedTable.pop_back(); - --iLast; - } - // a semaphor recorded beyond the switch went away with the discarded entries - if( SemNextIndex != npos - && SemNextIndex >= sSpeedTable.size() ) { - SemNextIndex = npos; - } - if( SemNextStopIndex != npos - && SemNextStopIndex >= sSpeedTable.size() ) { - SemNextStopIndex = npos; - } - tLast = sSpeedTable[ i ].trTrack; - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); - TableSort(); - // nie kontynuujemy pętli, trzeba doskanować ciąg dalszy - break; - } - // a switch is a track, the update of a signal never ends the loop above - CheckSignalPassed( sSpeedTable[ i ], passedbefore ); - if (sSpeedTable[i].iFlags & spTrack) // jeśli odcinek - { - if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza - { // degradacja pozycji - sSpeedTable[i].iFlags &= ~spEnabled; // nie liczy się - } - else if( (sSpeedTable[i].iFlags & 0xF0000028) == spElapsed && sSpeedTable[i].fVelNext < 0 ) { - // jest z tyłu (najechany) i nie jest zwrotnicą ani skrzyżowaniem - // a nie ma ograniczenia prędkości - sSpeedTable[i].iFlags = 0; // to nie ma go po co trzymać (odtykacz usunie ze środka) - } - } - else if (sSpeedTable[i].iFlags & spEvent && (sSpeedTable[i].iFlags & spPointVelocity) == 0 && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && mvOccupied->CategoryFlag == 2 && - sSpeedTable[i].fDist < -0.75) // jeśli event - { - // jeśli jest z tyłu - // pociąg staje zawsze, a samochód tylko jeśli nie przejedzie całą długością (może być zaskoczony zmianą) - // WriteLog("TableCheck: Event is behind. Delete from table: " + sSpeedTable[i].evEvent->asName); - sSpeedTable[i].iFlags &= ~spEnabled; // degradacja pozycji dla samochodu; - // semafory usuwane tylko przy sprawdzaniu, bo wysyłają komendy - } - } - } - auto const lastpassedbefore { TestFlag( sSpeedTable[ iLast ].iFlags, spElapsed ) }; - sSpeedTable[iLast].Update(); // aktualizacja ostatniego - // a signal at stop often is the last, the scan doesn't go past it - CheckSignalPassed( sSpeedTable[ iLast ], lastpassedbefore ); - // WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist)); - if( sSpeedTable[ iLast ].fDist < fDistance ) { - TableTraceRoute( fDistance, pVehicles[ end::rear ] ); // doskanowanie dalszego odcinka - TableSort(); - } - // garbage collection - TablePurger(); - } -}; - -namespace { - -// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop -bool is_signal_at_stop( TSpeedPos const &Point ) -{ - return TestFlag( Point.iFlags, spEvent ) - && TestFlag( Point.iFlags, spSemaphor ) - && false == TestFlag( Point.iFlags, spStopOnSBL ) - && std::abs( Point.fVelNext ) <= 0.0 - && Point.evEvent != nullptr; -} - -void clear_signal_area_end( TSpeedPos &Point ) -{ - if( TestFlag( Point.iFlags, spSignalAreaEnd ) ) { - Point.Clear(); - } -} - -// the position is a signal, a main or a shunting one: the aspect comes from its memory cell. putvalues events -// set speed limits by the track, and the flags they get don't make them signals -bool is_signal( TSpeedPos const &Point ) -{ - return TestFlag( Point.iFlags, spEvent ) - && ( TestFlag( Point.iFlags, spSemaphor ) || TestFlag( Point.iFlags, spShuntSemaphor ) ) - && Point.evEvent != nullptr - && typeid( *Point.evEvent ) == typeid( getvalues_event ); -} - -std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsignal, bool const Trainmovement ) -{ - std::uint8_t flags { 0 }; - auto const shunting { TestFlag( Point.iFlags, spShuntSemaphor ) }; - if( shunting ) { - flags |= blackbox::passing_flags::shunt; - } - // the speeds of the aspects are whole km/h, -1 for no limit; a shunting signal binds only the shunting - if( std::abs( Speedatsignal ) < 0.5 && ( false == shunting || false == Trainmovement ) ) { - flags |= ( TestFlag( Point.iFlags, spStopOnSBL ) ? blackbox::passing_flags::automatic_block : blackbox::passing_flags::at_stop ); - } - return flags; -} - -} // namespace - -void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const -{ - if( Passedbefore - || false == TestFlag( Point.iFlags, spElapsed ) - || false == Point.bSeenAhead // found already behind the head: the train stood across it, it didn't pass it - || ( mvOccupied->CategoryFlag & 1 ) == 0 ) { // railway only - return; - } - if( is_signal_at_stop( Point ) ) { - simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name ); - } - if( is_signal( Point ) ) { - // the aspect the train had of it: the table keeps it once the signal is behind, while the memory cell - // may already show stop for the train itself, past the signal on the track it guards. the stop of an - // automatic block signal is kept as the speed allowed after it, with a flag of its own - auto const speedatsignal { TestFlag( Point.iFlags, spStopOnSBL ) ? 0.0 : Point.fVelNext }; - simulation::Blackbox.signal_passed( - pVehicles[ end::front ], *Point.evEvent, - speedatsignal, Point.evEvent->input_value( 2 ), - mvOccupied->Vel, -Point.fDist, - passing_flags_of( Point, speedatsignal, ( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) == 0 ) ); - } -} - -auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head - -// the margins of the final approach of a train [m], closer than the first of which it stops at once and within the -// second of which it makes its final approach: at a passenger stop, or at a signal and anything else it stops at -std::pair -TController::train_proximity_margins( bool const Passengerstop ) const { - - auto minproximity { 0.0 }; - auto maxproximity { 0.0 }; - if( Passengerstop ) { - // a stop point keeps the margins its W4 parameters (head or middle of the consist, - // platform length) were set up against - minproximity = std::clamp( 5 + iVehicles, 10, 15 ) + ( IsCargoTrain ? 10.0 : 0.0 ); - maxproximity = std::clamp( 10 + iVehicles, 15, 40 ); - } - else { - // a train stops 8-15 m short of the signal whatever its length; closer than the lower - // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out - minproximity = 8.0; - // the final approach begins far enough out to slow from the coasting speed down to the window, - // and at the same distance whether the train is moving or standing, so it does not flip - // between creeping closer and holding still when it comes to a stand short of the window - maxproximity = 50.0; - } - if( IsCargoTrain ) { - // start the final approach earlier for cargo trains, their brakes react more slowly - maxproximity += 10.0; - } - if( ( Global.FrictionWeatherFactor < 1.f ) - && ( iVehicles > 1 ) ) { - // take into account weather conditions - minproximity += 5.0; - maxproximity += 5.0; - } - if( mvOccupied->Vel < 0.1 ) { - // jak stanie za daleko, to niech nie dociąga paru metrów - maxproximity = std::max( maxproximity, 50.0 ); - } - return { minproximity, maxproximity }; -} - -TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc) -{ // ustalenie parametrów, zwraca typ komendy, jeśli sygnał podaje prędkość do jazdy - // fVelDes - prędkość zadana - // fDist - dystans w jakim należy rozważyć ruch - // fNext - prędkość na końcu tego dystansu - // fAcc - zalecane przyspieszenie w chwili obecnej - kryterium wyboru dystansu - auto a { 0.0 }; // przyspieszenie - auto v { 0.0 }; // prędkość - auto d { 0.0 }; // droga - auto d_to_next_sem { 10000.0 }; //ustaiwamy na pewno dalej niż widzi AI - auto go { TCommandType::cm_Unknown }; - auto speedlimitiscontinuous { true }; // stays true if potential active speed limit is unbroken to the last (relevant) point in scan table - eSignNext = nullptr; - IsAtPassengerStop = false; - bStopTargetIsPassengerStop = false; - IsScheduledPassengerStopVisible = false; - mvOccupied->SecuritySystem.set_cabsignal_lock(false); - // te flagi są ustawiane tutaj, w razie potrzeby - iDrivigFlags &= ~(moveTrackEnd | moveSwitchFound | moveSignalFound | /*moveSpeedLimitFound*/ moveStopPointFound ); - SignalAreaEndDist = -1.0; - update_point_limits(); - - for( std::size_t idx = 0; idx < sSpeedTable.size(); ++idx ) { - // o ile dana pozycja tabelki jest istotna - if( ( sSpeedTable[ idx ].iFlags & spEnabled ) == 0 ) { continue; } - - auto &point { sSpeedTable[ idx ] }; - - if( TestFlag( point.iFlags, spPassengerStopPoint ) ) { - if( TableUpdateStopPoint( go, point, d_to_next_sem ) ) { continue; }; - } - v = point.fVelNext; // odczyt prędkości do zmiennej pomocniczej - if( TestFlag( point.iFlags, spSwitch ) ) { - // zwrotnice są usuwane z tabelki dopiero po zjechaniu z nich - iDrivigFlags |= moveSwitchFound; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz - SwitchClearDist = point.fDist + point.trTrack->Length() + fLength; - } - else if ( TestFlag(point.iFlags, spEvent) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować - { // jeżeli event, może być potrzeba wysłania komendy, aby ruszył - continue; - } - - auto const railwaytrackend { true == TestFlag(point.iFlags, spEnd) && is_train() }; - if( v >= 0.0 // pozycje z prędkością -1 można spokojnie pomijać - || railwaytrackend ) { - - // a PointVelocity limit lies fPointDist beyond its entry and stays ahead of us until the head passes it - auto const ispointlimit { TestFlag( point.iFlags, spPointVelocity ) }; - d = point.fDist + point.fPointDist; - - if( v >= 0.0 ) { - // points located in front of us can potentially affect our acceleration and target speed - if( d > 0.0 - && ( false == TestFlag(point.iFlags, spElapsed) || ispointlimit ) ) { - // sygnał lub ograniczenie z przodu (+32=przejechane) - // 2014-02: jeśli stoi, a ma do przejechania kawałek, to niech jedzie - if( mvOccupied->Vel < 0.01 - && true == TestFlag(point.iFlags, spEnabled | spEvent | spPassengerStopPoint) - && false == IsAtPassengerStop ) { - // ma podjechać bliżej - czy na pewno w tym miejscu taki warunek? - a = d > passengerstopmaxdistance || (iDrivigFlags & moveStopCloser) != 0 ? fAcc : 0.0; - } - else { - // przyspieszenie: ujemne, gdy trzeba hamować - if( v >= 0.0 ) { - a = ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ); - if( mvOccupied->Vel < v - || v == 0.0 ) { - // if we're going slower than the target velocity and there's enough room for safe stop, speed up - auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; - if( brakingdistance > 0.0 ) { - // maintain desired acc while we have enough room to brake safely, when close enough start paying attention - // try to make a smooth transition instead of sharp change - a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); - } - } - if( d < ( ispointlimit && v > 0.0 ? point_limit_approach() : fMinProximityDist ) - && v < fVelDes ) { - // jak jest już blisko, ograniczenie aktualnej prędkości - fVelDes = v; - } - } - } - } - // points located behind can affect our current speed, but little else - else if ( point.iFlags & spTrack) // jeśli tor - { // tor ogranicza prędkość, dopóki cały skład nie przejedzie, - if( v >= 1.0 && d + point.trTrack->Length() < -fLength && false == railwaytrackend ) { // EU06 się zawieszało po dojechaniu na koniec toru postojowego - // zapętlenie, jeśli już wyjechał za ten odcinek - continue; - } - if( v < fVelDes ) { - // ograniczenie aktualnej prędkości aż do wyjechania za ograniczenie - fVelDes = v; - } - if( v < VelLimitLastDist.first ) { - VelLimitLastDist.second = d + point.trTrack->Length() + fLength; - } - else if( VelLimitLastDist.second > 0 && (point.iFlags & (spSwitch | spPassengerStopPoint)) == 0 ) { // the speed limit can potentially start afterwards, so don't mark it as broken too soon - speedlimitiscontinuous = false; - } - if( false == railwaytrackend ) { - continue; // i tyle wystarczy - } - } - else { - // event trzyma tylko jeśli VelNext=0, nawet po przejechaniu (nie powinno dotyczyć samochodów?) - a = v > 0.0 ? - fAcc : - mvOccupied->Vel < 0.01 ? - 0.0 : // already standing still so no need to bother with brakes - -2.0; // ruszanie albo hamowanie - } - } - // track can potentially end, which creates another virtual point of interest with speed limit of 0 at the end of it - // TBD, TODO: when tracing the route create a dedicated table entry for it, to simplify the code? - if( railwaytrackend ) { - // if the railway track ends here set the velnext accordingly as well - // TODO: test this with turntables and such - auto const stopatendacceleration = -1.0 * mvOccupied->Vel * mvOccupied->Vel / ( 25.92 * ( d + point.trTrack->Length() ) ); - if( stopatendacceleration < a ) { - a = stopatendacceleration; - v = 0.0; - d += point.trTrack->Length(); - if( d < fMinProximityDist ) { - // jak jest już blisko, ograniczenie aktualnej prędkości - fVelDes = v; - } - } - } - - if( a <= fAcc - && ( v < fNext || fNext < 0 ) ) { // filter out consecutive, farther out blocks with the same speed limit; they'd make us accelerate slower due to their lower a value - // mniejsze przyspieszenie to mniejsza możliwość rozpędzenia się albo konieczność hamowania - // jeśli droga wolna, to może być a>1.0 i się tu nie załapuje - fAcc = a; // zalecane przyspieszenie (nie musi być uwzględniane przez AI) - fNext = v; // istotna jest prędkość na końcu tego odcinka - fDist = d; // dlugość odcinka - bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 ); - } -/* - else if ((fAcc > 0) && (v >= 0) && (v > fNext)) { - // jeśli nie ma wskazań do hamowania, można podać drogę i prędkość na jej końcu - fNext = v; // istotna jest prędkość na końcu tego odcinka - fDist = d; // dlugość odcinka (kolejne pozycje mogą wydłużać drogę, jeśli prędkość jest stała) - } -*/ - // we'll pick first scanned target speed as our goal - // farther scan table points can override it through previous clause, if they require lower acceleration or speed reduction - else if( a > 0 && a <= fAcc && v >= 0 && fNext < 0 ) { - fAcc = a; - fNext = v; - fDist = d; - bStopTargetIsPassengerStop = ( v == 0.0 ) && ( ( point.iFlags & spPassengerStopPoint ) != 0 ); - } - // potentially update our current speed limit - // a point limit binds only the head at its point, it neither extends nor breaks a limit over a stretch of the line - if( false == ispointlimit - && v < VelLimitLastDist.first - && ( d < 0 // the point counts as part of last speed limit either if it's behind us - || VelLimitLastDist.second > 0 ) ) { // or if we already have the last limit ongoing - VelLimitLastDist.second = d + fLength; - if( ( point.iFlags & spTrack ) != 0 ) { - VelLimitLastDist.second += point.trTrack->Length(); - } - } - else if( ( point.iFlags & ( spSwitch | spPassengerStopPoint | spPointVelocity ) ) == 0 ) { - // if we found a point which isn't part of the current speed limit mark the limit as broken - // NOTE: we exclude switches from this rule, as speed limits generally extend through these - speedlimitiscontinuous = false; - } - } // if (v>=0.0) - // finding a point which doesn't impose speed limit means any potential active speed limit can't extend through entire scan table - // NOTE: we test actual speed value for the given point, as events may receive (v = -1) as a way to disable them in irrelevant modes - if( point.fVelNext < 0 && (point.iFlags & (spSwitch | spPassengerStopPoint | spPointVelocity)) == 0 ) { - // NOTE: we exclude switches from this rule, as speed limits generally extend through these - // and point limits, which say nothing of the line they lie on - speedlimitiscontinuous = false; - } - if (fNext >= 0.0) - { // jeśli ograniczenie - if( (point.iFlags & (spEnabled | spEvent)) == (spEnabled | spEvent) && (point.iFlags & spPointVelocity) == 0 && eSignNext == nullptr ) { // tylko sygnał przypisujemy (a point limit isn't one) - // jeśli jeszcze nic nie zapisane tam - eSignNext = point.evEvent; // dla informacji - } - if( fNext == 0.0 ) { - break; // nie ma sensu analizować tabelki dalej - } - } - } - - // the point limits latched before, which aren't in the table any more - apply_point_limits( fVelDes, fDist, fNext, fAcc ); - - // jeśli mieliśmy ograniczenie z semafora i nie ma przed nami - if( VelSignalLast >= 0.0 - && (iDrivigFlags & (moveSignalFound | moveSwitchFound | moveStopPointFound)) == 0 - && true == TestFlag(OrderCurrentGet(), Obey_train) ) { - VelSignalLast = -1.0; - } - // if there's unbroken speed limit through our scan table take a note of it - if( VelLimitLastDist.second > 0 - && speedlimitiscontinuous ) { - VelLimitLastDist.second = EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE; - } - // take into account the effect switches have on duration of signal-imposed speed limit, in calculation of speed limit end point - // a reduced speed ends where the interlocking area does, if that is marked, and not past the switches farther on - if( auto const signallimitend { VelSignalLast > 0.0 && SignalAreaEndDist >= 0.0 ? SignalAreaEndDist : SwitchClearDist }; - VelSignalLast >= 0.0 && signallimitend >= 0.0 ) { - VelLimitLastDist.second = std::max( VelLimitLastDist.second, signallimitend ); - } - - //analiza spisanych z tabelki ograniczeń i nadpisanie aktualnego - // if stopped at a valid passenger stop, hold there - if( true == IsAtPassengerStop && mvOccupied->Vel < 0.01 ) { - fVelDes = 0.0; - } - else { - fVelDes = min_speed( fVelDes, VelSignalLast ); - fVelDes = min_speed( fVelDes, VelLimitLast ); - fVelDes = min_speed( fVelDes, VelRoad ); - fVelDes = min_speed( fVelDes, VelRestricted ); - } - // nastepnego semafora albo zwrotnicy to uznajemy, że mijamy W5 - FirstSemaphorDist = d_to_next_sem; // przepisanie znalezionej wartosci do zmiennej - return go; -}; - -bool -TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance ) { - // stop points are irrelevant when not in one of the basic modes - if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { return true; } - // jeśli przystanek, trzeba obsłużyć wg rozkładu - iDrivigFlags |= moveStopPointFound; - // first 19 chars of the command is expected to be "PassengerStopPoint:" so we skip them - if( ToLower( Point.evEvent->input_text() ).compare( 19, sizeof( asNextStop ), ToLower( asNextStop ) ) != 0 ) - { // jeśli nazwa nie jest zgodna - if( false == IsScheduledPassengerStopVisible // check if our next scheduled stop didn't show up earlier in the scan - && Point.fDist < 1.15 * fBrakeDist + 300 - && Point.fDist > 0 ) // tylko jeśli W4 jest blisko, przy dwóch może zaczać szaleć - { - // porównuje do następnej stacji, więc trzeba przewinąć do poprzedniej - // nastepnie ustawić następną na aktualną tak żeby prawidłowo ją obsłużył w następnym kroku - if( true == TrainParams.RewindTimeTable( Point.evEvent->input_text() ) ) { - asNextStop = TrainParams.NextStop(); - TrainParams.StationStart = TrainParams.StationIndex; - } - } - else if( Point.fDist < -fLength ) { - // jeśli został przejechany - Point.iFlags = 0; // to można usunąć (nie mogą być usuwane w skanowaniu) - } - return true; // ignorowanie jakby nie było tej pozycji - } - else if (iDrivigFlags & moveStopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu - { // tylko gdy nazwa zatrzymania się zgadza - if( ( OrderCurrentGet() & ( Obey_train | Bank ) ) != 0 ) { - // check whether the station specifies radio channel change - // NOTE: we don't do it in shunt mode, as shunting operations tend to use dedicated radio channel - // NOTE: there's a risk radio channel change was specified by a station which we skipped during timetable rewind - // we ignore this for the time being as it's not a high priority error - auto const radiochannel { TrainParams.radio_channel() }; - if( radiochannel > 0 ) { - if( iGuardRadio != 0 ) { - iGuardRadio = radiochannel; - } - if( iRadioChannel != radiochannel ) { - cue_action( driver_hint::radiochannel, radiochannel ); - } - } - } - IsScheduledPassengerStopVisible = true; // block potential timetable rewind if the next stop shows up later in the scan - if (false == TrainParams.IsStop()) - { // jeśli nie ma tu postoju - Point.fVelNext = -1; // maksymalna prędkość w tym miejscu - // przy 160km/h jedzie 44m/s, to da dokładność rzędu 5 sekund - if (Point.fDist < passengerstopmaxdistance * 0.5 ) { - // zaliczamy posterunek w pewnej odległości przed (choć W4 nie zasłania już semafora) -#if LOGSTOPS - WriteLog(std::format( - "{} as {}: at {}:{} passed {}", - pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja -#endif - // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = mvOccupied->DistCounter + 0.250 + 0.001 * fLength; - TrainParams.UpdateMTable( simulation::Time, asNextStop ); - record_station( Point, blackbox::station_kinds::passed ); - UpdateDelayFlag(); - TrainParams.StationIndexInc(); // przejście do następnej - asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania - Point.iFlags = 0; // nie liczy się już - return true; // table entry recognized and handled - } - } // koniec obsługi przelotu na W4 - else { - // zatrzymanie na W4 - // the margins of a passenger stop, whether the train is already making for it or not: the present ones - // depend on this very flag, and a check against them would turn it on and off every other scan - auto const [ stopminproximity, stopmaxproximity ] { - is_train() ? - train_proximity_margins( true ) : - std::pair{ fMinProximityDist, fMaxProximityDist } }; - if ( false == Point.bMoved ) { - // potentially shift the stop point in accordance with its defined parameters - /* - // https://rainsted.com/pl/Wersja/18.2.133#Okr.C4.99gi_dla_W4_i_W32 - Pierwszy parametr ujemny - preferowane zatrzymanie czoła składu (np. przed przejściem). - Pierwszy parametr dodatni - preferowane zatrzymanie środka składu (np. przy wiacie, przejściu podziemnym). - Drugi parametr ujemny - wskazanie zatrzymania dla krótszych składów (W32). - Drugi paramer dodatni - długość peronu (W4). - */ - auto L = 0.0; - auto Par1 = Point.evEvent->input_value(1); - auto Par2 = Point.evEvent->input_value(2); - if (Par2 >= 0 || fLength < -Par2) { //użyj tego W4 - if (Par1 < 0) { - L = -Par1; - } - else { - //środek - L = Par1 - stopminproximity - fLength * 0.5; - } - // the train comes to a stand anywhere up to the margin of a passenger stop short of this point, not - // that of the signals it may be making for when it first sees the W4, so the tail is to keep that far - // inside the platform - L = std::max(0.0, std::min(L, std::abs(Par2) - stopminproximity - fLength)); - Point.UpdateDistance(L); - Point.bMoved = true; - Point.fMoved = L; - } - else { - Point.iFlags = 0; - } - } - // for human-driven vehicles discard the stop point if they leave it far enough behind - if( false == AIControllFlag - && Point.fDist < -1 * std::max(fLength + 100, 250.0) - Point.fMoved ) { - record_station( Point, blackbox::station_kinds::missed ); - Point.iFlags = 0; // nie liczy się już zupełnie (nie wyśle SetVelocity) - Point.fVelNext = -1; // można jechać za W4 - if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { - // sanity check, if we're held by this stop point, let us go - VelSignalLast = -1; - } - return true; - } - - IsAtPassengerStop = Point.fDist <= passengerstopmaxdistance - // Ra 2F1I: odległość plus długość pociągu musi być mniejsza od długości - // peronu, chyba że pociąg jest dłuższy, to wtedy minimalna. - // jeśli długość peronu ((sSpeedTable[i].evEvent->ValueGet(2)) nie podana, - // przyjąć odległość fMinProximityDist - && ((iDrivigFlags & moveStopCloser) != 0 ? - Point.fDist + fLength + (Point.fMoved - stopminproximity * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)), - 2.0 * stopmaxproximity + fLength) : - Point.fDist < Signaldistance); - - if( !eSignNext ) { - //jeśli nie widzi następnego sygnału ustawia dotychczasową - eSignNext = Point.evEvent; - } - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { - // jeśli jedzie (nie trzeba czekać, aż się drgania wytłumią - drzwi zamykane od 1.0) to będzie zatrzymanie - Point.fVelNext = 0; - // potentially announce pending stop - if( m_lastannouncement != announcement_t::approaching - && Point.fDist < 750 - && Point.fDist > 250 ) { - announce( announcement_t::approaching ); - } - } else if( true == IsAtPassengerStop ) { - // jeśli się zatrzymał przy W4, albo stał w momencie zobaczenia W4 - if( !AIControllFlag ) { - // w razie przełączenia na AI ma nie podciągać do W4, gdy użytkownik zatrzymał za daleko - iDrivigFlags &= ~moveStopCloser; - } - if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { - // to się wykona tylko raz po zatrzymaniu na W4 - record_station( Point, blackbox::station_kinds::stopped ); - if( TrainParams.StationIndex < TrainParams.StationCount ) { - // jeśli są dalsze stacje, bez trąbienia przed odjazdem - // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop - iDrivigFlags &= ~( moveStartHorn | moveStartHornNow ); - } - UpdateDelayFlag(); - - // perform loading/unloading - // HACK: manual check if we didn't already do load exchange at this stop - // TODO: remove the check once the station system is in place - if( m_lastexchangestop != asNextStop ) { - m_lastexchangestop = asNextStop; - m_lastexchangedirection = pVehicle->DirectionGet(); - m_lastexchangeplatforms = static_cast( std::floor( std::abs( Point.evEvent->input_value( 2 ) ) ) ) % 10; - auto const exchangetime { simulation::Station.update_load( pVehicles[ end::front ], TrainParams, m_lastexchangeplatforms ) }; - WaitingSet( exchangetime ); - // announce the stop name while at it - announce( announcement_t::current ); - m_makenextstopannouncement = true; - } - - if (TrainParams.DirectionChange()) { - // jeśli "@" w rozkładzie, to wykonanie dalszych komend - // wykonanie kolejnej komendy, nie dotyczy ostatniej stacji - if (iDrivigFlags & movePushPull) { - // SN61 ma się też nie ruszać, chyba że ma wagony - iDrivigFlags |= moveStopHere; // EZT ma stać przy peronie - if (OrderNextGet() != Change_direction) { - OrderPush(Change_direction); // zmiana kierunku - OrderPush( - TrainParams.StationIndex < TrainParams.StationCount ? - Obey_train : - Shunt); // to dalej wg rozkładu - } - } - else { - // a dla lokomotyw... - // pozwolenie na przejechanie za W4 przed czasem i nie ma stać - iDrivigFlags &= ~( moveStopPoint | moveStopHere ); - } - // przejście do kolejnego rozkazu (zmiana kierunku, odczepianie) - JumpToNextOrder(); - // ma nie podjeżdżać pod W4 po przeciwnej stronie - iDrivigFlags &= ~moveStopCloser; - // ten W4 nie liczy się już zupełnie (nie wyśle SetVelocity) - Point.iFlags = 0; - // jechać - Point.fVelNext = -1; - // nie analizować prędkości - return true; - } - } - - if (OrderCurrentGet() & ( Shunt | Loose_shunt )) { - OrderNext(Obey_train); // uruchomić jazdę pociągową - CheckVehicles(); // zmienić światła - } - - if (TrainParams.StationIndex < TrainParams.StationCount) { - // jeśli są dalsze stacje, czekamy do godziny odjazdu - if ( true == IsCargoTrain - || true == TrainParams.IsMaintenance() - || TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond * 0.0167) ) { - // z dalszą akcją czekamy do godziny odjazdu - // cargo trains and passenger trains at maintenance stop don't need to wait - IsAtPassengerStop = false; - record_station( Point, blackbox::station_kinds::ready ); - // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój - fLastStopExpDist = mvOccupied->DistCounter + 0.050 + 0.001 * fLength; - TrainParams.StationIndexInc(); // przejście do następnej - asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania -#if LOGSTOPS - WriteLog(std::format( - "{} as {}: at {}:{} next {}", - pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja -#endif - // update consist weight, brake settings and ai braking tables - // NOTE: this calculation is expected to run after completing loading/unloading - CheckVehicles(); // nastawianie hamulca do jazdy pociągowej - - if( static_cast( std::floor( std::abs( Point.evEvent->input_value( 1 ) ) ) ) % 2 ) { - // nie podjeżdżać do semafora, jeśli droga nie jest wolna - iDrivigFlags |= moveStopHere; - } - else { - //po czasie jedź dalej - iDrivigFlags &= ~moveStopHere; - } - iDrivigFlags |= moveStopCloser; // do następnego W4 podjechać blisko (z dociąganiem) - Point.iFlags = 0; // nie liczy się już zupełnie (nie wyśle SetVelocity) - Point.fVelNext = -1; // można jechać za W4 - if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { - // sanity check, if we're held by this stop point, let us go - VelSignalLast = -1; - } - if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej - Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) - } - if( false == tsGuardSignal.empty() ) { - // jeśli mamy głos kierownika, to odegrać - iDrivigFlags |= moveGuardSignal; - } - return true; // nie analizować prędkości - } // koniec startu z zatrzymania - else { - cue_action(driver_hint::waitdeparturetime); - if (TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure - iDrivigFlags |= moveGuardOpenDoor; - GuardOpenDoor(); - } - } - } // koniec obsługi początkowych stacji - else { - // jeśli dojechaliśmy do końca rozkładu -#if LOGSTOPS - WriteLog(std::format( - "{} as {}: at {}:{} end of route.", - pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute)); // informacja -#endif - asNextStop = TrainParams.NextStop(); // informacja o końcu trasy - TrainParams.NewName("none"); // czyszczenie nieaktualnego rozkładu - // koniec kursu, gasimy wyświetlacze relacji (tablice blaszane zostają) - for( auto *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - vehicle->DestinationClear(); - } - // ma nie podjeżdżać pod W4 i ma je pomijać - iDrivigFlags &= ~moveStopCloser; - if( false == TestFlag( iDrivigFlags, movePushPull ) ) { - // if the consist can change direction through a simple cab change it doesn't need fiddling with recognition of passenger stops - iDrivigFlags &= ~moveStopPoint; - } - fLastStopExpDist = -1.0f; // nie ma rozkładu, nie ma usuwania stacji - Point.iFlags = 0; // W4 nie liczy się już (nie wyśle SetVelocity) - Point.fVelNext = -1; // można jechać za W4 - if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { - // sanity check, if we're held by this stop point, let us go - VelSignalLast = -1; - } - // wykonanie kolejnego rozkazu (Change_direction albo Shunt) - JumpToNextOrder(); - // ma się nie ruszać aż do momentu podania sygnału - iDrivigFlags |= moveStopHere | moveStartHorn; - return true; // nie analizować prędkości - } // koniec obsługi ostatniej stacji - } // vel 0, at passenger stop - else { - // HACK: momentarily deactivate W4 to trick the controller into moving closer - Point.fVelNext = -1; - } // vel 0, outside of passenger stop - } // koniec obsługi zatrzymania na W4 - } // koniec warunku pomijania W4 podczas zmiany czoła - else - { // skoro pomijanie, to jechać i ignorować W4 - Point.iFlags = 0; // W4 nie liczy się już (nie zatrzymuje jazdy) - Point.fVelNext = -1; - return true; // nie analizować prędkości - } - - return false; // -} - -// a road speed sign (W27/W27a) passed by the head stays in the table until the rear is past it too. not for cars: their -// passed events leave the table at the latest when the rear passes them (TableCheck), before the table update sees that -bool -TController::is_road_velocity_held( TSpeedPos const &Point ) const { - - return TestFlag( Point.iFlags, spRoadVel ) - && mvOccupied->CategoryFlag != 2 - && Point.fDist >= -fLength; -} - -// a passed event is handled once and then dropped from the table, except a road speed sign held for the rear -void -TController::TableDropPassedEvent( TSpeedPos &Point ) const { - - if( is_road_velocity_held( Point ) ) { - Point.iFlags |= spRoadVelHeld; - return; - } - Point.Clear(); -} - -// the lowest road speed of the signs past the given one that the head has passed: held until the rear is past them too, -// or passed in this very tick and not marked as held yet; -1 if there's none -double -TController::held_road_velocity_beyond( TSpeedPos const &Point ) const { - - auto lowest { -1.0 }; - for( auto const &held : sSpeedTable ) { - if( ( held.iFlags & ( spEnabled | spRoadVel ) ) != ( spEnabled | spRoadVel ) - || held.fDist >= 0.0 - || held.fDist <= Point.fDist ) { - continue; - } - lowest = min_speed( lowest, held.fVelNext ); - } - return lowest; -} - -// a road speed (W27/W27a) lower than the one in force holds once the head passes the sign, a higher one only once the -// whole train is past it (a car takes it from the head). the first pass after the head handles the sign as before, the -// entry is then only held for the rear: returns true for it, so the rest of the table update leaves it out -bool -TController::TableUpdateRoadVelocity( TSpeedPos &Point ) { - - if( Point.fDist >= 0.0 ) { return false; } - - if( mvOccupied->CategoryFlag == 2 ) { - VelRoad = Point.fVelNext; - return false; - } - - auto const isrearpast { Point.fDist < -fLength }; - if( isrearpast ) { - // the rear past it, but not past a sign after it the head has passed too: none of those may be exceeded, so a - // lower one (W27a 60 within a train's length after a 120) stays in force - VelRoad = min_speed( Point.fVelNext, held_road_velocity_beyond( Point ) ); - } - else if( Point.fVelNext == min_speed( Point.fVelNext, VelRoad ) ) { - VelRoad = Point.fVelNext; - } - if( false == TestFlag( Point.iFlags, spRoadVelHeld ) ) { - return false; - } - if( isrearpast ) { - Point.Clear(); - } - return true; -} - -// a reduced speed shown by a signal holds to the end of the interlocking area the signal guards (Ie-1), and that end is -// marked on the main track with a SignalAreaEnd event. on a track without the marker the speed holds as it did before: -// until the next signal, or until no signal, switch or stop point is left in the scan -void -TController::TableUpdateSignalAreaEnd( TSpeedPos &Point ) { - - // the switches lie in front of the marker, so the whole train has left them once its rear end is past it - if( Point.fDist >= -fLength ) { - if( SignalAreaEndDist < 0.0 - && TestFlag( OrderCurrentGet(), Obey_train ) ) { - // the table is sorted by distance, so the first marker is the nearest one - SignalAreaEndDist = Point.fDist + fLength; - } - return; - } - - // in shunting the marker stays, a train order given before the next signal still finds it - if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } - - // a passed signal at stop (0) keeps holding the train, only a reduced speed ends here - if( VelSignalLast > 0.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", left the interlocking area at " + Point.evEvent->m_name ); - } - VelSignalLast = -1.0; - } - Point.Clear(); -} - -bool TController::point_limit_latched( basic_event const *Cell ) const { - - return std::any_of( - m_pointlimits.begin(), m_pointlimits.end(), - [&]( point_limit const &Limit ) { return Limit.source == Cell; } ); -} - -double TController::point_limit_end( glm::dvec3 const &Heading ) const { - - auto const origin { pVehicle->GetPosition() }; - auto result { 0.0 }; - auto first { true }; - for( auto const *vehicle : { pVehicles[ end::front ], pVehicles[ end::rear ] } ) { - if( vehicle == nullptr ) { continue; } - for( auto const side : { end::front, end::rear } ) { - auto const along { glm::dot( vehicle->CouplerPosition( side ) - origin, Heading ) }; - result = ( first ? along : std::max( result, along ) ); - first = false; - } - } - return result; -} - -void TController::latch_point_limit( TSpeedPos const &Point ) { - - if( point_limit_latched( Point.evEvent ) ) { return; } - m_pointlimits.push_back( - point_limit { Point.evEvent, Point.fVelNext, Point.fDist + Point.fPointDist, Point.fPointDist, travel_direction() } ); - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", latched point limit of " + Point.evEvent->m_name - + ": " + to_string( Point.fVelNext, 0 ) + " in " + to_string( m_pointlimits.back().distance, 0 ) + " m" ); - } -} - -void TController::update_point_limits() { - - if( pVehicle == nullptr ) { return; } - auto const position { pVehicle->GetPosition() }; - if( m_pointlimitsvehicle == pVehicle ) { - auto const movement { position - m_pointlimitsposition }; - auto const length { glm::length( movement ) }; - if( length >= 200.0 ) { - // a longer jump between two updates isn't driving: the consist was moved elsewhere - m_pointlimits.clear(); - } - else if( length > 0.0 ) { - auto const step { movement / length }; - for( auto &limit : m_pointlimits ) { - if( glm::length( limit.heading ) < 0.5 ) { - // the way wasn't known when the limit was latched, the head was passing the cell - limit.heading = step; - } - auto const along { glm::dot( step, limit.heading ) }; - limit.distance += ( along >= 0.0 ? -length : length ); - // the way towards the point follows the line, step by step; a step far off it - // (a jolt of a standing vehicle) doesn't turn it - if( std::abs( along ) > 0.5 ) { - limit.heading = ( along >= 0.0 ? step : -step ); - } - } - } - } - // a change of the vehicle (another cab) starts the measure from its place - auto const vehiclechanged { m_pointlimitsvehicle != pVehicle }; - auto const previousposition { m_pointlimitsposition }; - m_pointlimitsvehicle = pVehicle; - m_pointlimitsposition = position; - // the consist, as its end vehicles and its length - auto const *front { pVehicles[ end::front ] }; - auto const *rear { pVehicles[ end::rear ] }; - auto const consistchanged { - false == ( ( front == m_pointlimitsends[ 0 ] && rear == m_pointlimitsends[ 1 ] ) - || ( front == m_pointlimitsends[ 1 ] && rear == m_pointlimitsends[ 0 ] ) ) - || std::abs( fLength - m_pointlimitslength ) > 0.5 }; - m_pointlimitsends[ 0 ] = front; - m_pointlimitsends[ 1 ] = rear; - m_pointlimitslength = fLength; - // vehicles coupled or uncoupled at the end towards the point move the head towards it or away. only a change of - // the consist counts, as the end measured from the vehicle shifts on curves. another vehicle measured from (a cab - // change, which may come with a coupling in the same order) moves the end measured before to its place - for( auto &limit : m_pointlimits ) { - if( glm::length( limit.heading ) < 0.5 ) { continue; } - auto const consistend { point_limit_end( limit.heading ) }; - if( limit.endknown && consistchanged ) { - auto const previousend { - vehiclechanged ? - limit.end + glm::dot( previousposition - position, limit.heading ) : - limit.end }; - limit.distance -= consistend - previousend; - } - limit.end = consistend; - limit.endknown = true; - } - - auto const travel { travel_direction() }; - std::erase_if( - m_pointlimits, - [&]( point_limit const &Limit ) { - // passed by the head - if( Limit.distance < 0.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Limit.source->m_name ); - } - return true; - } - // the head backed up behind the cell: the speed table reads it again if it is ahead - if( Limit.distance > Limit.celldistance + 1.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", left behind point limit of " + Limit.source->m_name ); - } - return true; - } - // the cell ahead of the head again, going towards the point after backing up past the cell: it is read anew - // (not while backing up: the cell may as well be scanned from the other side) - return glm::dot( travel, Limit.heading ) > 0.0 - && std::any_of( - sSpeedTable.begin(), sSpeedTable.end(), - [&]( TSpeedPos const &Point ) { - return Point.evEvent == Limit.source - && TestFlag( Point.iFlags, spEnabled | spEvent | spPointVelocity ) - && Point.fDist > 0.0; } ); } ); -} - -void TController::apply_point_limits( double &Velocity, double &Distance, double &Next, double &Acceleration ) { - - auto const travel { travel_direction() }; - for( auto const &limit : m_pointlimits ) { - // latched with no limit, or passed (dropped at the next update) - if( limit.velocity < 0.0 || limit.distance <= 0.0 ) { continue; } - // going away from the point, or the way isn't known - if( glm::dot( travel, limit.heading ) <= 0.0 ) { continue; } - // the same as for a point of the speed table ahead - auto const v { limit.velocity }; - auto const d { limit.distance }; - auto a { ( v * v - mvOccupied->Vel * mvOccupied->Vel ) / ( 25.92 * d ) }; - if( mvOccupied->Vel < v ) { - auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; - if( brakingdistance > 0.0 ) { - a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); - } - } - if( d < point_limit_approach() && v < Velocity ) { - Velocity = v; - } - if( a <= Acceleration - && ( v < Next || Next < 0 ) ) { - Acceleration = a; - Next = v; - Distance = d; - bStopTargetIsPassengerStop = false; - } - } -} - -double TController::point_limit_approach() const { - // a point limit holds at its point and not a metre beyond, so the braking curve alone leaves a slow consist - // coasting above it (the deceleration asked for is below what makes the driver brake). within the final - // approach, and five seconds of the present speed before it, the speed is held down to it already - return fMaxProximityDist + mvOccupied->Vel / 3.6 * 5.0; -} - -glm::dvec3 TController::travel_direction() const { - - if( pVehicle == nullptr || iDirection == 0 ) { return glm::dvec3 { 0.0 }; } - // the direction is given against the couplers of the vehicle the driver is in, which is the vehicle measured; - // along its own length it follows the track, where the chord of a long consist on a curve doesn't - auto const along { pVehicle->CouplerPosition( end::front ) - pVehicle->CouplerPosition( end::rear ) }; - auto const length { glm::length( along ) }; - if( length < 0.001 ) { return glm::dvec3 { 0.0 }; } - return ( iDirection > 0 ? along : -along ) / length; -} - -bool -TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex ) { - - if( TestFlag( Point.iFlags, spSignalAreaEnd ) ) { - // not a signal: it neither sends a command nor counts as the end of a speed limit in the scan - TableUpdateSignalAreaEnd( Point ); - return true; - } - - if( TestFlag( Point.iFlags, spPointVelocity ) ) { - // PointVelocity: no signal, no command, only the limit at its point - // done once the head passes the point - if( Point.fDist + Point.fPointDist < 0.0 ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Point.GetName() ); - } - Point.Clear(); - return true; - } - if( Point.fDist < 0.0 ) { - if( point_limit_latched( Point.evEvent ) ) { - // a table built anew found under the consist a cell whose state holds already - Point.Clear(); - return true; - } - if( Point.fVelNext != 0.0 ) { - // the head passed the cell: what it says now holds at the point, whatever happens to the table. - // a stop at 0 stays in the table, where the cell can still release it - latch_point_limit( Point ); - Point.Clear(); - return true; - } - } - return false; - } - - // sprawdzanie eventów pasywnych miniętych - if( Point.fDist < 0.0 ) { - if( SemNextIndex == Pointindex ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextIndex ].GetName() ); - } - SemNextIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód - } - if( SemNextStopIndex == Pointindex ) { - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextStopIndex ].GetName() ); - } - SemNextStopIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód - } - switch( Point.evEvent->input_command() ) { - // TBD, TODO: expand emergency_brake handling to a more generic security system signal - case TCommandType::cm_EmergencyBrake: { - pVehicle->RadioStop(); - Point.Clear(); // signal received, deactivate - return true; - } - case TCommandType::cm_SecuritySystemMagnet: { - // NOTE: magnet induction calculation presumes the driver is located in the front vehicle - // TBD, TODO: take into account actual position of controlled/occupied vehicle in the consist, whichever comes first - auto const magnetlocation { pVehicles[ end::front ]->MoverParameters->SecuritySystem.MagnetLocation }; - auto const magnetrange { 1.0 }; - auto const ismagnetpassed { Point.fDist < -( magnetlocation + magnetrange ) }; - if( Point.fDist < -magnetlocation && (mvOccupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) { - // NOTE: normally we'd activate the magnet once the leading vehicle passes it - // but on a fresh scan after direction change it would be detected as long as it's under consist, and meet the (simple) activation condition - // thus we're doing a more precise check in such situation (we presume direction change takes place only if the vehicle is standing still) - mvOccupied->SecuritySystem.set_cabsignal_lock(!AIControllFlag); // don't make life difficult for the ai, but a human driver is a fair game - PutCommand(Point.evEvent->input_text(), Point.evEvent->input_value(1), Point.evEvent->input_value(2), nullptr); - } - if( ismagnetpassed ) { - Point.Clear(); - mvOccupied->SecuritySystem.set_cabsignal_lock(false); - } - return true; - } - default: { - break; - } - } - } - // check signals ahead - if( Point.fDist > 0.0 ) { - // bail out early for signals which activate when passed - // TBD: make it an event method? - switch( Point.evEvent->input_command() ) { - case TCommandType::cm_EmergencyBrake: { - return true; - } - case TCommandType::cm_SecuritySystemMagnet: { - return true; - } - default: { - break; - } - } - - if( Point.IsProperSemaphor( OrderCurrentGet() ) ) { - // special rule for cars: ignore stop signals at distance too short to come to a stop - // as trying to stop in such situation is likely to place the car on train tracks - if( is_car() - && Point.fVelNext != -1.0 - && Point.fVelNext < 1.0 - && Point.fDist < -0.5 + std::min(fBrakeDist * 0.2, mvOccupied->Vel * 0.2) ) { - Point.Clear(); - return true; - } - // jeśli jest mienięty poprzedni semafor a wcześniej - // byl nowy to go dorzucamy do zmiennej, żeby cały czas widział najbliższy - if( SemNextIndex == npos ) { // NOSONAR - SemNextIndex = Pointindex; - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table update for " + OwnerName() + ", next semaphor is " + sSpeedTable[ SemNextIndex ].GetName() ); - } - } - if( SemNextStopIndex == npos - || ( sSpeedTable[SemNextStopIndex].fVelNext != 0 - && Point.fVelNext == 0 ) ) { - SemNextStopIndex = Pointindex; - } - } - } - if (Point.iFlags & spOutsideStation) - { // jeśli W5, to reakcja zależna od trybu jazdy - if (OrderCurrentGet() & Obey_train) - { // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) - Velocity = -1.0; // ignorować? - if ( Point.fDist < 0.0) { // jeśli wskaźnik został minięty - VelSignalLast = Velocity; //ustawienie prędkości na -1 - } - else if( ( iDrivigFlags & moveSwitchFound ) == 0 ) { // jeśli rozjazdy już minięte - VelSignalLast = Velocity; //!!! to też koniec ograniczenia - } - } - else - { // w trybie manewrowym: skanować od niego wstecz, stanąć po wyjechaniu za sygnalizator i zmienić kierunek - Velocity = 0.0; // zmiana kierunku może być podanym sygnałem, ale wypadało by zmienić światło wcześniej - if( ( iDrivigFlags & moveSwitchFound ) == 0 ) { // jeśli nie ma rozjazdu - // check for presence of a signal facing the opposite direction - // if there's one, we'll want to pass it before changing direction - basic_event *foundevent = nullptr; - if( Point.fDist - fMaxProximityDist > 0 ) { - auto scandistance{ Point.fDist + fLength - fMaxProximityDist }; - auto *scanvehicle{ pVehicles[ end::rear ] }; - auto scandirection{ scanvehicle->DirectionGet() * scanvehicle->RaDirectionGet() }; - auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, end::front, false ); - } - if( foundevent == nullptr ) { - iDrivigFlags |= moveTrackEnd; // to dalsza jazda trwale ograniczona (W5, koniec toru) - } - } - } - } - else if ( Point.iFlags & spStopOnSBL) { - // jeśli S1 na SBL - if( mvOccupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) { - // stanąć nie musi, ale zwolnić przynajmniej - // jest w maksymalnym zasięgu to można go pominąć (wziąć drugą prędkosć) - // as long as there isn't any obstacle in arbitrary view range - eSignSkip = Point.evEvent; - // jazda na widoczność - skanować możliwość kolizji i nie podjeżdżać zbyt blisko - // usunąć flagę po podjechaniu blisko semafora zezwalającego na jazdę - // ostrożnie interpretować sygnały - semafor może zezwalać na jazdę pociągu z przodu! - iDrivigFlags |= moveVisibility; - // store the ordered restricted speed and don't exceed it until the flag is cleared - VelRestricted = Point.evEvent->input_value(2); - } - if( eSignSkip != Point.evEvent ) { - // jeśli ten SBL nie jest do pominięcia to ma 0 odczytywać - Velocity = Point.evEvent->input_value( 1 ); - // TODO sprawdzić do której zmiennej jest przypisywane v i zmienić to tutaj - } - } - else if ( Point.IsProperSemaphor(OrderCurrentGet())) - { // to semaphor - if( Point.fDist < 0 ) { - // for human-driven vehicles ignore the signal if it was passed by sufficient distance - if( false == AIControllFlag - && Point.fDist < -1 * std::max(fLength + 100, 250.0) ) { - VelSignal = -1.0; - Point.Clear(); - return true; - } - // for ai-driven vehicles always play by the rules - else { - VelSignalLast = Point.fVelNext; //minięty daje prędkość obowiązującą - // a marker before this signal ends the interlocking area of an earlier signal, not the area of this one - // (a train longer than the way between the two, or one which started standing over the marker) - std::ranges::for_each( sSpeedTable | std::views::take( Pointindex ), clear_signal_area_end ); - } - } - else { - //jeśli z przodu to dajemy flagę, że jest - iDrivigFlags |= moveSignalFound; - Signaldistance = std::min( Point.fDist, Signaldistance ); - // if there's another vehicle closer to the signal, then it's likely its intended recipient - // HACK: if so, make it a stop point, to prevent non-signals farther down affect us - auto const isforsomeoneelse { is_train() && Obstacle.distance < Point.fDist }; - if( Point.fDist <= Signaldistance ) { - if( isforsomeoneelse ) { - VelSignalNext = 0.0; - Velocity = 0.0; - } - else { - VelSignalNext = Point.fVelNext; - if( Velocity < 0 ) { - Velocity = fVelMax; - VelSignal = fVelMax; - } - } - } - } - } - else if ( Point.iFlags & spRoadVel) - { // to W27/W27a - if( TableUpdateRoadVelocity( Point ) ) { - return true; - } - } - else if ( Point.iFlags & spSectionVel && Point.fDist < 0) - { // to W9 - // teraz trzeba sprawdzić inne warunki - if (Point.fSectionVelocityDist == 0.0) - { - if (Global.iWriteLogEnabled & 8) - { - WriteLog("TableUpdate: Event is behind. SVD = 0: " + Point.evEvent->m_name); - } - Point.Clear(); // jeśli punktowy to kasujemy i nie dajemy ograniczenia na stałe - } - else if (Point.fSectionVelocityDist < 0.0) - { - // ograniczenie obowiązujące do następnego - if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) - { - // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz - VelLimitLast = Point.fVelNext; - } - else if (Point.fDist < -fLength) - { - // jeśli większe to musi wyjechać za poprzednie - VelLimitLast = Point.fVelNext; - if (Global.iWriteLogEnabled & 8) - { - WriteLog("TableUpdate: Event is behind. SVD < 0: " + Point.evEvent->m_name); - } - Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować - } - } - else - { // jeśli większe to ograniczenie ma swoją długość - if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) - { - // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz - VelLimitLast = Point.fVelNext; - } - else if (Point.fDist < -fLength && Point.fVelNext != VelLimitLast) - { - // jeśli większe to musi wyjechać za poprzednie - VelLimitLast = Point.fVelNext; - } - else if (Point.fDist < -fLength - Point.fSectionVelocityDist) - { - VelLimitLast = -1.0; - if (Global.iWriteLogEnabled & 8) - { - WriteLog("TableUpdate: Event is behind. SVD > 0: " + Point.evEvent->m_name); - } - Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować - } - } - } - - //sprawdzenie eventów pasywnych przed nami - { // zawalidrogi nie ma (albo pojazd jest samochodem), sprawdzić sygnał - if ( Point.iFlags & spShuntSemaphor) // jeśli Tm - w zasadzie to sprawdzić komendę! - { // jeśli podana prędkość manewrowa - if( Velocity == 0.0 - && true == TestFlag(OrderCurrentGet(), Obey_train) ) { - // jeśli tryb pociągowy a tarcze ma ShuntVelocity 0 0 - Velocity = -1; // ignorować, chyba że prędkość stanie się niezerowa - if( true == TestFlag( Point.iFlags, spElapsed ) ) { - // a jak przejechana to można usunąć, bo podstawowy automat usuwa tylko niezerowe - Point.Clear(); - } - } - else if( Command == TCommandType::cm_Unknown && Velocity != 0.0 ) { - // jeśli jeszcze nie ma komendy - // komenda jest tylko gdy ma jechać, bo stoi na podstawie tabelki - // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal - Command = TCommandType::cm_ShuntVelocity; // w trybie pociągowym tylko jeśli włącza tryb manewrowy (v!=0.0) - // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo Tm może być daleko - if (VelSignal == 0.0) - { - // aby stojący ruszył - VelSignal = Velocity; - } - if (Point.fDist < 0.0) - { - // jeśli przejechany - //!!! ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to - VelSignal = Velocity; - // to można usunąć (nie mogą być usuwane w skanowaniu) - Point.Clear(); - } - } - } - else if( ( Point.iFlags & spSectionVel ) == 0 ) { - //jeśli jakiś event pasywny ale nie ograniczenie - if( Command != TCommandType::cm_Unknown ) - { - } - else - { - // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal - if (Velocity < 0.0 || Velocity >= 1.0) - { - // bo wartość 0.1 służy do hamowania tylko - Command = TCommandType::cm_SetVelocity; // może odjechać - // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo semafor może być daleko - // VelSignal=v; //nie do końca tak, to jest druga prędkość; -1 nie wpisywać... - if (VelSignal == 0.0) - { - // aby stojący ruszył - VelSignal = -1.0; - } - if (Point.fDist < 0.0) - { - // jeśli przejechany - VelSignal = Velocity == 0.0 ? 0.0 : -1.0; - // ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to - if (Point.iFlags & spEvent && (Point.evEvent != eSignSkip || Point.fVelNext != VelRestricted)) - { - // jeśli event - // ale inny niż ten, na którym minięto S1, chyba że się już zmieniło - // sygnał zezwalający na jazdę wyłącza jazdę na widoczność (po S1 na SBL) - iDrivigFlags &= ~moveVisibility; - // remove restricted speed - VelRestricted = -1.0; - } - // jeśli nie jest ograniczeniem prędkości to można usunąć - // (nie mogą być usuwane w skanowaniu) - TableDropPassedEvent( Point ); - } - } - else if (Point.fDist > 0.0 && typeid(*Point.evEvent) == typeid(road_order)) - { - // a level crossing or a junction which holds the vehicle ahead: the road orders past it, which let the traffic - // through, aren't for this vehicle yet. without this the first of them would tell the standing vehicle to drive on - Command = TCommandType::cm_SetProximityVelocity; // taken, and not acted on - } - else if (Point.evEvent->is_command()) - { - // jeśli prędkość jest zerowa, a komórka zawiera komendę - eSignNext = Point.evEvent; // dla informacji - // make sure the command isn't for someone else - // TBD, TODO: revise this check for bank/loose_shunt; we might want to ignore obstacles with no owner in these modes - if (Point.fDist < Obstacle.distance) - { - if (true == TestFlag(iDrivigFlags, moveStopHere)) - { - // jeśli ma stać, dostaje komendę od razu - Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu - } - // NOTE: human drivers are likely to stop wherever and expect things to still work, so we give them more leeway - else if (Point.fDist <= (AIControllFlag ? fMaxProximityDist : std::max(250.0, fMaxProximityDist))) - { - // jeśli ma dociągnąć, to niech dociąga - // (moveStopCloser dotyczy dociągania do W4, nie semafora) - Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu - } - } - } - } - } - } // jeśli nie ma zawalidrogi - - return false; -} - -// modifies brake distance for low target speeds, to ease braking rate in such situations -float -TController::braking_distance_multiplier( float const Targetvelocity ) const { - - auto const frictionmultiplier { 1.f / Global.FrictionWeatherFactor }; - - if( Targetvelocity > 65.f ) { return 1.f * frictionmultiplier; } - if( Targetvelocity < 5.f ) { - // HACK: engaged automatic transmission means extra/earlier braking effort is needed for the last leg before full stop - if( is_dmu() - && mvOccupied->Vel < 40.0 - && Targetvelocity == 0.f ) { - auto const multiplier { std::clamp( 1.f + iVehicles * 0.5f, 2.f, 4.f ) }; - return std::lerp(multiplier, 1.f, static_cast(mvOccupied->Vel / 40.0)) * frictionmultiplier; - } - // HACK: cargo trains or trains going downhill with high braking threshold need more distance to come to a full stop - if( fBrake_a0[1] > 0.2 - && ( true == IsCargoTrain - || fAccGravity > 0.025 ) ) { - return std::lerp(1.f, 2.f, std::clamp((fBrake_a0[1] - 0.2) / 0.2, 0.0, 1.0)) * frictionmultiplier; - } - - return 1.f * frictionmultiplier; - } - // stretch the braking distance up to 3 times; the lower the speed, the greater the stretch - return std::lerp(3.f, 1.f, (Targetvelocity - 5.f) / 60.f) * frictionmultiplier; -} - -void TController::TablePurger() -{ // odtykacz: usuwa mniej istotne pozycje ze środka tabelki, aby uniknąć zatkania - //(np. brak ograniczenia pomiędzy zwrotnicami, usunięte sygnały, minięte odcinki łuku) - if( sSpeedTable.size() < 2 ) { - return; - } - // simplest approach should be good enough for start -- just copy whatever is still relevant, then swap - auto const isexpendable = []( TSpeedPos const &Speedpoint ) { - return - 0 == ( Speedpoint.iFlags & spEnabled ) - || ( ( Speedpoint.iFlags & ( spElapsed | spTrack | spCurve | spSwitch ) ) == ( spElapsed | spTrack | spCurve ) - && Speedpoint.fVelNext < 0.0 ); }; - // do a trial run first, to see if we need to bother at all - std::size_t trimcount{ 0 }; - for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { - // NOTE: we could break out early here, but running through entire thing gives us exact size needed for new table - if( isexpendable( sSpeedTable[ idx ] ) ) { - ++trimcount; - } - } - if( trimcount == 0 ) { - // there'd be no gain, may as well bail - return; - } - std::vector trimmedtable; trimmedtable.reserve( sSpeedTable.size() - trimcount ); - // the indices are only valid for the old table, so the new placements are recorded separately - // and assigned once the new table is complete - auto semnextindex { std::size_t( -1 ) }; - auto semnextstopindex { std::size_t( -1 ) }; - auto const trackplacement = [&]( std::size_t const Index, bool const Kept ) { - // a trimmed point leaves the index invalid, a kept one lands where the new table ends - if( Index == SemNextIndex ) { - semnextindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); - } - if( Index == SemNextStopIndex ) { - semnextstopindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); - } }; - - for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { - auto const &speedpoint = sSpeedTable[ idx ]; - auto const kept { false == isexpendable( speedpoint ) }; - trackplacement( idx, kept ); - if( false == kept ) { continue; } - // we're left with useful speed point record we should copy - trimmedtable.emplace_back( speedpoint ); - } - // always copy the last entry; an index pointing at it has to follow it as well - trackplacement( sSpeedTable.size() - 1, true ); - trimmedtable.emplace_back( sSpeedTable.back() ); - - SemNextIndex = semnextindex; - SemNextStopIndex = semnextstopindex; - - if( Global.iWriteLogEnabled & 8 ) { - WriteLog( "Speed table garbage collection for " + OwnerName() + " cut away " + std::to_string( trimcount ) + ( trimcount == 1 ? " record" : " records" ) ); - } - // update the data - std::swap( sSpeedTable, trimmedtable ); - iLast = sSpeedTable.size() - 1; -}; - -void TController::TableSort() { - - if( sSpeedTable.size() < 3 ) { - // we skip last slot and no point in checking if there's only one other entry - return; - } - // the last slot holds the track the scan stopped at and stays where it is. - // a single bubble pass is not enough: TableTraceRoute() adds the events of a track before the - // track itself, so a track with k scanned events lands k places too far and needs k passes - auto const sortedcount { static_cast( iLast ) }; - auto const inrange = [&]( std::size_t const Index ) { - return Index < sortedcount; }; - // the placements point at semaphor entries; remember which ones, the sort moves them around - auto const *semnextevent { inrange( SemNextIndex ) ? sSpeedTable[ SemNextIndex ].evEvent : nullptr }; - auto const *semnextstopevent { inrange( SemNextStopIndex ) ? sSpeedTable[ SemNextStopIndex ].evEvent : nullptr }; - - std::stable_sort( - std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, - []( TSpeedPos const &Left, TSpeedPos const &Right ) { - return Left.fDist < Right.fDist; } ); - - auto const relocate = [&]( basic_event const *Event, std::size_t &Index ) { - if( Event == nullptr ) { return; } - auto const lookup { - std::find_if( - std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, - [Event]( TSpeedPos const &Point ) { - return Point.evEvent == Event; } ) }; - Index = ( - lookup != std::begin( sSpeedTable ) + sortedcount ? - static_cast( std::distance( std::begin( sSpeedTable ), lookup ) ) : - std::size_t( -1 ) ); - }; - relocate( semnextevent, SemNextIndex ); - relocate( semnextstopevent, SemNextStopIndex ); -} - -//--------------------------------------------------------------------------- - -TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, bool Primary) :// czy ma aktywnie prowadzić? - AIControllFlag( AI ), pVehicle( NewControll ) -{ - if( pVehicle != nullptr ) { - pVehicles[ end::front ] = pVehicle->GetFirstDynamic( end::front ); // pierwszy w kierunku jazdy (Np. Pc1) - pVehicles[ end::rear ] = pVehicle->GetFirstDynamic( end::rear ); // ostatni w kierunku jazdy (końcówki) - } - else { - pVehicles[ end::front ] = nullptr; - pVehicles[ end::rear ] = nullptr; - } - ControllingSet(); // utworzenie połączenia do sterowanego pojazdu - if( mvOccupied != nullptr ) { - iDirectionOrder = mvOccupied->CabActive; // 1=do przodu (w kierunku sprzęgu 0) - VehicleName = mvOccupied->Name; - - if( is_car() ) { // samochody: na podst. http://www.prawko-kwartnik.info/hamowanie.html - // fDriverBraking=0.0065; //mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] - fDriverBraking = 0.03; // coś nie hamują te samochody zbyt dobrze - fDriverDist = 5.0; // 5m - zachowywany odstęp przed kolizją - fVelPlus = 10.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 2.0; // margines prędkości powodujący załączenie napędu - } - else { // pociągi i statki - fDriverBraking = 0.06; // mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] - fDriverDist = 50.0; // 50m - zachowywany odstęp przed kolizją - fVelPlus = 5.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu - } - - // fAccThreshold może podlegać uczeniu się - hamowanie powinno być rejestrowane, a potem analizowane - // próg opóźnienia dla zadziałania hamulca - fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; -/* - // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - if( ( mvOccupied->TrainType == dt_EZT ) - && ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) { - fAccThreshold += 0.10; - } -*/ - } - // TrainParams=NewTrainParams; - // if (TrainParams) - // asNextStop=TrainParams.NextStop(); - // else - TrainParams = TTrainParameters("none"); // rozkład jazdy - // OrderCommand=""; - // OrderValue=0; - OrdersClear(); - - if( true == Primary ) { - iDrivigFlags |= movePrimary; // aktywnie prowadzące pojazd - } - - if( mvOccupied != nullptr ) { - SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych - } - TableClear(); - - // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every - // crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive - // before it starts, so they get no file with only the header - if( WriteLogFlag ) { - begin_physicslog(); - } - - // HACK: give the simulation a small window to potentially replace the AI with a human driver - fActionTime = -5.0; -}; - -TController::~TController() -{ // wykopanie mechanika z roboty -}; - -// zamiana kodu rozkazu na opis -std::string TController::Order2Str(TOrders Order) const { - - if( (Order & Change_direction) != 0 - && Order != Change_direction ) { - // może być nałożona na inną i wtedy ma priorytet - return - Order2Str( Change_direction ) - + " + " - + Order2Str( static_cast( Order & ~Change_direction ) ); - } - switch( Order ) { - case Wait_for_orders: return "Wait_for_orders"; - case Prepare_engine: return "Prepare_engine"; - case Release_engine: return "Release_engine"; - case Change_direction: return "Change_direction"; - case Connect: return "Connect"; - case Disconnect: return "Disconnect"; - case Shunt: return "Shunt"; - case Loose_shunt: return "Loose_shunt"; - case Obey_train: return "Obey_train"; - case Bank: return "Bank"; - case Jump_to_first_order: return "Jump_to_first_order"; - default: return "Undefined"; - } -} - -std::array orderbuffer; - -std::string TController::OrderCurrent() const -{ // pobranie aktualnego rozkazu celem wyświetlenia - auto const order { OrderCurrentGet() }; - // generally prioritize direction change... - if( order & Change_direction && false == TestFlag(iDrivigFlags, moveConnect) ) { - // ...but not in the middle of coupling operation - return STR("Change direction"); - } - - switch( static_cast( order & ~Change_direction ) ) { - case Wait_for_orders: { return STR("Wait for orders"); } - case Prepare_engine: { return STR("Start the engine"); } - case Release_engine: { return STR("Shut down the engine"); } - case Change_direction: { return STR("Change direction"); } - case Connect: { return STR("Couple to consist ahead"); } - case Disconnect: { - if( iVehicleCount < 0 ) { - // done with uncoupling, order should update shortly - return STR("Wait for orders"); - } - // try to provide some task details - auto const count { iVehicleCount }; - - if( iVehicleCount > 1 ) { - std::snprintf( - orderbuffer.data(), orderbuffer.size(), - STR_C("the engine plus %d next vehicles"), // TODO: implement plural forms - count ); - } - auto const countstring { ( - count == 0 ? STR("the engine") : - count == 1 ? STR("the engine plus the next vehicle") : - orderbuffer.data() ) }; - - std::snprintf( - orderbuffer.data(), orderbuffer.size(), - STR_C("Uncouple %s"), - countstring.c_str() ); - return orderbuffer.data(); - } - case Shunt: { return STR("Shunt according to signals"); } - case Loose_shunt: { return STR("Loose shunt according to signals"); } - case Obey_train: { return STR("Drive according to signals and timetable"); } - case Bank: { return STR("Bank consist ahead"); } - default: { return{}; } - } -}; - -void TController::OrdersClear() -{ // czyszczenie tabeli rozkazów na starcie albo po dojściu do końca - OrderPos = 0; - OrderTop = 1; // szczyt stosu rozkazów - for (int b = 0; b < maxorders; b++) - OrderList[b] = Wait_for_orders; -#if LOGORDERS - OrdersDump("OrdersClear", false); -#endif -}; - -void TController::Activation() -{ // umieszczenie obsady w odpowiednim członie, wykonywane wyłącznie gdy steruje AI - iDirection = iDirectionOrder; // kierunek (względem sprzęgów pojazdu z AI) właśnie został ustalony (zmieniony) - if (iDirection) - { // jeśli jest ustalony kierunek - auto *initialvehicle { pVehicle }; -/* - auto const initiallocalbrakelevel { mvOccupied->LocalBrakePosA }; -*/ - auto const initialspringbrakestate { mvOccupied->SpringBrake.Activate }; - // switch off tempomat - SpeedCntrl( 0.0 ); - mvControlling->DecScndCtrl( 2 ); - // reset controls - ZeroSpeed(); - ZeroDirection(); - mvOccupied->CabOccupied = mvOccupied->CabActive; // użytkownik moze zmienić CabOccupied wychodząc - mvOccupied->CabDeactivisation(); // tak jest w Train.cpp - if (TestFlag(pVehicle->MoverParameters->Couplers[iDirectionOrder < 0 ? end::rear : end::front].CouplingFlag, coupling::control)) { - ZeroLocalBrake(); - if( initialspringbrakestate ) { - mvOccupied->SpringBrakeActivate( false ); - } - // odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty - BrakeLevelSet( mvOccupied->BrakeCtrlPos ); //ustawienie zmiennej GBH - } - // przejście AI na drugą stronę EN57, ET41 itp. - // TODO: clean this up, there's lot of redundancy with TMoverParameters::ChangeCab() and TTrain::MoveToVehicle() - { - int movedirection { ( iDirection < 0 ? end::rear : end::front ) }; - auto *targetvehicle { pVehicle->FirstFind( movedirection, coupling::control ) }; - if( pVehicle != targetvehicle ) { - auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami - // move to the new vehicle - targetvehicle->Mechanik = this; // na razie bilokacja - targetvehicle->MoverParameters->SetInternalCommand("", 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) - if( targetvehicle->DirectionGet() != pVehicle->DirectionGet() ) { - // jeśli są przeciwne do siebie to będziemy jechać w drugą stronę względem zasiedzianego pojazdu - iDirection = -iDirection; - } - // move the other driver to our old vehicle - pVehicle->Mechanik = targetvehicledriver; // wsadzamy tego, co ewentualnie był (podwójna trakcja) - // NOTE: having caboccupied != 0 (by swapping in the driver from the target vehicle) may lead to dysfunctional brake - // TODO: investigate and resolve if necessary - pVehicle->MoverParameters->CabOccupied = targetvehicle->MoverParameters->CabOccupied; - if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty - pVehicle->Mechanik->BrakeLevelSet( pVehicle->MoverParameters->BrakeCtrlPos ); - } - // finish driver swap - pVehicle = targetvehicle; - } - } - if (pVehicle != initialvehicle) - { // jeśli zmieniony został pojazd prowadzony - ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT - if( mvOccupied->BrakeCtrlPosNo > 0 - && ( BrakeSystem == TBrakeSystem::Pneumatic - || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { - mvOccupied->LimPipePress = mvOccupied->PipePress; - mvOccupied->ActFlowSpeed = 0; - } - BrakeLevelSet( mvOccupied->BrakeCtrlPos ); - } - if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { - // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy - mvControlling->CurrentSwitch((OrderCurrentGet() & (Shunt | Loose_shunt)) != 0 || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym - } - // Ra: to przełączanie poniżej jest tu bez sensu - mvOccupied->CabOccupied = iDirection; // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) - mvOccupied->CabActivisation(); // uruchomienie kabin w członach - DirectionForward(true); // nawrotnik do przodu - mvOccupied->SpringBrakeActivate( initialspringbrakestate ); -/* - // NOTE: this won't restore local brake if the vehicle has integrated local brake control - // TBD, TODO: fix or let the ai activate the brake again as part of its standard logic? - if (initiallocalbrakelevel > 0.0) // hamowanie tylko jeśli był wcześniej zahamowany (bo możliwe, że jedzie!) - mvOccupied->LocalBrakePosA = initiallocalbrakelevel; // zahamuj jak wcześniej -*/ - if( pVehicle != initialvehicle ) { - auto *train { simulation::Trains.find( initialvehicle->name() ) }; - if( train ) { - train->MoveToVehicle( pVehicle ); - } - } - - CheckVehicles(); // sprawdzenie składu, AI zapali światła - TableClear(); // resetowanie tabelki skanowania torów - } -}; - -void TController::AutoRewident() -{ // autorewident: nastawianie hamulców w składzie - // 1. Zebranie informacji o składzie pociągu, od czoła do końca - std::vector consist; - for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { - consist.emplace_back(brake_setting::describe(*d->MoverParameters, d == pVehicle)); - } - // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did. - // brakes are cut out (Cw-1 §19.9) only in a train (a bank engine's run included), not in a consist being shunted - auto const train{brake_setting::runs_as_train(OrderCurrentGet())}; - auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)}; - // and only at a standstill, the train creeping to a stop included: a check on the run (the order changed mid-run, or - // the train was just formed by coupling, which the AI does above that speed) leaves them to reinspect_brakes() - auto const standstill{brake_setting::at_standstill(mvOccupied->Vel)}; - auto reinspect{false}; - // a light engine counts as a passenger train for the braking below - auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; - // 3. Nastawianie - auto setting{settings.begin()}; - for (auto *d = pVehicles[0]; d != nullptr && setting != settings.end(); d = d->Next(), ++setting) { - if (false == AIControllFlag && d == pVehicle) { - // don't touch human-controlled vehicle, but others are free game - continue; - } - // the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out - if (brake_setting::apply(*d->MoverParameters, *setting, standstill)) { - // a brake to cut out, with the train moving: left for the next standstill - reinspect = true; - } - // potentially release manual brake - d->MoverParameters->DecManualBrakeLevel( ManualBrakePosNo ); - d->MoverParameters->SpringBrake.Activate = false; - } - BrakeReinspectionPending = reinspect; - //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI - if( true == AIControllFlag ) { - // if a human is in charge leave the brake mode up to them, otherwise do as you like - for( int i = 1; i <= 8; i *= 2 ) { - if( ( mvOccupied->BrakeOpModes & i ) > 0 ) { - mvOccupied->BrakeOpModeFlag = i; - } - } - } - - // teraz zerujemy tabelkę opóźnienia hamowania - for (int i = 0; i < BrakeAccTableSize; ++i) - { - fBrake_a0[i+1] = 0; - fBrake_a1[i+1] = 0; - } - - if( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) { - // for uniform behaviour and compatibility with older scenarios set default acceleration table values for shunting - fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; - // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - if( is_emu() - && mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { - fAccThreshold += 0.10; - } - fNominalAccThreshold = fAccThreshold; - } - - BrakeSystem = consist_brake_system(); - // Change the EP fuse state only when AI is in charge, don't fiddle with controls when the user is controlling the vehicle - if (AIControllFlag) { - mvOccupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); - } - - if( OrderCurrentGet() & ( Obey_train | Bank ) ) { - // 4. Przeliczanie siły hamowania - double const velstep = mvOccupied->Vmax * 0.5 / BrakeAccTableSize; - auto *d = pVehicles[0]; // pojazd na czele składu - while (d) { - // a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only; - // the inspector of the earlier releases counted its brake in - auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->MoverParameters)}; - for( int i = 0; i < BrakeAccTableSize && brakes; ++i ) { - fBrake_a0[ i + 1 ] += d->MoverParameters->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); - fBrake_a1[ i + 1 ] += d->MoverParameters->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) ); - } - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - for (int i = 0; i < BrakeAccTableSize; ++i) - { - fBrake_a1[i+1] -= fBrake_a0[i+1]; - fBrake_a0[i+1] /= fMass; - fBrake_a0[i + 1] += 0.001*velstep*(1 + 2 * i); - fBrake_a1[i+1] /= 12 * fMass; - } - - IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (mvOccupied->BrakeDelayFlag & bdelay_G) == 0; - IsCargoTrain = is_train() && (mvOccupied->BrakeDelayFlag & bdelay_G) != 0; - IsHeavyCargoTrain = true == IsCargoTrain && fBrake_a0[1] > 0.4 && iVehicles - ControlledEnginesCount > 0 && fMass / iVehicles > 50000; - - BrakingInitialLevel = IsHeavyCargoTrain ? 1.25 : IsCargoTrain ? 1.25 : 1.00; - - BrakingLevelIncrease = 0.25; - - if( is_emu() ) { - auto ep_factor { ( BrakeSystem == TBrakeSystem::ElectroPneumatic ? 8 : 4 ) }; - if( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { - // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors - fNominalAccThreshold = std::max( -0.60, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); - } - else { - fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); - } - fBrakeReaction = 0.25; - } - else if( is_dmu() ) { - fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - 8 * fBrake_a1[ BrakeAccTableSize ] ); - fBrakeReaction = 0.25; - } - else if (passengertrain) { - fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 4 * fBrake_a1[ BrakeAccTableSize ]; - fBrakeReaction = 1.00 + fLength*0.004; - } - else { - fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 1 * fBrake_a1[ BrakeAccTableSize ]; - fBrakeReaction = 1.00 + fLength*0.005; - } - fAccThreshold = fNominalAccThreshold; - } - -} - -// a brake the inspector had to cut out (Cw-1 §19.9) while the train was moving gets cut out once the train stands. -// a train formed by coupling is looked at as the buffers meet, above the speed the inspector takes for a standstill, -// and with no stop ahead nothing would look at it standing again (eu07/maszyna#350) -void TController::reinspect_brakes() -{ - if (false == BrakeReinspectionPending) { - return; - } - if (false == brake_setting::runs_as_train(OrderCurrentGet())) { - // no longer a train: nothing is cut out in a consist being shunted - BrakeReinspectionPending = false; - return; - } - if (brake_setting::at_standstill(mvOccupied->Vel)) { - // standing, the inspector leaves nothing for later: this clears the flag - AutoRewident(); - } -} - -double TController::ESMVelocity(bool Main) -{ - double fCurrentCoeff = 0.9; - double fFrictionCoeff = 0.85; - double ESMVel = 9999; - int MCPN = mvControlling->MainCtrlActualPos; - int SCPN = mvControlling->ScndCtrlActualPos; - if (Main) - MCPN += 1; - else - SCPN += 1; - if (mvControlling->RList[MCPN].ScndAct < 255 && mvControlling->ScndCtrlActualPos == 0) - SCPN = mvControlling->RList[MCPN].ScndAct; - double FrictionMax = mvControlling->Mass*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; - double IF = mvControlling->Imax; - double MS = 0; - double Fmax = 0; - for (int i = 0; i < 5; i++) - { - MS = mvControlling->MomentumF(IF, IF, SCPN); - Fmax = MS * mvControlling->RList[MCPN].Bn * mvControlling->RList[MCPN].Mn * 2 / mvControlling->WheelDiameter * mvControlling->Transmision.Ratio; - if( Fmax != 0.0 ) { - IF = 0.5 * IF * ( 1 + FrictionMax / Fmax ); - } - else { - // NOTE: gets trimmed to actual highest acceptable value after the loop - IF = std::numeric_limits::max(); - break; - } - } - IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); - double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes; - double pole = mvControlling->MotorParam[SCPN].fi * - std::max(abs(IF) / (abs(IF) + mvControlling->MotorParam[SCPN].Isat) - mvControlling->MotorParam[SCPN].fi0, 0.0); - double Us = abs(mvControlling->EngineVoltage) - IF*R; - double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); - ESMVel = ns * mvControlling->WheelDiameter*M_PI*3.6/mvControlling->Transmision.Ratio; - return ESMVel; -} - -int TController::CheckDirection() { - - int d = mvOccupied->DirAbsolute; // który sprzęg jest z przodu - if( !d ) { - // jeśli nie ma ustalonego kierunku to jedziemy wg aktualnej kabiny - d = mvOccupied->CabActive; - } - return d; -} - -bool TController::CheckVehicles(TOrders user) -{ // sprawdzenie stanu posiadanych pojazdów w składzie i zapalenie świateł - TDynamicObject *p; // roboczy wskaźnik na pojazd - iVehicles = 0; // ilość pojazdów w składzie - auto d = CheckDirection(); - d = d >= 0 ? 0 : 1; // kierunek szukania czoła (numer sprzęgu) - p = pVehicle->FirstFind(d); // pojazd na czele składu - if (!p) - p = pVehicle; - auto *const frontvehicle { p }; // stays the consist head for the rest of this check - pVehicles[end::front] = frontvehicle; - // liczenie pojazdów w składzie i ustalenie parametrów - auto dir = d = 1 - d; // a dalej będziemy zliczać od czoła do tyłu - fLength = 0.0; // długość składu do badania wyjechania za ograniczenie - fMass = 0.0; // całkowita masa do liczenia stycznej składowej grawitacji - fVelMax = -1; // ustalenie prędkości dla składu - bool main = true; // czy jest głównym sterującym - iDrivigFlags |= moveOerlikons; // zakładamy, że są same Oerlikony - // Ra 2014-09: ustawić moveMultiControl, jeśli wszystkie są w ukrotnieniu (i skrajne mają kabinę?) - while (p) - { // sprawdzanie, czy jest głównym sterującym, żeby nie było konfliktu - if( p->Mechanik // jeśli ma obsadę - && p->Mechanik != this && p->Mechanik->iDrivigFlags & movePrimary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający - // a tamten ma priorytet - // TODO: take into account drivers' operating modes, one or more of them might be on banking duty - if (iDrivigFlags & movePrimary && mvOccupied->DirAbsolute && mvOccupied->BrakeCtrlPos >= -1) - { - // jeśli rządzi i ma kierunek - p->Mechanik->primary(false); // dezaktywuje tamtego - p->Mechanik->ZeroLocalBrake(); - p->MoverParameters->BrakeLevelSet(p->MoverParameters->Handle->GetPos(bh_NP)); // odcięcie na zaworze maszynisty - p->Mechanik->BrakeLevelSet(p->MoverParameters->BrakeCtrlPos); // ustawienie zmiennej GBH - } - else - { - main = false; // nici z rządzenia - } - } - ++iVehicles; // jest jeden pojazd więcej - pVehicles[end::rear] = p; // zapamiętanie ostatniego - fLength += p->MoverParameters->Dim.L; // dodanie długości pojazdu - fMass += p->MoverParameters->TotalMass; // dodanie masy łącznie z ładunkiem - fVelMax = min_speed( fVelMax, p->MoverParameters->Vmax ); // ustalenie maksymalnej prędkości dla składu - // reset oerlikon brakes consist flag as different type was detected - if( p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_ESt - && p->MoverParameters->BrakeSubsystem != TBrakeSubSystem::ss_LSt ) { - iDrivigFlags &= ~moveOerlikons; - } - p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony - } - if( main ) { - iDrivigFlags |= movePrimary; // nie znaleziono innego, można się porządzić - } - - ControllingSet(); // ustalenie członu do sterowania (może być inny niż zasiedziany) - - if (iDrivigFlags & movePrimary) - { // jeśli jest aktywnie prowadzącym pojazd, może zrobić własny porządek - auto pantmask = 1; - p = frontvehicle; - // establish ownership and vehicle order - while (p) - { - if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { // jeśli pojazd posiada pantograf, to przydzielamy mu maskę, którą będzie informował o jeździe bezprądowej - p->iOverheadMask = pantmask; - pantmask = pantmask << 1; // przesunięcie bitów, max. 32 pojazdy z pantografami w składzie - } - - d = p->DirectionSet(d ? 1 : -1); // zwraca położenie następnego (1=zgodny,0=odwrócony - względem czoła składu) - p->ctOwner = this; // dominator oznacza swoje terytorium - p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) - } - // with the order established the virtual train manager can do their work - p = frontvehicle; - ControlledEnginesCount = p->MoverParameters->Power > 1.0 ? 1 : 0; - auto hasheaters { false }; - while (p) - { - if( p != pVehicle ) { - if( false == p->is_connected( pVehicle, coupling::control ) ) { - // NOTE: don't set battery in controllable vehicles, let the user/ai do it explicitly - // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... - p->MoverParameters->BatterySwitch( true ); - // enable heating and converter in carriages with can be heated - if( p->MoverParameters->HeatingPower > 0 ) { - p->MoverParameters->HeatingAllow = true; - p->MoverParameters->ConverterSwitch( true, range_t::local ); - hasheaters = true; - } - } - else { - if( p->MoverParameters->Power > 1.0 ) { - ++ControlledEnginesCount; - } - } - } - - if( p->asDestination == "none" ) { - p->DestinationSet( TrainParams.Relation2, TrainParams.TrainName ); // relacja docelowa, jeśli nie było - } - if( AIControllFlag ) { // jeśli prowadzi komputer - p->RaLightsSet( 0, 0 ); // gasimy światła - } - p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) - } - - if( user == Connect && true == main ) { - // HACK: with additional vehicles in the consist ensure all linked vehicles are set to move in the same direction - if( pVehicle->Prev(coupling::control) != nullptr - || pVehicle->Next(coupling::control) != nullptr ) { - sync_consist_reversers(); - } - // potentially sync compartment lighting state for the newly connected vehicles - if( mvOccupied->CompartmentLights.start_type == start_t::manual ) { - mvOccupied->CompartmentLightsSwitchOff( mvOccupied->CompartmentLights.is_disabled ); - mvOccupied->CompartmentLightsSwitch( mvOccupied->CompartmentLights.is_enabled ); - } - } - - // kasowanie pamieci hamowania kontrolnego - if (OrderCurrentGet() & (Shunt | Loose_shunt | Disconnect | Connect | Change_direction)) { - DynamicBrakeTest = 0; - DBT_VelocityBrake - = DBT_VelocityRelease - = DBT_VelocityFinish - = DBT_BrakingTime - = DBT_ReleasingTime - = DBT_MidPointAcc - = 0; - } - - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank ) ) { - // nastawianie hamulca do jazdy pociągowej - AutoRewident(); -/* - if( ( true == TestFlag( iDrivigFlags, moveConnect ) ) - && ( true == TestFlag( OrderCurrentGet(), Connect ) ) ) { - iCoupler = 0; // dalsza jazda manewrowa już bez łączenia - iDrivigFlags &= ~moveConnect; // zdjęcie flagi doczepiania - SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie - JumpToNextOrder(); // wykonanie następnej komendy - } -*/ - } - - // detect push-pull train configurations and mark them accordingly - if( frontvehicle->is_connected( pVehicles[ end::rear ], coupling::control ) ) { - // zmiana czoła przez zmianę kabiny - iDrivigFlags |= movePushPull; - } - else { - // zmiana czoła przez manewry - iDrivigFlags &= ~movePushPull; - } - - // HACK: ensure vehicle lights are active from the beginning, if it had pre-activated battery - if( mvOccupied->LightsPosNo > 0 ) { - pVehicle->SetLights(); - } - if( iEngineActive ) { - // potentially adjust light state - control_lights(); - // custom ai action for disconnect mode: switch off lights on disconnected vehicle(s) - if( is_train() && true == TestFlag(OrderCurrentGet(), Disconnect) && AIControllFlag ) { - // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem - if (mvOccupied->DirActive >= 0) - { // jak ma kierunek do przodu - pVehicles[end::rear]->RaLightsSet(-1, 0); - } - else - { // jak dociska - frontvehicle->RaLightsSet(0, -1); - } - } - // enable door locks - cue_action( driver_hint::consistdoorlockson ); - // potentially enable train heating - { - auto const ispassengertrain { IsPassengerTrain && iVehicles - ControlledEnginesCount > 0 }; - // TODO: replace connection test with connection check between last engine and first car, specifically - auto const isheatingcouplingactive { ( - ControlledEnginesCount == 1 ? - frontvehicle->is_connected( pVehicles[ end::rear ], coupling::heating ) : - true ) }; - auto const isheatingneeded { - (is_emu() || is_dmu() ? true : - (OrderCurrentGet() & (Obey_train | Bank)) == 0 ? false : - false == isheatingcouplingactive ? false : - ispassengertrain ? hasheaters : - false) }; - if( mvControlling->HeatingAllow != isheatingneeded ) { - cue_action( - isheatingneeded ? - driver_hint::consistheatingon : - driver_hint::consistheatingoff ); - } - } - } - - if( user == Connect - || user == Disconnect ) { - // HACK: force route table update on consist change, new consist length means distances to points of interest are now wrong - iTableDirection = 0; - } - } // blok wykonywany, gdy aktywnie prowadzi - return true; -} - -void TController::Lights(int head, int rear) -{ // zapalenie świateł w skłądzie - pVehicles[ end::front ]->RaLightsSet(head, -1); // zapalenie przednich w pierwszym - pVehicles[ end::rear ]->RaLightsSet(-1, rear); // zapalenie końcówek w ostatnim -} - -void TController::DirectionInitial() -{ // ustawienie kierunku po wczytaniu trainset (może jechać na wstecznym - mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) - if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) - { // jeśli na starcie jedzie - iDirection = iDirectionOrder = - mvOccupied->V > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy - DirectionForward(mvOccupied->V * mvOccupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika - } - CheckVehicles(); // sprawdzenie świateł oraz skrajnych pojazdów do skanowania -}; - -void TController::DirectionChange() { - - auto const initialstate { iDirection }; - iDirection = CheckDirection(); - if( iDirection != initialstate ) { - CheckVehicles( Change_direction ); - } -} - -TBrakeSystem TController::consist_brake_system() const { - - if( mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic ) { return mvOccupied->BrakeSystem; } - - auto isepcapable = true; - if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { - // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first - while( true == isepcapable - && vehicle != nullptr ) { - // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself - // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction - isepcapable = (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > -1)) && - (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > -1)); - vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - } - return isepcapable ? TBrakeSystem::ElectroPneumatic : TBrakeSystem::Pneumatic; -} - -std::pair TController::next_speed_limit() const { - - auto const speedlimit { static_cast( VelDesired ) }; - auto nextspeedlimit { speedlimit }; - auto nextspeedlimitdistance { std::numeric_limits::max() }; - if( speedlimit == 0 ) { - // if we aren't allowed to move then any next speed limit is irrelevant - return { nextspeedlimit, nextspeedlimitdistance }; - } - // nie przekraczać rozkladowej - auto const schedulespeedlimit { ( - ( OrderCurrentGet() & ( Obey_train | Bank ) ) != 0 && TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : - ( OrderCurrentGet() & ( Obey_train | Bank ) ) == 0 ? static_cast( fShuntVelocity ) : - -1 ) }; - // first take note of any speed change which should occur after passing potential current speed limit - if( VelLimitLastDist.second > 0 ) { - nextspeedlimit = min_speed( schedulespeedlimit, static_cast( VelLimitLastDist.first ) ); - nextspeedlimitdistance = VelLimitLastDist.second; - } - // then take into account speed change ahead, compare it with speed after potentially clearing last limit - // lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared - auto const noactivespeedlimit { VelLimitLastDist.second < 0 }; - if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) { - if( noactivespeedlimit ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - } - else if( speedatproximitydistance < nextspeedlimit ) { - // if the speed limit ahead is more strict than our current limit, it's important enough to report - if( speedatproximitydistance < VelDesired ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - // otherwise report it only if it's located after our current (lower) limit ends - else if( ActualProximityDist > nextspeedlimitdistance ) { - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - } - else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present - nextspeedlimit = speedatproximitydistance; - nextspeedlimitdistance = ActualProximityDist; - } - // HACK: if our current speed limit extends beyond our scan range don't display potentially misleading information about its length - if( nextspeedlimitdistance >= EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE ) { - nextspeedlimit = speedlimit; - } - // HACK: hide next speed limit if the 'limit' is a vehicle in front of us - else if( ActualProximityDist == std::abs( TrackObstacle() ) ) { - nextspeedlimit = speedlimit; - } - return { nextspeedlimit, nextspeedlimitdistance }; -} - -blackbox::ai_reference TController::ai_reference() const { - - blackbox::ai_reference ai; - ai.target_kmh = static_cast( VelDesired ); - if( auto const [ limit, distance ] { next_speed_limit() }; limit != static_cast( VelDesired ) ) { - ai.next_limit_kmh = static_cast( limit ); - ai.next_limit_distance = static_cast( distance ); - } - ai.acceleration = static_cast( AccDesired ); - ai.braking_distance = static_cast( fBrakeDist ); - ai.timetable_vmax_kmh = ( TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : -1.0f ); - ai.track_vmax_kmh = static_cast( mvOccupied->RunningTrack.Velmax ); - return ai; -} - -void TController::record_station( TSpeedPos const &Point, std::uint8_t const Kind ) const { - - if( Point.evEvent == nullptr ) { return; } - blackbox::station_event entry; - entry.kind = Kind; - auto const row { TrainParams.StationIndex }; - entry.row = static_cast( std::max( 0, row ) ); - entry.station = asNextStop; - entry.position = Point.evEvent->input_location(); - // the stop point may be moved back from the indicator, to where the head of the train is to stop - entry.distance = static_cast( Point.fDist + Point.fMoved ); - entry.stop_at = static_cast( Point.fMoved ); - entry.train_length = static_cast( fLength ); - entry.platform = static_cast( Point.evEvent->input_value( 2 ) ); - if( row >= 0 && row <= TrainParams.StationCount ) { - auto const &line { TrainParams.TimeTable[ row ] }; - entry.arrival = ( line.Ah >= 0 ? static_cast( line.Ah * 60 ) + line.Am : -1.0f ); - entry.departure = ( line.Dh >= 0 ? static_cast( line.Dh * 60 ) + line.Dm : -1.0f ); - } - simulation::Blackbox.station( pVehicles[ end::front ], std::move( entry ) ); -} - -int TController::OrderDirectionChange(int newdir, TMoverParameters *Vehicle) -{ // zmiana kierunku jazdy, niezależnie od kabiny - int testd = newdir; - if (Vehicle->Vel < 0.5) - { // jeśli prawie stoi, można zmienić kierunek, musi być wykonane dwukrotnie, bo za pierwszym razem daje na zero - switch (newdir * Vehicle->CabActive) - { // DirectionBackward() i DirectionForward() to zmiany względem kabiny - case -1: // if (!Vehicle->DirectionBackward()) testd=0; break; - DirectionForward(false); - break; - case 1: // if (!Vehicle->DirectionForward()) testd=0; break; - DirectionForward(true); - break; - } - if (testd == 0) - VelforDriver = -1; // kierunek został zmieniony na żądany, można jechać - } - else // jeśli jedzie - VelforDriver = 0; // ma się zatrzymać w celu zmiany kierunku - if (Vehicle->DirActive == 0 && VelforDriver < Vehicle->Vel) // Ra: to jest chyba bez sensu - IncBrake(); // niech hamuje - if (Vehicle->DirActive == testd * Vehicle->CabActive) - VelforDriver = -1; // można jechać, bo kierunek jest zgodny z żądanym - if (is_emu() && Vehicle->DirActive > 0) - // if () //tylko jeśli jazda pociągowa (tego nie wiemy w momencie odpalania silnika) - Vehicle->DirectionForward(); - // Ra: z przekazaniem do silnikowego - return (int)VelforDriver; // zwraca prędkość mechanika -} - -void TController::WaitingSet(double Seconds) -{ // ustawienie odczekania po zatrzymaniu (ustawienie w trakcie jazdy zatrzyma) - fStopTime = -Seconds; // ujemna wartość oznacza oczekiwanie (potem >=0.0) -} - -void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r) -{ // ustawienie nowej prędkości - WaitingTime = -WaitingExpireTime; // przypisujemy -WaitingExpireTime, a potem porównujemy z zerem - if (NewVel == 0.0) { // jeśli ma stanąć - if (r != stopNone) // a jest powód podany - eStopReason = r; // to zapamiętać nowy powód - } - else { - eStopReason = stopNone; // podana prędkość, to nie ma powodów do stania - // to całe poniżej to warunki zatrąbienia przed ruszeniem - if( is_train() // tylko pociągi trąbią (unimogi tylko na torach, więc trzeba raczej sprawdzać tor) - && (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank | Connect | Prepare_engine)) != 0 // jeśli jedzie w dowolnym trybie - && (iDrivigFlags & moveStartHorn) != 0 // jezeli trąbienie włączone - && (iDrivigFlags & (moveStartHornDone | moveConnect)) == 0 // jeśli nie zatrąbione i nie jest to moment podłączania składu - && mvOccupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) - && ( NewVel >= 1.0 || NewVel < 0.0 ) ) { // o ile prędkość jest znacząca zatrąb po odhamowaniu - iDrivigFlags |= moveStartHornNow; - } - } - VelSignal = NewVel; // prędkość zezwolona na aktualnym odcinku - VelNext = NewVelNext; // prędkość przy następnym obiekcie -} - -double TController::BrakeAccFactor() const -{ - double Factor = 1.0; - - if( fAccThreshold != 0.0 - && AccDesired < 0.0 - && ( ActualProximityDist > fMinProximityDist - || mvOccupied->Vel > VelDesired + fVelPlus ) ) { - Factor += fBrakeReaction * (/*mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * mvOccupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); - } -/* - if (mvOccupied->TrainType == dt_DMU && mvOccupied->Vel > 40 && VelNext<40) - Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (mvOccupied->Vel * mvOccupied->Vel) ); -*/ - return Factor; -} - -void TController::SetDriverPsyche() { - - if (Psyche == Aggressive && OrderCurrentGet() == Obey_train) { - ReactionTime = HardReactionTime; // w zaleznosci od charakteru maszynisty - if (is_car()) { - WaitingExpireTime = 1; // tyle ma czekać samochód, zanim się ruszy - AccPreferred = 3.0; //[m/ss] agresywny - } - else { - WaitingExpireTime = 61; // tyle ma czekać, zanim się ruszy - AccPreferred = HardAcceleration; // agresywny - } - } - else { - ReactionTime = EasyReactionTime; // spokojny - if (is_car()) { - WaitingExpireTime = 3; // tyle ma czekać samochód, zanim się ruszy - AccPreferred = 2.0; //[m/ss] - } - else { - WaitingExpireTime = 65; // tyle ma czekać, zanim się ruszy - AccPreferred = EasyAcceleration; - } - } -} - -// closes the line breaker, or starts the engine, the relays reset first -void TController::close_line_breaker() -{ - cue_action( driver_hint::mastercontrollersetzerospeed ); - // consist-wide ground relay reset - cue_action( driver_hint::maincircuitgroundreset ); - cue_action( driver_hint::tractionnmotoroverloadreset ); - if( mvOccupied->EngineType == TEngineType::DieselEngine ) { - // specjalnie dla SN61 żeby nie zgasł - cue_action( driver_hint::mastercontrollersetidle ); - } - cue_action( driver_hint::linebreakerclose ); -} - -bool TController::PrepareEngine() -{ // odpalanie silnika - // HACK: don't immediately activate inert vehicle in case the simulation is about to replace us with human driver - if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return false; } - - LastReactionTime = 0.0; - ReactionTime = mvOccupied->Vel < 5 ? PrepareTime : EasyReactionTime; // react faster with rolling start - - cue_action( driver_hint::batteryon ); - cue_action( driver_hint::cabactivation); - cue_action( driver_hint::radiofuseon ); - cue_action( driver_hint::radioon ); - - if( has_diesel_engine() ) { - cue_action( driver_hint::oilpumpon ); - PrepareHeating(); - if( true == IsHeatingTemperatureOK ) { - cue_action( driver_hint::fuelpumpon ); - } - else { - cue_action( driver_hint::waittemperaturetoolow ); - } - } - - if( mvControlling->PantographsRequireMains - && IsAnyLineBreakerOpen ) { - // the pantographs rise only through the closed line breaker, which closes without their voltage - PrepareDirection(); - close_line_breaker(); - } - - if( mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector - && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { - // if our pantograph unit isn't a pantograph-devoid fallback - auto const sufficientpantographpressure { ( - is_emu() ? - 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 - 3.5 ) - + 0.1 }; // leeway margin - - if (mvPantographUnit->PantPress < sufficientpantographpressure) { - // załączenie małej sprężarki - if( false == mvPantographUnit->PantAutoValve ) { - // odłączenie zbiornika głównego, bo z nim nie da rady napompować - cue_action( driver_hint::pantographairsourcesetauxiliary ); - } - cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów - if( mvPantographUnit->PantCompFlag ) { - cue_action( driver_hint::waitpantographpressuretoolow ); - } - } - else { - // jeżeli jest wystarczające ciśnienie w pantografach - if( false == mvPantographUnit->bPantKurek3 - || mvPantographUnit->PantPress <= mvPantographUnit->ScndPipePress ) { // kurek przełączony albo główna już pompuje - cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć - } - } - // TODO: make pantograph setup a part of control_pantographs() and call it here instead - if( fOverhead2 == -1.0 && iOverheadDown == 0 ) { - cue_action( driver_hint::pantographsvalveon ); - cue_action( driver_hint::frontpantographvalveon, iDirection >= 0 ? 5 : 0 ); - cue_action( driver_hint::rearpantographvalveon, iDirection >= 0 ? 0 : 5 ); - } - } - - auto const ispoweravailable = - mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector - || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage) > mvControlling->EnginePowerSource.CollectorParameters.MinV; - - bool isready = false; - - if( IsHeatingTemperatureOK - && ispoweravailable ) { - // najpierw ustalamy kierunek, jeśli nie został ustalony - PrepareDirection(); - - if( IsAnyConverterOverloadRelayOpen ) { - // wywalił bezpiecznik nadmiarowy przetwornicy - cue_action( driver_hint::compressoroff ); // TODO: discern whether compressor needs converter to operate - cue_action( driver_hint::converteroff ); - cue_action( driver_hint::primaryconverteroverloadreset ); // reset nadmiarowego - } - if( IsAnyLineBreakerOpen ) { - // activate main circuit or engine - close_line_breaker(); - } - else { - // main circuit or engine is on, set up vehicle devices and controls - if( false == IsAnyConverterOverloadRelayOpen ) { - if( IsAnyConverterPresent ) { - cue_action( driver_hint::converteron ); - } - // w EN57 sprężarka w ra jest zasilana z silnikowego - // TODO: change condition to presence of required voltage type - if( IsAnyCompressorPresent && IsAnyConverterEnabled ) { - cue_action( driver_hint::compressoron ); - } - if( mvControlling->ScndPipePress < 4.5 && mvControlling->VeselVolume > 0.0 ) { - cue_action( driver_hint::waitpressuretoolow ); - } - // enable motor blowers - if( mvOccupied->MotorBlowers[ end::front ].speed != 0 ) { - cue_action( driver_hint::frontmotorblowerson ); - } - if( mvOccupied->MotorBlowers[ end::rear ].speed != 0 ) { - cue_action( driver_hint::rearmotorblowerson ); - } - } - // sync virtual brake state with the 'real' one - if( mvOccupied->BrakeHandle != TBrakeHandle::NoHandle ) { - std::unordered_map const brakepositions{ - { static_cast( mvOccupied->Handle->GetPos( bh_RP ) ), gbh_RP }, - { static_cast( mvOccupied->Handle->GetPos( bh_NP ) ), gbh_NP }, - { static_cast( mvOccupied->Handle->GetPos( bh_FS ) ), gbh_FS } }; - auto const lookup{ brakepositions.find( static_cast( mvOccupied->fBrakeCtrlPos ) ) }; - if( lookup != brakepositions.end() ) { - BrakeLevelSet( lookup->second ); // GBH - } - } - // set up train brake - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_RP ) ) { - if ( !mvOccupied->Handle->Time - || mvOccupied->Handle->GetCP() < mvOccupied->HighPipePress - 0.05 ); - cue_action( driver_hint::trainbrakerelease ); - } - // sync spring brake state across consist - cue_action( - mvOccupied->SpringBrake.Activate ? - driver_hint::springbrakeon : - driver_hint::springbrakeoff ); - } - isready = false == IsAnyConverterOverloadRelayOpen - && mvOccupied->DirActive != 0 - && false == IsAnyLineBreakerOpen - && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) - && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) - && ( mvControlling->ScndPipePress > 4.5 || mvControlling->VeselVolume == 0.0 ); - } - - if( true == isready ) { - // jeśli dotychczas spał teraz nie ma powodu do stania - eAction = TAction::actUnknown; - if( eStopReason == stopSleep ) { - eStopReason = stopNone; - } - // może skanować sygnały i reagować na komendy - iDrivigFlags |= moveActive; - } - - iEngineActive = isready; - - return iEngineActive; -} - -// wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer) -bool TController::ReleaseEngine() { -/* - if( mvOccupied->Vel > 0.01 ) { - VelDesired = 0.0; - AccDesired = std::min( AccDesired, -1.25 ); // hamuj solidnie - if( true == AIControllFlag ) { - // TBD, TODO: make a dedicated braking procedure out of it for potential reuse - ZeroSpeed(); - IncBrake(); - ReactionTime = 0.1; - } - // don't bother with the rest until we're standing still - return false; - } -*/ - // don't bother with the rest until we're standing still - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { return false; } - - LastReactionTime = 0.0; - ReactionTime = PrepareTime; - - cue_action( driver_hint::releaseroff ); - // release train brake if on flats... - if( std::abs( fAccGravity ) < 0.01 ) { - apply_independent_brake_only(); - } - // ... but on slopes engage train brake - else { -// AccDesired = std::min( AccDesired, -0.9 ); - cue_action( driver_hint::trainbrakeapply ); - } - - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( driver_hint::directionnone ); - // zamykanie drzwi - cue_action( driver_hint::doorrightclose ); - cue_action( driver_hint::doorleftclose ); - // heating - cue_action( driver_hint::consistheatingoff ); - // devices - cue_action( driver_hint::compressoroff ); - cue_action( driver_hint::converteroff ); - // line breaker/engine - cue_action( driver_hint::linebreakeropen ); - // pantographs - cue_action( driver_hint::frontpantographvalveoff ); - cue_action( driver_hint::rearpantographvalveoff ); - - if( false == mvControlling->Mains ) { - // finish vehicle shutdown - if( has_diesel_engine() ) { - // heating/cooling subsystem - cue_action( driver_hint::waterheateroff ); - // optionally turn off the water pump as well - if( mvControlling->WaterPump.start_type != start_t::battery ) { - cue_action( driver_hint::waterpumpoff ); - } - // fuel and oil subsystems - cue_action( driver_hint::fuelpumpoff ); - cue_action( driver_hint::oilpumpoff ); - } - // gasimy światła - cue_action( driver_hint::lightsoff ); - // activate parking brake - // TBD: do it earlier? - cue_action( driver_hint::springbrakeon ); - if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake - || mvOccupied->MBrake == true ) { - cue_action( driver_hint::manualbrakon ); - } - // switch off remaining power - cue_action( driver_hint::radiooff ); - cue_action( driver_hint::batteryoff ); - } - - auto const OK { - mvOccupied->DirActive == 0 -// && ( false == IsAnyCompressorEnabled ) -// && ( false == IsAnyConverterEnabled ) - && false == mvControlling->Mains - && false == mvOccupied->Power24vIsAvailable }; - - if (OK) { - // jeśli się zatrzymał - iEngineActive = false; - eStopReason = stopSleep; // stoimy z powodu wyłączenia - eAction = TAction::actSleep; //śpi (wygaszony) - - OrderNext(Wait_for_orders); //żeby nie próbował coś robić dalej - iDrivigFlags &= ~moveActive; // ma nie skanować sygnałów i nie reagować na komendy - TableClear(); // zapominamy ograniczenia - VelSignalLast = -1.0; - } - return OK; -} - -// defined further down, with the braking demand it is used for -static double brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); - -// one step more of the train brake, sized from the consist brake table against the deceleration asked for -bool -TController::increase_train_brake() { - - // dodane dla towarowego - float pos_corr = 0; - - TDynamicObject *d; - d = pVehicles[0]; // pojazd na czele składu - while (d) - { // przeliczanie dodatkowego potrzebnego spadku ciśnienia - if( ( d->MoverParameters->Hamulec->GetBrakeStatus() & b_dmg ) == 0 ) { - pos_corr -= ( std::min( 5.0, d->MoverParameters->Hamulec->GetCRP() ) - 5.0 ) * d->MoverParameters->TotalMass; - } - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - pos_corr = pos_corr / fMass * 2.5; - - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - pos_corr += mvOccupied->Handle->GetCP()*0.2; - - } - if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); - deltaAcc > brake_increase_margin() ) - { - if( /*GBH mvOccupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { - auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH - // HACK: stronger braking to overcome SA134 engine behaviour - if( is_dmu() - && VelNext == 0.0 - && fBrakeDist < 200.0 ) { - BrakeLevelAdd( - fBrakeDist / ActualProximityDist < 0.8 ? - 0.5 : - 1.0 ); - } - return OK; - } - auto const OK { /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH - // brake harder if the acceleration is much higher than desired - /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] ) - && ( mvOccupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { - mvOccupied->BrakeLevelAdd( BrakingLevelIncrease ); - } GBH */ - if( deltaAcc > 2 * fBrake_a1[0] - && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) { - /*mvOccupied->*/BrakeLevelAdd( BrakingLevelIncrease ); - } - return OK; - } - if( BrakeCtrlPosition > 0.0 - && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting - && ( fBrakeHeldTime > ( - mvOccupied->BrakeDelayFlag > bdelay_G ? - mvOccupied->BrakeDelay[ 1 ] : - mvOccupied->BrakeDelay[ 3 ] ) - // a train falling further behind needs no full fill time to be seen not to get enough - || ( ( fShortfall > 0.02 ) - && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { - // the table says the present position is enough, but the brake has had its full fill - // time since the handle last moved and the train is still not slowing down as asked: - // believe the train rather than the table - return BrakeLevelAdd( BrakingLevelIncrease ); - } - return false; -} - -bool TController::IncBrake() -{ // zwiększenie hamowania - auto OK { false }; - auto const bs { - BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? - TBrakeSystem::Pneumatic : - BrakeSystem }; - switch( bs ) { - case TBrakeSystem::Individual: { - if( mvOccupied->LocalBrake == TLocalBrake::ManualBrake ) { - OK = mvOccupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); - } - else { - OK = mvOccupied->IncLocalBrakeLevel( std::floor( 1.5 + std::abs( AccDesired ) ) ); - } - break; - } - case TBrakeSystem::Pneumatic: { - if (bs != mvOccupied->BrakeSystem) - { - while (mvOccupied->BrakeOpModeFlag > bom_PN) - { - mvOccupied->BrakeOpModeFlag >>= 1; - } - } - // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles - auto standalone { true }; - if( mvOccupied->TrainType == dt_ET41 - || mvOccupied->TrainType == dt_ET42 ) { - // NOTE: we're doing simplified checks full of presuptions here. - // they'll break if someone does strange thing like turning around the second unit - if( mvOccupied->Couplers[end::rear].CouplingFlag & coupling::permanent - && mvOccupied->Couplers[end::rear].Connected->Couplers[end::rear].Connected != nullptr ) { - standalone = false; - } - if( mvOccupied->Couplers[end::front].CouplingFlag & coupling::permanent - && mvOccupied->Couplers[end::front].Connected->Couplers[end::front].Connected != nullptr ) { - standalone = false; - } - } - else if( is_dmu() ) { - // enforce use of train brake for DMUs - standalone = false; - } - else if( (OrderCurrentGet() & Loose_shunt) != 0 - && mvOccupied->Vel - VelDesired < fVelPlus + fVelMinus ) { - // try to reduce train brake use in loose shunting mode - standalone = true; - } - else { -/* - standalone = - ( ( mvOccupied->Couplers[ 0 ].CouplingFlag == 0 ) - && ( mvOccupied->Couplers[ 1 ].CouplingFlag == 0 ) ); -*/ - if( pVehicles[ end::front ] != pVehicles[ end::rear ] ) { - // more detailed version, will use manual braking also for coupled sets of controlled vehicles - auto *vehicle = pVehicles[ end::front ]; // start from first - while( true == standalone - && vehicle != nullptr ) { - // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself - // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction - standalone = - (vehicle->MoverParameters->Couplers[end::front].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::front].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::front].Connected->Power > 1)) && - (vehicle->MoverParameters->Couplers[end::rear].Connected == nullptr || - (vehicle->MoverParameters->Couplers[end::rear].CouplingFlag & coupling::control && vehicle->MoverParameters->Couplers[end::rear].Connected->Power > 1)); - vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - } - } - - //standalone = standalone && ( mvControlling->EIMCtrlType == 0 ); - - if( true == standalone && false == ForcePNBrake ) { - if( mvControlling->EIMCtrlType > 0 ) { - OK = IncBrakeEIM(); - } - else { - OK = mvOccupied->IncLocalBrakeLevel( - 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); // hamowanie lokalnym bo luzem jedzie - } - } - else { - if( /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition + 1 == gbh_MAX ) { - if (AccDesired < -1.5) // hamowanie nagle - OK = /*mvOccupied->*/BrakeLevelAdd(1.0); //GBH - else - OK = false; - } - else { - OK = increase_train_brake(); - } - } - if( /*GBH mvOccupied->BrakeCtrlPos*/ - /*GBH mvOccupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && mvOccupied->Hamulec->Releaser() ) { - mvOccupied->BrakeReleaser(0); - } - break; - } - case TBrakeSystem::ElectroPneumatic: { - while( mvOccupied->BrakeOpModeFlag << 1 <= mvOccupied->BrakeOpModes ) { - mvOccupied->BrakeOpModeFlag <<= 1; - } - if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { - if (mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57) { - if (mvOccupied->BrakeCtrlPos < mvOccupied->Handle->GetPos(bh_FB)) - OK = mvOccupied->BrakeLevelAdd(1.0); - } - else { - OK = IncBrakeEIM(); - } - } - else if( mvOccupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; - mvOccupied->BrakeLevelSet( - std::lerp( - mvOccupied->Handle->GetPos( bh_EPR ), - mvOccupied->Handle->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; - } - else if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_EPB ) ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPB ) ); - if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) - mvOccupied->SwitchEPBrake( 1 ); // to nie chce działać - OK = true; - } - else if( ( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) - && ( mvOccupied->EpForce <= 0.0 ) - && ( mvOccupied->EPBrakeControlPowered() ) ) { - // the handle already in the EP brake position, but the EP brake dropped out with the control's - // supply (e.g. the EP fuse off in the running brake test): switch it on again - mvOccupied->SwitchEPBrake( 1 ); - OK = ( mvOccupied->EpForce > 0.0 ); - } - else - OK = false; - break; - } - default: { break; } - } - return OK; -} - -bool TController::IncBrakeEIM() -{ // zwiększenie hamowania - bool OK = false; - switch (mvOccupied->EIMCtrlType) - { - case 0: { - if( mvOccupied->MED_amax != 9.81 ) { - auto const maxpos{mvOccupied->EIMCtrlEmergency ? 0.9 : 1.0 }; - auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low - auto const brakehinted{ -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * AccDesired / fMedAmax }; //preffered by AI - auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; - OK = brakeposition != mvOccupied->LocalBrakePosA; - mvOccupied->LocalBrakePosA = brakeposition; - } - else { - OK = mvOccupied->IncLocalBrakeLevel( 1 ); - } - break; - } - case 1: { - OK = mvOccupied->MainCtrlPos > 0; - if( OK ) - mvOccupied->MainCtrlPos = 0; - break; - } - case 2: { - // the braking position, above the emergency brake one where the controller has it - auto const brakepos{1 + mvOccupied->EIMCtrlEmergencyPositions()}; - OK = mvOccupied->MainCtrlPos > brakepos; - if( OK ) - mvOccupied->MainCtrlPos = brakepos; - break; - } - case 3: { - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { - OK = mvOccupied->MainCtrlPos > 0; - if( OK ) - mvOccupied->MainCtrlPos = 0; - } - else { - OK = mvOccupied->IncLocalBrakeLevel( 1 ); - } - break; - } - default: { - break; - } - } - return OK; -} - -// zmniejszenie siły hamowania -bool TController::DecBrake() { - - auto OK { false }; - auto const bs { - BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? - TBrakeSystem::Pneumatic : - BrakeSystem }; - switch( bs ) { - case TBrakeSystem::Individual: { - auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) }; - OK = mvOccupied->LocalBrake == TLocalBrake::ManualBrake ? mvOccupied->DecManualBrakeLevel(positionchange) : mvOccupied->DecLocalBrakeLevel(positionchange); - break; - } - case TBrakeSystem::Pneumatic: { - auto deltaAcc { -1.0 }; - if( fBrake_a0[0] != 0.0 - || fBrake_a1[0] != 0.0 ) { - auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) }; - // a distributor applied at all gives at least its minimum stage, about what the first position does, so - // 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 && ( false == bUphillRelease ) ) { - // starting uphill the train brake holds the train until the power does - break; - } - if( ( BrakeCtrlPosition > 0.0 ) - && ( uphill_stop_hold() ) ) { - // 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 (deltaAcc < 0 && /*GBH mvOccupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { - OK = /*mvOccupied->*/ BrakeLevelAdd(-0.25); - // if ((deltaAcc < 5 * fBrake_a1[0]) && (mvOccupied->BrakeCtrlPosR >= 1.2)) - // mvOccupied->BrakeLevelAdd(-1.0); - /* if (mvOccupied->BrakeCtrlPosR < 0.74) GBH */ - if (BrakeCtrlPosition < 0.74) - /*mvOccupied->*/ BrakeLevelSet(gbh_RP); - } - if( !OK ) { - OK = mvOccupied->DecLocalBrakeLevel(2); - } - if( !OK ) { - OK = DecBrakeEIM(); - } - /* - // NOTE: disabled, duplicate of AI's behaviour in UpdateSituation() - if (mvOccupied->PipePress < 3.0) - Need_BrakeRelease = true; - */ - break; - } - case TBrakeSystem::ElectroPneumatic: { - if( mvOccupied->EngineType == TEngineType::ElectricInductionMotor ) { - if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { - if( mvOccupied->BrakeCtrlPos > mvOccupied->Handle->GetPos( bh_RP ) ) { - OK = mvOccupied->BrakeLevelAdd( -1.0 ); - } - } - else { - OK = DecBrakeEIM(); - } - } - else if( mvOccupied->Handle->TimeEP == false ) { - auto const initialbrakeposition { mvOccupied->fBrakeCtrlPos }; - auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], mvOccupied->MED_amax ) }; - mvOccupied->BrakeLevelSet( - std::lerp( - mvOccupied->Handle->GetPos( bh_EPR ), - mvOccupied->Handle->GetPos( bh_EPB ), - std::clamp( -AccDesired / AccMax * mvOccupied->AIHintLocalBrakeAccFactor, 0.0, 1.0 ) ) ); - OK = mvOccupied->fBrakeCtrlPos != initialbrakeposition; - } - else { - OK = false; - if (mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos(bh_EPR)) { - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPR)); - OK = true; - } - if (mvOccupied->Handle->GetPos(bh_EPR) - mvOccupied->Handle->GetPos(bh_EPN) < 0.1) { - OK = OK || mvOccupied->SwitchEPBrake(1); - } - } - if( !OK ) { - OK = mvOccupied->DecLocalBrakeLevel( 2 ); - } - break; - } - default: { - break; - } - } - return OK; -} - -void TController::LapBrake() { - - if( mvOccupied->Handle->TimeEP ) { - if( mvOccupied->Handle->GetPos( bh_EPR ) - mvOccupied->Handle->GetPos( bh_EPN ) < 0.1 ) { - mvOccupied->SwitchEPBrake( 0 ); - } - else { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_EPN ) ); - } - } -} - -void TController::ZeroLocalBrake() { - - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl ) { - while( DecBrakeEIM() ) { - ; - } - } - else { - mvOccupied->DecLocalBrakeLevel( LocalBrakePosNo ); - } -} - -bool TController::DecBrakeEIM() -{ // zmniejszenie siły hamowania - bool OK = false; - switch (mvOccupied->EIMCtrlType) - { - case 0: { - if( mvOccupied->MED_amax != 9.81 ) { - auto const desiredacceleration { ( mvOccupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; - auto const brakeposition { std::clamp( -1.0 * mvOccupied->AIHintLocalBrakeAccFactor * desiredacceleration / mvOccupied->MED_amax, 0.0, 1.0 ) }; - OK = brakeposition != mvOccupied->LocalBrakePosA; - mvOccupied->LocalBrakePosA = brakeposition; - } - else { - OK = mvOccupied->DecLocalBrakeLevel( 1 ); - } - break; - } - case 1: { - OK = mvOccupied->MainCtrlPos < 2; - if( OK ) - mvOccupied->MainCtrlPos = 2; - break; - } - case 2: { - auto const neutralpos{mvOccupied->MainCtrlNoPowerPos()}; - OK = mvOccupied->MainCtrlPos < neutralpos; - if( OK ) - mvOccupied->MainCtrlPos = neutralpos; - break; - } - case 3: { - OK = mvOccupied->MainCtrlPos < mvOccupied->MainCtrlMaxDirChangePos; - if( OK ) - mvOccupied->MainCtrlPos = mvOccupied->MainCtrlMaxDirChangePos; - break; - } - } - return OK; -} - -bool TController::IncSpeed() -{ // zwiększenie prędkości; zwraca false, jeśli dalej się nie da zwiększać - auto OK { false }; - switch (mvOccupied->EngineType) - { - case TEngineType::None: // McZapkie-041003: wagon sterowniczy - if (mvControlling->MainCtrlPosNo > 0) // jeśli ma czym kręcić - iDrivigFlags |= moveIncSpeed; // ustawienie flagi jazdy - return false; - case TEngineType::ElectricSeriesMotor: - if (mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący - { - if (fOverhead2 >= 0.0) // a jazda bezprądowa ustawiana eventami (albo opuszczenie) - return false; // to nici z ruszania - if (iOverheadZero) // jazda bezprądowa z poziomu toru ustawia bity - return false; // to nici z ruszania - } - // TODO: move all fVoltage assignments to a single, more generic place - if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { - fVoltage = mvControlling->BatteryVoltage; - } - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || iDrivigFlags & movePress)) { - // youBy polecił dodać 2012-09-08 v367 - // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) - auto const usehighoverloadrelaythreshold{mvControlling->TrainType != dt_ET42 // ET42 uses these variables for different purpose. TODO: fix this - && mvControlling->ImaxHi > mvControlling->ImaxLo && mvOccupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && - iVehicles - ControlledEnginesCount > 0 - // && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) - && mvControlling->Imax * mvControlling->EngineVoltage * ControlledEnginesCount / - (fMass * (fAccGravity == 0.025 ? -0.01 : // prevent div/0 - fAccGravity - 0.025)) < - -2.8}; - // use series mode: - // if high threshold is set for motor overload relay, - // if the power station is heavily burdened, - // if it generates enough traction force - // to build up speed to 30/40 km/h for passenger/cargo train (10 km/h less if going uphill) - auto const sufficienttractionforce{std::abs(mvControlling->Ft) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0}; - auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)}; - auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1}; - auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos > 0 && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1}; - auto const minvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; - auto const maxvoltage{(mvPantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? mvPantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; - auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)}; - auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage || - (true == sufficientacceleration && true == sufficienttractionforce && - mvOccupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); - // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train - // (if there's only one parallel mode configuration it'll be used regardless of current speed) - auto const usefieldshunting = mvControlling->StLinFlag && mvControlling->RList[mvControlling->MainCtrlPos].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && - (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos].Bn == 1 : - true == sufficientacceleration && true == sufficienttractionforce && mvOccupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? - mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1 : - mvControlling->MainCtrlPos == mvControlling->MainCtrlPosNo); - - // if needed enable high threshold for overload relay... - if (mvControlling->TrainType != dt_ET42) - { // ET42 uses these variables for different purpose. TODO: fix this - if (usehighoverloadrelaythreshold) - { - if (mvControlling->Imax < mvControlling->ImaxHi) - { - // to enable this setting we'll typically need the main controller in series mode (which is not guaranteed) - if (mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) - { - if (false == mvControlling->IsScndCtrlNoPowerPos()) - { - mvControlling->DecScndCtrl(2); - } - while (false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->RList[mvControlling->MainCtrlPos].Bn > 1) - { - mvControlling->DecMainCtrl(1); // kręcimy nastawnik jazdy o 1 wstecz - } - } - mvControlling->CurrentSwitch(true); // rozruch wysoki (za to może się ślizgać) - } - } - // ...or disable high threshold for overload relay if no longer needed - else - { - if (mvControlling->IsMotorOverloadRelayHighThresholdOn() && std::fabs(mvControlling->Im) < mvControlling->ImaxLo) - { - mvControlling->CurrentSwitch(false); // rozruch wysoki wyłącz - } - } - } - - double Vs = 99999; - if (usefieldshunting ? mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo : mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo) - { - Vs = ESMVelocity(!usefieldshunting); - } - - if (std::abs(mvControlling->Im) < (fReady < 0.4 ? mvControlling->Imin : mvControlling->IminLo) || mvControlling->Vel > Vs) - { - // Ra: wywalał nadmiarowy, bo Im może być ujemne; jak nie odhamowany, to nie przesadzać z prądem - if (usefieldshunting) - { - // to dać bocznik - // engage the shuntfield only if there's sufficient power margin to draw from - auto const sufficientpowermargin{fVoltage - seriesmodevoltage > (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; - - OK = sufficientpowermargin ? mvControlling->IncScndCtrl(1) : true; - } - else - { - // jeśli ustawiony bocznik to bocznik na zero po chamsku - if (mvControlling->ScndCtrlPos) - { - mvControlling->DecScndCtrl(2); - } - // kręcimy nastawnik jazdy - // don't draw too much power; - // keep from dropping into series mode when entering/using parallel mode, and from shutting down in the series mode - auto const sufficientpowermargin{fVoltage - - (mvControlling->RList[std::min(mvControlling->MainCtrlPos + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) > - (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; - - OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag ? mvControlling->IncMainCtrl(1) : true; - // czekaj na 1 pozycji, zanim się nie włączą liniowe - if (true == mvControlling->StLinFlag) - { - iDrivigFlags |= moveIncSpeed; - } - else - { - iDrivigFlags &= ~moveIncSpeed; - } - - if (mvControlling->Im == 0 && mvControlling->MainCtrlPowerPos() > 1) - { - // brak prądu na dalszych pozycjach - // nie załączona lokomotywa albo wywalił nadmiarowy - Need_TryAgain = true; - } - } - } - else - { - OK = false; - } - } -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - break; - case TEngineType::Dumb: - if (!IsAnyMotorOverloadRelayOpen && (Ready || iDrivigFlags & movePress)) - //{(BrakePress<=0.01*MaxBrakePress)} - { - OK = IncSpeedEIM(); - if (!OK) - OK = mvControlling->IncMainCtrl(1); - if (!OK) - OK = mvControlling->IncScndCtrl(1); - } - break; - case TEngineType::DieselElectric: - if (!IsAnyMotorOverloadRelayOpen && !mvControlling->ControlPressureSwitch && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->StLinFlag) && (Ready || iDrivigFlags & movePress)) { - // youBy polecił dodać 2012-09-08 v367 - // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) - //{(BrakePress<=0.01*MaxBrakePress)} - OK = IncSpeedEIM(); - if (!OK) - OK = mvControlling->IncMainCtrl(1); - if (!OK) - OK = mvControlling->IncScndCtrl(1); - } - break; - case TEngineType::ElectricInductionMotor: - if( !IsAnyMotorOverloadRelayOpen && (Ready || iDrivigFlags & movePress || mvOccupied->ShuntMode) ) { - //{(BrakePress<=0.01*MaxBrakePress)} - OK = IncSpeedEIM(); - if (mvControlling->SpeedCtrl && mvControlling->Mains) - { - // cruise control - auto const couplinginprogress{true == TestFlag(iDrivigFlags, moveConnect) && true == TestFlag(OrderCurrentGet(), Connect)}; - auto const SpeedCntrlVel{(ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : min_speed(VelDesired, VelNext))}; - if (SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity && - SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep)) - { - SpeedCntrl(SpeedCntrlVel); - } - else if (SpeedCntrlVel > 0.1) - { - SpeedCntrl(0.0); - mvControlling->DecScndCtrl(2); - } - } - } - break; - case TEngineType::WheelsDriven: - if (!mvControlling->CabActive) - mvControlling->CabActivisation(); - if (sin(mvControlling->eAngle) > 0) - mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - else - mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - break; - case TEngineType::DieselEngine: - if (mvControlling->ShuntModeAllow) - { // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku) - // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); - } - if (mvControlling->SpeedCtrl && mvControlling->Mains) {// cruise control - auto const couplinginprogress { true == TestFlag(iDrivigFlags, moveConnect) && true == TestFlag(OrderCurrentGet(), Connect) }; - auto const SpeedCntrlVel { ( - ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? - VelDesired : - min_speed( VelDesired, VelNext ) ) }; - if( SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity - && SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep) ) { - SpeedCntrl(SpeedCntrlVel); - } - else if (SpeedCntrlVel > 0.1) { - SpeedCntrl(0.0); - mvControlling->DecScndCtrl( 2 ); - } - } - if (mvControlling->EIMCtrlType > 0) { - if (true == Ready) - { - bool max = mvControlling->Vel > mvControlling->dizel_minVelfullengage - || (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0); - DizelPercentage = max ? 100 : 1; - } - break; - } - else { - if( true == Ready ) { - if( mvControlling->Vel > mvControlling->dizel_minVelfullengage - && mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 ) { - OK = mvControlling->IncMainCtrl( 1 ); - } - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Mn == 0 ) { - OK = mvControlling->IncMainCtrl( 1 ); - } - } - } - // TODO: move this check to a more suitable place, or scrap it - if( false == mvControlling->Mains ) { - SpeedCntrl(0.0); - mvControlling->DecScndCtrl( 2 ); - cue_action( driver_hint::linebreakerclose ); - cue_action( driver_hint::converteron ); - cue_action( driver_hint::compressoron ); - } - break; - } - return OK; -} - -void TController::ZeroSpeed( bool const Enforce ) { - - while( DecSpeed( Enforce ) ) { - ; - } -} - -bool TController::DecSpeed(bool force) -{ // zmniejszenie prędkości (ale nie hamowanie) - bool OK = false; // domyślnie false, aby wyszło z pętli while - switch (mvOccupied->EngineType) - { - case TEngineType::None: // McZapkie-041003: wagon sterowniczy - iDrivigFlags &= ~moveIncSpeed; // usunięcie flagi jazdy - if (force && mvControlling->MainCtrlPosNo > 0) // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania - // McZapkie-041003: wagon sterowniczy, np. EZT - mvControlling->DecMainCtrl(std::min(mvControlling->MainCtrlPowerPos(), 2)); - // mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - return false; - case TEngineType::ElectricSeriesMotor: - OK = mvControlling->DecScndCtrl(2); // najpierw bocznik na zero - if (!OK) - OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 ) ); -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - break; - case TEngineType::Dumb: - case TEngineType::DieselElectric: - OK = mvControlling->DecScndCtrl(2); - if (!OK) - OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 + mvControlling->MainCtrlPowerPos() / 2 ) ); - break; - case TEngineType::ElectricInductionMotor: - OK = DecSpeedEIM(); - break; - case TEngineType::WheelsDriven: - if (!mvControlling->CabActive) - mvControlling->CabActivisation(); - if (sin(mvControlling->eAngle) < 0) - mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - else - mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); - break; - case TEngineType::DieselEngine: - if (mvControlling->EIMCtrlType > 0) - { - DizelPercentage = 0; - if (force) { - SpeedCntrl(0.0); //wylacz od razu tempomat - mvControlling->DecScndCtrl(2); - } - if (VelDesired > 0.1 && mvControlling->SpeedCtrlUnit.MinVelocity > VelDesired) { - SpeedCntrl(0.0); //wylacz od razu tempomat - mvControlling->DecScndCtrl(2); - } - break; - } - - if (mvControlling->Vel > mvControlling->dizel_minVelfullengage) - { - if (mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0) - OK = mvControlling->DecMainCtrl(1); - } - else { - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 - && mvControlling->MainCtrlPowerPos() > 1 ) { - OK = mvControlling->DecMainCtrl( 1 ); - } - } - if (force) { // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania - OK = mvControlling->DecMainCtrl(mvControlling->MainCtrlPowerPos() > 2 ? 2 : 1); - SpeedCntrl(0.0); //wylacz od razu tempomat - mvControlling->DecScndCtrl( 2 ); - } - break; - } - return OK; -}; - -bool TController::IncSpeedEIM() { - - bool OK = false; // domyślnie false, aby wyszło z pętli while - switch( mvControlling->EIMCtrlType ) { - case 0: - OK = mvControlling->IncMainCtrl( 1 ); - break; - case 1: - OK = mvControlling->MainCtrlPos < 6; - if( OK ) { - mvControlling->MainCtrlPos = 6; - } -/* - // TBD, TODO: set position based on desired acceleration? - OK = mvControlling->MainCtrlPos < mvControlling->MainCtrlPosNo; - if( OK ) { - mvControlling->MainCtrlPos = safe_clamp( mvControlling->MainCtrlPos + 1, 6, mvControlling->MainCtrlPosNo ); - } -*/ - break; - case 2: { - auto const powerpos{4 + mvControlling->EIMCtrlEmergencyPositions()}; - OK = mvControlling->MainCtrlPos < powerpos; - if( OK ) { - mvControlling->MainCtrlPos = powerpos; - } - break; - } - } - return OK; -} - -bool TController::DecSpeedEIM( int const Amount ) -{ // zmniejszenie prędkości (ale nie hamowanie) - bool OK = false; // domyślnie false, aby wyszło z pętli while - switch( mvControlling->EIMCtrlType ) { - case 0: { - OK = mvControlling->DecMainCtrl( Amount ); - break; - } - case 1: { - OK = mvControlling->MainCtrlPos > 4; - if( OK ) { - mvControlling->MainCtrlPos = 4; - } - break; - } - case 2: { - if( AccDesired > 0 - && mvControlling->SpeedCtrlUnit.IsActive - && mvControlling->SpeedCtrlUnit.PowerStep > 0 - && mvControlling->SpeedCtrlUnit.DesiredPower > mvControlling->SpeedCtrlUnit.MinPower ) { - mvControlling->SpeedCtrlPowerDec(); - } - else { - auto const holdpos{2 + mvControlling->EIMCtrlEmergencyPositions()}; - OK = mvControlling->MainCtrlPos > holdpos; - if( OK ) { - mvControlling->MainCtrlPos = holdpos; - } - } - break; - } - default: { - break; - } - } - return OK; -} - -void TController::BrakeLevelSet(double b) -{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo - // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego - if (BrakeCtrlPosition == b) - return; // nie przeliczać, jak nie ma zmiany - BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX); - fBrakeHeldTime = 0.0; -} - -bool TController::BrakeLevelAdd(double b) -{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) - // zwraca false, gdy po dodaniu było by poza zakresem - BrakeLevelSet(BrakeCtrlPosition + b); - return b > 0.0 ? BrakeCtrlPosition < gbh_MAX : - BrakeCtrlPosition > -1.0; // true, jeśli można kontynuować -} - -// Ra: regulacja prędkości, wykonywana w każdym przebłysku świadomości AI -// ma dokręcać do bezoporowych i zdejmować pozycje w przypadku przekroczenia prądu -void TController::SpeedSet() { - - if( false == AIControllFlag ) { return; } - - switch (mvOccupied->EngineType) - { - case TEngineType::None: { // McZapkie-041003: wagon sterowniczy - if (mvControlling->MainCtrlPosNo > 0) - { // jeśli ma czym kręcić - // TODO: sprawdzanie innego czlonu //if (!FuseFlagCheck()) - if( ( iDrivigFlags & moveIncSpeed ) == 0 ) { - // przetok rozłączać od razu (no dependency on fActionTime) - while( mvControlling->MainCtrlPos - && mvControlling->DecMainCtrl(1) ) { - ; // na zero - } - if( fActionTime >= 0.0 ) { - fActionTime = -5.0; // niech trochę potrzyma - } -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - } - else { - // jak ma jechać - if( fActionTime < 0.0 ) { break; } - if( false == Ready ) { break; } - - if( mvOccupied->DirActive > 0 ) { - mvOccupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie - } - - if( mvControlling->MainCtrlPos > 0 - && false == mvControlling->StLinFlag ) { - // jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego - mvControlling->DecMainCtrl( 2 ); - } - else { - // ruch nastawnika uzależniony jest od aktualnie ustawionej pozycji - switch( mvControlling->MainCtrlPos ) { - case 0: - if( mvControlling->MainCtrlActualPos ) { - // jeśli kułakowy nie jest wyzerowany to czekać na wyzerowanie - break; - } - mvControlling->IncMainCtrl( 1 ); // przetok; bez "break", bo nie ma czekania na 1. pozycji - case 1: - if( VelDesired >= 20 ) - mvControlling->IncMainCtrl( 1 ); // szeregowa - case 2: - if( VelDesired >= 50 ) - mvControlling->IncMainCtrl( 1 ); // równoległa - case 3: - if( VelDesired >= 80 ) - mvControlling->IncMainCtrl( 1 ); // bocznik 1 - case 4: - if( VelDesired >= 90 ) - mvControlling->IncMainCtrl( 1 ); // bocznik 2 - case 5: - if( VelDesired >= 100 ) - mvControlling->IncMainCtrl( 1 ); // bocznik 3 - } - } - if( mvControlling->MainCtrlPos ) // jak załączył pozycję - { - fActionTime = -5.0; // niech trochę potrzyma -// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania - } - } - } - break; - } - case TEngineType::ElectricSeriesMotor: { -/* - if (Ready || (iDrivigFlags & movePress)) { // o ile może jechać -// if (fAccGravity < -0.10) // i jedzie pod górę większą niż 10 promil - { // procedura wjeżdżania na ekstremalne wzniesienia - if( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) { // a prąd jest większy niż 85% nadmiarowego - if( mvControlling->Imax * mvControlling->EngineVoltage / ( fMass * fAccGravity ) < -2.8 ) // a na niskim się za szybko nie pojedzie - { // włączenie wysokiego rozruchu; - // (I*U)[A*V=W=kg*m*m/sss]/(m[kg]*a[m/ss])=v[m/s]; 2.8m/ss=10km/h - if( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) { // jeśli jedzie na równoległym, to zbijamy do szeregowego, aby włączyć wysoki rozruch - if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik - mvControlling->DecScndCtrl( 2 ); // wyłączyć bocznik, bo może blokować skręcenie NJ - } - do { // skręcanie do bezoporowej na szeregowym - mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz - } - while( ( false == mvControlling->IsMainCtrlNoPowerPos() ) - && ( mvControlling->RList[ mvControlling->MainCtrlPos ].Bn > 1 ) ); // oporowa zapętla - } - if( mvControlling->Imax < mvControlling->ImaxHi ) { // jeśli da się na wysokim - mvControlling->CurrentSwitch( true ); // rozruch wysoki (za to może się ślizgać) - } - if( ReactionTime > 0.1 ) { - ReactionTime = 0.1; // orientuj się szybciej - } - } // if (Im>Imin) - } - if( std::fabs( mvControlling->Im ) > 0.96 * mvControlling->Imax ) {// jeśli prąd jest duży (można 690 na 750) - if( mvControlling->ScndCtrlPos > 0 ) { // jeżeli jest bocznik - mvControlling->DecScndCtrl( 2 ); // zmniejszyć bocznik - } - else { - mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz - } - } - } -// else // gdy nie jedzie ambitnie pod górę - { // sprawdzenie, czy rozruch wysoki jest potrzebny - if( ( mvControlling->Imax > mvControlling->ImaxLo ) - && ( mvOccupied->Vel >= 30.0 ) ) { // jak się rozpędził -// if (fAccGravity > -0.02) // a i pochylenie mnijsze niż 2‰ - mvControlling->CurrentSwitch( false ); // rozruch wysoki wyłącz - } - } - } -*/ - break; - } - case TEngineType::Dumb: { - break; - } - case TEngineType::DieselElectric: { - break; - } - case TEngineType::ElectricInductionMotor: { - break; - } - case TEngineType::DieselEngine: { - // Ra 2014-06: "automatyczna" skrzynia biegów... - auto const &motorparams { mvControlling->MotorParam[ mvControlling->ScndCtrlPos ] }; - auto const velocity { ( mvControlling->ShuntMode ? mvControlling->AnPos : 1.0 ) * mvControlling->Vel }; - if( false == motorparams.AutoSwitch ) { - // gdy biegi ręczne - // jak prędkość większa niż procent maksymalnej na danym biegu, wrzucić wyższy - if( velocity > 0.75 * motorparams.mfi ) { - // ...presuming there is a higher gear - if( mvControlling->ScndCtrlPos < mvControlling->ScndCtrlPosNo ) { - mvControlling->DecMainCtrl( 2 ); - while( mvControlling->IncScndCtrl(1) - && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny - ; - } - } - } - // jak prędkość mniejsza niż minimalna na danym biegu, wrzucić niższy - else if( velocity < motorparams.fi && mvControlling->ScndCtrlPos > 1 ) { - // ... but ensure we don't switch all way down to 0 - mvControlling->DecMainCtrl(2); - while (mvControlling->ScndCtrlPos > 1 // repeat the entry check as we're working in a loop - && mvControlling->DecScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos].mIsat == 0.0) - { // jeśli bieg jałowy to kolejny - ; - } - } - } - break; - } - default: { - break; - } - } // enginetype -}; - -void TController::SpeedCntrl(double DesiredSpeed) -{ - if( false == mvControlling->SpeedCtrl ) { return; } - - if (mvControlling->EngineType == TEngineType::DieselEngine) - { - if (DesiredSpeed < 0.1) { - mvControlling->DecScndCtrl(2); - DesiredSpeed = 0; - } - else if (mvControlling->ScndCtrlPos < 1) { - mvControlling->IncScndCtrl(1); - } - mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); - } - else - if (mvControlling->ScndCtrlPosNo == 1) - { - mvControlling->IncScndCtrl(1); - mvControlling->RunCommand("SpeedCntrl", DesiredSpeed, mvControlling->CabActive); - } - else if (mvControlling->ScndCtrlPosNo > 1 && !mvOccupied->SpeedCtrlTypeTime) - { - int DesiredPos = 1 + mvControlling->ScndCtrlPosNo * ((DesiredSpeed - 1.0) / mvControlling->Vmax); - while( mvControlling->ScndCtrlPos > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop - while( mvControlling->ScndCtrlPos < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop - } - - if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->ScndCtrlPos > 0 ) { - while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower) - { - mvControlling->SpeedCtrlPowerInc(); - } - } -}; - -void TController::SetTimeControllers() -{ - // TBD, TODO: rework this method to use hint system and regardless of driver type - if( false == AIControllFlag || 0 == mvOccupied->CabActive ) { return; } - - //1. Check the type of Main Brake Handle - if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) - { - if (mvOccupied->Handle->Time) - { - auto const pressuredifference { mvOccupied->Handle->GetCP() - ( mvOccupied->HighPipePress - BrakeCtrlPosition * 0.25*mvOccupied->DeltaPipePress ) }; - if (BrakeCtrlPosition > 0 && pressuredifference > 0.05) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FB)); - else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); - else if (BrakeCtrlPosition == 0) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); - else if (BrakeCtrlPosition == -1) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_FS)); - else if (BrakeCtrlPosition == -2) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_NP)); - } - if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a ) { - mvOccupied->BrakeLevelSet( BrakeCtrlPosition ); - } - if( mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_EN57 ) { - if( BrakeCtrlPosition == 0 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_RP ) ); - } - else if( BrakeCtrlPosition == -1 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_FS ) ); - } - else if( BrakeCtrlPosition == -2 ) { - mvOccupied->BrakeLevelSet( mvOccupied->Handle->GetPos( bh_NP ) ); - } - else if( BrakeCtrlPosition > 4.5 ) { - mvOccupied->BrakeLevelSet( 10 ); - } - else if( BrakeCtrlPosition > 3.70 ) { - mvOccupied->BrakeLevelSet( 9 ); - } - else { - mvOccupied->BrakeLevelSet( round( ( BrakeCtrlPosition * 0.4 - 0.1 ) / 0.15 ) ); - } - } - } - //2. Check the type of Secondary Brake Handle - - //3. Check the type od EIMCtrlType -/* - if (mvOccupied->EIMCtrlType > 0) - { - if (mvOccupied->EIMCtrlType == 1) //traxx - { - if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 0; - } - else if (mvOccupied->EIMCtrlType == 2) //elf - { - if (mvOccupied->LocalBrakePosA > 0.95) mvOccupied->MainCtrlPos = 1; - } - } -*/ - if( mvOccupied->UniCtrlIntegratedLocalBrakeCtrl - && mvOccupied->LocalBrakePosA > 0.95 ) { - while( IncBrakeEIM() ) { ; } - } - - //4. Check Speed Control System - if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime) - { - double SpeedCntrlVel = - ActualProximityDist > std::max(50.0, fMaxProximityDist) ? - VelDesired : - min_speed(VelDesired, VelNext); - SpeedCntrlVel = 10 * std::floor(SpeedCntrlVel*0.1); - if (mvOccupied->ScndCtrlPosNo == 4) - { - if (mvOccupied->NewSpeed + 0.1 < SpeedCntrlVel) - mvOccupied->ScndCtrlPos = 3; - if (mvOccupied->NewSpeed - 0.1 > SpeedCntrlVel) - mvOccupied->ScndCtrlPos = 1; - } - } - //5. Check Main Controller in Dizels - //5.1. Digital controller in DMUs with hydro - if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) - { - - DizelPercentage_Speed = DizelPercentage; //wstepnie procenty - auto MinVel{ std::min(mvControlling->hydro_TC_LockupSpeed, mvControlling->Vmax / 6) }; //minimal velocity - //when speed controll unit is active - start with the procedure - if (mvControlling->SpeedCtrl && mvControlling->ScndCtrlPos > 0) { - if (mvControlling->ScndCtrlPos > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) - DizelPercentage_Speed = 101; //keep last position to start - } - else if (VelDesired > MinVel) //more power for faster ride - { - auto const Factor{ 10 * mvControlling->Vmax / (mvControlling->Vmax + 3 * mvControlling->Vel) }; - auto DesiredPercentage{ std::clamp( - VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0, - 0.0, 1.0) }; //correction for reaching desired velocity - if (VelDesired < 0.5 * mvControlling->Vmax //low velocity and reaching desired - && VelDesired - mvControlling->Vel < 10) { - DesiredPercentage = std::min(DesiredPercentage, 0.75); - } - DizelPercentage_Speed = std::round(DesiredPercentage * DizelPercentage); - } - else //slow acceleration during shunting wth minimal velocity - { - DizelPercentage_Speed = std::min(DizelPercentage, mvControlling->Vel < 0.99 * VelDesired ? 1 : 0); - } - - auto const DizelActualPercentage { int(100.4 * mvControlling->eimic_real) }; - - auto const PosInc { mvControlling->MainCtrlPosNo }; - auto PosDec { 0 }; - for( int i = PosInc; i >= 0; --i ) { - if( mvControlling->UniCtrlList[i].SetCtrlVal <= 0 - && mvControlling->UniCtrlList[i].SpeedDown > 0.01 ) { - PosDec = i; - break; - } - } - - if( std::abs( DizelPercentage_Speed - DizelActualPercentage ) > 0 ) { - - if( PosDec > 0 - && ( DizelActualPercentage - DizelPercentage_Speed > 50 - || ( DizelPercentage_Speed == 0 - && DizelActualPercentage > 10 ) ) ) { - //one position earlier should be fast decreasing - PosDec -= 1; - } - auto const DesiredPos { ( - DizelPercentage_Speed > DizelActualPercentage ? - PosInc : - PosDec ) }; - while( mvControlling->MainCtrlPos > DesiredPos ) { mvControlling->DecMainCtrl( 1 ); } - while( mvControlling->MainCtrlPos < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); } - } - if (BrakeCtrlPosition < 0.1) //jesli nie hamuje - mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym - } - else - //5.2. Analog direct controller - if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax > 30) - { - int MaxPos = mvControlling->MainCtrlPosNo; - int MinPos = MaxPos; - for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i; - if (MaxPos > MinPos && mvControlling->MainCtrlPos > 0 && AccDesired > 0) - { - double Factor = 5 * mvControlling->Vmax / (mvControlling->Vmax + mvControlling->Vel); - int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0); - if (DesiredPos > MaxPos) DesiredPos = MaxPos; - if (DesiredPos < MinPos) DesiredPos = MinPos; - if (!mvControlling->SlippingWheels) - { - while (mvControlling->MainCtrlPos > DesiredPos) mvControlling->DecMainCtrl(1); - if (mvControlling->Vel>mvControlling->dizel_minVelfullengage) - while (mvControlling->MainCtrlPos < DesiredPos) mvControlling->IncMainCtrl(1); - } - } - } - // 5.5 universal control for diesel electric vehicles - if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->StLinFlag) - { - // NOTE: partial implementation for speedinc/dec - // TBD, TODO: implement fully? - auto const PosInc{mvControlling->MainCtrlPosNo}; - auto PosKeep{0}; - auto PosDec{0}; - for (int i = PosInc; i >= 0; --i) - { - if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0) - { - if (mvControlling->UniCtrlList[i].SpeedDown == 0.0) - { - PosKeep = i; - } - if (mvControlling->UniCtrlList[i].SpeedDown > 0.01) - { - PosDec = i; - break; - } - } - } - - auto const DesiredPos{(AccDesired > AbsAccS + 0.05 ? PosInc : AccDesired < AbsAccS - 0.05 ? PosDec : PosKeep)}; - - while (mvControlling->MainCtrlPos > DesiredPos && mvControlling->DecMainCtrl(1)) - { - ; - } - while (mvControlling->MainCtrlPos < DesiredPos && mvControlling->IncMainCtrl(1)) - { - ; - } - } - //6. UniversalBrakeButtons - //6.1. Checking flags for Over pressure - if (std::abs(BrakeCtrlPosition - gbh_FS)<0.5) { - UniversalBrakeButtons |= TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload; - } - else { - UniversalBrakeButtons &= ~(TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload); - } - //6.2. Setting buttons - for (int i = 0; i < 3; i++) { - mvOccupied->UniversalBrakeButton(i, UniversalBrakeButtons & mvOccupied->UniversalBrakeButtonFlag[i]); - } -}; - -void TController::CheckTimeControllers() -{ - // TODO: rework this method to use hint system and regardless of driver type - if( false == AIControllFlag || 0 == mvControlling->CabActive ) { return; } - - //1. Check the type of Main Brake Handle - if( BrakeSystem == TBrakeSystem::ElectroPneumatic && mvOccupied->Handle->TimeEP && !ForcePNBrake ) - { - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_EPN)); - } - if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && mvOccupied->Handle->Time ) - { - if (BrakeCtrlPosition > 0) - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_MB)); - else - mvOccupied->BrakeLevelSet(mvOccupied->Handle->GetPos(bh_RP)); - } - //2. Check the type of Secondary Brake Handle - - //3. Check the type od EIMCtrlType - if (mvOccupied->EIMCtrlType > 0) - { - if (mvOccupied->EIMCtrlType == 1) //traxx - { - if (mvOccupied->MainCtrlPos > 3) mvOccupied->MainCtrlPos = 5; - if (mvOccupied->MainCtrlPos < 3) mvOccupied->MainCtrlPos = 1; - } - else if (mvOccupied->EIMCtrlType == 2) //elf - { - auto const emergencypositions{mvOccupied->EIMCtrlEmergencyPositions()}; - if (mvOccupied->eimic > 0) mvOccupied->MainCtrlPos = 3 + emergencypositions; - if (mvOccupied->eimic < 0) mvOccupied->MainCtrlPos = 2 + emergencypositions; - } - } - //4. Check Speed Control System - if (mvOccupied->EngineType == TEngineType::ElectricInductionMotor && mvOccupied->ScndCtrlPosNo > 1 && mvOccupied->SpeedCtrlTypeTime && mvOccupied->ScndCtrlPosNo == 4) - { - mvOccupied->ScndCtrlPos = 2; - } - - //5. Check Main Controller in Dizels - //5.1. Digital controller in DMUs with hydro - if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) - { - int DizelActualPercentage = 100.4 * mvControlling->eimic_real; - int NeutralPos = mvControlling->MainCtrlPosNo - 1; //przedostatnia powinna wstrzymywać - hipoteza robocza - for (int i = mvControlling->MainCtrlPosNo; i >= 0; i--) - if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0 && mvControlling->UniCtrlList[i].SpeedDown < 0.01) //niby zero, ale nie zmniejsza procentów - { - NeutralPos = i; - break; - } - if (BrakeCtrlPosition < 0.1) //jesli nie hamuje - { - if (DizelActualPercentage >= DizelPercentage_Speed && mvControlling->MainCtrlPos > NeutralPos) - while (mvControlling->MainCtrlPos > NeutralPos) mvControlling->DecMainCtrl(1); - if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos < NeutralPos) - while (mvControlling->MainCtrlPos < NeutralPos) mvControlling->IncMainCtrl(1); - mvOccupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos].mode); //zeby nie bruzdzilo machanie zespolonym - } - } -}; - -// otwieranie/zamykanie drzwi w składzie albo (tylko AI) EZT -void TController::Doors( bool const Open, int const Side ) { - // otwieranie drzwi - if( true == Open ) { - - auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; - auto const prawe = 3 - lewe; - // grant door control permission if it's not automatic - // TBD: stricter requirements? - if( true == pVehicle->MoverParameters->Doors.permit_needed ) { - if( Side & prawe ) { - cue_action( driver_hint::doorrightpermiton ); - } - if( Side & lewe ) { - cue_action( driver_hint::doorleftpermiton ); - } - } - // consist-wide remote signals to open doors doors - if( pVehicle->MoverParameters->Doors.open_control == control_t::conductor - || pVehicle->MoverParameters->Doors.open_control == control_t::driver - // NOTE: disabled for mixed controls, leave it up to passengers to open doors by themselves -/* || ( pVehicle->MoverParameters->Doors.open_control == control_t::mixed ) */ ) { - if( Side & prawe ) { - cue_action( driver_hint::doorrightopen ); - } - if( Side & lewe ) { - cue_action( driver_hint::doorleftopen ); - } - } - } - // zamykanie drzwi - else { - // if the doors are already closed and locked then there's nothing to do - if( false == doors_permit_active() - && false == doors_open() ) { - iDrivigFlags &= ~moveDoorOpened; - iDrivigFlags &= ~moveDepartureWarned; - return; - } - - if (mvOccupied->Doors.has_warning && !TestFlag(iDrivigFlags, moveDepartureWarned)) - { - if (!mvOccupied->DepartureSignal) - { - // Not warned yet, not warning yet - start the warning signal. - cue_action( driver_hint::departuresignalon ); // załącenie bzyczka - fActionTime = Random( -0.8, -0.3 ); // 0.3-0.8 second buzzer - return; - } - // Not warned yet, warning now - stop the warning signal and mark it as done. - cue_action( driver_hint::departuresignaloff ); - fActionTime = Random( -0.2, 0.0 ); // Wait just a bit more before departing - iDrivigFlags |= moveDepartureWarned; - return; - } - - if( true == doors_open() && (pVehicle->MoverParameters->Doors.close_control == control_t::conductor || pVehicle->MoverParameters->Doors.close_control == control_t::driver || - pVehicle->MoverParameters->Doors.close_control == control_t::mixed) ) { - // consist-wide remote signals to close doors - cue_action(driver_hint::doorrightclose); - cue_action(driver_hint::doorleftclose); - } - if( true == doors_permit_active() ) { - cue_action( driver_hint::doorrightpermitoff ); - cue_action( driver_hint::doorleftpermitoff ); - } - // if applicable close manually-operated doors in vehicles which may ignore remote signals - { - const auto *vehicle = pVehicles[ end::front ]; // pojazd na czole składu - while( vehicle != nullptr ) { - // zamykanie drzwi w pojazdach - flaga zezwolenia była by lepsza - auto const ismanualdoor { - vehicle->MoverParameters->Doors.auto_velocity == -1.f - && ( vehicle->MoverParameters->Doors.close_control == control_t::passenger - || vehicle->MoverParameters->Doors.close_control == control_t::mixed ) }; - - if( true == ismanualdoor - && ( vehicle->LoadExchangeTime() == 0.f - || vehicle->MoverParameters->Vel > EU07_AI_MOVEMENT ) ) { - vehicle->MoverParameters->OperateDoors( side::right, false, range_t::local ); - vehicle->MoverParameters->OperateDoors( side::left, false, range_t::local ); - } - vehicle = vehicle->Next(); // pojazd podłączony z tyłu (patrząc od czoła) - } - } - fActionTime = Random(-3.5, -1.0); // 1.0-3.5 sec wait - iDrivigFlags &= ~moveDoorOpened; // zostały zamknięte - nie wykonywać drugi raz - iDrivigFlags &= ~moveDepartureWarned; - } -} - -// returns true if any vehicle in the consist has open doors -bool -TController::doors_open() const { - - return IsAnyDoorOpen[side::right] || IsAnyDoorOpen[side::left]; -} - -bool -TController::doors_permit_active() const { - - return IsAnyDoorPermitActive[side::right] || IsAnyDoorPermitActive[side::left]; -} - -void -TController::announce( announcement_t const Announcement ) { - - m_lastannouncement = Announcement; - - if( IsCargoTrain ) { - // cargo trains aren't likely to have announcement systems, so we can skip the procedure altogether - return; - } - - auto *vehicle { pVehicles[ end::front ] }; - while( vehicle ) { - vehicle->announce( Announcement ); - vehicle = vehicle->Next(); - } -} - -void TController::RecognizeCommand() -{ // odczytuje i wykonuje komendę przekazaną lokomotywie - TCommand *c = &mvOccupied->CommandIn; - PutCommand(c->Command, c->Value1, c->Value2, c->Location, stopComm); - c->Command = ""; // usunięcie obsłużonej komendy -} - -void TController::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation, TStopReason reason) -{ // wysłanie komendy przez event PutValues, jak pojazd ma obsadę, to wysyła tutaj, a nie do pojazdu bezpośrednio - // zamiana na współrzędne scenerii - glm::dvec3 sl { -NewLocation.X, NewLocation.Z, NewLocation.Y }; - if (!PutCommand(NewCommand, NewValue1, NewValue2, &sl, reason)) - mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, NewLocation); -} - -bool TController::PutCommand( std::string NewCommand, double NewValue1, double NewValue2, glm::dvec3 const *NewLocation, TStopReason reason ) -{ // analiza komendy - if (NewCommand == "CabSignal") - { // SHP wyzwalane jest przez człon z obsadą, ale obsługiwane przez silnikowy - // nie jest to najlepiej zrobione, ale bez symulacji obwodów lepiej nie będzie - // Ra 2014-04: jednak przeniosłem do rozrządczego - mvOccupied->PutCommand(NewCommand, NewValue1, NewValue2, mvOccupied->Loc); - mvOccupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje - return true; // załatwione - } - - if (NewCommand == "Overhead") - { // informacja o stanie sieci trakcyjnej - fOverhead1 = NewValue1; // informacja o napięciu w sieci trakcyjnej (0=brak drutu, zatrzymaj!) - fOverhead2 = NewValue2; // informacja o sposobie jazdy (-1=normalnie, 0=bez prądu, >0=z - // opuszczonym i ograniczeniem prędkości) - return true; // załatwione - } - - if (NewCommand == "Emergency_brake") // wymuszenie zatrzymania, niezależnie kto prowadzi - { // Ra: no nadal nie jest zbyt pięknie -// SetVelocity(0, 0, reason); - mvOccupied->PutCommand("Emergency_brake", 1.0, 1.0, mvOccupied->Loc); - return true; // załatwione - } - - if (NewCommand.compare(0, 10, "Timetable:") == 0) - { // przypisanie nowego rozkładu jazdy, również prowadzonemu przez użytkownika - NewCommand.erase(0, 10); // zostanie nazwa pliku z rozkładem -#if LOGSTOPS - WriteLog("New timetable for " + pVehicle->asName + ": " + NewCommand); // informacja -#endif - TrainParams = TTrainParameters(NewCommand); // rozkład jazdy - tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika - m_lastexchangestop.clear(); - if (NewCommand != "none") - { - if (false == TrainParams.LoadTTfile( - std::string(Global.asCurrentSceneryPath.c_str()), floor(NewValue2 + 0.5), - NewValue1)) // pierwszy parametr to przesunięcie rozkładu w czasie - { - if (ConversionError == -8) - ErrorLog("Missed timetable: " + NewCommand); - WriteLog("Cannot load timetable file " + NewCommand + "\r\nError " + - std::to_string(ConversionError) + " in position " + std::to_string(TrainParams.StationCount)); - NewCommand = ""; // puste, dla wymiennej tekstury - } - else - { // inicjacja pierwszego przystanku i pobranie jego nazwy - // HACK: clear the potentially set door state flag to ensure door get opened if applicable - if( true == AIControllFlag ) { - // simplified door closing procedure, to sync actual door state with the door state flag - // NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh - if( pVehicle->MoverParameters->Doors.close_control == control_t::driver - || pVehicle->MoverParameters->Doors.close_control == control_t::mixed ) { - pVehicle->MoverParameters->OperateDoors( side::right, false ); - pVehicle->MoverParameters->OperateDoors( side::left, false ); - } - if( pVehicle->MoverParameters->Doors.permit_needed ) { - pVehicle->MoverParameters->PermitDoors( side::right, false ); - pVehicle->MoverParameters->PermitDoors( side::left, false ); - } - } - iDrivigFlags &= ~moveDoorOpened; - - TrainParams.UpdateMTable( simulation::Time, TrainParams.NextStationName ); - TrainParams.StationIndexInc(); // przejście do następnej - TrainParams.StationStart = TrainParams.StationIndex; - asNextStop = TrainParams.NextStop(); - m_lastannouncement = announcement_t::idle; - iDrivigFlags |= movePrimary; // skoro dostał rozkład, to jest teraz głównym -// NewCommand = Global.asCurrentSceneryPath + NewCommand; - auto lookup = - FileExists( - { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, - { ".ogg", ".flac", ".wav" } ); - if( false == lookup.first.empty() ) { - // wczytanie dźwięku odjazdu podawanego bezpośrenido - tsGuardSignal = sound_source( sound_placement::external, 75.f ).deserialize( lookup.first + lookup.second, sound_type::single ); - iGuardRadio = 0; // nie przez radio - } - else { - NewCommand += "radio"; - lookup = - FileExists( - { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, - { ".ogg", ".flac", ".wav" } ); - if( false == lookup.first.empty() ) { - // wczytanie dźwięku odjazdu w wersji radiowej (słychać tylko w kabinie) - tsGuardSignal = sound_source( sound_placement::internal, EU07_SOUND_HANDHELDRADIORANGE ).deserialize( lookup.first + lookup.second, sound_type::single ); - iGuardRadio = iRadioChannel; - } - } - NewCommand = TrainParams.Relation2; // relacja docelowa z rozkładu - } - // jeszcze poustawiać tekstury na wyświetlaczach - TDynamicObject *p = pVehicles[end::front]; - while (p) - { - p->DestinationSet(NewCommand, TrainParams.TrainName); // relacja docelowa - p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) - } - } - if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład (trainset - // nie podaje) - { - auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego - auto d = pVehicle->VectorFront(); // wektor wskazujący przód - iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? - 1 : - -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie - /* - if (NewValue1!=0.0) //jeśli ma jechać - if (iDirectionOrder==0) //a kierunek nie był określony (normalnie określany przez - reardriver/headdriver) - iDirectionOrder=NewValue1>0?1:-1; //ustalenie kierunku jazdy względem sprzęgów - else - if (NewValue1<0) //dla ujemnej prędkości - iDirectionOrder=-iDirectionOrder; //ma jechać w drugą stronę - */ - if (AIControllFlag) // jeśli prowadzi komputer - Activation(); // umieszczenie obsługi we właściwym członie, ustawienie nawrotnika w - // przód - } - /* - else - if (!iDirectionOrder) - {//jeśli nie ma kierunku, trzeba ustalić - if (mvOccupied->V!=0.0) - iDirectionOrder=mvOccupied->V>0?1:-1; - else - iDirectionOrder=mvOccupied->CabOccupied; - if (!iDirectionOrder) iDirectionOrder=1; - } - */ - // jeśli wysyłane z Trainset, to wszystko jest już odpowiednio ustawione - // if (!NewLocation) //jeśli wysyłane z Trainset - // if (mvOccupied->CabActive*mvOccupied->V*NewValue1<0) //jeśli zadana prędkość niezgodna z - // aktualnym kierunkiem jazdy - // DirectionForward(false); //jedziemy do tyłu (nawrotnik do tyłu) - // CheckVehicles(); //sprawdzenie składu, AI zapali światła - TableClear(); // wyczyszczenie tabelki prędkości, bo na nowo trzeba określić kierunek i - // sprawdzić przystanki - OrdersInit(fabs(NewValue1)); // ustalenie tabelki komend wg rozkładu oraz prędkości początkowej - // if (NewValue1!=0.0) if (!AIControllFlag) DirectionForward(NewValue1>0.0); //ustawienie - // nawrotnika użytkownikowi (propaguje się do członów) - // if (NewValue1>0) - // TrainNumber=floor(NewValue1); //i co potem ??? - return true; // załatwione - } - - if (NewCommand == "SetVelocity") - { - if (NewLocation) - vCommandLocation = *NewLocation; - if (NewValue1 != 0.0 && OrderCurrentGet() != Obey_train) - { // o ile jazda - if( false == iEngineActive ) { - // trzeba odpalić silnik najpierw, światła ustawi - OrderNext( Prepare_engine ); - } - OrderNext(Obey_train); // to uruchomić jazdę pociągową (od razu albo po odpaleniu silnika - OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje - } - if (NewValue1 != 0.0) // jeśli jechać - iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone - else - iDrivigFlags |= moveStopHere; // stać do momentu podania komendy jazdy - SetVelocity(NewValue1, NewValue2, reason); // bylo: nic nie rob bo SetVelocity zewnetrznie - // jest wywolywane przez dynobj.cpp - return true; - } - - if( NewCommand == "PointVelocity" ) { - // read by the speed table scan only; when the cell's event runs, there is nothing to do - return true; - } - - if (NewCommand == "SetProximityVelocity") - { - /* - if (SetProximityVelocity(NewValue1,NewValue2)) - if (NewLocation) - vCommandLocation=*NewLocation; - */ - return true; - } - - if (NewCommand == "ShuntVelocity") - { // uruchomienie jazdy manewrowej bądź zmiana prędkości - if (NewLocation) - vCommandLocation = *NewLocation; - // if (OrderList[OrderPos]=Obey_train) and (NewValue1<>0)) - if (false == iEngineActive) - OrderNext(Prepare_engine); // trzeba odpalić silnik najpierw - OrderNext(Shunt); // zamieniamy w aktualnej pozycji, albo dodajey za odpaleniem silnika - if (NewValue1 != 0.0) - { - // if (iVehicleCount>=0) WriteLog("Skasowano ilosć wagonów w ShuntVelocity!"); - iVehicleCount = -2; // wartość neutralna - CheckVehicles(); // zabrać to do OrderCheck() - } - // dla prędkości ujemnej przestawić nawrotnik do tyłu? ale -1=brak ograniczenia !!!! - iDrivigFlags &= ~movePress; // bez dociskania - SetVelocity(NewValue1, NewValue2, reason); - if (NewValue1 != 0.0) - iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone - else - iDrivigFlags |= moveStopHere; // ma stać w miejscu - if (fabs(NewValue1) > 2.0) // o ile wartość jest sensowna (-1 nie jest konkretną wartością) - fShuntVelocity = fabs(NewValue1); // zapamiętanie obowiązującej prędkości dla manewrów - - return true; - } - - if (NewCommand == "Wait_for_orders") - { // oczekiwanie; NewValue1 - czas oczekiwania, -1 = na inną komendę - if (NewValue1 > 0.0 ? NewValue1 > fStopTime : false) - fStopTime = NewValue1; // Ra: włączenie czekania bez zmiany komendy - else - OrderCurrentSet( Wait_for_orders ); // czekanie na komendę (albo dać OrderPos=0) - - return true; - } - - if (NewCommand == "Prepare_engine") - { // włączenie albo wyłączenie silnika (w szerokim sensie) - OrdersClear(); // czyszczenie tabelki rozkazów, aby nic dalej nie robił - if (NewValue1 == 0.0) - OrderNext(Release_engine); // wyłączyć silnik (przygotować pojazd do jazdy) - else if (NewValue1 > 0.0) - OrderNext(Prepare_engine); // odpalić silnik (wyłączyć wszystko, co się da) - // po załączeniu przejdzie do kolejnej komendy, po wyłączeniu na Wait_for_orders - return true; - } - - if (NewCommand == "Change_direction") - { - TOrders o = OrderCurrentGet(); // co robił przed zmianą kierunku - if (false == iEngineActive) - OrderNext(Prepare_engine); // trzeba odpalić silnik najpierw - if (NewValue1 == 0.0) - iDirectionOrder = -iDirection; // zmiana na przeciwny niż obecny - else if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład - // (trainset nie podaje) - { - auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego - auto d = pVehicle->VectorFront(); // wektor wskazujący przód - iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? - 1 : - -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie - // iDirectionOrder=1; else if (NewValue1<0.0) iDirectionOrder=-1; - } - if ( - - iDirectionOrder != iDirection) - OrderNext(Change_direction); // zadanie komendy do wykonania - if (o >= Shunt) // jeśli jazda manewrowa albo pociągowa - OrderNext(o); // to samo robić po zmianie - else if (!o) // jeśli wcześniej było czekanie - OrderNext(Shunt); // to dalej jazda manewrowa - if (mvOccupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie - iDrivigFlags &= ~moveStartHorn; // to bez trąbienia po ruszeniu z zatrzymania - // Change_direction wykona się samo i następnie przejdzie do kolejnej komendy - return true; - } - - if (NewCommand == "Obey_train") { - if( false == iEngineActive ) { - OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw - } - OrderNext( Obey_train ); - // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? - OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje - - return true; - } - - if (NewCommand == "Bank") { - if( false == iEngineActive ) { - OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw - } - OrderNext( Bank ); - // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? - OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje - - return true; - } - - if( NewCommand == "Shunt" || NewCommand == "Loose_shunt" ) - { // NewValue1 - ilość wagonów (-1=wszystkie); NewValue2: 0=odczep, 1..63=dołącz, -1=bez zmian - //-3,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać w trybie pociągowym - //-2,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać - //-2, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i czekać - //-1,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać w powrotną stronę - //-1, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać dalej - //-1, 0 - tryb manewrowy bez zmian (odczepianie z pozostawieniem wagonów nie ma sensu) - // 0, 0 - odczepienie lokomotywy - // x,-y - podłączyć się do składu (sprzęgiem y>=1), a następnie odczepić i zabrać (x) wagonów - // 1, 0 - odczepienie lokomotywy z jednym wagonem - iDrivigFlags &= ~moveStopHere; // podjeżanie do semaforów zezwolone - if( false == iEngineActive ) { - OrderNext( Prepare_engine ); // trzeba odpalić silnik najpierw - } - if (NewValue2 != 0) // jeśli podany jest sprzęg - { - iCoupler = std::floor( std::abs( NewValue2 ) ); // jakim sprzęgiem - OrderNext(Connect); // najpierw połącz pojazdy - if (NewValue1 >= 0.0) // jeśli ilość wagonów inna niż wszystkie - { // to po podpięciu należy się odczepić - iDirectionOrder = -iDirection; // zmiana na ciągnięcie - OrderPush(Change_direction); // najpierw zmień kierunek, bo odczepiamy z tyłu - OrderPush(Disconnect); // a odczep już po zmianie kierunku - if( NewValue2 > 0.0 - && NewCommand == "Loose_shunt" ) { - // after decoupling continue pushing in the original direction - // NOTE: for backward compatibility this option isn't supported for basic shunting mode - iDirectionOrder = iDirection; // back to pushing - OrderPush( Change_direction ); - } - } - else if (NewValue2 < 0.0) // jeśli wszystkie, a sprzęg ujemny, to tylko zmiana kierunku po podczepieniu - { // np. Shunt -1 -3 - iDirectionOrder = -iDirection; // jak się podczepi, to jazda w przeciwną stronę - OrderNext(Change_direction); - } - WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie - } - else { // if (NewValue2==0.0) //zerowy sprzęg - if( NewValue1 >= 0.0 ) { - // jeśli ilość wagonów inna niż wszystkie będzie odczepianie, - // ale jeśli wagony są z przodu, to trzeba najpierw zmienić kierunek - if( mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::rear : end::front].Connected == nullptr // z tyłu nic - && mvOccupied->Couplers[mvOccupied->DirAbsolute > 0 ? end::front : end::rear].Connected != nullptr ) { // a z przodu skład - iDirectionOrder = -iDirection; // zmiana na ciągnięcie - OrderNext( Change_direction ); // najpierw zmień kierunek (zastąpi Disconnect) - OrderPush( Disconnect ); // a odczep już po zmianie kierunku - } - else if( mvOccupied->Couplers[ mvOccupied->DirAbsolute > 0 ? end::rear : end::front ].Connected != nullptr ) { // z tyłu coś - OrderNext( Disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów - } - else { - // both couplers empty - // NOTE: this condition implements legacy behavior (mis)used by some scenarios to keep vehicle idling without moving - SetVelocity( 0, 0, stopJoin ); - iDrivigFlags |= moveStopHere; // nie podjeżdżać do semafora, jeśli droga nie jest wolna - } - WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie - } - } - if (NewValue1 == -1.0) { - iDrivigFlags &= ~moveStopHere; // ma jechać - WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać - } - if( NewValue1 < -1.5 ) { // jeśli -2/-3, czyli czekanie z ruszeniem na sygnał - iDrivigFlags |= moveStopHere; // nie podjeżdżać do semafora, jeśli droga nie jest wolna - } - // (nie dotyczy Connect) - if( NewValue1 < -2.5 ) { // jeśli -3 to potem jazda pociągowa - OrderNext( NewCommand == "Shunt" ? Obey_train : Bank ); - } - else { // otherwise continue shunting - OrderNext( NewCommand == "Shunt" ? Shunt : Loose_shunt ); - } - CheckVehicles(); // sprawdzić światła - iVehicleCount = std::floor( NewValue1 ); - - return true; - } - - if( NewCommand == "Jump_to_first_order" ) { - JumpToFirstOrder(); - return true; - } - - if (NewCommand == "Jump_to_order") - { - if( NewValue1 == -1.0 ) { - JumpToNextOrder(); - } - else if (NewValue1 >= 0 && NewValue1 < maxorders) - { - OrderPos = floor(NewValue1); - if( !OrderPos ) { - // zgodność wstecz: dopiero pierwsza uruchamia - OrderPos = 1; - } -#if LOGORDERS - OrdersDump("Jump_to_order"); -#endif - } - return true; - } - - if (NewCommand == "Warning_signal") - { - if( NewValue1 > 0 && NewValue2 > 0 ) { - fWarningDuration = NewValue1; // czas trąbienia - cue_action( driver_hint::hornon, NewValue2 ); // horn combination flag - simulation::Blackbox.horn_requested( - pVehicles[ end::front ], NewValue1, NewValue2, NewLocation != nullptr ? *NewLocation : pVehicles[ end::front ]->GetPosition() ); - } - return true; - } - - if (NewCommand == "Radio_channel") { - // wybór kanału radiowego (którego powinien używać AI, ręczny maszynista musi go ustawić sam) - if (NewValue1 >= 0) { - // wartości ujemne są zarezerwowane, -1 = nie zmieniać kanału - if( AIControllFlag ) { - iRadioChannel = NewValue1; - } - if( iGuardRadio ) { - // kierownikowi też zmienić - iGuardRadio = NewValue1; - } - } - // NewValue2 może zawierać dodatkowo oczekiwany kod odpowiedzi, np. dla W29 "nawiązać - // łączność radiową z dyżurnym ruchu odcinkowym" - return true; - } - - if( NewCommand == "SetLights" ) { - // set consist lights pattern hints - m_lighthints[ end::front ] = static_cast( NewValue1 ); - m_lighthints[ end::rear ] = static_cast( NewValue2 ); - if( true == TestFlag( OrderCurrentGet(), Obey_train ) ) { - // light hints only apply in the obey_train mode - CheckVehicles(); - } - return true; - } - - if (NewCommand == "SetSignal") { - TSignals signal = (TSignals)std::lrint(NewValue1); - - for (int i = Signal_START; i <= Signal_MAX; i++) - iDrivigFlags &= ~(1 << i); - - if (NewValue2 > 0.5) - iDrivigFlags |= 1 << (uint32_t)signal; - else - CheckVehicles(); // restore light state - } - - return false; // nierozpoznana - wysłać bezpośrednio do pojazdu -}; - -std::string_view TController::physicslog_header() { - // the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are: - // a new one goes at the end - return "Time[s] Velocity[m/s] Acceleration[m/ss] " - "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " - "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " - "MCP SCP BCP LBP Direction Command CVal1 CVal2 " - "Security Wheelslip " - "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " - "VehicleVelocity[km/h]" - "\r\n"; -} - -std::string TController::physicslog_line() const { - std::ostringstream line; - line << std::fixed << std::setprecision( 4 ) - << ElapsedTime << " " - << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) << " " - << mvControlling->AccS << " " - << mvOccupied->Couplers[1].Dist << " " - << mvOccupied->Couplers[1].CForce << " " - << mvOccupied->Ft << " " - << mvOccupied->Ff << " " - << mvOccupied->Fb << " " - << mvOccupied->BrakePress << " " - << mvOccupied->PipePress << " " - << mvControlling->Im << " " - << int(mvControlling->MainCtrlPos) << " " - << int(mvControlling->ScndCtrlPos) << " " - << mvOccupied->fBrakeCtrlPos << " " - << mvOccupied->LocalBrakePosA << " " - << int(mvControlling->DirActive) << " " - << ( mvOccupied->CommandIn.Command.empty() ? "none" : mvOccupied->CommandIn.Command.c_str() ) << " " - << mvOccupied->CommandIn.Value1 << " " - << mvOccupied->CommandIn.Value2 << " " - << int(mvControlling->SecuritySystem.is_blinking()) << " " - << int(mvControlling->SlippingWheels) << " " - << mvControlling->dizel_heat.Ts << " " - << mvControlling->dizel_heat.To << " " - << mvControlling->dizel_heat.temperatura1 << " " - << mvControlling->dizel_heat.temperatura2 << " " - // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid - << mvOccupied->V * 3.6 - << "\r\n"; - return line.str(); -} - -void TController::begin_physicslog() -{ - // physicslog/.dat, written every two seconds along with the logs of the other drivers -#if LOGPRESS == 0 - PhysicsLogs.begin( VehicleName, physicslog_header() ); -#endif -#if LOGPRESS == 1 - PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); -#endif - PhysicsLogBegun = true; -} - -void TController::PhysicsLog() -{ // zapis logu - na razie tylko wypisanie parametrów -#if LOGPRESS == 0 - PhysicsLogs.append( VehicleName, physicslog_line() ); -#endif -#if LOGPRESS == 1 - std::ostringstream line; - line << ElapsedTime << "\t" << fabs(11.31 * mvOccupied->WheelDiameter * mvOccupied->nrot) - << "\t"; - line << mvControlling->AccS << "\t"; - line << mvOccupied->PipePress << "\t" << mvOccupied->CntrlPipePress << "\t" - << mvOccupied->BrakePress << "\t"; - line << mvOccupied->Volume << "\t" << mvOccupied->Hamulec->GetCRP() << "\n"; - PhysicsLogs.append( VehicleName, line.str() ); -#endif -}; - -void -TController::Update( double const Timedelta ) { - // uruchamiać przynajmniej raz na sekundę - if( ( iDrivigFlags & movePrimary ) == 0 ) { return; } // pasywny nic nie robi - if( false == simulation::is_ready ) { return; } - - update_timers( Timedelta ); - update_logs( Timedelta ); - - auto const reactiontime { std::min( ReactionTime, 2.0 ) }; - - if( LastReactionTime < reactiontime ) { return; } - LastReactionTime -= reactiontime; -/* - // TBD, TODO: put this in an appropriate place, or get rid of it - // NOTE: this section moved all cars to the edge of their respective roads - // it may have some use eventually for collision avoidance, - // but when enabled all the time it produces silly effect - if( mvOccupied->Vel > 1.0 ) { - // przy prowadzeniu samochodu trzeba każdą oś odsuwać oddzielnie, inaczej kicha wychodzi - if (mvOccupied->CategoryFlag & 2) // jeśli samochód - // if (fabs(mvOccupied->OffsetTrackH)Dim.W) //Ra: szerokość drogi tu powinna być? - if (!mvOccupied->ChangeOffsetH(-0.01 * mvOccupied->Vel * dt)) // ruch w poprzek drogi - mvOccupied->ChangeOffsetH(0.01 * mvOccupied->Vel * dt); // Ra: co to miało być, to nie wiem - } -*/ - update_hints(); - // main ai update routine - determine_consist_state(); - determine_braking_distance(); - determine_proximity_ranges(); - // vicinity check - auto const awarenessrange { - std::max( - 750.0, - mvOccupied->Vel > EU07_AI_MOVEMENT ? - 400 + fBrakeDist : - 30.0 * fDriverDist ) }; // 1500m dla stojących pociągów; - if( is_active() ) { - scan_route( awarenessrange ); - } - scan_obstacles( awarenessrange ); - // generic actions - control_security_system( reactiontime ); - if( iEngineActive ) { - control_wheelslip(); - control_horns( reactiontime ); - control_pantographs(); - if( fActionTime > 0.0 ) { - // potentially delayed and/or low priority actions - control_lights(); - control_doors(); - control_compartment_lights(); - } - } - CheckTimeControllers(); - // external command actions - UpdateCommand(); - // mode specific actions - handle_engine(); - handle_orders(); - // a brake the wagon inspector left to cut out while the train was moving - reinspect_brakes(); - // situational velocity and acceleration adjustments - pick_optimal_speed( awarenessrange ); - if( iEngineActive ) { - control_tractive_and_braking_force(); - } - SetTimeControllers(); -} - -// configures vehicle heating given current situation; returns: true if vehicle can be operated normally, false otherwise -bool -TController::PrepareHeating() { - - switch( mvControlling->EngineType ) { - - case TEngineType::DieselElectric: - case TEngineType::DieselEngine: { - - auto const &heat { mvControlling->dizel_heat }; - - // determine whether there's need to enable the water heater - // if the heater has configured maximum temperature, it'll disable itself automatically, so we can leave it always running - // otherwise enable the heater only to maintain minimum required temperature - auto const lowtemperature { ( - ( heat.water.config.temp_min > 0 && heat.temperatura1 < heat.water.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) - || ( heat.water_aux.config.temp_min > 0 && heat.temperatura2 < heat.water_aux.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) - || ( heat.oil.config.temp_min > 0 && heat.To < heat.oil.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) ) }; - auto const heateron { ( - mvControlling->WaterHeater.config.temp_max > 0 - || true == lowtemperature ) }; - if( true == heateron ) { - // make sure the water pump is running before enabling the heater - if( false == mvControlling->WaterPump.is_active ) { - cue_action( driver_hint::waterpumpbreakeron ); - cue_action( driver_hint::waterpumpon ); - } - if( true == mvControlling->WaterPump.is_active ) { - cue_action( driver_hint::waterheaterbreakeron ); - cue_action( driver_hint::waterheateron ); - cue_action( driver_hint::watercircuitslinkon ); - } - } - else { - // no need to heat anything up, switch the heater off - cue_action( driver_hint::watercircuitslinkoff ); - cue_action( driver_hint::waterheateroff ); - cue_action( driver_hint::waterheaterbreakeroff ); - // optionally turn off the water pump as well - if( mvControlling->WaterPump.start_type != start_t::battery ) { - cue_action( driver_hint::waterpumpoff ); - cue_action( driver_hint::waterpumpbreakeroff ); - } - } - - IsHeatingTemperatureTooLow = lowtemperature; - break; - } - default: { - IsHeatingTemperatureTooLow = false; - break; - } - } - // TBD, TODO: potentially pay attention to too high temperature as well? - IsHeatingTemperatureOK = false == IsHeatingTemperatureTooLow; - - return IsHeatingTemperatureOK; -} - -void -TController::PrepareDirection() { - - if( iDirection == 0 ) { - // jeśli nie ma ustalonego kierunku - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { // ustalenie kierunku, gdy stoi - iDirection = mvOccupied->CabActive; // wg wybranej kabiny -/* - if( iDirection == 0 ) { - // jeśli nie ma ustalonego kierunku - if( mvOccupied->Couplers[ end::rear ].Connected == nullptr ) { - // jeśli z tyłu nie ma nic - iDirection = -1; // jazda w kierunku sprzęgu 1 - } - if( mvOccupied->Couplers[ end::front ].Connected == nullptr ) { - // jeśli z przodu nie ma nic - iDirection = 1; // jazda w kierunku sprzęgu 0 - } - } -*/ - } - else { - // ustalenie kierunku, gdy jedzie - iDirection = mvOccupied->V >= 0 ? 1 : // jazda w kierunku sprzęgu 0 - -1; // jazda w kierunku sprzęgu 1 - } - } - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( - iDirection > 0 ? - driver_hint::directionforward : - driver_hint::directionbackward ); -} - -void TController::JumpToNextOrder( bool const Ignoremergedchangedirection ) -{ // wykonanie kolejnej komendy z tablicy rozkazów - if (auto const currentorder { OrderCurrentGet() }; currentorder != Wait_for_orders) - { - if( (currentorder & Change_direction) != 0 // jeśli zmiana kierunku - && currentorder != Change_direction && false == Ignoremergedchangedirection ) { // ale nałożona na coś - - // usunięcie zmiany kierunku z innej komendy - OrderCurrentSet( TOrders(currentorder & ~Change_direction) ); - OrderCheck(); - return; - } - if (OrderPos < maxorders - 1) - ++OrderPos; - else - OrderPos = 0; - } - OrderCheck(); -#if LOGORDERS - OrdersDump("JumpToNextOrder"); // normalnie nie ma po co tego wypisywać -#endif -}; - -void TController::JumpToFirstOrder() -{ // taki relikt - OrderPos = 1; - if (OrderTop == 0) - OrderTop = 1; - OrderCheck(); -#if LOGORDERS - OrdersDump("JumpToFirstOrder"); // normalnie nie ma po co tego wypisywać -#endif -}; - -void TController::OrderCheck() -{ // reakcja na zmianę rozkazu - - if( OrderCurrentGet() != Obey_train ) { - // reset light hints - m_lighthints[ end::front ] = m_lighthints[ end::rear ] = -1; - } - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect | Obey_train | Bank ) ) { - CheckVehicles(); // sprawdzić światła - } - if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect ) ) { - // HACK: ensure consist doors will be closed on departure - iDrivigFlags |= moveDoorOpened; - } - auto const currentorder { OrderCurrentGet() }; - if (currentorder & Change_direction) // może być nałożona na inną i wtedy ma priorytet - iDirectionOrder = -iDirection; // trzeba zmienić jawnie, bo się nie domyśli - else if (currentorder == Obey_train) - iDrivigFlags |= moveStopPoint; // W4 są widziane - else if (currentorder == Disconnect) - iVehicleCount = iVehicleCount < 0 ? 0 : iVehicleCount; // odczepianie lokomotywy - else if (currentorder == Connect) - iDrivigFlags &= ~moveStopPoint; // podczas jazdy na połączenie nie zwracać uwagi na W4 - else if (currentorder == Wait_for_orders) - OrdersClear(); // czyszczenie rozkazów i przeskok do zerowej pozycji -} - -void TController::OrderNext(TOrders NewOrder) -{ // ustawienie rozkazu do wykonania jako następny - if (OrderCurrentGet() == NewOrder) - return; // jeśli robi to, co trzeba, to koniec - if (!OrderPos) - OrderPos = 1; // na pozycji zerowej pozostaje czekanie - OrderTop = OrderPos; // ale może jest czymś zajęty na razie - if (NewOrder >= Shunt) // jeśli ma jechać - { // ale może być zajęty chwilowymi operacjami - while (OrderTop >= 0 && OrderTop < maxorders - 1 - && OrderList[OrderTop] != Wait_for_orders && OrderList[OrderTop] < Shunt) // jeśli coś robi - ++OrderTop; // pomijamy wszystkie tymczasowe prace - } - else - { // jeśli ma ustawioną jazdę, to wyłączamy na rzecz operacji - while (OrderTop >= 0 && OrderTop < maxorders - 1 - && OrderList[OrderTop] != Wait_for_orders && OrderList[OrderTop] < Shunt && OrderList[OrderTop] != NewOrder) // jeśli coś robi - ++OrderTop; // pomijamy wszystkie tymczasowe prace - } - if (OrderTop < 0 || OrderTop >= maxorders) - { - ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); - return; - } - OrderList[OrderTop++] = NewOrder; // dodanie rozkazu jako następnego -#if LOGORDERS - OrdersDump( "OrderNext" ); // normalnie nie ma po co tego wypisywać -#endif -} - -void TController::OrderPush(TOrders NewOrder) -{ // zapisanie na stosie kolejnego rozkazu do wykonania - if (OrderPos == OrderTop && OrderCurrentGet() < Shunt) // jeśli miałby być zapis na aktalnej pozycji - // ale nie jedzie - ++OrderTop; - // niektóre operacje muszą zostać najpierw dokończone => zapis na kolejnej - if (OrderTop < 0 || OrderTop >= maxorders) - { - ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); - return; - } - if (OrderList[OrderTop] != NewOrder) // jeśli jest to samo, to nie dodajemy - OrderList[OrderTop++] = NewOrder; // dodanie rozkazu na stos -#if LOGORDERS - OrdersDump( "OrderPush: [" + Order2Str( NewOrder ) + "]" ); // normalnie nie ma po co tego wypisywać -#endif -} - -void TController::OrdersDump( std::string const Neworder, bool const Verbose ) -{ // wypisanie kolejnych rozkazów do logu - WriteLog( "New order for [" + pVehicle->asName + "]: " + Neworder ); - if( false == Verbose ) { return; } - for (int b = 0; b < maxorders; ++b) - { - WriteLog( ( OrderPos == b ? ">" : " " ) + (std::to_string(b) + ": " + Order2Str(OrderList[b]))); - if (b && OrderList[b] == Wait_for_orders) // z wyjątkiem pierwszej pozycji - // jeśli końcowa komenda - break; - // dalej nie trzeba - } -}; - -void TController::OrdersInit(double fVel) -{ // wypełnianie tabelki rozkazów na podstawie rozkładu - // ustawienie kolejności komend, niezależnie kto prowadzi - OrdersClear(); // usunięcie poprzedniej tabeli - OrderPush(Prepare_engine); // najpierw odpalenie silnika - if (TrainParams.StationCount == 0) - { // brak rozkładu to jazda manewrowa -// if (fVel > 0.05) // typowo 0.1 oznacza gotowość do jazdy, 0.01 tylko załączenie silnika - OrderPush(Shunt); // jeśli nie ma rozkładu, to manewruje - } - else - { // jeśli z rozkładem, to jedzie na szlak - if (fVel > 0.0 && fVel < 0.02) - OrderPush(Shunt); // dla prędkości 0.01 włączamy jazdę manewrową - else if (TrainParams.DirectionChange() ? // jeśli obrót na pierwszym przystanku - (iDrivigFlags & movePushPull ? // SZT również! SN61 zależnie od wagonów... - TrainParams.TimeTable[1].StationName == TrainParams.Relation1 : - false) : - false) - OrderPush(Shunt); // a teraz start będzie w manewrowym, a tryb pociągowy włączy W4 - else - // jeśli start z pierwszej stacji i jednocześnie jest na niej zmiana kierunku, to EZT ma mieć Shunt - OrderPush(Obey_train); // dla starych scenerii start w trybie pociagowym - if (DebugModeFlag) // normalnie nie ma po co tego wypisywać - WriteLog("/* Timetable: " + TrainParams.ShowRelation()); - TMTableLine *t; - for (int i = 0; i <= TrainParams.StationCount; ++i) - { - t = TrainParams.TimeTable + i; - if (DebugModeFlag) { - // normalnie nie ma po co tego wypisywa? - WriteLog( - t->StationName - + " " + std::to_string(t->Ah) + ":" + std::to_string(t->Am) - + ", " + std::to_string(t->Dh) + ":" + std::to_string(t->Dm) - + " " + t->StationWare); - } - if ( contains( t->StationWare, '@' ) ) - { // zmiana kierunku i dalsza jazda wg rozk?adu - if (iDrivigFlags & movePushPull) // SZT również! SN61 zależnie od wagonów... - { // jeśli skład zespolony, wystarczy zmienić kierunek jazdy - OrderPush(Change_direction); // zmiana kierunku - } - else - { // dla zwykłego składu wagonowego odczepiamy lokomotywę - OrderPush(Disconnect); // odczepienie lokomotywy - OrderPush(Shunt); // a dalej manewry - } - if (i < TrainParams.StationCount) // jak nie ostatnia stacja - OrderPush(Obey_train); // to dalej wg rozkładu - } - } - if( DebugModeFlag ) { - // normalnie nie ma po co tego wypisywać - WriteLog( "*/" ); - } - OrderPush(Shunt); // po wykonaniu rozkładu przełączy się na manewry - } - // McZapkie-100302 - to ma byc wyzwalane ze scenerii - if( fVel == 0.0 ) { - // jeśli nie ma prędkości początkowej, to śpi - SetVelocity( 0, 0, stopSleep ); - } - else { - // jeśli podana niezerowa prędkość - if( fVel >= 1.0 - || fVel < 0.02 ) { - // jeśli ma jechać - dla 0.01 ma podjechać manewrowo po podaniu sygnału - // to do następnego W4 ma podjechać blisko - iDrivigFlags = iDrivigFlags & ~moveStopHere | moveStopCloser; - } - else { - // czekać na sygnał - iDrivigFlags |= moveStopHere; - } - JumpToFirstOrder(); - if (fVel >= 1.0) // jeśli ma jechać - SetVelocity(fVel, -1); // ma ustawić żądaną prędkość - else - SetVelocity(0, 0, stopSleep); // prędkość w przedziale (0;1) oznacza, że ma stać - } -#if LOGORDERS - OrdersDump( "OrdersInit", DebugModeFlag ); // wypisanie kontrolne tabelki rozkazów -#endif - // McZapkie! - zeby w ogole AI ruszyl to musi wykonac powyzsze rozkazy - // Ale mozna by je zapodac ze scenerii -}; - -std::string TController::StopReasonText() const -{ // informacja tekstowa o przyczynie zatrzymania - if (eStopReason != 7) // zawalidroga będzie inaczej - return StopReasonTable[eStopReason]; - else - return "Blocked by " + pVehicles[0]->PrevAny()->name(); -}; - -//---------------------------------------------------------------------------------------------------------------------- -// McZapkie: skanowanie semaforów -// Ra: stare funkcje skanujące, używane podczas manewrów do szukania sygnalizatora z tyłu -//- nie reagują na PutValues, bo nie ma takiej potrzeby -//- rozpoznają tylko zerową prędkość (jako koniec toru i brak podstaw do dalszego skanowania) -//---------------------------------------------------------------------------------------------------------------------- - -bool TController::IsOccupiedByAnotherConsist( TTrack *Track, double const Distance = 0 ) -{ // najpierw sprawdzamy, czy na danym torze są pojazdy z innego składu - if( false == Track->Dynamics.empty() ) { - for( auto dynamic : Track->Dynamics ) { - if( dynamic->ctOwner != this ) { - // jeśli jest jakiś cudzy to tor jest zajęty i skanowanie nie obowiązuje - if( Distance == 0 ) { - return true; - } - else { - // based on provided position of scanning vehicle and scan direction, filter out vehicles on irrelevant end - auto const scandirection { Distance > 0 ? 1 : -1 }; // positive value means scan towards point2 end of the track - auto const obstaclelocation { scandirection > 0 ? Track->Length() - dynamic->RaTranslationGet() : dynamic->RaTranslationGet() }; - // if detected vehicle is closer to the end of the track in scanned direction than we are, it means it's blocking our way - if( obstaclelocation < std::abs( Distance ) ) { - return true; - } - } - } - } - } - return false; // wolny -}; - -basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection, end const End) -{ // sprawdzanie eventu w torze, czy jest sygnałowym - skanowanie do tyłu - // NOTE: this method returns only one event which meets the conditions, due to limitations in the caller - // TBD, TODO: clean up the caller and return all suitable events, as in theory things will go awry if the track has more than one signal - auto const dir{ Vehicle->VectorFront() * (double)Vehicle->DirectionGet() }; - auto const pos{ End == end::front ? Vehicle->RearPosition() : Vehicle->HeadPosition() }; - auto const &eventsequence { ( fDirection * Eventdirection > 0 ? Track->m_events2 : Track->m_events1 ) }; - for( auto const &event : eventsequence ) { - if( event.second != nullptr - && event.second->m_passive - && typeid(*event.second) == typeid(getvalues_event) ) { - // since we're checking for events behind us discard the sources in front of the scanning vehicle - auto const sl{ event.second->input_location() }; // położenie komórki pamięci - auto const sem{ sl - pos }; // wektor do komórki pamięci od końca składu - auto const isahead { dir.x * sem.x + dir.z * sem.z > 0 }; - if( End == end::front ? isahead : !isahead ) { - // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu - return event.second; - } - } - } - return nullptr; -}; - -TTrack * TController::BackwardTraceRoute(double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection, end const End, bool const Untiloccupied ) -{ // szukanie sygnalizatora w kierunku przeciwnym jazdy (eventu odczytu komórki pamięci) - auto *Track = Vehicle->GetTrack(); - double fCurrentDistance = Vehicle->RaTranslationGet(); // aktualna pozycja na torze - if (fDirection > 0) // jeśli w kierunku Point2 toru - fCurrentDistance = Track->Length() - fCurrentDistance; - double s = 0; - - if( Track->VelocityGet() == 0.0 ) { // jak prędkosć 0 albo uszkadza, to nie ma po co skanować - fDistance = s; // to na tym torze stoimy - return nullptr; // stop, skanowanie nie dało sensownych rezultatów - } - // jak tor zajęty innym składem, to nie ma po co skanować - if( Untiloccupied && IsOccupiedByAnotherConsist( Track, fCurrentDistance * fDirection ) ) { - fDistance = s; // to na tym torze stoimy - return nullptr; // stop, skanowanie nie dało sensownych rezultatów - } - if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) - { // jeśli jest semafor na tym torze - fDistance = s; // to na tym torze stoimy - return Track; - } - TTrack *pTrackFrom; // odcinek poprzedni, do znajdywania końca dróg - while (s < fDistance) - { - // Track->ScannedFlag=true; //do pokazywania przeskanowanych torów - pTrackFrom = Track; // zapamiętanie aktualnego odcinka - s += fCurrentDistance; // doliczenie kolejnego odcinka do przeskanowanej długości - if (fDirection > 0) - { // jeśli szukanie od Point1 w kierunku Point2 - if (Track->iNextDirection) - fDirection = -fDirection; - Track = Track->CurrentNext(); // może być NULL - } - else // if (fDirection<0) - { // jeśli szukanie od Point2 w kierunku Point1 - if (!Track->iPrevDirection) - fDirection = -fDirection; - Track = Track->CurrentPrev(); // może być NULL - } - if (Track == pTrackFrom) - Track = nullptr; // koniec, tak jak dla torów - - // gdy dalej toru nie ma albo zerowa prędkość, albo uszkadza pojazd - // zwraca NULL, że skanowanie nie dało sensownych rezultatów - if( Track == nullptr ) { - fDistance = s; - return nullptr; - } - if( Track->VelocityGet() == 0.0 ) - { - fDistance = s; - return nullptr; - } - if( Untiloccupied && IsOccupiedByAnotherConsist( Track ) ) { - fDistance = s; - return nullptr; - } - fCurrentDistance = Track->Length(); - if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) - { // znaleziony tor z eventem - fDistance = s; - return Track; - } - } - Event = nullptr; // jak dojdzie tu, to nie ma semafora - // zwraca ostatni sprawdzony tor - fDistance = s; - return Track; -} - -// sprawdzanie zdarzeń semaforów i ograniczeń szlakowych -void TController::SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos ) -{ // Ra:przeslanie do AI prędkości - /* - //!!!! zastąpić prawidłową reakcją AI na SetProximityVelocity !!!! - if (vel==0) - {//jeśli zatrzymanie, to zmniejszamy dystans o 10m - dist-=10.0; - }; - if (dist<0.0) dist=0.0; - if ((vel<0)?true:dist>0.1*(MoverParameters->Vel*MoverParameters->Vel-vel*vel)+50) - {//jeśli jest dalej od umownej drogi hamowania - */ - PutCommand( "SetProximityVelocity", dist, vel, pos ); - /* - } - else - {//jeśli jest zagrożenie, że przekroczy - Mechanik->SetVelocity(floor(0.2*sqrt(dist)+vel),vel,stopError); - } - */ -} - -TCommandType TController::BackwardScan( double const Range ) -{ // sprawdzanie zdarzeń semaforów z tyłu pojazdu, zwraca komendę - // dzięki temu będzie można stawać za wskazanym sygnalizatorem, a zwłaszcza jeśli będzie jazda na kozioł - // ograniczenia prędkości nie są wtedy istotne, również koniec toru jest do niczego nie przydatny - // zwraca true, jeśli należy odwrócić kierunek jazdy pojazdu - if( OrderCurrentGet() & ~(Shunt | Loose_shunt | Connect) ) { - // skanowanie sygnałów tylko gdy jedzie w trybie manewrowym albo czeka na rozkazy - return TCommandType::cm_Unknown; - } - // kierunek jazdy względem sprzęgów pojazdu na czele - int const startdir = -pVehicles[0]->DirectionGet(); - if( startdir == 0 ) { - // jeśli kabina i kierunek nie jest określony nie robimy nic - return TCommandType::cm_Unknown; - } - // szukamy od pierwszej osi w wybranym kierunku - double scandir = startdir * pVehicles[0]->RaDirectionGet(); - - if( scandir == 0.0 ) { return TCommandType::cm_Unknown; } - - // skanowanie toru w poszukiwaniu eventów GetValues (PutValues nie są przydatne) - // Ra: przy wstecznym skanowaniu prędkość nie ma znaczenia - double scandist = Range; // zmodyfikuje na rzeczywiście przeskanowane - basic_event *e = nullptr; // event potencjalnie od semafora - // opcjonalnie może być skanowanie od "wskaźnika" z przodu, np. W5, Tm=Ms1, koniec toru wg - // drugiej osi w kierunku ruchu - auto const *scantrack{BackwardTraceRoute(scandist, scandir, pVehicles[end::front], e)}; - auto const dir{(double)startdir * - pVehicles[end::front]->VectorFront()}; // wektor w kierunku jazdy/szukania - - // jeśli wstecz wykryto koniec toru to raczej nic się nie da w takiej sytuacji zrobić - if (e == nullptr) - { - return TCommandType::cm_Unknown; - } - if (typeid(*e) != typeid(getvalues_event)) - { - return TCommandType::cm_Unknown; - } - - // jeśli jest jakiś sygnał na widoku - double scanvel; // prędkość ustawiona semaforem -#if LOGBACKSCAN - std::string edir{"Backward scan by " + pVehicle->asName + " - " + - ((scandir > 0) ? "Event2 " : "Event1 ")}; - edir += "(" + (e->name()) + ")"; -#endif - { - // najpierw sprawdzamy, czy semafor czy inny znak został przejechany - auto const sl{e->input_location()}; // położenie komórki pamięci - auto const pos{pVehicles[end::rear]->RearPosition()}; // pozycja tyłu - if (auto const sem{sl - pos}; dir.x * sem.x + dir.z * sem.z < 0) // wektor do komórki pamięci od końca składu - { - // jeśli został minięty - // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu -#if LOGBACKSCAN - WriteLog(edir + " - ignored as not passed yet"); -#endif - return TCommandType::cm_Unknown; // nic - } - scanvel = e->input_value(1); // prędkość przy tym semaforze -#if LOGBACKSCAN - // przeliczamy odległość od semafora - potrzebne by były współrzędne początku składu - scandist = std::max(glm::length(sl - pos) - 2.0, 0.0); // 2m luzu przy manewrach wystarczy, ujemnych nie ma po co wysyłać -#endif - } - - auto move{false}; // czy AI w trybie manewerowym ma dociągnąć pod S1 - if (e->input_command() == TCommandType::cm_SetVelocity) - { - if (scanvel == 0.0 ? OrderCurrentGet() & (Shunt | Loose_shunt | Connect) : - OrderCurrentGet() & Connect) - { // przy podczepianiu ignorować wyjazd? - move = true; // AI w trybie manewerowym ma dociągnąć pod S1 - } - else - { - // jeśli semafor jest daleko, a pojazd jedzie, to informujemy o zmianie prędkości - // jeśli jedzie manewrowo, musi dostać SetVelocity, żeby sie na pociągowy przełączył - // w przeciwnym razie ustawiamy prędkość tylko wtedy, gdy ma ruszyć, stanąć albo ma stać - // ruszać stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam -#if LOGBACKSCAN - if (scandist > fMinProximityDist && - mvOccupied->Vel > EU07_AI_NOMOVEMENT && (OrderCurrentGet() & (Shunt | Loose_shunt)) == 0) - { - WriteLog(edir); - } - else - { - WriteLog(edir + " - [SetVelocity] [" + to_string(scanvel, 2) + "] [" + - to_string(e->input_value(2), 2) + "]"); - } -#endif - return scanvel > 0 ? TCommandType::cm_SetVelocity : TCommandType::cm_Unknown; - } - } - // reakcja AI w trybie manewrowym dodatkowo na sygnały manewrowe - if ((OrderCurrentGet() ? OrderCurrentGet() & (Shunt | Loose_shunt | Connect) : true) && (move || e->input_command() == TCommandType::cm_ShuntVelocity)) // w Wait_for_orders też widzi tarcze - { - // jeśli powyżej było SetVelocity 0 0, to dociągamy pod S1 - /* - if ((scandist > fMinProximityDist) && - ((mvOccupied->Vel > EU07_AI_NOMOVEMENT) || (scanvel == 0.0))) - { - // jeśli tarcza jest daleko, to: - //- jesli pojazd jedzie, to informujemy o zmianie prędkości - //- jeśli stoi, to z własnej inicjatywy może podjechać pod zamkniętą tarczę - if (mvOccupied->Vel > EU07_AI_NOMOVEMENT) // tylko jeśli jedzie - { // Mechanik->PutCommand("SetProximityVelocity",scandist,scanvel,sl); - #if LOGBACKSCAN - // WriteLog(edir+"SetProximityVelocity "+AnsiString(scandist)+" - // "+AnsiString(scanvel)); - WriteLog(edir); - #endif - // SetProximityVelocity(scandist,scanvel,&sl); - // jeśli jedzie na W5 albo koniec toru, to można zmienić kierunek - return (iDrivigFlags & moveTrackEnd) ? TCommandType::cm_ChangeDirection : - TCommandType::cm_Unknown; - // TBD: request direction change also if VelNext in current direction is 0, - // while signal behind requests movement? - } - } - else - { - // ustawiamy prędkość tylko wtedy, gdy ma ruszyć, albo stanąć albo ma stać pod - // tarczą stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam if - // ((MoverParameters->Vel==0.0)||(scanvel==0.0)) //jeśli jedzie lub ma stanąć/stać - { // nie dostanie komendy jeśli jedzie i ma jechać - // PutCommand("ShuntVelocity",scanvel,e->Params[9].asMemCell->Value2(),&sl,stopSem); - #if LOGBACKSCAN - WriteLog(edir + " - [ShuntVelocity] [" + to_string(scanvel, 2) + "] [" + - to_string(e->input_value(2), 2) + "]"); - #endif - return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : - TCommandType::cm_Unknown); - } - } - // NOTE: dead code due to returns in branching above - if ((scanvel != 0.0) && (scandist < 100.0)) - { - // jeśli Tm w odległości do 100m podaje zezwolenie na jazdę, to od razu ją - // ignorujemy, aby móc szukać kolejnej eSignSkip=e; //wtedy uznajemy ignorowaną przy - // poszukiwaniu nowej - #if LOGBACKSCAN - WriteLog(edir + " - will be ignored due to Ms2"); - #endif - return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : TCommandType::cm_Unknown); - } - */ - return VelNext > 0 ? - TCommandType::cm_Unknown : // no need to bother if we can continue in current direction - scanvel == 0 ? - TCommandType::cm_Unknown : // no need to bother with a stop signal - TCommandType::cm_ShuntVelocity; // otherwise report a relevant shunt signal behind - // if (move?... - } // if (OrderCurrentGet()==Shunt) - - return e->m_passive && e->is_command() ? TCommandType::cm_Command : TCommandType::cm_Unknown; -}; - -std::string TController::NextStop() const -{ // informacja o następnym zatrzymaniu, wyświetlane pod [F1] - if (asNextStop == "[End of route]") - return ""; // nie zawiera nazwy stacji, gdy dojechał do końca - // dodać godzinę odjazdu - auto nextstop{ Bezogonkow( asNextStop, true ) }; - auto const *t{ TrainParams.TimeTable + TrainParams.StationIndex }; - if( t->Ah >= 0 ) { - // przyjazd - nextstop += " przyj." + std::to_string( t->Ah ) + ":" - + to_minutes_str( t->Am, true, 3 ); - - } - if( t->Dh >= 0 ) { - // jeśli jest godzina odjazdu - nextstop += " odj." + std::to_string( t->Dh ) + ":" - + to_minutes_str( t->Dm, true, 3 ); - } - return nextstop; -}; - -void TController::UpdateDelayFlag() { - - if( TrainParams.CheckTrainLatency() < 0.0 ) { - // odnotowano spóźnienie - iDrivigFlags |= moveLate; - } - else { - // przyjazd o czasie - iDrivigFlags &= ~moveLate; - } -} - -//-----------koniec skanowania semaforow - -void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck ) -{ // przejęcie kontroli przez AI albo oddanie - if (AIControllFlag == Aidriver && !Forcevehiclecheck) - return; // już jest jak ma być - if( AIControllFlag != Aidriver ) { - // the autopilot switched on or off - simulation::Blackbox.driver_changed( pVehicle, Aidriver ); - } - if (Aidriver) //żeby nie wykonywać dwa razy - { // teraz AI prowadzi - AIControllFlag = AIdriver; - pVehicle->Controller = AIdriver; - // the AI doesn't operate the headlight dimmer, drop the state left by the human driver - // so the lights set by the AI aren't hidden (dimmer in off position) or dimmed - pVehicle->HeadlightsAoff = false; - pVehicle->HeadlightsBoff = false; - pVehicle->DimHeadlights = false; - pVehicle->HighBeamLights = false; - control_lights(); // reinicjalizacja swiatel - mvOccupied->CabActivisation(true); - iDirection = 0; // kierunek jazdy trzeba dopiero zgadnąć - TableClear(); // ponowne utworzenie tabelki, bo człowiek mógł pojechać niezgodnie z sygnałami - if( action() != TAction::actSleep ) { - // gdy zgaszone światła, flaga podjeżdżania pod semafory pozostaje bez zmiany - // conditional below disabled to get around the situation where the AI train does nothing ever - // because it is waiting for orders which don't come until the engine is engaged, i.e. effectively never - if( OrderCurrentGet() ) { - // jeśli coś robi - PrepareEngine(); // niech sprawdzi stan silnika - } - else { - // jeśli nic nie robi - OrderNext( Prepare_engine ); - if( pVehicle->MoverParameters->iLights[ ( mvOccupied->CabActive < 0 ? - end::rear : - end::front ) ] - & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone? - { // od wersji 357 oczekujemy podania komend dla AI przez scenerię -/* - if( pVehicle->MoverParameters->iLights[ mvOccupied->CabActive < 0 ? end::rear : end::front ] & light::headlight_upper ) // górne światło zapalone - OrderNext( Obey_train ); // jazda pociągowa - else - OrderNext( Shunt ); // jazda manewrowa -*/ - if( mvOccupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) - iDrivigFlags &= ~moveStopHere; // to ma nie czekać na sygnał, tylko jechać - else - iDrivigFlags |= moveStopHere; // a jak stoi, to niech czeka - } - } - CheckVehicles(); // ustawienie świateł - } - } - else - { // a teraz użytkownik - if (eAction == TAction::actSleep || OrderCurrentGet() == Wait_for_orders) // gasimy swiatla jesli przejmujemy odstawione - pVehicle->RaLightsSet(0, 0); - auto const aiwasdriving { AIControllFlag == AIdriver }; - if( aiwasdriving ) { - // the horn, sandbox, departure signal and brake releaser the AI may have latched are momentary for the human driver - handover::release_ai_controls( *mvOccupied, *mvControlling ); - fWarningDuration = 0.0; - remove_hint( driver_hint::hornon ); - // the AI sets the lights directly, leave the selector in matching position so it doesn't revert them later - sync_lights_selector(); - } - AIControllFlag = Humandriver; - pVehicle->Controller = Humandriver; - if( aiwasdriving ) { - // same with the headlight dimmer, which is only applied for the human driver - sync_lights_dimmer(); - } - if( eAction == TAction::actSleep ) { - eAction = TAction::actUnknown; - } - if( Forcevehiclecheck ) { - // update consist ownership and other consist data - CheckVehicles(); - } - } -}; - -void TController::DirectionForward(bool forward) -{ // ustawienie jazdy do przodu dla true i do tyłu dla false (zależy od kabiny) - ZeroSpeed( true ); // TODO: check if force switch is needed anymore here - // HACK: make sure the master controller isn't set in position which prevents direction change - mvControlling->MainCtrlPos = std::min( mvControlling->MainCtrlPos, mvControlling->MainCtrlMaxDirChangePos ); - - if( forward ) { - // do przodu w obecnej kabinie - while( mvOccupied->DirActive <= 0 - && mvOccupied->DirectionForward() ) { - // force scan table update - iTableDirection = 0; - } - } - else { - // do tyłu w obecnej kabinie - while( mvOccupied->DirActive >= 0 - && mvOccupied->DirectionBackward() ) { - // force scan table update - iTableDirection = 0; - } - } - if( mvOccupied->TrainType == dt_SN61 ) { - // specjalnie dla SN61 żeby nie zgasł - while( mvControlling->RList[mvControlling->MainCtrlPos].Mn == 0 - && mvControlling->IncMainCtrl(1) ) { - ; // all work is done in the header - } - } -} - -void TController::ZeroDirection() { - - while( mvOccupied->DirActive > 0 && mvOccupied->DirectionBackward() ) { ; } - while( mvOccupied->DirActive < 0 && mvOccupied->DirectionForward() ) { ; } -} - -void TController::sync_consist_reversers() { - - auto const currentdirection { mvOccupied->DirActive }; - auto const fastforward { is_emu() && mvOccupied->EngineType != TEngineType::ElectricInductionMotor - && mvOccupied->Imin == mvOccupied->IminHi }; - - // move reverser all way in the opposite direction... - for( auto idx = 0; idx < 3; ++idx ) { - if( currentdirection >= 0 ) { - mvOccupied->DirectionBackward(); - } - else { - mvOccupied->DirectionForward(); - - } - } - // ...then restore original setting - while( mvOccupied->DirActive != currentdirection ) { - if( false == ( - currentdirection >= 0 ? - mvOccupied->DirectionForward() : - mvOccupied->DirectionBackward() ) ) { - // sanity check for potential endless loop - break; - } - } - // potentially restore 'fast forward' setting - if( currentdirection > 0 && true == fastforward ) { - mvOccupied->DirectionForward(); - } -} - -Mtable::TTrainParameters const & -TController::TrainTimetable() const { - return TrainParams; -} - -std::string TController::Relation() const -{ // zwraca relację pociągu - return TrainParams.ShowRelation(); -}; - -const std::string& TController::TrainName() const -{ // zwraca numer pociągu - return TrainParams.TrainName; -}; - -int TController::StationCount() const -{ // zwraca ilość stacji (miejsc zatrzymania) - return TrainParams.StationCount; -}; - -int TController::StationIndex() const -{ // zwraca indeks aktualnej stacji (miejsca zatrzymania) - return TrainParams.StationIndex; -}; - -bool TController::IsStop() const -{ // informuje, czy jest zatrzymanie na najbliższej stacji - return TrainParams.IsStop(); -}; - -// returns most recently calculated distance to potential obstacle ahead -double -TController::TrackObstacle() const { - - return Obstacle.distance; -} - -void TController::MoveTo(TDynamicObject *to) -{ // przesunięcie AI do innego pojazdu (przy zmianie kabiny) - if( to->Mechanik != nullptr - && to->Mechanik != this ) { - // ai controller thunderdome, there can be only one - if( to->Mechanik->AIControllFlag ) { - if( to->Mechanik->primary() ) { - // take over boss duties - primary( true ); - } - SafeDelete( to->Mechanik ); - } - else { - // can't quite delete a human - if( AIControllFlag ) { - delete this; - } - return; - } - } - pVehicle->Mechanik = nullptr; - pVehicle = to; - ControllingSet(); // utworzenie połączenia do sterowanego pojazdu - pVehicle->Mechanik = this; - -}; - -void TController::ControllingSet() -{ // znajduje człon do sterowania w EZT będzie to silnikowy - // problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy - // dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym - // w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT - if( pVehicle == nullptr ) { - // a driver of no vehicle has nothing to control - return; - } - mvOccupied = pVehicle->MoverParameters; // domyślny skrót do obiektu parametrów - BrakeSystem = mvOccupied->BrakeSystem; // domyślny sposób hamowania - mvControlling = pVehicle->FindPowered()->MoverParameters; // poszukiwanie członu sterowanego - { - auto *lookup { pVehicle->FindPantographCarrier() }; - mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlling; - } - BrakeSystem = consist_brake_system(); -}; - -std::string TController::TableText( std::size_t const Index ) const -{ // pozycja tabelki prędkości - if( Index < sSpeedTable.size() ) { - return sSpeedTable[ Index ].TableText(); - } - else { - return ""; - } -}; - -int TController::CrossRoute(TTrack *tr) -{ // zwraca numer segmentu dla skrzyżowania (tr) - // pożądany numer segmentu jest określany podczas skanowania drogi - // droga powinna być określona sposobem przejazdu przez skrzyżowania albo współrzędnymi miejsca - // docelowego - for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) - { // trzeba przejrzeć tabelę skanowania w poszukiwaniu (tr) - // i jak się znajdzie, to zwrócić zapamiętany numer segmentu i kierunek przejazdu - // (-6..-1,1..6) - if( true == TestFlag(sSpeedTable[i].iFlags, spEnabled | spTrack) - && sSpeedTable[i].trTrack == tr ) { - // jeśli pozycja odpowiadająca skrzyżowaniu (tr) - return sSpeedTable[i].iFlags >> 28; // najstarsze 4 bity jako liczba -8..7 - } - } - return 0; // nic nie znaleziono? -}; -/* -void TController::RouteSwitch(int d) -{ // ustawienie kierunku jazdy z kabiny - d &= 3; - if( ( d != 0 ) - && ( iRouteWanted != d ) ) { // nowy kierunek - iRouteWanted = d; // zapamiętanie - if( mvOccupied->CategoryFlag & 2 ) { - // jeśli samochód - for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) { - // szukanie pierwszego skrzyżowania i resetowanie kierunku na nim - if( true == TestFlag( sSpeedTable[ i ].iFlags, spEnabled | spTrack ) ) { - // jeśli pozycja istotna (1) oraz odcinek (2) - if( false == TestFlag( sSpeedTable[ i ].iFlags, spElapsed ) ) { - // odcinek nie może być miniętym - if( sSpeedTable[ i ].trTrack->eType == tt_Cross ) // jeśli skrzyżowanie - { - while( sSpeedTable.size() >= i ) { - // NOTE: we're ignoring semaphor flags and not resetting them like we do for train route trimming - // but what if there's street lights? - // TODO: investigate - sSpeedTable.pop_back(); - } - iLast = sSpeedTable.size(); - } - } - } - } - } - } -}; -*/ -std::string TController::OwnerName() const -{ - return pVehicle ? pVehicle->MoverParameters->Name : "none"; -}; - -void -TController::update_timers( double dt ) { - - ElapsedTime += dt; - WaitingTime += dt; - fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca - fBrakeHeldTime += dt; - if( mvOccupied->fBrakeCtrlPos != mvOccupied->Handle->GetPos( bh_FS ) ) { - // brake charging timeout starts after charging ends - BrakeChargingCooldown += dt; - } - fStopTime += dt; // zliczanie czasu postoju, nie ruszy dopóki ujemne - fActionTime += dt; // czas używany przy regulacji prędkości i zamykaniu drzwi - LastReactionTime += dt; - if( mvOccupied->Vel < 0.05 - && (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 ) { - IdleTime += dt; - } - else { - IdleTime = 0.0; - } - fWarningDuration -= dt; // horn activation while the value is positive -} - -void -TController::update_logs( double const dt ) { - // log vehicle data - if( false == writes_physicslog() ) { - // not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on, - // it would write a line every 0.05 s from then on, not one each update to make up for the time before - LastUpdatedTime = 0.0; - return; - } - LastUpdatedTime += dt; - if( LastUpdatedTime > deltalog ) { - // zapis do pliku DAT - if( false == PhysicsLogBegun ) { - begin_physicslog(); - } - PhysicsLog(); - LastUpdatedTime -= deltalog; - } -} - -void -TController::determine_consist_state() { - // ABu-160305 testowanie gotowości do jazdy - // Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować - - if (mvOccupied->CabActive == 0 && mvOccupied->Power24vIsAvailable) - { - cue_action( driver_hint::cabactivation ); - } - else if (!mvOccupied->AutomaticCabActivation - && ( mvOccupied->CabActive == -mvOccupied->CabOccupied || !mvOccupied->CabMaster || !mvOccupied->Power24vIsAvailable ) ) - { - cue_action( driver_hint::cabdeactivation ); - } - - int index = double(BrakeAccTableSize) * (mvOccupied->Vel / mvOccupied->Vmax); - index = std::min(BrakeAccTableSize, std::max(1, index)); - fBrake_a0[0] = fBrake_a0[index]; - fBrake_a1[0] = fBrake_a1[index]; - - if (is_emu() || is_dmu()) { - auto Coeff = std::clamp( mvOccupied->Vel*0.015 , 0.5 , 1.0); - fAccThreshold = fNominalAccThreshold * Coeff - fBrake_a0[BrakeAccTableSize] * (1.0 - Coeff); - } - - Ready = true; // wstępnie gotowy - fReady = 0.0; // założenie, że odhamowany - IsConsistBraked = mvOccupied->BrakeSystem == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? mvOccupied->BrakePress > 2.0 : - mvOccupied->PipePress < std::max(3.9, mvOccupied->BrakePressureActual.PipePressureVal) + 0.1; - fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia - IsAnyCouplerStretched = false; - IsAnyDoorOnlyOpen[ side::right ] = IsAnyDoorOnlyOpen[ side::left ] = false; - IsAnyDoorOpen[ side::right ] = IsAnyDoorOpen[ side::left ] = false; - IsAnyDoorPermitActive[ side::right ] = IsAnyDoorPermitActive[ side::left ] = false; - auto doorclosure { door_closure_t::none }; - 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 }; - 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 ) ) }; - momentum += vehicle->TotalMass * vehicle->V * ( p->DirectionGet() == iDirection ? 1 : -1 ); - mostapplied = std::max( bp, mostapplied ); - auto const wasready { Ready }; - if( released || Ready ) { - // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać - 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 - 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 - && vehicle->PipePress - mvOccupied->Handle->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy - && vehicle->Hamulec->GetCRP() > vehicle->PipePress + 0.12 ) { // wg UIC określone sztywno na 0.04 - // za dużo w zbiorniku - // indywidualne luzowanko - vehicle->BrakeReleaser(1); - } - if (bp < 0.1 && (AIControllFlag || Global.AITrainman) && false == TestFlag(vehicle->Hamulec->GetBrakeStatus(), b_dmg) // brake isn't broken - && vehicle->Hamulec->GetCRP() < vehicle->PipePress - 0.1) { - // już nie jest za dużo w zbiorniku - // koniec indywidualnego luzowanka - vehicle->BrakeReleaser(0); - } - } - // 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 - fAccGravity -= vehicle->TotalMassxg * dy * ( p->DirectionGet() == iDirection ? 1 : -1 ); - } - // check coupler state - IsAnyCouplerStretched = - IsAnyCouplerStretched - || vehicle->Couplers[end::front].stretch_duration > 0.0 - || vehicle->Couplers[end::rear].stretch_duration > 0.0; - // check door state - { - auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? mvOccupied->CabOccupied : iDirection) }; - auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? side::left : side::right ) ] }; - auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? side::right : side::left ) ] }; - if( vehicle->Doors.close_control != control_t::autonomous ) { - IsAnyDoorOpen[ side::right ] |= false == rightdoor.is_closed; - IsAnyDoorOpen[ side::left ] |= false == leftdoor.is_closed; - } - if (vehicle->Doors.close_control != control_t::autonomous) { - IsAnyDoorOnlyOpen[ side::right ] |= false == rightdoor.is_door_closed; - IsAnyDoorOnlyOpen[ side::left ] |= false == leftdoor.is_door_closed; - } - if( vehicle->Doors.permit_needed ) { - IsAnyDoorPermitActive[ side::right ] |= rightdoor.open_permit; - IsAnyDoorPermitActive[ side::left ] |= leftdoor.open_permit; - } - doorclosure = std::max( doorclosure, vehicle->door_closure() ); - } - // measure lighting level - // TBD: apply weight (multiplier) to partially lit vehicles? - ConsistShade += p->fShade > 0.0 ? p->fShade : 1.0; - p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) - } - DoorClosure = doorclosure; - // calculate average amount of received sunlight - ConsistShade /= iVehicles; - - // test state of main devices in all vehicles under control - IsAnyConverterOverloadRelayOpen = false; - IsAnyMotorOverloadRelayOpen = false; - IsAnyGroundRelayOpen = false; - IsAnyLineBreakerOpen = false; - IsAnyCompressorPresent = false; - IsAnyCompressorEnabled = false; - IsAnyCompressorExplicitlyEnabled = false; - IsAnyConverterPresent = false; - IsAnyConverterEnabled = false; - IsAnyConverterExplicitlyEnabled = false; - // whether the line contactors of a vehicle wait for its own converter (LineContactorsInterlock), off with its local switch - auto islocalconverterswitchoff { false }; - - pVehicle->for_each( - coupling::control, - [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { - auto const *vehicle { Vehicle->MoverParameters }; - islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); - IsAnyConverterOverloadRelayOpen |= vehicle->ConvOvldFlag; - IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; - IsAnyGroundRelayOpen |= !vehicle->GroundRelay; - IsAnyCompressorPresent |= vehicle->CompressorSpeed > 0.0; - IsAnyCompressorEnabled |= vehicle->CompressorSpeed > 0.0 ? (vehicle->CompressorAllow || vehicle->CompressorStart == start_t::automatic) && vehicle->CompressorAllowLocal : false; - IsAnyCompressorExplicitlyEnabled |= vehicle->CompressorSpeed > 0.0 ? vehicle->CompressorAllow && vehicle->CompressorAllowLocal : false; - IsAnyConverterPresent |= vehicle->ConverterStart != start_t::disabled; - IsAnyConverterEnabled |= ( vehicle->ConverterAllow || vehicle->ConverterStart == start_t::automatic ) && vehicle->ConverterAllowLocal; - IsAnyConverterExplicitlyEnabled |= vehicle->ConverterAllow && vehicle->ConverterAllowLocal; - if( vehicle->Power > 0.01 ) { - IsAnyLineBreakerOpen |= !vehicle->Mains; } } ); - - // siłę generują pojazdy na pochyleniu ale działa ona całość składu, więc a=F/m - fAccGravity *= iDirection >= 0 ? 1 : -1; - fAccGravity /= fMass; - { - auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { - absaccs = 0; - auto *d = pVehicles[ end::front ]; // pojazd na czele składu - while( d ) { - absaccs += d->MoverParameters->TotalMass * d->MoverParameters->AccS * ( d->DirectionGet() == iDirection ? 1 : -1 ); - d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) - } - absaccs *= iDirection >= 0 ? 1 : -1; - absaccs /= fMass; - } - AbsAccS = absaccs; - } -#if LOGVELOCITY - WriteLog( "Vel=" + to_string( DirectionalVel() ) + ", AbsAccS=" + to_string( AbsAccS ) + ", AccGrav=" + to_string( fAccGravity ) ); -#endif - - if( !Ready // v367: jeśli wg powyższych warunków skład nie jest odhamowany - && fAccGravity < -0.05 // jeśli ma pod górę na tyle, by się stoczyć - && 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 ); - auto const departblocked { - AIControllFlag - && mvOccupied->Vel < EU07_AI_NOMOVEMENT - && VelDesired > 0.0 - && ( false == Ready || fReady > 0.4 ) }; - if( false == departblocked ) { - DepartBlockedStart = -1.0; - } - else if( DepartBlockedStart < 0.0 ) { - DepartBlockedStart = ElapsedTime; - } - // second pass, for diesel engines verify the (live) engines are fully started - // TODO: cache presence of diesel engines in the consist, to skip this test if there isn't any - p = pVehicles[ end::front ]; // pojazd na czole składu - while( true == Ready - && p != nullptr ) { - - auto const *vehicle { p->MoverParameters }; - - if( has_diesel_engine() ) { - - Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving - || false == vehicle->Mains // deadweight vehicle - || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->dizel_nmin : vehicle->DElist[0].RPM / 60.0); - } - p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) - } - // test consist state for external events and/or weird things human user could've done - iEngineActive &= - false == IsAnyConverterOverloadRelayOpen - && false == IsAnyLineBreakerOpen - && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) - && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) - // the ai goes back to preparing the engine and switches that converter on, the human driver may run with it off - && ( false == AIControllFlag || false == islocalconverterswitchoff ); -} - -void -TController::control_wheelslip() { - // wheel slip - if( mvControlling->SlippingWheels ) { - cue_action( driver_hint::sandingon ); // piasku! - cue_action( driver_hint::tractiveforcedecrease ); - cue_action( driver_hint::brakingforcedecrease ); - cue_action( driver_hint::antislip ); - ++iDriverFailCount; - } - else if( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi ) { - cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać - } - else { - // deactivate sandbox if we aren't slipping - if( mvControlling->SandDose ) { - cue_action( driver_hint::sandingoff ); - } - } -} - -void -TController::control_pantographs() { - - if( mvPantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } - - if( false == mvPantographUnit->PantAutoValve - && mvOccupied->ScndPipePress > 4.3 ) { - // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki - cue_action( driver_hint::pantographairsourcesetmain ); - } - - // uśrednione napięcie sieci: przy spadku poniżej wartości minimalnej opóźnić rozruch o losowy czas - fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->PantographVoltage ) ); - if( fVoltage < mvControlling->EnginePowerSource.CollectorParameters.MinV && fActionTime >= PrepareTime ) { - // gdy rozłączenie WS z powodu niskiego napięcia - // jeśli czas oczekiwania nie został ustawiony, losowy czas oczekiwania przed ponownym załączeniem jazdy - fActionTime = -2.0 - Random(10); - } - - // the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none - // or the vehicle isn't shunting - auto const shuntpantographsetup { - ( OrderCurrentGet() & ( Shunt | Loose_shunt ) ) != 0 ? - mvOccupied->AIHintShuntPantstate : - 0 }; - - // raise/lower pantographs as needed - auto const useregularpantographlayout { - pVehicle->Next(coupling::control) == nullptr // standalone - || is_emu() // special case - || mvControlling->TrainType == dt_ET41 }; // special case - - if( mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { - - if( fOverhead2 >= 0.0 || iOverheadZero ) { - // jeśli jazda bezprądowa albo z opuszczonym pantografem - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - - if( fOverhead2 > 0.0 || iOverheadDown ) { - // jazda z opuszczonymi pantografami - if( mvPantographUnit->Pantographs[ end::front ].is_active ) { - cue_action( driver_hint::frontpantographvalveoff ); - } - if( mvPantographUnit->Pantographs[ end::rear ].is_active ) { - cue_action( driver_hint::rearpantographvalveoff ); - } - } - else { - // jeśli nie trzeba opuszczać pantografów - // TODO: check if faction alone reduces frequency enough - if( fActionTime > 0.0 ) { - if( shuntpantographsetup != 0 ) { - // shunting with the pantograph setup the .fiz suggests for it - control_pantographs_setup( shuntpantographsetup ); - } - else if( mvOccupied->AIHintPantstate == 0 ) { - // jazda na tylnym - if( iDirection >= 0 && useregularpantographlayout ) { - // jak jedzie w kierunku sprzęgu 0 - if( mvPantographUnit->PantRearVolt == 0.0 - // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( mvPantographUnit->PantographVoltage == 0.0 - || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { - cue_action( driver_hint::rearpantographvalveon ); - } - } - else { - // jak jedzie w kierunku sprzęgu 0 - if( mvPantographUnit->PantFrontVolt == 0.0 - // filter out cases with single _other_ working pantograph so we don't try to raise something we can't - && ( mvPantographUnit->PantographVoltage == 0.0 - || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { - cue_action( driver_hint::frontpantographvalveon ); - } - } - - if( mvOccupied->Vel > 5 && mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) { - // opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden - if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0 - { // poczekać na podniesienie tylnego - if (mvPantographUnit->PantFrontVolt != 0.0 && mvPantographUnit->PantRearVolt != 0.0) - { // czy jest napięcie zasilające na tylnym? - cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0 - } - } - else - { // poczekać na podniesienie przedniego - if (mvPantographUnit->PantRearVolt != 0.0 && mvPantographUnit->PantFrontVolt != 0.0) - { // czy jest napięcie zasilające na przednim? - cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1 - } - } - } - - } - else { - // use suggested pantograph setup - if( mvOccupied->Vel > 5 ) { - auto const pantographsetup{ mvOccupied->AIHintPantstate }; - cue_action( - pantographsetup & 1 << 0 ? driver_hint::frontpantographvalveon : driver_hint::frontpantographvalveoff ); - cue_action( - pantographsetup & 1 << 1 ? driver_hint::rearpantographvalveon : driver_hint::rearpantographvalveoff ); - } - } - } - } - } - else if( shuntpantographsetup != 0 ) { - // shunting with the suggested setup, also while standing, and without raising more pantographs when idling - if( fOverhead2 <= 0.0 && iOverheadDown == 0 ) { - control_pantographs_setup( shuntpantographsetup ); - } - } - else { - if( !mvOccupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || mvPantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 ) - { - } - else - { - // spending a longer at a stop, raise also front pantograph - if (iDirection >= 0 && useregularpantographlayout) - { - // jak jedzie w kierunku sprzęgu 0 - if (mvPantographUnit->PantFrontVolt == 0.0) - { - cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h - } - } - else - { - if (mvPantographUnit->PantRearVolt == 0.0) - { - cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h - } - } - } - } -} - -// raises the pantographs of the suggested setup (bit 0: front, bit 1: rear) and lowers the others, these only once -// a pantograph of the setup collects the voltage, so the vehicle doesn't lose its power on the way -void -TController::control_pantographs_setup( int const Setup ) { - - auto const front { ( Setup & 1 << 0 ) != 0 }; - auto const rear { ( Setup & 1 << 1 ) != 0 }; - if( front ) { - cue_action( driver_hint::frontpantographvalveon ); - } - if( rear ) { - cue_action( driver_hint::rearpantographvalveon ); - } - if( auto const setuplive { ( front && mvPantographUnit->PantFrontVolt != 0.0 ) || ( rear && mvPantographUnit->PantRearVolt != 0.0 ) }; - false == setuplive ) { - return; - } - if( false == front ) { - cue_action( driver_hint::frontpantographvalveoff ); - } - if( false == rear ) { - cue_action( driver_hint::rearpantographvalveoff ); - } -} - -void -TController::control_horns( double const Timedelta ) { - // horn control - if( fWarningDuration > 0.0 ) { - // jeśli pozostało coś do wytrąbienia trąbienie trwa nadal - if( mvOccupied->WarningSignal == 0 ) { - cue_action( driver_hint::hornon, 1 ); // low tone horn by default - } - } - else { - if( mvOccupied->WarningSignal != 0 ) { - cue_action( driver_hint::hornoff ); // a tu się kończy - } - } - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { - // jesli jedzie, można odblokować trąbienie, bo się wtedy nie włączy - iDrivigFlags &= ~moveStartHornDone; // zatrąbi dopiero jak następnym razem stanie - iDrivigFlags |= moveStartHorn; // i trąbić przed następnym ruszeniem - } - - if( true == TestFlag(iDrivigFlags, moveStartHornNow) - && true == Ready - && true == iEngineActive - && mvControlling->MainCtrlPowerPos() > 0 ) { - // uruchomienie trąbienia przed ruszeniem - fWarningDuration = 0.3; // czas trąbienia - cue_action( driver_hint::hornon, pVehicle->iHornWarning ); // wysokość tonu (2=wysoki) - iDrivigFlags |= moveStartHornDone; // nie trąbić aż do ruszenia - iDrivigFlags &= ~moveStartHornNow; // trąbienie zostało zorganizowane - } -} - -void -TController::control_security_system( double const Timedelta ) { - if( mvOccupied->SecuritySystem.is_cabsignal_blinking() && mvOccupied->SecuritySystem.has_separate_acknowledge()) { - // jak zadziałało SHP - if( false == is_emu() - && mvOccupied->DirActive == 0 ) { - cue_action( driver_hint::directionforward ); - } - cue_action( driver_hint::shpsystemreset ); // to skasuj - if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types - && AccDesired > 0.0 - && mvOccupied->SecuritySystem.is_braking() ) { - cue_action( driver_hint::trainbrakerelease ); - } - } - - if( mvOccupied->SecuritySystem.is_blinking() ) { - // jak zadziałało CA/SHP - if( false == is_emu() - && mvOccupied->DirActive == 0 ) { - cue_action( driver_hint::directionforward ); - } - cue_action( driver_hint::securitysystemreset ); // to skasuj - if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types - && AccDesired > 0.0 - && mvOccupied->SecuritySystem.is_braking() ) { - cue_action( driver_hint::trainbrakerelease ); - } - } - // basic emergency stop handling, while at it - if( true == mvOccupied->RadioStopFlag // radio-stop - && mvOccupied->Vel < 0.01 // and actual stop - && true == mvOccupied->Radio ) { // and we didn't touch the radio yet - // turning off the radio should reset the flag, during security system check - if( m_radiocontroltime > 5.0 ) { // arbitrary delay between stop and disabling the radio - cue_action( driver_hint::radiooff ); - } - else { - m_radiocontroltime += Timedelta; - } - } - if( iEngineActive - && ( false == mvOccupied->Radio || false == mvOccupied->RadioFuse ) - && false == mvOccupied->RadioStopFlag ) { - // otherwise if it's safe to do so, turn the radio back on - // arbitrary 5 sec delay before switching radio back on - m_radiocontroltime = std::min( m_radiocontroltime, 5.0 ); - if( m_radiocontroltime < 0.0 ) { - // hint at whichever of the two is open, the radio's switch or the cut-off in its power supply - if( false == mvOccupied->RadioFuse ) { - cue_action( driver_hint::radiofuseon ); - } - if( false == mvOccupied->Radio ) { - cue_action( driver_hint::radioon ); - } - } - else { - m_radiocontroltime -= Timedelta; - } - } -} - -void -TController::control_handles() { - - switch( mvControlling->EngineType ) { - case TEngineType::ElectricSeriesMotor: { - // styczniki liniowe rozłączone yBARC - if( false == mvControlling->StLinFlag - && false == mvControlling->DelayCtrlFlag - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - // if the power station is heavily burdened drop down to series mode to reduce the load - auto const useseriesmodevoltage { - std::lerp( - mvControlling->EnginePowerSource.CollectorParameters.MinV, - mvControlling->EnginePowerSource.CollectorParameters.MaxV, - IsHeavyCargoTrain ? 0.35 : 0.40 ) }; - - if( fVoltage <= useseriesmodevoltage ) { - cue_action( driver_hint::mastercontrollersetseriesmode ); - } - // sanity check - if( false == Ready - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - break; - } - case TEngineType::DieselElectric: { - // styczniki liniowe rozłączone yBARC - if( false == mvControlling->StLinFlag - && false == mvControlling->DelayCtrlFlag - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - // sanity check - if( false == Ready - && mvControlling->MainCtrlPowerPos() > 1 ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - break; - } - default: { - break; - } } // enginetype -} - -// moves the light preset selector to the position matching the lights set directly by the AI, -// otherwise the next SetLights() call (e.g. from CheckVehicles()) reverts them to the untouched selector position -void -TController::sync_lights_selector() { - - if( mvOccupied->LightsPosNo <= 0 ) { return; } - - auto const *headvehicle { pVehicles[ end::front ] }; - if( headvehicle == nullptr ) { return; } - // same choice of the light table as in TDynamicObject::SetLights() - auto const lightstable { ( mvOccupied->CabOccupied * pVehicle->DirectionGet() >= 0 ? end::front : end::rear ) }; - // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() - auto const headend { ( headvehicle->iDirection > 0 ? end::front : end::rear ) }; - auto const position { handover::light_selector_position( - *mvOccupied, lightstable, headvehicle->MoverParameters->iLights[ headend ], headvehicle->LightList( headend ) ) }; - if( position == mvOccupied->LightsPos ) { return; } - - mvOccupied->LightsPos = position; - // visual feedback - auto *train { simulation::Trains.find( pVehicle->name() ) }; - if( train != nullptr ) { - train->ggLightsButton.PutValue( static_cast( position - 1 ) ); - } -} - -// re-applies the headlight dimmer state after the AI handed the vehicle over to the human driver, -// moving the dimmer out of the off position if it'd hide the head lights set by the AI -void -TController::sync_lights_dimmer() { - - if( mvOccupied->dimPositions.empty() ) { return; } - - auto const *headvehicle { pVehicles[ end::front ] }; - auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? end::front : end::rear ) }; - auto const headlightson { - headvehicle != nullptr - && ( headvehicle->MoverParameters->iLights[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; - - auto const position { handover::dimmer_position( *mvOccupied, headlightson ) }; - if( position != mvOccupied->modernDimmerPosition ) { - mvOccupied->modernDimmerPosition = position; - // visual feedback - auto *train { simulation::Trains.find( pVehicle->name() ) }; - if( train != nullptr ) { - train->ggModernLightDimSw.PutValue( static_cast( position ) ); - } - } - if( position < 0 || position >= static_cast( mvOccupied->dimPositions.size() ) ) { return; } // SetLightDimmings() doesn't check the range - pVehicle->SetLightDimmings(); -} - -// activate consist lamp codes -void -TController::control_lights() { - - if( is_train() ) { - // jeśli jazda pociągowa - if( true == TestFlag( OrderCurrentGet(), Obey_train ) ) { - // head lights - if( m_lighthints[ end::front ] == -1 ) { - cue_action( driver_hint::headcodepc1 ); - } - else if( m_lighthints[ end::front ] == ( light::redmarker_left | light::headlight_right | light::headlight_upper ) ) { - cue_action( driver_hint::headcodepc2 ); - } - else { - // custom light pattern - if( AIControllFlag ) { - pVehicles[ end::front ]->RaLightsSet( m_lighthints[ end::front ], -1 ); - } - } - // tail lights - if( m_lighthints[ end::rear ] == -1 ) { - cue_action( driver_hint::headcodepc5 ); - } - else { - if( AIControllFlag ) { - pVehicles[ end::rear ]->RaLightsSet( -1, m_lighthints[ end::rear ] ); - } - } - } - // for shunting mode - else if( OrderCurrentGet() & ( Shunt | Loose_shunt | Connect ) ) { - cue_action( driver_hint::headcodetb1 ); - } - } - else if( is_car() ) { - Lights( - light::headlight_left | light::headlight_right, - light::redmarker_left | light::redmarker_right ); - } -} - -void -TController::control_compartment_lights() { - // compartment lights - if( mvOccupied->CompartmentLights.start_type != start_t::manual ) { return; } - - auto const currentlightstate { mvOccupied->CompartmentLights.is_enabled }; - auto const lightlevel { Global.fLuminance * ConsistShade }; - auto const desiredlightstate{ ( - currentlightstate ? - lightlevel < 0.40 : // turn off if lighting level goes above 0.4 - lightlevel < 0.35 ) }; // turn on if lighting level goes below 0.35 - if( desiredlightstate != currentlightstate ) { - cue_action( desiredlightstate ? driver_hint::consistlightson : driver_hint::consistlightsoff ); - } -} - -void -TController::control_doors() { - - if( false == doors_open() ) { return; } - // jeżeli jedzie - // nie zamykać drzwi przy drganiach, bo zatrzymanie na W4 akceptuje niewielkie prędkości - if( mvOccupied->Vel > EU07_AI_MOVEMENT ) { - Doors( false ); - return; - } - // HACK: crude way to deal with automatic door opening on W4 preventing further ride - // for human-controlled vehicles with no door control and dynamic brake auto-activating with door open - // TODO: check if this situation still happens and the hack is still needed - if( false == AIControllFlag && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { - // for diesel engines react when engine is put past idle revolutions - // for others straightforward master controller check - Doors(false); - return; - } -} - -void -TController::UpdateCommand() { - - if( false == mvOccupied->CommandIn.Command.empty() && false == mvOccupied->RunInternalCommand() ) { - // rozpoznaj komende bo lokomotywa jej nie rozpoznaje - RecognizeCommand(); // samo czyta komendę wstawioną do pojazdu? - } -} - -void -TController::UpdateNextStop() { - - if( fLastStopExpDist > 0.0 - && mvOccupied->DistCounter > fLastStopExpDist ) { - // zaktualizować wyświetlanie rozkładu - TrainParams.StationStart = TrainParams.StationIndex; - fLastStopExpDist = -1.0; // usunąć licznik - if( true == m_makenextstopannouncement ) { - announce( announcement_t::next ); - m_makenextstopannouncement = false; // keep next stop announcements suppressed until another scheduled stop - } - } -} - -void -TController::determine_braking_distance() { - // przybliżona droga hamowania - // NOTE: we're ensuring some minimal braking distance to reduce ai flipping states between starting and braking - auto const velceil { std::max( 2.0, std::ceil( mvOccupied->Vel ) ) }; - fBrakeDist = fDriverBraking * velceil * ( 40.0 + velceil ); - if( fMass > 1000000.0 ) { - // korekta dla ciężkich, bo przeżynają - da to coś? - fBrakeDist *= 2.0; - } - if( -fAccThreshold > 0.05 - && mvOccupied->CategoryFlag == 1 ) { - fBrakeDist = velceil * velceil / 25.92 / -fAccThreshold; - } - if( mvOccupied->BrakeDelayFlag == bdelay_G ) { - // dla nastawienia G koniecznie należy wydłużyć drogę na czas reakcji - fBrakeDist += 2 * velceil; - } - if( mvOccupied->Vel > 15.0 - && mvControlling->EngineType == TEngineType::ElectricInductionMotor - && is_emu() ) { - // HACK: make the induction motor powered EMUs start braking slightly earlier - fBrakeDist += 10.0; - } -/* - // take into account effect of gravity (but to stay on safe side of calculations, only downhill) - if( fAccGravity > 0.025 ) { - fBrakeDist *= ( 1.0 + fAccGravity ); - // TBD: use version which shortens route going uphill, too - //fBrakeDist = std::max( fBrakeDist, fBrakeDist * ( 1.0 + fAccGravity ) ); - } -*/ -} - -void -TController::scan_route( double const Range ) { - - TableCheck( Range ); -} - -// check for potential collisions -void -TController::scan_obstacles( double const Range ) { - // HACK: vehicle order in the consist is based on intended travel direction - // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist - // we cast to int to avoid getting confused by microstutters - auto *frontvehicle { pVehicles[ ( static_cast( mvOccupied->V ) * iDirection >= 0 ? end::front : end::rear ) ] }; - - int routescandirection; - // for moving vehicle determine heading from velocity; for standing fall back on the set direction - if( std::abs(frontvehicle->MoverParameters->V) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" - frontvehicle->MoverParameters->V > 0.0 : - pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) { - // towards coupler 0 - routescandirection = end::front; - } - else { - // towards coupler 1 - routescandirection = end::rear; - } -/* - if( pVehicle->MoverParameters->CabOccupied < 0 ) { - // flip the scan direction in the rear cab - routescandirection ^= routescandirection; - } -*/ - Obstacle = neighbour_data(); - auto const obstaclescanrange { std::max( is_car() ? 250.0 : 1000.0, Range ) }; - auto const lookup { frontvehicle->find_vehicle( routescandirection, obstaclescanrange ) }; - - if( std::get( lookup ) == true ) { - - Obstacle.vehicle = std::get( lookup ); - Obstacle.vehicle_end = std::get( lookup ); - Obstacle.distance = std::get( lookup ); - - if( Obstacle.distance < ( is_car() ? 50 : 100 ) ) { - // at short distances (re)calculate range between couplers directly - Obstacle.distance = TMoverParameters::CouplerDist( frontvehicle->MoverParameters, Obstacle.vehicle->MoverParameters ); - } - } -} - -void -TController::determine_proximity_ranges() { - // ustalenie dystansów w pozostałych przypadkach - switch (OrderCurrentGet()) - { - case Connect: { - // podłączanie do składu - if (iDrivigFlags & moveConnect) { - // jeśli stanął już blisko, unikając zderzenia i można próbować podłączyć - fMinProximityDist = -1.0; - fMaxProximityDist = 0.0; //[m] dojechać maksymalnie - fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu - } - else { - // jak daleko, to jazda jak dla Shunt na kolizję - fMinProximityDist = 2.0; - fMaxProximityDist = 5.0; //[m] w takim przedziale odległości powinien stanąć - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 1.0; // margines prędkości powodujący załączenie napędu - } - break; - } - case Disconnect: { - // 20.07.03 - manewrowanie wagonami - fMinProximityDist = 1.0; - fMaxProximityDist = 10.0; //[m] - fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu - break; - } - case Shunt: { - // na jaką odleglość i z jaką predkością ma podjechać - // TODO: test if we can use the distances calculation from obey_train - fMinProximityDist = std::min( 5 + iVehicles, 25 ); - fMaxProximityDist = std::min( 10 + iVehicles, 50 ); - // HACK: modern vehicles might brake slower at low speeds, increase safety margin as crude counter - if( mvControlling->EIMCtrlType > 0 ) { - fMinProximityDist += 5.0; - fMaxProximityDist += 5.0; - } - // take into account weather conditions - if (Global.FrictionWeatherFactor < 1.f - && iVehicles > 1 ) { - fMinProximityDist += 5.0; - fMaxProximityDist += 5.0; - } - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - // margines prędkości powodujący załączenie napędu - // były problemy z jazdą np. 3km/h podczas ładowania wagonów - fVelMinus = std::min( 0.1 * fShuntVelocity, 3.0 ); - break; - } - case Loose_shunt: { - fMinProximityDist = -1.0; - fMaxProximityDist = 0.0; //[m] dojechać maksymalnie - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu - break; - } - case Obey_train: { - // na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody - // jeśli pociąg - if( is_train() ) { - auto const [ minproximity, maxproximity ] { train_proximity_margins( IsAtPassengerStop ) }; - fMinProximityDist = minproximity; - fMaxProximityDist = maxproximity; - - if( iDrivigFlags & moveLate ) { - // jeśli spóźniony, to gna - fVelMinus = 1.0; - // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelPlus = 5.0; - } - else { - // gdy nie musi się sprężać - // margines prędkości powodujący załączenie napędu; min 1.0 żeby nie ruszał przy 0.1 - fVelMinus = std::clamp( std::round( 0.05 * VelDesired ), 1.0, 5.0 ); - // normalnie dopuszczalne przekroczenie to 5% prędkości ale nie więcej niż 5km/h - // bottom margin raised to 2 km/h to give the AI more leeway at low speed limits - fVelPlus = std::clamp( std::ceil( 0.05 * VelDesired ), 2.0, 5.0 ); - } - } - // samochod (sokista też) - else { - fMinProximityDist = std::max( 3.5, mvOccupied->Vel * 0.2 ); - fMaxProximityDist = std::max( 9.5, mvOccupied->Vel * 0.375 ); //[m] - if( Global.FrictionWeatherFactor < 1.f ) { - // take into account weather conditions - fMinProximityDist += 0.75; - fMaxProximityDist += 0.75; - } - // margines prędkości powodujący załączenie napędu - fVelMinus = 2.0; - // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelPlus = std::min( 10.0, mvOccupied->Vel * 0.1 ); - } - break; - } - case Bank: { - // TODO: implement - break; - } - default: { - fMinProximityDist = 5.0; - fMaxProximityDist = 10.0; //[m] - fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania - fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu - } - } // switch OrderList[OrderPos] -} - -void -TController::check_departure() { - - if(( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank | Connect ) ) == 0 ) { return; } - // odjechać sam może tylko jeśli jest w trybie jazdy - // automatyczne ruszanie po odstaniu albo spod SBL - if( VelSignal == 0.0 - && WaitingTime > 0.0 - && mvOccupied->RunningTrack.Velmax != 0.0 ) { - // jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość - if( OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank) - && iDrivigFlags & moveStopHere ) { - // zakaz ruszania z miejsca bez otrzymania wolnej drogi - WaitingTime = -WaitingExpireTime; - } - else { - if( mvOccupied->CategoryFlag & 1 ) { // jeśli pociąg - PrepareDirection(); // zmieni ustawiony kierunek - SetVelocity( 20, 20 ); // jak się nastał, to niech jedzie 20km/h - WaitingTime = 0.0; - fWarningDuration = 1.5; // a zatrąbić trochę - } - else { // samochód ma stać, aż dostanie odjazd, chyba że stoi przez kolizję - if( eStopReason == stopBlock - && Obstacle.distance > fDriverDist ) { - PrepareDirection(); // zmieni ustawiony kierunek - SetVelocity( -1, -1 ); // jak się nastał, to niech jedzie - WaitingTime = 0.0; - } - } - } - } - else if( VelSignal == 0.0 && VelNext > 0.0 && mvOccupied->Vel < 1.0 && (iCoupler > 0 || (iDrivigFlags & moveStopHere) == 0) ) { - // Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!! - SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL - } -} - -// verify progress of load exchange -void -TController::check_load_exchange() { - - ExchangeTime = 0.f; - DoesAnyDoorNeedOpening = false; - - if( fStopTime > 0 ) { return; } - - // czas postoju przed dalszą jazdą (np. na przystanku) - auto *vehicle { pVehicles[ end::front ] }; - while( vehicle != nullptr ) { - auto const vehicleexchangetime { vehicle->LoadExchangeTime() }; - DoesAnyDoorNeedOpening |= vehicleexchangetime > 0 && vehicle->LoadExchangeSpeed() == 0; - ExchangeTime = std::max( ExchangeTime, vehicleexchangetime ); - vehicle = vehicle->Next(); - } - - if( pVehicle->DirectionGet() != m_lastexchangedirection ) { - // generally means the ai driver moved to the opposite end of the consist - // TODO: investigate whether user playing with the reverser can mess this up - auto const left { m_lastexchangedirection > 0 ? 1 : 2 }; - auto const right { 3 - left }; - m_lastexchangeplatforms = - ( ( m_lastexchangeplatforms & left ) != 0 ? right : 0 ) - + ( ( m_lastexchangeplatforms & right ) != 0 ? left : 0 ); - m_lastexchangedirection = pVehicle->DirectionGet(); - } - if( false == TrainParams.IsMaintenance() - && ( false == TestFlag(iDrivigFlags, moveDoorOpened) - || true == DoesAnyDoorNeedOpening ) ) { - iDrivigFlags |= moveDoorOpened; // nie wykonywać drugi raz - remove_hint( driver_hint::doorleftopen ); - remove_hint( driver_hint::doorrightopen ); - Doors( true, m_lastexchangeplatforms ); - } -} - -void -TController::UpdateChangeDirection() { - // TODO: rework into driver mode independent routine - if( false == TestFlag( OrderCurrentGet(), Change_direction ) ) { return; } - - if( true == AIControllFlag && mvOccupied->Vel < EU07_AI_NOMOVEMENT ) { - // sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą) - // jeśli się zatrzymał, to zmieniamy kierunek jazdy, a nawet kabinę/człon - Activation(); // ustawienie zadanego wcześniej kierunku i ewentualne przemieszczenie AI - // Change_direction (tylko dla AI) - } - // shared part of the routine, implement if direction matches what was requested - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT - && iDirection == iDirectionOrder ) { - // NOTE: we can't be sure there's a visible signal within scan range after direction change - // which would normally overwrite the old limit, so we reset signal value manually here - VelSignal = -1; - VelSignalNext = -1; - PrepareEngine(); - JumpToNextOrder(); // następnie robimy, co jest do zrobienia (Shunt albo Obey_train) - if( OrderCurrentGet() & (Shunt | Loose_shunt | Connect) && false == TestFlag(iDrivigFlags, moveStopHere) ) { - // jeśli dalej mamy manewry - // o ile nie ma stać w miejscu, - // jechać od razu w przeciwną stronę i nie trąbić z tego tytułu: - iDrivigFlags &= ~moveStartHorn; - SetVelocity(fShuntVelocity, fShuntVelocity); - } - } -} - -void -TController::UpdateLooseShunt() { - // when loose shunting try to detect situations where engaged brakes in a consist to be pushed prevent movement - // TODO: run also for potential settings-based virtual assistant - auto const autobrakerelease { ( true == AIControllFlag ) }; - - if( autobrakerelease - && Obstacle.distance < 1.0 - && AccDesired > 0.1 - && mvOccupied->Vel < 1.0 ) { - - auto *vehicle { Obstacle.vehicle }; - auto const direction { ( vehicle->Prev() != nullptr ? end::front : end::rear ) }; - while( vehicle != nullptr ) { - if( vehicle->MoverParameters->BrakePress > 0.2 ) { - vehicle->MoverParameters->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował - vehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać - } - // NOTE: we trust the consist to be arranged in a valid chain - // TBD, TODO: traversal direction validation? - vehicle = direction == end::front ? vehicle->Prev() : vehicle->Next(); - } - } -} - -void -TController::UpdateObeyTrain() { - - UpdateNextStop(); - - if( (iDrivigFlags & moveGuardSignal) != 0 - && VelDesired > 0.0 ) { - // komunikat od kierownika tu, bo musi być wolna droga i odczekany czas stania - iDrivigFlags &= ~moveGuardSignal; // tylko raz nadać - iDrivigFlags &= ~moveGuardOpenDoor; // nie trzeba już otwierać drzwi - if( false == tsGuardSignal.empty() ) { - tsGuardSignal.stop(); - // w zasadzie to powinien mieć flagę, czy jest dźwiękiem radiowym, czy bezpośrednim - // albo trzeba zrobić dwa dźwięki, jeden bezpośredni, słyszalny w - // pobliżu, a drugi radiowy, słyszalny w innych lokomotywach - // na razie zakładam, że to nie jest dźwięk radiowy, bo trzeba by zrobić - // obsługę kanałów radiowych itd. - if( iGuardRadio == 0 ) { - // jeśli nie przez radio - tsGuardSignal.owner( pVehicle ); - // place virtual conductor some distance away - tsGuardSignal.offset( { pVehicle->MoverParameters->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); - tsGuardSignal.play( sound_flags::exclusive ); - // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera - fActionTime = -5.0; // niech trochę potrzyma - } - else { - // radio message - tsGuardSignal.owner( pVehicle ); -/* - tsGuardSignal.offset( { 0.f, 2.f, pVehicle->MoverParameters->Dim.L * 0.4f * ( pVehicle->MoverParameters->CabOccupied < 0 ? -1 : 1 ) } ); - tsGuardSignal.play( sound_flags::exclusive ); -*/ - simulation::radio_message( &tsGuardSignal, iGuardRadio ); - // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera - fActionTime = -5.0; // niech trochę potrzyma - } - } - } -} - -void -TController::UpdateConnect() { - // podłączanie do składu - if (iDrivigFlags & moveConnect) { - // sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec - auto *vehicle { iCouplingVehicle.value().first }; - auto const couplingend { iCouplingVehicle.value().second }; - auto *vehicleparameters { vehicle->MoverParameters }; - auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] }; - // vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520) - auto expectedcoupling { iCoupler }; - if( neighbour.vehicle != nullptr ) { - auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr }; - expectedcoupling = vehicleparameters->CompatibleCoupling( couplingend, *neighbour.vehicle->MoverParameters, neighbourend, iCoupler ); - } - if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) { - if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) { - // check whether we need to attach coupler adapter - auto coupleriscompatible{true}; - auto const &coupler{vehicleparameters->Couplers[couplingend]}; - if (coupler.type() != TCouplerType::Automatic) - { - auto const &othercoupler = neighbour.vehicle->MoverParameters->Couplers[(neighbour.vehicle_end != 2 ? neighbour.vehicle_end : coupler.ConnectedNr)]; - if (othercoupler.type() == TCouplerType::Automatic) - { - coupleriscompatible = false; - cue_action(driver_hint::couplingadapterattach, couplingend); - } - } - // próba podczepienia - if ((AIControllFlag || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2) - { - vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->MoverParameters, iCoupler); - } - } - } - // NOTE: no else as the preceeding block can potentially establish expected connection - if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) { - // jeżeli został podłączony - CheckVehicles( Connect ); // sprawdzić światła nowego składu - - iCoupler = 0; // dalsza jazda manewrowa już bez łączenia - iCouplingVehicle.reset(); - iDrivigFlags &= ~moveConnect; // zdjęcie flagi doczepiania - JumpToNextOrder( true ); // wykonanie następnej komendy - } - } // moveConnect - else { - // początek podczepiania, z wyłączeniem sprawdzania fTrackBlock - if( Obstacle.distance <= 20.0 && !iCouplingVehicle ) { - // write down which vehicle should be coupled with the target consist, - // so we don't lose track of it if the user does something unexpected - iCouplingVehicle = {pVehicles[end::front], (pVehicles[end::front]->DirectionGet() > 0 ? end::front : end::rear)}; - iDrivigFlags |= moveConnect; - } - } -} - -void -TController::GuardOpenDoor() { - if ((iDrivigFlags & moveGuardOpenDoor) != 0) { - auto *vehicle{ pVehicles[end::front] }; - while (vehicle != nullptr && vehicle->MoverParameters->Doors.range == 0) { - vehicle = vehicle->Next(); - } - if (vehicle != nullptr && vehicle->MoverParameters->Doors.range > 0) { - auto const lewe = vehicle->DirectionGet() > 0 ? 1 : 2; - auto const prawe = 3 - lewe; - if (m_lastexchangeplatforms & lewe) { - vehicle->MoverParameters->OperateDoors(side::left, true, range_t::local); - } - if (m_lastexchangeplatforms & prawe) { - vehicle->MoverParameters->OperateDoors(side::right, true, range_t::local); - } - } - else { - iDrivigFlags &= ~moveGuardOpenDoor; - } - } -} - -int -TController::unit_count( int const Threshold ) const { - - auto *vehicle { pVehicle }; - auto unitcount { 1 }; - do { - auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu - end::rear : - end::front ) }; - auto const coupling { vehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag }; - if( coupling == coupling::faux ) { - break; - } - // jeżeli sprzęg zablokowany to liczymy człony jako jeden - if( ( coupling & coupling::permanent ) == 0 ) { - ++unitcount; - } - vehicle = vehicle->Next(); - } while( unitcount < Threshold ); - - return unitcount; -} - -void -TController::UpdateDisconnect() { - - if( iVehicleCount >= 0 ) { - // early test for human drivers, who might disregard the proper procedure, or perform it before they receive the order to - if( false == AIControllFlag && unit_count(iVehicleCount + 2) <= iVehicleCount + 1 ) { - // iVehicleCount = 0 means the consist should be reduced to (1) leading unit, thus we increase our test values by 1 - iVehicleCount = -2; // odczepiono, co było do odczepienia - return; // we'll wrap up the procedure on the next update beat - } - // regular uncoupling procedure, performed by ai and naively expected from the human drivers - // 3rd stage: change direction, compress buffers and uncouple - if( iDirection != iDirectionOrder ) { - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( driver_hint::directionother ); - } - if( (iDrivigFlags & movePress) != 0 && iDirection == iDirectionOrder ) { - if( iVehicleCount >= 0 ) { - // zmieni się po odczepieniu - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: actuating and compressing buffers..." ); - cue_action( driver_hint::independentbrakerelease ); - cue_action( driver_hint::bufferscompress ); - } - - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: from " + ( mvOccupied->DirAbsolute > 0 ? "front" : "rear" ) ); - auto *decoupledvehicle { pVehicle }; // pojazd do odczepienia, w (pVehicle) siedzi AI - int decoupledend; // numer sprzęgu, który sprawdzamy albo odczepiamy - auto vehiclecount { iVehicleCount }; // ile wagonów ma zostać - // szukanie pojazdu do odczepienia - do { - decoupledend = decoupledvehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu - end::front : - end::rear; - // jeżeli sprzęg zablokowany to liczymy człony jako jeden - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag & coupling::permanent ) { - ++vehiclecount; - } - if( decoupledvehicle != pVehicle ) { - decoupledvehicle->MoverParameters->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać - } - if( vehiclecount ) { // jeśli jeszcze nie koniec - decoupledvehicle = decoupledvehicle->Prev(); // kolejny w stronę czoła składu (licząc od tyłu), bo dociskamy - if( decoupledvehicle == nullptr ) { - vehiclecount = 0; // nie ma co dalej sprawdzać, odczepianie zakończone - } - } - } while( vehiclecount-- ); - if( decoupledvehicle == nullptr ) { - // no target, or already just virtual coupling - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: didn't find anything to disconnect" ); - iVehicleCount = -2; // odczepiono, co było do odczepienia - } - else { - if( AIControllFlag || Global.AITrainman ) { - decoupledvehicle->Dettach( decoupledend ); - } - // tylko jeśli odepnie - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].CouplingFlag == coupling::faux ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: uncoupled" ); - iVehicleCount = -2; - // update trainset state - CheckVehicles( Disconnect ); - // potentially remove coupler adapter -/* - if( decoupledvehicle->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { - decoupledvehicle->remove_coupler_adapter( decoupledend ); - } -*/ - if( pVehicles[ end::front ]->MoverParameters->Couplers[ decoupledend ].has_adapter() ) { - cue_action( driver_hint::couplingadapterremove, decoupledend ); - } - } - } // a jak nie, to dociskać dalej - } - // 2nd stage: apply consist brakes and change direction - if( ( iDrivigFlags & movePress ) == 0 ) { - // store initial consist direction - if( !iDirectionBackup ) { - iDirectionBackup = iDirection; - } - if( false == IsConsistBraked ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: applying consist brakes..." ); - cue_action( driver_hint::trainbrakeapply ); - } - // jeśli w miarę został zahamowany (ciśnienie mniejsze niż podane na pozycji 3, zwyle 0.37) - else { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: direction change" ); -/* // TODO: test if this block is needed - if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { - // wyłączenie EP, gdy wystarczy (może nie być potrzebne, bo na początku jest) - mvOccupied->BrakeLevelSet( 0 ); - } -*/ - iDirectionOrder = -iDirection; // zmiana kierunku jazdy na przeciwny (dociskanie) - iDrivigFlags |= movePress; // następnie będzie dociskanie - } - } - } // odczepianie - if( iVehicleCount < 0 ) { - // 4th stage: restore initial direction - if( iDirectionBackup ) { - iDirectionOrder = iDirectionBackup.value(); - iDirectionBackup.reset(); - } - if( iDirection != iDirectionOrder ) { - WriteLog( "Uncoupling [" + mvOccupied->Name + "]: second direction change" ); - cue_action( driver_hint::mastercontrollersetreverserunlock ); - cue_action( driver_hint::directionother ); // zmiana kierunku jazdy na właściwy - } - // 5th stage: clean up and move on to next order - if( iDirection == iDirectionOrder ) { - iDrivigFlags &= ~movePress; // koniec dociskania - JumpToNextOrder( true ); // zmieni światła - TableClear(); // skanowanie od nowa - iDrivigFlags &= ~moveStartHorn; // bez trąbienia przed ruszeniem - } - } -} - -void -TController::handle_engine() { - // HACK: activate route scanning if an idling vehicle is activated by a human user - if( OrderCurrentGet() == Wait_for_orders - && false == iEngineActive -// && ( false == AIControllFlag ) - && true == mvOccupied->Power24vIsAvailable ) { - OrderNext( Prepare_engine ); - } - // basic engine preparation - if( OrderCurrentGet() == Prepare_engine && PrepareEngine() ) { - // gotowy do drogi? - JumpToNextOrder(); - } - // engine state can potentially deteriorate in one of usual driving modes - if( OrderCurrentGet() & (Change_direction | Connect | Disconnect | Shunt | Loose_shunt | Obey_train | Bank) - && false == iEngineActive ) { - // jeśli coś ma robić to niech odpala do skutku - PrepareEngine(); - } -} - -void -TController::handle_orders() { - - switch (OrderCurrentGet()) - { - case Release_engine: { - if( ReleaseEngine() ) { // zdana maszyna? - JumpToNextOrder(); - } - break; - } - case Obey_train: { - UpdateObeyTrain(); - break; - } - case Loose_shunt: { - UpdateLooseShunt(); - break; - } - case Connect: { - UpdateConnect(); - break; - } - case Disconnect: { - UpdateDisconnect(); - break; - } - case Jump_to_first_order: { - if( OrderPos > 1 ) { - OrderPos = 1; // w zerowym zawsze jest czekanie - } - else { - ++OrderPos; - } -#if LOGORDERS - OrdersDump("Jump_to_first_order"); -#endif - break; - } - default: { - // special case, change_direction potentially received during partially completed coupling operation - // this is unlikely to happen for the AI, but can happen for a (slower) human user - if( TestFlag( iDrivigFlags, moveConnect ) ) { - UpdateConnect(); - } - break; - } - } // switch OrderList[OrderPos] - UpdateChangeDirection(); -} - -// the stages of uncoupling: each one sets the speed for the next -void -TController::set_velocity_for_uncoupling() { - - if( iVehicleCount < 0 ) { - // 4th stage: restore initial direction - if( ( iDrivigFlags & movePress ) != 0 ) { - SetVelocity( 0, 0, stopJoin ); - } - return; - } - // 3rd stage: compress buffers and uncouple - if( ( iDrivigFlags & movePress ) != 0 && iDirection == iDirectionOrder ) { - SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2 - return; - } - // 1st stage: bring it to stop - // 2nd stage: apply consist brakes and change direction - SetVelocity( 0, 0, stopJoin ); -} - -// uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released -// brake applies; so the train brake goes on while the train is coming to a stand, stays on while it -// stands, and is applied for real if the train has started to roll back -void -TController::hold_train_coming_to_stand_uphill() { - - if( ( false == is_train() ) - || ( ( OrderCurrentGet() & Obey_train ) == 0 ) - || ( VelNext != 0.0 ) - || ( ActualProximityDist > fMaxProximityDist ) - || ( fAccGravity >= EU07_AI_UPHILLGRAVITY ) ) { - return; - } - auto const vel { DirectionalVel() }; - if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) { - VelDesired = 0.0; - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - return; - } - if( ( vel < 0.0 ) - || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) - // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops: - // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any - // sooner and the brake takes off more of the distance than the stop was planned with - || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) - // not for a train that is short of where it is to stop and is to pull up further - && ( AccDesired <= 0.0 ) - && ( vel / 3.6 / -fAccGravity <= 0.5 * brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { - // the gradient alone already slows the train down nearly this much; ask for enough on top of it that - // the brake is applied for sure, not held back by the margin against small corrections - AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() ); - } -} - -void -TController::pick_optimal_speed( double const Range ) { - -// if( ( OrderCurrentGet() & ( Shunt | Loose_shunt | Obey_train | Bank | Connect | Disconnect | Change_direction ) ) == 0 ) { return; } - - // set initial velocity and acceleration values - SetDriverPsyche(); // ustawia AccPreferred (potrzebne tu?) - VelDesired = fVelMax; // wstępnie prędkość maksymalna dla pojazdu(-ów), będzie następnie ograniczana - AccDesired = AccPreferred; // AccPreferred wynika z osobowości mechanika - - // nie przekraczać rozkladowej - if( (OrderCurrentGet() & Obey_train) != 0 - && TrainParams.TTVmax > 0.0 ) { - VelDesired = - min_speed( - VelDesired, - TrainParams.TTVmax ); - } - -// VelNext = VelDesired; // maksymalna prędkość wynikająca z innych czynników niż trajektoria ruchu - // HACK: -1 means we can pick up 0 speed limits in ( point.velnext > velnext ) tests aimed to find highest next speed, - // but also doubles as 'max speed' in min_speed tests, so it shouldn't interfere if we don't find any speed limits - VelNext = -1.0; - - // basic velocity and acceleration adjustments - // jeśli manewry, to ograniczamy prędkość - if( ( OrderCurrentGet() & ( Obey_train | Bank ) ) == 0 ) { // spokojne manewry - SetVelocity( fShuntVelocity, fShuntVelocity ); - VelDesired = - min_speed( - VelDesired, - fShuntVelocity ); - } - // uncoupling mode changes velocity/acceleration between stages - if( ( OrderCurrentGet() & Disconnect ) != 0 ) { - set_velocity_for_uncoupling(); - } - - VelLimitLastDist = { VelDesired, -1 }; - SwitchClearDist = -1; - ActualProximityDist = Range; // funkcja Update() może pozostawić wartości bez zmian - - // if we're idling bail out early - if( false == is_active() ) { - VelDesired = 0.0; - VelNext = 0.0; - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - return; - } - - // Ra: odczyt (ActualProximityDist), (VelNext) i (AccPreferred) z tabelki prędkosci - check_route_ahead( Range ); - - check_departure(); - - // if ordered to turn off the vehicle, try to stop - if( true == TestFlag( OrderCurrentGet(), Release_engine ) ) { - SetVelocity( 0, 0, stopSleep ); - } - // if ordered to change direction, try to stop - if( true == TestFlag( OrderCurrentGet(), Change_direction ) ) { - SetVelocity( 0, 0, stopDir ); - } - - adjust_desired_speed_for_obstacles(); - adjust_desired_speed_for_limits(); - adjust_desired_speed_for_target_speed( Range ); - adjust_desired_speed_for_current_speed(); - adjust_desired_speed_for_braking_test(); - - // Ra 2F1I: wyłączyć kiedyś to uśrednianie i przeanalizować skanowanie, czemu migocze - if( AccDesired > EU07_AI_NOACCELERATION ) { // hamowania lepeiej nie uśredniać - AccDesired = fAccDesiredAv = - 0.2 * AccDesired + - 0.8 * fAccDesiredAv; // uśrednione, żeby ograniczyć migotanie - } - if( VelDesired == 0.0 ) { - // Ra 2F1J: jeszcze jedna prowizoryczna łatka - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - } - - // last step sanity check, until the whole calculation is straightened out - AccDesired = std::min( AccDesired, AccPreferred ); - AccDesired = std::clamp( - AccDesired, - is_car() ? -2.0 : -0.9, - is_car() ? 2.0 : 0.9 ); - - // done last, so that none of the adjustments above, made for a train moving forward, can undo it - hold_train_coming_to_stand_uphill(); - - // if the route ahead is blocked we might need to head the other way - check_route_behind( 1000 ); // NOTE: legacy scan range value -} - -void -TController::adjust_desired_speed_for_obstacles() { - // prędkość w kierunku jazdy, ujemna gdy jedzie w przeciwną stronę niż powinien - auto const vel { DirectionalVel() }; - - if (VelDesired < 0.0) - VelDesired = fVelMax; // bo VelDesired<0 oznacza prędkość maksymalną - - // Ra: jazda na widoczność - if( Obstacle.distance < 5000 ) { - // mamy coś z przodu - // prędkość pojazdu z przodu (zakładając, że jedzie w tę samą stronę!!!) - auto const k { Obstacle.vehicle->MoverParameters->Vel }; - - if( k - vel < 5 ) { - // porównanie modułów prędkości [km/h] - // zatroszczyć się trzeba, jeśli tamten nie jedzie znacząco szybciej - if( Obstacle.distance < ActualProximityDist ) { - // the vehicle ahead, not the stop found by the scan, is what the train is now to stop short of - bStopTargetIsPassengerStop = false; - } - ActualProximityDist = std::min( - ActualProximityDist, - Obstacle.distance ); - - if( Obstacle.distance <= ( - mvOccupied->CategoryFlag & 2 ? - 100.0 : // cars - 250.0 ) ) { // others - // regardless of driving mode at close distance take precaution measures: - // match the other vehicle's speed or slow down if the other vehicle is stopped - VelDesired = - min_speed( - VelDesired, - std::max( - k, - mvOccupied->CategoryFlag & 2 ? - 40.0 : // cars - 20.0 ) ); // others - if( vel > VelDesired + fVelPlus ) { - // if going too fast force some prompt braking - AccPreferred = std::min( - mvOccupied->CategoryFlag & 2 ? -0.65 : // cars - -0.30, // others - AccPreferred ); - } - } - - double const distance = Obstacle.distance - fMaxProximityDist - fBrakeDist * 1.15; // odległość bezpieczna zależy od prędkości - if( distance < 0.0 ) { - // jeśli odległość jest zbyt mała - if( k < 10.0 ) // k - prędkość tego z przodu - { // jeśli tamten porusza się z niewielką prędkością albo stoi - // keep speed difference within a safer margin - VelDesired = std::floor( - min_speed( - VelDesired, - Obstacle.distance > 100 ? k + 20.0 : std::min(8.0, k + 4.0) ) ); - - if( ( OrderCurrentGet() & ( Connect | Loose_shunt ) ) != 0 ) { - // jeśli spinanie, to jechać dalej - AccPreferred = std::min( 0.35, AccPreferred ); // nie hamuj - VelNext = std::floor( std::min( 8.0, k + 2.0 ) ); // i pakuj się na tamtego - } - else { - // a normalnie to hamować - VelNext = 0.0; - if( Obstacle.distance <= fMinProximityDist ) { - VelDesired = 0.0; - } - - if( mvOccupied->CategoryFlag & 1 - && OrderCurrentGet() & Obey_train ) { - // trains which move normally should try to stop at safe margin - ActualProximityDist -= fDriverDist; - } - } - } - else { - // jeśli oba jadą, to przyhamuj lekko i ogranicz prędkość - if( Obstacle.distance < ( - mvOccupied->CategoryFlag & 2 ? - fMaxProximityDist + 0.5 * vel : // cars - 2.0 * fMaxProximityDist + 2.0 * vel ) ) { //others - // jak tamten jedzie wolniej a jest w drodze hamowania - AccPreferred = std::min( -0.9, AccPreferred ); - VelNext = min_speed( std::round( k ) - 5.0, VelDesired ); - if( Obstacle.distance <= ( - mvOccupied->CategoryFlag & 2 ? - fMaxProximityDist : // cars - 2.0 * fMaxProximityDist ) ) { //others - // try to force speed change if obstacle is really close - VelDesired = VelNext; - } - } - } - ReactionTime = mvOccupied->Vel > EU07_AI_NOMOVEMENT ? 0.1 : // orientuj się, bo jest goraco - 2.0; // we're already standing still, so take it easy - } - else { - if( OrderCurrentGet() & Connect ) { - // if there's something nearby in the connect mode don't speed up too much - VelDesired = - min_speed( - VelDesired, - Obstacle.distance > 100 ? 20.0 : 4.0 ); - } - } - } - } -} - -void -TController::adjust_desired_speed_for_limits() { - // speed caps checks - // sprawdzamy możliwe ograniczenia prędkości - if( VelSignal >= 0 ) { - // jeśli skład był zatrzymany na początku i teraz już może jechać - VelDesired = - min_speed( - VelDesired, - VelSignal ); - } - if( mvOccupied->RunningTrack.Velmax >= 0 ) { - // ograniczenie prędkości z trajektorii ruchu - VelDesired = - min_speed( - VelDesired, - mvOccupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej! - } - if( VelforDriver >= 0 ) { - // tu jest zero przy zmianie kierunku jazdy - // Ra: tu może być 40, jeśli mechanik nie ma znajomości szlaaku, albo kierowca jeździ 70 - VelDesired = - min_speed( - VelDesired, - VelforDriver ); - } - - // recalculate potential load exchange duration - check_load_exchange(); - if( ExchangeTime > 0 - || mvOccupied->Vel > 2.0 ) { // HACK: force timer reset if the load exchange is cancelled due to departure - WaitingSet( ExchangeTime ); - } - if( fStopTime < 0 ) { - VelDesired = 0.0; // jak ma czekać, to nie ma jazdy - cue_action( driver_hint::waitloadexchange ); - return; // speed limit can't get any lower - } - - if( (OrderCurrentGet() & (Shunt | Loose_shunt | Obey_train | Bank)) != 0 && (iDrivigFlags & moveStopHere) != 0 && mvOccupied->Vel < 0.01 && VelSignalNext == 0.0 ) { - // w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu - // jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać - VelDesired = 0.0; - return; // speed limit can't get any lower - } - - if( OrderCurrentGet() == Wait_for_orders ) { - // wait means sit and wait - VelDesired = 0.0; - return; // speed limit can't get any lower - } -} - -// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time -// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G -// is tens of seconds; never shorter than the look-ahead the AI has always used -static double -brake_response_horizon( TMoverParameters const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { - - auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; - if( Brakesystem == TBrakeSystem::Pneumatic ) { - // BrakeDelay holds the release and the application time in G, then the same two in P - auto const delays { Vehicle->BrakeDelayFlag > bdelay_G ? 0 : 2 }; - auto const isrelease { Acceleration < 0.0 }; - horizon = std::max( horizon, 0.5 * Vehicle->BrakeDelay[ delays + ( isrelease ? 0 : 1 ) ] ); - } - return horizon; -} - -// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand -static double -uphill_stopping_distance( double const Velocity, double const Gravity ) { - return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) ); -} - -// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m] -static double -uphill_coasting_speed( double const Distance, double const Gravity ) { - return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); -} - -// outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the -// direction of travel -void -TController::adjust_desired_speed_for_braking_curve( double const Vel ) { - - AccDesired = AccPreferred; - if( Vel <= min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) { - return; - } - // allow to coast at reasonably low speed - auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) }; - if( auto const slowdowndistance { ( - mvOccupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance - brakingdistance : - std::max( - (OrderCurrentGet() & Connect) == 0 ? 100.0 : 25.0, - brakingdistance ) ) }; - brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) { - // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good - return; - } - // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever - auto const brakingpointoffset = ( - ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & Obey_train ) ? - stopping_margin() : // the same stopping point as the final approach - VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); - // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't - // worked out) the braking curve is the constant deceleration over the distance left, as before them - braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax }; - // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon - // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its - // independent brake, which leaves the train brake handle where it is, kept braking earlier - // and earlier the whole way in, to crawl the last tens of metres to the stop point - auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; - braking_curve::approach const approach { - Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, BrakeCtrlPosition > 0.0, - brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), - brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fillbrakea0 ) }; - auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; - AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje - if( Vel <= VelNext ) { - return; - } - if( deceleration < fAccGravity - 0.001 ) { - // no power while still above the speed being braked for - AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); - } - else if( ( fAccGravity < -0.025 ) - && ( ( OrderCurrentGet() & Obey_train ) != 0 ) - && ( false == uphill_brake_committed( Vel ) ) - && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { - // uphill the gradient alone slows the train down more than it is asked to; - // keep it rolling at the present speed until that changes - AccDesired = std::min( 0.0, AccPreferred ); - VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) ); - } -} - -// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel -void -TController::adjust_desired_speed_for_final_approach( double const Vel ) { - - if( ( mvOccupied->CategoryFlag & 1 ) == 0 ) { - // for cars (and others) coast at low speed until we hit min proximity range - VelDesired = min_speed( VelDesired, 5.0 ); - return; - } - // trains - if( ( OrderCurrentGet() & ( Shunt | Connect ) ) - && ( Obstacle.distance < 50 ) ) { - // crude detection of edge case, if approaching another vehicle coast slowly until min distance - // this should allow to bunch up trainsets more on sidings - VelDesired = min_speed( 5.0, VelDesired ); - return; - } - // hamowanie tak, aby stanąć - if( ( OrderCurrentGet() & Obey_train ) == 0 ) { - VelDesired = VelNext; - AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) ); - AccDesired = std::min( AccDesired, fAccThreshold ); - return; - } - // a train keeps its desired speed until the lower edge of the stopping window (a desired - // speed of 0 here asks for hard braking whatever the distance left), aims at the middle - // of the window, and asks only for what that takes - auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) }; - AccDesired = ( - BrakeSystem == TBrakeSystem::Pneumatic ? - // cast iron blocks grip harder as the train comes to a stand - braking_curve::shaped_demand( - Vel, VelNext, stoppingroom, fAccGravity, - { fBrake_a0, fBrake_a1, BrakeAccTableSize, mvOccupied->Vmax } ) : - ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); - if( ( fAccGravity < -0.025 ) - && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all - && ( false == uphill_brake_committed( Vel ) ) - && ( ActualProximityDist - uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) { - // uphill the gradient alone would bring the train to a stand short of the - // middle of the stopping window; keep it rolling at the present speed until that changes, - // but no faster than the gradient alone can take off by the middle of the window - AccDesired = std::min( 0.0, AccPreferred ); - VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) ); - } -} - -void -TController::adjust_desired_speed_for_target_speed( double const Range ) { - // ustalanie zadanego przyspieszenia - //(ActualProximityDist) - odległość do miejsca zmniejszenia prędkości - //(AccPreferred) - wynika z psychyki oraz uwzglęnia już ewentualne zderzenie z pojazdem z przodu, ujemne gdy należy hamować - //(AccDesired) - uwzględnia sygnały na drodze ruchu, ujemne gdy należy hamować - //(fAccGravity) - chwilowe przspieszenie grawitacyjne, ujemne działa przeciwnie do zadanego kierunku jazdy - //(AbsAccS) - chwilowe przyspieszenie pojazu (uwzględnia grawitację), ujemne działa przeciwnie do zadanego kierunku jazdy - //(AccDesired) porównujemy z (fAccGravity) albo (AbsAccS) - - // gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze - // normalna jazda - AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01; - fAccDesiredGravity = 0.0; - - auto const vel { DirectionalVel() }; - - if( VelNext >= 0.0 - && ActualProximityDist <= Range - && vel >= VelNext ) { - // gdy zbliża się i jest za szybki do nowej prędkości, albo stoi na zatrzymaniu - if (vel > EU07_AI_NOMOVEMENT) { - // jeśli jedzie - if( vel < VelNext - && ActualProximityDist > fMaxProximityDist * (1.0 + 0.1 * vel) ) { - // jeśli jedzie wolniej niż można i jest wystarczająco daleko, to można przyspieszyć - if( AccPreferred > 0.0 ) { - // jeśli nie ma zawalidrogi dojedz do semafora/przeszkody - AccDesired = AccPreferred; - } - } - else if( ( ActualProximityDist > fMinProximityDist ) - // only a stop has a final approach of its own inside the proximity range; a lower speed ahead - // keeps the braking curve below right up to where it begins, or the train would stop braking - // (and even take power) that far out - && ( VelNext == 0.0 ) - && ( ActualProximityDist < fMaxProximityDist ) ) { - // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko - // jak minął już maksymalny dystans po prostu hamuj (niski stopień) - // ma stanąć, a jest w drodze hamowania albo ma jechać - adjust_desired_speed_for_final_approach( vel ); - AccDesired = std::min( AccDesired, AccPreferred ); - } - else if (ActualProximityDist > fMinProximityDist) { - // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko - adjust_desired_speed_for_braking_curve( vel ); - AccDesired = std::min( AccDesired, AccPreferred ); - } - else { - // jest bliżej niż fMinProximityDist - // utrzymuj predkosc bo juz blisko -/* - VelDesired = min_speed( VelDesired, VelNext ); -*/ - if( VelNext == 0.0 ) { - VelDesired = VelNext; - } - else { - if( vel <= VelNext + fVelPlus ) { - // jeśli niewielkie przekroczenie, ale ma jechać - AccDesired = std::max( 0.0, AccPreferred ); // to olej (zacznij luzować) - } - } - ReactionTime = 0.1; // i orientuj się szybciej - } - } - else { - // zatrzymany (vel==0.0) - if( VelNext > 0.0 ) { - // można jechać - AccDesired = AccPreferred; - } - else { - // jeśli daleko jechać nie można - if( ActualProximityDist > ( - mvOccupied->CategoryFlag & 2 ? - fMinProximityDist : // cars - fMaxProximityDist ) ) { // trains and others - // ale ma kawałek do sygnalizatora - if( AccPreferred > 0.0 ) { - // dociagnij do semafora; - AccDesired = AccPreferred; - } - else { - //stoj - VelDesired = 0.0; - } - } - else { - // VelNext=0 i stoi bliżej niż fMaxProximityDist - VelDesired = 0.0; - } - } - } - } -} - -void -TController::adjust_desired_speed_for_current_speed() { - // decisions based on current speed - auto const vel { DirectionalVel() }; - - if( is_train() ) { - // on flats or uphill we can be less careful - if( vel > VelDesired ) { - // jesli jedzie za szybko do AKTUALNEGO - if( VelDesired == 0.0 ) { - // jesli stoj, to hamuj, ale i tak juz za pozno :) - AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie - } - else { - // slow down, not full stop - if( vel > VelDesired + fVelPlus ) { - // hamuj tak średnio - AccDesired = std::min( AccDesired, -0.05 + fAccThreshold ); - } - else { - // o 5 km/h to olej (zacznij luzować) - AccDesired = std::min( - AccDesired, // but don't override decceleration for VelNext - std::max( 0.0, AccPreferred ) ); - } - } - } - - if( fAccGravity > 0.025 ) { - // going sharply downhill we may need to start braking sooner than usual - // try to estimate increase of current velocity before engaged brakes start working - // look ahead for as long as the brake takes to respond, since that is how long the - // present acceleration will last whatever is done with the handle now; a pneumatic - // brake applies and releases on its own time scale, which in G is tens of seconds - auto const horizon { brake_response_horizon( mvOccupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; - auto const speedestimate = vel + 3.6 * horizon * AbsAccS; - // already below a lower limit ahead, the train has no business speeding up towards it - auto holdlimit { VelDesired }; - if( ( VelNext > 0.0 ) - && ( VelNext < holdlimit ) - && ( vel <= VelNext + fVelPlus ) - && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) { - holdlimit = VelNext; - } - // hold a band just below the limit; the steeper the descent the harder the train pulls - // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille) - // an electro-pneumatic or electric brake responds at once and needs far less room - auto const holdspeed { holdlimit - ( - BrakeSystem == TBrakeSystem::Pneumatic ? - std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) : - std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) }; - // the predicted difference is to be made up over the time the brake takes to respond, not at once: with a - // slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as - // long to let go, and the train ends up well below the speed it was to hold - auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) }; - if( ( speedestimate > VelDesired ) - && ( VelDesired == 0.0 ) ) { - // jesli stoj, to hamuj, ale i tak juz za pozno :) - AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie - } - else { - // one continuous law on both sides of the target, proportional to the predicted - // difference: a demand that jumps to the braking threshold above the target and to - // full acceleration below it alternates, with a brake that responds in seconds, - // between a hard application and a full release - AccDesired = std::min( - AccDesired, // but don't override decceleration for VelNext - std::clamp( - EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ), - -0.05 + fAccThreshold, - std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) ); - // HACK: for cargo trains with high braking threshold ensure we cross that threshold - auto const crossthreshold { IsCargoTrain && fBrake_a0[ 0 ] > 0.2 && speedestimate > holdlimit }; - AccDesired -= ( crossthreshold ? std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ) : 0.0 ); - } - // final tweaks - if( vel > EU07_AI_NOMOVEMENT ) { - // going downhill also take into account impact of gravity - AccDesired -= fAccGravity; - // from here on AccDesired is what the brake alone has to deliver, which is what - // IncBrake() sizes the handle position for; AbsAccS already contains the gravity, - // so the comparisons with it have to add this part back - fAccDesiredGravity = fAccGravity; - // HACK: if the max allowed speed was exceeded something went wrong; brake harder - AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 ); - } - } - // HACK: limit acceleration for cargo trains, to reduce probability of breaking couplers on sudden jolts - auto MaxAcc{ 0.5 * mvOccupied->Couplers[(mvOccupied->DirAbsolute >= 0 ? end::rear : end::front)].FmaxC / fMass }; - if( iVehicles - ControlledEnginesCount > 0 ) { - MaxAcc *= std::clamp( vel * 0.025, 0.2, 1.0 ); - } - AccDesired = std::min(AccDesired, safe_clamp(MaxAcc, HeavyCargoTrainAcceleration, AccPreferred)); - // TBD: expand this behaviour to all trains with car(s) exceeding certain weight? - /* - if( ( IsPassengerTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { - AccDesired = std::min( AccDesired, ( iVehicles - ControlledEnginesCount > 8 ? HeavyPassengetTrainAcceleration : PassengetTrainAcceleration ) ); - } - if( ( IsCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { - AccDesired = std::min( AccDesired, CargoTrainAcceleration ); - } - if( ( IsHeavyCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { - AccDesired = std::min( AccDesired, HeavyCargoTrainAcceleration ); - } */ - } - else { - // for cars the older version works better - if( vel > VelDesired ) { - // jesli jedzie za szybko do AKTUALNEGO - if( VelDesired == 0.0 ) { - // jesli stoj, to hamuj, ale i tak juz za pozno :) - AccDesired = std::min( AccDesired, -0.9 ); // hamuj solidnie - } - else { - // slow down, not full stop - if( vel > VelDesired + fVelPlus ) { - // hamuj tak średnio - AccDesired = std::min( AccDesired, -fBrake_a0[ 0 ] * 0.5 ); - } - else { - // o 5 km/h to olej (zacznij luzować) - AccDesired = std::min( - AccDesired, // but don't override decceleration for VelNext - std::max( 0.0, AccPreferred ) ); - } - } - } - } - - // NOTE: as a stop-gap measure the routine is limited to trains only while car calculations seem off - if( is_train() && vel < VelDesired && - -AccDesired * BrakeAccFactor() < (false == Ready || VelNext > vel - 40.0 ? fBrake_a0[0] * 0.8 : -fAccThreshold) / (1.2 * braking_distance_multiplier(VelNext)) ) { - // don't adjust acceleration when going above current target speed - AccDesired = std::max(EU07_AI_NOACCELERATION, AccDesired); - } -} - -// hamowanie kontrolne -void -TController::adjust_desired_speed_for_braking_test() { - -// if( false == Global.DynamicBrakeTest ) { return; } - if( DynamicBrakeTest >= 5 ) { return; } // all done - if( false == is_train() ) { return; } // not applicable - if( mvOccupied->BrakeHandle == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now - if( false == TestFlag( OrderCurrentGet(), Obey_train ) ) { return; } // not applicable - if( false == AIControllFlag ) { return; } // TBD: add notification about braking test and enable it for human driver as well? - - auto const vel { DirectionalVel() }; - // what the route ahead asks for; the test may brake harder than that, never softer - auto const routeaccdesired { AccDesired }; - auto const routeaccdesiredgravity { fAccDesiredGravity }; - auto const routeveldesired { VelDesired }; - - switch( DynamicBrakeTest ) { - case 0: { - if( primary() - && vel < VelDesired - && fAccGravity >= 0.0 // not if going uphill - && AccDesired >= EU07_AI_ACCELERATION - && TrainParams.TTVmax >= 10.0 - && vel > std::min(TrainParams.TTVmax, 60.0) - 2.0 ) { - DynamicBrakeTest = 1; - DBT_BrakingTime = ElapsedTime; - DBT_VelocityBrake = vel; - } - break; - } - case 1: { - AccDesired = EU07_AI_BRAKINGTESTACCELERATION; - fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( ElapsedTime - DBT_BrakingTime > 1 ) { - ForcePNBrake = true; - mvOccupied->EpFuseSwitch( false ); - DynamicBrakeTest = 2; - } - break; - } - case 2: { - AccDesired = EU07_AI_BRAKINGTESTACCELERATION; - fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( ElapsedTime - DBT_BrakingTime > 2 ) { - DBT_BrakingTime = ElapsedTime; - DBT_VelocityBrake = vel; - DBT_VelocityRelease = vel - 8.0; - DynamicBrakeTest = 3; - } - break; - } - case 3: { - AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 ); - fAccDesiredGravity = 0.0; - VelDesired = DBT_VelocityBrake; - if( vel <= DBT_VelocityRelease ) { - DynamicBrakeTest = 4; - DBT_BrakingTime = ElapsedTime - DBT_BrakingTime; - DBT_MidPointAcc = AbsAccS; - DBT_ReleasingTime = ElapsedTime; - } - break; - } - case 4: { - if( Ready ) { - if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { - mvOccupied->EpFuseSwitch( true ); - } - ForcePNBrake = false; - DynamicBrakeTest = 5; - DBT_ReleasingTime = ElapsedTime - DBT_ReleasingTime; - DBT_VelocityFinish = vel; - } - break; - } - default: { - break; - } - } - // a stop or a restriction coming up while the test runs takes precedence - if( ( DynamicBrakeTest >= 1 ) - && ( DynamicBrakeTest <= 3 ) - && ( routeaccdesired < AccDesired ) ) { - AccDesired = routeaccdesired; - fAccDesiredGravity = routeaccdesiredgravity; - VelDesired = std::min( VelDesired, routeveldesired ); - } -} - -void -TController::control_tractive_and_braking_force() { - -#if LOGVELOCITY - WriteLog("Dist=" + FloatToStrF(ActualProximityDist, ffFixed, 7, 1) + - ", VelDesired=" + FloatToStrF(VelDesired, ffFixed, 7, 1) + - ", AccDesired=" + FloatToStrF(AccDesired, ffFixed, 7, 3) + - ", VelSignal=" + AnsiString(VelSignal) + ", VelNext=" + - AnsiString(VelNext)); -#endif - - if (iDriverFailCount > maxdriverfails) { - Psyche = Easyman; - if (iDriverFailCount > maxdriverfails * 2) - SetDriverPsyche(); - } - - control_relays(); - control_motor_connectors(); - - // if the radio-stop was issued don't waste effort trying to fight it - if( true == mvOccupied->RadioStopFlag // radio-stop - && mvOccupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving - cue_action( driver_hint::mastercontrollersetzerospeed ); // just throttle down... - return; // ...and don't touch any other controls - } - // if we're slipping leave the controls alone, there's a separate logic section trying to deal with it - if( true == mvControlling->SlippingWheels ) { - return; - } - - // ensure train brake isn't locked - if( BrakeCtrlPosition == gbh_NP ) { - cue_action( driver_hint::trainbrakerelease ); - } - control_releaser(); - control_main_pipe(); - - control_tractive_force(); - control_braking_force(); - -#if LOGVELOCITY - WriteLog("BrakePos=" + AnsiString(mvOccupied->BrakeCtrlPos) + ", MainCtrl=" + - AnsiString(mvControlling->MainCtrlPos)); -#endif -} - -// ensure relays are active -void TController::control_relays() { - - if( fActionTime < 0.0 ) { return; } - - if( IsAnyMotorOverloadRelayOpen ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - cue_action( driver_hint::tractionnmotoroverloadreset ); - ++iDriverFailCount; - } - if( IsAnyGroundRelayOpen ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - cue_action( driver_hint::maincircuitgroundreset ); - ++iDriverFailCount; - } -} - -void TController::control_motor_connectors() { - // ensure motor connectors are active - if( (mvControlling->EngineType == TEngineType::ElectricSeriesMotor || mvControlling->EngineType == TEngineType::DieselElectric || is_emu()) && Need_TryAgain ) { - // true, jeśli druga pozycja w elektryku nie załapała - cue_action(driver_hint::mastercontrollersetzerospeed); - Need_TryAgain = false; - } -} - -void TController::control_tractive_force() { - - control_uphill_start(); - - auto const velocity { DirectionalVel() }; - // jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz... - 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) && - (ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance - fMaxProximityDist) ? // other vehicle types keep wider margin - true : - velocity + 1.0 < VelNext - // uphill, a train told to hold its speed on the way to a stop needs the power to do it - || VelNext == 0.0 && (OrderCurrentGet() & Obey_train) != 0 && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) { - // ...jeśli prędkość w kierunku czoła jest mniejsza od dozwolonej o margines... - // within proximity margin don't exceed next scheduled speed, outside of the margin accelerate as you like - // ...to można przyspieszyć - increase_tractive_force(); - } - // zmniejszanie predkosci - // margines dla prędkości jest doliczany tylko jeśli oczekiwana prędkość jest większa od 5km/h - if( false == TestFlag( iDrivigFlags, movePress ) ) { - double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0; - // jeśli nie dociskanie - if( AccDesired <= EU07_AI_NOACCELERATION ) { - cue_action( driver_hint::mastercontrollersetzerospeed ); - } - else if( velocity > VelDesired + SpeedCtrlMargin - || ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 ) - || IsAnyCouplerStretched ) { - // jak za bardzo przyspiesza albo prędkość przekroczona - // dodany wyjatek na "pelna w przod" - cue_action( driver_hint::tractiveforcedecrease ); - } - } - - control_handles(); - SpeedSet(); // ciągla regulacja prędkości -} - -bool TController::is_too_fast_uphill() const { - - if( AccDesired < 0.0 ) { return true; } - // holding the speed uphill on the way to a stop asks for no speeding up - return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ); -} - -// starting uphill a driver of a heavy train keeps the train brake applied, lets the locomotive's own brake off (the -// independent brake, and its share of the train brake with the releaser), applies the power, and releases the train -// brake only once the power holds the train. releasing everything first lets the train roll back before the power is -// there, and holding the train on the locomotive brake is no way out where that brake cuts the power (asynchronous -// drives, the control pressure switch) -void TController::control_uphill_start() { - - auto const velocity { DirectionalVel() }; - if( auto const uphill { - ( BrakeSystem == TBrakeSystem::Pneumatic ) - && is_train() - && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it - && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; - false == uphill ) { - 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 - bUphillStart = true; - bUphillRelease = false; - UphillTopUp = {}; - fUphillStartTime = ElapsedTime; - } - else { - return; - } - } - if( AccDesired <= EU07_AI_NOACCELERATION ) { - // no longer to start: the standing rules take over - end_uphill_start(); - return; - } - 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; - } - fUphillTractiveForce = 0.0; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - // 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 ) ); - } - 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; -} - -void TController::increase_tractive_force() { - - if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać - if( IsAnyCouplerStretched ) { return; } // train is already stretched past its limits, don't pull even harder - - if( mvOccupied->SpringBrake.Activate ) { - cue_action( driver_hint::springbrakeoff ); - } - if( VelDesired > 0.0 // to prevent door shuffle on stop - && ( doors_open() || doors_permit_active() ) ) { - // zamykanie drzwi - tutaj wykonuje tylko AI (zmienia fActionTime) - Doors( false ); - // Doors() call can potentially adjust fActionTime - if( fActionTime < 0.0 ) { return; } - } - if( true == mvOccupied->DepartureSignal ) { - cue_action( driver_hint::departuresignaloff ); - } - - cue_action( driver_hint::tractiveforceincrease ); -} - -// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower -// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand -// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough -double -TController::brake_increase_margin() const { - - if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( VelNext > 0.0 ) - && ( VelNext < DirectionalVel() ) ) { - return 0.5 * fBrake_a1[ 0 ]; - } - return fBrake_a1[ 0 ]; -} - -// a train coming to a stand with at least part of it on an up gradient: a long train brake released now cannot be -// applied again before the train stops and starts to roll back, so the train brake is not released any further, and the -// locomotive brake, which acts at once, helps to hold the train -bool -TController::uphill_stop_hold() const { - - return ( - ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( ( OrderCurrentGet() & Obey_train ) != 0 ) - && ( VelNext == 0.0 ) - && ( ActualProximityDist <= fMaxProximityDist ) - && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) - && ( std::abs( DirectionalVel() ) < 10.0 ) - // not while the train is to be driven on - && ( AccDesired <= 0.0 ) ); -} - -// uphill with the train brake applied, the gradient brings a slow train to a stand sooner than the brake of the consist -// can be released: letting the train roll on (or pulling up) at this speed only releases the brake for nothing, and the -// train stands with the brake on its way off instead -bool -TController::uphill_brake_committed( double const Velocity ) const { - - return ( - ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( BrakeCtrlPosition > 0.0 ) - && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) - && ( Velocity / 3.6 / -fAccGravity < brake_response_horizon( mvOccupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); -} - -void TController::control_braking_force() { - - // don't touch the brakes when compressing buffers during coupling/uncoupling - 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 == slippingbackuphill ) { - cue_action(driver_hint::brakingforcesetzero); - } - - // AbsAccS is the resultant acceleration, gravity included, so it is compared with the - // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent - auto const accdesiredresultant { AccDesired + fAccDesiredGravity }; - - // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake - // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a - // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve - if( ElapsedTime - fShortfallTime >= 3.0 ) { - auto const shortfall { AbsAccS - accdesiredresultant }; - iShortfallGrowth = ( - ( ( AccDesired < 0.0 ) && ( shortfall > fShortfall + 0.005 ) ) ? - iShortfallGrowth + 1 : - 0 ); - fShortfall = shortfall; - fShortfallTime = ElapsedTime; - } - - if( is_emu() && !ForcePNBrake ) { - // właściwie, to warunek powinien być na działający EP - // Ra: to dobrze hamuje EP w EZT - auto const accthreshold { ( - fAccGravity < 0.025 ? // HACK: when going downhill be more responsive to desired deceleration - fAccThreshold : - std::max( -0.2, fAccThreshold ) ) }; - auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], mvOccupied->MED_amax) }; - auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ? - 0.05 : 0.0; - if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold - && ( AbsAccS > accdesiredresultant + accmargin - || BrakeCtrlPosition < 0 ) ) - || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back - // hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired) - cue_action( driver_hint::brakingforceincrease ); - } - else if( OrderCurrentGet() != Disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca - if( AbsAccS < accdesiredresultant - 0.05 ) { - // jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo - // TBD: check if the condition isn't redundant with the DecBrake() code - if( BrakeCtrlPosition >= 0 && VelDesired > 0.0 ) { - // sanity check to prevent unintended brake release on sharp slopes - cue_action(driver_hint::brakingforcedecrease); - } - } - else { - cue_action( driver_hint::brakingforcelap ); - } - } - } // type & dt_ezt - 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 - || 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) - || AccDesired < fAccGravity - 0.5 || BrakeCtrlPosition <= 0) ) { - // u góry ustawia się hamowanie na fAccThreshold - // jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował - // TODO: check whether brake delay variable still has any purpose - cue_action(driver_hint::brakingforceincrease, - // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy - (3.0 + 0.5 * ((mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[1] : mvOccupied->BrakeDelay[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 - } - else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) - && ( AccDesired < 0.0 ) - && ( BrakeCtrlPosition > 0.0 ) - && ( fShortfall > 0.02 ) - && ( iShortfallGrowth >= 2 ) - && ( fBrakeHeldTime > brake_response_horizon( mvOccupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { - // the train has been falling further behind the demand for a while at a handle left alone for longer than - // the brake takes to respond: a small step now, while it still is small, rather than the deep one the - // margin above would allow only once the train is far behind - cue_action( driver_hint::brakingforceincrease ); - iShortfallGrowth = 0; - } - 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 ) { - // 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 - // sanity check to prevent unintended brake release on sharp slopes - // TODO: check whether brake delay variable still has any purpose - cue_action(driver_hint::brakingforcedecrease, - (mvOccupied->BrakeDelayFlag > bdelay_G ? mvOccupied->BrakeDelay[0] : mvOccupied->BrakeDelay[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 - } - // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: - // put it on as the train comes to a stand, and at once if the train has started to roll back - if( ( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) - && ( mvOccupied->LocalBrakePosA < 1.0 ) - && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) - // a train that has slowed down short of where it is to stop and is to pull up further does not get it - && ( VelDesired <= std::abs( velocity ) + 0.5 ) - && ( ActualProximityDist - uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) ) - || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) { - cue_action( driver_hint::independentbrakeapply ); - } - // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry - // instead of releasing the brakes and creeping into obstacle at 1-2 km/h - if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && mvOccupied->LocalBrakePosA < 0.01 ) { - cue_action(driver_hint::brakingforceincrease); - } - } - - // odhamowywanie składu po zatrzymaniu i zabezpieczanie lokomotywy - if( mvOccupied->Vel < EU07_AI_NOMOVEMENT - && ( VelDesired == 0.0 - || AccDesired <= EU07_AI_NOACCELERATION ) ) { - - if( (OrderCurrentGet() & (Disconnect | Connect | Change_direction)) == 0 // przy (p)odłączaniu nie zwalniamy tu hamulca - && std::abs(fAccGravity) < 0.01 ) { // only do this on flats, on slopes keep applied the train brake - apply_independent_brake_only(); - } - // if told to change direction don't confuse human driver with request to leave applied brake in the cab they're about to leave - if( ( OrderCurrentGet() & Change_direction ) != 0 ) { - cue_action( driver_hint::independentbrakerelease ); - } - } -} - -void TController::apply_independent_brake_only() { - - if( mvOccupied->LocalBrake != TLocalBrake::ManualBrake ) { - if( false == mvOccupied->ShuntMode // no need for independent brake if autobrake is active - && is_equal(mvOccupied->fBrakeCtrlPos, mvOccupied->Handle->GetPos(bh_RP), 0.2) ) { - cue_action( driver_hint::independentbrakeapply ); - } - else { - cue_action( driver_hint::trainbrakerelease ); - } - } -} - -void TController::control_releaser() { - // HACK: don't immediately touch releaser in inert vehicle, in case the simulation is about to replace us with human driver - if( mvOccupied->Vel < 1.0 && fActionTime < 0.0 ) { return; } - // TODO: combine all releaser handling in single decision tree instead of having bits all over the place - // TODO: replace handle and system conditions with flag indicating releaser presence - if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } - - auto const hasreleaser { - false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale - && ( mvOccupied->BrakeHandle == TBrakeHandle::FV4a - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) }; - - if( false == hasreleaser ) { return; } - - auto actuate { false }; - auto isbrakehandleinrightposition { true }; - - if( AccDesired > EU07_AI_NOACCELERATION ) { - // fill up brake pipe if needed - if( mvOccupied->PipePress < 3.0 ) { - actuate = true; - // some vehicles require brake handle to be moved to specific position - if( mvOccupied->HandleUnlock != -3 ) { - cue_action( driver_hint::trainbrakesetpipeunlock ); - isbrakehandleinrightposition &= BrakeCtrlPosition == mvOccupied->HandleUnlock; - } - } - // wyluzuj lokomotywę, to szybciej ruszymy - // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent - // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it - if( mvOccupied->BrakePress > 0.4 - && ( mvOccupied->Hamulec->GetCRP() > 4.9 - // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go - // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied) - || bUphillStart ) - && mvOccupied->Vel < 1.0 ) { - actuate = true; - } - // keep engine brakes released during coupling/uncoupling - if( true == TestFlag(iDrivigFlags, movePress) - && mvOccupied->BrakePress > 0.1 ) { - actuate = true; - } - } - // don't overcharge train brake pipe - if( mvOccupied->PipePress > 5.2 ) { - actuate = false; - } - - if( actuate ) { - // some vehicles may require master controller in neutral position - cue_action( driver_hint::mastercontrollersetzerospeed ); - if( false == mvOccupied->Hamulec->Releaser() - && isbrakehandleinrightposition ) { - cue_action( driver_hint::releaseron ); - } - } - else { - if( true == mvOccupied->Hamulec->Releaser() ) { - cue_action( driver_hint::releaseroff ); - } - } -} - -void TController::control_main_pipe() { - - // unlocking main pipe - if( AccDesired > -0.03 - && true == mvOccupied->LockPipe ) { - UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; - } - else if (false == mvOccupied->LockPipe ) { - UniversalBrakeButtons &= ~TUniversalBrake::ub_UnlockPipe; - } - - // napełnianie uderzeniowe - if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } - - if( mvOccupied->BrakeHandle == TBrakeHandle::FV4a - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_6P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K5P - || mvOccupied->BrakeHandle == TBrakeHandle::MHZ_K8P - || mvOccupied->BrakeHandle == TBrakeHandle::M394 ) { - - auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; - if( (iDrivigFlags & moveOerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - mvOccupied->Vel > 2.0 && fReady > 0.35 && - ( mvOccupied->EqvtPipePress < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe - && mvOccupied->Compressor >= 7.5 // don't charge without sufficient pressure in the tank - && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active - && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon - || min_speed(mvOccupied->Vel, VelNext) >= mvOccupied->Vel) ) { - - BrakeLevelSet(gbh_FS); - // don't charge the brakes too often, or we risk overcharging - BrakeChargingCooldown = -1 * std::clamp(iVehicles * 3, 30, 90); - } - - update_brake_charging(); - - if( mvOccupied->Compressor < 5.0 - || ( BrakeCtrlPosition < gbh_RP - && ( mvOccupied->EqvtPipePress > (fReady < 0.25 ? 5.1 : 5.2) || is_brake_charging_done() ) ) ) { - cue_action( driver_hint::trainbrakerelease ); - } - } -} - -void TController::update_brake_charging() { - - if( std::abs( BrakeCtrlPosition - gbh_FS ) >= 0.5 ) { - BrakeChargingStart = -1.0; - BrakeChargingPipeOverchargeStart.clear(); - return; - } - if( BrakeChargingStart < 0.0 ) { - BrakeChargingStart = ElapsedTime; - } - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - auto const isovercharged { - vehicle->MoverParameters != mvOccupied - && vehicle->MoverParameters->PipePress > FSOverchargePipePress }; - if( isovercharged ) { - BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime ); - } - else { - BrakeChargingPipeOverchargeStart.erase( vehicle ); - } - } -} - -bool TController::is_departure_blocked( double const Delay ) const { - - return DepartBlockedStart >= 0.0 - && ElapsedTime - DepartBlockedStart > Delay; -} - -double TController::consist_max_crp() const { - - auto result { 0.0 }; - for( auto const *vehicle { pVehicles[ end::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { - result = std::max( result, vehicle->MoverParameters->Hamulec->GetCRP() ); - } - return result; -} - -bool TController::is_brake_charging_done() const { - - if( BrakeChargingStart < 0.0 ) { - return false; - } - return ElapsedTime - BrakeChargingStart > FSMaxTime - || consist_max_crp() > mvOccupied->HighPipePress + FSOverchargeCRP - || std::ranges::any_of( - BrakeChargingPipeOverchargeStart, - [this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } ); -} - -void -TController::check_route_ahead( double const Range ) { - - auto const comm { TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ) }; - - switch (comm) { - // ustawienie VelSignal - trochę proteza = do przemyślenia - case TCommandType::cm_Ready: { // W4 zezwolił na jazdę - // ewentualne doskanowanie trasy za W4, który zezwolił na jazdę - TableCheck( Range ); - TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ); // aktualizacja po skanowaniu - if( VelNext == 0.0 ) { - break; // ale jak coś z przodu zamyka, to ma stać - } - if( iDrivigFlags & moveStopCloser ) { - VelSignal = -1.0; // ma czekać na sygnał z sygnalizatora! - } - break; - } - case TCommandType::cm_SetVelocity: { // od wersji 357 semafor nie budzi wyłączonej lokomotywy - if( (OrderCurrentGet() & ~(Shunt | Loose_shunt | Obey_train | Bank)) == 0 && std::fabs(VelSignal) >= 1.0 ) { // jedzie w dowolnym trybie albo Wait_for_orders - // 0.1 nie wysyła się do samochodow, bo potem nie ruszą - PutCommand("SetVelocity", VelSignal, VelNext, nullptr); // komenda robi dodatkowe operacje - } - break; - } - case TCommandType::cm_ShuntVelocity: { // od wersji 357 Tm nie budzi wyłączonej lokomotywy - if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Obey_train | Bank ) ) == 0 ) { // jedzie w dowolnym trybie albo Wait_for_orders - PutCommand( "ShuntVelocity", VelSignal, VelNext, nullptr ); - } - else if( iCoupler ) { // jeśli jedzie w celu połączenia - SetVelocity( VelSignal, VelNext ); - } - break; - } - case TCommandType::cm_Command: { // komenda z komórki - if( (OrderCurrentGet() & ~(Shunt | Loose_shunt | Obey_train | Bank)) == 0 && mvOccupied->Vel < 0.1 ) { - // jedzie w dowolnym trybie albo Wait_for_orders - // dopiero jak stanie - /* - PutCommand( eSignNext->text(), eSignNext->value( 1 ), eSignNext->value( 2 ), nullptr ); - eSignNext->StopCommandSent(); // się wykonało już - */ // replacement of the above - eSignNext->send_command(*this); - } - break; - } - default: { - break; - } - } -} - -void -TController::check_route_behind( double const Range ) { - - if( VelNext != 0.0 ) { return; } // not if we can move ahead - if( TestFlag( iDrivigFlags, moveConnect ) ) { return; } // not if we're in middle of coupling operation - - if( ( OrderCurrentGet() & ~( Shunt | Loose_shunt | Connect ) ) == 0 ) { - // jedzie w Shunt albo Connect, albo Wait_for_orders - // w trybie Connect skanować do tyłu tylko jeśli przed kolejnym sygnałem nie ma taboru do podłączenia - auto const couplinginprogress { - TestFlag(OrderCurrentGet(), Connect) - && ( Obstacle.distance < std::min(2000.0, FirstSemaphorDist) - || TestFlag(iDrivigFlags, moveConnect) ) }; - if( couplinginprogress ) { return; } - - auto const commandbehind { BackwardScan( Range ) }; - if( commandbehind != TCommandType::cm_Unknown ) { - // jeśli w drugą można jechać - // należy sprawdzać odległość od znalezionego sygnalizatora, - // aby w przypadku prędkości 0.1 wyciągnąć najpierw skład za sygnalizator - // i dopiero wtedy zmienić kierunek jazdy, oczekując podania prędkości >0.5 - if( commandbehind == TCommandType::cm_Command ) { - // jeśli komenda Shunt to ją odbierz bez przemieszczania się (np. odczep wagony po dopchnięciu do końca toru) - iDrivigFlags |= moveStopHere; - } - iDirectionOrder = -iDirection; // zmiana kierunku jazdy - // zmiana kierunku bez psucia kolejnych komend - OrderCurrentSet( TOrders( OrderCurrentGet() | Change_direction ) ); - } - } -} - -void -TController::UpdateBrakingHelper() { - - if (HelperState > 0 && -AccDesired < fBrake_a0[0] + 2 * fBrake_a1[0] && mvOccupied->Vel > EU07_AI_NOMOVEMENT) { - HelperState = 0; - } - - switch( HelperState ) { - case 0: { - if( -AccDesired > fBrake_a0[0] + 8 * fBrake_a1[0] ) { - HelperState = 1; - } - break; - } - case 1: { - if( -AccDesired > fBrake_a0[0] + 12 * fBrake_a1[0] ) { - HelperState = 2; - } - break; - } - case 2: { - if( -AccDesired > 0 && -ActualProximityDist > 5 ) { - HelperState = 3; - } - break; - } - default: { - break; - } - } -} diff --git a/vehicle/Driver.h b/vehicle/Driver.h index 62b326696..c58ce134b 100644 --- a/vehicle/Driver.h +++ b/vehicle/Driver.h @@ -13,14 +13,17 @@ http://mozilla.org/MPL/2.0/. #include #include "utilities/Classes.h" #include "utilities/utilities.h" -#include "MOVER.h" +#include "physics/vehicletypes.h" +#include "vehicle/driverorders.h" #include "audio/sound.h" #include "vehicle/DynObj.h" #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" auto const EU07_AI_ACCELERATION = 0.05; auto const EU07_AI_NOACCELERATION = -0.05; @@ -28,28 +31,11 @@ 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 -enum TOrders -{ // rozkazy dla AI - Wait_for_orders = 0, // czekanie na dostarczenie następnych rozkazów - // operacje tymczasowe - Prepare_engine = 1 << 0, // włączenie silnika - Release_engine = 1 << 1, // wyłączenie silnika - Change_direction = 1 << 2, // zmiana kierunku (bez skanowania sygnalizacji) - Connect = 1 << 3, // podłączanie wagonów (z częściowym skanowaniem sygnalizacji) - Disconnect = 1 << 4, // odłączanie wagonów (bez skanowania sygnalizacji) - // jazda - Shunt = 1 << 5, // tryb manewrowy - Loose_shunt = 1 << 6, // coupling-free shunting mode - Obey_train = 1 << 7, // tryb pociągowy - Bank = 1 << 8, // assist mode - // others - Jump_to_first_order = 1 << 9, // zapęlenie do pierwszej pozycji (po co?) -}; -// TSignals is shifted into TMovementStatus +// the signals the map asks the driver to show (SetSignal) enum TSignals { Signal_START = 30, @@ -58,36 +44,37 @@ enum TSignals Signal_MAX = 31 }; -enum TMovementStatus -{ // flagi bitowe ruchu (iDrivigFlags) - moveStopCloser = 1, // podjechać blisko W4 (nie podjeżdżać na początku ani po zmianie czoła) - moveStopPoint = 2, // stawać na W4 (wyłączone podczas zmiany czoła) - moveActive = 4, // pojazd jest załączony i skanuje - movePress = 8, // dociskanie przy odłączeniu (zamiast zmiennej Prepare2press) - moveConnect = 0x10, // jest blisko innego pojazdu i można próbować podłączyć - movePrimary = 0x20, // ma priorytet w składzie (master) - moveLate = 0x40, // flaga spóźnienia, włączy bardziej - moveStopHere = 0x80, // nie podjeżdżać do semafora, jeśli droga nie jest wolna - moveStartHorn = 0x100, // podawaj sygnał po podaniu wolnej drogi - moveStartHornNow = 0x200, // podaj sygnał po odhamowaniu - moveStartHornDone = 0x400, // podano sygnał po podaniu wolnej drogi - moveOerlikons = 0x800, // skład wyłącznie z zaworami? Oerlikona - moveIncSpeed = 0x1000, // załączenie jazdy (np. dla EZT) - moveTrackEnd = 0x2000, // dalsza jazda do przodu trwale ograniczona (W5, koniec toru) - moveSwitchFound = 0x4000, // na drodze skanowania do przodu jest rozjazd - moveGuardSignal = 0x8000, // sygnał od kierownika (minął czas postoju) - moveVisibility = 0x10000, // jazda na widoczność po przejechaniu S1 na SBL - moveDoorOpened = 0x20000, // drzwi zostały otwarte - doliczyć czas na zamknięcie - movePushPull = 0x40000, // zmiana czoła przez zmianę kabiny - nie odczepiać przy zmianie kierunku - moveSignalFound = 0x80000, // na drodze skanowania został znaleziony semafor - moveStopPointFound = 0x100000, // stop point detected ahead - moveGuardOpenDoor = 0x200000, // time for opening a door before departure - moveDepartureWarned = 0x400000 // driver has already warned about the doors being closed (only for manual warning - i.e. EN57-ish) -/* - moveSemaphorWasElapsed = 0x100000, // minięty został semafor - moveTrainInsideStation = 0x200000, // pociąg między semaforem a rozjazdami lub następnym semaforem - moveSpeedLimitFound = 0x400000 // pociąg w ograniczeniu z podaną jego długością -*/ +// what the driver keeps in mind about the movement of the train: each a condition of its own, set and cleared on its own +struct DrivingFlags +{ + bool stopCloser{ false }; // podjechać blisko W4 (nie podjeżdżać na początku ani po zmianie czoła) + bool stopPoint{ true }; // stawać na W4 (wyłączone podczas zmiany czoła) + bool active{ false }; // pojazd jest załączony i skanuje + bool press{ false }; // dociskanie przy odłączeniu + bool connect{ false }; // jest blisko innego pojazdu i można próbować podłączyć + bool primary{ false }; // ma priorytet w składzie (master) + bool late{ false }; // spóźnienie, włączy bardziej + bool stopHere{ true }; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + bool startHorn{ true }; // podawaj sygnał po podaniu wolnej drogi + bool startHornNow{ false }; // podaj sygnał po odhamowaniu + bool startHornDone{ false }; // podano sygnał po podaniu wolnej drogi + bool oerlikons{ false }; // skład wyłącznie z zaworami Oerlikona + bool incSpeed{ false }; // załączenie jazdy (np. dla EZT) + bool trackEnd{ false }; // dalsza jazda do przodu trwale ograniczona (W5, koniec toru) + bool switchFound{ false }; // na drodze skanowania do przodu jest rozjazd + bool guardSignal{ false }; // sygnał od kierownika (minął czas postoju) + bool visibility{ false }; // jazda na widoczność po przejechaniu S1 na SBL + bool doorOpened{ false }; // drzwi zostały otwarte - doliczyć czas na zamknięcie + bool pushPull{ false }; // zmiana czoła przez zmianę kabiny - nie odczepiać przy zmianie kierunku + bool signalFound{ false }; // na drodze skanowania został znaleziony semafor + bool stopPointFound{ false }; // stop point detected ahead + bool guardOpenDoor{ false }; // time for opening a door before departure + bool departureWarned{ false }; // driver has already warned about the doors being closed (only for manual warning - i.e. EN57-ish) + bool signalPc6{ false }; // the map asked to show the Pc6 signal (SetSignal); nothing reads it yet + bool signalA1{ false }; // the map asked to show the A1 signal (SetSignal); nothing reads it yet + + // the names of the flags set, for the debug panel + std::vector ActiveNames() const; }; enum TStopReason @@ -129,32 +116,36 @@ enum class TAction : int actTrial // próba hamulca (na postoju) }; -enum TSpeedPosFlag -{ // wartości dla iFlag w TSpeedPos - spNone = 0x0, - spEnabled = 0x1, // pozycja brana pod uwagę - spTrack = 0x2, // to jest tor - spReverse = 0x4, // odwrotnie - spSwitch = 0x8, // to zwrotnica - spSwitchStatus = 0x10, // stan zwrotnicy - spElapsed = 0x20, // pozycja minięta przez pojazd - spEnd = 0x40, // koniec - spCurve = 0x80, // łuk - spEvent = 0x100, // event - spShuntSemaphor = 0x200, // tarcza manewrowa - spPassengerStopPoint = 0x400, // przystanek osobowy (wskaźnik W4) - spStopOnSBL = 0x800, // zatrzymanie na SBL - spCommandSent = 0x1000, // komenda wysłana - spOutsideStation = 0x2000, // wskaźnik końca manewrów - spSemaphor = 0x4000, // semafor pociągowy - spRoadVel = 0x8000, // zadanie prędkości drogowej - spSectionVel = 0x20000, // odcinek z ograniczeniem - spProximityVelocity = 0x40000, // odcinek z ograniczeniem i podaną jego długościa - spPointVelocity = 0x80000, // ograniczenie dla czoła w punkcie fPointDist za wpisem (PointVelocity) - spRoadVelHeld = 0x100000, // a road speed sign passed by the head, handled, kept until the rear is past it - spSignalAreaEnd = 0x200000 // end of the interlocking area of the signal passed last -// spDontApplySpeedLimit = 0x10000 // this point won't apply its speed limit. potentially set by the scanning vehicle +// what a position of the speed table of the AI is and what became of it +enum class SpeedPointFlag : unsigned +{ + none = 0x0, + enabled = 0x1, // pozycja brana pod uwagę + track = 0x2, // to jest tor + reverse = 0x4, // odwrotnie + switchTrack = 0x8, // to zwrotnica + switchState = 0x10, // stan zwrotnicy + elapsed = 0x20, // pozycja minięta przez pojazd + trackEnd = 0x40, // koniec + curve = 0x80, // łuk + event = 0x100, // event + shuntSignal = 0x200, // tarcza manewrowa + passengerStop = 0x400, // przystanek osobowy (wskaźnik W4) + stopOnAutomaticBlock = 0x800, // zatrzymanie na SBL + commandSent = 0x1000, // komenda wysłana + outsideStation = 0x2000, // wskaźnik końca manewrów + signal = 0x4000, // semafor pociągowy + roadSpeed = 0x8000, // zadanie prędkości drogowej + sectionSpeed = 0x20000, // odcinek z ograniczeniem + proximitySpeed = 0x40000, // odcinek z ograniczeniem i podaną jego długością + pointSpeed = 0x80000, // ograniczenie dla czoła w punkcie fPointDist za wpisem (PointVelocity) + roadSpeedHeld = 0x100000, // a road speed sign passed by the head, handled, kept until the rear is past it + signalAreaEnd = 0x200000, // end of the interlocking area of the signal passed last }; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using SpeedPointFlags = EnumSet; class TSpeedPos { // pozycja tabeli prędkości dla AI @@ -163,7 +154,8 @@ class TSpeedPos double fVelNext{ -1.0 }; // prędkość obowiązująca od tego miejsca double fSectionVelocityDist{ 0.0 }; // długość ograniczenia prędkości double fPointDist{ 0.0 }; // PointVelocity: o ile dalej od wpisu leży punkt, w którym czoło ma mieć fVelNext - int iFlags{ spNone }; // flagi typu wpisu do tabelki + SpeedPointFlags flags; // flagi typu wpisu do tabelki + int crossRoute{ 0 }; // the segment of a crossing the route takes, -8..7, the sign the direction (in the top 4 bits of the flags before) bool bMoved{ false }; // czy przesunięty (dotyczy punktu zatrzymania w peronie) double fMoved{ 0.0 }; // ile przesunięty (dotyczy punktu zatrzymania w peronie) bool bSeenAhead{ false }; // the head of the train had it ahead once: only such a point can be passed by the train @@ -174,10 +166,17 @@ class TSpeedPos basic_event *evEvent{ nullptr }; // połączenie z eventem albo komórką pamięci }; void CommandCheck(); + // the flags and the route as the one number they were before: the scan of the route reads its sign, the table its hex + int LegacyFlagsValue() const { + return static_cast( ( static_cast( crossRoute ) << 28 ) | static_cast( flags.Bits() ) ); } + // no flags and no route: the position doesn't count any more + void ResetFlags() { + flags = {}; + crossRoute = 0; } public: - TSpeedPos(TTrack *track, double dist, int flag); - TSpeedPos(basic_event *event, double dist, double length, TOrders order); + TSpeedPos(TTrack *track, double dist, SpeedPointFlags flag); + TSpeedPos(basic_event *event, double dist, double length, DriverOrders order); TSpeedPos() = default; void Clear(); bool Update(); @@ -186,11 +185,12 @@ class TSpeedPos void UpdateDistance( double dist ) { fDist -= dist; } - bool Set(basic_event *e, double d, double length, TOrders order = Wait_for_orders); - void Set(TTrack *t, double d, int f); + // Standing: the train stands, so an event found behind its head wasn't passed by it + bool Set(basic_event *e, double d, double length, DriverOrders order = DriverOrder::waitForOrders, bool Standing = false); + void Set(TTrack *t, double d, SpeedPointFlags f); std::string TableText() const; std::string GetName() const; - bool IsProperSemaphor(TOrders order = Wait_for_orders); + bool IsProperSemaphor(DriverOrders order = DriverOrder::waitForOrders); }; //---------------------------------------------------------------------------- @@ -213,14 +213,51 @@ static const int gbh_MIN = -2; //minimalna pozycja w hamulcu ogolnym static const int gbh_MAX = 6; //maksymalna pozycja w hamulcu ogolnym //---------------------------------------------------------------------------- +// the running brake test of a train run (hamowanie kontrolne), as the timetable asks for it +struct RunningBrakeTest +{ + enum class Stage + { + waiting, // for the speed to run it at + applying, // the brake applied, the electropneumatic brake still in + switchingToAir, // the electropneumatic brake out, the train braked by the air brake alone + measuring, // braking down by 8 km/h, timed + releasing, // the brakes released + done + }; + Stage stage{ Stage::waiting }; + double velocityBrake{ 0.0 }; // where the braking began, then where its timed part began [km/h] + double velocityRelease{ 0.0 }; // the speed the brakes are released at [km/h] + double velocityFinish{ 0.0 }; // the speed the test ended at [km/h] + double brakingTime{ 0.0 }; // when the braking began, then how long its timed part took [s] + double releasingTime{ 0.0 }; // when the release began, then how long it took [s] + double midPointAcc{ 0.0 }; // the deceleration at the end of the timed part [m/s2] + + // the brakes applied by the test, until the release + bool IsBraking() const { return stage >= Stage::applying && stage <= Stage::measuring; } +}; + +// how far the train falls short of the braking it is asked for, as the driver watches it +struct BrakingShortfall +{ + double value{ 0.0 }; // at the last check [m/s2] + double time{ 0.0 }; // when that was checked + int growth{ 0 }; // how many checks in a row it has grown +}; + +// a start in which the wheels slipped: sand while under power until the train is under way +struct SandedStart +{ + bool active{ false }; + double decreaseTime{ -1.0 }; // when the power was last taken down a step for a slip +}; + class TController { // TBD: few authorized inspectors, or bunch of public getters? - friend class TTrain; friend class drivingaid_panel; friend class timetable_panel; friend class scenario_panel; friend class debug_panel; - friend class whois_event; public: TController( bool AI, TDynamicObject *NewControll, bool InitPsyche, bool primary = true ); @@ -237,17 +274,17 @@ public: void TakeControl( bool const Aidriver, bool const Forcevehiclecheck = false ); inline bool primary( bool const Primary ) { - SetFlag( iDrivigFlags, Primary ? movePrimary : -movePrimary ); + drivingFlags.primary = Primary; return primary(); } inline bool primary() const { - return (iDrivigFlags & movePrimary) != 0; }; + return drivingFlags.primary; }; inline - TMoverParameters const *Controlling() const { + physics::Vehicle const *Controlling() const { return mvControlling; } inline - TMoverParameters const *Occupied() const { - return mvOccupied; } + physics::Vehicle const *Occupied() const { + return occupied; } void DirectionInitial(); void DirectionChange(); inline @@ -261,23 +298,12 @@ public: return eAction; } inline bool is_active() const { - return TestFlag( iDrivigFlags, moveActive ); } - inline - bool is_train() const { - return TestFlag( mvOccupied->CategoryFlag, 1 ); } - inline - bool is_car() const { - return TestFlag( mvOccupied->CategoryFlag, 2 ); } - inline - bool is_emu() const { - return mvControlling->TrainType == dt_EZT; } - inline - bool is_dmu() const { - return mvControlling->TrainType == dt_DMU; } - inline - bool has_diesel_engine() const { - return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; - } + return drivingFlags.active; } + bool is_train() const; + bool is_car() const; + bool is_emu() const; + bool is_dmu() const; + bool has_diesel_engine() const; TBrakeSystem consist_brake_system() const; // the next change of the speed limit ahead, as the driving aid tells it: the speed and the distance to it. // the speed is the present limit (VelDesired) when nothing worth telling changes within the scan range @@ -285,9 +311,39 @@ public: // what the AI would do at this place and speed, worked out also while a human drives, for the black box blackbox::ai_reference ai_reference() const; // the light pattern the timetable or the scenery asks for at an end of the train, -1 the usual one - int light_hint( int const End ) const { return m_lighthints[ End ]; } + int light_hint( VehicleEnd const End ) const { return m_lighthints[ End ]; } // the order the driver goes by now: a train run, shunting and the like - TOrders order_current() const { return OrderCurrentGet(); } + DriverOrders order_current() const { return OrderCurrentGet(); } + // the reversers of the consist set as the driver's one, where they went apart + void sync_consist_reversers(); + // the stations of the timetable: where the train is among them, how many there are, whether it stops at the next + int StationIndex() const; + int StationCount() const; + bool IsStop() const; + // what the cab shows of the consist the driver leads + BySide const &ConsistDoorsOpen() const { return IsAnyDoorOpen; } + BySide const &ConsistDoorsOnlyOpen() const { return IsAnyDoorOnlyOpen; } // the steps not counted + BySide const &ConsistDoorPermits() const { return IsAnyDoorPermitActive; } + door_closure_t ConsistDoorClosure() const { return DoorClosure; } + bool ConsistConverterOverloaded() const { return IsAnyConverterOverloadRelayOpen; } + bool ConsistCompressorEnabled() const { return IsAnyCompressorEnabled; } + double ConsistLength() const { return fLength; } + int RadioChannel() const { return iRadioChannel; } + void SetRadioChannel( int const Channel ) { iRadioChannel = Channel; } + int Helper() const { return HelperState; } + // what the driver goes by on the route, for the screens of the cab and the events + double DesiredVelocity() const { return VelDesired; } + double RoadVelocity() const { return VelRoad; } + double LastLimitVelocity() const { return VelLimitLast; } + double LastSignalVelocity() const { return VelSignalLast; } + double NextSignalVelocity() const { return VelSignalNext; } + double NextVelocity() const { return VelNext; } + double ProximityDistance() const { return ActualProximityDist; } + bool AtPassengerStop() const { return IsAtPassengerStop; } + // how far the brakes of the consist are released (fReady), the most braked vehicle counting + double BrakesReleaseLevel() const { return fReady; } + // the distance to the obstacle ahead on the track + double TrackObstacle() const; private: // tells the black box of the train at the station of its timetable it makes for, at the stop point given void record_station( TSpeedPos const &Point, std::uint8_t Kind ) const; @@ -320,8 +376,7 @@ private: void WaitingSet( double Seconds ); void DirectionForward( bool forward ); void ZeroDirection(); - int OrderDirectionChange( int newdir, TMoverParameters *Vehicle ); - void sync_consist_reversers(); + int OrderDirectionChange( int newdir, physics::Vehicle *Vehicle ); void Lights( int head, int rear ); std::string StopReasonText() const; double BrakeAccFactor() const; @@ -329,11 +384,9 @@ private: float braking_distance_multiplier( float const Targetvelocity ) const; inline - int DrivigFlags() const { - return iDrivigFlags; }; - inline - double DirectionalVel() const { - return mvOccupied->Vel * sign( iDirection * mvOccupied->V ); } + DrivingFlags const &DrivingFlagsState() const { + return drivingFlags; } + double DirectionalVel() const; double brake_increase_margin() const; bool uphill_stop_hold() const; @@ -341,6 +394,8 @@ private: 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 ); @@ -392,6 +447,7 @@ private: bool is_brake_charging_done() const; double consist_max_crp() const; bool is_departure_blocked( double const Delay ) const; + void control_field_shunting(); void control_relays(); void control_motor_connectors(); void control_tractive_force(); @@ -401,7 +457,7 @@ private: // how far short of a stop the AI aims: in train running the middle of the 8-15 m window before a signal, // otherwise (a W4 stop point, shunting, coupling) half the minimum proximity distance, as before double stopping_margin() const { - return ( ( OrderCurrentGet() & Obey_train ) != 0 ) && !IsAtPassengerStop ? + return ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) && !IsAtPassengerStop ? fMinProximityDist + 3.5 : 0.5 * fMinProximityDist; } void apply_independent_brake_only(); @@ -417,7 +473,30 @@ private: void cue_action( driver_hint const Action, float const Actionparameter = 0.f ); // members public: - bool AIControllFlag = false; // rzeczywisty/wirtualny maszynista + // the AI drives, or a human does + bool AIControllFlag() const { return aiControlled; } + // what the overhead line of the track under a vehicle of the consist asks for (TDynamicObject::OverheadTrack()), by the + // bit of that vehicle: below zero the usual running, above it running without current with the pantographs down, zero + // running without current with them up + void MarkOverhead( int const Mask, float const Mode ) { + if( Mode < 0.0 ) { // normalna jazda po tym torze + iOverheadZero &= ~Mask; // zerowanie bitu - może pobierać prąd + iOverheadDown &= ~Mask; // zerowanie bitu - może podnieść pantograf + } + else if( Mode > 0.0 ) { // opuszczenie pantografów + iOverheadZero |= Mask; // ustawienie bitu - ma jechać bez pobierania prądu + iOverheadDown |= Mask; // ustawienie bitu - ma opuścić pantograf + } + else { // jazda bezprądowa z podniesionym pantografem + iOverheadZero |= Mask; // ustawienie bitu - ma jechać bez pobierania prądu + iOverheadDown &= ~Mask; // zerowanie bitu - może podnieść pantograf + } + } + // the most deceleration of the service braking of the consist with the blended brakes, which the driver goes by + double MedAmax() const { return fMedAmax; } + void SetMedAmax( double const Deceleration ) { fMedAmax = Deceleration; } +private: + bool aiControlled = false; // rzeczywisty/wirtualny maszynista int iOverheadZero = 0; // suma bitowa jezdy bezprądowej, bity ustawiane przez pojazdy z podniesionymi pantografami int iOverheadDown = 0; // suma bitowa opuszczenia pantografów, bity ustawiane przez pojazdy z podniesionymi pantografami double BrakeCtrlPosition = 0.0; // intermediate position of main brake controller @@ -429,29 +508,28 @@ private: bool Psyche = false; int HelperState = 0; //stan pomocnika maszynisty TDynamicObject *pVehicle = nullptr; // pojazd w którym siedzi sterujący - TMoverParameters *mvControlling = nullptr; // jakim pojazdem steruje (może silnikowym w EZT) - TMoverParameters *mvOccupied = nullptr; // jakim pojazdem hamuje - TMoverParameters *mvPantographUnit = nullptr; //pantograph equipped vehicle in the occupied/controlled set + physics::Vehicle *mvControlling = nullptr; // jakim pojazdem steruje (może silnikowym w EZT) + physics::Vehicle *occupied = nullptr; // jakim pojazdem hamuje + physics::Vehicle *pantographUnit = nullptr; //pantograph equipped vehicle in the occupied/controlled set std::string VehicleName; - std::array m_lighthints = { -1, -1 }; // suggested light patterns + ByEnd m_lighthints = { -1, -1 }; // suggested light patterns double AccPreferred = 0.0; // preferowane przyspieszenie (wg psychiki kierującego, zmniejszana przy wykryciu kolizji) double AccDesired = 0.0; // przyspieszenie, jakie ma utrzymywać (<0:nie przyspieszaj,<-0.1:hamuj) double VelDesired = 0.0; // predkość, z jaką ma jechać, wynikająca z analizy tableki; <=VelSignal double fAccDesiredAv = 0.0; // uśrednione przyspieszenie z kolejnych przebłysków świadomości, żeby ograniczyć migotanie double fBrakeHeldTime = 0.0; // czas od ostatniego przestawienia kranu hamulca zasadniczego bool bStopTargetIsPassengerStop = false; // the point the train is to stop at, found by the last scan of the route, is a passenger stop - double fShortfall = 0.0; // how far the train fell short of the braking demand at the last check [m/s2] - double fShortfallTime = 0.0; // when that was checked - int iShortfallGrowth = 0; // how many checks in a row the shortfall has grown - bool bUphillStart = false; // starting uphill: the train brake holds the train until the power does - 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] + BrakingShortfall brakingShortfall; + uphill_start::Progress uphillStart; // a start uphill, the train brake holding the train until the power does + SandedStart sandedStart; 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?) @@ -473,7 +551,7 @@ private: std::optional iDirectionBackup; // consist direction to be restored after coupling/uncoupling and similar direction-changing operations std::optional> iCouplingVehicle; // to be coupled with another consist in current coupling operation int iVehicleCount = -2; // wartość neutralna // ilość pojazdów do odłączenia albo zabrania ze składu (-1=wszystkie) - int iCoupler = 0; // maska sprzęgu, jaką należy użyć przy łączeniu (po osiągnięciu trybu Connect), 0 gdy jazda bez łączenia + CouplingSet iCoupler; // maska sprzęgu, jaką należy użyć przy łączeniu (po osiągnięciu trybu Connect), 0 gdy jazda bez łączenia int iDriverFailCount = 0; // licznik błędów AI bool Need_TryAgain = false; // true, jeśli druga pozycja w elektryku nie załapała // bool Need_BrakeRelease = true; @@ -496,10 +574,7 @@ private: double fStopTime = 0.0; // czas postoju przed dalszą jazdą (np. na przystanku) float ExchangeTime{ 0.0 }; // time needed to finish current load exchange double fShuntVelocity = 40.0; // prędkość manewrowania, zależy m.in. od składu - int iDrivigFlags = // flagi bitowe ruchu - moveStopPoint | // podjedź do W4 możliwie blisko - moveStopHere | // nie podjeżdżaj do semafora, jeśli droga nie jest wolna - moveStartHorn; // podaj sygnał po podaniu wolnej drogi + DrivingFlags drivingFlags; // what the driver keeps in mind about the movement of the train double fDriverBraking = 0.0; // po pomnożeniu przez v^2 [km/h] daje ~drogę hamowania [m] double fDriverDist = 0.0; // dopuszczalna odległość podjechania do przeszkody double fVelMax = -1.0; // maksymalna prędkość składu (sprawdzany każdy pojazd) @@ -523,14 +598,7 @@ private: double DepartBlockedStart = -1.0; TBrakeSystem BrakeSystem = TBrakeSystem::Individual; //type of main brake bool ForcePNBrake = false; //is it necessary to use PN brake instead of EP brake - int DynamicBrakeTest = 0; //is it necessary to make brake test while driving - double DBT_VelocityBrake = 0; - double DBT_VelocityRelease = 0; - double DBT_VelocityFinish = 0; - double DBT_BrakingTime = 0; - double DBT_ReleasingTime = 0; - double DBT_MidPointAcc = 0; - int StaticBrakeTest = 0; //is it necessary to make brake test while standing + RunningBrakeTest brakeTest; double LastReactionTime = 0.0; double fActionTime = 0.0; // czas używany przy regulacji prędkości i zamykaniu drzwi double m_radiocontroltime{ 0.0 }; // timer used to control speed of radio operations @@ -550,20 +618,20 @@ private: void RecognizeCommand(); // odczytuje komende przekazana lokomotywie void JumpToNextOrder( bool const Skipmergedchangedirection = false ); void JumpToFirstOrder(); - void OrderPush( TOrders NewOrder ); - void OrderNext( TOrders NewOrder ); - inline TOrders OrderCurrentGet() const; - inline void OrderCurrentSet( TOrders const Order ); - inline TOrders OrderNextGet() const; + void OrderPush( DriverOrders NewOrder ); + void OrderNext( DriverOrders NewOrder ); + inline DriverOrders OrderCurrentGet() const; + inline void OrderCurrentSet( DriverOrders const Order ); + inline DriverOrders OrderNextGet() const; void OrderCheck(); void OrdersInit( double fVel ); void OrdersClear(); void OrdersDump( std::string const Neworder, bool const Verbose = true ); - std::string Order2Str( TOrders Order ) const; + std::string Order2Str( DriverOrders Order ) const; // members std::string m_assignment; glm::dvec3 vCommandLocation; // polozenie wskaznika, sygnalizatora lub innego obiektu do ktorego odnosi sie komenda // NOTE: not used - TOrders OrderList[ maxorders ]; // lista rozkazów + DriverOrders OrderList[ maxorders ]; // lista rozkazów int OrderPos = 0, OrderTop = 0; // rozkaz aktualny oraz wolne miejsce do wstawiania nowych @@ -606,8 +674,6 @@ private: bool point_limit_latched( basic_event const *Cell ) const; // how far before a point limit the speed is held down to it double point_limit_approach() const; - // returns most recently calculated distance to potential obstacle ahead - double TrackObstacle() const; void TablePurger(); void TableSort(); inline double MoveDistanceGet() const { @@ -620,9 +686,9 @@ private: void TableClear(); int TableDirection() { return iTableDirection; } // Ra: stare funkcje skanujące, używane do szukania sygnalizatora z tyłu - bool IsOccupiedByAnotherConsist( TTrack *Track, double const Distance ); - basic_event *CheckTrackEventBackward( double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection = 1, end const End = end::rear ); - TTrack *BackwardTraceRoute( double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection = 1, end const End = end::rear, bool const Untiloccupied = true ); + bool IsOccupiedByAnotherConsist( TTrack *Track, double const Distance = 0 ); + basic_event *CheckTrackEventBackward( double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection = 1, VehicleEnd const End = VehicleEnd::rear ); + TTrack *BackwardTraceRoute( double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection = 1, VehicleEnd const End = VehicleEnd::rear, bool const Untiloccupied = true ); void SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos ); TCommandType BackwardScan( double const Range ); std::string TableText( std::size_t const Index ) const; @@ -667,9 +733,6 @@ public: Mtable::TTrainParameters const & TrainTimetable() const; private: std::string Relation() const; - int StationIndex() const; - int StationCount() const; - bool IsStop() const; std::string NextStop() const; // tests whether the train is delayed and sets accordingly a driving flag void UpdateDelayFlag(); @@ -680,6 +743,7 @@ private: std::string m_lastexchangestop; // HACK: safeguard to prevent multiple load exchanges per station int m_lastexchangeplatforms { 0 }; // cached station platforms for last exchange int m_lastexchangedirection { 0 }; // + timetable::service_flags m_stopflags; // service flags of the timetable at the stop the train is at or left last double fLastStopExpDist = -1.0; // odległość wygasania ostateniego przystanku int iRadioChannel = 1; // numer aktualnego kanału radiowego int iGuardRadio = 0; // numer kanału radiowego kierownika (0, gdy nie używa radia) @@ -690,9 +754,12 @@ private: // consist // methods public: - bool CheckVehicles( TOrders user = Wait_for_orders ); + bool CheckVehicles( DriverOrders user = DriverOrder::waitForOrders ); private: bool PrepareEngine(); + // tells in the log, once, of standing with the pantographs up and no voltage (eu07/maszyna#421) + void report_power_stall( bool const Poweravailable, double const Pantographpressure ); + ai_power::reporter m_powerstall; // the reports of report_power_stall() void close_line_breaker(); bool ReleaseEngine(); void Doors( bool const Open, int const Side = 0 ); @@ -717,11 +784,11 @@ private: bool Ready = false; // ABu: stan gotowosci do odjazdu - sprawdzenie odhamowania wagonow bool IsConsistBraked { false }; double ConsistShade{ 1.0 }; // averaged amount of sunlight received by the consist - TDynamicObject *pVehicles[ 2 ]; // skrajne pojazdy w składzie (niekoniecznie bezpośrednio sterowane) + ByEnd pVehicles; // skrajne pojazdy w składzie (niekoniecznie bezpośrednio sterowane) bool DoesAnyDoorNeedOpening{ false }; - bool IsAnyDoorOpen[ 2 ]; // state of door in the consist - bool IsAnyDoorOnlyOpen[ 2 ]; // state of door in the consist regardless of step - bool IsAnyDoorPermitActive[ 2 ]; // state of door permit in the consist + BySide IsAnyDoorOpen; // state of door in the consist + BySide IsAnyDoorOnlyOpen; // state of door in the consist regardless of step + BySide IsAnyDoorPermitActive; // state of door permit in the consist door_closure_t DoorClosure{ door_closure_t::none }; // state of the door closure signalling (SOD) of the consist bool IsAnyLineBreakerOpen{ false }; // state of line breaker in all powered vehicles under control bool IsAnyConverterOverloadRelayOpen{ false }; // state of converter overload relays in all vehicles under control @@ -761,7 +828,7 @@ public: return WriteLogFlag || ( WriteTrainLogFlag && is_train() && primary() ); } static std::string_view physicslog_header(); std::string physicslog_line() const; - TDynamicObject *Vehicle( end const Side ) const { + TDynamicObject *Vehicle( VehicleEnd const Side ) const { return pVehicles[ Side ]; } private: std::string OwnerName() const; @@ -773,23 +840,23 @@ private: }; -inline TOrders TController::OrderCurrentGet() const { +inline DriverOrders TController::OrderCurrentGet() const { if( OrderPos < 0 || OrderPos >= maxorders ) { - return Wait_for_orders; + return DriverOrder::waitForOrders; } return OrderList[ OrderPos ]; } -inline void TController::OrderCurrentSet( TOrders const Order ) { +inline void TController::OrderCurrentSet( DriverOrders const Order ) { if( OrderPos < 0 || OrderPos >= maxorders ) { return; } OrderList[ OrderPos ] = Order; } -inline TOrders TController::OrderNextGet() const { +inline DriverOrders TController::OrderNextGet() const { if( OrderPos < 0 || OrderPos >= maxorders ) { - return Wait_for_orders; + return DriverOrder::waitForOrders; } // the order list wraps around, same as in JumpToNextOrder() return OrderList[ ( OrderPos + 1 ) % maxorders ]; diff --git a/vehicle/DynObj.cpp b/vehicle/DynObj.cpp deleted file mode 100644 index e5e387198..000000000 --- a/vehicle/DynObj.cpp +++ /dev/null @@ -1,9512 +0,0 @@ -/* -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/. -*/ -/* - MaSzyna EU07 locomotive simulator - Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others - -*/ - -#include "stdafx.h" -#include "vehicle/DynObj.h" - -#include "vehicle/lightsprogrammer.h" - -#include "simulation/simulation.h" -#include "simulation/blackboxrecorder.h" -#include "rendering/lightarray.h" -#include "vehicle/Camera.h" -#include "vehicle/Train.h" -#include "vehicle/odometer.h" -#include "vehicle/Driver.h" - -#include -#include -#include -#include -#include "utilities/Globals.h" -#include "utilities/Timer.h" -#include "utilities/workerpool.h" -#include "utilities/Logs.h" -#include "utilities/glmHelpers.h" -#include "Console.h" -#include "world/Traction.h" -#include "audio/sound.h" -#include "model/MdlMngr.h" -#include "model/Model3d.h" -#include "vehicle/doorwings.h" -#include "rendering/renderer.h" -#include "application/uitranscripts.h" -#include "input/messaging.h" -#include "application/application.h" -#include "vehicle/Driver.h" - -// Ra: taki zapis funkcjonuje lepiej, ale może nie jest optymalny -#define vWorldFront glm::vec3(0, 0, 1) -#define vWorldUp glm::vec3(0, 1, 0) -#define vWorldLeft glm::cross(vWorldUp, vWorldFront) - -#define M_2PI 6.283185307179586476925286766559; -const float maxrot = (float)(M_PI / 3.0); // 60° - -std::string const TDynamicObject::MED_labels[] = { - "masa: ", "amax: ", "Fzad: ", "FmPN: ", "FmED: ", "FrED: ", "FzPN: ", "nPrF: " -}; - -bool TDynamicObject::bDynamicRemove { false }; - -// helper, locates submodel with specified name in specified 3d model; returns: pointer to the submodel, or null -TSubModel * -GetSubmodelFromName( TModel3d * const Model, std::string const Name ) { - - return Model ? Model->GetFromName(Name) : nullptr; -} - -// Ra 2015-01: sprawdzenie dostępności tekstury o podanej nazwie -std::string -TextureTest( std::string const &Name ) { - - auto const lookup { - FileExists( - { Global.asCurrentTexturePath + Name, Name, paths::textures + Name }, - { ".mat", ".dds", ".tga", ".ktx", ".png", ".bmp", ".jpg", ".tex" } ) }; - - return lookup.first + lookup.second; -} - -//--------------------------------------------------------------------------- -void TAnimPant::common_pantograph_settings() -{ // wspólne ustawienia, liczone po przypisaniu wymiarów ramion - vPos = glm::dvec3(0, 0, 0); - fAngleL0 = glm::radians(2.8547285515689267247882521833308); - fAngleL = fAngleL0; // początkowy kąt dolnego ramienia - fAngleU0 = acos((fLenL1 * cos(fAngleL) + fHoriz) / fLenU1); // górne ramię - fAngleU = fAngleU0; // początkowy kąt - PantWys = fLenL1 * sin(fAngleL) + fLenU1 * sin(fAngleU) + fHeight; // wysokość początkowa - PantTraction = PantWys; - hvPowerWire = nullptr; - fWidthExtra = 0.381f; //(2.032m-1.027)/2 - // poza obszarem roboczym jest aproksymacja łamaną o 5 odcinkach - fHeightExtra[0] = 0.0f; //+0.0762 - fHeightExtra[1] = -0.01f; //+0.1524 - fHeightExtra[2] = -0.03f; //+0.2286 - fHeightExtra[3] = -0.07f; //+0.3048 - fHeightExtra[4] = -0.15f; //+0.3810 -} - -void TAnimPant::AKP_4E() -{ // ustawienie wymiarów dla pantografu AKP-4E - fLenL1 = 1.22; // 1.176289 w modelach - fLenU1 = 1.755; // 1.724482197 w modelach - fHoriz = 0.535; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego - // ramienia - fHeight = 0.07; // wysokość ślizgu ponad oś obrotu - fWidth = 0.635; // połowa szerokości ślizgu, 0.635 dla AKP-1 i AKP-4E - common_pantograph_settings(); -}; -void TAnimPant::WBL85() -{ // ustawienie wymiarów dla pantografu WBL88 - // mnozniki animacji ramion dla pantografu WBL88 - rd1rf = 1.f; - rd2rf = 1.2; - rg1rf = 0.875; - rg2rf = 1.0; - slizgrf = 1.f; - - fLenL1 = 1.98374; - fLenU1 = 2.14199; - fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego ramienia - fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu - fWidth = 0.4969; // połowa szerokości ślizgu - common_pantograph_settings(); -}; -void TAnimPant::EC160_200() -{ // ustawienie wymiarów dla pantografow EC160 lub EC200 - // mnozniki animacji ramion dla pantografow EC160 lub EC200 - rd1rf = 1.f; - rd2rf = 0.85; - rg1rf = 1.f; - rg2rf = 1.f; // 0.833 - slizgrf = 1.f; - - fLenL1 = 1.98374; - fLenU1 = 2.14199; - fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego ramienia - fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu - fWidth = 0.4969; // połowa szerokości ślizgu - common_pantograph_settings(); -}; -void TAnimPant::DSAx() -{ // ustawienie wymiarów dla pantografow z rodziny DSA - // mnozniki animacji ramion dla pantografow z rodziny DSA - rd1rf = 1.f; - rd2rf = 1.025; - rg1rf = 0.875; - rg2rf = 1.f; - slizgrf = 1.f; - - fLenL1 = 1.98374; - fLenU1 = 2.14199; - fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem - // osi obrotu dolnego ramienia - fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu - fWidth = 0.4969; // połowa szerokości ślizgu - common_pantograph_settings(); -}; -//--------------------------------------------------------------------------- -int TAnim::TypeSet(int i, TMoverParameters currentMover, int fl) -{ // ustawienie typu animacji i zależnej od niego ilości animowanych submodeli - fMaxDist = -1.0; // normalnie nie pokazywać - switch (i) - { // maska 0x000F: ile używa wskaźników na submodele (0 gdy jeden, - // wtedy bez tablicy) - // maska 0x00F0: - // 0-osie,1-drzwi,2-obracane,3-zderzaki,4-wózki,5-pantografy,6-tłoki - // maska 0xFF00: ile używa liczb float dla współczynników i stanu - case 0: - iFlags = 0x000; - break; // 0-oś - case 1: - iFlags = 0x010; - break; // 1-drzwi - case 2: - iFlags = 0x020; - fParam = fl ? new float[fl] : nullptr; - iFlags += fl << 8; - break; // 2-wahacz, dźwignia itp. - case 3: - iFlags = 0x030; - break; // 3-zderzak - case 4: - iFlags = 0x040; - break; // 4-wózek - case 5: // 5-pantograf - 5 submodeli - iFlags = 0x055; - fParamPants = new TAnimPant(); - switch (currentMover.EnginePowerSource.CollectorParameters.PantographType) { - case TPantType::AKP_4E: - fParamPants->AKP_4E(); - break; - case TPantType::DSAx: - fParamPants->DSAx(); - break; - case TPantType::EC160_200: - fParamPants->EC160_200(); - break; - case TPantType::WBL85: - fParamPants->WBL85(); - break; - } - - break; - case 6: - iFlags = 0x068; - break; // 6-tłok i rozrząd - 8 submodeli - case 7: - iFlags = 0x070; - break; // doorstep - case 8: - iFlags = 0x080; - break; // mirror - case 9: - iFlags = 0x023; // 2: Rotating/Motion-based, 8: Uses 3 submodels - break; - default: - iFlags = 0; - } - yUpdate = nullptr; - return iFlags & 15; // ile wskaźników rezerwować dla danego typu animacji -}; - -TAnim::~TAnim() -{ // usuwanie animacji - switch (iFlags & 0xF0) - { // usuwanie struktur, zależnie ile zostało stworzonych - case 0x20: // 2-wahacz, dźwignia itp. - delete fParam; - break; - case 0x50: // 5-pantograf - delete fParamPants; - break; - default: - break; - } -}; -/* -void TAnim::Parovoz(){ - // animowanie tłoka i rozrządu parowozu -}; -*/ - - -// assigns specified texture or a group of textures to replacable texture slots -void -material_data::assign( std::string const &Replacableskin ) { - - // a template puts its parameter after a folder ("tabl/(p6)"): a texture made by a script given there keeps its scheme - if( auto const scheme { Replacableskin.find( "/make:" ) }; - scheme != std::string::npos - && false == contains( Replacableskin, '|' ) ) { - assign( Replacableskin.substr( scheme + 1 ) ); - return; - } - // check for the pipe method first - if( contains( Replacableskin, '|' ) ) { - cParser nameparser( Replacableskin ); - nameparser.getTokens( 4, false, "|" ); - int skinindex = 0; - std::string texturename; nameparser >> texturename; - while( texturename != "" && skinindex < 4 ) { - replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( texturename ); - ++skinindex; - texturename = ""; nameparser >> texturename; - } - multi_textures = skinindex; - } - else { - // otherwise try the basic approach - int skinindex = 0; - do { - // test quietly for file existence so we don't generate tons of false errors in the log - // NOTE: this means actual missing files won't get reported which is hardly ideal, but still somewhat better - auto const material { TextureTest( ToLower( Replacableskin + "," + std::to_string( skinindex + 1 ) ) ) }; - if( true == material.empty() ) { break; } - - replacable_skins[ skinindex + 1 ] = GfxRenderer->Fetch_Material( material ); - ++skinindex; - } while( skinindex < 4 ); - multi_textures = skinindex; - if( multi_textures == 0 ) { - // zestaw nie zadziałał, próbujemy normanie - replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); - } - } - if( replacable_skins[ 1 ] == null_handle ) { - // last ditch attempt, check for single replacable skin texture - replacable_skins[ 1 ] = GfxRenderer->Fetch_Material( Replacableskin ); - } - - // BUGS! it's not entierly designed whether opacity is property of material or submodel, - // and code does confusing things with this in various places - textures_alpha = GfxRenderer->Material(replacable_skins[1])->is_translucent() ? 0x31310031 : // tekstura -1 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - 0x30300030; // wszystkie tekstury nieprzezroczyste - nie renderować w cyklu przezroczystych - if( GfxRenderer->Material( replacable_skins[ 2 ] )->is_translucent() ) { - // tekstura -2 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - textures_alpha |= 0x02020002; - } - if( GfxRenderer->Material( replacable_skins[ 3 ] )->is_translucent() ) { - // tekstura -3 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - textures_alpha |= 0x04040004; - } - if( GfxRenderer->Material( replacable_skins[ 4 ] )->is_translucent() ) { - // tekstura -4 z kanałem alfa - nie renderować w cyklu nieprzezroczystych - textures_alpha |= 0x08080008; - } -} - - -namespace { - -// a luadestinationsign: or wasmdestinationsign: block, its script in the vehicle folder when it has no path of its own -void deserialize_script_sign( cParser &Parser, script_screens::screen_config &Sign, std::string const &Folder ) { - - Sign.deserialize( Parser ); - if( false == Sign.script.empty() - && substr_path( Sign.script ).empty() ) { - Sign.script = Folder + Sign.script; - } -} - -} // namespace - -void TDynamicObject::destination_data::deserialize( cParser &Input ) { - - while( true == deserialize_mapping( Input ) ) { - ; // all work done by while() - } -} - -bool TDynamicObject::destination_data::deserialize_mapping( cParser &Input ) { - // token can be a key or block end - auto const key { Input.getToken( true, "\n\r\t ,;[]" ) }; - - if( true == key.empty() || key == "}" ) { return false; } - - if( key == "{" ) { - script = Input.getToken(); - } - else if( key == "update:" ) { - auto const value { Input.getToken() }; - // TODO: implement - } - else if( key == "instance:" ) { - instancing = Input.getToken(); - } - else if( key == "parameters:" ) { - parameters = Input.getToken(); - } - else if( key == "background:" ) { - background = Input.getToken(); - } - - return true; -} - - -//--------------------------------------------------------------------------- -TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, int cf) -{ // szukanie skrajnego połączonego pojazdu w pociagu - // od strony sprzegu (coupler_nr) obiektu (start) - TDynamicObject *temp = this; - for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu - { - if (!temp) - return nullptr; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & cf) != cf) - return temp; // nic nie ma już dalej podłączone sprzęgiem cf - if (coupler_nr == end::front) - { // jeżeli szukamy od sprzęgu 0 - if (temp->PrevConnected()) // jeśli mamy coś z przodu - { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->PrevConnected(); // ten jest od strony 0 - } - else - return temp; // jeśli jednak z przodu nic nie ma - } - else - { - if (temp->NextConnected()) - { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->NextConnected(); // ten pojazd jest od strony 1 - } - else - return temp; // jeśli jednak z tyłu nic nie ma - } - } - return nullptr; // to tylko po wyczerpaniu pętli -}; - -//--------------------------------------------------------------------------- -float TDynamicObject::GetEPP() -{ // szukanie skrajnego połączonego pojazdu w pociagu - // od strony sprzegu (coupler_nr) obiektu (start) - TDynamicObject *temp = this; - int coupler_nr = 0; - double eq = 0.0; - double am = 0.0; - - for (int i = 0; i < 300; ++i) // ograniczenie do 300 na wypadek zapętlenia składu - { - if (!temp) - break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; - am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & coupling::brakehose) != coupling::brakehose) - break; // nic nie ma już dalej podłączone - if (coupler_nr == 0) - { // jeżeli szukamy od sprzęgu 0 - if (temp->PrevConnected()) // jeśli mamy coś z przodu - { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->PrevConnected(); // ten jest od strony 0 - } - else - break; // jeśli jednak z przodu nic nie ma - } - else - { - if (temp->NextConnected()) - { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->NextConnected(); // ten pojazd jest od strony 1 - } - else - break; // jeśli jednak z tyłu nic nie ma - } - } - - temp = this; - coupler_nr = 1; - for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu - { - if (!temp) - break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów - eq += temp->MoverParameters->PipePress * temp->MoverParameters->Dim.L; - am += temp->MoverParameters->Dim.L; - if ((temp->MoverParameters->Couplers[coupler_nr].CouplingFlag & coupling::brakehose) != coupling::brakehose) - break; // nic nie ma już dalej podłączone - if (coupler_nr == 0) - { // jeżeli szukamy od sprzęgu 0 - if (temp->PrevConnected()) // jeśli mamy coś z przodu - { - if (temp->PrevConnectedNo() == end::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->PrevConnected(); // ten jest od strony 0 - } - else - break; // jeśli jednak z przodu nic nie ma - } - else - { - if (temp->NextConnected()) - { - if (temp->NextConnectedNo() == end::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony - coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu - temp = temp->NextConnected(); // ten pojazd jest od strony 1 - } - else - break; // jeśli jednak z tyłu nic nie ma - } - } - eq -= MoverParameters->PipePress * MoverParameters->Dim.L; - am -= MoverParameters->Dim.L; - return eq / am; -}; - -//--------------------------------------------------------------------------- -TDynamicObject * TDynamicObject::GetFirstDynamic(int cpl_type, int cf) -{ // Szukanie skrajnego połączonego pojazdu w pociagu - // od strony sprzegu (cpl_type) obiektu szukajacego - // Ra: wystarczy jedna funkcja do szukania w obu kierunkach - return FirstFind(cpl_type, cf); // używa referencji -}; - -void TDynamicObject::ABuSetModelShake(glm::dvec3 mShake) -{ - modelShake = mShake; -}; - -int TDynamicObject::GetPneumatic(bool front, bool red) -{ - int x, y, z; // 1=prosty, 2=skośny - if (red) - { - if (front) - { - x = btCPneumatic1.GetStatus(); - y = btCPneumatic1r.GetStatus(); - } - else - { - x = btCPneumatic2.GetStatus(); - y = btCPneumatic2r.GetStatus(); - } - } - else if (front) - { - x = btPneumatic1.GetStatus(); - y = btPneumatic1r.GetStatus(); - } - else - { - x = btPneumatic2.GetStatus(); - y = btPneumatic2r.GetStatus(); - } - z = 0; // brak węży? - if (x > 0 && y > 0) - z = 3; // dwa - if (x > 0 && y == 0) - z = 1; // lewy, brak prawego - if (x == 0 && y > 0) - z = 2; // brak lewego, prawy - - return z; -} - -void TDynamicObject::SetPneumatic(bool front, bool red) -{ - int x = 0, - ten = 0, - tamten = 0; - ten = GetPneumatic(front, red); // 1=lewy skos,2=prawy skos,3=dwa proste - if (front) - if (PrevConnected()) // pojazd od strony sprzęgu 0 - tamten = PrevConnected()->GetPneumatic(PrevConnectedNo() == end::front ? true : false, red); - if (!front) - if (NextConnected()) // pojazd od strony sprzęgu 1 - tamten = NextConnected()->GetPneumatic(NextConnectedNo() == end::front ? true : false, red); - if (ten == tamten) // jeśli układ jest symetryczny - switch (ten) - { - case 1: - x = 2; - break; // mamy lewy skos, dać lewe skosy - case 2: - x = 3; - break; // mamy prawy skos, dać prawe skosy - case 3: // wszystkie cztery na prosto - if (MoverParameters->Couplers[front ? end::front : end::rear].Render) - x = 1; - else - x = 4; - break; - } - else - { - if (ten == 2) - x = 4; - if (ten == 1) - x = 1; - if (ten == 3) - if (tamten == 1) - x = 4; - else - x = 1; - } - if (front) - { - if (red) - cp1 = x; - else - sp1 = x; - } // który pokazywać z przodu - else - { - if (red) - cp2 = x; - else - sp2 = x; - } // który pokazywać z tyłu -} - -void TDynamicObject::UpdateAxle(TAnim *pAnim) -{ // animacja osi - size_t wheel_id = pAnim->dWheelAngle; - pAnim->smAnimated->SetRotate(float3(1, 0, 0), dWheelAngle[wheel_id]); - pAnim->smAnimated->future_transform = glm::rotate((float)glm::radians(m_future_wheels_angle[wheel_id]), glm::vec3(1.0f, 0.0f, 0.0f)); -}; - -// angle of a slotted lever for given angle of the wheel, which drives the coupling rod with the pin -// all points of the coupling rod move along circles of crank radius, the lever follows the pin sliding in its slot -double TDynamicObject::slottedlever_angle( slottedlever_data const &Lever, double const Wheelangle ) { - // crank turned around X axis, the same way as the wheel - auto const wheelangle { glm::radians( Wheelangle ) }; - auto const crank { glm::dvec2( - Lever.crank.x * std::cos( wheelangle ) - Lever.crank.y * std::sin( wheelangle ), - Lever.crank.x * std::sin( wheelangle ) + Lever.crank.y * std::cos( wheelangle ) ) }; - auto const pin { Lever.pin - Lever.crank + crank }; - // angle relative to the pose of the lever in the model, which matches wheel angle 0 - return glm::degrees( std::atan2( pin.y, pin.x ) - std::atan2( Lever.pin.y, Lever.pin.x ) ); -} - -void TDynamicObject::update_slottedlevers() { - - for( auto const &lever : m_slottedlevers ) { - auto const wheelid { ( - ( lever.axle < iAnimType[ ANIM_WHEELS ] ) && ( lever.axle < static_cast( pAnimations.size() ) ) ? - pAnimations[ lever.axle ].dWheelAngle : - 1 ) }; // driving wheels and coupling rods by default - auto const angle { slottedlever_angle( lever, dWheelAngle[ wheelid ] ) }; - auto const futureangle { slottedlever_angle( lever, dWheelAngle[ wheelid ] + m_future_wheels_angle[ wheelid ] ) }; - lever.submodel->SetRotate( float3( 1, 0, 0 ), angle ); - lever.submodel->future_transform = glm::rotate( (float)glm::radians( std::remainder( futureangle - angle, 360.0 ) ), glm::vec3( 1.0f, 0.0f, 0.0f ) ); - } -} - -namespace { - -// the position of the door the animated wing belongs to: its shift or angle from closed -float door_position( TMoverParameters const &Mover, TAnim const *Animation ) { - - return Mover.Doors.instances[ ( - door_wings::on_right_side( Animation->iNumber ) ? - side::right : - side::left ) ].position; -} - -// the wing in the main model, and its namesake in the low poly interior; either can be missing -std::array wing_parts( TAnim const *Animation ) { - - return { Animation->smAnimated, Animation->smInterior }; -} - -// folding door: the smaller wing turns, the larger wing (its child) the other way, the step (child of that) under it -void fold_wing( TSubModel *Wing, door_wings::fold_angles const &Angles ) { - - if( Wing == nullptr ) { return; } - // skrzydło mniejsze - Wing->SetRotate( float3( 0, 0, 1 ), Angles.smaller ); - // skrzydło większe - auto *larger { Wing->ChildGet() }; - if( larger == nullptr ) { return; } - larger->SetRotate( float3( 0, 0, 1 ), Angles.larger ); - // podnóżek? - auto *step { larger->ChildGet() }; - if( step == nullptr ) { return; } - step->SetRotate( float3( 0, 1, 0 ), Angles.step ); -} - -} // namespace - -// animacja drzwi - przesuw -void TDynamicObject::UpdateDoorTranslate(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const shift { door_wings::slide( door_position( *MoverParameters, pAnim ) ) }; - for( auto *wing : wing_parts( pAnim ) ) { - if( wing != nullptr ) { - wing->SetTranslate( shift ); - } - } -}; - -// animacja drzwi - obrót -void TDynamicObject::UpdateDoorRotate(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const angle { door_position( *MoverParameters, pAnim ) }; - for( auto *wing : wing_parts( pAnim ) ) { - if( wing != nullptr ) { - wing->SetRotate( float3( 1, 0, 0 ), angle ); - } - } -}; - -// animacja drzwi - obrót -void TDynamicObject::UpdateDoorFold(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const angles { door_wings::fold( door_position( *MoverParameters, pAnim ) ) }; - for( auto *wing : wing_parts( pAnim ) ) { - fold_wing( wing, angles ); - } -}; - -// animacja drzwi - odskokprzesuw -void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const shift { door_wings::plug( door_position( *MoverParameters, pAnim ), MoverParameters->Doors.range_out ) }; - for( auto *wing : wing_parts( pAnim ) ) { - if( wing != nullptr ) { - wing->SetTranslate( shift ); - } - } -} - -void TDynamicObject::UpdatePant(TAnim *pAnim) -{ // animacja pantografu - 4 obracane ramiona, ślizg piąty - float a, b, c; - a = glm::degrees(pAnim->fParamPants->fAngleL - pAnim->fParamPants->fAngleL0); - b = glm::degrees(pAnim->fParamPants->fAngleU - pAnim->fParamPants->fAngleU0); - c = a + b; - if (pAnim->smElement[0]) - pAnim->smElement[0]->SetRotate(float3(-1, 0, 0), a); // dolne ramie 1 - if (pAnim->smElement[1]) - pAnim->smElement[1]->SetRotate(float3(1, 0, 0), a * pAnim->fParamPants->rd2rf); // dolne ramie 2 - if (pAnim->smElement[2]) - pAnim->smElement[2]->SetRotate(float3(1, 0, 0), c); // górne ramie 1 - if (pAnim->smElement[3]) - pAnim->smElement[3]->SetRotate(float3(-1, 0, 0), c * pAnim->fParamPants->rg2rf); // gorne ramie 2 - if (pAnim->smElement[4]) - pAnim->smElement[4]->SetRotate(float3(-1, 0, 0), b * pAnim->fParamPants->slizgrf); // ślizg -} - -// doorstep animation, shift -void TDynamicObject::UpdatePlatformTranslate( TAnim *pAnim ) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - pAnim->smAnimated->SetTranslate( - glm::vec3{ - std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ), - 0.0, - 0.0 } ); -} - -// doorstep animation, rotate -void TDynamicObject::UpdatePlatformRotate( TAnim *pAnim ) { - - if( pAnim->smAnimated == nullptr ) { return; } - - auto const &door { MoverParameters->Doors.instances[ ( - ( pAnim->iNumber & 1 ) == 0 ? - side::right : - side::left ) ] }; - - pAnim->smAnimated->SetRotate( - float3( 0, 1, 0 ), - std::lerp( 0.f, MoverParameters->Doors.step_range, door.step_position ) ); -} - -// mirror animation, rotate -void TDynamicObject::UpdateMirror( TAnim *pAnim ) { - - if( pAnim->smAnimated == nullptr ) { return; } - - // only animate the mirror if it's located on the same end of the vehicle as the active cab - auto const isactive { ( - MoverParameters->CabOccupied > 0 ? ( pAnim->iNumber >> 4 == end::front ? 1.0 : 0.0 ) : - MoverParameters->CabOccupied < 0 ? ( pAnim->iNumber >> 4 == end::rear ? 1.0 : 0.0 ) : - 0.0 ) }; - - if( pAnim->iNumber & 1 ) - pAnim->smAnimated->SetRotate( - float3( 0, 1, 0 ), - std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveR * isactive ) ); - else - pAnim->smAnimated->SetRotate( - float3( 0, 1, 0 ), - std::lerp( 0.0, MoverParameters->MirrorMaxShift, dMirrorMoveL * isactive ) ); -} - -// wipers -void TDynamicObject::UpdateWiper(TAnim* pAnim) -{ - if (!pAnim || !pAnim->smElement) - return; - - int i = pAnim->iNumber; - // odwaramy animacje dla parzystych indexow - const double rotateAngle = (i + 1) % 2 == 0 ? -MoverParameters->WiperAngle : MoverParameters->WiperAngle; - - if (pAnim->smElement[0]) // ramie 1 - pAnim->smElement[0]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); - if (pAnim->smElement[1]) // ramie 2 - pAnim->smElement[1]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); - if (pAnim->smElement[2]) // pioro - pAnim->smElement[2]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, -rotateAngle, dWiperPos[i])); -} - -/* -void TDynamicObject::UpdateLeverDouble(TAnim *pAnim) -{ // animacja gałki zależna od double - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fDoubleBase); -}; -void TDynamicObject::UpdateLeverFloat(TAnim *pAnim) -{ // animacja gałki zależna od float - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fFloatBase); -}; -void TDynamicObject::UpdateLeverInt(TAnim *pAnim) -{ // animacja gałki zależna od int - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->iIntBase); -}; -void TDynamicObject::UpdateLeverEnum(TAnim *pAnim) -{ // ustawienie kąta na - // wartość wskazaną przez - // int z tablicy fParam - // pAnim->fParam[0]; - dodać lepkość - pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fParam[*pAnim->iIntBase]); -}; -*/ -// sets light levels for registered interior sections -void -TDynamicObject::toggle_lights() { - - if( true == SectionLightsActive ) { - // switch all lights off... - for( auto §ion : Sections ) { - auto const sectionname { section.compartment->pName }; - if( sectionname.rfind( "cab", 0 ) != 0 ) { - section.light_level = 0.0; - } - } - SectionLightsActive = false; - } - else { - // set lights with probability depending on the compartment type. TODO: expose this in .mmd file - for( auto §ion : Sections ) { - - auto const sectionname { section.compartment->pName }; - if( sectionname.find("corridor") == 0 - || sectionname.find("korytarz") == 0 ) { - // corridors are lit 100% of time - section.light_level = 0.75f; - } - else if( - sectionname.find("compartment") == 0 - || sectionname.find("przedzial") == 0 ) { - // compartments are lit with 75% probability - section.light_level = Random() < 0.75 ? 0.75f : 0.10f; - } - } - SectionLightsActive = true; - } -} - -void -TDynamicObject::set_cab_lights( int const Cab, float const Level ) { - - for( auto §ion : Sections ) { - // cab compartments are placed at the beginning of the list, so we can bail out as soon as we find different compartment type - auto const sectionname { section.compartment->pName }; - if( sectionname.size() < 4 ) { return; } - if( sectionname.find( "cab" ) != 0 ) { return; } - if( sectionname[ 3 ] != Cab + '0' ) { continue; } // match the cab with correct index - - section.light_level = Level; - } -} - -// aktualizujemy submodele w zaleznosci od aktualnej pory roku -void TDynamicObject::on_season_update() -{ - if (sm_winter_variant != nullptr) // pokazujemy wariant zimowy - sm_winter_variant->SetVisibilityLevel(Global.Season == "winter:" ? 1 : 0, true, false); - if (sm_spring_variant != nullptr) // pokazujemy wariant wiosenny - sm_spring_variant->SetVisibilityLevel(Global.Season == "spring:" ? 1 : 0, true, false); - if (sm_summer_variant != nullptr) // pokazujemy wariant letni - sm_summer_variant->SetVisibilityLevel(Global.Season == "summer:" ? 1 : 0, true, false); - if (sm_autumn_variant != nullptr) // pokazujemy wariant jesienny - sm_autumn_variant->SetVisibilityLevel(Global.Season == "autumn:" ? 1 : 0, true, false); -} - -// ABu 29.01.05 przeklejone z render i renderalpha: ********************* -void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) -{ // ABu290105: pozbierane i uporzadkowane powtarzajace - // sie rzeczy z Render i RenderAlpha - // dodatkowy warunek, if (ObjSqrDist<...) zeby niepotrzebnie nie zmianiec w - // obiektach, - // ktorych i tak nie widac - // NBMX wrzesien, MC listopad: zuniwersalnione - btnOn = false; // czy przywrócić stan domyślny po renderowaniu - - // the submodels set below are shared with whatever else is drawn with the same models - for( auto *model : { mdModel, mdLoad, mdLowPolyInt, mdKabina } ) { - if( model != nullptr ) { - model->state_changed(); - } - } - for( auto *model : mdAttachments ) { - if( model != nullptr ) { - model->state_changed(); - } - } - - if (mdLoad) // tymczasowo ładunek na poziom podłogi - if (vFloor.z > 0.0) - mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); - - // model jest współdzielony przez pojazdy, a pora roku może się zmienić w trakcie symulacji - if (Global.UpdateMaterials) - on_season_update(); - - if (ObjSqrDist < 400 * 400 ) // gdy bliżej niż 400m - { - for( auto &animation : pAnimations ) { - // wykonanie kolejnych animacji - if( ObjSqrDist < animation.fMaxDist - && animation.yUpdate ) { - // jeśli zdefiniowana funkcja aktualizacja animacji (położenia submodeli - animation.yUpdate( &animation ); - } - } - update_slottedlevers(); - - if( mdModel != nullptr - && ObjSqrDist < 50 * 50 ) { - // gdy bliżej niż 50m - // ABu290105: rzucanie pudlem - // te animacje wymagają bananów w modelach! - mdModel->GetSMRoot()->SetTranslate(modelShake); - if (mdKabina) - mdKabina->GetSMRoot()->SetTranslate(modelShake); - if (mdLoad) - mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); - if (mdLowPolyInt) - mdLowPolyInt->GetSMRoot()->SetTranslate(modelShake); - // ABu: koniec rzucania - // ABu011104: liczenie obrotow wozkow - ABuBogies(); - // Mczapkie-100402: rysowanie lub nie - sprzegow - // ABu-240105: Dodatkowy warunek: if (...).Render, zeby rysowal tylko jeden z polaczonych sprzegow - // display _on if connected with another vehicle and the coupling owner (render flag) - // display _xon if connected with another vehicle and not the coupling owner - // display _xon if not connected, but equipped with coupling adapter - // display _off if not connected, not equipped with coupling adapter or if _xon model is missing - if( TestFlag( MoverParameters->Couplers[ end::front ].CouplingFlag, coupling::coupler ) ) { - if( MoverParameters->Couplers[ end::front ].Render ) { - btCoupler1.TurnOn(); - } - else { - btCoupler1.TurnxOnWithOffAsFallback(); - } - btnOn = true; - } - else { - if( true == MoverParameters->Couplers[ end::front ].has_adapter() ) { - btCoupler1.TurnxOnWithOffAsFallback(); - btnOn = true; - } - } - if( TestFlag( MoverParameters->Couplers[ end::rear ].CouplingFlag, coupling::coupler ) ) { - if( MoverParameters->Couplers[ end::rear ].Render ) { - btCoupler2.TurnOn(); - } - else { - btCoupler2.TurnxOnWithOffAsFallback(); - } - btnOn = true; - } - else { - if( true == MoverParameters->Couplers[ end::rear ].has_adapter() ) { - btCoupler2.TurnxOnWithOffAsFallback(); - btnOn = true; - } - } - //******************************************************************************** - // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie - // 'render' - juz - // nie - // przewody powietrzne, yB: decyzja na podstawie polaczen w t3d - if (Global.bnewAirCouplers) - { - SetPneumatic(false, false); // wczytywanie z t3d ulozenia wezykow - SetPneumatic(true, false); // i zapisywanie do zmiennej - SetPneumatic(true, true); // ktore z nich nalezy - SetPneumatic(false, true); // wyswietlic w tej klatce - - if (TestFlag(MoverParameters->Couplers[end::front].CouplingFlag, ctrain_pneumatic)) - { - switch (cp1) - { - case 1: - btCPneumatic1.TurnOn(); - break; - case 2: - btCPneumatic1.TurnxOn(); - break; - case 3: - btCPneumatic1r.TurnxOn(); - break; - case 4: - btCPneumatic1r.TurnOn(); - break; - } - btnOn = true; - } - - if (TestFlag(MoverParameters->Couplers[end::rear].CouplingFlag, ctrain_pneumatic)) - { - switch (cp2) - { - case 1: - btCPneumatic2.TurnOn(); - break; - case 2: - btCPneumatic2.TurnxOn(); - break; - case 3: - btCPneumatic2r.TurnxOn(); - break; - case 4: - btCPneumatic2r.TurnOn(); - break; - } - btnOn = true; - } - - // przewody zasilajace, j.w. (yB) - if (TestFlag(MoverParameters->Couplers[end::front].CouplingFlag, ctrain_scndpneumatic)) - { - switch (sp1) - { - case 1: - btPneumatic1.TurnOn(); - break; - case 2: - btPneumatic1.TurnxOn(); - break; - case 3: - btPneumatic1r.TurnxOn(); - break; - case 4: - btPneumatic1r.TurnOn(); - break; - } - btnOn = true; - } - - if (TestFlag(MoverParameters->Couplers[end::rear].CouplingFlag, ctrain_scndpneumatic)) - { - switch (sp2) - { - case 1: - btPneumatic2.TurnOn(); - break; - case 2: - btPneumatic2.TurnxOn(); - break; - case 3: - btPneumatic2r.TurnxOn(); - break; - case 4: - btPneumatic2r.TurnOn(); - break; - } - btnOn = true; - } - } - //*********************************************************************************/ - else // po staremu ABu'oewmu - { - // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie - // 'render' - if (TestFlag(MoverParameters->Couplers[end::front].CouplingFlag, ctrain_pneumatic)) - { - if (MoverParameters->Couplers[end::front].Render) - btCPneumatic1.TurnOn(); - else - btCPneumatic1r.TurnOn(); - btnOn = true; - } - - if (TestFlag(MoverParameters->Couplers[end::rear].CouplingFlag, ctrain_pneumatic)) - { - if (MoverParameters->Couplers[end::rear].Render) - btCPneumatic2.TurnOn(); - else - btCPneumatic2r.TurnOn(); - btnOn = true; - } - - // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie - // 'render' - // //yB - zasilajace - if (TestFlag(MoverParameters->Couplers[0].CouplingFlag, ctrain_scndpneumatic)) - { - if (MoverParameters->Couplers[0].Render) - btPneumatic1.TurnOn(); - else - btPneumatic1r.TurnOn(); - btnOn = true; - } - - if (TestFlag(MoverParameters->Couplers[1].CouplingFlag, ctrain_scndpneumatic)) - { - if (MoverParameters->Couplers[1].Render) - btPneumatic2.TurnOn(); - else - btPneumatic2r.TurnOn(); - btnOn = true; - } - } - //*************************************************************/// koniec - // wezykow - // uginanie zderzakow - for (int i = 0; i < 2; ++i) { - - if( MoverParameters->Couplers[ i ].has_adapter() ) { - // HACK: if there's coupler adapter on this side, we presume there's additional distance put between vehicles - // which prevents buffers from clashing against each other (or the other vehicle doesn't have buffers to begin with) - continue; - } - - auto const dist { safe_clamp( MoverParameters->Couplers[ i ].Dist / 2.0, -MoverParameters->Couplers[ i ].DmaxB, 0.0 ) }; - - if( dist >= 0.0 ) { continue; } - - if( smBuforLewy[ i ] ) { - smBuforLewy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); - } - if( smBuforPrawy[ i ] ) { - smBuforPrawy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); - } - } - } // vehicle within 50m - - // Winger 160204 - podnoszenie pantografow - - // przewody sterowania ukrotnionego - if (TestFlag(MoverParameters->Couplers[0].CouplingFlag, coupling::control)) - { - btCCtrl1.Turn( true ); - btnOn = true; - } - // else btCCtrl1.TurnOff(); - if (TestFlag(MoverParameters->Couplers[1].CouplingFlag, coupling::control)) - { - btCCtrl2.Turn( true ); - btnOn = true; - } - // else btCCtrl2.TurnOff(); - // McZapkie-181103: mostki przejsciowe - if (TestFlag(MoverParameters->Couplers[0].CouplingFlag, ctrain_passenger)) - { - btCPass1.Turn( true ); - btnOn = true; - } - // else btCPass1.TurnOff(); - if (TestFlag(MoverParameters->Couplers[1].CouplingFlag, ctrain_passenger)) - { - btCPass2.Turn( true ); - btnOn = true; - } - // else btCPass2.TurnOff(); - if (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) - { // sygnaly konca pociagu - if (m_endsignals1.Active()) { - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left | light::redmarker_right ) ) { - m_endsignals1.Turn( true ); - btnOn = true; - } - } - else { - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_left) && !HeadlightsAoff) - { - m_endsignal13.Turn( true ); - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::redmarker_right) && !HeadlightsAoff) - { - m_endsignal12.Turn( true ); - btnOn = true; - } - } - if (m_endsignals2.Active()) { - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left | light::redmarker_right ) ) { - m_endsignals2.Turn( true ); - btnOn = true; - } - } - else { - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_left) && !HeadlightsBoff) - { - m_endsignal23.Turn( true ); - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::redmarker_right) && !HeadlightsBoff) - { - m_endsignal22.Turn( true ); - btnOn = true; - } - } - } - // tablice blaszane: - if (TestFlag(MoverParameters->iLights[end::front], light::rearendsignals)) { - m_endtab1.Turn( true ); - btnOn = true; - } - // else btEndSignalsTab1.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::rear], light::rearendsignals)) { - m_endtab2.Turn( true ); - btnOn = true; - } - // destination signs - update_destinations(); - // else btEndSignalsTab2.TurnOff(); - // McZapkie-181002: krecenie wahaczem (korzysta z kata obrotu silnika) - if (iAnimType[ANIM_LEVERS]) - for (int i = 0; i < 4; ++i) - if (smWahacze[i]) - smWahacze[i]->SetRotate(float3(1, 0, 0), - fWahaczeAmp * cos(MoverParameters->eAngle)); - - // cooling shutters - // NOTE: shutters display _on state when they're closed, _off otherwise - if( true == MoverParameters->dizel_heat.water.config.shutters - && false == MoverParameters->dizel_heat.zaluzje1 ) { - btShutters1.Turn( true ); - btnOn = true; - } - if( true == MoverParameters->dizel_heat.water_aux.config.shutters - && false == MoverParameters->dizel_heat.zaluzje2 ) { - btShutters2.Turn( true ); - btnOn = true; - } - - // only external models ( external_only_on / external_only_off ) - btExteriorOnly.Turn(!bDisplayCab); // display only when cab is not rendered - - if( false == bDisplayCab // edge case, lowpoly may act as a stand-in for the hi-fi cab, so make sure not to show the driver when inside - && Mechanik != nullptr - && Mechanik->action() != TAction::actSleep ) { - // rysowanie figurki mechanika - btMechanik1.Turn(MoverParameters->CabOccupied > 0); - btMechanik2.Turn( MoverParameters->CabOccupied < 0 ); - if( MoverParameters->CabOccupied != 0 ) { - btnOn = true; - } - } - - } // vehicle within 400m - - if( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) - { // sygnały czoła pociagu //Ra: wyświetlamy bez - // ograniczeń odległości, by były widoczne z - // daleka - - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) - && !HeadlightsAoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp13.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp13.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_upper) - && !HeadlightsAoff) - { - if( DimHeadlights ) { - m_headlamp11.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp11.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) - && !HeadlightsAoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp12.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp12.TurnOn(); - } - btnOn = true; - } - // else btHeadSignals13.TurnOff(); - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) - && !HeadlightsBoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp23.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp23.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_upper) - && !HeadlightsBoff) - { - if( DimHeadlights ) { - m_headlamp21.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp21.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) - && !HeadlightsBoff && !HighBeamLights) - { - if( DimHeadlights ) { - m_headlamp22.TurnxOnWithOnAsFallback(); - } - else { - m_headlamp22.TurnOn(); - } - btnOn = true; - } - // auxiliary lights - if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_left) && !HeadlightsAoff) - { - if( DimHeadlights ) { - m_headsignal13.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal13.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::front], light::auxiliary_right) && !HeadlightsAoff) - { - if( DimHeadlights ) { - m_headsignal12.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal12.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_left) && !HeadlightsBoff) - { - if( DimHeadlights ) { - m_headsignal23.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal23.TurnOn(); - } - btnOn = true; - } - if (TestFlag(MoverParameters->iLights[end::rear], light::auxiliary_right) && !HeadlightsBoff) - { - if( DimHeadlights ) { - m_headsignal22.TurnxOnWithOnAsFallback(); - } - else { - m_headsignal22.TurnOn(); - } - btnOn = true; - } - - // logika dlugich - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_left) - && !HeadlightsAoff && HighBeamLights) - m_highbeam13.TurnxOnWithOnAsFallback(); - else - m_highbeam13.TurnOff(); - - if (TestFlag(MoverParameters->iLights[end::front], light::headlight_right) - && !HeadlightsAoff && HighBeamLights) - m_highbeam12.TurnxOnWithOnAsFallback(); - else - m_highbeam12.TurnOff(); - - // i to samo od dupy strony - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_left) - && !HeadlightsBoff && HighBeamLights) - m_highbeam23.TurnxOnWithOnAsFallback(); - else - m_highbeam23.TurnOff(); - - if (TestFlag(MoverParameters->iLights[end::rear], light::headlight_right) - && !HeadlightsBoff && HighBeamLights) - m_highbeam22.TurnxOnWithOnAsFallback(); - else - m_highbeam22.TurnOff(); - } - // interior light levels - auto sectionlightcolor { glm::vec4( 1.f ) }; - bool cabsection{ true }; - for( auto const §ion : Sections ) { - if( cabsection ) { - // check whether we're still processing cab sections - auto const §ionname { section.compartment->pName }; - cabsection &= sectionname.size() >= 4 && sectionname.starts_with("cab"); - } - // TODO: add cablight devices - auto const sectionlightlevel { section.light_level * ( cabsection ? 1.0f : MoverParameters->CompartmentLights.intensity ) }; - sectionlightcolor = glm::vec4( - sectionlightlevel == 0.f || Global.fLuminance > section.compartment->fLight ? - glm::vec3(240.f / 255.f) : // TBD: save and restore initial submodel diffuse instead of enforcing one? - InteriorLight, // TODO: per-compartment (type) light color - sectionlightlevel ); - section.compartment->SetLightLevel( sectionlightcolor, true ); - if( section.load != nullptr ) { - section.load->SetLightLevel( sectionlightcolor, true ); - } - } - // load chunks visibility - for( auto const §ion : Sections ) { - // section isn't guaranteed to have load model, so check that first - if( section.load == nullptr ) { continue; } - section.load->iVisible = section.load_chunks_visible > 0; - // if the section root isn't visible we can skip meddling with its children - if( false == section.load->iVisible ) { continue; } - // if the section root is visible set the state of section chunks - auto *sectionchunk { section.load->ChildGet() }; - auto visiblechunkcount { section.load_chunks_visible }; - while( sectionchunk != nullptr ) { - sectionchunk->iVisible = visiblechunkcount > 0; - --visiblechunkcount; - sectionchunk = sectionchunk->NextGet(); - } - } - - // driver cabs visibility - for( int cabidx = 0; cabidx < LowPolyIntCabs.size(); ++cabidx ) { - if( LowPolyIntCabs[ cabidx ] == nullptr ) { continue; } - LowPolyIntCabs[ cabidx ]->iVisible = mdKabina == nullptr ? true : // there's no hi-fi cab - bDisplayCab == false ? true : // we're in external view - simulation::Train == nullptr ? true : // not a player-driven vehicle, implies external view - simulation::Train->Dynamic() != this ? true : // not a player-driven vehicle, implies external view - JointCabs ? false : // internal view, all cabs share the model so hide them 'all' - simulation::Train->iCabn != cabidx; // internal view, hide occupied cab and show others - } -} -// ABu 29.01.05 koniec przeklejenia ************************************* - -TDynamicObject * TDynamicObject::ABuFindNearestObject(glm::vec3 pos, TTrack *Track, TDynamicObject *MyPointer, int &CouplNr) -{ - // zwraca wskaznik do obiektu znajdujacego sie na torze (Track), którego sprzęg jest najblizszy punktowi - // służy np. do łączenia i rozpinania sprzęgów - // WE: Track - tor, na ktorym odbywa sie poszukiwanie - // MyPointer - wskaznik do obiektu szukajacego - // WY: CouplNr - który sprzęg znalezionego obiektu jest bliższy kamerze - - // Uwaga! Jesli CouplNr==-2 to szukamy njblizszego obiektu, a nie sprzegu!!! - for( auto dynamic : Track->Dynamics ) { - - if( CouplNr == -2 ) { - // wektor [kamera-obiekt] - poszukiwanie obiektu - // length2 is better than length for comparing because it does not require sqrt function - if (glm::length2(glm::dvec3(pos) - dynamic->vPosition) < sq(10.0)) - { - // 10 metrów - return dynamic; - } - } - else { - // jeśli (CouplNr) inne niz -2, szukamy sprzęgu - // length2 is better than length for comparing because it does not require sqrt function - if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[0]) < sq(5.0)) { - // 5 metrów - CouplNr = 0; - return dynamic; - } - // length2 is better than length for comparing because it does not require sqrt function - if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[1]) < sq(5.0)) { - // 5 metrów - CouplNr = 1; - return dynamic; - } - } - } - // empty track or nothing found - return nullptr; -} - -TDynamicObject * TDynamicObject::ABuScanNearestObject(glm::vec3 pos, TTrack *Track, double ScanDir, double ScanDist, int &CouplNr) -{ // skanowanie toru w poszukiwaniu obiektu najblizszego punktowi - if (ABuGetDirection() < 0) - ScanDir = -ScanDir; - TDynamicObject *FoundedObj; - FoundedObj = - ABuFindNearestObject(pos, Track, this, CouplNr); // zwraca numer sprzęgu znalezionego pojazdu - if (FoundedObj == nullptr && Track != nullptr) - { - double ActDist; // Przeskanowana odleglosc. - double CurrDist = 0; // Aktualna dlugosc toru. - if (ScanDir >= 0) - ActDist = - Track->Length() - RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru - else - ActDist = RaTranslationGet(); // przesunięcie wózka względem Point1 toru - while (ActDist < ScanDist) - { - ActDist += CurrDist; - if (ScanDir > 0) // do przodu - { - if (Track->iNextDirection) // NOSONAR - { - Track = Track->CurrentNext(); - ScanDir = -ScanDir; - } - else - Track = Track->CurrentNext(); - } - else // do tyłu - { - if (Track->iPrevDirection) // NOSONAR - Track = Track->CurrentPrev(); - else - { - Track = Track->CurrentPrev(); - ScanDir = -ScanDir; - } - } - if (Track != nullptr) - { // jesli jest kolejny odcinek toru - CurrDist = Track->Length(); - FoundedObj = ABuFindNearestObject(pos, Track, this, CouplNr); - if (FoundedObj != nullptr) - ActDist = ScanDist; - } - else // Jesli nie ma, to wychodzimy. - break; - } - } // Koniec szukania najblizszego toru z jakims obiektem. - return FoundedObj; -} - -// ABu 01.11.04 poczatek wyliczania przechylow pudla ********************** -void TDynamicObject::ABuModelRoll() -{ // ustawienie przechyłki pojazdu i jego - // zawartości - // Ra: przechyłkę załatwiamy na etapie przesuwania modelu -} - -// ABu 06.05.04 poczatek wyliczania obrotow wozkow ********************** - -void TDynamicObject::ABuBogies() -{ // Obracanie wozkow na zakretach. Na razie - // uwzględnia tylko zakręty, - // bez zadnych gorek i innych przeszkod. - if (smBogie[0] != nullptr && smBogie[1] != nullptr) - { - // modelRot.z=ABuAcos(Axle0.pPosition-Axle1.pPosition); //kąt obrotu pojazdu - // [rad] - // bogieRot[0].z=ABuAcos(Axle0.pPosition-Axle3.pPosition); - bogieRot[0].z = Axle0.vAngles.z; - bogieRot[0] = glm::degrees(modelRot - bogieRot[0]); // mnożenie wektora przez stałą - smBogie[0]->SetRotateXYZ(bogieRot[0]); - // bogieRot[1].z=ABuAcos(Axle2.pPosition-Axle1.pPosition); - bogieRot[1].z = Axle1.vAngles.z; - bogieRot[1] = glm::degrees(modelRot - bogieRot[1]); - smBogie[1]->SetRotateXYZ(bogieRot[1]); - } -}; -// ABu 06.05.04 koniec wyliczania obrotow wozkow ************************ - -// ABu 16.03.03 sledzenie toru przed obiektem: ************************** -void TDynamicObject::ABuCheckMyTrack() -{ // Funkcja przypisujaca obiekt - // prawidlowej tablicy Dynamics, - // bo gdzies jest jakis blad i wszystkie obiekty z danego - // pociagu na poczatku stawiane sa na jednym torze i wpisywane - // do jednej tablicy. Wykonuje sie tylko raz - po to 'ABuChecked' - TTrack *OldTrack = MyTrack; - TTrack *NewTrack = Axle0.GetTrack(); - if( NewTrack != OldTrack ) { - if( OldTrack ) { - OldTrack->RemoveDynamicObject( this ); - } - NewTrack->AddDynamicObject(this); - } - iAxleFirst = 0; // pojazd powiązany z przednią osią - Axle0 -} - -// Ra: w poniższej funkcji jest problem ze sprzęgami -TDynamicObject * -TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler ) const -{ // Zwraca wskaźnik najbliższego obiektu znajdującego się - // na torze w określonym kierunku, ale tylko wtedy, kiedy - // obiekty mogą się zderzyć, tzn. nie mijają się. - // WE: - // Track - tor, na ktorym odbywa sie poszukiwanie, - // Direction - kierunek szukania na torze (+1:w stronę Point2, -1:w stronę Point1) - // Mycoupler - nr sprzegu obiektu szukajacego; - // WY: - // wskaznik do znalezionego obiektu. - // Foundcoupler - nr sprzegu znalezionego obiektu - // Distance - distance to found object - - if( true == Track->Dynamics.empty() ) { - // sens szukania na tym torze jest tylko, gdy są na nim pojazdy - Distance += Track->Length(); // doliczenie długości odcinka do przeskanowanej odległości - return nullptr; // nie ma pojazdów na torze, to jest NULL - } - - double distance = Track->Length(); // najmniejsza znaleziona odleglość (zaczynamy od długości toru) - double myposition; // pozycja szukającego na torze - TDynamicObject *foundobject = nullptr; - if( MyTrack == Track ) { - // gdy szukanie na tym samym torze - myposition = RaTranslationGet(); // położenie wózka względem Point1 toru - } - else { - // gdy szukanie na innym torze - if( Direction > 0 ) { - // szukanie w kierunku Point2 (od zera) - jesteśmy w Point1 - myposition = 0; - } - else { - // szukanie w kierunku Point1 (do zera) - jesteśmy w Point2 - myposition = distance; - } - } - - double objectposition; // robocza odległość od kolejnych pojazdów na danym odcinku - for( auto dynamic : Track->Dynamics ) { - - if( dynamic == this ) { continue; } // szukający się nie liczy -/* - if( ( ( dynamic == PrevConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::front ].CouplingFlag != coupling::faux ) ) - || ( ( dynamic == NextConnected ) && ( MoverParameters->Couplers[ TMoverParameters::side::rear ].CouplingFlag != coupling::faux ) ) ){ - // stop-gap check to prevent 'detection' of attached vehicles - // which seems to be a side-effect of inaccurate location calculation in 'simple' mode? - // TODO: investigate actual cause - continue; - } -*/ - if( Direction > 0 ) { - // jeśli szukanie w kierunku Point2 - objectposition = dynamic->RaTranslationGet() - myposition; // odległogłość tamtego od szukającego - if( objectposition > 0 - && objectposition < distance ) { - // gdy jest po właściwej stronie i bliżej niż jakiś wcześniejszy - Foundcoupler = dynamic->RaDirectionGet() > 0 ? 1 : 0; // to, bo (ScanDir>=0) - } - else { continue; } - } - else { - objectposition = myposition - dynamic->RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru - if( objectposition > 0 - && objectposition < distance ) { - Foundcoupler = dynamic->RaDirectionGet() > 0 ? 0 : 1; // odwrotnie, bo (ScanDir<0) - } - else { continue; } - } - - if( Track->iCategoryFlag & 254 ) { - // trajektoria innego typu niż tor kolejowy - // dla torów nie ma sensu tego sprawdzać, rzadko co jedzie po jednej szynie i się mija - // Ra: mijanie samochodów wcale nie jest proste - // Przesuniecie wzgledne pojazdow. Wyznaczane, zeby sprawdzic, - // czy pojazdy faktycznie sie zderzaja (moga byc przesuniete - // w/m siebie tak, ze nie zachodza na siebie i wtedy sie mijaja). - double relativeoffset; // wzajemna odległość poprzeczna - if( Foundcoupler != Mycoupler ) { - // facing the same direction - relativeoffset = std::abs( MoverParameters->OffsetTrackH - dynamic->MoverParameters->OffsetTrackH ); - } - else { - relativeoffset = std::abs( MoverParameters->OffsetTrackH + dynamic->MoverParameters->OffsetTrackH ); - } - if( relativeoffset + relativeoffset > MoverParameters->Dim.W + dynamic->MoverParameters->Dim.W ) { - // odległość większa od połowy sumy szerokości - kolizji nie będzie - continue; - } - // jeśli zahaczenie jest niewielkie, a jest miejsce na poboczu, to zjechać na pobocze - } - foundobject = dynamic; // potencjalna kolizja - distance = objectposition; // odleglość pomiędzy aktywnymi osiami pojazdów - } - - Distance += distance; // doliczenie odległości przeszkody albo długości odcinka do przeskanowanej odległości - return foundobject; -} - -int TDynamicObject::DettachStatus(int dir) -{ // sprawdzenie odległości sprzęgów - // rzeczywistych od strony (dir): - // 0=przód,1=tył - // Ra: dziwne, że ta funkcja nie jest używana - if( MoverParameters->Couplers[ dir ].CouplingFlag == coupling::faux ) { - return 0; // jeśli nic nie podłączone, to jest OK - } - return MoverParameters->DettachStatus(dir); // czy jest w odpowiedniej odległości? -} - -int TDynamicObject::Dettach(int dir) -{ // rozłączenie sprzęgów rzeczywistych od - // strony (dir): 0=przód,1=tył - // zwraca maskę bitową aktualnych sprzegów (0 jeśli rozłączony) - if (ctOwner) - { // jeśli pojazd ma przypisany obiekt nadzorujący skład, to póki - // są wskaźniki - TDynamicObject *d = this; - while (d) - { - d->ctOwner = nullptr; // usuwanie właściciela - d = d->Prev(); - } - d = Next(); - while (d) - { - d->ctOwner = nullptr; // usuwanie właściciela - d = d->Next(); // i w drugą stronę - } - } - if( MoverParameters->Couplers[ dir ].CouplingFlag ) { - // odczepianie, o ile coś podłączone - MoverParameters->Dettach( dir ); -/* - if( true == MoverParameters->Dettach( dir ) ) { - auto *othervehicle { dir ? NextConnected : PrevConnected }; - auto const othercoupler { dir ? NextConnectedNo() : PrevConnectedNo() }; - ( othercoupler ? othervehicle->NextConnected : othervehicle->PrevConnected ) = nullptr; - ( dir ? NextConnected : PrevConnected ) = nullptr; - }; -*/ - } - // sprzęg po rozłączaniu (czego się nie da odpiąć - return MoverParameters->Couplers[dir].CouplingFlag; -} - -void -TDynamicObject::couple( int const Side ) { - - auto const &neighbour { MoverParameters->Neighbours[ Side ] }; - - if( neighbour.vehicle == nullptr ) { return; } - - auto const &coupler { MoverParameters->Couplers[ Side ] }; - auto *othervehicle { neighbour.vehicle }; - auto *othervehicleparams{ othervehicle->MoverParameters }; - auto const &othercoupler { othervehicleparams->Couplers[ neighbour.vehicle_end ] }; - - if( coupler.CouplingFlag == coupling::faux ) { - // najpierw hak - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & coupling::coupler ) == coupling::coupler ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupling::coupler ) ) { - // one coupling type per key press - return; - } - else { - WriteLog( "Mechanical coupling failed." ); - } - } - } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::brakehose ) ) { - // pneumatyka - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & coupling::brakehose ) == coupling::brakehose ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | coupling::brakehose ) ) { - SetPneumatic( Side != 0, true ); - othervehicle->SetPneumatic( Side != 0, true ); - // one coupling type per key press - return; - } - } - } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::mainhose ) ) { - // zasilajacy - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & coupling::mainhose ) == coupling::mainhose ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | coupling::mainhose ) ) { - SetPneumatic( Side != 0, false ); - othervehicle->SetPneumatic( Side != 0, false ); - // one coupling type per key press - return; - } - } - } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::control ) ) { - // ukrotnionko - if( (coupler.AllowedFlag & othercoupler.AllowedFlag & coupling::control) == coupling::control - && coupler.control_type == othercoupler.control_type - && ( MoverParameters->CompatibleCoupling( Side, *othervehicleparams, neighbour.vehicle_end, coupler.CouplingFlag | coupling::control ) & coupling::control ) != 0 ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | coupling::control ) ) { - // one coupling type per key press - return; - } - } - } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::gangway ) ) { - // mostek - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & coupling::gangway ) == coupling::gangway ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | coupling::gangway ) ) { - // one coupling type per key press - return; - } - } - } - if( false == TestFlag( MoverParameters->Couplers[ Side ].CouplingFlag, coupling::heating ) ) { - // heating - if( ( coupler.AllowedFlag - & othercoupler.AllowedFlag - & coupling::heating ) == coupling::heating ) { - if( MoverParameters->Attach( - Side, neighbour.vehicle_end, - othervehicleparams, - coupler.CouplingFlag | coupling::heating ) ) { - // one coupling type per key press - return; - } - } - } - -} - -int -TDynamicObject::uncouple( int const Side ) { - - if( DettachStatus(Side) >= 0 - || true == TestFlag(MoverParameters->Couplers[Side].CouplingFlag, coupling::permanent) ) { - // can't uncouple, return existing coupling state - return MoverParameters->Couplers[ Side ].CouplingFlag; - } - // jeżeli sprzęg niezablokowany, jest co odczepić i się da - auto const couplingflag { Dettach( Side ) }; - return couplingflag; -} - -bool -TDynamicObject::attach_coupler_adapter( int const Side, bool const Enforce ) { - - auto &coupler { MoverParameters->Couplers[ Side ] }; - // sanity check(s) - if( coupler.type() == TCouplerType::Automatic ) { return false; } - auto const *neighbour { MoverParameters->Neighbours[ Side ].vehicle }; - if( neighbour == nullptr - || MoverParameters->Neighbours[Side].distance > 25.0 ) { - // can only acquire the adapter from a nearby enough vehicle - return false; - } - // TBD: empty struct instead of fallback defaults, to allow vehicles without adapter? - auto adapterdata { - coupleradapter_data { - { 0.085f, 0.95f }, - "tabor/polsprzeg" } }; - if( false == neighbour->m_coupleradapter.model.empty() ) { - // explicit coupler adapter definition overrides default parameters - adapterdata = neighbour->m_coupleradapter; - } - if( MoverParameters->Neighbours[Side].distance - adapterdata.position.x < 0.5 - && false == Enforce ) { - // arbitrary amount of free room required to install the adapter - // NOTE: this also covers cases with established physical connection - return false; - } - - coupler.adapter_type = TCouplerType::Automatic; - coupler.adapter_length = adapterdata.position.x; - coupler.adapter_height = adapterdata.position.y; - // audio flag, visuals update - coupler.sounds |= sound::attachadapter; - m_coupleradapters[ Side ] = TModelsManager::GetModel( adapterdata.model ); - - return true; -} - -bool -TDynamicObject::remove_coupler_adapter( int const Side ) { - - auto &coupler{ MoverParameters->Couplers[ Side ] }; - - if( coupler.adapter_type == TCouplerType::NoCoupler ) { return false; } - // TODO: sanity check(s) - if( coupler.Connected != nullptr ) { - // TBD: disallow instead adapter removal if it's coupled with another vehicle? - uncouple( Side ); - } - coupler.adapter_type = TCouplerType::NoCoupler; - coupler.adapter_length = 0.0; - coupler.adapter_height = 0.0; - // audio flag, visuals update - coupler.sounds |= sound::removeadapter; - m_coupleradapters[ Side ] = nullptr; - - return true; -} - -TDynamicObject::TDynamicObject() { - modelShake = glm::dvec3(0, 0, 0); -// fTrackBlock = 10000.0; // brak przeszkody na drodze - btnOn = false; - vUp = vWorldUp; - vFront = vWorldFront; - vLeft = vWorldLeft; - iNumAxles = 0; - MoverParameters = nullptr; - Mechanik = nullptr; - MechInside = false; - // McZapkie-270202 - Controller = AIdriver; - bDisplayCab = false; // 030303 -// NextConnected = PrevConnected = NULL; -// NextConnectedNo = PrevConnectedNo = 2; // ABu: Numery sprzegow. 2=nie podłączony - bEnabled = true; - MyTrack = nullptr; - // McZapkie-260202 - dWheelAngle[0] = 0.0; - dWheelAngle[1] = 0.0; - dWheelAngle[2] = 0.0; - // Winger 160204 - pantografy - // PantVolume = 3.5; - NoVoltTime = 0; - mdModel = nullptr; - mdKabina = nullptr; - // smWiazary[0]=smWiazary[1]=NULL; - smWahacze[0] = smWahacze[1] = smWahacze[2] = smWahacze[3] = nullptr; - fWahaczeAmp = 0; - smBrakeMode = nullptr; - smLoadMode = nullptr; - mdLoad = nullptr; - mdLowPolyInt = nullptr; - //smMechanik0 = smMechanik1 = NULL; - smBuforLewy[0] = smBuforLewy[1] = nullptr; - smBuforPrawy[0] = smBuforPrawy[1] = nullptr; - smBogie[0] = smBogie[1] = nullptr; - bogieRot[0] = bogieRot[1] = glm::dvec3(0, 0, 0); - modelRot = glm::dvec3(0, 0, 0); - cp1 = cp2 = sp1 = sp2 = 0; - iDirection = 1; // stoi w kierunku tradycyjnym (0, gdy jest odwrócony) - iAxleFirst = 0; // numer pierwszej osi w kierunku ruchu (przełączenie - // następuje, gdy osie sa na - // tym samym torze) - RaLightsSet(0, 0); // początkowe zerowanie stanu świateł - // Ra: domyślne ilości animacji dla zgodności wstecz (gdy brak ilości podanych - // w MMD) - // ustawienie liczby modeli animowanych podczas konstruowania obiektu a nie na 0 - // prowadzi prosto do wysypów jeśli źle zdefiniowane mmd - iAnimations = 0; // na razie nie ma żadnego - pAnimated = nullptr; - fShade = 0.0; // standardowe oświetlenie na starcie - iHornWarning = 1; // numer syreny do użycia po otrzymaniu sygnału do jazdy - asDestination = "none"; // stojący nigdzie nie jedzie - pValveGear = nullptr; // Ra: tymczasowo - iCabs = 0; // maski bitowe modeli kabin - smBrakeSet = nullptr; // nastawa hamulca (wajcha) - smLoadSet = nullptr; // nastawa ładunku (wajcha) - smWiper = nullptr; // wycieraczka (poniekąd też wajcha) - ctOwner = nullptr; // na początek niczyj - iOverheadMask = 0; // maska przydzielana przez AI pojazdom posiadającym - // pantograf, aby wymuszały - // jazdę bezprądową - tmpTraction.TractionVoltage = 0; // Ra 2F1H: prowizorka, trzeba przechować - // napięcie, żeby nie wywalało WS pod - // izolatorem - fAdjustment = 0.0; // korekcja odległości pomiędzy wózkami (np. na łukach) -} - -TDynamicObject::~TDynamicObject() { - SafeDelete( Mechanik ); - SafeDelete( MoverParameters ); - SafeDeleteArray( pAnimated ); // lista animowanych submodeli -} - -void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) -{ - for( auto &axle : m_axlesounds ) { - // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) - axle.distance = ( - Reversed ? - -axle.offset : - axle.offset + MoverParameters->Dim.L ) + fDist; - } - double fAxleDistHalf = fAxleDist * 0.5; - // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu - fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) - switch (iNumAxles) { - // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane - case 2: // ustawianie osi na torze - Axle0.Reset(); - Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); - Axle1.Reset(); - Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów - break; - } - // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji - // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie - // zrobiło tego - Move( 0.0001 ); - ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) -} - -double -TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" - std::string BaseDir, // z którego katalogu wczytany, np. "PKP/EU07" - std::string asReplacableSkin, // nazwa wymiennej tekstury - std::string Type_Name, // nazwa CHK/MMD, np. "303E" - TTrack *Track, // tor początkowy wstwawienia (początek składu) - double fDist, // dystans względem punktu 1 - std::string DriverType, // typ obsady - double fVel, // prędkość początkowa - std::string TrainName, // nazwa składu, np. "PE2307" albo Vmax, jeśli pliku nie ma a są cyfry - float Load, // ilość ładunku - std::string LoadType, // nazwa ładunku - bool Reversed, // true, jeśli ma stać odwrotnie w składzie - std::string MoreParams // dodatkowe parametry wczytywane w postaci tekstowej - ) -{ // Ustawienie początkowe pojazdu - iDirection = Reversed ? 0 : 1; // Ra: 0, jeśli ma być wstawiony jako obrócony tyłem - asBaseDir = paths::dynamic + BaseDir + "/"; // McZapkie-310302 - asName = Name; - // derived from the name and the seed of the simulation rather than drawn at random, so that the vehicle - // keeps the same look for the whole session and looks the same for everyone in a multiplayer game, while - // another run of the same scenario, with another seed, dresses it differently - m_variantseed = hash_string( asName, Global.random_seed ); - std::string asAnimName; // zmienna robocza do wyszukiwania osi i wózków - // Ra: zmieniamy znaczenie obsady na jednoliterowe, żeby dosadzić kierownika - if (DriverType == "headdriver") - DriverType = "1"; // sterujący kabiną +1 - else if (DriverType == "reardriver") - DriverType = "2"; // sterujący kabiną -1 - else if (DriverType == "passenger") - DriverType = ""; // legacy type, no longer needed - else if (DriverType == "nobody") - DriverType = ""; // nikt nie siedzi - - int Cab = 0; // numer kabiny z obsadą (nie można zająć obu) - if (DriverType == "1") // od przodu składu - Cab = 1; // iDirection?1:-1; //iDirection=1 gdy normalnie, =0 odwrotnie - else if (DriverType == "2") // od tyłu składu - Cab = -1; // iDirection?-1:1; -/* - // NOTE: leave passenger in the middle section, this is most likely to be 'passenger' section in MU trains - else if (DriverType == "p") - { - if (Random(6) < 3) - Cab = 1; - else - Cab = -1; // losowy przydział kabiny - } -*/ - // utworzenie parametrów fizyki - MoverParameters = new TMoverParameters(iDirection ? fVel : -fVel, Type_Name, asName, Cab); - // the vehicle carries on with the odometer state of its earlier sessions (eu07/maszyna#72) - MoverParameters->Odometer = odometer::starting_state( odometer::states(), asName, asBaseDir ); - // McZapkie: TypeName musi byc nazwą CHK/MMD pojazdu - if (!MoverParameters->LoadFIZ(asBaseDir)) - { // jak wczytanie CHK się nie uda, to błąd - if (ConversionError == 666) - ErrorLog( "Bad vehicle: failed to locate definition file \"" + BaseDir + "/" + Type_Name + ".fiz" + "\"" ); - else { - ErrorLog( "Bad vehicle: failed to load definition from file \"" + BaseDir + "/" + Type_Name + ".fiz\" (error " + std::to_string( ConversionError ) + ")" ); - } - return 0.0; // zerowa długość to brak pojazdu - } - // load the cargo now that we know whether the vehicle will allow it - MoverParameters->AssignLoad( LoadType, Load ); - MoverParameters->ComputeMass(); - - bool driveractive = fVel != 0.0; // jeśli prędkość niezerowa, to aktywujemy ruch - if (!MoverParameters->CheckLocomotiveParameters( - driveractive, - (fVel > 0 ? 1 : -1) * Cab * - (iDirection ? 1 : -1))) // jak jedzie lub obsadzony to gotowy do drogi - { - Error("Parameters mismatch: dynamic object " + asName + " from \"" + BaseDir + "/" + Type_Name + "\"" ); - return 0.0; // zerowa długość to brak pojazdu - } - // controller position - MoverParameters->MainCtrlPos = MoverParameters->MainCtrlNoPowerPos(); - // ustawienie pozycji hamulca - MoverParameters->LocalBrakePosA = 0.0; - if (driveractive) - { - if (Cab == 0) - MoverParameters->BrakeCtrlPos = - static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); - else - MoverParameters->BrakeCtrlPos = static_cast( std::floor(MoverParameters->Handle->GetPos(bh_RP)) ); - - // engage independent brake if applicable, if the vehicle is to be on standby - // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep - // TBD, TODO: have the virtual helper release independent brakes during consist check? - if( DriverType != "" ) { - if( MoverParameters->LocalBrake != TLocalBrake::ManualBrake ) { - if( fVel < 1.0 ) { - MoverParameters->IncLocalBrakeLevel( LocalBrakePosNo ); - if ( MoverParameters->EIMCtrlEmergency ) { - MoverParameters->DecLocalBrakeLevel(1); - } - } - } - } - } - else - MoverParameters->BrakeCtrlPos = - static_cast( std::floor(MoverParameters->Handle->GetPos(bh_NP)) ); - - // poprawienie hamulca po ewentualnym przestawieniu przez Pascal - // TODO: check if needed, we're not in Pascal anymore, Toto - MoverParameters->BrakeLevelSet(MoverParameters->BrakeCtrlPos); - - // dodatkowe parametry yB - MoreParams += "."; // wykonuje o jedną iterację za mało, więc trzeba mu dodać - // kropkę na koniec - size_t kropka = MoreParams.find("."); // znajdź kropke - std::string ActPar; // na parametry - while (kropka != std::string::npos) // jesli sa kropki jeszcze - { - size_t dlugosc = MoreParams.length(); - ActPar = ToUpper(MoreParams.substr(0, kropka)); // pierwszy parametr; - MoreParams = MoreParams.substr(kropka + 1, dlugosc - kropka); // reszta do dalszej obrobki - kropka = MoreParams.find("."); - - if (ActPar.substr(0, 1) == "B") // jesli hamulce - { // sprawdzanie kolejno nastaw - WriteLog("Wpis hamulca: " + ActPar); - if ( contains( ActPar, 'G') ) - { - MoverParameters->BrakeDelaySwitch(bdelay_G); - } - if( contains( ActPar, 'P' ) ) - { - MoverParameters->BrakeDelaySwitch(bdelay_P); - } - if( contains( ActPar, 'R' ) ) - { - MoverParameters->BrakeDelaySwitch(bdelay_R); - } - if( contains( ActPar, 'M' ) ) - { - MoverParameters->BrakeDelaySwitch(bdelay_R); - MoverParameters->BrakeDelaySwitch(bdelay_R + bdelay_M); - } - // wylaczanie hamulca - if ( contains( ActPar, "<>") ) // wylaczanie na probe hamowania naglego - { - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - if ( contains( ActPar, '0' ) ) // wylaczanie na sztywno - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - if ( contains( ActPar, 'E' ) ) // oprozniony - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Pipe->CreatePress(0); - MoverParameters->Pipe2->CreatePress(0); - } - if ( contains( ActPar, 'Q' ) ) // oprozniony - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Pipe->CreatePress(0.0); - MoverParameters->PipePress = 0.0; - MoverParameters->Pipe2->CreatePress(0.0); - MoverParameters->ScndPipePress = 0.0; - MoverParameters->PantVolume = 0.1; - MoverParameters->PantPress = 0.0; - MoverParameters->CompressedVolume = 0.0; - } - - if ( contains( ActPar, '1' ) ) // wylaczanie 10% - { - if (Random(10) < 1) // losowanie 1/10 - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - } - if ( contains( ActPar, 'X') ) // agonalny wylaczanie 20%, usrednienie przekladni - { - if (Random(100) < 20) // losowanie 20/100 - { - MoverParameters->Hamulec->ForceEmptiness(); - MoverParameters->Hamulec->SetBrakeStatus( MoverParameters->Hamulec->GetBrakeStatus() | b_dmg ); // wylacz - } - if (MoverParameters->BrakeCylMult[2] * MoverParameters->BrakeCylMult[1] > - 0.01) // jesli jest nastawiacz mechaniczny PL - { - float rnd = Random(100); - if (rnd < 20) // losowanie 20/100 usrednienie - { - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1] = - (MoverParameters->BrakeCylMult[2] + MoverParameters->BrakeCylMult[1]) / - 2; - } - else if (rnd < 70) // losowanie 70/100-20/100 oslabienie - { - MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[1] * 0.50; - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[2] * 0.75; - } - else if (rnd < 80) // losowanie 80/100-70/100 tylko prozny - { - MoverParameters->BrakeCylMult[2] = MoverParameters->BrakeCylMult[1]; - } - else // tylko ladowny - { - MoverParameters->BrakeCylMult[1] = MoverParameters->BrakeCylMult[2]; - } - } - } - // nastawianie ladunku - if ( contains( ActPar, 'T' ) ) // prozny - { - MoverParameters->DecBrakeMult(); - MoverParameters->DecBrakeMult(); - } // dwa razy w dol - if ( contains( ActPar, 'H' ) ) // ladowny I (dla P-Ł dalej prozny) - { - MoverParameters->IncBrakeMult(); - MoverParameters->IncBrakeMult(); - MoverParameters->DecBrakeMult(); - } // dwa razy w gore i obniz - if ( contains( ActPar, 'F' ) ) // ladowny II - { - MoverParameters->IncBrakeMult(); - MoverParameters->IncBrakeMult(); - } // dwa razy w gore - if ( contains( ActPar, 'N' ) ) // parametr neutralny - { - } - } // koniec hamulce - else if( ActPar.size() >= 3 - && ActPar.front() == 'W' ) { - // wheel - ActPar.erase( 0, 1 ); - - auto fixedflatsize { 0 }; - auto randomflatsize { 0 }; - auto flatchance { 100 }; - - while( false == ActPar.empty() ) { - // TODO: convert this whole copy and paste mess to something more elegant one day - switch( ActPar.front() ) { - case 'F': { - // fixed flat size - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - fixedflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - break; - } - case 'R': { - // random flat size - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - randomflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - break; - } - case 'P': { - // random flat probability - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - flatchance = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - break; - } - case 'H': { - // truck hunting - auto const indexstart { 1 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - auto const huntingchance { std::atoi( ActPar.substr( indexstart, indexend ).c_str() ) }; - MoverParameters->TruckHunting = Random(0, 100) < huntingchance; - ActPar.erase( 0, indexend ); - break; - } - default: { - // unrecognized key - ActPar.erase( 0, 1 ); - break; - } - } - } - if( Random( 0, 100 ) <= flatchance ) { - MoverParameters->WheelFlat += fixedflatsize + Random( 0, randomflatsize ); - } - } // wheel - else if( ActPar.size() >= 2 - && ActPar.front() == 'T' ) { - // temperature - ActPar.erase( 0, 1 ); - - auto setambient { false }; - - while( false == ActPar.empty() ) { - switch( ActPar.front() ) { - case 'A': { - // cold start, set all temperatures to ambient level - setambient = true; - ActPar.erase( 0, 1 ); - break; - } - default: { - // unrecognized key - ActPar.erase( 0, 1 ); - break; - } - } - } - if( true == setambient ) { - // TODO: pull ambient temperature from environment data - MoverParameters->dizel_HeatSet( Global.AirTemperature ); - } - } // temperature - else if( ActPar.size() >= 2 - && ActPar.front() == 'L' ) { - // load - ActPar.erase( 0, 1 ); - // immediately followed by max load override - // TBD: make it instead an optional sub-parameter? - { - auto const indexstart { 0 }; - auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; - MoverParameters->MaxLoad = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); - ActPar.erase( 0, indexend ); - } - while( false == ActPar.empty() ) { - switch( ActPar.front() ) { - default: { - // unrecognized key - ActPar.erase( 0, 1 ); - break; - } - } - } - } // load -/* else if (ActPar.substr(0, 1) == "") // tu mozna wpisac inny prefiks i inne rzeczy - { - // jakies inne prefiksy - } -*/ - } // koniec while kropka - - if (MoverParameters->CategoryFlag & 2) // jeśli samochód - { // ustawianie samochodow na poboczu albo na środku drogi - if( Track->fTrackWidth < 3.5 // jeśli droga wąska - || Track->m_road != nullptr ) // a lane of a road node is one-way, the vehicle keeps to its middle - MoverParameters->OffsetTrackH = 0.0; // to stawiamy na środku, niezależnie od stanu - // ruchu - else if( driveractive ) {// od 3.5m do 8.0m jedzie po środku pasa, dla - // szerszych w odległości - // 1.5m - auto const lanefreespace = 0.5 * Track->fTrackWidth - MoverParameters->Dim.W; - MoverParameters->OffsetTrackH = lanefreespace > 1.5 ? - -0.5 * MoverParameters->Dim.W - 0.75 : // wide road, keep near centre with safe margin - lanefreespace > 0.1 ? - -0.25 * Track->fTrackWidth : // narrow fit, stay on the middle - -0.5 * MoverParameters->Dim.W - 0.075; // too narrow, just keep some minimal clearance - } - else // jak stoi, to kołem na poboczu i pobieramy szerokość razem z - // poboczem, ale nie z - // chodnikiem - MoverParameters->OffsetTrackH = - -0.5 * (Track->WidthTotal() - MoverParameters->Dim.W) + 0.05; - iHornWarning = 0; // nie będzie trąbienia po podaniu zezwolenia na jazdę - if (fDist < 0.0) //-0.5*MoverParameters->Dim.L) //jeśli jest przesunięcie do tyłu - if (!Track->CurrentPrev()) // a nie ma tam odcinka i trzeba by coś - // wygenerować - fDist = -fDist; // to traktujemy, jakby przesunięcie było w drugą stronę - } - - create_controller( DriverType, !TrainName.empty() ); - - ShakeSpring.Init( 125.0 ); - BaseShake = baseshake_config {}; - ShakeState = shake_state {}; - ShakeStateBefore = shake_state {}; - - // McZapkie-250202 -/* - iAxles = std::min( MoverParameters->NAxles, MaxAxles ); // ilość osi -*/ - // wczytywanie z pliku nazwatypu.mmd, w tym model - erase_extension( asReplacableSkin ); - LoadMMediaFile(Type_Name, asReplacableSkin); - // McZapkie-100402: wyszukiwanie submodeli sprzegów - btCoupler1.Init( "coupler1", mdModel ); // false - ma być wyłączony - btCoupler2.Init( "coupler2", mdModel ); - // brake hoses - btCPneumatic1.Init("cpneumatic1", mdModel); - btCPneumatic2.Init("cpneumatic2", mdModel); - btCPneumatic1r.Init("cpneumatic1r", mdModel); - btCPneumatic2r.Init("cpneumatic2r", mdModel); - // main hoses - btPneumatic1.Init("pneumatic1", mdModel); - btPneumatic2.Init("pneumatic2", mdModel); - btPneumatic1r.Init("pneumatic1r", mdModel); - btPneumatic2r.Init("pneumatic2r", mdModel); - // control cables - btCCtrl1.Init( "cctrl1", mdModel, false); - btCCtrl2.Init( "cctrl2", mdModel, false); - // gangways - btCPass1.Init( "cpass1", mdModel, false); - btCPass2.Init( "cpass2", mdModel, false); - // sygnaly - m_endsignal12.Init( "endsignal12", mdModel, false ); - m_endsignal13.Init( "endsignal13", mdModel, false ); - m_endsignal22.Init( "endsignal22", mdModel, false ); - m_endsignal23.Init( "endsignal23", mdModel, false ); - m_endsignals1.Init( "endsignals1", mdModel, false ); - m_endsignals2.Init( "endsignals2", mdModel, false ); - m_endtab1.Init( "endtab1", mdModel, false ); - m_endtab2.Init( "endtab2", mdModel, false ); - m_headlamp11.Init( "headlamp11", mdModel ); // górne - m_headlamp12.Init( "headlamp12", mdModel ); // prawe - m_headlamp13.Init( "headlamp13", mdModel ); // lewe - m_highbeam12.Init("highbeam12", mdModel); // prawe dlugie - m_highbeam13.Init("highbeam13", mdModel); // lewe dlugie - m_headlamp21.Init( "headlamp21", mdModel ); - m_headlamp22.Init( "headlamp22", mdModel ); - m_headlamp23.Init( "headlamp23", mdModel ); - m_highbeam22.Init("highbeam22", mdModel); - m_highbeam23.Init("highbeam23", mdModel); - m_headsignal12.Init( "headsignal12", mdModel ); - m_headsignal13.Init( "headsignal13", mdModel ); - m_headsignal22.Init( "headsignal22", mdModel ); - m_headsignal23.Init( "headsignal23", mdModel ); - // informacja, czy ma poszczególne światła - iInventory[ end::front ] |= m_endsignal12.Active() ? light::redmarker_right : 0; - iInventory[ end::front ] |= m_endsignal13.Active() ? light::redmarker_left : 0; - iInventory[ end::rear ] |= m_endsignal22.Active() ? light::redmarker_right : 0; - iInventory[ end::rear ] |= m_endsignal23.Active() ? light::redmarker_left : 0; - iInventory[ end::front ] |= m_endsignals1.Active() ? light::redmarker_left | light::redmarker_right : 0; - iInventory[ end::rear ] |= m_endsignals2.Active() ? light::redmarker_left | light::redmarker_right : 0; - iInventory[ end::front ] |= m_endtab1.Active() ? light::rearendsignals : 0; // tabliczki blaszane - iInventory[ end::rear ] |= m_endtab2.Active() ? light::rearendsignals : 0; - iInventory[ end::front ] |= m_headlamp11.Active() ? light::headlight_upper : 0; - iInventory[ end::front ] |= m_headlamp12.Active() ? light::headlight_right : 0; - iInventory[ end::front ] |= m_headlamp13.Active() ? light::headlight_left : 0; - - iInventory[end::front] |= m_highbeam12.Active() ? light::highbeamlight_right : 0; - iInventory[end::front] |= m_highbeam13.Active() ? light::highbeamlight_left : 0; - - iInventory[ end::rear ] |= m_headlamp21.Active() ? light::headlight_upper : 0; - iInventory[ end::rear ] |= m_headlamp22.Active() ? light::headlight_right : 0; - iInventory[ end::rear ] |= m_headlamp23.Active() ? light::headlight_left : 0; - iInventory[ end::front ] |= m_headsignal12.Active() ? light::auxiliary_right : 0; - iInventory[ end::front ] |= m_headsignal13.Active() ? light::auxiliary_left : 0; - iInventory[ end::rear ] |= m_headsignal22.Active() ? light::auxiliary_right : 0; - iInventory[ end::rear ] |= m_headsignal23.Active() ? light::auxiliary_left : 0; - - iInventory[end::rear] |= m_highbeam22.Active() ? light::highbeamlight_right : 0; - iInventory[end::rear] |= m_highbeam23.Active() ? light::highbeamlight_left : 0; - - btExteriorOnly.Init("external_only", mdModel, false); - - btMechanik1.Init( "mechanik1", mdLowPolyInt, false); - btMechanik2.Init( "mechanik2", mdLowPolyInt, false); - - if( MoverParameters->dizel_heat.water.config.shutters ) { - btShutters1.Init( "shutters1", mdModel, false ); - } - if( MoverParameters->dizel_heat.water_aux.config.shutters ) { - btShutters2.Init( "shutters2", mdModel, false ); - } - TurnOff(); // resetowanie zmiennych submodeli - - if( mdLowPolyInt != nullptr ) { - // check the low poly interior for potential compartments of interest, ie ones which can be individually lit - // TODO: definition of relevant compartments in the .mmd file - TSubModel *submodel { nullptr }; - if( ( submodel = mdLowPolyInt->GetFromName( "cab0" ) ) != nullptr ) { - Sections.push_back( { submodel, nullptr, 0, 0.0f } ); - LowPolyIntCabs[ 0 ] = submodel; - } - if( ( submodel = mdLowPolyInt->GetFromName( "cab1" ) ) != nullptr ) { - Sections.push_back( { submodel, nullptr, 0, 0.0f } ); - LowPolyIntCabs[ 1 ] = submodel; - } - if( ( submodel = mdLowPolyInt->GetFromName( "cab2" ) ) != nullptr ) { - Sections.push_back( { submodel, nullptr, 0, 0.0f } ); - LowPolyIntCabs[ 2 ] = submodel; - } - // passenger car compartments - std::vector nameprefixes = { "corridor", "korytarz", "compartment", "przedzial" }; - for( auto const &nameprefix : nameprefixes ) { - init_sections( mdLowPolyInt, nameprefix, MoverParameters->CompartmentLights.start_type == start_t::manual ); - } - // the inside of the door wings, if the interior has them - init_interior_doors(); - } - // destination sign - if( mdModel ) { - init_destination( mdModel ); - } - // 'external_load' is an optional special section in the main model, pointing to submodel of external load - if( mdModel ) { - init_sections( mdModel, "external_load", false ); - } - update_load_sections(); - update_load_visibility(); - // wyszukiwanie zderzakow - if( mdModel ) { - // jeśli ma w czym szukać - for( int i = 0; i < 2; i++ ) { - asAnimName = std::string( "buffer_left0" ) + std::to_string( i + 1 ); - smBuforLewy[ i ] = mdModel->GetFromName( asAnimName ); - if( smBuforLewy[ i ] ) - smBuforLewy[ i ]->WillBeAnimated(); // ustawienie flagi animacji - asAnimName = std::string( "buffer_right0" ) + std::to_string( i + 1 ); - smBuforPrawy[ i ] = mdModel->GetFromName( asAnimName ); - if( smBuforPrawy[ i ] ) - smBuforPrawy[ i ]->WillBeAnimated(); - } - } - if( Track->fSoundDistance > 0.f ) { - for( auto &axle : m_axlesounds ) { - // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) - axle.distance = - clamp_circular( - ( Reversed ? - -axle.offset : - axle.offset ) - - 0.5 * MoverParameters->Dim.L - + fDist, - Track->fSoundDistance ); - } - } - // McZapkie-250202 end. - Track->AddDynamicObject(this); // wstawiamy do toru na pozycję 0, a potem przesuniemy - // McZapkie: zmieniono na ilosc osi brane z chk - // iNumAxles=(MoverParameters->NAxles>3 ? 4 : 2 ); - initial_track = MyTrack; - iNumAxles = 2; - // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami - fAxleDist = safe_clamp( - std::max( MoverParameters->BDist, MoverParameters->ADist ), - 0.2, //żeby się dało wektory policzyć - MoverParameters->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" - double fAxleDistHalf = fAxleDist * 0.5; - // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu - fDist -= 0.5 * MoverParameters->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) - switch (iNumAxles) { - // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane - case 2: // ustawianie osi na torze - Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); - Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów - break; - case 4: - Axle0.Init(Track, this, iDirection ? 1 : -1); - Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + MoverParameters->ADist * 0.5), false); - Axle1.Init(Track, this, iDirection ? 1 : -1); - Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + MoverParameters->ADist * 0.5), false); - // Axle2.Init(Track,this,iDirection?1:-1); - // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-MoverParameters->ADist*0.5),false); - // Axle3.Init(Track,this,iDirection?1:-1); - // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-MoverParameters->ADist*0.5),false); - break; - } - // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji - // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie - // zrobiło tego - Move( 0.0001 ); - ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) - // Ra: ustawienie pozycji do obliczania sprzęgów - MoverParameters->Loc = { - -vPosition.x, - vPosition.z, - vPosition.y }; // normalnie przesuwa ComputeMovement() w Update() - // ABuWozki 060504 - if (mdModel) // jeśli ma w czym szukać - { - smBogie[0] = mdModel->GetFromName("bogie1"); // Ra: bo nazwy są małymi - smBogie[1] = mdModel->GetFromName("bogie2"); - if (!smBogie[0]) - smBogie[0] = mdModel->GetFromName("boogie01"); // Ra: alternatywna nazwa - if (!smBogie[1]) - smBogie[1] = mdModel->GetFromName("boogie02"); // Ra: alternatywna nazwa - if (smBogie[0]) - smBogie[0]->WillBeAnimated(); - if (smBogie[1]) - smBogie[1]->WillBeAnimated(); - sm_winter_variant = mdModel->GetFromName("winter_variant"); - sm_spring_variant = mdModel->GetFromName("spring_variant"); - sm_summer_variant = mdModel->GetFromName("summer_variant"); - sm_autumn_variant = mdModel->GetFromName("autumn_variant"); - } - // ABu: zainicjowanie zmiennej, zeby nic sie nie ruszylo w pierwszej klatce, - // potem juz liczona prawidlowa wartosc masy - MoverParameters->ComputeConstans(); - // wektor podłogi dla wagonów, przesuwa ładunek - vFloor = glm::dvec3(0, 0, MoverParameters->Floor); - - // długość większa od zera oznacza OK; 2mm docisku? - return MoverParameters->Dim.L; -} - -int -TDynamicObject::init_sections( TModel3d const *Model, std::string const &Nameprefix, bool const Overrideselfillum ) { - - auto sectioncount = 0; - auto sectionindex = 0; - TSubModel *sectionsubmodel { nullptr }; - - do { - // section names for index < 10 match either prefix0X or prefixX - // section names above 10 match prefixX - auto const sectionindexname { std::to_string( sectionindex ) }; - sectionsubmodel = Model->GetFromName( Nameprefix + sectionindexname ); - if( sectionsubmodel == nullptr - && sectionindex < 10 ) { - sectionsubmodel = Model->GetFromName( Nameprefix + "0" + sectionindexname ); - } - if( sectionsubmodel != nullptr ) { - // HACK: disable automatic self-illumination threshold, at least until 3d model update - if( Overrideselfillum ) { - sectionsubmodel->SetSelfIllum( 2.0f, true, false ); - } - Sections.push_back( { - sectionsubmodel, - nullptr, // pointers to load sections are generated afterwards - 0, - 0.0f } ); - ++sectioncount; - } - ++sectionindex; - } while( sectionsubmodel != nullptr - || sectionindex < 2 ); // chain can start from prefix00 or prefix01 - - return sectioncount; -} - -// a door wing of the main model is seen from the outside, lit as the exterior. its namesake in the low poly interior, -// if the model has one, follows its moves and is lit with the interior, by its compartment section if it's in one -void -TDynamicObject::init_interior_doors() { - - if( mdLowPolyInt == nullptr ) { return; } - - for( auto &animation : pAnimations ) { - // the door animation is only set up for a wing found in the main model - if( false == door_wings::is_wing( animation.iFlags ) ) { continue; } - if( ( animation.yUpdate == nullptr ) || ( animation.smAnimated == nullptr ) ) { continue; } - - auto *interiorwing { mdLowPolyInt->GetFromName( animation.smAnimated->pName ) }; - if( ( interiorwing == nullptr ) || ( interiorwing == animation.smAnimated ) ) { continue; } - - interiorwing->WillBeAnimated(); - animation.smInterior = interiorwing; - } -} - -bool -TDynamicObject::init_destination( TModel3d *Model ) { - - if( Model->GetSMRoot() == nullptr ) { return false; } - - std::tie( DestinationSign.sign, DestinationSign.has_light ) = Model->GetSMRoot()->find_replacable4(); - - return DestinationSign.sign != nullptr; -} - -void -TDynamicObject::create_controller( std::string const Type, bool const Trainset ) { - - if( Type == "" ) { return; } - - // McZapkie-151102: rozkład jazdy czytany z pliku *.txt z katalogu w którym jest sceneria - if( Type == "1" - || Type == "2" ) { - // McZapkie-110303: mechanik i rozklad tylko gdy jest obsada - Mechanik = new TController( Controller, this, Aggressive ); - - if( false == Trainset ) { - // jeśli nie w składzie - // załączenie rozrządu (wirtualne kabiny) itd. - Mechanik->DirectionInitial(); - // tryb pociągowy z ustaloną prędkością (względem sprzęgów) - Mechanik->PutCommand( - "Timetable:", - MoverParameters->V * 3.6 * ( iDirection ? -1.0 : 1.0 ), - 0, - nullptr ); - } - } - else if( Type == "p" ) { - // obserwator w charakterze pasażera - // Ra: to jest niebezpieczne, bo w razie co będzie pomagał hamulcem bezpieczeństwa - Mechanik = new TController( Controller, this, Easyman, false ); - } -} - -void TDynamicObject::FastMove(double fDistance) -{ - MoverParameters->dMoveLen = MoverParameters->dMoveLen + fDistance; -} - -void TDynamicObject::Move(double fDistance) -{ // przesuwanie pojazdu po - // trajektorii polega na - // przesuwaniu poszczególnych osi - // Ra: wartość prędkości 2km/h ma ograniczyć aktywację eventów w przypadku - // drgań - if (Axle0.GetTrack() == Axle1.GetTrack()) // przed przesunięciem - { // powiązanie pojazdu z osią można zmienić tylko wtedy, gdy skrajne osie są - // na tym samym torze - if (MoverParameters->Vel > - 2) //|[km/h]| nie ma sensu zmiana osi, jesli pojazd drga na postoju - iAxleFirst = MoverParameters->V >= 0.0 ? - 1 : - 0; //[m/s] ?1:0 - aktywna druga oś w kierunku jazdy - // aktualnie eventy aktywuje druga oś, żeby AI nie wyłączało sobie semafora - // za szybko - } - if (fDistance > 0.0) - { // gdy ruch w stronę sprzęgu 0, doliczyć korektę do osi 1 - bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu - bEnabled &= Axle1.Move(fDistance /*-fAdjustment*/, iAxleFirst != 0); // oś z tyłu pojazdu - } - else if (fDistance < 0.0) - { // gdy ruch w stronę sprzęgu 1, doliczyć korektę do osi 0 - bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza - bEnabled &= Axle0.Move(fDistance /*-fAdjustment*/, iAxleFirst == 0); // oś z przodu pojazdu - } - else // gf: bez wywolania Move na postoju nie ma event0 - { - bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza - bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu - } - if (fDistance != 0.0) // nie liczyć ponownie, jeśli stoi - { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach - vPosition = 0.5 * (Axle1.pPosition + Axle0.pPosition); //środek między skrajnymi osiami - vFront = Axle0.pPosition - Axle1.pPosition; // wektor pomiędzy skrajnymi osiami - // Ra 2F1J: to nie jest stabilne (powoduje rzucanie taborem) i wymaga - // dopracowania - fAdjustment = glm::length(vFront) - fAxleDist; // na łuku będzie ujemny - // if (fabs(fAdjustment)>0.02) //jeśli jest zbyt dużo, to rozłożyć na kilka przeliczeń (wygasza drgania?) - //{//parę centymetrów trzeba by już skorygować; te błędy mogą się też - // generować na ostrych łukach - // fAdjustment*=0.5; //w jednym kroku korygowany jest ułamek błędu - //} - // else - // fAdjustment=0.0; - vFront = glm::normalize(vFront); // kierunek ustawienia pojazdu (wektor jednostkowy) - vLeft = glm::normalize(glm::cross(glm::dvec3(vWorldUp), vFront)); // wektor poziomy w lewo, - // normalizacja potrzebna z powodu pochylenia (vFront) - vUp = glm::cross(vFront, vLeft); // wektor w górę, będzie jednostkowy - modelRot.z = atan2(-vFront.x, vFront.z); // kąt obrotu pojazdu [rad]; z ABuBogies() - auto const roll { Roll() }; // suma przechyłek - if (roll != 0.0) - { // wyznaczanie przechylenia tylko jeśli jest przechyłka - // można by pobrać wektory normalne z toru... - mMatrix = glm::rotate(glm::dmat4(1.0), roll * 0.5, vFront); // ta macierz jest potrzebna głównie do wyświetlania // obrót wzdłuż osi o przechyłkę - vUp = glm::dvec3(mMatrix * glm::dvec4(vUp, 0.0)); // wektor w górę pojazdu (przekręcenie na przechyłce) - // vLeft=mMatrix*DynamicObject->vLeft; - // vUp=CrossProduct(vFront,vLeft); //wektor w górę - // vLeft=Normalize(CrossProduct(vWorldUp,vFront)); //wektor w lewo - vLeft = glm::normalize(glm::cross(vUp, vFront)); // wektor w lewo - // vUp=CrossProduct(vFront,vLeft); //wektor w górę - } - mMatrix = BasisChange(vLeft, vUp, vFront); // to też można by od razu policzyć, ale potrzebne jest do wyświetlania // przesuwanie jest jednak rzadziej niż renderowanie - mMatrix = glm::inverse(mMatrix); // wyliczenie macierzy dla pojazdu (potrzebna tylko do wyświetlania?) - // if (MoverParameters->CategoryFlag&2) - { // przesunięcia są używane po wyrzuceniu pociągu z toru - vPosition.x += MoverParameters->OffsetTrackH * vLeft.x; // dodanie przesunięcia w bok - vPosition.z += MoverParameters->OffsetTrackH * vLeft.z; // vLeft jest wektorem poprzecznym - // if () na przechyłce będzie dodatkowo zmiana wysokości samochodu - vPosition.y += MoverParameters->OffsetTrackV; // te offsety są liczone przez moverparam - } - // obliczanie pozycji sprzęgów do liczenia zderzeń - auto dir = 0.5 * MoverParameters->Dim.L * vFront; // wektor sprzęgu - vCoulpler[end::front] = vPosition + dir; // współrzędne sprzęgu na początku - vCoulpler[end::rear] = vPosition - dir; // współrzędne sprzęgu na końcu - // bCameraNear= - // if (bCameraNear) //jeśli istotne są szczegóły (blisko kamery) - { // przeliczenie cienia - TTrack *t0 = Axle0.GetTrack(); // już po przesunięciu - TTrack *t1 = Axle1.GetTrack(); - if (t0->eEnvironment == e_flat && t1->eEnvironment == e_flat) // może być e_bridge... - fShade = 0.0; // standardowe oświetlenie - else - { // jeżeli te tory mają niestandardowy stopień zacienienia - // (e_canyon, e_tunnel) - if (t0->eEnvironment == t1->eEnvironment) - { - switch (t0->eEnvironment) - { // typ zmiany oświetlenia - case e_canyon: - fShade = 0.65f; - break; // zacienienie w kanionie - case e_tunnel: - fShade = 0.20f; - break; // zacienienie w tunelu - } - } - else // dwa różne - { // liczymy proporcję - double d = Axle0.GetTranslation(); // aktualne położenie na torze - if (Axle0.GetDirection() < 0) - d = t0->Length() - d; // od drugiej strony liczona długość - d /= fAxleDist; // rozsataw osi procentowe znajdowanie się na torze - - float shadefrom = 1.0f, shadeto = 1.0f; - // NOTE, TODO: calculating brightness level is used enough times to warrant encapsulation into a function - switch( t0->eEnvironment ) { - case e_canyon: { shadeto = 0.65f; break; } - case e_tunnel: { shadeto = 0.2f; break; } - default: {break; } - } - switch( t1->eEnvironment ) { - case e_canyon: { shadefrom = 0.65f; break; } - case e_tunnel: { shadefrom = 0.2f; break; } - default: {break; } - } - fShade = std::lerp( shadefrom, shadeto, static_cast( d ) ); -/* - switch (t0->eEnvironment) - { // typ zmiany oświetlenia - zakładam, że - // drugi tor ma e_flat - case e_canyon: - fShade = (d * 0.65) + (1.0 - d); - break; // zacienienie w kanionie - case e_tunnel: - fShade = (d * 0.20) + (1.0 - d); - break; // zacienienie w tunelu - } - switch (t1->eEnvironment) - { // typ zmiany oświetlenia - zakładam, że - // pierwszy tor ma e_flat - case e_canyon: - fShade = d + (1.0 - d) * 0.65; - break; // zacienienie w kanionie - case e_tunnel: - fShade = d + (1.0 - d) * 0.20; - break; // zacienienie w tunelu - } -*/ - } - } - } - } -}; - -void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) -{ // Ra: doczepia Object na końcu składu (nazwa funkcji może być myląca) - // Ra: używane tylko przy wczytywaniu scenerii - auto const vehicleend { iDirection }; - auto const othervehicleend { Object->iDirection ^ 1 }; - - MoverParameters->Attach( vehicleend, othervehicleend, Object->MoverParameters, iType, true, false ); - // update neighbour data for both affected vehicles - update_neighbours(); - Object->update_neighbours(); - - // potentially attach automatic coupler adapter to allow the connection - // HACK: we're doing it after establishin actual connection, as the method needs valid neighbour data - auto &coupler { MoverParameters->Couplers[ vehicleend ] }; - auto &othercoupler { Object->MoverParameters->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; - - if( coupler.type() != othercoupler.type() ) { - if( othercoupler.type() == TCouplerType::Automatic ) { - // try to attach adapter to the vehicle - attach_coupler_adapter( - vehicleend, - true ); - } - else if( coupler.type() == TCouplerType::Automatic ) { - // try to attach adapter to the other vehicle - Object->attach_coupler_adapter( - othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr, - true ); - } - // update distance to neighbours on account of potentially attached adapter - update_neighbours(); - Object->update_neighbours(); - } - // potentially adjust vehicle position to avoid collision at the simulation start - if( MoverParameters->Neighbours[ vehicleend ].distance > -0.001 ) { return; } - - Object->Move( MoverParameters->Neighbours[ vehicleend ].distance * Object->DirectionGet() ); - // HACK: manually update vehicle position as it's used by neighbour distance update we do next - Object->MoverParameters->Loc = { - -Object->vPosition.x, - Object->vPosition.z, - Object->vPosition.y }; - // update neighbour distance data after moving our vehicle - update_neighbours(); - Object->update_neighbours(); -} - -bool TDynamicObject::UpdateForce(double dt) -{ - if (!bEnabled) - return false; - if( dt > 0 ) { - // wywalenie WS zależy od ustawienia kierunku - MoverParameters->ComputeTotalForce( dt ); - } - return true; -} - -// initiates load change by specified amounts, with a platform on specified side -void TDynamicObject::LoadExchange( int const Disembark, int const Embark, int const Platforms ) { -/* - if( ( MoverParameters->Doors.open_control == control_t::passenger ) - || ( MoverParameters->Doors.open_control == control_t::mixed ) ) { - // jeśli jedzie do tyłu, to drzwi otwiera odwrotnie - auto const lewe = ( DirectionGet() > 0 ) ? 1 : 2; - auto const prawe = 3 - lewe; - if( Platform & lewe ) { - MoverParameters->OperateDoors( side::left, true, range_t::local ); - } - if( Platform & prawe ) { - MoverParameters->OperateDoors( side::right, true, range_t::local ); - } - } -*/ - if( Platforms == 0 ) { return; } // edge case, if there's no accessible platforms discard the request - - m_exchange.unload_count += Disembark; - m_exchange.load_count += Embark; - m_exchange.platforms = Platforms; - m_exchange.time = 0.0; -} - -// calculates time needed to complete current load change -float TDynamicObject::LoadExchangeTime( int const Platforms ) { - - m_exchange.platforms = Platforms; - return LoadExchangeTime(); -} - -float TDynamicObject::LoadExchangeTime() const { - - if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return 0.f; } - - auto const baseexchangetime { m_exchange.unload_count / MoverParameters->UnLoadSpeed + m_exchange.load_count / MoverParameters->LoadSpeed }; - auto const nominalexchangespeedfactor { ( m_exchange.platforms == 3 ? 2.f : 1.f ) }; - auto const actualexchangespeedfactor { LoadExchangeSpeed() }; - - return baseexchangetime / ( actualexchangespeedfactor > 0.f ? actualexchangespeedfactor : nominalexchangespeedfactor ); -} - -// calculates current load exchange rate -float TDynamicObject::LoadExchangeSpeed() const { - // platforms (1:left, 2:right, 3:both) - // with exchange performed on both sides waiting times are halved - auto exchangespeedfactor { 0.f }; - auto const lewe { DirectionGet() > 0 ? 1 : 2 }; - auto const prawe { 3 - lewe }; - if( m_exchange.platforms & lewe ) { - exchangespeedfactor += MoverParameters->Doors.instances[side::left].is_open ? 1.f : 0.f; - } - if( m_exchange.platforms & prawe ) { - exchangespeedfactor += MoverParameters->Doors.instances[side::right].is_open ? 1.f : 0.f; - } - - return exchangespeedfactor; -} - -// update state of load exchange operation -void TDynamicObject::update_exchange( double const Deltatime ) { - - // TODO: move offset calculation after initial check, when the loading system is all unified - update_load_offset(); - - if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return; } - - if( MoverParameters->Vel < 2.0 ) { - - auto const exchangespeed { LoadExchangeSpeed() }; - - if( exchangespeed < ( m_exchange.platforms == 3 ? 2.f : 1.f ) ) { - // the exchange isn't performed at optimal rate, or at all. try to open viable vehicle doors to speed it up - auto const lewe { DirectionGet() > 0 ? 1 : 2 }; - auto const prawe { 3 - lewe }; - if( m_exchange.platforms & lewe - && false == (MoverParameters->Doors.instances[side::left].is_open || MoverParameters->Doors.instances[side::left].is_opening) ) { - // try to open left door - MoverParameters->OperateDoors( side::left, true, range_t::local ); - } - if( m_exchange.platforms & prawe - && false == (MoverParameters->Doors.instances[side::right].is_open || MoverParameters->Doors.instances[side::right].is_opening) ) { - // try to open right door - MoverParameters->OperateDoors( side::right, true, range_t::local ); - } - } - - if( exchangespeed > 0.f ) { - - m_exchange.time += Deltatime; - while( m_exchange.unload_count > 0.01 - && m_exchange.time >= 1.0 ) { - - m_exchange.time -= 1.0; - auto const exchangesize = std::min( m_exchange.unload_count, MoverParameters->UnLoadSpeed * exchangespeed ); - m_exchange.unload_count -= exchangesize; - MoverParameters->LoadStatus = 1; - MoverParameters->LoadAmount = std::max( 0.f, MoverParameters->LoadAmount - exchangesize ); - MoverParameters->ComputeMass(); - update_load_visibility(); - } - if( m_exchange.unload_count < 0.01 ) { - // finish any potential unloading operation before adding new load - // don't load more than can fit - m_exchange.load_count = std::min( m_exchange.load_count, MoverParameters->MaxLoad - MoverParameters->LoadAmount ); - while( m_exchange.load_count > 0.01 - && m_exchange.time >= 1.0 ) { - - m_exchange.time -= 1.0; - auto const exchangesize = std::min( m_exchange.load_count, MoverParameters->LoadSpeed * exchangespeed ); - m_exchange.load_count -= exchangesize; - MoverParameters->LoadStatus = 2; - MoverParameters->LoadAmount = std::min( MoverParameters->MaxLoad, MoverParameters->LoadAmount + exchangesize ); // std::max not strictly needed but, eh - MoverParameters->ComputeMass(); - update_load_visibility(); - } - } - } - } - - if( MoverParameters->Vel > 2.0 ) { - // if the vehicle moves too fast cancel the exchange - m_exchange.unload_count = 0; - m_exchange.load_count = 0; - } - - if( m_exchange.unload_count < 0.01 - && m_exchange.load_count < 0.01 ) { - - MoverParameters->LoadStatus = 4; - // if the exchange is completed (or canceled) close the door, if applicable - if( MoverParameters->Doors.close_control == control_t::passenger - || MoverParameters->Doors.close_control == control_t::mixed ) { - - if( MoverParameters->Vel > 2.0 - || Random() < ( - // remotely controlled door are more likely to be left open - MoverParameters->Doors.close_control == control_t::passenger ? 0.75 : 0.50) ) { - - MoverParameters->OperateDoors( side::left, false, range_t::local ); - MoverParameters->OperateDoors( side::right, false, range_t::local ); - } - } - // if the vehicle was emptied potentially switch load visualization model - if( MoverParameters->LoadAmount == 0 ) { - MoverParameters->AssignLoad( "" ); - } - } -} - -void TDynamicObject::LoadUpdate() { - - MoverParameters->LoadStatus &= 1 | 2; // po zakończeniu będzie równe zero - // przeładowanie modelu ładunku - if( MoverParameters->LoadTypeChange ) { - // whether we succeed or not don't try more than once - MoverParameters->LoadTypeChange = false; - // bieżąca ścieżka do tekstur to dynamic/... - Global.asCurrentTexturePath = asBaseDir; - mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); - // TODO: discern from vehicle component which merely uses vehicle directory and has no animations, so it can be initialized outright - // and actual vehicles which get their initialization after their animations are set up - if( mdLoad != nullptr ) { - mdLoad->Init(); - } - // update bindings between lowpoly sections and potential load chunks placed inside them - update_load_sections(); - // z powrotem defaultowa sciezka do tekstur - Global.asCurrentTexturePath = std::string( paths::textures ); - } -} - -void -TDynamicObject::update_load_sections() { - - SectionLoadOrder.clear(); - - for( auto §ion : Sections ) { - - section.load = GetSubmodelFromName( mdLoad, section.compartment->pName ); - - if( section.load != nullptr ) { - // create entry for each load model chunk assigned to the section - // TBD, TODO: store also pointer to chunk submodel and control its visibility more directly, instead of per-section visibility flag? - auto loadchunkcount { section.load->count_children() }; - while( loadchunkcount-- ) { - SectionLoadOrder.push_back( §ion ); - } - // HACK: disable automatic self-illumination threshold, at least until 3d model update - if( MoverParameters->CompartmentLights.start_type == start_t::manual ) { - section.load->SetSelfIllum( 2.0f, true, false ); - } - } - } - shuffle_load_order(); -} - -void -TDynamicObject::update_load_visibility() { - // start with clean load chunk visibility slate - for( auto §ion : Sections ) { - section.load_chunks_visible = 0; - } - // each entry in load order sequence matches a single chunk of the section it points to - // the length of load order sequence matches total number of load chunks - auto const loadpercentage { ( - MoverParameters->MaxLoad == 0.f ? - 0.0 : - MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - auto visiblechunkcount { ( - SectionLoadOrder.empty() ? - 0 : - static_cast( std::ceil( loadpercentage * SectionLoadOrder.size() - 0.001f ) ) ) }; - for( auto *section : SectionLoadOrder ) { - if( visiblechunkcount == 0 ) { break; } - section->load_chunks_visible++; - --visiblechunkcount; - } -} - -void -TDynamicObject::update_load_offset() { - - if( MoverParameters->LoadType.offset_min == 0.f ) { return; } - - auto const loadpercentage { ( - MoverParameters->MaxLoad == 0.f ? - 0.0 : - 100.0 * MoverParameters->LoadAmount / MoverParameters->MaxLoad ) }; - - LoadOffset = std::lerp( MoverParameters->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); -} - -void -TDynamicObject::shuffle_load_order() { - - // order of visible load chunks, nothing security related -- see the engines in Globals.h - std::shuffle( std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), Global.random_engine ); // NOSONAR - // shift chunks assigned to corridors to the end of the list, so they show up last - std::stable_partition( - std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), - []( vehicle_section const *section ) { - return section->compartment->pName.find("compartment") == 0 || section->compartment->pName.find("przedzial") == 0; } ); - // NOTE: potentially we're left with a mix of corridor and external section loads - // but that's not necessarily a wrong outcome, so we leave it this way for the time being -} - -/* -Ra: - Powinny być dwie funkcje wykonujące aktualizację fizyki. Jedna wykonująca -krok obliczeń, powtarzana odpowiednią liczbę razy, a druga wykonująca zbiorczą -aktualzację mniej istotnych elementów. - Ponadto należało by ustalić odległość składów od kamery i jeśli przekracza -ona np. 10km, to traktować składy jako uproszczone, np. bez wnikania w siły -na sprzęgach, opóźnienie działania hamulca itp. Oczywiście musi mieć to pewną -histerezę czasową, aby te tryby pracy nie przełączały się zbyt szybko. -*/ - -void TDynamicObject::update_destinations() { - - if( DestinationSign.sign == nullptr ) { return; } - - auto const lowvoltagepower { ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) }; - - DestinationSign.sign->fLight = DestinationSign.has_light && lowvoltagepower ? 2.0 : -1.0; - - // jak są 4 tekstury wymienne, to nie zmieniać rozkładem - if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } - // TODO: dedicated setting to discern electronic signs, instead of fallback on light presence - m_materialdata.replacable_skins[ 4 ] = DestinationSign.destination != null_handle && (false == DestinationSign.has_light // physical destination signs remain up until manually changed - || (lowvoltagepower // lcd signs are off without power - && ctOwner != nullptr)) ? // lcd signs are off for carriages without engine, potentially left on a siding - DestinationSign.destination : - DestinationSign.destination_off; - - update_script_destination(); -} - -void TDynamicObject::update_script_destination() { - - if( DestinationSign.script_sign == nullptr ) { return; } - // only while the sign shows the destination it draws - if( m_materialdata.replacable_skins[ 4 ] != DestinationSign.destination ) { return; } - - auto &queue { Application.screens() }; - if( false == queue.due( *DestinationSign.script_sign ) ) { return; } - // read anew on every refresh, so the sign follows the timetable - queue.submit( DestinationSign.script_sign, std::make_shared( DestinationSign.script_request ), 0 ); -} - -bool TDynamicObject::Update(double dt, double dt1) -{ - if (dt1 == 0.0) - return true; // Ra: pauza - if (!MoverParameters->PhysicActivation && - !MechInside) // to drugie, bo będąc w maszynowym blokuje się fizyka - return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba - if (!MyTrack) - return false; // pojazdy postawione na torach portalowych mają MyTrack==NULL - if (!bEnabled) - return false; // a normalnie powinny mieć bEnabled==false - - double dDOMoveLen; - // McZapkie: parametry powinny byc pobierane z toru - if (Axle0.vAngles.z != Axle1.vAngles.z) - { // wyliczenie promienia z obrotów osi - modyfikację zgłosił youBy - ts.R = Axle0.vAngles.z - Axle1.vAngles.z; // różnica może dawać stałą ±M_2PI - if( ts.R > 15000.0 || ts.R < -15000.0 ) { - // szkoda czasu na zbyt duże promienie, 4km to promień nie wymagający przechyłki - ts.R = 0.0; - } - else { - // normalizacja - if( ts.R > M_PI ) { ts.R -= M_2PI; } - else if( ts.R < -M_PI ) { ts.R += M_2PI; } - - if( ts.R != 0.0 ) { - // sin(0) results in division by zero - ts.R = -0.5 * MoverParameters->BDist / sin( ts.R * 0.5 ); - } - } - } - else - ts.R = 0.0; - // ts.R=ComputeRadius(Axle1.pPosition,Axle2.pPosition,Axle3.pPosition,Axle0.pPosition); - // Ra: składową pochylenia wzdłużnego mamy policzoną w jednostkowym wektorze - // vFront - ts.Len = 1.0; // std::max(MoverParameters->BDist,MoverParameters->ADist); - ts.dHtrack = -vFront.y; // Axle1.pPosition.y-Axle0.pPosition.y; //wektor - // między skrajnymi osiami - // (!!!odwrotny) - ts.dHrail = (Axle1.GetRoll() + Axle0.GetRoll()) * 0.5; //średnia przechyłka pudła - // TTrackParam tp; - tp.Width = MyTrack->fTrackWidth; - // McZapkie-250202 - tp.friction = MyTrack->Friction() * Global.fFriction * Global.FrictionWeatherFactor; - tp.CategoryFlag = MyTrack->iCategoryFlag & 15; - tp.DamageFlag = MyTrack->iDamageFlag; - tp.QualityFlag = MyTrack->iQualityFlag; - - // couplers - if( MoverParameters->Couplers[0].CouplingFlag != coupling::faux - && MoverParameters->Couplers[1].CouplingFlag != coupling::faux ) { - MoverParameters->InsideConsist = true; - } - else { - MoverParameters->InsideConsist = false; - } - if( TestFlag( MoverParameters->AIFlag, sound::attachcoupler ) ) { - auto *driver{ ctOwner ? ctOwner : Mechanik }; - if( driver != nullptr ) { - driver->CheckVehicles( Connect ); - } - ClearFlag( MoverParameters->AIFlag, sound::attachcoupler ); - } - - // napiecie sieci trakcyjnej - if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy - - tmpTraction.TractionVoltage = std::max( std::abs( MoverParameters->PantRearVolt ), std::abs( MoverParameters->PantFrontVolt ) ); - // jeśli brak zasilania dłużej niż 0.2 sekundy (25km/h pod izolatorem daje 0.15s) - // Ra 2F1H: prowizorka, trzeba przechować napięcie, żeby nie wywalało WS pod izolatorem - if( tmpTraction.TractionVoltage > 0.0) { - NoVoltTime = 0; - } - else { - NoVoltTime += dt1; - if( NoVoltTime <= 0.2 ) { - tmpTraction.TractionVoltage = MoverParameters->PantographVoltage; - } - else { - // jeśli jedzie - if( MoverParameters->Vel > 0.5 ) { - // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej - if( MoverParameters->Pantographs[end::front].is_active - || MoverParameters->Pantographs[end::rear].is_active ) { - if( MoverParameters->Mains // Ra 15-01: logować tylko, jeśli WS załączony - && MoverParameters->GetTrainsetHighVoltage() < 0.1f ) { // yB 16-03: i nie jest to asynchron zasilany z daleka - // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje - ErrorLog( - "Bad traction: " + MoverParameters->Name - + " lost power for " + to_string( NoVoltTime, 2 ) + " sec. at " - + to_string(vPosition) ); - } - } - } - } - } - } - else { - tmpTraction.TractionVoltage = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; - } - tmpTraction.TractionFreq = 0; - tmpTraction.TractionMaxCurrent = 7500; // Ra: chyba za dużo? powinno wywalać przy 1500 - tmpTraction.TractionResistivity = 0.3; - - MoverParameters->PantographVoltage = tmpTraction.TractionVoltage; - // McZapkie: predkosc w torze przekazac do TrackParam - // McZapkie: Vel ma wymiar [km/h] (absolutny), V ma wymiar [m/s], taka przyjalem notacje - tp.Velmax = MyTrack->VelocityGet(); - - if (Mechanik) - { // Ra 2F3F: do Driver.cpp to przenieść? - if( Mechanik->primary() ) { - MoverParameters->EqvtPipePress = GetEPP(); // srednie cisnienie w PG - } - if (Mechanik->primary() && - (MoverParameters->EngineType == TEngineType::DieselEngine || - MoverParameters->EngineType == TEngineType::DieselElectric) - && MoverParameters->EIMCtrlType > 0) { - MoverParameters->CheckEIMIC(dt1); - if (MoverParameters->SpeedCtrl) - MoverParameters->CheckSpeedCtrl(dt1); - MoverParameters->eimic_real = std::min(MoverParameters->eimic,MoverParameters->eimicSpeedCtrl); - MoverParameters->SendCtrlToNext("EIMIC", MoverParameters->eimic_real, MoverParameters->CabActive); - } - if( Mechanik->primary() - && MoverParameters->EngineType == TEngineType::ElectricInductionMotor ) { - // jesli glowny i z asynchronami, to niech steruje hamulcem i napedem lacznie dla calego pociagu/ezt - auto const kier = DirectionGet() * MoverParameters->CabOccupied > 0; - auto FED { 0.0 }; - auto np { 0 }; - auto masa { 0.0 }; - auto FrED { 0.0 }; - auto masamax { 0.0 }; - auto FmaxPN { 0.0 }; - auto FfulED { 0.0 }; - auto FmaxED { 0.0 }; - auto Frj { 0.0 }; - auto osie { 0 }; - // 0a. ustal aktualna nastawe zadania sily napedowej i hamowania - if( MoverParameters->Power < 1 - && ctOwner != nullptr ) { - MoverParameters->MainCtrlPos = ctOwner->Controlling()->MainCtrlPos*MoverParameters->MainCtrlPosNo / std::max(1, ctOwner->Controlling()->MainCtrlPosNo); - MoverParameters->SpeedCtrlValue = ctOwner->Controlling()->SpeedCtrlValue; - MoverParameters->SpeedCtrlUnit.IsActive = ctOwner->Controlling()->SpeedCtrlUnit.IsActive; - } - MoverParameters->CheckEIMIC(dt1); - MoverParameters->CheckSpeedCtrl(dt1); - - auto eimic = std::min(MoverParameters->eimic, MoverParameters->eimicSpeedCtrl); - MoverParameters->eimic_real = eimic; - // Elf: full braking at once in the lowest position, and in the emergency brake position below it - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos <= MoverParameters->EIMCtrlEmergencyPositions()) - eimic = -1.0; - MoverParameters->SendCtrlToNext("EIMIC", std::max(0., eimic), MoverParameters->CabActive); - auto LBR = std::max(-eimic, 0.); - auto eim_lb = Mechanik->AIControllFlag || !MoverParameters->LocHandleTimeTraxx ? 0 : MoverParameters->eim_localbrake; - - // 1. ustal wymagana sile hamowania calego pociagu - // - opoznienie moze byc ustalane na podstawie charakterystyki - // - opoznienie moze byc ustalane na podstawie mas i cisnien granicznych - // - - // 2. ustal mozliwa do realizacji sile hamowania ED - // - w szczegolnosci powinien brac pod uwage rozne sily hamowania - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - kier ? p = p->Next(4) : p = p->Prev(4)) - { - ++np; - masamax += - p->MoverParameters->MBPM - + ( p->MoverParameters->MBPM > 1.0 ? - 0.0 : - p->MoverParameters->Mass ) - + p->MoverParameters->Mred; - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - FmaxPN += Nmax * p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * - 1000; // sila hamowania pn - FmaxED += p->MoverParameters->Mains && p->MoverParameters->DirActive != 0 && p->MoverParameters->InvertersRatio == 1.0 && - p->MoverParameters->eimc[eimc_p_Fh] * p->MoverParameters->NPoweredAxles > 0 ? - p->MoverParameters->eimc[eimc_p_Fh] * 1000 : - 0; // chwilowy max ED -> do rozdzialu sil - FED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - FfulED = std::min(p->MoverParameters->eimv[eimv_Fful], 0.0) * - 1000; // chwilowy max ED -> do rozdzialu sil - FrED -= std::min(p->MoverParameters->eimv[eimv_Fmax], 0.0) * - 1000; // chwilowo realizowane ED -> do pneumatyki - Frj += std::max(p->MoverParameters->eimv[eimv_Fmax], 0.0) * - 1000;// chwilowo realizowany napęd -> do utrzymującego - masa += p->MoverParameters->TotalMass; - osie += p->MoverParameters->NAxles; - } - double RapidMult = 1.0; - if ((MoverParameters->BrakeDelays & bdelay_P + bdelay_R) == bdelay_P + bdelay_R - && MoverParameters->BrakeDelayFlag & bdelay_P) - RapidMult = MoverParameters->RapidMult; - - auto const amax = RapidMult * std::min(FmaxPN / masamax, MoverParameters->MED_amax); - - Mechanik->fMedAmax = amax; - auto doorisopen { - false == MoverParameters->Doors.instances[side::left].is_closed - || false == MoverParameters->Doors.instances[side::right].is_closed - || ( MoverParameters->Doors.permit_needed - && ( MoverParameters->Doors.instances[ side::left ].open_permit - || MoverParameters->Doors.instances[ side::right ].open_permit ) ) }; - doorisopen &= !(MoverParameters->ReleaseParkingBySpringBrakeWhenDoorIsOpen && MoverParameters->SpringBrake.IsActive); - - if (MoverParameters->Vel < 0.5 && (eimic < 0 || doorisopen || MoverParameters->Hamulec->GetEDBCP())) - { - MoverParameters->ShuntMode = true; - } - if (MoverParameters->ShuntMode) - { - MoverParameters->ShuntModeAllow = false == doorisopen && - LBR < 0.01; - } - if( MoverParameters->Vel > 1 && false == doorisopen ) - { - MoverParameters->ShuntMode = false; - MoverParameters->ShuntModeAllow = MoverParameters->BrakePress > 0.2 && - LBR < 0.01; - } - auto Fzad = amax * LBR * masa; - if ((MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->eimc[eimc_p_abed] < 0.001) || - MoverParameters->EmergencyValveFlow > 0) - Fzad = amax * masa; //pętla bezpieczeństwa - pełne służbowe - if (MoverParameters->ScndS && - MoverParameters->Vel > MoverParameters->eimc[eimc_p_Vh1] && FmaxED > 0) - { - Fzad = std::min(LBR * FmaxED, FfulED); - } - if (MoverParameters->ShuntMode && eimic <= 0 || doorisopen /*|| - (MoverParameters->V * MoverParameters->DirAbsolute < -0.2)*/) - { - auto const sbd { ( MoverParameters->SpringBrake.IsActive && MoverParameters->ReleaseParkingBySpringBrake ? 0.0 : MoverParameters->StopBrakeDecc ) }; - Fzad = std::max( Fzad, sbd * masa ); - } - if (Fzad > 1 && !MEDLogFile.is_open() && MoverParameters->Vel > 1) - { - MEDLogFile.open( - "MEDLOGS/" + MoverParameters->Name + "_" + std::to_string( ++MEDLogCount ) + ".csv", - std::ios::in | std::ios::out | std::ios::trunc ); - MEDLogFile << "t\tVel\tMasa\tOsie\tFmaxPN\tFmaxED\tFfulED\tFrED\tFzad\tFzadED\tFzadPN"; - for(int k=1;k<=np;k++) - { - MEDLogFile << "\tBP" << k; - } - MEDLogFile << "\n"; - MEDLogFile.flush(); - MEDLogInactiveTime = 0; - MEDLogTime = 0; - } - auto FzadED { 0.0 }; - if( LBR > MoverParameters->MED_MinBrakeReqED - && ( MoverParameters->BrakeHandle == TBrakeHandle::MHZ_EN57 ? - (MoverParameters->BrakeOpModeFlag & bom_MED) != 0 : - MoverParameters->EpFuse ) ) { - FzadED = std::min( Fzad, FmaxED ); - } - /*/ELF - wdrazanie ED po powrocie na utrzymanie hamowania - do usuniecia - if (MoverParameters->EIMCtrlType == 2 && MoverParameters->MainCtrlPos < 2 && MoverParameters->eimic > -0.999) - { - FzadED = std::min(FzadED, MED_oldFED); - } //*/ - //opoznienie wdrazania ED - if (FzadED > MED_oldFED) - { - if (MoverParameters->MED_ED_DelayTimer <= 0) { - MoverParameters->MED_ED_DelayTimer += dt1; - if (MoverParameters->MED_ED_DelayTimer > 0) { - - } - else { - FzadED = std::min(FzadED, MED_oldFED); - } - } - else - { - FzadED = std::min(FzadED, MED_oldFED); - MoverParameters->MED_ED_DelayTimer = FrED > 0 ? -MoverParameters->MED_ED_Delay2 : -MoverParameters->MED_ED_Delay1; - } - } - if (MoverParameters->BrakeCtrlPos == MoverParameters->Handle->GetPos(bh_EB) - && MoverParameters->eimc[eimc_p_abed] < 0.001) - FzadED = 0; //pętla bezpieczeństwa - bez ED - auto const FzadPN = Fzad - FrED * MoverParameters->MED_FrED_factor; - std::vector PrzekrF( np ); - float nPrzekrF = 0; - bool test = true; - std::vector FzED( np ); - std::vector FzEP( np ); - std::vector FmaxEP( np ); - // 3. ustaw pojazdom sile hamowania ED - // - proporcjonalnie do mozliwosci - - // 4. ustal potrzebne dohamowanie pneumatyczne - // - od sily zadanej trzeba odjac realizowana przez ED - // 5. w razie potrzeby wlacz hamulec utrzymujacy - // - gdy zahamowany ma ponizej 2 km/h - // 6. ustaw pojazdom sile hamowania ep - // - proporcjonalnie do masy, do liczby osi, rowne cisnienia - jak - // bedzie, tak bedzie dobrze - float Fpoj = 0; // MoverParameters->CabOccupied < 0 - ////ALGORYTM 2 - KAZDEMU PO ROWNO, ale nie wiecej niz eped * masa - // 1. najpierw daj kazdemu tyle samo - int i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - p = kier == true ? p->Next(4) : p->Prev(4) ) - { - auto const Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - FmaxEP[i] = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), - p->MoverParameters->MED_Vref) * - 1000; // sila hamowania pn - - PrzekrF[i] = false; - FzED[i] = FmaxED > 0 ? FzadED / FmaxED : 0; - p->MoverParameters->AnPos = - MoverParameters->ScndS ? LBR : FzED[i]; - FzEP[ i ] = static_cast( FzadPN * p->MoverParameters->NAxles ) / static_cast( osie ); - ++i; - p->MoverParameters->ShuntMode = MoverParameters->ShuntMode; - p->MoverParameters->ShuntModeAllow = MoverParameters->ShuntModeAllow; - } - while (test) - { - test = false; - i = 0; - float przek = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - p = kier == true ? p->Next(4) : p->Prev(4) ) - { - if (FzEP[i] > 0.01 && - FzEP[i] > p->MoverParameters->TotalMass * p->MoverParameters->eimc[eimc_p_eped] + std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 && - !PrzekrF[i]) - { - float przek1 = -std::min(p->MoverParameters->eimv[eimv_Fmax], 0.) * 1000 + - FzEP[i] - - p->MoverParameters->TotalMass * - p->MoverParameters->eimc[eimc_p_eped] * 0.999; - PrzekrF[i] = true; - test = true; - nPrzekrF++; - przek1 = std::min(przek1, FzEP[i]); - FzEP[i] -= przek1; - if (FzEP[i] < 0) - FzEP[i] = 0; - przek += przek1; - } - ++i; - } - i = 0; - przek = przek / (np - nPrzekrF); - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - true == kier ? p = p->Next(4) : p = p->Prev(4)) - { - if (!PrzekrF[i]) - { - FzEP[i] += przek; - } - ++i; - } - } - i = 0; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - true == kier ? p = p->Next(4) : p = p->Prev(4)) - { - float Nmax = ((p->MoverParameters->P2FTrans * p->MoverParameters->MaxBrakePress[0] - - p->MoverParameters->BrakeCylSpring) * - p->MoverParameters->BrakeCylMult[0] - - p->MoverParameters->BrakeSlckAdj) * - p->MoverParameters->BrakeCylNo * p->MoverParameters->BrakeRigEff; - if (FrED > 0.1) - p->MoverParameters->MED_EPVC_CurrentTime = 0; - else - p->MoverParameters->MED_EPVC_CurrentTime += dt1; - bool EPVC = p->MoverParameters->MED_EPVC && (p->MoverParameters->MED_EPVC_Time < 0 || p->MoverParameters->MED_EPVC_CurrentTime < p->MoverParameters->MED_EPVC_Time); - float VelC = EPVC ? safe_clamp(p->MoverParameters->Vel, p->MoverParameters->MED_Vmin, p->MoverParameters->MED_Vmax) : p->MoverParameters->MED_Vref;//korekcja EP po prędkości - float FmaxPoj = Nmax * - p->MoverParameters->Hamulec->GetFC( - Nmax / (p->MoverParameters->NAxles * p->MoverParameters->NBpA), VelC) * - 1000; // sila hamowania pn - p->MoverParameters->LocalBrakePosAEIM = FzEP[i] / FmaxPoj; - if (p->MoverParameters->LocalBrakePosAEIM>0.009) - if (p->MoverParameters->P2FTrans * p->MoverParameters->BrakeCylMult[0] * - p->MoverParameters->MaxBrakePress[0] != 0) - { - float x = (p->MoverParameters->BrakeSlckAdj / p->MoverParameters->BrakeCylMult[0] + - p->MoverParameters->BrakeCylSpring) / (p->MoverParameters->P2FTrans * - p->MoverParameters->MaxBrakePress[0]); - p->MoverParameters->LocalBrakePosAEIM = x + (1 - x) * p->MoverParameters->LocalBrakePosAEIM; - } - else - p->MoverParameters->LocalBrakePosAEIM = p->MoverParameters->LocalBrakePosAEIM; - else - p->MoverParameters->LocalBrakePosAEIM = 0; - if (p->MoverParameters->LocHandleTimeTraxx) - { - p->MoverParameters->eim_localbrake = eim_lb; - p->MoverParameters->LocalBrakePosAEIM = std::max(p->MoverParameters->LocalBrakePosAEIM, eim_lb); - } - ++i; - } - - MED[0][0] = masa*0.001; - MED[0][1] = amax; - MED[0][2] = Fzad*0.001; - MED[0][3] = FmaxPN*0.001; - MED[0][4] = FmaxED*0.001; - MED[0][5] = FrED*0.001; - MED[0][6] = FzadPN*0.001; - MED[0][7] = nPrzekrF; - - if (MEDLogFile.is_open()) - { - MEDLogFile << MEDLogTime << "\t" << MoverParameters->Vel << "\t" << masa*0.001 << "\t" << osie << "\t" << FmaxPN*0.001 << "\t" << FmaxED*0.001 << "\t" - << FfulED*0.001 << "\t" << FrED*0.001 << "\t" << Fzad*0.001 << "\t" << FzadED*0.001 << "\t" << FzadPN*0.001; - for (TDynamicObject *p = GetFirstDynamic(MoverParameters->CabOccupied < 0 ? 1 : 0, 4); p; - true == kier ? p = p->Next(4) : p = p->Prev(4)) - { - MEDLogFile << "\t" << p->MoverParameters->BrakePress; - } - MEDLogFile << "\n"; - if (floor(MEDLogTime + dt1) > floor(MEDLogTime)) - { - MEDLogFile.flush(); - } - MEDLogTime += dt1; - - if (MoverParameters->Vel < 0.1 || MoverParameters->MainCtrlPowerPos() > 0) - { - MEDLogInactiveTime += dt1; - } - else - { - MEDLogInactiveTime = 0; - } - if (MEDLogInactiveTime > 5) - { - MEDLogFile.flush(); - MEDLogFile.close(); - } - - } - - MED_oldFED = FzadED; - } - - Timer::subsystem.vehicles_ai.start(); - Mechanik->Update(dt1); // przebłyski świadomości AI - Timer::subsystem.vehicles_ai.stop(); - } - - // fragment "z EXE Kursa" - if( MoverParameters->Mains ) { // nie wchodzić w funkcję bez potrzeby - if( false == (MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable) -/* - // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected - && ( Controller == Humandriver ) -*/ - && MoverParameters->EngineType != TEngineType::DieselEngine - && MoverParameters->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna - if( MoverParameters->MainSwitch( false, MoverParameters->TrainType == dt_EZT ? range_t::unit : range_t::local ) ) { - // wyłączyć zasilanie - // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists - MoverParameters->EventFlag = true; - // drop pantographs - // NOTE: this isn't universal behaviour - // TODO: have this dependant on .fiz-driven flag - // NOTE: moved to pantspeed calculation part a little later in the function. all remarks and todo still apply -/* - MoverParameters->PantFront( false, ( MoverParameters->TrainType == dt_EZT ? range::unit : range::local ) ); - MoverParameters->PantRear( false, ( MoverParameters->TrainType == dt_EZT ? range::unit : range::local ) ); -*/ - } - } - } - - // przekazanie pozycji do fizyki - // NOTE: coordinate system swap - // TODO: replace with regular glm vectors - TLocation const l { - -vPosition.x, - vPosition.z, - vPosition.y }; - TRotation const r { - 0.0, - 0.0, - modelRot.z }; - // McZapkie-260202 - dMoveLen przyda sie przy stukocie kol - dDOMoveLen = GetdMoveLen() + MoverParameters->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); - if( Mechanik ) { - // dodanie aktualnego przemieszczenia - Mechanik->MoveDistanceAdd( dDOMoveLen ); - } - if( simulation::Train != nullptr - && simulation::Train->Dynamic() == this ) { - // update distance meter in user-controlled cab - // TBD: place the meter on mover logic level? - simulation::Train->add_distance( dDOMoveLen ); - } - glm::dvec3 old_pos = vPosition; - Move(dDOMoveLen); - - m_future_movement = (vPosition - old_pos) / dt1 * Timer::GetDeltaRenderTime(); - - if (!bEnabled) // usuwane pojazdy nie mają toru - { // pojazd do usunięcia - bDynamicRemove = true; // sprawdzić - return false; - } - ResetdMoveLen(); - - // McZapkie-260202 - // tupot mew, tfu, stukot kol: - if( MyTrack->fSoundDistance != -1 ) { - - if( MyTrack->fSoundDistance != dRailLength ) { - if( dRailLength > 0.0 ) { - for( auto &axle : m_axlesounds ) { - axle.distance = axle.offset; - axle.atjoints = false; - } - } - dRailLength = MyTrack->fSoundDistance; - } - if( dRailLength > 0.0 ) { - if( MoverParameters->Vel > 0 ) { - // TODO: track quality and/or environment factors as separate subroutine - auto volume = - std::lerp( - 0.8, 1.2, - std::clamp( - MyTrack->iQualityFlag / 10.0, - 0.0, 1.5 ) ); - switch( MyTrack->eEnvironment ) { - case e_tunnel: { - volume *= 1.3; - break; - } - case e_bridge: { - volume *= 1.5; - break; - } - default: { - break; - } - } - if( dRailLength > 0.0 ) { - auto axleindex { 0 }; - auto const directioninconsist { ( - ctOwner == nullptr ? - 1 : - ctOwner->Vehicle()->DirectionGet() == DirectionGet() ? 1 : -1 ) }; - for( auto &axle : m_axlesounds ) { - if( axle_passed_joint( axle, dDOMoveLen, directioninconsist ) - && MoverParameters->Vel > 0.1 ) { - // NOTE: for combined clatter sound we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range - auto const frequency = true == axle.clatter.is_combined() ? MoverParameters->Vel * 0.01 : 1.0; - axle.clatter - .pitch( frequency ) - .gain( volume ) - .play(); - // crude bump simulation, drop down on even axles, move back up on - // the odd ones - // MoverParameters->AccVert += (MoverParameters->Vel*0.1f) * - // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the - // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is - // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only - double const headroom = safe_clamp( 0.0, MoverParameters->Vmax, MoverParameters->Vmax - ( MoverParameters->Vel + MoverParameters->Vmax * 0.32f ) ); - double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); - if (MyTrack->eType == tt_Normal) - { - MoverParameters->AccVert += safe_clamp( 0.0, 4.0, jolt ); - } - else if (MyTrack->eType == tt_Switch) - { - double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); - MoverParameters->AccS += accHorizontal; - MoverParameters->AccN += accHorizontal; - MoverParameters->AccVert += safe_clamp( 0.0, 2.0, jolt ); - } - } - ++axleindex; - } - } - } - } - } - // McZapkie-260202 end - - // fragment z EXE Kursa - /* if (MoverParameters->TrainType==dt_ET42) - { - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - ((MoverParameters->BrakePress > - 0.2) || ( MoverParameters->PipePress < 0.36 ))) - { - MoverParameters->StLinFlag=true; - } - else - if ((MoverParameters->DynamicBrakeType=dbrake_switch) && - (MoverParameters->BrakePress < - 0.1)) - { - MoverParameters->StLinFlag=false; - - } - } */ - - if (MoverParameters->Vel != 0) - { // McZapkie-050402: krecenie kolami: - glm::dvec3 old_wheels = glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]); - - dWheelAngle[0] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / - MoverParameters->WheelDiameterL; // przednie toczne - dWheelAngle[1] += MoverParameters->nrot * dt1 * 360.0; // napędne - dWheelAngle[2] += 114.59155902616464175359630962821 * MoverParameters->V * dt1 / - MoverParameters->WheelDiameterT; // tylne toczne - - - m_future_wheels_angle = (glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]) - old_wheels) / dt1 * Timer::GetDeltaRenderTime(); - - dWheelAngle[0] = clamp_circular( dWheelAngle[0] ); - dWheelAngle[1] = clamp_circular( dWheelAngle[1] ); - dWheelAngle[2] = clamp_circular( dWheelAngle[2] ); - } - if (pants) // pantograf może być w wagonie kuchennym albo pojeździe rewizyjnym (np. SR61) - { // przeliczanie kątów dla pantografów - double k; // tymczasowy kąt - double PantDiff; - TAnimPant *p; // wskaźnik do obiektu danych pantografu - double fCurrent = ( - MoverParameters->DynamicBrakeFlag && MoverParameters->ResistorsFlag ? - 0 : - std::abs( MoverParameters->Itot ) * MoverParameters->IsVehicleEIMBrakingFactor() ) - + MoverParameters->TotalCurrent; // prąd pobierany przez pojazd - bez sensu z tym (TotalCurrent) - // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) - // fCurrent+=fabs(MoverParameters->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF -/* - double fPantCurrent = fCurrent; // normalnie cały prąd przez jeden pantograf - if (iAnimType[ANIM_PANTS] > 1) { // a jeśli są dwa pantografy //Ra 1014-11: proteza, trzeba zrobić sensowniej - if (pants[0].fParamPants->hvPowerWire && pants[1].fParamPants->hvPowerWire) { // i oba podłączone do drutów - fPantCurrent = fCurrent * 0.5; // to dzielimy prąd równo na oba (trochę bez sensu, ale lepiej tak niż podwoić prąd) - } - } -*/ - // test whether more than one pantograph touches the wire - // NOTE: we're duplicating lot of code from below - // TODO: clean this up - auto activepantographs { 0 }; - for( int idx = 0; idx < iAnimType[ ANIM_PANTS ]; ++idx ) { - auto const *pantograph { pants[ idx ].fParamPants }; - if( Global.bLiveTraction == false ) { - if( pantograph->PantWys >= 1.2 ) { - ++activepantographs; - } - } - else { - if( pantograph->hvPowerWire != nullptr - && true == MoverParameters->Pantographs[end::front].is_active - && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania - ++activepantographs; - } - } - } - auto const fPantCurrent { fCurrent / std::max( 1, activepantographs ) }; - - for (int i = 0; i < iAnimType[ANIM_PANTS]; ++i) - { // pętla po wszystkich pantografach - p = pants[i].fParamPants; - if (p->PantWys < 0) - { // patograf został połamany, liczony nie będzie - if (p->fAngleL > p->fAngleL0) - p->fAngleL -= 0.2 * dt1; // nieco szybciej niż jak dla opuszczania - if (p->fAngleL < p->fAngleL0) - p->fAngleL = p->fAngleL0; // kąt graniczny - if (p->fAngleU < M_PI) - p->fAngleU += 0.5 * dt1; // górne się musi ruszać szybciej. - if (p->fAngleU > M_PI) - p->fAngleU = M_PI; - if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie - MoverParameters->PantRearVolt = 0.0; - else - MoverParameters->PantFrontVolt = 0.0; - continue; // reszta wtedy nie jest wykonywana - } - PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny - switch (i) // numer pantografu - { // trzeba usunąć to rozróżnienie - case 0: - if (Global.bLiveTraction == false - && p->hvPowerWire == nullptr ) { - // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantFrontVolt = - p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : - 0.0; - } - else if( true == MoverParameters->Pantographs[end::front].is_active - && PantDiff < 0.01 ) // tolerancja niedolegania - { - if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantFrontVolt }; - // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() - if( lastvoltage == 0.0 ) { - // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); - } - else { - MoverParameters->PantFrontVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantFrontVolt > 0.0 ) { - fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) - } - } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph - if( lastvoltage == 0.0 - && MoverParameters->PantFrontVolt > 0.0 ) { - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantUp.offset().z > 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantUp.play( sound_flags::exclusive ); - } - } - } - } - else - MoverParameters->PantFrontVolt = 0.0; - } - else - MoverParameters->PantFrontVolt = 0.0; - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantRearVolt * fPantCurrent * dt1 / 3600000.0; - break; - case 1: - if( false == Global.bLiveTraction - && nullptr == p->hvPowerWire ) { - // jeśli nie ma drutu, może pooszukiwać - MoverParameters->PantRearVolt = - p->PantWys >= 1.2 ? - 0.95 * MoverParameters->EnginePowerSource.MaxVoltage : - 0.0; - } - else if ( true == MoverParameters->Pantographs[end::rear].is_active - && PantDiff < 0.01 ) - { - if (p->hvPowerWire) { - auto const lastvoltage { MoverParameters->PantRearVolt }; - // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() - if( lastvoltage == 0.0 ) { - // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, 0.0 ); - } - else { - MoverParameters->PantRearVolt = p->hvPowerWire->VoltageGet( MoverParameters->PantographVoltage, fPantCurrent ); - if( MoverParameters->PantRearVolt > 0.0 ) { - fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) - } - } - // TODO: refactor reaction to voltage change to mover as sound event for specific pantograph - if( lastvoltage == 0.0 - && MoverParameters->PantRearVolt > 0.0 ) { - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantUp.offset().z < 0 ) { - // limit to pantographs located in the rear half of the vehicle - pantograph.sPantUp.play( sound_flags::exclusive ); - } - } - } - } - else - MoverParameters->PantRearVolt = 0.0; - } - else { -// Global.iPause ^= 2; - MoverParameters->PantRearVolt = 0.0; - } - ( fPantCurrent > 0.0 ? MoverParameters->EnergyMeter.first : MoverParameters->EnergyMeter.second ) += MoverParameters->PantFrontVolt * fPantCurrent * dt1 / 3600000.0; - break; - } // pozostałe na razie nie obsługiwane - if( MoverParameters->PantPress > ( - MoverParameters->TrainType == dt_EZT ? - 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 - 3.45 ) ) { - // z EXE Kursa - // Ra: wysokość zależy od ciśnienia !!! - pantspeedfactor = 0.015 * MoverParameters->PantPress * dt1; - } - else { - pantspeedfactor = 0.0; - } - if( false == ( MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable ) ) { - pantspeedfactor = 0.0; - } - pantspeedfactor = std::max( 0.0, pantspeedfactor ); - k = p->fAngleL; - if( pantspeedfactor > 0.0 - && MoverParameters->Pantographs[i].is_active )// jeśli ma być podniesiony - { - if (PantDiff > 0.001) // jeśli nie dolega do drutu - { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego - // ramienia zgodnie z ciśnieniem - if (pantspeedfactor > - 0.55 * PantDiff) // 0.55 to około pochodna kąta po wysokości - k += 0.55 * PantDiff; // ograniczenie "skoku" w danej klatce - else - k += pantspeedfactor; // dolne ramię - // jeśli przekroczono kąt graniczny, zablokować pantograf - // (wymaga interwencji pociągu sieciowego) - } - else if (PantDiff < -0.001) { - // drut się obniżył albo pantograf podniesiony za wysoko - // jeśli wysokość jest zbyt duża, wyznaczyć zmniejszenie kąta - // jeśli zmniejszenie kąta jest zbyt duże, przejść do trybu łamania pantografu - // if (PantFrontDiff<-0.05) //skok w dół o 5cm daje złąmanie pantografu - k += 0.4 * PantDiff; // mniej niż pochodna kąta po wysokości - } // jeśli wysokość jest dobra, nic więcej nie liczyć - } - else - { // jeśli ma być na dole - if (k > p->fAngleL0) // jeśli wyżej niż położenie wyjściowe - k -= 0.15 * dt1; // ruch w dół - if (k < p->fAngleL0) - k = p->fAngleL0; // położenie minimalne - } - if (k != p->fAngleL) - { //żeby nie liczyć w kilku miejscach ani gdy nie potrzeba - if (k + p->fAngleU < M_PI) - { // o ile nie został osiągnięty kąt maksymalny - p->fAngleL = k; // zmieniony kąt - // wyliczyć kąt górnego ramienia z wzoru (a)cosinusowego - //=acos((b*cos()+c)/a) - // p->dPantAngleT=acos((1.22*cos(k)+0.535)/1.755); //górne ramię - p->fAngleU = acos((p->fLenL1 * cos(k) + p->fHoriz) / p->fLenU1); // górne ramię - // wyliczyć aktualną wysokość z wzoru sinusowego - // h=a*sin()+b*sin() - // wysokość całości - p->PantWys = p->fLenL1 * sin(k) + p->fLenU1 * sin(p->fAngleU) + p->fHeight; - } - } - } // koniec pętli po pantografach - // TBD, TODO: generate sound event during mover update instead? - if( MoverParameters->Pantographs[end::front].sound_event != MoverParameters->Pantographs[ end::front ].is_active ) { - if( MoverParameters->Pantographs[ end::front ].is_active ) { - // pantograph moving up - // TBD: add a sound? - } - else { - // pantograph dropping - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantDown.offset().z > 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantDown.play( sound_flags::exclusive ); - } - } - } - MoverParameters->Pantographs[ end::front ].sound_event = MoverParameters->Pantographs[ end::front ].is_active; - } - if( MoverParameters->Pantographs[ end::rear ].sound_event != MoverParameters->Pantographs[ end::rear ].is_active ) { - if( MoverParameters->Pantographs[ end::rear ].is_active ) { - // pantograph moving up - // TBD: add a sound? - } - else { - // pantograph dropping - for( auto &pantograph : m_pantographsounds ) { - if( pantograph.sPantDown.offset().z < 0 ) { - // limit to pantographs located in the front half of the vehicle - pantograph.sPantDown.play( sound_flags::exclusive ); - } - } - } - MoverParameters->Pantographs[ end::rear ].sound_event = MoverParameters->Pantographs[ end::rear ].is_active; - } - } - else if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::InternalSource) - if (MoverParameters->EnginePowerSource.PowerType == TPowerType::SteamPower) - // if (smPatykird1[0]) - { // Ra: animacja rozrządu parowozu, na razie nieoptymalizowane - /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji - pantografów - double fi,dx,c2,ka,kc; - double sin_fi,cos_fi; - double L1=1.6688888888888889; - double L2=5.6666666666666667; //2550/450 - double Lc=0.4; - double L=5.686422222; //2558.89/450 - double G1,G2,G3,ksi,sin_ksi,gam; - double G1_2,G2_2,G3_2; //kwadraty - //ruch tłoków oraz korbowodów - for (int i=0;i<=1;++i) - {//obie strony w ten sam sposób - fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)); //kąt obrotu koła dla - tłoka 1 - sin_fi=sin(fi); - cos_fi=cos(fi); - dx=panty*cos_fi+sqrt(panth*panth-panty*panty*sin_fi*sin_fi)-panth; - //nieoptymalne - if (smPatykird1[i]) //na razie zabezpieczenie - smPatykird1[i]->SetTranslate(float3(dx,0,0)); - ka=-asin(panty/panth)*sin_fi; - if (smPatykirg1[i]) //na razie zabezpieczenie - smPatykirg1[i]->SetRotateXYZ(vector3(RadToDeg(ka),0,0)); - //smPatykirg1[0]->SetRotate(float3(0,1,0),RadToDeg(fi)); //obracamy - //ruch drążka mimośrodkowego oraz jarzma - //korzystałem z pliku PDF "mm.pdf" (opis czworoboku - korbowo-wahaczowego): - //"MECHANIKA MASZYN. Szkic wykładu i laboratorium komputerowego." - //Prof. dr hab. inż. Jerzy Zajączkowski, 2007, Politechnika Łódzka - //L1 - wysokość (w pionie) osi jarzma ponad osią koła - //L2 - odległość w poziomie osi jarzma od osi koła - //Lc - długość korby mimośrodu na kole - //Lr - promień jarzma =1.0 (pozostałe przeliczone proporcjonalnie) - //L - długość drążka mimośrodowego - //fi - kąt obrotu koła - //ksi - kąt obrotu jarzma (od pionu) - //gam - odchylenie drążka mimośrodowego od poziomu - //G1=(Lr*Lr+L1*L1+L2*L2+Kc*Lc-L*L-2.0*Lc*L2*cos(fi)+2.0*Lc*L1*sin(fi))/(Lr*Lr); - //G2=2.0*(L2-Lc*cos(fi))/Lr; - //G3=2.0*(L1-Lc*sin(fi))/Lr; - fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)-96.77416667); //kąt - obrotu koła dla - tłoka 1 - //1) dla dWheelAngle[1]=0° korba jest w dół, a mimośród w stronę - jarzma, czyli - fi=-7° - //2) dla dWheelAngle[1]=90° korba jest do tyłu, a mimośród w dół, - czyli fi=83° - sin_fi=sin(fi); - cos_fi=cos(fi); - G1=(1.0+L1*L1+L2*L2+Lc*Lc-L*L-2.0*Lc*L2*cos_fi+2.0*Lc*L1*sin_fi); - G1_2=G1*G1; - G2=2.0*(L2-Lc*cos_fi); - G2_2=G2*G2; - G3=2.0*(L1-Lc*sin_fi); - G3_2=G3*G3; - sin_ksi=(G1*G2-G3*_fm_sqrt(G2_2+G3_2-G1_2))/(G2_2+G3_2); //x1 (minus - delta) - ksi=asin(sin_ksi); //kąt jarzma - if (smPatykirg2[i]) - smPatykirg2[i]->SetRotateXYZ(vector3(RadToDeg(ksi),0,0)); //obrócenie - jarzma - //1) ksi=-23°, gam= - //2) ksi=10°, gam= - //gam=acos((L2-sin_ksi-Lc*cos_fi)/L); //kąt od poziomu, liczony - względem poziomu - //gam=asin((L1-cos_ksi-Lc*sin_fi)/L); //kąt od poziomu, liczony - względem pionu - gam=atan2((L1-cos(ksi)+Lc*sin_fi),(L2-sin_ksi+Lc*cos_fi)); //kąt od - poziomu - if (smPatykird2[i]) //na razie zabezpieczenie - smPatykird2[i]->SetRotateXYZ(vector3(RadToDeg(-gam-ksi),0,0)); - //obrócenie drążka - mimośrodowego - } - */ - } - - if (MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector - && MoverParameters->EnginePowerSource.CollectorParameters.FakePower) { - MoverParameters->PantRearVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; - MoverParameters->PantFrontVolt = 0.95 * MoverParameters->EnginePowerSource.MaxVoltage; - } - - // wipers - if (dWiperPos.size() > 0) // tylko dla wozow ze zdefiniowanymi wycierakami - { - for (int i = 0; i < dWiperPos.size(); i++) // iteracja po kazdej wycieraczce - { - bool wipersActive; - auto const bytesum = MoverParameters->WiperList[MoverParameters->wiperSwitchPos].byteSum; - // rozroznienie kabinowe - if (MoverParameters->CabActive == 1) - { - wipersActive = (bytesum & 1 << i) != 0 && MoverParameters->Battery; - } - else if (MoverParameters->CabActive == -1) - { - // odwroconie indexow wycieraczek - wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && MoverParameters->Battery; - } - else { - wipersActive = false; - } - - auto const currentWiperParams = MoverParameters->WiperList[workingSwitchPos[i]]; - - wiperOutTimer[i] += dt1; // aktualizujemy zegarek - wiperParkTimer[i] += dt1; // aktualizujemy zegarek - - if (wipersActive || dWiperPos[i] > 0.0) // zeby wrocily do trybu park - { - if (dWiperPos[i] > 0.0 && !wipersActive) // bezwzgledny powrot do zera - { - dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); - } - else { - - if (dWiperPos[i] < 1.0 && !wiperDirection[i] && wiperParkTimer[i] > currentWiperParams.interval) - // go out - { - if (!sWiperFromParkPlayed) - { - sWiperFromPark.play(sound_flags::exclusive); - sWiperFromParkPlayed = true; - } - dWiperPos[i] = std::min(1.0, dWiperPos[i] + 1.f / currentWiperParams.WiperSpeed * dt1); - } - if (dWiperPos[i] > 0.0 && wiperDirection[i] && wiperOutTimer[i] > currentWiperParams.outBackDelay) - // return back - { - if (!sWiperToParkPlayed) - { - sWiperToPark.play(sound_flags::exclusive); - sWiperToParkPlayed = true; - } - dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); - } - if (dWiperPos[i] >= 1.0) // we reached end - { - sWiperFromPark.stop(); - sWiperFromParkPlayed = false; - wiperParkTimer[i] = 0.0; - wiperDirection[i] = true; // switch direction - } - if (dWiperPos[i] <= 0.0) - { - // when in park position - sWiperToPark.stop(); - sWiperToParkPlayed = false; - wiperOutTimer[i] = 0.0; - wiperDirection[i] = false; - workingSwitchPos[i] = MoverParameters->wiperSwitchPos; // update configuration - } - - } - } - } - } - - - - // mirrors - auto const mirrorleft { dMirrorMoveL }; - auto const mirrorright { dMirrorMoveR }; - if( MoverParameters->Vel > MoverParameters->MirrorVelClose - || MoverParameters->CabActive == 0 && activation::mirrors - || MoverParameters->MirrorForbidden ) { - // automatically fold mirrors when above velocity threshold - if( dMirrorMoveL > 0.0 ) { - dMirrorMoveL = std::max( - 0.0, - dMirrorMoveL - 1.0 * dt1 ); - } - if( dMirrorMoveR > 0.0 ) { - dMirrorMoveR = std::max( - 0.0, - dMirrorMoveR - 1.0 * dt1 ); - } - } - else { - // unfold mirror on the side with open doors, if not moving too fast - if( dMirrorMoveL < 1.0 - && true == MoverParameters->Doors.instances[side::left].open_permit ) { - dMirrorMoveL = std::min( - 1.0, - dMirrorMoveL + 1.0 * dt1 ); - } - if( dMirrorMoveR < 1.0 - && true == MoverParameters->Doors.instances[side::right].open_permit ) { - dMirrorMoveR = std::min( - 1.0, - dMirrorMoveR + 1.0 * dt1 ); - } - } - play_mirror_sounds( side::left, m_mirrormotion[ side::left ].update( dMirrorMoveL - mirrorleft ) ); - play_mirror_sounds( side::right, m_mirrormotion[ side::right ].update( dMirrorMoveR - mirrorright ) ); - - // compartment lights - // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself - if( ctOwner != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : - Mechanik != nullptr ? SectionLightsActive != MoverParameters->CompartmentLights.is_active : - SectionLightsActive ) { // without controller switch the lights off - toggle_lights(); - } - - if (MoverParameters->InactiveCabPantsCheck) - { - pants_up(); - MoverParameters->InactiveCabPantsCheck = false; - } - - if( MoverParameters->LoadStatus ) { - LoadUpdate(); // zmiana modelu ładunku - } - update_exchange( dt ); - - return true; // Ra: chyba tak? -} - -void TDynamicObject::pants_up() -{ - TDynamicObject *d = this; - bool isAnyPantUp = false; - while (d) { - for (auto &item : d->MoverParameters->Pantographs) - { - isAnyPantUp |= item.is_active; - } - d = d->Next(4); // pozostałe też - } - d = Prev(4); - while (d) { - for (auto &item : d->MoverParameters->Pantographs) - { - isAnyPantUp |= item.is_active; - } - d = d->Prev(4); // w drugą stronę też - } - if (isAnyPantUp) - { - d = this; - while (d) { - d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); - d = d->Next(4); // pozostałe też - } - d = Prev(4); - while (d) { - d->MoverParameters->OperatePantographValve(end::front, operation_t::enable, range_t::local); - d->MoverParameters->OperatePantographValve(end::rear, operation_t::enable, range_t::local); - d = d->Prev(4); // w drugą stronę też - } - } -} - -glm::dvec3 TDynamicObject::get_future_movement() const -{ - return m_future_movement; -} - -void TDynamicObject::move_set(double distance) -{ - TDynamicObject *d = this; - while( d ) { - d->Move( distance * d->DirectionGet() ); - d = d->Next(); // pozostałe też - } - d = Prev(); - while( d ) { - d->Move( distance * d->DirectionGet() ); - d = d->Prev(); // w drugą stronę też - } -} - -bool TDynamicObject::FastUpdate(double dt) -{ - if (dt == 0.0) - return true; // Ra: pauza - double dDOMoveLen; - if (!MoverParameters->PhysicActivation) - return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba - - if (!bEnabled) - return false; - - // NOTE: coordinate system swap - // TODO: replace with regular glm vectors - TLocation const l { - -vPosition.x, - vPosition.z, - vPosition.y }; - TRotation const r { - 0.0, - 0.0, - modelRot.z }; - // McZapkie: parametry powinny byc pobierane z toru - // ts.R=MyTrack->fRadius; - // ts.Len= std::max(MoverParameters->BDist,MoverParameters->ADist); - // ts.dHtrack=Axle1.pPosition.y-Axle0.pPosition.y; - // ts.dHrail=((Axle1.GetRoll())+(Axle0.GetRoll()))*0.5f; - // tp.Width=MyTrack->fTrackWidth; - // McZapkie-250202 - // tp.friction= MyTrack->fFriction; - // tp.CategoryFlag= MyTrack->iCategoryFlag&15; - // tp.DamageFlag=MyTrack->iDamageFlag; - // tp.QualityFlag=MyTrack->iQualityFlag; - dDOMoveLen = MoverParameters->FastComputeMovement(dt, ts, tp, l, r); // ,ts,tp,tmpTraction); - // Move(dDOMoveLen); - // ResetdMoveLen(); - FastMove(dDOMoveLen); - - if( MoverParameters->LoadStatus ) { - LoadUpdate(); // zmiana modelu ładunku - } - update_exchange( dt ); - - return true; // Ra: chyba tak? -} - -// McZapkie-040402: liczenie pozycji uwzgledniajac wysokosc szyn itp. -// vector3 TDynamicObject::GetPosition() -//{//Ra: pozycja pojazdu jest liczona zaraz po przesunięciu -// return vPosition; -//}; - -void TDynamicObject::TurnOff() -{ // wyłączenie rysowania submodeli zmiennych dla - // egemplarza pojazdu - btnOn = false; - btCoupler1.TurnOff(); - btCoupler2.TurnOff(); - btCPneumatic1.TurnOff(); - btCPneumatic1r.TurnOff(); - btCPneumatic2.TurnOff(); - btCPneumatic2r.TurnOff(); - btPneumatic1.TurnOff(); - btPneumatic1r.TurnOff(); - btPneumatic2.TurnOff(); - btPneumatic2r.TurnOff(); - btCCtrl1.Turn( false ); - btCCtrl2.Turn( false ); - btCPass1.Turn( false ); - btCPass2.Turn( false ); - m_endsignal12.Turn( false ); - m_endsignal13.Turn( false ); - m_endsignal22.Turn( false ); - m_endsignal23.Turn( false ); - m_endsignals1.Turn( false ); - m_endsignals2.Turn( false ); - m_endtab1.Turn( false ); - m_endtab2.Turn( false ); - m_headlamp11.TurnOff(); - m_headlamp12.TurnOff(); - m_headlamp13.TurnOff(); - m_headlamp21.TurnOff(); - m_headlamp22.TurnOff(); - m_headlamp23.TurnOff(); - m_highbeam12.TurnOff(); - m_highbeam13.TurnOff(); - m_highbeam22.TurnOff(); - m_highbeam23.TurnOff(); - m_headsignal12.TurnOff(); - m_headsignal13.TurnOff(); - m_headsignal22.TurnOff(); - m_headsignal23.TurnOff(); - btMechanik1.Turn( false ); - btMechanik2.Turn( false ); - btShutters1.Turn( false ); - btShutters2.Turn( false ); -}; - -// przeliczanie dźwięków, bo będzie słychać bez wyświetlania sektora z pojazdem -void TDynamicObject::RenderSounds() { - - if( false == simulation::is_ready ) { return; } - if( Global.iPause != 0 ) { return; } - - if( m_startjoltplayed - && ( std::abs(MoverParameters->AccSVBased) < 0.01 - || GetVelocity() < 0.01 ) ) { - // if the vehicle comes to a stop set the movement jolt to play when it starts moving again - m_startjoltplayed = false; - } - - auto const dt{ Timer::GetDeltaRenderTime() }; - m_powertrainsounds.render( *MoverParameters, dt ); - - auto volume{ 0.0 }; - auto frequency{ 1.0 }; - - // NBMX dzwiek przetwornicy - if( MoverParameters->ConverterFlag ) { - if( MoverParameters->EngineType == TEngineType::ElectricSeriesMotor ) { - auto const voltage { std::max( MoverParameters->GetTrainsetHighVoltage(), MoverParameters->PantographVoltage ) }; - if( voltage > 0.0 ) { - // NOTE: we do sound modulation here to avoid sudden jump on voltage loss - frequency = voltage / (MoverParameters->NominalVoltage * MoverParameters->RList[MoverParameters->RlistSize].Mn); - frequency *= sConverter.m_frequencyfactor + sConverter.m_frequencyoffset; - sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) - } - } - else { - frequency = sConverter.m_frequencyoffset + sConverter.m_frequencyfactor * frequency; - sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) - } - sConverter.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sConverter.stop(); - } - - // Odtworzenie dzwieku wentylatora rezystora hamowania - - if (MoverParameters->BRVentilators) - { - sBRVent.play(sound_flags::exclusive | sound_flags::looping); - } - else - { - sBRVent.stop(); - } - - - - - - if( MoverParameters->CompressorSpeed > 0.0 ) { - // McZapkie! - dzwiek compressor.wav tylko gdy dziala sprezarka - if( MoverParameters->CompressorFlag ) { - // for compressor coupled with the diesel engine sound pitch is driven by engine revolutions - if( MoverParameters->CompressorPower == 3 ) { - // presume the compressor sound is recorded for idle revolutions - // increase the pitch according to increase of engine revolutions - auto const enginefactor { - std::clamp( // try to keep the sound pitch in semi-reasonable range - MoverParameters->EngineMaxRPM() / MoverParameters->EngineIdleRPM() * MoverParameters->EngineRPMRatio(), - 0.5, 2.5 ) }; - sCompressor.pitch( enginefactor ); - sCompressorIdle.pitch( enginefactor ); - } - if( sCompressorIdle.empty() ) { - // legacy sound path, if there's no dedicated idle sound - sCompressor.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // enhanced sound path, with dedicated sound for idling compressor - if( MoverParameters->CompressorGovernorLock ) { - sCompressor.stop(); - sCompressorIdle.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sCompressor.play( sound_flags::exclusive | sound_flags::looping ); - sCompressorIdle.stop(); - } - } - } - else { - sCompressor.stop(); - sCompressorIdle.stop(); - } - } - - // Winger 160404 - dzwiek malej sprezarki - if( MoverParameters->PantCompFlag ) { - sSmallCompressor.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sSmallCompressor.stop(); - } - - // heater sound - { - auto const isdieselenginepowered { MoverParameters->EngineType == TEngineType::DieselElectric || MoverParameters->EngineType == TEngineType::DieselEngine }; - if( true == MoverParameters->Heating - && ( false == isdieselenginepowered - || std::abs(MoverParameters->enrot) > 0.01 ) ) { - sHeater - .pitch( true == sHeater.is_combined() ? - std::abs( MoverParameters->enrot ) * 60.f * 0.01f : - 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHeater.stop(); - } - } - - // battery sound - if( MoverParameters->Battery ) { - m_batterysound.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - m_batterysound.stop(); - } - - // brake system and braking sounds: - - // brake cylinder piston - auto const brakepressureratio { std::max( 0.0, MoverParameters->BrakePress ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; - if( m_lastbrakepressure != -1.f ) { - // HACK: potentially reset playback of opening bookend sounds - if( false == m_brakecylinderpistonadvance.is_playing() ) { - m_brakecylinderpistonadvance.stop(); - } - if( false == m_brakecylinderpistonrecede.is_playing() ) { - m_brakecylinderpistonrecede.stop(); - } - // actual sound playback - auto const quantizedratio { static_cast( 15 * brakepressureratio ) }; - auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[ 3 ] ) }; - auto const quantizedratiochange { quantizedratio - static_cast( 15 * lastbrakepressureratio ) }; - if( quantizedratiochange > 0 ) { - m_brakecylinderpistonadvance - .pitch( - true == m_brakecylinderpistonadvance.is_combined() ? - quantizedratio * 0.01f : - m_brakecylinderpistonadvance.m_frequencyoffset + m_brakecylinderpistonadvance.m_frequencyfactor * 1.f ) - .play(); - } - else if( quantizedratiochange < 0 ) { - m_brakecylinderpistonrecede - .pitch( true == m_brakecylinderpistonrecede.is_combined() ? - quantizedratio * 0.01f : - m_brakecylinderpistonrecede.m_frequencyoffset + m_brakecylinderpistonrecede.m_frequencyfactor * 1.f ) - .play(); - } - } - - // epbrake - epcompact - if (MoverParameters->BrakeSystem == TBrakeSystem::ElectroPneumatic && MoverParameters->LocHandle) { - auto const epbrakepressureratio{ std::min( std::max( 0.0, MoverParameters->LocHandle->GetCP() ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ), - m_epbrakepressurechangedectimer > -1.0f ? - std::max( MoverParameters->LocalBrakePosAEIM, MoverParameters->Hamulec->GetEDBCP() / MoverParameters->MaxBrakePress[3]) : - 1.0 ) }; - if ( m_lastepbrakepressure != -1.f ) { - // HACK: potentially reset playback of opening bookend sounds - if ( false == m_epbrakepressureincrease.is_playing() ) { - m_epbrakepressureincrease.stop(); - } - if ( false == m_epbrakepressuredecrease.is_playing() ) { - m_epbrakepressuredecrease.stop(); - } - m_epbrakepressurechangeinctimer += dt; - m_epbrakepressurechangedectimer += dt; - // actual sound playback - auto const epquantizedratio{ static_cast( 50 * epbrakepressureratio) }; - auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, MoverParameters->MaxBrakePress[0] ) }; - auto const epquantizedratiochange { epquantizedratio - static_cast( 50 * lastepbrakepressureratio ) }; - if ( epquantizedratiochange > 0 && m_epbrakepressurechangeinctimer > 0.05f) { - m_epbrakepressureincrease - .pitch( - true == m_epbrakepressureincrease.is_combined() ? - epquantizedratio * 0.01f : - m_epbrakepressureincrease.m_frequencyoffset + m_epbrakepressureincrease.m_frequencyfactor * 1.f ) - .play(); - m_epbrakepressurechangeinctimer = 0; - } - else if ( epquantizedratiochange < 0 && m_epbrakepressurechangedectimer > 0.3f) { - m_epbrakepressuredecrease - .pitch(true == m_epbrakepressuredecrease.is_combined() ? - -epquantizedratiochange * 0.01f : - m_epbrakepressuredecrease.m_frequencyoffset + m_epbrakepressuredecrease.m_frequencyfactor * 1.f ) - .play(); - m_epbrakepressurechangedectimer = 0; - } - } - if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) - m_lastepbrakepressure = std::min( MoverParameters->LocHandle->GetCP(), - MoverParameters->LocalBrakePosAEIM * std::max( 1.0, MoverParameters->MaxBrakePress[0] ) ); - } - - // emergency brake - if( MoverParameters->EmergencyValveFlow > 0.025 ) { - // smooth out air flow rate - m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? MoverParameters->EmergencyValveFlow : std::lerp(m_emergencybrakeflow, MoverParameters->EmergencyValveFlow, 0.1); - // scale volume based on the flow rate and on the pressure in the main pipe - auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * MoverParameters->PipePress, 0.0, 0.5 ) }; - m_emergencybrake - .pitch( m_emergencybrake.m_frequencyoffset + 1.0 * m_emergencybrake.m_frequencyfactor ) - .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else if( MoverParameters->EmergencyValveFlow < 0.015 ) { - m_emergencybrakeflow = 0.0; - m_emergencybrake.stop(); - } - - // air release - if( m_lastbrakepressure != -1.f ) { - // calculate rate of pressure drop in brake cylinder, once it's been initialized - auto const brakepressuredifference{ m_lastbrakepressure - MoverParameters->BrakePress }; - m_brakepressurechange = std::lerp( m_brakepressurechange, brakepressuredifference / dt, 0.05f ); - } - m_lastbrakepressure = MoverParameters->BrakePress; - // ensure some basic level of volume and scale it up depending on pressure in the cylinder; scale this by the air release rate - volume = rsUnbrake.m_amplitudefactor * m_brakepressurechange * ( 0.25 + 0.75 * brakepressureratio ); - if( m_brakepressurechange > 0.05 && brakepressureratio > 0.05 ) { - rsUnbrake - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // don't stop the sound too abruptly - volume = std::max( 0.0, rsUnbrake.gain() - 0.5 * dt ); - rsUnbrake.gain( volume ); - if( volume < 0.05 ) { - rsUnbrake.stop(); - } - } - - // Dzwiek odluzniacza - if( MoverParameters->Hamulec->Releaser() ) { - sReleaser - .gain( - std::clamp( - MoverParameters->BrakePress * 1.25, // arbitrary multiplier - 0., 1. ) ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sReleaser.stop(); - } - - // slipping wheels - if( MoverParameters->SlippingWheels ) { - - if( MoverParameters->UnitBrakeForce > 100.0 - && GetVelocity() > 1.0 ) { - - auto const velocitydifference{ GetVelocity() / MoverParameters->Vmax }; - rsSlippery - .gain( rsSlippery.m_amplitudeoffset + rsSlippery.m_amplitudefactor * velocitydifference ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - rsSlippery.stop(); - } - - // Dzwiek piasecznicy - if( MoverParameters->SandDose ) { - sSand.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sSand.stop(); - } - - // brakes - auto brakeforceratio{ 0.0 }; - if( //( false == mvOccupied->SlippingWheels ) && - MoverParameters->UnitBrakeForce > 10.0 - && MoverParameters->Vel > 0.05 ) { - - brakeforceratio = - std::clamp( - MoverParameters->UnitBrakeForce / std::max( 1.0, MoverParameters->BrakeForceR( 1.0, MoverParameters->Vel ) / ( MoverParameters->NAxles * std::max( 1, MoverParameters->NBpA ) ) ), - 0.0, 1.0 ); - rsBrake - .pitch( rsBrake.m_frequencyoffset + MoverParameters->Vel * rsBrake.m_frequencyfactor ) - .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, MoverParameters->Vel / (1 + MoverParameters->Vmax) ) ) * rsBrake.m_amplitudefactor ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - rsBrake.stop(); - } - - // yB: przyspieszacz (moze zadziala, ale dzwiek juz jest) - if( true == bBrakeAcc ) { - if( true == TestFlag( MoverParameters->Hamulec->GetSoundFlag(), sf_Acc ) ) { - sBrakeAcc.play( sound_flags::exclusive ); - } - } - - // McZapkie-280302 - pisk mocno zacisnietych hamulcow - if( MoverParameters->Vel > 2.5 ) { - - volume = rsPisk.m_amplitudeoffset + std::lerp( -1.0, 1.0, brakeforceratio ) * rsPisk.m_amplitudefactor; - if( volume > 0.075 ) { - rsPisk - .pitch( - true == rsPisk.is_combined() ? - MoverParameters->Vel * 0.01f : - rsPisk.m_frequencyoffset + rsPisk.m_frequencyfactor * 1.f ) - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - // don't stop the sound too abruptly - volume = std::max( 0.0, rsPisk.gain() - rsPisk.gain() * 2.5 * dt ); - rsPisk.gain( volume ); - } - if( volume < 0.05 ) { - rsPisk.stop(); - } - - // spring brake - if( m_springbrakesounds.state != MoverParameters->SpringBrake.Activate ) { - m_springbrakesounds.state = MoverParameters->SpringBrake.Activate; - if( m_springbrakesounds.state ) { - m_springbrakesounds.activate.play( sound_flags::exclusive ); - m_springbrakesounds.release.stop(); - } - else { - m_springbrakesounds.activate.stop(); - m_springbrakesounds.release.play( sound_flags::exclusive ); - } - } - - // other sounds - // load exchange - if( MoverParameters->LoadStatus & 1 ) { - m_exchangesounds.unloading.play( sound_flags::exclusive ); - } - else { - m_exchangesounds.unloading.stop(); - } - if( MoverParameters->LoadStatus & 2 ) { - m_exchangesounds.loading.play( sound_flags::exclusive ); - } - else { - m_exchangesounds.loading.stop(); - } - // NBMX sygnal odjazdu - if( MoverParameters->Doors.has_warning ) { - auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; - for( auto &doorspeaker : m_doorspeakers ) { - // TBD, TODO: per-location door state triggers? - if( MoverParameters->DepartureSignal - && lowvoltagepower -/* - || ( ( MoverParameters->DoorCloseCtrl = control::autonomous ) - && ( ( ( false == MoverParameters->DoorLeftOpened ) && ( dDoorMoveL > 0.0 ) ) - || ( ( false == MoverParameters->DoorRightOpened ) && ( dDoorMoveR > 0.0 ) ) ) ) -*/ - ) { - // for the autonomous doors play the warning automatically whenever a door is closing - // MC: pod warunkiem ze jest zdefiniowane w chk - doorspeaker.departure_signal.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - doorspeaker.departure_signal.stop(); - } - } - } - // announcements - { - auto const lowvoltagepower { MoverParameters->Power24vIsAvailable || MoverParameters->Power110vIsAvailable }; - if( lowvoltagepower ) { - // system is powered up, can play queued announcements - if( false == m_pasystem.announcement_queue.empty() - && false == m_pasystem.announcement.is_playing() ) { - // pull first sound from the queue - m_pasystem.announcement = m_pasystem.announcement_queue.front(); - m_pasystem.announcement.owner( this ); - m_pasystem.announcement.range( 0.5 * MoverParameters->Dim.L * -1 ); - if( m_pasystem.soundproofing ) { - if( !m_pasystem.announcement.soundproofing() ) { - m_pasystem.announcement.soundproofing() = m_pasystem.soundproofing; - } - } - m_pasystem.announcement.play(); - m_pasystem.announcement_queue.pop_front(); - } - } - else { - m_pasystem.announcement.stop(); - m_pasystem.announcement_queue.clear(); - } - } - // NBMX Obsluga drzwi, MC: zuniwersalnione - std::array const sides { side::right, side::left }; - for( auto const side : sides ) { - - auto const &door { MoverParameters->Doors.instances[ side ] }; - - if( true == door.is_opening ) { - // door sounds - if( false == door.step_unfolding // no wait if no doorstep - || MoverParameters->Doors.step_type == 2 ) { // no wait for rotating doorstep - if( door.position < 0.5f ) { // safety measure, to keep slightly too short sounds from repeating - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - // determine left side doors from their offset - doorsounds.rsDoorOpen.play( sound_flags::exclusive ); - doorsounds.rsDoorClose.stop(); - } - } - } - } - } - if( true == door.is_closing ) { - // door sounds can start playing before the door begins moving but shouldn't cease once the door closes - if( door.position > 0.f ) { - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - // determine left side doors from their offset - doorsounds.rsDoorClose.play( sound_flags::exclusive ); - doorsounds.rsDoorOpen.stop(); - } - } - } - } - // doorstep sounds - if( door.step_unfolding ) { - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - doorsounds.step_open.play( sound_flags::exclusive ); - doorsounds.step_close.stop(); - } - } - } - if( door.step_folding ) { - if( door.step_position < 1.0f ) { // sanity check, the vehicles may keep the doorstep unfolded until the door close - for( auto &doorsounds : m_doorsounds ) { - if( doorsounds.placement == side ) { - // determine left side doors from their offset - doorsounds.step_close.play( sound_flags::exclusive ); - doorsounds.step_open.stop(); - } - } - } - } - } - // door locks - if( MoverParameters->Doors.is_locked != m_doorlocks ) { - // toggle state of the locks... - m_doorlocks = !m_doorlocks; - // ...and play relevant sounds - for( auto &door : m_doorsounds ) { - if( m_doorlocks ) { - door.lock.play( sound_flags::exclusive ); - } - else { - door.unlock.play( sound_flags::exclusive ); - } - } - } - - // horns - { - // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active; - // the horns without the air or the voltage they need stay silent - auto const warningsignal { MoverParameters->SoundingHorns( - ( MoverParameters->Vel > 0.5 && MoverParameters->AlarmChainFlag ? - MoverParameters->EmergencyBrakeWarningSignal : - 0 ) - | MoverParameters->WarningSignal ) }; - - if( TestFlag( warningsignal, 1 ) ) { - sHorn1.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHorn1.stop(); - } - if( TestFlag( warningsignal, 2 ) ) { - sHorn2.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHorn2.stop(); - } - if( TestFlag( warningsignal, 4 ) ) { - sHorn3.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - sHorn3.stop(); - } - } - // szum w czasie jazdy - if( GetVelocity() > 0.5 -#ifdef EU07_SOUND_BOGIESOUNDS - && false == m_bogiesounds.empty() -#endif - && ( // compound test whether the vehicle belongs to user-driven consist (as these don't emit outer noise in cab view) - FreeFlyModeFlag ? true : // in external view all vehicles emit outer noise - simulation::Train == nullptr ? true : // no player train, e.g. it went through a portal and the view isn't switched yet - ctOwner == nullptr ? true : // standalone vehicle, can't be part of user-driven train - ctOwner != simulation::Train->Dynamic()->ctOwner ? true : // confirmed isn't a part of the user-driven train - Global.CabWindowOpen ? true : // sticking head out we get to hear outer noise - false ) ) { -#ifdef EU07_SOUND_BOGIESOUNDS - auto const &bogiesound { m_bogiesounds.front() }; -#else - auto const &bogiesound { m_outernoise }; -#endif - // frequency calculation - auto const normalizer { ( - true == bogiesound.is_combined() ? - MoverParameters->Vmax * 0.01f : - 1.f ) }; - frequency = - bogiesound.m_frequencyoffset - + bogiesound.m_frequencyfactor * MoverParameters->Vel * normalizer; - - // volume calculation - volume = - bogiesound.m_amplitudeoffset - + bogiesound.m_amplitudefactor * MoverParameters->Vel; - if( brakeforceratio > 0.0 ) { - // hamulce wzmagaja halas - volume *= 1 + 0.125 * brakeforceratio; - } - // scale volume by track quality - // TODO: track quality and/or environment factors as separate subroutine - volume *= - std::lerp( - 0.8, 1.2, - std::clamp( - MyTrack->iQualityFlag / 20.0, - 0.0, 1.0 ) ); - // for single sample sounds muffle the playback at low speeds - if( false == bogiesound.is_combined() ) { - volume *= - std::lerp( - 0.0, 1.0, - std::clamp( - MoverParameters->Vel / 40.0, - 0.0, 1.0 ) ); - } - switch( MyTrack->eEnvironment ) { - case e_tunnel: { - volume *= 1.3; - break; - } - case e_bridge: { - volume *= 1.5; - break; - } - default: { - break; - } - } - - if( volume > 0.05 ) { - // apply calculated parameters to all motor instances -#ifdef EU07_SOUND_BOGIESOUNDS - for( auto &bogiesound : m_bogiesounds ) { - bogiesound - .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } -#else - m_outernoise - .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); -#endif - } - else { - // stop all noise instances -#ifdef EU07_SOUND_BOGIESOUNDS - for( auto &bogiesound : m_bogiesounds ) { - bogiesound.stop(); - } -#else - m_outernoise.stop(); -#endif - } - } - else { - // don't play the optional ending sound if the listener switches views -#ifdef EU07_SOUND_BOGIESOUNDS - for( auto &bogiesound : m_bogiesounds ) { - bogiesound.stop( false == FreeFlyModeFlag ); - } -#else - m_outernoise.stop( false == FreeFlyModeFlag ); -#endif - } - // flat spot sound - if( MoverParameters->CategoryFlag == 1 ) { - // trains only - if( GetVelocity() > 1.0 - && MoverParameters->WheelFlat > 5.0 ) { - m_wheelflat - .pitch( m_wheelflat.m_frequencyoffset + std::abs( MoverParameters->nrot ) * m_wheelflat.m_frequencyfactor ) - .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + MoverParameters->Vel / MoverParameters->Vmax + std::clamp( MoverParameters->WheelFlat / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - m_wheelflat.stop(); - } - } - - // youBy: dzwiek ostrych lukow i ciasnych zwrotek - if( MoverParameters->Vel > 5.0 - && ts.R * ts.R > 1.0 - && std::abs(ts.R) < 15000.0 ) { - // scale volume with curve radius and vehicle speed - volume = - std::abs( MoverParameters->AccN ) // * MoverParameters->AccN - * std::lerp( - 0.5, 1.0, - std::clamp( - MoverParameters->Vel / 40.0, - 0.0, 1.0 ) ) - * ( MyTrack->eType == tt_Switch && std::abs(ts.R) < 1500.0 ? 100.0 : 1.0 ); - } - else { - volume = 0; - } - if( volume > 0.05 ) { - rscurve - .pitch( - true == rscurve.is_combined() ? - MoverParameters->Vel * 0.01f : - rscurve.m_frequencyoffset + rscurve.m_frequencyfactor * 1.f ) - .gain( 2.5 * volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - rscurve.stop(); - } - - // movement start jolt - if( false == m_startjoltplayed ) { - auto const velocity { GetVelocity() }; - if( ( MoverParameters->V > 0.0 ? MoverParameters->AccSVBased > 0.1 : MoverParameters->AccSVBased < 0.1 ) - && velocity > 1.0 - && velocity < 15.0 ) { - m_startjolt.play( sound_flags::exclusive ); - m_startjoltplayed = true; - } - } - - // McZapkie! - to wazne - SoundFlag wystawiane jest przez moje moduly gdy zachodza pewne wydarzenia komentowane dzwiekiem. - // pneumatic relay - if( TestFlag( MoverParameters->SoundFlag, sound::pneumatic ) ) { - dsbPneumaticRelay - .gain( - true == TestFlag( MoverParameters->SoundFlag, sound::loud ) ? - 1.0f : - 0.8f ) - .play(); - } - // door permit - if( TestFlag( MoverParameters->SoundFlag, sound::doorpermit ) ) { - // NOTE: current implementation doesn't discern between permit for left/right side, - // which may be undesired in weird setups with doors only on one side - // TBD, TODO: rework into dedicated sound event flag for each door location instance? - for( auto &door : m_doorsounds ) { - door.permit_granted.play( sound_flags::exclusive ); - } - } - - // couplers - int couplerindex { 0 }; - for( auto &couplersounds : m_couplersounds ) { - - auto &coupler { MoverParameters->Couplers[ couplerindex ] }; - - if( coupler.sounds == sound::none ) { - ++couplerindex; - continue; - } - - if( true == TestFlag( coupler.sounds, sound::bufferclash ) ) { - // zderzaki uderzaja o siebie - if( true == TestFlag( coupler.sounds, sound::loud ) ) { - // loud clash - if( false == couplersounds.dsbBufferClamp_loud.empty() ) { - // dedicated sound for loud clash - couplersounds.dsbBufferClamp_loud - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - else { - // fallback on the standard sound - couplersounds.dsbBufferClamp - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - else { - // basic clash - couplersounds.dsbBufferClamp - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - - if( true == TestFlag( coupler.sounds, sound::couplerstretch ) ) { - // sprzegi sie rozciagaja - if( true == TestFlag( coupler.sounds, sound::loud ) ) { - // loud stretch - if( false == couplersounds.dsbCouplerStretch_loud.empty() ) { - // dedicated sound for loud stretch - couplersounds.dsbCouplerStretch_loud - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - else { - // fallback on the standard sound - couplersounds.dsbCouplerStretch - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - else { - // basic clash - couplersounds.dsbCouplerStretch - .gain( 1.f ) - .play( sound_flags::exclusive ); - } - } - // attach/detach sounds - if( ( coupler.sounds & sound::detach ) == 0 ) { - // potentially added some couplings - if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { - couplersounds.attach_coupler.play(); - } - if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { - couplersounds.attach_brakehose.play(); - } - if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { - couplersounds.attach_mainhose.play(); - } - if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { - couplersounds.attach_control.play(); - } - if( ( coupler.sounds & sound::attachgangway ) != 0 ) { - couplersounds.attach_gangway.play(); - } - if( ( coupler.sounds & sound::attachheating ) != 0 ) { - couplersounds.attach_heating.play(); - } - } - else { - // potentially removed some couplings - if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { - couplersounds.detach_coupler.play(); - } - if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { - couplersounds.detach_brakehose.play(); - } - if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { - couplersounds.detach_mainhose.play(); - } - if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { - couplersounds.detach_control.play(); - } - if( ( coupler.sounds & sound::attachgangway ) != 0 ) { - couplersounds.detach_gangway.play(); - } - if( ( coupler.sounds & sound::attachheating ) != 0 ) { - couplersounds.detach_heating.play(); - } - } - if( true == TestFlag( coupler.sounds, sound::attachadapter ) ) { - couplersounds.dsbAdapterAttach.play(); - } - if( true == TestFlag( coupler.sounds, sound::removeadapter ) ) { - couplersounds.dsbAdapterRemove.play(); - } - - ++couplerindex; - coupler.sounds = 0; - } - - MoverParameters->SoundFlag = 0; - // McZapkie! - koniec obslugi dzwiekow z mover.pas - -// special events - if( MoverParameters->EventFlag ) { - // McZapkie: w razie wykolejenia - if( true == TestFlag( MoverParameters->DamageFlag, dtrain_out ) ) { - rsDerailment.play( sound_flags::exclusive ); - } - - MoverParameters->EventFlag = false; - } -} - -// calculates distance between event-starting axle and front of the vehicle -double -TDynamicObject::tracing_offset() const { - - auto const axletoend{ ( GetLength() - fAxleDist ) * 0.5 }; - return iAxleFirst ? axletoend : axletoend + iDirection * fAxleDist; -} - -// TODO: compute and cache radius during vehicle initialization -double -TDynamicObject::radius() const { - - glm::vec3 diagonal( - static_cast( MoverParameters->Dim.L ), - static_cast( MoverParameters->Dim.H ), - static_cast( MoverParameters->Dim.W ) ); - return glm::length( diagonal ) * 0.5f; -} - -// McZapkie-250202 -// wczytywanie pliku z danymi multimedialnymi (dzwieki) -void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string const &ReplacableSkin ) { - rTypeName = TypeName; - rReplacableSkin = ReplacableSkin; - Global.asCurrentDynamicPath = asBaseDir; - std::string asFileName = asBaseDir + TypeName + ".mmd"; - std::string asAnimName; - bool Stop_InternalData = false; - pants = nullptr; // wskaźnik pierwszego obiektu animującego dla pantografów - wipers = nullptr; // wskaznik pierwszego obiektu animujacego dla wycieraczek - { - // preliminary check whether the file exists - cParser parser( TypeName + ".mmd", cParser::buffer_FILE, asBaseDir ); - if( false == parser.ok() ) { - ErrorLog( "Failed to load appearance data for vehicle " + MoverParameters->Name ); - return; - } - } - // use #include wrapper to access the appearance data file - // this allows us to provide the file content with user-defined parameters - cParser parser( - "include " + TypeName + ".mmd" - + " " + asName // (p1) - + " " + TypeName // (p2) - + " " + ReplacableSkin // (p3) - + " end", - cParser::buffer_TEXT, - asBaseDir, true, std::vector(), true ); - std::string token; - do { - token = ""; - parser.getTokens(); parser >> token; - - if( token == "models:" ) { - // modele i podmodele - m_materialdata.multi_textures = 0; // czy jest wiele tekstur wymiennych? - parser.getTokens(); - parser >> asModel; - replace_slashes( asModel ); - if( asModel.back() == '#' ) // Ra 2015-01: nie podoba mi siê to - { // model wymaga wielu tekstur wymiennych - m_materialdata.multi_textures = 1; - asModel.erase( asModel.length() - 1 ); - } - // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory - erase_leading_slashes( asModel ); - /* - // never really used, may as well get rid of it - std::size_t i = asModel.find( ',' ); - if ( i != std::string::npos ) - { // Ra 2015-01: może szukać przecinka w nazwie modelu, a po przecinku była by liczba tekstur? - if( i < asModel.length() ) { - m_materialdata.multi_textures = asModel[ i + 1 ] - '0'; - } - m_materialdata.multi_textures = std::clamp( m_materialdata.multi_textures, 0, 1 ); // na razie ustawiamy na 1 - } - */ - asModel = asBaseDir + asModel; // McZapkie 2002-07-20: dynamics maja swoje modele w dynamics/basedir - Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... - mdModel = TModelsManager::GetModel(asModel, true); - if (ReplacableSkin != "none") { - m_materialdata.assign( ReplacableSkin ); - } - Global.asCurrentTexturePath = paths::textures; // z powrotem defaultowa sciezka do tekstur - do { - token = ""; - parser.getTokens(); parser >> token; - - if( token == "animations:" ) { - // Ra: ustawienie ilości poszczególnych animacji - musi być jako pierwsze, inaczej ilości będą domyślne -/* - if( nullptr == pAnimations ) -*/ - if( true == pAnimations.empty() ) - { // jeśli nie ma jeszcze tabeli animacji, można odczytać nowe ilości - int co = 0; - iAnimations = 0; - int ile; - do - { // kolejne liczby to ilość animacj, -1 to znacznik końca - ile = -1; - parser.getTokens( 1, false ); - parser >> ile; // ilość danego typu animacji - if (ile >= 0) - { - iAnimType[co] = ile; // zapamiętanie - iAnimations += ile; // ogólna ilość animacji - } - else { - iAnimType[co] = 0; - } - ++co; - } while ( ile >= 0 && co < ANIM_TYPES ); //-1 to znacznik końca - - pAnimations.resize( iAnimations ); - int i, j, k = 0, sm = 0; - for (j = 0; j < ANIM_TYPES; ++j) // petla po wszystkich wpisach w animations - for (i = 0; i < iAnimType[j]; ++i) // petla iteruje sie tyle razy ile mamy wpisane w animations - { - if (j == ANIM_PANTS) // zliczamy poprzednie animacje - if (!pants) - if (iAnimType[ANIM_PANTS]) // o ile jakieś pantografy są (a domyślnie są) - pants = &pAnimations[k]; // zapamiętanie na potrzeby wyszukania submodeli - if (j == ANIM_WIPERS) - if (!wipers) - if (iAnimType[ANIM_WIPERS]) - wipers = &pAnimations[k]; - pAnimations[k].iShift = sm; // przesunięcie do przydzielenia wskaźnika - sm += pAnimations[k++].TypeSet(j, *MoverParameters); // ustawienie typu animacji i zliczanie tablicowanych submodeli - } - if (sm) // o ile są bardziej złożone animacje - { - pAnimated = new TSubModel *[sm]; // tabela na animowane submodele - for (k = 0; k < iAnimations; ++k) - pAnimations[k].smElement = pAnimated + pAnimations[k].iShift; // przydzielenie wskaźnika do tabelki - } - } - } - - else if(token == "lowpolyinterior:") { - // ABu: wnetrze lowpoly - parser.getTokens(); - parser >> asModel; - - replace_slashes( asModel ); - erase_leading_slashes( asModel ); - asModel = asBaseDir + asModel; // McZapkie-200702 - dynamics maja swoje modele w dynamic/basedir - Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... - mdLowPolyInt = TModelsManager::GetModel(asModel, true); - } - - else if(token == "coupleradapter:") { - // coupling adapter data - parser.getTokens( 3 ); - parser - >> m_coupleradapter.model - >> m_coupleradapter.position.x - >> m_coupleradapter.position.y; - replace_slashes( m_coupleradapter.model ); - erase_leading_slashes( m_coupleradapter.model ); - } - - else if(token == "attachments:") { - // additional 3d models attached to main body - // content provided as a series of values together enclosed in "{}" - // each value is a name of additional 3d model - // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly - // TBD: reconsider something more yaml-compliant and/or ability to define offset and rotation - while( (token = deserialize_random_set(parser)) != "" - && token != "}" ) { - if( token == "{" ) { continue; } - replace_slashes( token ); - Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... - auto *attachmentmodel { TModelsManager::GetModel( asBaseDir + token, true ) }; - if( attachmentmodel != nullptr ) { - mdAttachments.emplace_back( attachmentmodel ); - } - } - } - - else if(token == "loads:") { - // default load visualization models overrides - // content provided as "key: value" pairs together enclosed in "{}" - // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly - while( (token = parser.getToken()) != "" - && token != "}" ) { - if( token.back() == ':' ) { - auto loadmodel { deserialize_random_set( parser ) }; - replace_slashes( loadmodel ); - LoadModelOverrides.emplace( token.erase( token.size() - 1 ), loadmodel ); - } - } - } - - else if( token == "brakemode:" ) { - // Ra 15-01: gałka nastawy hamulca - parser.getTokens(); - parser >> asAnimName; - smBrakeMode = GetSubmodelFromName( mdModel, asAnimName ); - // jeszcze wczytać kąty obrotu dla poszczególnych ustawień - } - - else if( token == "loadmode:" ) { - // Ra 15-01: gałka nastawy hamulca - parser.getTokens(); - parser >> asAnimName; - smLoadMode = GetSubmodelFromName( mdModel, asAnimName ); - // jeszcze wczytać kąty obrotu dla poszczególnych ustawień - } - - else if (token == "animwheelprefix:") { - // prefiks kręcących się kół - int i, k, m; - unsigned int j; - parser.getTokens( 1, false ); parser >> token; - for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // liczba osi - { // McZapkie-050402: wyszukiwanie kol o nazwie str* - asAnimName = token + std::to_string(i + 1); - pAnimations[i].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if (pAnimations[i].smAnimated) - { //++iAnimatedAxles; - pAnimations[i].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - pAnimations[i].yUpdate = std::bind( &TDynamicObject::UpdateAxle, this, std::placeholders::_1 ); - pAnimations[i].fMaxDist = Global.fDistanceFactor * MoverParameters->WheelDiameter * 200; - pAnimations[i].fMaxDist *= pAnimations[i].fMaxDist; - } - } - // Ra: ustawianie indeksów osi - for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // ilość osi (zabezpieczenie przed błędami w CHK) - pAnimations[i].dWheelAngle = 1; // domyślnie wskaźnik na napędzające - i = 0; - j = 1; - k = 0; - m = 0; // numer osi; kolejny znak; ile osi danego typu; która średnica - if (MoverParameters->WheelDiameterL != MoverParameters->WheelDiameter || - MoverParameters->WheelDiameterT != MoverParameters->WheelDiameter) - { // obsługa różnych średnic, o ile występują - while (i < iAnimType[ANIM_WHEELS] && - j <= MoverParameters->AxleArangement.length()) - { // wersja ze wskaźnikami jest bardziej elastyczna na nietypowe układy - if (k >= 'A' && k <= 'J') // 10 chyba maksimum? - { - pAnimations[i++].dWheelAngle = 1; // obrót osi napędzających - --k; // następna będzie albo taka sama, albo bierzemy kolejny znak - m = 2; // następujące toczne będą miały inną średnicę - } - else if (k >= '1' && k <= '9') - { - pAnimations[i++].dWheelAngle = m; // obrót osi tocznych - --k; // następna będzie albo taka sama, albo bierzemy kolejny znak - } - else - k = MoverParameters->AxleArangement[j++]; // pobranie kolejnego znaku - } - } - } - // else if (str==AnsiString("animrodprefix:")) //prefiks wiazarow dwoch - // { - // str= Parser->GetNextSymbol(); - // for (int i=1; i<=2; i++) - // {//McZapkie-050402: wyszukiwanie max 2 wiazarow o nazwie str* - // asAnimName=str+i; - // smWiazary[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smWiazary[i-1]->WillBeAnimated(); - // } - // } - - else if( token == "animpantprefix:" ) { - // Ra: pantografy po nowemu mają literki i numerki - } - // Pantografy - Winger 160204 - else if( token == "animpantrd1prefix:" ) { - // prefiks ramion dolnych 1 - parser.getTokens(); parser >> token; - float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu - TSubModel *sm; - if (pants) - for (int i = 0; i < iAnimType[ANIM_PANTS]; i++) - { // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string(i + 1); - sm = GetSubmodelFromName( mdModel, asAnimName ); - pants[i].smElement[0] = sm; // jak NULL, to nie będzie animowany - if (sm) - { // w EP09 wywalało się tu z powodu NULL - sm->WillBeAnimated(); - sm->ParentMatrix(&m); // pobranie macierzy transformacji - // m(3)[1]=m[3][1]+0.054; //w górę o wysokość ślizgu (na razie tak) - pants[i].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) - pants[i].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu - if ((sm = pants[i].smElement[0]->ChildGet()) != nullptr) - { // jeśli ma potomny, można policzyć długość (odległość potomnego od osi obrotu) - m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, nie trzeba kopiować - // może trzeba: pobrać macierz dolnego ramienia, wyzerować przesunięcie, przemnożyć przez macierz górnego - pants[i].fParamPants->fHoriz = -fabs(m[3][1]); - pants[i].fParamPants->fLenL1 = hypot(m[3][1], m[3][2]); // po osi OX nie potrzeba - pants[i].fParamPants->fAngleL0 = atan2(fabs(m[3][2]), fabs(m[3][1])); - // if (pants[i].fParamPants->fAngleL0fAngleL0+=M_PI; //gdyby w odwrotną stronę wyszło - // if - // ((pants[i].fParamPants->fAngleL0<0.03)||(pants[i].fParamPants->fAngleL0>0.09)) - // //normalnie ok. 0.05 - // pants[i].fParamPants->fAngleL0=pants[i].fParamPants->fAngleL; - pants[i].fParamPants->fAngleL = pants[i].fParamPants->fAngleL0; // początkowy kąt dolnego ramienia - if ((sm = sm->ChildGet()) != nullptr) - { // jeśli dalej jest ślizg, można policzyć długość górnego ramienia - m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, - // nie trzeba kopiować trzeba by uwzględnić macierz dolnego ramienia, żeby uzyskać kąt do poziomu... - pants[i].fParamPants->fHoriz += fabs(m(3)[1]); // różnica długości rzutów ramion na - // płaszczyznę podstawy (jedna dodatnia, druga ujemna) - pants[i].fParamPants->fLenU1 = hypot( m[3][1], m[3][2] ); // po osi OX nie potrzeba - // pants[i].fParamPants->pantu=acos((1.22*cos(pants[i].fParamPants->fAngleL)+0.535)/1.755); //górne ramię - // pants[i].fParamPants->fAngleU0=acos((1.176289*cos(pants[i].fParamPants->fAngleL)+0.54555075)/1.724482197); //górne ramię - pants[i].fParamPants->fAngleU0 = atan2( fabs(m[3][2]), fabs(m[3][1]) ); // początkowy kąt górnego ramienia, odczytany z modelu - // if (pants[i].fParamPants->fAngleU0fAngleU0+=M_PI; //gdyby w odwrotną stronę wyszło - // if (pants[i].fParamPants->fAngleU0<0) - // pants[i].fParamPants->fAngleU0=-pants[i].fParamPants->fAngleU0; - // if - // ((pants[i].fParamPants->fAngleU0<0.00)||(pants[i].fParamPants->fAngleU0>0.09)) //normalnie ok. 0.07 - // pants[i].fParamPants->fAngleU0=acos((pants[i].fParamPants->fLenL1*cos(pants[i].fParamPants->fAngleL)+pants[i].fParamPants->fHoriz)/pants[i].fParamPants->fLenU1); - pants[i].fParamPants->fAngleU = pants[i].fParamPants->fAngleU0; // początkowy kąt - // Ra: ze względu na to, że niektóre modele pantografów są zrąbane, ich mierzenie ma obecnie ograniczony sens - sm->ParentMatrix(&m); // pobranie macierzy transformacji pivota ślizgu względem wstawienia pojazdu - float det = Det(m); - if (std::fabs(det - 1.0) < 0.001) // dopuszczamy 1 promil błędu na skalowaniu ślizgu - { // skalowanie jest w normie, można pobrać wymiary z modelu - pants[i].fParamPants->fHeight = sm->MaxY(m); // przeliczenie maksimum wysokości wierzchołków względem macierzy - pants[i].fParamPants->fHeight -= m[3][1]; // odjęcie wysokości pivota ślizgu - pants[i].fParamPants->vPos.x = m[3][2]; // przy okazji odczytać z modelu pozycję w długości - // ErrorLog("Model OK: "+asModel+", - // height="+pants[i].fParamPants->fHeight); - // ErrorLog("Model OK: "+asModel+", - // pos.x="+pants[i].fParamPants->vPos.x); - } - else - { // gdy ktoś przesadził ze skalowaniem - pants[i].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: - ErrorLog( - "Bad model: " + asModel + ", scale of " + sm->pName + " is " + std::to_string(100.0 * det) + "%", - logtype::model ); - } - } - } - } - else { - // brak ramienia - pants[ i ].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); - } - } - } - - else if( token == "animpantrd2prefix:" ) { - // prefiks ramion dolnych 2 - parser.getTokens(); parser >> token; - float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu - TSubModel *sm; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - sm = GetSubmodelFromName( mdModel, asAnimName ); - pants[ i ].smElement[ 1 ] = sm; // jak NULL, to nie będzie animowany - if( sm ) { // w EP09 wywalało się tu z powodu NULL - sm->WillBeAnimated(); - if( pants[ i ].fParamPants->vPos.y == 0.0 ) { - // jeśli pierwsze ramię nie ustawiło tej wartości, próbować drugim - //!!!! docelowo zrobić niezależną animację ramion z każdej strony - m = float4x4( - *sm->GetMatrix()); // skopiowanie, bo będziemy mnożyć - m( 3 )[ 1 ] = - m[ 3 ][ 1 ] + 0.054; // w górę o wysokość ślizgu (na razie tak) - while( sm->Parent ) { - if( sm->Parent->GetMatrix() ) - m = *sm->Parent->GetMatrix() * m; - sm = sm->Parent; - } - pants[ i ].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) - pants[ i ].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu - } - } - else - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - - else if( token == "animpantrg1prefix:" ) { - // prefiks ramion górnych 1 - parser.getTokens(); parser >> token; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - pants[ i ].smElement[ 2 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( pants[ i ].smElement[ 2 ] ) { - pants[ i ].smElement[ 2 ]->WillBeAnimated(); - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - } - - else if( token == "animpantrg2prefix:" ) { - // prefiks ramion górnych 2 - parser.getTokens(); parser >> token; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - pants[ i ].smElement[ 3 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( pants[ i ].smElement[ 3 ] ) { - pants[ i ].smElement[ 3 ]->WillBeAnimated(); - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - } - - else if( token == "animpantslprefix:" ) { - // prefiks ślizgaczy - parser.getTokens(); parser >> token; - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { - // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* - asAnimName = token + std::to_string( i + 1 ); - pants[ i ].smElement[ 4 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( pants[ i ].smElement[ 4 ] ) { - pants[ i ].smElement[ 4 ]->WillBeAnimated(); - pants[ i ].yUpdate = std::bind( &TDynamicObject::UpdatePant, this, std::placeholders::_1 ); - pants[ i ].fMaxDist = 300 * 300; // nie podnosić w większej odległości - pants[ i ].iNumber = i; - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia - } - } - } - } - - else if( token == "pantfactors:" ) { - // Winger 010304: - // parametry pantografow - double pant1x, pant2x, pant1h, pant2h; - parser.getTokens( 4, false ); - parser - >> pant1x - >> pant2x - >> pant1h // wysokość pierwszego ślizgu - >> pant2h;// wysokość drugiego ślizgu - if( pant1h > 0.5 ) { - pant1h = pant2h; // tu może być zbyt duża wartość - } - if (pant1x < 0 && - pant2x > 0) // pierwsza powinna być dodatnia, a druga ujemna - { - pant1x = -pant1x; - pant2x = -pant2x; - } - if( pants ) { - for( int i = 0; i < iAnimType[ ANIM_PANTS ]; ++i ) { - // przepisanie współczynników do pantografów (na razie nie będzie lepiej) - auto &pantograph { *pants[i].fParamPants }; - - pantograph.fAngleL = pantograph.fAngleL0; // początkowy kąt dolnego ramienia - pantograph.fAngleU = pantograph.fAngleU0; // początkowy kąt - // pants[i].fParamPants->PantWys=1.22*sin(pants[i].fParamPants->fAngleL)+1.755*sin(pants[i].fParamPants->fAngleU); - // //wysokość początkowa - // pants[i].fParamPants->PantWys=1.176289*sin(pants[i].fParamPants->fAngleL)+1.724482197*sin(pants[i].fParamPants->fAngleU); - // //wysokość początkowa - if( pantograph.fHeight == 0.0 ) // gdy jest nieprawdopodobna wartość (np. nie znaleziony ślizg) - { // gdy pomiary modelu nie udały się, odczyt podanych parametrów z MMD - pantograph.vPos.x = - i & 1 ? - pant2x : - pant1x; - pantograph.fHeight = - i & 1 ? - pant2h : - pant1h; // wysokość ślizgu jest zapisana w MMD - } - pantograph.PantWys = - pantograph.fLenL1 * sin( pantograph.fAngleL ) + - pantograph.fLenU1 * sin( pantograph.fAngleU ) + - pantograph.fHeight; // wysokość początkowa - // pants[i].fParamPants->vPos.y=panty-panth-pants[i].fParamPants->PantWys; //np. 4.429-0.097=4.332=~4.335 - if( pantograph.vPos.y == 0.0 ) { - // crude fallback, place the pantograph(s) atop of the vehicle-sized box - pantograph.vPos.y = MoverParameters->Dim.H - pantograph.fHeight - pantograph.PantWys; - } - // pants[i].fParamPants->vPos.z=0; //niezerowe dla pantografów asymetrycznych - pantograph.PantTraction = pantograph.PantWys; - // połowa szerokości ślizgu; jest w "Power: CSW=" - pantograph.fWidth = 0.5 * MoverParameters->EnginePowerSource.CollectorParameters.CSW; - - // create sound emitters for the pantograph - m_pantographsounds.emplace_back(); - } - } - } - - else if (token == "animpistonprefix:") { - // prefiks tłoczysk - na razie uzywamy modeli pantografów - parser.getTokens(1, false); parser >> token; - for( int i = 1; i <= 2; ++i ) - { - // asAnimName=str+i; - // smPatykird1[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykird1[i-1]->WillBeAnimated(); - } - } - - else if( token == "animconrodprefix:" ) { - // prefiks korbowodów - na razie używamy modeli pantografów - parser.getTokens(); parser >> token; - for( int i = 1; i <= 2; i++ ) - { - // asAnimName=str+i; - // smPatykirg1[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykirg1[i-1]->WillBeAnimated(); - } - } - - else if( token == "pistonfactors:" ) { - // Ra: parametry - // silnika parowego - // (tłoka) - /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji - pantografów - pant1x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia - dla - pierwszego tłoka - pant2x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia - dla - drugiego tłoka - panty=Parser->GetNextSymbol().ToDouble(); //długość korby (r) - panth=Parser->GetNextSymbol().ToDouble(); //długoś korbowodu - (k) - */ - MoverParameters->EnginePowerSource.PowerType = - TPowerType::SteamPower; // Ra: po chamsku, ale z CHK nie działa - } - - else if( token == "animreturnprefix:" ) { - // prefiks drążka mimośrodowego - na razie używamy modeli pantografów - parser.getTokens(1, false); parser >> token; - for( int i = 1; i <= 2; i++ ) - { - // asAnimName=str+i; - // smPatykird2[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykird2[i-1]->WillBeAnimated(); - } - } - - else if (token == "animexplinkprefix:"){ // animreturnprefix: - // prefiks jarzma - na razie używamy modeli pantografów - parser.getTokens(1, false); parser >> token; - for( int i = 1; i <= 2; i++ ) - { - // asAnimName=str+i; - // smPatykirg2[i-1]=mdModel->GetFromName(asAnimName.c_str()); - // smPatykirg2[i-1]->WillBeAnimated(); - } - } - - else if( token == "animpendulumprefix:" ) { - // prefiks wahaczy - parser.getTokens(); parser >> token; - asAnimName = ""; - for( int i = 1; i <= 4; ++i ) { - // McZapkie-050402: wyszukiwanie max 4 wahaczy o nazwie str* - asAnimName = token + std::to_string( i ); - smWahacze[ i - 1 ] = GetSubmodelFromName( mdModel, asAnimName ); - if( smWahacze[ i - 1 ] ) { - smWahacze[ i - 1 ]->WillBeAnimated(); - } - } - parser.getTokens(); parser >> token; - if( token == "pendulumamplitude:" ) { - parser.getTokens( 1, false ); - parser >> fWahaczeAmp; - } - } - - else if( token == "animslottedlever:" ) { - // lever with a slot, turned by a pin on the coupling rod (e.g. speedometer drive) - // parameters: submodel name, number of axle (from animwheelprefix) driving the coupling rod, crank radius [m], - // pin position relative to the lever axis [m] and crank angle [deg] for wheel angle 0, in local (Y, Z) plane of the lever - // angle is measured from Y axis towards Z axis, i.e. in the direction of rotation around X axis - slottedlever_data lever; - int axle { 1 }; - double crankradius { 0.0 }; - double crankangle { 0.0 }; - parser.getTokens( 6, false ); - parser - >> asAnimName - >> axle - >> crankradius - >> lever.pin.x - >> lever.pin.y - >> crankangle; - lever.submodel = GetSubmodelFromName( mdModel, asAnimName ); - if( lever.submodel != nullptr ) { - lever.submodel->WillBeAnimated(); - lever.axle = std::max( 0, axle - 1 ); - lever.crank = crankradius * glm::dvec2( std::cos( glm::radians( crankangle ) ), std::sin( glm::radians( crankangle ) ) ); - m_slottedlevers.emplace_back( lever ); - } - else { - ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); - } - } - - else if( token == "animdoorprefix:" ) { - // nazwa animowanych drzwi - int i, j; - parser.getTokens(1, false); parser >> token; - for (i = 0, j = 0; i < ANIM_DOORS; ++i) - j += iAnimType[i]; // zliczanie wcześniejszych animacji - for (i = 0; i < iAnimType[ANIM_DOORS]; ++i) // liczba drzwi - { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* - // ustalenie submodelu - asAnimName = token + std::to_string(i + 1); - pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if (pAnimations[i + j].smAnimated) - { //++iAnimatedDoors; - pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - switch( MoverParameters->Doors.type ) - { // od razu zapinamy potrzebny typ animacji - case 1: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); - break; - case 2: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); - break; - case 3: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); - break; // obrót 3 kolejnych submodeli - case 4: - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); - break; - default: - break; - } - pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste - pAnimations[i + j].fMaxDist = 300 * 300; // drzwi to z daleka widać -/* - // NOTE: no longer used - pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor - pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; -*/ - } - } - } - - else if( token == "animstepprefix:" ) { - // animated doorstep submodel name prefix - int i, j; - parser.getTokens(1, false); parser >> token; - for (i = 0, j = 0; i < ANIM_DOORSTEPS; ++i) - j += iAnimType[i]; // zliczanie wcześniejszych animacji - for (i = 0; i < iAnimType[ANIM_DOORSTEPS]; ++i) // liczba drzwi - { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* - // ustalenie submodelu - asAnimName = token + std::to_string(i + 1); - pAnimations[i + j].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if (pAnimations[i + j].smAnimated) - { //++iAnimatedDoors; - pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - switch( MoverParameters->Doors.step_type ) - { // od razu zapinamy potrzebny typ animacji - case 1: // shift - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformTranslate, this, std::placeholders::_1 ); - break; - case 2: // rotate - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformRotate, this, std::placeholders::_1 ); - break; - default: - break; - } - pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste - pAnimations[i + j].fMaxDist = 150 * 150; // drzwi to z daleka widać -/* - // NOTE: no longer used - pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor - pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; -*/ - } - } - } - - else if( token == "animmirrorprefix:" ) { - // animated mirror submodel name prefix - int i, j; - parser.getTokens( 1, false ); parser >> token; - for( i = 0, j = 0; i < ANIM_MIRRORS; ++i ) - j += iAnimType[ i ]; // zliczanie wcześniejszych animacji - for( i = 0; i < iAnimType[ ANIM_MIRRORS ]; ++i ) // liczba drzwi - { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* - // ustalenie submodelu - asAnimName = token + std::to_string( i + 1 ); - pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); - if( pAnimations[ i + j ].smAnimated ) { - pAnimations[ i + j ].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu - // od razu zapinamy potrzebny typ animacji - auto const offset { pAnimations[ i + j ].smAnimated->offset() }; - pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateMirror, this, std::placeholders::_1 ); - // we don't expect more than 2-4 mirrors, so it should be safe to store submodel location (front/rear) in the higher bits - // parzyste działają inaczej niż nieparzyste - pAnimations[ i + j ].iNumber = - ( ( pAnimations[ i + j ].smAnimated->offset().z > 0 ? - end::front : - end::rear ) << 4 ) - + i; - pAnimations[ i + j ].fMaxDist = 150 * 150; // drzwi to z daleka widać -/* - // NOTE: no longer used - pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor - pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; -*/ - } - } - } - - else if (token == "animwiperprefix:") - { - parser.getTokens(1, false); - parser >> token; - TSubModel *sm; - if (wipers) - { - - for (int i = 0; i < iAnimType[ANIM_WIPERS]; i++) // zebranie wszystkich submodeli wycieraczek - { - dWiperPos.emplace_back(0.0); // dodajemy na koniec zeby sie miejsce tam zrobilo i nie bylo invalid addressow potem - - asAnimName = token + std::to_string(i + 1); - // element wycieraczki nr 1 - sm = GetSubmodelFromName(mdModel, asAnimName + "_p1"); - wipers[i].smElement[0] = sm; - if (sm) - { - wipers[i].smElement[0]->WillBeAnimated(); - // auto const offset{wipers[i].smElement[0]->offset()}; - } - - // element wycieraczki nr 2 - sm = GetSubmodelFromName(mdModel, asAnimName + "_p2"); - wipers[i].smElement[1] = sm; - if (sm) - { - wipers[i].smElement[1]->WillBeAnimated(); - // auto const offset{wipers[i].smElement[0]->offset()}; - } - - // element wycieraczki nr 3 - sm = GetSubmodelFromName(mdModel, asAnimName + "_p3"); - wipers[i].smElement[2] = sm; - if (sm) - { - wipers[i].smElement[2]->WillBeAnimated(); - // auto const offset{wipers[i].smElement[0]->offset()}; - } - wipers[i].yUpdate = std::bind(&TDynamicObject::UpdateWiper, this, std::placeholders::_1); - wipers[i].fMaxDist = 150 * 150; - wipers[i].iNumber = i; - } - } - } - - } while( token != "" - && token != "endmodels" ); - - if( false == MoverParameters->LoadAttributes.empty() ) { - // Ra: tu wczytywanie modelu ładunku jest w porządku - - // bieżąca ścieżka do tekstur to dynamic/... - Global.asCurrentTexturePath = asBaseDir; - - mdLoad = LoadMMediaFile_mdload( MoverParameters->LoadType.name ); - - // z powrotem defaultowa sciezka do tekstur - Global.asCurrentTexturePath = std::string( paths::textures ); - } - - } // models - - else if( token == "sounds:" ) { - // dzwieki - do { - token = ""; - parser.getTokens(); parser >> token; - if( token == "wheel_clatter:" ){ - // polozenia osi w/m srodka pojazdu - double dSDist; - parser.getTokens( 1, false ); - parser >> dSDist; - while( (token = parser.getToken()) != "" - && token != "end" ) { - // add another axle entry to the list - axle_sounds axle { - 0, - std::atof( token.c_str() ) * -1.0, // for axle locations negative value means ahead of centre but vehicle faces +Z in 'its' space - { sound_placement::external, static_cast( dSDist ) } }; - axle.clatter.deserialize( parser, sound_type::single ); - axle.clatter.owner( this ); - axle.clatter.offset( { 0, 0, axle.offset } ); - m_axlesounds.emplace_back( axle ); - } - // arrange the axles in case they're listed out of order - std::sort( - std::begin( m_axlesounds ), std::end( m_axlesounds ), - []( axle_sounds const &Left, axle_sounds const &Right ) { - return Left.offset > Right.offset; } ); - } - - else if( token == "engine:" - && MoverParameters->Power > 0 ) { - // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. - m_powertrainsounds.engine.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.engine.owner( this ); - - auto const amplitudedivisor = static_cast( MoverParameters->EngineType == TEngineType::DieselEngine ? 1 : - MoverParameters->EngineType == TEngineType::DieselElectric ? 1 : - MoverParameters->nmax * 60 + MoverParameters->Power * 3 ); - m_powertrainsounds.engine.m_amplitudefactor /= amplitudedivisor; - - } else if (token == "fakeengine:") { - m_powertrainsounds.fake_engine.deserialize(parser, sound_type::single); - m_powertrainsounds.fake_engine.owner(this); - } - - else if( token == "dieselinc:" ) { - // dzwiek przy wlazeniu na obroty woodwarda - m_powertrainsounds.engine_revving.deserialize( parser, sound_type::single, sound_parameters::range ); - m_powertrainsounds.engine_revving.owner( this ); - } - - else if( token == "oilpump:" ) { - m_powertrainsounds.oil_pump.deserialize( parser, sound_type::single ); - m_powertrainsounds.oil_pump.owner( this ); - } - - else if( token == "fuelpump:" ) { - m_powertrainsounds.fuel_pump.deserialize( parser, sound_type::single ); - m_powertrainsounds.fuel_pump.owner( this ); - } - - else if( token == "waterpump:" ) { - m_powertrainsounds.water_pump.deserialize( parser, sound_type::single ); - m_powertrainsounds.water_pump.owner( this ); - } - - else if( token == "waterheater:" ) { - m_powertrainsounds.water_heater.deserialize( parser, sound_type::single ); - m_powertrainsounds.water_heater.owner( this ); - } - - else if( token == "tractionmotor:" && MoverParameters->Power > 0 ) { - // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. - sound_source motortemplate { sound_placement::external }; - motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - auto const amplitudedivisor { static_cast( MoverParameters->nmax * 60 + MoverParameters->Power * 3 ) }; - motortemplate.m_amplitudefactor /= amplitudedivisor; - motortemplate.owner( this ); - - auto &motors { m_powertrainsounds.motors }; - - if( true == motors.empty() ) { - // fallback for cases without specified motor locations, convert sound template to a single sound source - motors.emplace_back( motortemplate ); - } - else { - // apply configuration to all defined motors - for( auto &motor : motors ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors - auto motoroffset { motortemplate.offset() }; - motoroffset.z = motor.offset().z; - motor = motortemplate; - motor.offset( motoroffset ); - // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources - motor.start( LocalRandom( 0.0, 1.0 ) ); - } - } - } - - else if( token == "tractionacmotor:" && MoverParameters->Power > 0 ) { - // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. - sound_source motortemplate { sound_placement::external }; - motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - motortemplate.owner( this ); - - auto &motors { m_powertrainsounds.acmotors }; - - if( true == motors.empty() ) { - // fallback for cases without specified motor locations, convert sound template to a single sound source - motors.emplace_back( motortemplate ); - } - else { - // apply configuration to all defined motors - for( auto &motor : motors ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors - auto motoroffset { motortemplate.offset() }; - motoroffset.z = motor.offset().z; - motor = motortemplate; - motor.offset( motoroffset ); - // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources - motor.start( LocalRandom( 0.0, 1.0 ) ); - } - } - } - - else if( token == "motorblower:" ) { - - sound_source blowertemplate { sound_placement::engine }; - blowertemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - blowertemplate.owner( this ); - - auto const amplitudedivisor { static_cast( - MoverParameters->MotorBlowers[ end::front ].speed > 0 ? MoverParameters->MotorBlowers[ end::front ].speed * MoverParameters->nmax * 60 + MoverParameters->Power * 3 : - blowertemplate.has_bookends() ? 1 : // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - MoverParameters->MotorBlowers[ end::front ].speed * -1 ) }; - blowertemplate.m_amplitudefactor /= amplitudedivisor; - blowertemplate.m_frequencyfactor /= amplitudedivisor; - - if( true == m_powertrainsounds.motors.empty() ) { - // fallback for cases without specified motor locations, convert sound template to a single sound source - m_powertrainsounds.motorblowers.emplace_back( blowertemplate ); - } - else { - // apply configuration to all defined motor blowers - for( auto &blower : m_powertrainsounds.motorblowers ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual blowers - auto bloweroffset { blowertemplate.offset() }; - bloweroffset.z = blower.offset().z; - blower = blowertemplate; - blower.offset( bloweroffset ); - // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources - blower.start( LocalRandom( 0.0, 1.0 ) ); - } - } - } - - else if( token == "inverter:" ) { - // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. - m_powertrainsounds.inverter.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.inverter.owner( this ); - } - - else if( token == "ventilator:" ) { - // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. - m_powertrainsounds.rsWentylator.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.rsWentylator.owner( this ); - - m_powertrainsounds.rsWentylator.m_amplitudefactor /= MoverParameters->RVentnmax; - m_powertrainsounds.rsWentylator.m_frequencyfactor /= MoverParameters->RVentnmax; - } - - else if( token == "radiatorfan1:" ) { - // primary circuit radiator fan - m_powertrainsounds.radiator_fan.deserialize( parser, sound_type::single ); - m_powertrainsounds.radiator_fan.owner( this ); - } - - else if( token == "radiatorfan2" ) { - // auxiliary circuit radiator fan - m_powertrainsounds.radiator_fan_aux.deserialize( parser, sound_type::single ); - m_powertrainsounds.radiator_fan_aux.owner( this ); - } - - else if( token == "transmission:" ) { - // plik z dzwiekiem, mnozniki i ofsety amp. i czest. - // NOTE, fixed default parameters, legacy system leftover - auto &sound { m_powertrainsounds.transmission }; - sound.m_amplitudefactor = 0.029; - sound.m_amplitudeoffset = 0.1; - sound.m_frequencyfactor = 0.005; - sound.m_frequencyoffset = 1.0; - - sound.deserialize( parser, sound_type::single, sound_parameters::range ); - sound.owner( this ); - } - - else if( token == "brakesound:" ) { - // hamowanie zwykle: - rsBrake.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); - rsBrake.owner( this ); - // NOTE: can't pre-calculate amplitude normalization based on max brake force, as this varies depending on vehicle speed - rsBrake.m_frequencyfactor /= 1 + MoverParameters->Vmax; - } - - else if( token == "brake:" ) { - // plik z piskiem hamulca, mnozniki i ofsety amplitudy. - rsPisk.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude ); - rsPisk.owner( this ); - - if( rsPisk.m_amplitudefactor > 10.f ) { - // HACK: convert old style activation point threshold to the new, regular amplitude adjustment system - rsPisk.m_amplitudefactor = 1.f; - rsPisk.m_amplitudeoffset = 0.f; - } - rsPisk.m_amplitudeoffset *= ( 105.f - Random( 10.f ) ) / 100.f; - } - - else if( token == "brakecylinderinc:" ) { - // brake cylinder pressure increase sounds - m_brakecylinderpistonadvance.deserialize( parser, sound_type::single ); - m_brakecylinderpistonadvance.owner( this ); - } - - else if( token == "brakecylinderdec:" ) { - // brake cylinder pressure decrease sounds - m_brakecylinderpistonrecede.deserialize( parser, sound_type::single ); - m_brakecylinderpistonrecede.owner( this ); - } - - else if (token == "epbrakeinc:") { - // brake cylinder pressure increase sounds - m_epbrakepressureincrease.deserialize(parser, sound_type::single); - m_epbrakepressureincrease.owner(this); - } - - else if (token == "epbrakedec:") { - // brake cylinder pressure decrease sounds - m_epbrakepressuredecrease.deserialize(parser, sound_type::single); - m_epbrakepressuredecrease.owner(this); - } - - else if( token == "emergencybrake:" ) { - // emergency brake sound - m_emergencybrake.deserialize( parser, sound_type::single ); - m_emergencybrake.owner( this ); - } - - else if( token == "brakeacc:" ) { - // plik z przyspieszaczem (upust po zlapaniu hamowania) - sBrakeAcc.deserialize( parser, sound_type::single ); - sBrakeAcc.owner( this ); - - bBrakeAcc = true; - } - - else if( token == "unbrake:" ) { - // plik z piskiem hamulca, mnozniki i ofsety amplitudy. - rsUnbrake.m_amplitudefactor = 20.0f; - rsUnbrake.deserialize( parser, sound_type::single, sound_parameters::range ); - rsUnbrake.owner( this ); - } - // spring brake sounds - else if( token == "springbrake:" ) { - m_springbrakesounds.activate.deserialize( parser, sound_type::single ); - m_springbrakesounds.activate.owner( this ); - } - else if( token == "springbrakeoff:" ) { - m_springbrakesounds.release.deserialize( parser, sound_type::single ); - m_springbrakesounds.release.owner( this ); - } - - else if( token == "derail:" ) { - // dzwiek przy wykolejeniu - rsDerailment.deserialize( parser, sound_type::single, sound_parameters::range ); - rsDerailment.owner( this ); - } - - else if( token == "curve:" ) { - rscurve.deserialize( parser, sound_type::single, sound_parameters::range ); - rscurve.owner( this ); - } - - else if( token == "horn1:" ) { - // pliki z trabieniem - sHorn1.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sHorn1.owner( this ); - } - - else if( token == "horn2:" ) { - // pliki z trabieniem wysokoton. - sHorn2.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sHorn2.owner( this ); - // TBD, TODO: move horn selection to ai config file - if( iHornWarning ) { - iHornWarning = 2; // numer syreny do użycia po otrzymaniu sygnału do jazdy - } - } - - else if( token == "horn3:" ) { - sHorn3.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sHorn3.owner( this ); - } - - else if( token == "pantographup:" ) { - // pliki dzwiekow pantografow - sound_source pantographup { sound_placement::external }; - pantographup.deserialize( parser, sound_type::single ); - pantographup.owner( this ); - for( auto &pantograph : m_pantographsounds ) { - pantograph.sPantUp = pantographup; - } - } - - else if( token == "pantographdown:" ) { - // pliki dzwiekow pantografow - sound_source pantographdown { sound_placement::external }; - pantographdown.deserialize( parser, sound_type::single ); - pantographdown.owner( this ); - for( auto &pantograph : m_pantographsounds ) { - pantograph.sPantDown = pantographdown; - } - } - - else if( token == "compressor:" ) { - // pliki ze sprezarka - sCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sCompressor.owner( this ); - } - - else if( token == "compressoridle:" ) { - // pliki ze sprezarka - sCompressorIdle.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sCompressorIdle.owner( this ); - } - - else if( token == "converter:" ) { - // pliki z przetwornica - sConverter.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sConverter.owner( this ); - } - - // Dzwiek wentylatora rezystora hamowania - else if (token == "brakingresistorventilator:") - { - sBRVent.deserialize(parser, sound_type::multipart, sound_parameters::range); - sBRVent.owner(this); - } - - else if( token == "heater:" ) { - // train heating device - sHeater.deserialize( parser, sound_type::single ); - sHeater.owner( this ); - } - - else if( token == "battery:" ) { - // train heating device - m_batterysound.deserialize( parser, sound_type::single ); - m_batterysound.owner( this ); - } - - else if( token == "turbo:" ) { - // pliki z turbogeneratorem - m_powertrainsounds.engine_turbo.deserialize( parser, sound_type::multipart, sound_parameters::range ); - m_powertrainsounds.engine_turbo.owner( this ); - m_powertrainsounds.engine_turbo.gain( 0 ); - } - - else if( token == "small-compressor:" ) { - // pliki z przetwornica - sSmallCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sSmallCompressor.owner( this ); - } - - else if( token == "departuresignal:" ) { - // pliki z sygnalem odjazdu - sound_source soundtemplate { sound_placement::general, 25.f }; - soundtemplate.deserialize( parser, sound_type::multipart, sound_parameters::range ); - soundtemplate.owner( this ); - for( auto &speaker : m_doorspeakers ) { - speaker.departure_signal = soundtemplate; - speaker.departure_signal.offset( speaker.offset ); - } - } - - else if( token == "dooropen:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.rsDoorOpen.offset() }; - door.rsDoorOpen = soundtemplate; - door.rsDoorOpen.offset( dooroffset ); - } - } - - else if( token == "doorclose:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.rsDoorClose.offset() }; - door.rsDoorClose = soundtemplate; - door.rsDoorClose.offset( dooroffset ); - } - } - - else if( token == "doorlock:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.lock.offset() }; - door.lock = soundtemplate; - door.lock.offset( dooroffset ); - } - } - - else if( token == "doorunlock:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.unlock.offset() }; - door.unlock = soundtemplate; - door.unlock.offset( dooroffset ); - } - } - - else if( token == "doorstepopen:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.step_open.offset() }; - door.step_open = soundtemplate; - door.step_open.offset( dooroffset ); - } - } - - else if( token == "mirroropen:" || token == "mirrorclose:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &mirror : m_mirrorsounds ) { - // apply configuration to all defined mirrors, but preserve their individual offsets - auto &sound { token == "mirroropen:" ? mirror.unfold : mirror.fold }; - auto const mirroroffset { sound.offset() }; - sound = soundtemplate; - sound.offset( mirroroffset ); - } - } - - else if( token == "doorstepclose:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.step_close.offset() }; - door.step_close = soundtemplate; - door.step_close.offset( dooroffset ); - } - } - - else if( token == "doorpermit:" ) { - sound_source soundtemplate { sound_placement::general }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &door : m_doorsounds ) { - // apply configuration to all defined doors, but preserve their individual offsets - auto const dooroffset { door.permit_granted.offset() }; - door.permit_granted = soundtemplate; - door.permit_granted.offset( dooroffset ); - } - } - - else if( token == "unloading:" ) { - m_exchangesounds.unloading.range( MoverParameters->Dim.L * 0.5f * -1 ); - m_exchangesounds.unloading.deserialize( parser, sound_type::single ); - m_exchangesounds.unloading.owner( this ); - } - - else if( token == "loading:" ) { - m_exchangesounds.loading.range( MoverParameters->Dim.L * 0.5f * -1 ); - m_exchangesounds.loading.deserialize( parser, sound_type::single ); - m_exchangesounds.loading.owner( this ); - } - - else if( token == "sand:" ) { - sSand.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sSand.owner( this ); - } - - else if( token == "releaser:" ) { - // pliki z odluzniaczem - sReleaser.deserialize( parser, sound_type::multipart, sound_parameters::range ); - sReleaser.owner( this ); - } - - else if( token == "outernoise:" ) { - // szum podczas jazdy: - sound_source noisetemplate{ sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; - noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, MoverParameters->Vmax ); - noisetemplate.owner( this ); - - noisetemplate.m_amplitudefactor /= 1 + MoverParameters->Vmax; - noisetemplate.m_frequencyfactor /= 1 + MoverParameters->Vmax; -#ifdef EU07_SOUND_BOGIESOUNDS - if( true == m_bogiesounds.empty() ) { - // fallback for cases without specified noise locations, convert sound template to a single sound source - m_bogiesounds.emplace_back( noisetemplate ); - } - else { - // apply configuration to all defined bogies - for( auto &bogie : m_bogiesounds ) { - // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors - auto bogieoffset{ noisetemplate.offset() }; - bogieoffset.z = bogie.offset().z; - bogie = noisetemplate; - bogie.offset( bogieoffset ); - } - } - // apply randomized playback start offset for each bogie, to reduce potential reverb with identical nearby sources - auto bogieidx( 0 ); - for( auto &bogie : m_bogiesounds ) { - bogie.start( ( - bogieidx % 2 ? - LocalRandom( 0.0, 30.0 ) : - LocalRandom( 50.0, 80.0 ) ) - * 0.01 ); - ++bogieidx; - } -#else - m_outernoise = noisetemplate; - // apply randomized playback start offset, to reduce potential reverb with identical nearby sources - m_outernoise.start( Random( 0.0, 80.0 ) * 0.01 ); -#endif - } - - else if( token == "wheelflat:" ) { - // szum podczas jazdy: - m_wheelflat.deserialize( parser, sound_type::single, sound_parameters::frequency ); - m_wheelflat.owner( this ); - } - - else if(token == "announcements:") { - // announcement sounds - // content provided as "key: value" pairs together enclosed in "{}" - // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly - std::unordered_map const announcements = { - { "near_stop:", announcement_t::approaching }, - { "stop:", announcement_t::current }, - { "next_stop:", announcement_t::next }, - { "destination:", announcement_t::destination }, - { "chime:", announcement_t::chime } }; - while( (token = parser.getToken()) != "" - && token != "}" ) { - if( token.back() == ':' ) { - - if( token == "soundproofing:" ) { - // custom soundproofing in format [ p1, p2, p3, p4, p5, p6 ] - parser.getTokens( 6, false, "\n\r\t ,;[]" ); - std::array soundproofing; - parser - >> soundproofing[ 0 ] - >> soundproofing[ 1 ] - >> soundproofing[ 2 ] - >> soundproofing[ 3 ] - >> soundproofing[ 4 ] - >> soundproofing[ 5 ]; - for( auto & soundproofingelement : soundproofing ) { - if( soundproofingelement != -1.f ) { - soundproofingelement = std::sqrt( std::clamp( soundproofingelement, 0.f, 1.f ) ); - } - } - m_pasystem.soundproofing = soundproofing; - continue; - } - - auto const lookup { announcements.find( token ) }; - auto const announcementtype { ( - lookup != announcements.end() ? - lookup->second : - announcement_t::idle ) }; - // NOTE: we retrieve key value for all keys, not just recognized ones - if( announcementtype == announcement_t::idle ) { - token = parser.getToken(); - continue; - } -/* - auto announcementsound { deserialize_random_set( parser ) }; - replace_slashes( announcementsound ); -*/ - sound_source soundtemplate { sound_placement::engine }; // NOTE: sound range gets filled by pa system - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - m_pasystem.announcements[ static_cast( announcementtype ) ] = soundtemplate; - } - } - // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) - if( m_pasystem.soundproofing ) { - for( auto &announcement : m_pasystem.announcements ) { - if( !announcement.soundproofing() ) { - announcement.soundproofing() = m_pasystem.soundproofing; - } - } - } - } - - } while( token != "" - && token != "endsounds" ); - - } // sounds: - - else if( token == "locations:" ) { - do { - token = ""; - parser.getTokens(); parser >> token; - - if( token == "doors:" ) { - // a list of pairs: offset along vehicle's z-axis and sides on which the door is present; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, for door locations negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - // recognized side specifications are "right", "left" and "both" - auto const sides { parser.getToken() }; - // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization - door_sounds door; - // add entries to the list: - if( sides == "both" - || sides == "left" ) { - // left... - auto const location { glm::vec3 { MoverParameters->Dim.W * 0.5f, MoverParameters->Dim.H * 0.5f, offset } }; - door.placement = side::left; - door.rsDoorClose.offset( location ); - door.rsDoorOpen.offset( location ); - door.lock.offset( location ); - door.unlock.offset( location ); - door.step_close.offset( location ); - door.step_open.offset( location ); - door.permit_granted.offset( location ); - m_doorsounds.emplace_back( door ); - } - if( sides == "both" - || sides == "right" ) { - // ...and right - auto const location { glm::vec3 { MoverParameters->Dim.W * -0.5f, 2.f, offset } }; - door.placement = side::right; - door.rsDoorClose.offset( location ); - door.rsDoorOpen.offset( location ); - door.lock.offset( location ); - door.unlock.offset( location ); - door.step_close.offset( location ); - door.step_open.offset( location ); - door.permit_granted.offset( location ); - m_doorsounds.emplace_back( door ); - } - m_doorspeakers.emplace_back( - doorspeaker_sounds { - { 0.f, 3.f, offset }, - {} } ); - } - } - - else if( token == "mirrors:" ) { - // a list of offsets along vehicle's z-axis of the mirror pairs, one at each cab; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, as for the doors negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - mirror_sounds mirror; - mirror.end = offset >= 0.f ? end::front : end::rear; - for( auto const mirrorside : { side::left, side::right } ) { - auto const location { glm::vec3 { - MoverParameters->Dim.W * ( mirrorside == side::left ? 0.5f : -0.5f ), - MoverParameters->Dim.H * 0.5f, - offset } }; - mirror.placement = mirrorside; - mirror.unfold.offset( location ); - mirror.fold.offset( location ); - m_mirrorsounds.emplace_back( mirror ); - } - } - } - - else if( token == "tractionmotors:" ) { - // a list of offsets along vehicle's z-axis; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, for motor locations negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization - sound_source motor { sound_placement::external }; // generic traction motor sounds - sound_source acmotor { sound_placement::external }; // inverter-specific traction motor sounds - sound_source motorblower { sound_placement::engine }; // associated motor blowers - // add entry to the list - auto const location { glm::vec3 { 0.f, 0.f, offset } }; - motor.offset( location ); - m_powertrainsounds.motors.emplace_back( motor ); - acmotor.offset( location ); - m_powertrainsounds.acmotors.emplace_back( acmotor ); - motorblower.offset( location ); - m_powertrainsounds.motorblowers.emplace_back( motorblower ); - } - } - - else if( token == "bogies:" ) { - // a list of offsets along vehicle's z-axis; followed with "end" - while( (token = parser.getToken()) != "" - && token != "end" ) { - // vehicle faces +Z in 'its' space, for bogie locations negative value means ahead of centre - auto const offset { std::atof( token.c_str() ) * -1.f }; - // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization - sound_source bogienoise { sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; - // add entry to the list - auto const location { glm::vec3 { 0.f, 0.f, offset } }; - bogienoise.offset( location ); -#ifdef EU07_SOUND_BOGIESOUNDS - m_bogiesounds.emplace_back( bogienoise ); -#endif - } - } - - } while( token != "" - && token != "endlocations" ); - - } // locations: - - else if( token == "internaldata:" ) { - // dalej nie czytaj - do { - // zbieranie informacji o kabinach - token = ""; - parser.getTokens(); parser >> token; - if( token == "cab0model:" ) { - parser.getTokens(); parser >> token; - if( token != "none" ) { iCabs |= 0x2; } - } - else if( token == "cab1model:" ) { - parser.getTokens(); parser >> token; - if( token != "none" ) { iCabs |= 0x1; } - } - else if( token == "cab2model:" ) { - parser.getTokens(); parser >> token; - if( token != "none" ) { iCabs |= 0x4; } - } - // engine sounds - else if( token == "ignition:" ) { - // odpalanie silnika - m_powertrainsounds.engine_ignition.deserialize( parser, sound_type::single ); - m_powertrainsounds.engine_ignition.owner( this ); - } else if (token == "shutdown:") { - m_powertrainsounds.engine_shutdown.deserialize(parser, sound_type::single); - m_powertrainsounds.engine_shutdown.owner(this); - } else if( token == "engageslippery:" ) { - // tarcie tarcz sprzegla: - m_powertrainsounds.rsEngageSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); - m_powertrainsounds.rsEngageSlippery.owner( this ); - - m_powertrainsounds.rsEngageSlippery.m_frequencyfactor /= 1 + MoverParameters->nmax; - } - - // dzwieki wycieraczkuf - else if (token == "wiperfrompark:") - { - sWiperFromPark.deserialize(parser, sound_type::single); - sWiperFromPark.owner(this); - } - else if (token == "wipertopark:") - { - sWiperToPark.deserialize(parser, sound_type::single); - sWiperToPark.owner(this); - } - - else if (token == "retarder:") { - m_powertrainsounds.retarder.deserialize(parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency); - m_powertrainsounds.retarder.owner(this); - } - else if( token == "linebreakerclose:" ) { - m_powertrainsounds.linebreaker_close.deserialize( parser, sound_type::single ); - m_powertrainsounds.linebreaker_close.owner( this ); - } - else if( token == "linebreakeropen:" ) { - m_powertrainsounds.linebreaker_open.deserialize( parser, sound_type::single ); - m_powertrainsounds.linebreaker_open.owner( this ); - } - else if( token == "relay:" ) { - // styczniki itp: - m_powertrainsounds.motor_relay.deserialize( parser, sound_type::single ); - m_powertrainsounds.motor_relay.owner( this ); - } - else if( token == "shuntfield:" ) { - // styczniki itp: - m_powertrainsounds.motor_shuntfield.deserialize( parser, sound_type::single ); - m_powertrainsounds.motor_shuntfield.owner( this ); - } - else if( token == "wejscie_na_bezoporow:" ) { - // hunter-111211: wydzielenie wejscia na bezoporowa i na drugi uklad do pliku - m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( parser, sound_type::single ); - m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); - } - // przekazniki od kierunku jazdy - else if (token == "directionrelay_d:") { - // przekaznik od kierunku jazdy do przodu - sDirectionRelayD.deserialize(parser, sound_type::single); - sDirectionRelayD.owner(this); - } - else if (token == "directionrelay_r:") { - // przekaznik od kierunku jazdy do tylu - sDirectionRelayR.deserialize(parser, sound_type::single); - sDirectionRelayR.owner(this); - } - else if (token == "directionrelay_n:") - { - // przekaznik od kierunku jazdy do tylu - sDirectionRelayN.deserialize(parser, sound_type::single); - sDirectionRelayN.owner(this); - } - else if( token == "wejscie_na_drugi_uklad:" ) { - m_powertrainsounds.motor_parallel.deserialize( parser, sound_type::single ); - m_powertrainsounds.motor_parallel.owner( this ); - } - else if( token == "pneumaticrelay:" ) { - // wylaczniki pneumatyczne: - dsbPneumaticRelay.deserialize( parser, sound_type::single ); - dsbPneumaticRelay.owner( this ); - } - else if( token == "slipperysound:" ) { - // sanie: - rsSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude ); - rsSlippery.owner( this ); - - rsSlippery.m_amplitudefactor /= 1 + MoverParameters->Vmax; - } - // coupler sounds - else if( token == "couplerattach:" ) { - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_coupler = soundtemplate; - } - } - else if( token == "brakehoseattach:" ) { - // laczenie: - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_brakehose = soundtemplate; - } - } - else if( token == "mainhoseattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_mainhose = soundtemplate; - } - } - else if( token == "controlattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_control = soundtemplate; - } - } - else if( token == "gangwayattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_gangway = soundtemplate; - } - } - else if( token == "heatingattach:" ) { - // laczenie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.attach_heating = soundtemplate; - } - } - else if( token == "couplerdetach:" ) { - // rozlaczanie: - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_coupler = soundtemplate; - } - } - else if( token == "brakehosedetach:" ) { - // rozlaczanie: - sound_source soundtemplate { sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_brakehose = soundtemplate; - } - } - else if( token == "mainhosedetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_mainhose = soundtemplate; - } - } - else if( token == "controldetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_control = soundtemplate; - } - } - else if( token == "gangwaydetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_gangway = soundtemplate; - } - } - else if( token == "heatingdetach:" ) { - // rozlaczanie: - sound_source soundtemplate{ sound_placement::external }; - soundtemplate.deserialize( parser, sound_type::single ); - soundtemplate.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.detach_heating = soundtemplate; - } - } - else if( token == "couplerstretch:" ) { - // coupler stretching - sound_source couplerstretch { sound_placement::external }; - couplerstretch.deserialize( parser, sound_type::single ); - couplerstretch.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbCouplerStretch = couplerstretch; - } - } - else if( token == "couplerstretch_loud:" ) { - // coupler stretching - sound_source couplerstretch { sound_placement::external }; - couplerstretch.deserialize( parser, sound_type::single ); - couplerstretch.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbCouplerStretch_loud = couplerstretch; - } - } - else if( token == "bufferclamp:" ) { - // buffers hitting one another - sound_source bufferclash { sound_placement::external }; - bufferclash.deserialize( parser, sound_type::single ); - bufferclash.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbBufferClamp = bufferclash; - } - } - else if( token == "bufferclamp_loud:" ) { - // buffers hitting one another - sound_source bufferclash { sound_placement::external }; - bufferclash.deserialize( parser, sound_type::single ); - bufferclash.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbBufferClamp_loud = bufferclash; - } - } - else if( token == "coupleradapterattach:" ) { - // laczenie: - sound_source adapterattach { sound_placement::external }; - adapterattach.deserialize( parser, sound_type::single ); - adapterattach.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbAdapterAttach = adapterattach; - } - } - else if( token == "coupleradapterremove:" ) { - // rozlaczanie: - sound_source adapterremove { sound_placement::external }; - adapterremove.deserialize( parser, sound_type::single ); - adapterremove.owner( this ); - for( auto &couplersounds : m_couplersounds ) { - couplersounds.dsbAdapterRemove = adapterremove; - } - } - else if( token == "startjolt:" ) { - // movement start jolt - m_startjolt.deserialize( parser, sound_type::single ); - m_startjolt.owner( this ); - } - - else if (token == "mechspring:") - { - // parametry bujania kamery: - double ks, kd; - parser.getTokens(2, false); - parser - >> ks - >> kd; - ShakeSpring.Init(ks, kd); - parser.getTokens(6, false); - parser - >> BaseShake.jolt_scale.x - >> BaseShake.jolt_scale.y - >> BaseShake.jolt_scale.z - >> BaseShake.jolt_limit - >> BaseShake.angle_scale.x - >> BaseShake.angle_scale.z; - } - else if( token == "enginespring:" ) { - parser.getTokens( 5, false ); - parser - >> EngineShake.scale - >> EngineShake.fadein_offset - >> EngineShake.fadein_factor - >> EngineShake.fadeout_offset - >> EngineShake.fadeout_factor; - // offsets values are provided as rpm for convenience - EngineShake.fadein_offset /= 60.f; - EngineShake.fadeout_offset /= 60.f; - } - else if( token == "huntingspring:" ) { - parser.getTokens( 4, false ); - parser - >> HuntingShake.scale - >> HuntingShake.frequency - >> HuntingShake.fadein_begin - >> HuntingShake.fadein_end; - } - - else if( token == "soundproofing:" ) { - for( auto &soundproofingtable : m_soundproofing ) { - for( auto &soundproofingelement : soundproofingtable ) { - auto const value { parser.getToken( false ) }; - if( value != -1.f ) { - soundproofingelement = std::sqrt( std::clamp( value, 0.f, 1.f ) ); - } - } - } - } - - else if( token == "jointcabs:" ) { - parser.getTokens(); - parser >> JointCabs; - } - - else if( token == "cablight:" ) { - parser.getTokens( 3, false ); // low power light, ignore - parser.getTokens( 3, false ); // base light - parser - >> InteriorLight.r - >> InteriorLight.g - >> InteriorLight.b; - InteriorLight = glm::clamp( InteriorLight / 255.f, glm::vec3( 0.f ), glm::vec3( 1.f ) ); - parser.getTokens( 3, false ); // dimmed light, ignore - } - - else if( token == "pydestinationsign:" ) { - DestinationSign.deserialize( parser ); - // supply vehicle folder as script path if none is provided - if( false == DestinationSign.script.empty() - && substr_path(DestinationSign.script).empty() ) { - DestinationSign.script = asBaseDir + DestinationSign.script; - } - } - else if( token == "luadestinationsign:" ) { - deserialize_script_sign( parser, DestinationSign.lua, asBaseDir ); - } - else if( token == "wasmdestinationsign:" ) { - deserialize_script_sign( parser, DestinationSign.wasm, asBaseDir ); - } - // NOTE: legacy key, now expected as optional "background:" parameter in pydestinationsign: { parameter block } - else if( token == "destinationsignbackground:" ) { - parser.getTokens(); - parser >> DestinationSign.background; - } - - } while( token != "" ); - - } // internaldata: - - } while( token != "" ); - - if( !iAnimations ) { - // if the animations weren't defined the model is likely to be non-functional. warrants a warning. - ErrorLog( "Animations tag is missing from the .mmd file \"" + asFileName + "\"" ); - } - - if( ReplacableSkin != "none" ) { - // potentially set blank destination texture - auto language { script_language::lua }; - auto const *scriptsign { script_destination( language ) }; - auto const &background { ( scriptsign != nullptr && false == scriptsign->background.empty() ) ? scriptsign->background : DestinationSign.background }; - DestinationSign.destination_off = DestinationFind( background.empty() ? "nowhere" : background ); - // a blank sign a script draws, drawn once - DestinationSign.background_sign = draw_script_texture( background, DestinationSign.destination_off ); - } - - // assign default samples to sound emitters which weren't included in the config file - if( TestFlag( MoverParameters->CategoryFlag, 1 ) ) { - // rail vehicles: - // engine - if( MoverParameters->Power > 0 ) { - if( true == m_powertrainsounds.dsbWejscie_na_bezoporow.empty() ) { - // hunter-111211: domyslne, gdy brak - m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( "wejscie_na_bezoporow", sound_type::single ); - m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); - } - if( true == m_powertrainsounds.motor_parallel.empty() ) { - m_powertrainsounds.motor_parallel.deserialize( "wescie_na_drugi_uklad", sound_type::single ); - m_powertrainsounds.motor_parallel.owner( this ); - } - } - // braking sounds - if( true == rsUnbrake.empty() ) { - rsUnbrake.deserialize( "[1007]estluz", sound_type::single ); - rsUnbrake.owner( this ); - } - // couplers - for( auto &couplersounds : m_couplersounds ) { - if( true == couplersounds.attach_coupler.empty() ) { - couplersounds.attach_coupler.deserialize( "couplerattach_default", sound_type::single ); - couplersounds.attach_coupler.owner( this ); - } - if( true == couplersounds.detach_coupler.empty() ) { - couplersounds.detach_coupler.deserialize( "couplerdetach_default", sound_type::single ); - couplersounds.detach_coupler.owner( this ); - } - if( true == couplersounds.dsbCouplerStretch.empty() ) { - couplersounds.dsbCouplerStretch.deserialize( "couplerstretch_default", sound_type::single ); - couplersounds.dsbCouplerStretch.owner( this ); - } - if( true == couplersounds.dsbBufferClamp.empty() ) { - couplersounds.dsbBufferClamp.deserialize( "bufferclamp_default", sound_type::single ); - couplersounds.dsbBufferClamp.owner( this ); - } - } - // other sounds - if( true == m_wheelflat.empty() ) { - m_wheelflat.deserialize( "lomotpodkucia 0.23 0.0", sound_type::single, sound_parameters::frequency ); - m_wheelflat.owner( this ); - } - if( true == rscurve.empty() ) { - // hunter-111211: domyslne, gdy brak - rscurve.deserialize( "curve", sound_type::single ); - rscurve.owner( this ); - } - } - - if (mdModel) - mdModel->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego - if (mdLoad) - mdLoad->Init(); - if (mdLowPolyInt) - mdLowPolyInt->Init(); - for( auto *attachment : mdAttachments ) { - attachment->Init(); - } - - Global.asCurrentTexturePath = paths::textures; // kiedyś uproszczone wnętrze mieszało tekstury nieba - Global.asCurrentDynamicPath = ""; - - // position sound emitters which weren't defined in the config file - // engine sounds, centre of the vehicle - auto const enginelocation { glm::vec3 {0.f, MoverParameters->Dim.H * 0.5f, 0.f } }; - m_powertrainsounds.position( enginelocation ); - // other engine compartment sounds - auto const nullvector { glm::vec3() }; - std::vector enginesounds = { - &sConverter, &sBRVent, &sCompressor, &sCompressorIdle, &sSmallCompressor, &sHeater, &m_batterysound - }; - for( auto sound : enginesounds ) { - if( sound->offset() == nullvector ) { - sound->offset( enginelocation ); - } - } - - // pantographs - if( pants != nullptr ) { - std::size_t pantographindex { 0 }; - for( auto &pantographsounds : m_pantographsounds ) { - auto const pantographoffset { - glm::vec3( - 0.f, - pants[ pantographindex ].fParamPants->vPos.y, - -pants[ pantographindex ].fParamPants->vPos.x ) }; - pantographsounds.sPantUp.offset( pantographoffset ); - pantographsounds.sPantDown.offset( pantographoffset ); - ++pantographindex; - } - } - // doors - std::size_t dooranimationfirstindex { 0 }; - for( std::size_t i = 0; i < ANIM_DOORS; ++i ) { - // zliczanie wcześniejszych animacji - dooranimationfirstindex += iAnimType[ i ]; - } - // couplers - auto const frontcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * 0.5f } }; - m_couplersounds[ end::front ].attach_coupler.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_brakehose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_mainhose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_control.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_gangway.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].attach_heating.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_coupler.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_brakehose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_mainhose.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_control.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_gangway.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].detach_heating.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbCouplerStretch.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbCouplerStretch_loud.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbBufferClamp.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbBufferClamp_loud.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbAdapterAttach.offset( frontcoupleroffset ); - m_couplersounds[ end::front ].dsbAdapterRemove.offset( frontcoupleroffset ); - auto const rearcoupleroffset { glm::vec3{ 0.f, 1.f, MoverParameters->Dim.L * -0.5f } }; - m_couplersounds[ end::rear ].attach_coupler.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_brakehose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_mainhose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_control.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_gangway.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].attach_heating.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_coupler.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_brakehose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_mainhose.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_control.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_gangway.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].detach_heating.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbCouplerStretch.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbCouplerStretch_loud.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbBufferClamp.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbBufferClamp_loud.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbAdapterAttach.offset( rearcoupleroffset ); - m_couplersounds[ end::rear ].dsbAdapterRemove.offset( rearcoupleroffset ); -} - -TModel3d * -TDynamicObject::LoadMMediaFile_mdload( std::string const &Name ) const { - - auto const loadname { ( Name.empty() ? "none" : Name ) }; - TModel3d *loadmodel { nullptr }; - - // check if we don't have model override for this load type - if ( loadmodel == nullptr ) - { - auto const lookup { LoadModelOverrides.find( loadname ) }; - if( lookup != LoadModelOverrides.end() ) { - loadmodel = TModelsManager::GetModel( asBaseDir + lookup->second, true ); - } - } - // regular routine if there's no override or it couldn't be loaded - // try first specialized version of the load model, vehiclename_loadname - if ( loadmodel == nullptr ) - { - auto const specializedloadfilename { asBaseDir + MoverParameters->TypeName + "_" + loadname }; - loadmodel = TModelsManager::GetModel( specializedloadfilename, true, false ); - } - // try generic version of the load model next, loadname - if ( loadmodel == nullptr ) - { - auto const genericloadfilename { asBaseDir + loadname }; - loadmodel = TModelsManager::GetModel( genericloadfilename, true, false ); - } - - if ( loadmodel != nullptr ) - loadmodel->GetSMRoot()->WillBeAnimated(); - - return loadmodel; -} - -//--------------------------------------------------------------------------- -void TDynamicObject::RadioStop() -{ // zatrzymanie pojazdu - if( Mechanik ) { - // o ile ktoś go prowadzi - if( MoverParameters->SecuritySystem.radiostop_available() - && MoverParameters->Radio - && MoverParameters->RadioFuse ) { - // jeśli pojazd ma RadioStop i jest on aktywny - // HACK cast until math types unification - glm::dvec3 pos = static_cast(vPosition); - Mechanik->PutCommand( "Emergency_brake", 1.0, 1.0, &pos, stopRadio ); - // add onscreen notification for human driver - // TODO: do it selectively for the 'local' driver once the multiplayer is in - if( false == Mechanik->AIControllFlag ) { - ui::Transcripts.AddLine( "!! RADIO-STOP !!", 0.0, 10.0, false ); - } - } - } -}; - -//--------------------------------------------------------------------------- -void TDynamicObject::Damage(char flag) -{ - if (flag & 1) //różnicówka nie robi nic - { - MoverParameters->MainSwitch(false); - MoverParameters->FuseOff(); - } - else - { - } - - if (flag & 2) //usterka sterowania - { - MoverParameters->StLinFlag = false; - if (MoverParameters->InitialCtrlDelay<100000000) - MoverParameters->InitialCtrlDelay += 100000001; - } - else - { - if (MoverParameters->InitialCtrlDelay>100000000) - MoverParameters->InitialCtrlDelay -= 100000001; - } - - if (flag & 4) //blokada przetwornicy - { - if( MoverParameters->ConverterStart != start_t::disabled ) { - MoverParameters->ConvOvldFlag = true; - } - } - else - { - } - - if (flag & 8) //blokada sprezarki - { - if (MoverParameters->MinCompressor>0) - MoverParameters->MinCompressor -= 100000001; - if (MoverParameters->MaxCompressor>0) - MoverParameters->MaxCompressor -= 100000001; - } - else - { - if (MoverParameters->MinCompressor<0) - MoverParameters->MinCompressor += 100000001; - if (MoverParameters->MaxCompressor<0) - MoverParameters->MaxCompressor += 100000001; - } - - if (flag & 16) //blokada wału - { - if (MoverParameters->CtrlDelay<100000000) - MoverParameters->CtrlDelay += 100000001; - if (MoverParameters->CtrlDownDelay<100000000) - MoverParameters->CtrlDownDelay += 100000001; - } - else - { - if (MoverParameters->CtrlDelay>100000000) - MoverParameters->CtrlDelay -= 100000001; - if (MoverParameters->CtrlDownDelay>100000000) - MoverParameters->CtrlDownDelay -= 100000001; - } - - if (flag & 32) //hamowanie nagŁe - { - } - else - { - } - - MoverParameters->EngDmgFlag = flag; -}; - -void TDynamicObject::SetLights() { - auto const isfrontcaboccupied { MoverParameters->CabOccupied * DirectionGet() >= 0 }; - int const automaticmarkers { MoverParameters->CabActive == 0 && MoverParameters->InactiveCabFlag & activation::redmarkers - ? light::redmarker_left + light::redmarker_right : 0 }; - auto const lightpos { MoverParameters->LightsPos - 1 }; - std::array const cablights { - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::front ][ lightpos ], - automaticmarkers > 0 ? automaticmarkers : MoverParameters->Lights[ end::rear ][ lightpos ] }; - // the custom position keeps the lights lit at coupled ends as well - auto const ignorecouplings { MoverParameters->LightsPos == 18 }; - auto *vehicle { GetFirstDynamic( MoverParameters->CabOccupied >= 0 ? end::front : end::rear, coupling::control ) }; - while( vehicle != nullptr ) { - // set lights on given side if there's no coupling with another vehicle, turn them off otherwise - auto const iscoupled { [ vehicle, ignorecouplings ]( end const Side ) { - return false == ignorecouplings - && ( vehicle->MoverParameters->Couplers[ Side ].CouplingFlag & coupling::coupler ) != 0 - && vehicle->MoverParameters->Neighbours[ Side ].vehicle != nullptr; } }; - auto const lights { lights_programmer::vehicle_lights( - cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( end::front ), iscoupled( end::rear ) } ) }; - vehicle->RaLightsSet( lights.head, lights.rear ); - vehicle = isfrontcaboccupied ? vehicle->Next(coupling::control) : vehicle->Prev(coupling::control); - } -}; - -void TDynamicObject::RaLightsSet(int head, int rear) -{ // zapalenie świateł z przodu i z - // tyłu, zależne od kierunku - // pojazdu - if (!MoverParameters) - return; // może tego nie być na początku - if (rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) - { // jeśli koniec pociągu, to trzeba ustalić, czy - // jest tam czynna lokomotywa - // EN57 może nie mieć końcówek od środka członu - if (MoverParameters->Power > 1.0) // jeśli ma moc napędową - if (!MoverParameters->DirActive) // jeśli nie ma ustawionego kierunku - { // jeśli ma zarówno światła jak i końcówki, ustalić, czy jest w stanie aktywnym - // np. lokomotywa na zimno będzie mieć końcówki a nie światła - rear = light::rearendsignals; // tablice blaszane - // trzeba to uzależnić od "załączenia baterii" w pojeździe - } - if( rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) // jeśli nadal obydwie możliwości - if( iInventory[ - ( iDirection ? - end::rear : - end::front ) ] & ( light::redmarker_left | light::redmarker_right ) ) { - // czy ma jakieś światła czerowone od danej strony - rear = light::redmarker_left | light::redmarker_right; // dwa światła czerwone - } - else { - rear = light::rearendsignals; // tablice blaszane - } - } - // w zależności od kierunku pojazdu w składzie - if( head >= 0 ) { - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; - MoverParameters->iLights[ vehicleend ] = head & iInventory[vehicleend]; - bool tLeft = MoverParameters->iLights[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone - bool tRight = MoverParameters->iLights[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej - if (Controller == Humandriver) { - - auto const dps{MoverParameters->currentDimPosition()}; - - // domyślnie - HighBeamLights = false; - DimHeadlights = false; - - // obsługa OFF - if (dps.isOff) - { - //MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa - HighBeamLights = false; - DimHeadlights = false; - switch (MoverParameters->CabActive) - { - case end::front: - HeadlightsAoff = true; - break; - case end::rear: - HeadlightsBoff = true; - break; - default: - break; - } - } - else - { - switch (MoverParameters->CabActive) - { - case end::front: - HeadlightsAoff = false; - break; - case end::rear: - HeadlightsBoff = false; - break; - default: - break; - } - } - - // obsługa przyciemnionych - DimHeadlights = dps.isDimmed; - - // obsługa długich - if (dps.isHighBeam) - { - HighBeamLights = true; - } - } - - } - if( rear >= 0 ) { - auto const vehicleend{ iDirection > 0 ? end::rear : end::front }; - MoverParameters->iLights[ vehicleend ] = rear & iInventory[vehicleend]; - } -}; - -void TDynamicObject::SetLightDimmings() -{ - auto const vehicleend{iDirection > 0 ? end::front : end::rear}; - if (Controller == Humandriver) - { - - auto const dps{MoverParameters->currentDimPosition()}; - - // domyślnie - HighBeamLights = false; - DimHeadlights = false; - - // obsługa OFF - if (dps.isOff) - { - // MoverParameters->iLights[vehicleend] &= 0 | light::rearendsignals; // zostawiamy tylko tabliczki jesli sa - HighBeamLights = false; - DimHeadlights = false; - switch (vehicleend) - { - case end::front: - HeadlightsAoff = true; - break; - case end::rear: - HeadlightsBoff = true; - break; - default: - break; - } - } - else - { - switch (vehicleend) - { - case end::front: - HeadlightsAoff = false; - break; - case end::rear: - HeadlightsBoff = false; - break; - default: - break; - } - } - - // obsługa przyciemnionych - DimHeadlights = dps.isDimmed; - - // obsługa długich - if (dps.isHighBeam) - { - // obsługa długich - if (dps.isHighBeam) - { - HighBeamLights = true; - } - } - } -} - -bool TDynamicObject::has_signal_pc1_on() const { - - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; - auto const equippedlights { iInventory[ vehicleend ] }; - auto const pattern { equippedlights & ( light::headlight_left | light::headlight_right | light::headlight_upper ) }; - auto const patternfallback { equippedlights & ( light::auxiliary_left | light::auxiliary_right | light::headlight_upper ) }; - auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; - - return (pattern != 0 && activelights == pattern) || (hasauxiliarylights && activelights == patternfallback) || - (pattern == 0 && patternfallback == 0 && activelights == light::rearendsignals); // pc4 -} - -bool TDynamicObject::has_signal_pc2_on() const { - - auto const vehicleend { iDirection > 0 ? end::front : end::rear }; - auto const equippedlights { iInventory[ vehicleend ] }; - auto const pattern { equippedlights & ( light::redmarker_left | light::headlight_right | light::headlight_upper ) }; - auto const patternfallback { equippedlights & ( light::redmarker_left | light::auxiliary_right | light::headlight_upper ) }; - auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; - - return activelights == pattern || (hasauxiliarylights && activelights == patternfallback); -} - -bool TDynamicObject::has_signal_pc5_on() const { - - auto const vehicleend { iDirection > 0 ? end::rear : end::front }; - auto const equippedlights { iInventory[ vehicleend ] }; - auto const pattern { equippedlights & ( light::redmarker_left | light::redmarker_right ) }; - auto const patternfallback { equippedlights & light::rearendsignals }; - auto const activelights { MoverParameters->iLights[ vehicleend ] }; - - return (pattern != 0 && activelights == pattern) || (patternfallback != 0 && activelights == patternfallback); -} - -bool TDynamicObject::has_signal_on( int const Side, int const Pattern ) const { -/* - auto const vehicleend { iDirection > 0 ? Side : 1 - Side }; - auto const pattern { iInventory[ vehicleend ] & Pattern }; - - return ( MoverParameters->iLights[ vehicleend ] == pattern ); -*/ - return MoverParameters->iLights[Side] == (Pattern & iInventory[Side]); -} - -int TDynamicObject::DirectionSet(int d) -{ // ustawienie kierunku w składzie (wykonuje AI) - auto const lastdirection { iDirection }; - iDirection = d > 0 ? 1 : 0; // d:1=zgodny,-1=przeciwny; iDirection:1=zgodny,0=przeciwny; - - if( iDirection != lastdirection ) { - // direction was flipped, switch recorded servicable platform sides for potentially ongoing load exchange - auto const left { lastdirection > 0 ? 1 : 2 }; - auto const right { 3 - left }; - m_exchange.platforms = - ( ( m_exchange.platforms & left ) != 0 ? right : 0 ) - + ( ( m_exchange.platforms & right ) != 0 ? left : 0 ); - } - - if (MyTrack) - { // podczas wczytywania wstawiane jest AI, ale może jeszcze nie być toru - // AI ustawi kierunek ponownie po uruchomieniu silnika - update_neighbours(); - } - // informacja o położeniu następnego - return 1 - ( iDirection > 0 ? NextConnectedNo() : PrevConnectedNo() ); -}; - -// wskaźnik na poprzedni, nawet wirtualny -TDynamicObject * TDynamicObject::PrevAny() const { - return MoverParameters->Neighbours[ iDirection ^ 1 ].vehicle; -} -TDynamicObject * TDynamicObject::Prev(int C) const { - return MoverParameters->Couplers[iDirection ^ 1].CouplingFlag & C ? MoverParameters->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było -} -TDynamicObject * TDynamicObject::Next(int C) const { - return MoverParameters->Couplers[iDirection].CouplingFlag & C ? MoverParameters->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było -} - -// checks whether there's unbroken connection of specified type to specified vehicle -bool -TDynamicObject::is_connected( TDynamicObject const *Vehicle, coupling const Coupling ) const { - - auto *vehicle { this }; - if( vehicle == Vehicle ) { - // edge case, vehicle is always "connected" with itself - return true; - } - // check ahead, it's more likely the "owner" using this method is located there - while( ( vehicle = vehicle->Prev( Coupling ) ) != nullptr ) { - if( vehicle == Vehicle ) { - return true; - } - if( vehicle == this ) { - // edge case, looping consist - return false; - } - } - // start anew in the other direction - vehicle = this; - while( ( vehicle = vehicle->Next( Coupling ) ) != nullptr ) { - if( vehicle == Vehicle ) { - return true; - } - } - // no luck in either direction, give up - return false; -} - -// ustalenie następnego (1) albo poprzedniego (0) w składzie bez względu na prawidłowość iDirection -TDynamicObject * -TDynamicObject::Neighbour(int &dir) { - - auto *neighbour { ( - MoverParameters->Couplers[ dir ].CouplingFlag != coupling::faux ? - MoverParameters->Neighbours[ dir ].vehicle : - nullptr ) }; - // nowa wartość - dir = 1 - MoverParameters->Neighbours[ dir ].vehicle_end; - - return neighbour; -}; - -// updates potential collision sources -void -TDynamicObject::update_neighbours() { - - for( int end = end::front; end <= end::rear; ++end ) { - - auto &neighbour { MoverParameters->Neighbours[ end ] }; - auto const &coupler { MoverParameters->Couplers[ end ] }; - - if( coupler.Connected != nullptr - && neighbour.vehicle != nullptr ) { - // physical connection with another vehicle locks down collision source on this end -// neighbour.vehicle = coupler.Connected; -// neighbour.vehicle_end = coupler.ConnectedNr; - neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, coupler.Connected ); - // take into account potential adapters attached to the couplers - auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; - neighbour.distance -= coupler.adapter_length; - neighbour.distance -= othercoupler.adapter_length; - } - else { - // if there's no connected vehicle check for potential collision sources in the vicinity - // NOTE: we perform a new scan on each update to ensure we always locate the nearest potential source - neighbour = neighbour_data(); - // 10m ~= 140 km/h at 4 fps + safety margin, potential distance between outer axles of involved vehicles - auto const scanrange { std::max( 10.0, std::abs( MoverParameters->V ) ) + 40.0 }; - auto const lookup { find_vehicle( end, scanrange ) }; - - if( false == std::get( lookup ) ) { continue; } - - neighbour.vehicle = std::get( lookup ); - neighbour.vehicle_end = std::get( lookup ); - neighbour.distance = std::get( lookup ); - - if( neighbour.vehicle - && neighbour.distance < (neighbour.vehicle->MoverParameters->CategoryFlag == 2 ? 50 : 100) ) { - // at short distances (re)calculate range between couplers directly - neighbour.distance = TMoverParameters::CouplerDist( MoverParameters, neighbour.vehicle->MoverParameters ); - // take into account potential adapters attached to the couplers - auto const &othercoupler { neighbour.vehicle->MoverParameters->Couplers[ neighbour.vehicle_end ] }; - neighbour.distance -= coupler.adapter_length; - neighbour.distance -= othercoupler.adapter_length; - } - } - } -} - -// locates potential collision source within specified range, scanning track in specified direction. returns: true if neighbour was located, false otherwise -// NOTE: reuses legacy code. TBD, TODO: review, refactor? -std::tuple -TDynamicObject::find_vehicle( int const Direction, double const Distance ) const { - - auto direction { ( Direction == end::front ? 1 : -1 ) }; - auto const initialdirection { direction }; // zapamiętanie kierunku poszukiwań na torze początkowym, względem sprzęgów - - auto const *track { RaTrackGet() }; - if( RaDirectionGet() < 0 ) { - // czy oś jest ustawiona w stronę Point1? - direction = -direction; - } - - // (teraz względem toru) - auto const mycoupler { ( initialdirection < 0 ? end::rear : end::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym - auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) - auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi - auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler ) }; // zaczynamy szukać na tym samym torze - - if( foundobject == nullptr ) { - // jeśli nie ma na tym samym, szukamy po okolicy szukanie najblizszego toru z jakims obiektem - // praktycznie przeklejone z TraceRoute()... - if (direction >= 0) // uwzględniamy kawalek przeanalizowanego wcześniej toru - distance = track->Length() - RaTranslationGet(); // odległość osi od Point2 toru - else - distance = RaTranslationGet(); // odległość osi od Point1 toru - - while (distance < Distance) { - if (direction > 0) { - // w kierunku Point2 toru - if( track ? - track->iNextDirection : - false ) { - // jeśli następny tor jest podpięty od Point2 - direction = -direction; // to zmieniamy kierunek szukania na tym torze - } - if( track ) { - track = track->CurrentNext(); // potem dopiero zmieniamy wskaźnik - } - } - else { - // w kierunku Point1 - if( track ? - !track->iPrevDirection : - true ) { - // jeśli poprzedni tor nie jest podpięty od Point2 - direction = -direction; // to zmieniamy kierunek szukania na tym torze - } - if( track ) { - track = track->CurrentPrev(); // potem dopiero zmieniamy wskaźnik - } - } - if (track) { - // jesli jest kolejny odcinek toru - foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler); // przejrzenie pojazdów tego toru - if (foundobject) { - break; - } - } - else { - // jeśli toru nie ma, to wychodzimy - distance = Distance + 1.0; // koniec przeglądania torów - break; - } - } - } // Koniec szukania najbliższego toru z jakimś obiektem. - - if( foundobject == nullptr ) { return {}; } -/* - auto const *vehicle { MoverParameters }; - auto const *foundvehicle { foundobject->MoverParameters }; - if( ( false == TestFlag( track->iCategoryFlag, 1 ) ) - && ( distance > 50.0 ) ) { - // Ra: jeśli dwa samochody się mijają na odcinku przed zawrotką, to odległość między nimi nie może być liczona w linii prostej! - // NOTE: the distance is approximated, and additionally less accurate for cars heading in opposite direction - distance -= ( 0.5 * ( vehicle->Dim.L + foundvehicle->Dim.L ) ); - } - else if( distance < 100.0 ) { - // at short distances start to calculate range between couplers directly - // odległość do najbliższego pojazdu w linii prostej - distance = TMoverParameters::CouplerDist( vehicle, foundvehicle ); - } -*/ - return { foundobject, foundcoupler, distance, true }; -} - -TDynamicObject * TDynamicObject::FindPowered() -{ // taka proteza: - // chcę podłączyć kabinę EN57 bezpośrednio z silnikowym, aby nie robić tego przez ukrotnienie - // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka - // lepiej by było przesyłać komendy sterowania, co jednak wymaga przebudowy transmisji komend (LD) - // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą świecić się w rozrządczych - // dla EZT światłą czołowe będą "zapalane w silnikowym", ale widziane z rozrządczych - // również wczytywanie MMD powinno dotyczyć aktualnego członu - // problematyczna może być kwestia wybranej kabiny (w silnikowym...) - // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno jeździć dobrze - // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... - auto const coupling { MoverParameters->TrainType == dt_EZT || MoverParameters->TrainType == dt_DMU ? - coupling::permanent : - coupling::control }; - - auto *lookup { - find_vehicle( - coupling, - []( TDynamicObject * vehicle ) { - return vehicle->MoverParameters->Power > 1.0; } ) }; - - return lookup != nullptr ? lookup : this; // always return valid vehicle for backward compatibility -} - -TDynamicObject * -TDynamicObject::FindPantographCarrier() { - - // try first within a single unit, broaden to all vehicles under our control if first attempt fails - std::array const couplings = { coupling::permanent, coupling::control }; - - for( auto const coupling : couplings ) { - auto *result = - find_vehicle( - coupling, - []( TDynamicObject * vehicle ) { - return vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && vehicle->MoverParameters->EnginePowerSource.CollectorParameters.CollectorsNo > 0; } ); - if( result != nullptr ) { - return result; - } - } - // if we're still here, admit failure - return nullptr; -} - -//--------------------------------------------------------------------------- - -void TDynamicObject::ParamSet(int what, int into) -{ // ustawienie lokalnego parametru (what) na stan (into) - switch (what & 0xFF00) - { - case 0x0100: // to np. są drzwi, bity 0..7 określają numer 1..254 albo maskę - // dla 8 różnych - if (what & 1) // na razie mamy lewe oraz prawe, czyli używamy maskę 1=lewe, - // 2=prawe, 3=wszystkie - if( MoverParameters->Doors.instances[side::left].is_open ) - { // są otwarte - if (!into) // jeśli zamykanie - { - // dźwięk zamykania - } - } - else - { // są zamknięte - if (into) // jeśli otwieranie - { - // dźwięk otwierania - } - } - if (what & 2) // prawe działają niezależnie od lewych - if( MoverParameters->Doors.instances[side::right].is_open ) - { // są otwarte - if (!into) // jeśli zamykanie - { - // dźwięk zamykania - } - } - else - { // są zamknięte - if (into) // jeśli otwieranie - { - // dźwięk otwierania - } - } - break; - } -}; - -int TDynamicObject::RouteWish(TTrack *tr) -{ // zapytanie do AI, po którym - // segmencie (-6..6) jechać na - // skrzyżowaniu (tr) - return Mechanik ? Mechanik->CrossRoute(tr) : 0; // wg AI albo prosto -}; - -void TDynamicObject::play_mirror_sounds( side const Side, mirror_moves::event const Event ) { - - if( Event == mirror_moves::event::none ) { return; } - // as UpdateMirror(), only the mirrors of the occupied cab move - if( MoverParameters->CabOccupied == 0 ) { return; } - auto const cabend { MoverParameters->CabOccupied > 0 ? end::front : end::rear }; - for( auto &mirror : m_mirrorsounds ) { - if( mirror.placement != Side || mirror.end != cabend ) { continue; } - auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold }; - auto &other { Event == mirror_moves::event::unfolding ? mirror.fold : mirror.unfold }; - other.stop(); - sound.play( sound_flags::exclusive ); - } -} - -void TDynamicObject::DestinationClear() { - - if( false == DestinationSign.has_light ) { return; } // physical destination signs remain up until manually changed - // update_destinations() shows the blank sign in place of the missing destination - DestinationSign.destination = null_handle; - DestinationSign.script_sign.reset(); -} - -void TDynamicObject::DestinationSet(std::string const &to, std::string const &numer) { - // ustawienie stacji docelowej oraz wymiennej tekstury 4, jeśli istnieje plik - // w zasadzie, to każdy wagon mógłby mieć inną stację docelową - // zwłaszcza w towarowych, pod kątem zautomatyzowania maewrów albo pracy górki - // ale to jeszcze potrwa, zanim będzie możliwe, na razie można wpisać stację z - // rozkładu - - asDestination = to; - - if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } // jak są 4 tekstury wymienne, to nie zmieniać rozkładem - if( DestinationSign.sign == nullptr ) { return; } // no sign submodel, no problem - // a sign drawn for the previous destination - DestinationSign.script_sign.reset(); - - // now see if we can find any version of the destination texture - std::vector const destinations = { - numer, // try dedicated timetable sign first... - to }; // ...then generic destination sign - - for( auto const &destination : destinations ) { - - DestinationSign.destination = DestinationFind( destination ); - if( DestinationSign.destination != null_handle ) { - // got what we wanted, we're done here - return; - } - } - // if we didn't get static texture we might be able to make one - if( true == destination_set_script( numer ) ) { return; } - if( DestinationSign.script.empty() ) { return; } // no script so no way to make the texture - if( numer == "none" ) { return; } // blank or incomplete/malformed timetable, don't bother - - DestinationSign.destination = GfxRenderer->Fetch_Material( destination_request( DestinationSign.script, DestinationSign.instancing, DestinationSign.parameters ) ); -} - -std::string TDynamicObject::destination_request( std::string const &Script, std::string const &Instancing, std::string const &Parameters ) const { - - auto const trainname { [this]() -> std::string { - if( ctOwner != nullptr ) { return ctOwner->TrainName(); } - if( Mechanik != nullptr ) { return Mechanik->TrainName(); } - return "none"; } }; // shouldn't get here but, eh - auto const instance { [this, &Instancing]() -> std::string { - if( Instancing == "name" ) { return MoverParameters->Name; } - if( Instancing == "type" ) { return MoverParameters->TypeName; } - return "none"; } }; - - std::string signrequest { - "make:" - + Script - + "?" - // timetable include - + "$timetable=" + ( - ctOwner == nullptr ? - MoverParameters->Name : // leading vehicle, can point to it directly - ctOwner->Vehicle()->MoverParameters->Name ) // owned vehicle, safer to point to owner as carriages can have identical names - // basic instancing string - // NOTE: underscore doesn't have any magic meaning for the time being, it's just less likely to conflict with regular dictionary keys - + "&_id1=" + trainname() }; - // TBD, TODO: replace instancing with support for variables in extra parameters string? - if( false == Instancing.empty() ) { - signrequest += "&_id2=" + instance(); - } - // optionl extra parameters - if( false == Parameters.empty() ) { - signrequest += "&" + Parameters; - } - return signrequest; -} - -script_screens::screen_config const *TDynamicObject::script_destination( script_language &Language ) const { - - auto const &screens { Application.screens() }; - if( false == DestinationSign.lua.script.empty() && screens.runs( script_language::lua ) ) { - Language = script_language::lua; - return &DestinationSign.lua; - } - if( false == DestinationSign.wasm.script.empty() && screens.runs( script_language::wasm ) ) { - Language = script_language::wasm; - return &DestinationSign.wasm; - } - return nullptr; // no script sign, maybe a python one -} - -bool TDynamicObject::destination_set_script( std::string const &Numer ) { - - if( Numer == "none" ) { return false; } // blank or incomplete/malformed timetable, don't bother - auto language { script_language::lua }; - auto const *scriptsign { script_destination( language ) }; - if( scriptsign == nullptr ) { return false; } - - auto const signrequest { destination_request( scriptsign->script, scriptsign->instancing, scriptsign->parameters ) }; - auto const signmaterial { GfxRenderer->Fetch_Material( signrequest ) }; - if( signmaterial == null_handle ) { return false; } - auto &signtexture { GfxRenderer->Texture( GfxRenderer->Material( signmaterial )->GetTexture( 0 ) ) }; - - // vehicles showing the same request (one train, one instance) share the screen, as they share the texture - auto sign { Application.screens().acquire( { - .kind = script_screen_kind::external, - .language = language, - .script = scriptsign->script, - .key = signrequest, - .texture = &signtexture, - .frames = scriptsign->frames } ) }; - if( sign == nullptr ) { return false; } - - DestinationSign.destination = signmaterial; - DestinationSign.script_sign = std::move( sign ); - DestinationSign.script_request = signrequest.substr( signrequest.find( '?' ) + 1 ); - return true; -} - -std::shared_ptr TDynamicObject::draw_script_texture( std::string const &Name, material_handle const Material ) { - - if( false == Name.starts_with( "make:" ) || Material == null_handle ) { return nullptr; } - auto const query { Name.find( '?' ) }; - auto const script { Name.substr( 5, query == std::string::npos ? std::string::npos : query - 5 ) }; - auto const language { script_language_of( script ) }; - if( false == language.has_value() ) { return nullptr; } // a python texture, made by the texture itself - - auto &queue { Application.screens() }; - auto &texture { GfxRenderer->Texture( GfxRenderer->Material( Material )->GetTexture( 0 ) ) }; - auto screen { queue.acquire( { - .kind = script_screen_kind::external, - .language = *language, - .script = script, - .key = Name, - .texture = &texture, - .frames = 0 } ) }; - if( screen == nullptr ) { return nullptr; } - queue.submit( - screen, - query == std::string::npos ? - std::make_shared() : - std::make_shared( Name.substr( query + 1 ) ), - 0 ); - return screen; -} - -material_handle TDynamicObject::DestinationFind( std::string Destination ) { - - if( Destination.empty() ) { return null_handle; } - - // destination textures are kept in the vehicle's directory so we point the current texture path there - auto const currenttexturepath { Global.asCurrentTexturePath }; - Global.asCurrentTexturePath = asBaseDir; - - auto destinationhandle { null_handle }; - - if( Destination.starts_with("make:") ) { - // autogenerated texture - destinationhandle = GfxRenderer->Fetch_Material( Destination ); - } - else { - // regular texture - Destination = Bezogonkow( Destination ); // do szukania pliku obcinamy ogonki - // now see if we can find any version of the texture - std::vector const destinations { - Destination + '@' + MoverParameters->TypeName, - Destination }; - - for( auto const &destination : destinations ) { - auto material = TextureTest( ToLower( destination ) ); - if( false == material.empty() ) { - destinationhandle = GfxRenderer->Fetch_Material( material ); - break; - } - } - } - // whether we got anything, restore previous texture path - Global.asCurrentTexturePath = currenttexturepath; - - return destinationhandle; -} - -void TDynamicObject::announce( announcement_t const Announcement, bool const Chime ) { - - if( m_doorspeakers.empty() ) { return; } - - auto const *driver { ( - ctOwner != nullptr ? - ctOwner : - Mechanik ) }; - if( driver == nullptr ) { return; } - - auto const &timetable { driver->TrainTimetable() }; - auto const &announcements { m_pasystem.announcements }; - auto playchime { Chime }; - - if( announcements[ static_cast( Announcement ) ].empty() ) { - goto followup; - } - // if the announcement sound was defined queue playback - { - sound_source stopnamesound; - switch( Announcement ) { - case announcement_t::approaching: - case announcement_t::next: { - stopnamesound = timetable.next_stop_sound(); - break; - } - case announcement_t::current: { - stopnamesound = timetable.current_stop_sound(); - break; - } - case announcement_t::destination: { - stopnamesound = timetable.last_stop_sound(); - break; - } - default: { - break; - } - } - if( stopnamesound.empty() ) { - goto followup; - } - // potentially precede the announcement with a chime... - if( true == playchime - && false == announcements[static_cast(announcement_t::chime)].empty() ) { - m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( announcement_t::chime ) ] ); - playchime = false; - } - // ...then play the announcement itself - m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( Announcement ) ] ); - m_pasystem.announcement_queue.emplace_back( stopnamesound ); - } -followup: - // potentially follow up with another announcement - if( Announcement == announcement_t::next ) { - announce( announcement_t::destination, playchime ); - } -} - -void TDynamicObject::OverheadTrack(float o) -{ // ewentualne wymuszanie jazdy - // bezprądowej z powodu informacji - // w torze - if (ctOwner) // jeśli ma obiekt nadzorujący - { // trzeba zaktualizować mapę flag bitowych jazdy bezprądowej - if (o < 0.0) - { // normalna jazda po tym torze - ctOwner->iOverheadZero &= ~iOverheadMask; // zerowanie bitu - może pobierać prąd - ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf - } - else if (o > 0.0) - { // opuszczenie pantografów - ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu - ctOwner->iOverheadDown |= iOverheadMask; // ustawienie bitu - ma opuścić pantograf - } - else - { // jazda bezprądowa z podniesionym pantografem - ctOwner->iOverheadZero |= iOverheadMask; // ustawienie bitu - ma jechać bez pobierania prądu - ctOwner->iOverheadDown &= ~iOverheadMask; // zerowanie bitu - może podnieść pantograf - } - } -}; - -void -TDynamicObject::update_shake( double const Timedelta ) { - - ShakeStateBefore = ShakeState; - // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu - // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu - - // Ra: tu by się przydało uwzględnić rozkład sił: - // - na postoju horyzont prosto, kabina skosem - // - przy szybkiej jeździe kabina prosto, horyzont pochylony - - // McZapkie: najpierw policzę pozycję w/m kabiny - - // ABu: rzucamy kabina tylko przy duzym FPS! - // Mala histereza, zeby bez przerwy nie przelaczalo przy FPS~17 - // Granice mozna ustalic doswiadczalnie. Ja proponuje 14:20 - if( Global.iSlowMotion == 0 ) { // musi być pełna prędkość - - glm::dvec3 shakevector; - if( MoverParameters->EngineType == TEngineType::DieselElectric - || MoverParameters->EngineType == TEngineType::DieselEngine ) { - if( std::abs( MoverParameters->enrot ) > 0.0 ) { - // engine vibration - shakevector.x += - std::sin(MoverParameters->eAngle * 4.0) * Timedelta * - EngineShake.scale - // fade in with rpm above threshold - * std::clamp( - ( MoverParameters->enrot - EngineShake.fadein_offset ) * EngineShake.fadein_factor, - 0.0, 1.0 ) - // fade out with rpm above threshold - * std::lerp( - 1.0, 0.0, - std::clamp( - ( MoverParameters->enrot - EngineShake.fadeout_offset ) * EngineShake.fadeout_factor, - 0.0, 1.0 ) ); - } - } - - if( HuntingShake.fadein_begin > 0.f - && true == MoverParameters->TruckHunting ) { - // hunting oscillation - HuntingAngle = clamp_circular( HuntingAngle + 4.0 * HuntingShake.frequency * Timedelta * MoverParameters->Vel, 360.0 ); - auto const huntingamount = - std::lerp( - 0.0, 1.0, - std::clamp( - ( MoverParameters->Vel - HuntingShake.fadein_begin ) / ( HuntingShake.fadein_end - HuntingShake.fadein_begin ), - 0.0, 1.0 ) ); - shakevector.x += - std::sin(glm::radians(HuntingAngle)) * Timedelta * HuntingShake.scale - * huntingamount; - IsHunting = huntingamount > 0.025; - } - - if (FreeFlyModeFlag) - shakevector *= 0; - - auto const iVel { std::min( GetVelocity(), 150.0 ) }; - // an uneven track shakes the cab by itself, in place of the sway drawn from the curve and the jolts drawn at random, as far as it does - auto const replaced { track_uneven::replaced_shake( MyTrack != nullptr ? MyTrack->uneven_underway() : track_uneven::amounts {} ) }; - if( iVel > 0.5 ) { - // acceleration-driven base shake - shakevector += glm::dvec3( - replaced.sway ? 0.0 : -MoverParameters->AccN * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway - -MoverParameters->AccVert * Timedelta * Global.ShakingMultiplierUD, - -MoverParameters->AccSVBased * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration - // unevenness of the track under the outer axles - auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( MoverParameters->V * MoverParameters->V ) }; - shakevector += glm::dvec3( - -glm::dot( ride, vLeft ) * Timedelta * 5.0 * Global.ShakingMultiplierRL, - -ride.y * Timedelta * Global.ShakingMultiplierUD, - 0.0 ); - } - - auto shake { 1.25 * ShakeSpring.ComputateForces( shakevector, ShakeState.offset ) }; - - if( false == replaced.jolts && LocalRandom( iVel ) > 25.0 ) { - // extra shake at increased velocity - shake += ShakeSpring.ComputateForces( - glm::dvec3( - ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.x, - ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.y, - ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.z ) -// * (( 200 - DynamicObject->MyTrack->iQualityFlag ) * 0.0075 ) // scale to 75-150% based on track quality - * 1.25, - ShakeState.offset ); - } - shake *= 0.85; - - ShakeState.velocity -= ( shake + ShakeState.velocity * 100.0 ) * (double)( BaseShake.jolt_scale.x + BaseShake.jolt_scale.y + BaseShake.jolt_scale.z ) / 200.0; - - // McZapkie: - ShakeState.offset += ShakeState.velocity * Timedelta; - if( std::abs( ShakeState.offset.y ) > std::abs( BaseShake.jolt_limit ) ) { - ShakeState.velocity.y = -ShakeState.velocity.y; - } - } - else { // hamowanie rzucania przy spadku FPS - ShakeState.offset -= ShakeState.offset * std::min( Timedelta, 1.0 ); // po tym chyba potrafią zostać jakieś ułamki, które powodują zjazd - } -} - -bool -TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction ) const { - - // from the follower on its side of the vehicle, as the two can be on different tracks. They stand fAxleDist apart, at the bogie pivots, and - // the offset of the axle is the place of its wheel set, so the two of a bogie come out half of ADist to either side of the pivot - auto const &follower { Axle.offset >= 0.0 ? Axle0 : Axle1 }; - if( auto const railphase { follower.RailPhase( Axle.offset - std::copysign( 0.5 * fAxleDist, Axle.offset ) ) }; railphase >= 0.0 ) { - // the rails under the axle, which aren't always those under the track the vehicle is on - auto const passed { Axle.atjoints && std::abs( railphase - Axle.distance ) > 0.5 * follower.GetTrack()->fSoundDistance }; - Axle.distance = railphase; - Axle.atjoints = true; - return passed; - } - Axle.atjoints = false; - Axle.distance += Move * Direction; - if( Axle.distance >= 0 && Axle.distance <= dRailLength ) { - return false; - } - Axle.distance = clamp_circular( Axle.distance, dRailLength ); - return true; -} - -std::pair -TDynamicObject::shake_angles() const { - - return shake_angles( ShakeState ); -} - -std::pair -TDynamicObject::shake_angles( shake_state const &State ) const { - - return { - std::atan( State.velocity.x * BaseShake.angle_scale.x ), - std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; -} - -TDynamicObject::shake_state -TDynamicObject::shake_between( double const Fraction ) const { - - if( Fraction >= 1.0 ) { - return ShakeState; - } - auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { - return glm::dvec3 { - std::lerp( Before.x, After.x, Part ), - std::lerp( Before.y, After.y, Part ), - std::lerp( Before.z, After.z, Part ) }; } }; - auto const part { std::max( Fraction, 0.0 ) }; - return { - between( ShakeStateBefore.velocity, ShakeState.velocity, part ), - between( ShakeStateBefore.offset, ShakeState.offset, part ) }; -} - -void -TDynamicObject::powertrain_sounds::position( glm::vec3 const Location ) { - - auto const nullvector { glm::vec3() }; - std::vector enginesounds = { - &inverter, - &motor_relay, &dsbWejscie_na_bezoporow, &motor_parallel, &motor_shuntfield, &rsWentylator, - &engine, &engine_ignition, &engine_shutdown, &engine_revving, &engine_turbo, &oil_pump, &fuel_pump, &water_pump, &water_heater, &radiator_fan, &radiator_fan_aux, - &transmission, &rsEngageSlippery, &retarder - }; - for( auto sound : enginesounds ) { - if( sound->offset() == nullvector ) { - sound->offset( Location ); - } - } -} - -void -TDynamicObject::powertrain_sounds::render( TMoverParameters const &Vehicle, double const Deltatime ) { - - if( Vehicle.Power == 0 ) { return; } - - double frequency { 1.0 }; - double volume { 0.0 }; - - // oil pump - if( true == Vehicle.OilPump.is_active ) { - oil_pump - .pitch( oil_pump.m_frequencyoffset + oil_pump.m_frequencyfactor * 1.f ) - .gain( oil_pump.m_amplitudeoffset + oil_pump.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - oil_pump.stop(); - } - // fuel pump - if( true == Vehicle.FuelPump.is_active ) { - fuel_pump - .pitch( fuel_pump.m_frequencyoffset + fuel_pump.m_frequencyfactor * 1.f ) - .gain( fuel_pump.m_amplitudeoffset + fuel_pump.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - fuel_pump.stop(); - } - // water pump - if( true == Vehicle.WaterPump.is_active ) { - water_pump - .pitch( water_pump.m_frequencyoffset + water_pump.m_frequencyfactor * 1.f ) - .gain( water_pump.m_amplitudeoffset + water_pump.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - water_pump.stop(); - } - // water heater - if( true == Vehicle.WaterHeater.is_active ) { - water_heater - .pitch( water_heater.m_frequencyoffset + water_heater.m_frequencyfactor * 1.f ) - .gain( water_heater.m_amplitudeoffset + water_heater.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - water_heater.stop(); - } - // engine sounds - // ignition - if( engine_state_last != Vehicle.Mains ) { - - if( true == Vehicle.Mains ) { - // TODO: separate engine and main circuit - // engine activation - engine_shutdown.stop(); - engine_ignition - .pitch( engine_ignition.m_frequencyoffset + engine_ignition.m_frequencyfactor * 1.f ) - .gain( engine_ignition.m_amplitudeoffset + engine_ignition.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive ); - // main circuit activation - linebreaker_close - .pitch( linebreaker_close.m_frequencyoffset + linebreaker_close.m_frequencyfactor * 1.f ) - .gain( linebreaker_close.m_amplitudeoffset + linebreaker_close.m_amplitudefactor * 1.f ) - .play(); - } - else { - // engine deactivation - engine_ignition.stop(); - engine_shutdown.pitch( engine_shutdown.m_frequencyoffset + engine_shutdown.m_frequencyfactor * 1.f ) - .gain( engine_shutdown.m_amplitudeoffset + engine_shutdown.m_amplitudefactor * 1.f ) - .play( sound_flags::exclusive ); - // main circuit deactivation - linebreaker_open - .pitch( linebreaker_open.m_frequencyoffset + linebreaker_open.m_frequencyfactor * 1.f ) - .gain( linebreaker_open.m_amplitudeoffset + linebreaker_open.m_amplitudefactor * 1.f ) - .play(); - } - engine_state_last = Vehicle.Mains; - } - // main engine sound - if( true == Vehicle.Mains ) { - - if( std::abs(Vehicle.enrot) > 0.01 - // McZapkie-280503: zeby dla dumb dzialal silnik na jalowych obrotach - || Vehicle.EngineType == TEngineType::Dumb ) { - - // frequency calculation - auto const normalizer { ( - true == engine.is_combined() ? - // for combined engine sound we calculate sound point in rpm, to make .mmd files setup easier - // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range - 60.f * 0.01f : - // for legacy single-piece sounds the standard frequency calculation is left untouched - 1.f ) }; - frequency = - engine.m_frequencyoffset - + engine.m_frequencyfactor * std::abs( Vehicle.enrot ) * normalizer; - - if( Vehicle.EngineType == TEngineType::Dumb ) { - frequency -= 0.2 * Vehicle.EnginePower / ( 1 + Vehicle.Power * 1000 ); - } - - // base volume calculation - switch( Vehicle.EngineType ) { - // TODO: check calculated values - case TEngineType::DieselElectric: { - - volume = - engine.m_amplitudeoffset - + engine.m_amplitudefactor * ( - 0.25 * ( Vehicle.EnginePower / Vehicle.Power ) - + 0.75 * Vehicle.EngineRPMRatio() ); - break; - } - case TEngineType::DieselEngine: { - if( Vehicle.enrot > 0.0 ) { - volume = Vehicle.EnginePower > 0 ? engine.m_amplitudeoffset + engine.m_amplitudefactor * Vehicle.dizel_fill : - engine.m_amplitudeoffset + engine.m_amplitudefactor * std::fabs(Vehicle.enrot / Vehicle.dizel_nmax); - } - break; - } - default: { - volume = - engine.m_amplitudeoffset - + engine.m_amplitudefactor * ( Vehicle.EnginePower + std::fabs( Vehicle.enrot ) * 60.0 ); - break; - } - } - - if( engine_volume >= 0.05 ) { - - auto enginerevvolume { 0.f }; - if( Vehicle.EngineType == TEngineType::DieselElectric - || Vehicle.EngineType == TEngineType::DieselEngine ) { - // diesel engine revolutions increase; it can potentially decrease volume of base engine sound - if( engine_revs_last != -1.f ) { - // calculate potential recent increase of engine revolutions - auto const revolutionsperminute { Vehicle.enrot * 60 }; - auto const revolutionsdifference { revolutionsperminute - engine_revs_last }; - auto const idlerevolutionsthreshold { 1.01 * Vehicle.EngineIdleRPM() }; - engine_revs_change = std::max( 0.0, engine_revs_change - 2.5 * Deltatime ); - if( revolutionsperminute > idlerevolutionsthreshold - && revolutionsdifference > 1.0 * Deltatime ) { - engine_revs_change = std::clamp( engine_revs_change + 5.0 * Deltatime, 0.0, 1.25 ); - } - enginerevvolume = 0.8 * engine_revs_change; - } - engine_revs_last = Vehicle.enrot * 60; - - auto const enginerevfrequency { ( - true == engine_revving.is_combined() ? - // if the sound contains multiple samples we reuse rpm-based calculation from the engine - frequency : - engine_revving.m_frequencyoffset + 1.f * engine_revving.m_frequencyfactor ) }; - - if( enginerevvolume > 0.02 ) { - engine_revving - .pitch( enginerevfrequency ) - .gain( enginerevvolume ) - .play( sound_flags::exclusive ); - } - else { - engine_revving.stop(); - } - } // diesel engines - - // multi-part revving sound pieces replace base engine sound, single revving simply gets mixed with the base - auto const enginevolume { ( - enginerevvolume > 0.02 && true == engine_revving.is_combined() ? - std::max( 0.0, engine_volume - enginerevvolume ) : - engine_volume ) }; - engine - .pitch( frequency ) - .gain( enginevolume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } // enginevolume > 0.05 - } - else { - engine.stop(); - } - } - - if (Vehicle.Mains) { - float power = std::clamp(Vehicle.eimv_pr, 0.0, 1.0); - - fake_engine - .pitch(fake_engine.m_frequencyoffset + power * fake_engine.m_frequencyfactor) - .gain(fake_engine.m_amplitudeoffset + power * fake_engine.m_amplitudefactor) - .play(sound_flags::exclusive | sound_flags::looping); - } - else { - fake_engine.stop(); - } - - engine_volume = std::lerp( engine_volume, volume, 0.25 ); - if( engine_volume < 0.05 ) { - engine.stop(); - } - - // youBy - przenioslem, bo diesel tez moze miec turbo - if( Vehicle.TurboTest > 0 ) { - // udawanie turbo: - auto const pitch_diesel{Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ? Vehicle.enrot / Vehicle.dizel_nmax * Vehicle.dizel_fill : 1}; - auto const goalpitch { std::max( 0.025, ( /*engine_volume **/ pitch_diesel + engine_turbo.m_frequencyoffset ) * engine_turbo.m_frequencyfactor ) }; - auto const goalvolume { ( - Vehicle.MainCtrlPos >= Vehicle.TurboTest && Vehicle.enrot > 0.1 ? - std::max( 0.0, ( engine_turbo_pitch + engine_turbo.m_amplitudeoffset ) * engine_turbo.m_amplitudefactor ) : - 0.0 ) }; - auto const currentvolume { engine_turbo.gain() }; - auto const changerate { 0.4 * Deltatime }; - - engine_turbo_pitch = engine_turbo_pitch > goalpitch ? std::max(goalpitch, engine_turbo_pitch - changerate * 0.5) : std::min(goalpitch, engine_turbo_pitch + changerate); - - volume = currentvolume > goalvolume ? std::max(goalvolume, currentvolume - changerate) : std::min(goalvolume, currentvolume + changerate); - - engine_turbo - .pitch( 0.4 + engine_turbo_pitch * 0.4 ) - .gain( volume ); - - if( volume > 0.05 ) { - engine_turbo.play( sound_flags::exclusive | sound_flags::looping ); - } - else { - engine_turbo.stop(); - } - } - - if( Vehicle.dizel_engage > 0.1 ) { - if( std::abs( Vehicle.dizel_engagedeltaomega ) > 0.2 ) { - frequency = rsEngageSlippery.m_frequencyoffset + rsEngageSlippery.m_frequencyfactor * std::fabs( Vehicle.dizel_engagedeltaomega ); - volume = rsEngageSlippery.m_amplitudeoffset + rsEngageSlippery.m_amplitudefactor * Vehicle.dizel_engage; - } - else { - frequency = 1.f; // rsEngageSlippery.FA+0.7*rsEngageSlippery.FM*(fabs(mvControlled->enrot)+mvControlled->nmax); - volume = Vehicle.dizel_engage > 0.2 ? rsEngageSlippery.m_amplitudeoffset + 0.2 * rsEngageSlippery.m_amplitudefactor * (Vehicle.enrot / Vehicle.nmax) : 0.f; - } - - rsEngageSlippery - .pitch( frequency ) - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - rsEngageSlippery.stop(); - } - - if (Vehicle.hydro_R) { - float speed = std::abs(Vehicle.hydro_R_n); - - retarder - .pitch(retarder.m_frequencyoffset + speed * retarder.m_frequencyfactor) - .gain(retarder.m_amplitudeoffset + Vehicle.hydro_R_Fill * retarder.m_amplitudefactor); - - if (retarder.gain() > 0.01 && speed > 1 && Vehicle.hydro_R_ClutchActive) { - retarder.play(sound_flags::exclusive | sound_flags::looping); - } - else { - retarder.stop(); - } - } - - // motor sounds - volume = 0.0; - // generic traction motor sounds - if( false == motors.empty() ) { - - if( std::abs( Vehicle.nrot ) > 0.01 ) { - - auto const &motor { motors.front() }; - // frequency calculation - auto normalizer { 1.f }; - if( true == motor.is_combined() ) { - // for combined motor sound we calculate sound point in rpm, to make .mmd files setup easier - // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range - normalizer = 60.f * 0.01f; - } - auto const motorrevolutions { std::abs( Vehicle.nrot ) * Vehicle.Transmision.Ratio }; - frequency = - motor.m_frequencyoffset - + motor.m_frequencyfactor * motorrevolutions * normalizer; - - // base volume calculation - switch( Vehicle.EngineType ) { - case TEngineType::ElectricInductionMotor: { - volume = - motor.m_amplitudeoffset - + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 2 ); - break; - } - case TEngineType::ElectricSeriesMotor: { - volume = - motor.m_amplitudeoffset - + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 60.0 ); - break; - } - default: { - volume = - motor.m_amplitudeoffset - + motor.m_amplitudefactor * motorrevolutions * 60.0; - break; - } - } - - if( Vehicle.EngineType == TEngineType::ElectricSeriesMotor ) { - // volume variation - if( volume < 1.0 - && Vehicle.EnginePower < 100 ) { - - auto const volumevariation { LocalRandom( 100 ) * Vehicle.enrot / ( 1 + Vehicle.nmax ) }; - if( volumevariation < 2 ) { - volume += volumevariation / 200; - } - } - - if( Vehicle.DynamicBrakeFlag - && Vehicle.EnginePower > 0.1 ) { - // Szociu - 29012012 - jeżeli uruchomiony jest hamulec elektrodynamiczny, odtwarzany jest dźwięk silnika - volume += 0.8; - } - } - // scale motor volume based on whether they're active - motor_momentum = - std::clamp( - motor_momentum - - 1.0 * Deltatime // smooth out decay - + std::abs( Vehicle.Mm ) / 60.0 * Deltatime, - 0.0, 1.25 ); - volume *= std::max( 0.25f, motor_momentum ); - motor_volume = std::lerp( motor_volume, volume, 0.25 ); - if( motor_volume >= 0.05 ) { - // apply calculated parameters to all motor instances - for( auto &motor : motors ) { - motor - .pitch( frequency ) - .gain( motor_volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - // stop all motor instances - for( auto &motor : motors ) { - motor.stop(); - } - } - } - else { - // stop all motor instances - motor_volume = 0.0; - for( auto &motor : motors ) { - motor.stop(); - } - } - } - // inverter-specific traction motor sounds - if( false == acmotors.empty() ) { - - if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { - if( Vehicle.InverterFrequency > 0.001 ) { - - for( auto &motor : acmotors ) { - motor - .pitch( motor.m_frequencyoffset + motor.m_frequencyfactor * Vehicle.InverterFrequency ) - .gain( motor.m_amplitudeoffset + motor.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr ) ) ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - } - else { - for( auto &motor : acmotors ) { - motor.stop(); - } - } - } - } - // motor blowers - if( false == motorblowers.empty() ) { - for( auto &blowersound : motorblowers ) { - // match the motor blower and the sound source based on whether they're located in the front or the back of the vehicle - auto const &blower { Vehicle.MotorBlowers[ ( blowersound.offset().z > 0 ? end::front : end::rear ) ] }; - // TODO: for the sounds with provided bookends invoke stop() when the stop is triggered and revolutions start dropping, instead of after full stop - if( blower.revolutions > 1 ) { - // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments - auto const revolutionmodifier { Vehicle.MotorBlowers[end::front].speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; - blowersound - .pitch( - true == blowersound.is_combined() ? - blower.revolutions * 0.01f : - blowersound.m_frequencyoffset + blowersound.m_frequencyfactor * revolutionmodifier ) - .gain( blowersound.m_amplitudeoffset + blowersound.m_amplitudefactor * revolutionmodifier ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - blowersound.stop(); - } - } - } - // inverter sounds - if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { - if( Vehicle.InverterFrequency > 0.001 ) { - - volume = inverter.m_amplitudeoffset + inverter.m_amplitudefactor * std::sqrt( std::abs( Vehicle.eimv_pr) ); - - inverter - .pitch( inverter.m_frequencyoffset + inverter.m_frequencyfactor * Vehicle.InverterFrequency ) - .gain( volume ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - inverter.stop(); - } - } - // ventillator sounds - if( Vehicle.RventRot > 0.1 ) { - - rsWentylator - .pitch( rsWentylator.m_frequencyoffset + rsWentylator.m_frequencyfactor * Vehicle.RventRot ) - .gain( rsWentylator.m_amplitudeoffset + rsWentylator.m_amplitudefactor * Vehicle.RventRot ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // ...otherwise shut down the sound - rsWentylator.stop(); - } - // radiator fan sounds - if( Vehicle.EngineType == TEngineType::DieselEngine - || Vehicle.EngineType == TEngineType::DieselElectric ) { - - if( Vehicle.dizel_heat.rpmw > 0.1 ) { - // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 - radiator_fan - .pitch( 0.5 + radiator_fan.m_frequencyoffset + radiator_fan.m_frequencyfactor * Vehicle.dizel_heat.rpmw * 0.01 ) - .gain( 0.5 + radiator_fan.m_amplitudeoffset + 0.5 * radiator_fan.m_amplitudefactor * Vehicle.dizel_heat.rpmw * 0.01 ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // ...otherwise shut down the sound - radiator_fan.stop(); - } - - if( Vehicle.dizel_heat.rpmw2 > 0.1 ) { - // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 - radiator_fan_aux - .pitch( 0.5 + radiator_fan_aux.m_frequencyoffset + radiator_fan_aux.m_frequencyfactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) - .gain( 0.5 + radiator_fan_aux.m_amplitudeoffset + 0.5 * radiator_fan_aux.m_amplitudefactor * Vehicle.dizel_heat.rpmw2 * 0.01 ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - // ...otherwise shut down the sound - radiator_fan_aux.stop(); - } - } - - // relay sounds - auto const soundflags { Vehicle.SoundFlag }; - if( TestFlag( soundflags, sound::relay ) ) { - // przekaznik - gdy bezpiecznik, automatyczny rozruch itp - if( true == TestFlag( soundflags, sound::shuntfield ) ) { - // shunt field - motor_shuntfield - .pitch( - true == motor_shuntfield.is_combined() ? - Vehicle.ScndCtrlActualPos * 0.01f : - motor_shuntfield.m_frequencyoffset + motor_shuntfield.m_frequencyfactor * 1.f ) - .gain( - motor_shuntfield.m_amplitudeoffset + ( - true == TestFlag( soundflags, sound::loud ) ? - 1.0f : - 0.8f ) - * motor_shuntfield.m_amplitudefactor ) - .play(); - } - else if( true == TestFlag( soundflags, sound::parallel ) ) { - // parallel mode - if( TestFlag( soundflags, sound::loud ) ) { - dsbWejscie_na_bezoporow.play(); - } - else { - motor_parallel.play(); - } - } - else { - // series mode - motor_relay - .pitch( - true == motor_relay.is_combined() ? - Vehicle.MainCtrlActualPos * 0.01f : - motor_relay.m_frequencyoffset + motor_relay.m_frequencyfactor * 1.f ) - .gain( - motor_relay.m_amplitudeoffset + ( - true == TestFlag( soundflags, sound::loud ) ? - 1.0f : - 0.8f ) - * motor_relay.m_amplitudefactor ) - .play(); - } - } - - if( Vehicle.Vel > 0.1 ) { - transmission - .pitch( transmission.m_frequencyoffset + transmission.m_frequencyfactor * Vehicle.Vel ) - .gain( transmission.m_amplitudeoffset + transmission.m_amplitudefactor * Vehicle.Vel ) - .play( sound_flags::exclusive | sound_flags::looping ); - } - else { - transmission.stop(); - } -} - - -namespace { - -// a train on the same track this close to the end of the player's train is taken into the physical coupler model [m] -constexpr double coupler_physics_reach { 200.0 }; -// and let go of once none of its vehicles is this close to the player's train [m]; farther than the reach, so that -// the trains don't switch to and fro between the models -constexpr double coupler_physics_release { 500.0 }; - -// the vehicle and those coupled with it, one after the other -std::vector -coupled_train( TDynamicObject *Vehicle ) { - - std::vector train { Vehicle }; - for( int direction = end::front; direction <= end::rear; ++direction ) { - auto *vehicle { Vehicle }; - auto side { direction }; - // a train of more vehicles than are on the tracks would be one coupled into a ring - while( train.size() < 10000 ) { - auto const &mover { *vehicle->MoverParameters }; - auto *next { mover.Neighbours[ side ].vehicle }; - if( next == nullptr - || ( mover.Couplers[ side ].CouplingFlag & coupling::coupler ) == 0 - || std::ranges::find( train, next ) != train.end() ) { - break; - } - train.emplace_back( next ); - // onwards from the end of the next vehicle away from this one - side = 1 - mover.Neighbours[ side ].vehicle_end; - vehicle = next; - } - } - return train; -} - -// the trains on the same track the player's train is closing in on: those found at its free ends, near enough -std::vector -trains_closing_in( std::vector const &Train ) { - - std::vector trains; - for( auto *vehicle : Train ) { - for( int side = end::front; side <= end::rear; ++side ) { - auto const &mover { *vehicle->MoverParameters }; - auto const &neighbour { mover.Neighbours[ side ] }; - if( neighbour.vehicle == nullptr - || ( mover.Couplers[ side ].CouplingFlag & coupling::coupler ) != 0 - || neighbour.distance > coupler_physics_reach - || std::ranges::find( Train, neighbour.vehicle ) != Train.end() ) { - continue; - } - std::ranges::copy( coupled_train( neighbour.vehicle ), std::back_inserter( trains ) ); - } - } - return trains; -} - -// whether any vehicle of the train is within the distance of any vehicle of the other one -bool -trains_within( std::vector const &Train, std::vector const &Other, double const Distance ) { - - return std::ranges::any_of( Train, [&]( TDynamicObject const *Vehicle ) { - return std::ranges::any_of( Other, [&]( TDynamicObject const *Othervehicle ) { - return glm::distance( Vehicle->GetPosition(), Othervehicle->GetPosition() ) <= Distance; } ); } ); -} - -} // namespace - -// the physical coupler model covers the player's train and the trains it closes in on, on the same track; the others -// keep the legacy model, as the AI drives them in it -void -vehicle_table::update_coupler_physics() const { - - if( false == Global.coupler_physics - || true == Global.coupler_physics_all ) { - return; - } - auto *player { simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr }; - std::vector train; - if( player != nullptr ) { - train = coupled_train( player ); - } - std::unordered_set covered { train.begin(), train.end() }; - for( auto *vehicle : trains_closing_in( train ) ) { - covered.insert( vehicle ); - } - - std::unordered_set checked; - for( auto *vehicle : m_items ) { - if( covered.contains( vehicle ) ) { - vehicle->MoverParameters->CouplerPhysics = true; - continue; - } - if( false == vehicle->MoverParameters->CouplerPhysics - || checked.contains( vehicle ) ) { - continue; - } - // a train taken in before stays in the model until it's far from the player's one, all of it alike - auto const other { coupled_train( vehicle ) }; - checked.insert( other.begin(), other.end() ); - if( false == trains_within( other, train, coupler_physics_release ) ) { - for( auto *othervehicle : other ) { - othervehicle->MoverParameters->CouplerPhysics = false; - } - } - } -} - -// legacy method, calculates changes in simulation state over specified time -void -vehicle_table::update( double Deltatime, int Iterationcount ) { - // Ra: w zasadzie to trzeba by utworzyć oddzielną listę taboru do liczenia fizyki - // na którą by się zapisywały wszystkie pojazdy będące w ruchu - // pojazdy stojące nie potrzebują aktualizacji, chyba że np. ktoś im zmieni nastawę hamulca - // oddzielną listę można by zrobić na pojazdy z napędem, najlepiej posortowaną wg typu napędu - // what the update goes through, for the debug panel. the counts are of the last call in the frame - auto &counts { Timer::subsystem.vehicles }; - counts.all = static_cast( m_items.size() ); - counts.enabled = counts.road = counts.ai = counts.active = 0; - counts.kind = {}; - counts.standing = {}; - counts.awake = {}; - counts.steps += static_cast( std::max( Iterationcount, 1 ) ); - // the kind of each vehicle: rail or road, near the camera or farther. the time of each vehicle in the loops below goes to its - // kind, measured from the end of the one before it - static std::vector kinds; - kinds.resize( m_items.size() ); - // road vehicles far from the camera with nobody inside go by one step of the physics in the frame, as long as all the steps - // together (Global.physics_roadlod): their movement goes on, in coarser steps nobody is close enough to tell - static std::vector coarse; - coarse.assign( m_items.size(), 0 ); - auto const camera { Global.pCamera.Pos }; - for( std::size_t index = 0; index < m_items.size(); ++index ) { - auto const *vehicle { m_items[ index ] }; - auto const road { ( vehicle->MoverParameters->CategoryFlag & 2 ) != 0 }; - auto const distant { glm::length2( vehicle->GetPosition() - camera ) > Timer::subsystem.VEHICLE_NEAR * Timer::subsystem.VEHICLE_NEAR }; - kinds[ index ] = static_cast( ( road ? 2 : 0 ) + ( distant ? 1 : 0 ) ); - coarse[ index ] = static_cast( Global.physics_roadlod && road && distant && ( false == vehicle->MechInside ) && ( Iterationcount > 1 ) ); - if( false == vehicle->bEnabled ) { continue; } - ++counts.kind[ kinds[ index ] ]; - auto const *mover { vehicle->MoverParameters }; - if( mover->Vel < 0.01 ) { - ++counts.standing[ kinds[ index ] ]; - if( ( false == road ) && mover->PhysicActivation ) { - // the test of TMoverParameters::ComputeTotalForce(), part by part - auto const moving = []( neighbour_data const &Neighbour ) { - return ( Neighbour.vehicle != nullptr ) - && ( ( Neighbour.vehicle->MoverParameters->Vel > 0.0001 ) || Neighbour.vehicle->MoverParameters->accelerating() ); }; - auto &awake { counts.awake }; - ++awake.vehicles; - if( mover->CabActive != 0 ) { ++awake.cab; } - if( mover->Vel > 0.0001 ) { ++awake.speed; } - if( mover->accelerating() ) { ++awake.acceleration; } - if( mover->LastSwitchingTime < 5 ) { ++awake.switching; } - if( ( mover->TrainType == dt_EZT ) || ( mover->TrainType == dt_DMU ) ) { ++awake.multipleunit; } - if( moving( mover->Neighbours[ end::front ] ) || moving( mover->Neighbours[ end::rear ] ) ) { ++awake.neighbour; } - } - } - } - auto const lap = [ & ]( std::size_t const Index, std::array &Times, std::chrono::steady_clock::time_point &Mark ) { - auto const now { std::chrono::steady_clock::now() }; - if( Index < kinds.size() ) { - Times[ kinds[ Index ] ].add( std::chrono::duration( now - Mark ).count() ); - } - Mark = now; - }; - for( auto const *vehicle : m_items ) { - if( false == vehicle->bEnabled ) { continue; } - ++counts.enabled; - if( vehicle->MoverParameters->CategoryFlag & 2 ) { ++counts.road; } - if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag ) { ++counts.ai; } - if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { ++counts.active; } - } - - Timer::subsystem.vehicles_prepare.start(); - for( auto *vehicle : m_items ) { - if( false == vehicle->bEnabled ) { continue; } - // Ra: zmienić warunek na sprawdzanie pantografów w jednej zmiennej: czy pantografy i czy podniesione - if( vehicle->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { - update_traction( vehicle ); - } - vehicle->MoverParameters->ComputeConstans(); - vehicle->update_neighbours(); - } - update_coupler_physics(); - Timer::subsystem.vehicles_prepare.stop(); - Timer::subsystem.vehicles_forces.start(); - auto const totaltime { Deltatime * Iterationcount }; // całkowity czas - // the steps of the physics on many threads (Global.performance_multithreading), as many as the work is worth: a thread for each - // STEPS_PER_THREAD steps of vehicles with the physics on, up to all the cores. not in a network session (network.server, - // .client), which keeps the draws of Random() in step across the machines: the threads have engines of their own. the messages - // to external programs (Global.iMultiplayer) don't mind - auto constexpr STEPS_PER_THREAD { 128 }; - std::size_t work { 0 }; - for( std::size_t index = 0; index < m_items.size(); ++index ) { - auto const *vehicle { m_items[ index ] }; - if( vehicle->MoverParameters->PhysicActivation || vehicle->MechInside ) { - work += ( coarse[ index ] != 0 ? 1 : static_cast( std::max( Iterationcount, 1 ) ) ); - } - } - auto const network { ( false == Global.network_servers.empty() ) || Global.network_client.has_value() }; - auto const threads { ( - network ? - 1 : - std::min( worker_pool::capacity(), std::max( 1, ( work + STEPS_PER_THREAD / 2 ) / STEPS_PER_THREAD ) ) ) }; - // what keeps them in one thread, for the debug panel - counts.capacity = static_cast( worker_pool::capacity() ); - counts.singlethread = ( - false == Global.performance_multithreading ? std::string{ "performance.multithreading off" } : - network ? std::string{ "network session" } : - threads <= 1 ? std::string{ "too little work" } : - std::string{} ); - counts.threads = 1; - auto const parallel { ( threads > 1 ) && update_steps_parallel( Deltatime, Iterationcount, coarse, threads ) }; - if( parallel ) { - counts.threads = static_cast( threads ); - } - else { - if( threads > 1 ) { - counts.singlethread = "a vehicle coupled with one it doesn't see"; - } - auto mark { std::chrono::steady_clock::now() }; - if( Iterationcount > 1 ) { - // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja - for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { - std::size_t index { 0 }; - for( auto *vehicle : m_items ) { - if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { - vehicle->UpdateForce( Deltatime ); - } - lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); - } - index = 0; - for( auto *vehicle : m_items ) { - if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { - vehicle->FastUpdate( Deltatime ); - } - lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); - } - } - } - { - std::size_t index { 0 }; - for( auto *vehicle : m_items ) { - // the vehicles going by one step take it with the time of all of them - auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; - vehicle->UpdateForce( coarsestep ? totaltime : Deltatime ); - lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); - } - } - } - Timer::subsystem.vehicles_forces.stop(); - - Timer::subsystem.vehicles_update.start(); - { - std::size_t index { 0 }; - auto mark { std::chrono::steady_clock::now() }; - for( auto *vehicle : m_items ) { - auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; - // Ra 2015-01: tylko tu przelicza sieć trakcyjną - vehicle->Update( coarsestep ? totaltime : Deltatime, totaltime ); - lap( index++, Timer::subsystem.vehicles_update_kind, mark ); - } - } - Timer::subsystem.vehicles_update.stop(); - - // jeśli jest coś do usunięcia z listy, to trzeba na końcu - erase_disabled(); - - // the odometers are saved now and then, a crash doesn't lose more than the last minute - m_odometersavetimer += totaltime; - if( m_odometersavetimer >= 60.0 ) { - save_odometers(); - } -} - -// records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) -void -vehicle_table::save_odometers() { - - m_odometersavetimer = 0.0; - auto &odometers { odometer::states() }; - for( auto const *vehicle : m_items ) { - if( vehicle->MoverParameters != nullptr ) { - odometer::record( odometers, vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); - } - } - odometer::save(); -} - -// the steps of the physics of vehicle_table::update() (UpdateForce() and FastUpdate() of each vehicle, Iterationcount times) on up -// to Threads threads of worker_pool. a step acts on the vehicle itself, on the ones coupled with it, and on the ones seen ahead or -// behind it (CollisionDetect() changes the speed of the other one); the movement along the tracks, the events and the sounds wait -// for Update(). so the vehicles are put in groups which act on nothing outside them, and each group goes through all its steps in -// one thread, its vehicles in their order, the groups at once: what doing them one by one gives. the groups of vehicles exchanging -// their load, which can load the models of it, are done in the main thread. Coarse: as in update(). returns false, having done -// nothing, when a vehicle is coupled with one it doesn't see next to it, which the groups don't account for -bool -vehicle_table::update_steps_parallel( double const Deltatime, int const Iterationcount, std::vector const &Coarse, std::size_t const Threads ) { - - auto const itemcount { m_items.size() }; - for( std::size_t index = 0; index < itemcount; ++index ) { - m_items[ index ]->m_tableindex = static_cast( index ); - } - // the groups, by joining the vehicles with the ones they act on. the coupled ones are those next to them - m_groupparent.resize( itemcount ); - std::iota( std::begin( m_groupparent ), std::end( m_groupparent ), 0u ); - auto const root = [ this ]( std::uint32_t Index ) { - while( m_groupparent[ Index ] != Index ) { - m_groupparent[ Index ] = m_groupparent[ m_groupparent[ Index ] ]; - Index = m_groupparent[ Index ]; - } - return Index; }; - for( std::size_t index = 0; index < itemcount; ++index ) { - auto const *mover { m_items[ index ]->MoverParameters }; - for( auto const end : { end::front, end::rear } ) { - auto const *neighbour { mover->Neighbours[ end ].vehicle }; - if( ( mover->Couplers[ end ].Connected != nullptr ) - && ( ( neighbour == nullptr ) || ( neighbour->MoverParameters != mover->Couplers[ end ].Connected ) ) ) { - return false; - } - if( neighbour == nullptr ) { continue; } - auto const other { neighbour->m_tableindex }; - if( ( other >= itemcount ) || ( m_items[ other ] != neighbour ) ) { - // not in the table, shouldn't happen - return false; - } - auto const left { root( static_cast( index ) ) }; - auto const right { root( other ) }; - if( left != right ) { - m_groupparent[ std::max( left, right ) ] = std::min( left, right ); - } - } - } - auto constexpr none { std::numeric_limits::max() }; - m_groupof.assign( itemcount, none ); - std::size_t groupcount { 0 }; - for( std::size_t index = 0; index < itemcount; ++index ) { - auto &group { m_groupof[ root( static_cast( index ) ) ] }; - if( group == none ) { - group = static_cast( groupcount++ ); - if( m_groups.size() < groupcount ) { m_groups.emplace_back(); } - m_groups[ group ].clear(); - } - m_groups[ group ].push_back( static_cast( index ) ); - } - // the groups done in the main thread, and the others largest first, for the threads to end close to one another - m_threadgroups.clear(); - m_maingroups.clear(); - std::size_t largest { 0 }; - for( std::size_t group = 0; group < groupcount; ++group ) { - largest = std::max( largest, m_groups[ group ].size() ); - auto const loading { std::any_of( - std::begin( m_groups[ group ] ), std::end( m_groups[ group ] ), - [ this ]( std::uint32_t const Index ) { - auto const *vehicle { m_items[ Index ] }; - return ( vehicle->MoverParameters->LoadStatus != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; - ( loading ? m_maingroups : m_threadgroups ).push_back( static_cast( group ) ); - } - std::sort( - std::begin( m_threadgroups ), std::end( m_threadgroups ), - [ this ]( std::uint32_t const Left, std::uint32_t const Right ) { - return m_groups[ Left ].size() > m_groups[ Right ].size(); } ); - auto &counts { Timer::subsystem.vehicles }; - counts.groups = static_cast( groupcount ); - counts.largestgroup = static_cast( largest ); - counts.maingroups = static_cast( m_maingroups.size() ); - - // all the steps of a group, in the order update() makes them - auto const totaltime { Deltatime * Iterationcount }; - auto const coarse = [ & ]( std::uint32_t const Index ) { - return ( Index < Coarse.size() ) && ( Coarse[ Index ] != 0 ); }; - auto const steps = [ & ]( std::uint32_t const Group ) { - auto const &members { m_groups[ Group ] }; - if( Iterationcount > 1 ) { - // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja - for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { - for( auto const index : members ) { - if( false == coarse( index ) ) { m_items[ index ]->UpdateForce( Deltatime ); } - } - for( auto const index : members ) { - if( false == coarse( index ) ) { m_items[ index ]->FastUpdate( Deltatime ); } - } - } - } - for( auto const index : members ) { - // the vehicles going by one step take it with the time of all of them - m_items[ index ]->UpdateForce( coarse( index ) ? totaltime : Deltatime ); - } }; - - Workers().run( - m_threadgroups.size(), Threads, - [ & ]( std::size_t const Group ) { - steps( m_threadgroups[ Group ] ); } ); - for( auto const group : m_maingroups ) { - steps( group ); - } - return true; -} - -// legacy method, checks for presence and height of traction wire for specified vehicle -void -vehicle_table::update_traction( TDynamicObject *Vehicle ) { - auto const vFront = Vehicle->VectorFront(); // wektor normalny dla płaszczyzny ruchu pantografu - auto const vUp = Vehicle->VectorUp(); // wektor pionu pudła (pochylony od pionu na przechyłce) - auto const vLeft = Vehicle->VectorLeft(); // wektor odległości w bok (odchylony od poziomu na przechyłce) - auto const position = Vehicle->GetPosition(); // współrzędne środka pojazdu - - for( int pantographindex = 0; pantographindex < Vehicle->iAnimType[ ANIM_PANTS ]; ++pantographindex ) { - // pętla po pantografach - auto *pantograph { Vehicle->pants[ pantographindex ].fParamPants }; - if( true == Vehicle->MoverParameters->Pantographs[ pantographindex ].is_active ) { - // jeśli pantograf podniesiony - auto const pant0 { position + vLeft * pantograph->vPos.z + vUp * pantograph->vPos.y + vFront * pantograph->vPos.x }; - if( pantograph->hvPowerWire != nullptr ) { - // jeżeli znamy drut z poprzedniego przebiegu - for( int attempts = 0; attempts < 30; ++attempts ) { - // sanity check. shouldn't happen in theory, but did happen in practice - if( pantograph->hvPowerWire == nullptr ) { break; } - - // powtarzane aż do znalezienia odpowiedniego odcinka na liście dwukierunkowej - if( pantograph->hvPowerWire->iLast & 0x3 ) { - // dla ostatniego i przedostatniego przęsła wymuszamy szukanie innego - // nie to, że nie ma, ale trzeba sprawdzić inne - pantograph->hvPowerWire = nullptr; - break; - } - if( pantograph->hvPowerWire->hvParallel ) { - // jeśli przęsło tworzy bieżnię wspólną, to trzeba sprawdzić pozostałe - // nie to, że nie ma, ale trzeba sprawdzić inne - pantograph->hvPowerWire = nullptr; - break; - } - // obliczamy wyraz wolny równania płaszczyzny (to miejsce nie jest odpowienie) - // podstawiamy równanie parametryczne drutu do równania płaszczyzny pantografu - // TODO: investigate this routine with reardriver/negative speed, does it picks the right wire? - auto const fRaParam = - -( glm::dot( pantograph->hvPowerWire->pPoint1, vFront ) - glm::dot( pant0, vFront ) ) - / glm::dot( pantograph->hvPowerWire->vParametric, vFront ); - - if( fRaParam < -0.001 ) { - // histereza rzędu 7cm na 70m typowego przęsła daje 1 promil - pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 0 ]; - continue; - } - if( fRaParam > 1.001 ) { - pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 1 ]; - continue; - } - // jeśli t jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft - // punkt styku płaszczyzny z drutem (dla generatora łuku el.) - auto const vStyk { pantograph->hvPowerWire->pPoint1 + fRaParam * pantograph->hvPowerWire->vParametric }; - auto const vGdzie { vStyk - pant0 }; // wektor - // odległość w pionie musi być w zasięgu ruchu "pionowego" pantografu - // musi się mieścić w przedziale ruchu pantografu - auto const fVertical { glm::dot( vGdzie, vUp ) }; - // odległość w bok powinna być mniejsza niż pół szerokości pantografu - // to się musi mieścić w przedziale zależnym od szerokości pantografu - auto const fHorizontal { std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth }; - // jeśli w pionie albo w bok jest za daleko, to dany drut jest nieużyteczny - if( fHorizontal <= 0.0 ) { - // koniec pętli, aktualny drut pasuje - pantograph->PantTraction = fVertical; - break; - } - else { - // the wire is outside contact area and as of now we don't have good detection of parallel sections - // as such there's no guaratee there isn't parallel section present. - // therefore we don't bother checking if the wire is still within range of guide horns - // but simply force area search for potential better option - pantograph->hvPowerWire = nullptr; - break; - } - } - } - - if( pantograph->hvPowerWire == nullptr ) { - // look in the region for a suitable traction piece if we don't already have any - simulation::Region->update_traction( Vehicle, pantographindex ); - } - - if( pantograph->hvPowerWire == nullptr - && false == Global.bLiveTraction ) { - // jeśli drut nie znaleziony ale można oszukiwać to dajemy coś tam dla picu - Vehicle->pants[ pantographindex ].fParamPants->PantTraction = 1.4; - } - } - else { - // pantograph is down - pantograph->hvPowerWire = nullptr; - } - } -} - -// legacy method, sends list of vehicles over network -void -vehicle_table::DynamicList( bool const Onlycontrolled ) const { - // odesłanie nazw pojazdów dostępnych na scenerii (nazwy, szczególnie wagonów, mogą się powtarzać!) - for( auto const *vehicle : m_items ) { - if( false == Onlycontrolled - || vehicle->Mechanik != nullptr ) { - // same nazwy pojazdów - multiplayer::WyslijString( vehicle->asName, 6 ); - } - } - // informacja o końcu listy - multiplayer::WyslijString( "none", 6 ); -} - -// maintenance; removes from tracks consists with vehicles marked as disabled -bool -vehicle_table::erase_disabled() { - - if( false == TDynamicObject::bDynamicRemove ) { return false; } - - // go through the list and retrieve vehicles scheduled for removal... - type_sequence disabledvehicles; - for( auto *vehicle : m_items ) { - if( false == vehicle->bEnabled ) { - disabledvehicles.emplace_back( vehicle ); - } - } - // ...now propagate removal flag through affected consists... - for( auto *vehicle : disabledvehicles ) { - TDynamicObject *coupledvehicle { vehicle }; - while( ( coupledvehicle = coupledvehicle->Next() ) != nullptr ) { - coupledvehicle->bEnabled = false; - } - // (try to) run propagation in both directions, it's simpler than branching based on direction etc - coupledvehicle = vehicle; - while( ( coupledvehicle = coupledvehicle->Prev() ) != nullptr ) { - coupledvehicle->bEnabled = false; - } - } - // ...then actually remove all disabled vehicles... - auto vehicleiter = std::begin( m_items ); - while( vehicleiter != std::end( m_items ) ) { - - auto *vehicle { *vehicleiter }; - - if( true == vehicle->bEnabled ) { - ++vehicleiter; - } - else { - // the distance the vehicle ran goes in the odometer store now, it doesn't depend on the vehicle being - // kept on the list until the next save (eu07/maszyna#72) - if( vehicle->MoverParameters != nullptr ) { - odometer::record( odometer::states(), vehicle->name(), vehicle->MoverParameters->HasDriverCab(), vehicle->MoverParameters->Odometer ); - } - if( vehicle->MyTrack != nullptr - && true == vehicle->MyTrack->RemoveDynamicObject(vehicle) ) { - vehicle->MyTrack = nullptr; - } - if( simulation::Train != nullptr - && simulation::Train->Dynamic() == vehicle ) { - // clear potential train binding - // TBD, TODO: kill vehicle sounds - simulation::Train = nullptr; - } - simulation::Trains.purge(vehicle->name()); - // remove potential entries in the light array - simulation::Lights.remove( vehicle ); - simulation::Blackbox.vehicle_removed( vehicle ); -/* - // finally get rid of the vehicle and its record themselves - // BUG: deleting the vehicle leaves dangling pointers in event->Activator and potentially elsewhere - // TBD, TODO: either mark 'dead' vehicles with additional flag, or delete the references as well - SafeDelete( vehicle ); - vehicleiter = m_items.erase( vehicleiter ); -*/ - ++vehicleiter; // NOTE: instead of the erase in the disabled section - } - } - // ...and call it a day - TDynamicObject::bDynamicRemove = false; - - return true; -} diff --git a/vehicle/DynObj.h b/vehicle/DynObj.h index 41601d3dc..adf70bb18 100644 --- a/vehicle/DynObj.h +++ b/vehicle/DynObj.h @@ -14,7 +14,11 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "interfaces/IMaterial.h" -#include "MOVER.h" +#include "model/materialdata.h" +#include "physics/vehicletypes.h" +#include "physics/derailment.h" +#include "physics/consistbraking.h" +#include "vehicle/derailmotion.h" #include "world/TrkFoll.h" #include "vehicle/Button.h" #include "vehicle/AirCoupler.h" @@ -22,12 +26,15 @@ http://mozilla.org/MPL/2.0/. #include "audio/sound.h" #include "world/Spring.h" #include "vehicle/mirrors.h" +#include "vehicle/doorwings.h" #include "scripting/scriptscreenrules.h" +#include #include #include class script_screen; // scripting/scriptscreens.h +namespace driver_figure { struct cab_place; } // vehicle/driverfigure.h enum class script_language; // scripting/scriptscreens.h #define EU07_SOUND_BOGIESOUNDS @@ -135,7 +142,7 @@ public: // destructor ~TAnim(); // methods - int TypeSet(int i, TMoverParameters currentMover, int fl = 0); // ustawienie typu + int TypeSet(int i, physics::Vehicle currentPhysics, int fl = 0); // ustawienie typu // members union { @@ -185,26 +192,17 @@ enum class announcement_t : int { }; // parameters for the material object, as currently used by various simulator models -struct material_data { - - int textures_alpha{ 0x30300030 }; // maska przezroczystości tekstur. default: tekstury wymienne nie mają przezroczystości - material_handle replacable_skins[ 5 ] = { null_handle, null_handle, null_handle, null_handle, null_handle }; // McZapkie:zmienialne nadwozie - int multi_textures{ 0 }; //<0 tekstury wskazane wpisem, >0 tekstury z przecinkami, =0 jedna - - // assigns specified texture or a group of textures to replacable texture slots - void assign( std::string const &Replacableskin ); -}; - class TDynamicObject { // klasa pojazdu friend opengl46_renderer; + friend class vehicle_table; public: static bool bDynamicRemove; // moved from ground //private: // położenie pojazdu w świecie oraz parametry ruchu glm::dvec3 vPosition; // Ra: pozycja pojazdu liczona zaraz po przesunięciu - glm::dvec3 vCoulpler[2]; // współrzędne sprzęgów do liczenia zderzeń czołowych + ByEnd vCoulpler; // współrzędne sprzęgów do liczenia zderzeń czołowych glm::dvec3 vUp, vFront, vLeft; // wektory jednostkowe ustawienia pojazdu int iDirection; // kierunek pojazdu względem czoła składu (1=zgodny,0=przeciwny) TTrackShape ts; // parametry toru przekazywane do fizyki @@ -224,13 +222,13 @@ public: std::string asTrack; // nazwa toru początkowego; wywalić? std::string asDestination; // dokąd pojazd ma być kierowany "(stacja):(tor)" glm::dmat4 mMatrix; // macierz przekształcenia do renderowania modeli - TMoverParameters *MoverParameters; // parametry fizyki ruchu oraz przeliczanie - inline TDynamicObject *NextConnected() { return MoverParameters->Neighbours[ end::rear ].vehicle; }; // pojazd podłączony od strony sprzęgu 1 (kabina -1) - inline TDynamicObject *PrevConnected() { return MoverParameters->Neighbours[ end::front ].vehicle; }; // pojazd podłączony od strony sprzęgu 0 (kabina 1) - inline TDynamicObject *NextConnected() const { return MoverParameters->Neighbours[ end::rear ].vehicle; }; // pojazd podłączony od strony sprzęgu 1 (kabina -1) - inline TDynamicObject *PrevConnected() const { return MoverParameters->Neighbours[ end::front ].vehicle; }; // pojazd podłączony od strony sprzęgu 0 (kabina 1) - inline int NextConnectedNo() const { return MoverParameters->Neighbours[ end::rear ].vehicle_end; } - inline int PrevConnectedNo() const { return MoverParameters->Neighbours[ end::front ].vehicle_end; } + physics::Vehicle *physics; // parametry fizyki ruchu oraz przeliczanie + TDynamicObject *NextConnected(); // pojazd podłączony od strony sprzęgu 1 (kabina -1) + TDynamicObject *PrevConnected(); // pojazd podłączony od strony sprzęgu 0 (kabina 1) + TDynamicObject *NextConnected() const; // pojazd podłączony od strony sprzęgu 1 (kabina -1) + TDynamicObject *PrevConnected() const; // pojazd podłączony od strony sprzęgu 0 (kabina 1) + int NextConnectedNo() const; + int PrevConnectedNo() const; // Dev tools void Reload(); @@ -244,6 +242,7 @@ public: TModel3d *mdLowPolyInt; // ABu 010305: wnetrze lowpoly std::array LowPolyIntCabs {}; // pointers to low fidelity version of individual driver cabs bool JointCabs{ false }; // flag for vehicles with multiple virtual 'cabs' sharing location and 3d model(s) + bool SingleDesk{ false }; // the joint cabs 1 and 2 are one desk: same model, same driver seat (driver figures, eu07/maszyna#535) std::vector mdAttachments; // additional models attached to main body struct destination_data { TSubModel *sign { nullptr }; // submodel mapped with replacable texture -4 @@ -304,6 +303,12 @@ private: void UpdateDoorRotate(TAnim *pAnim); // animacja drzwi - obrót void UpdateDoorFold(TAnim *pAnim); // animacja drzwi - składanie void UpdateDoorPlug(TAnim *pAnim); // animacja drzwi - odskokowo-przesuwne + // a wing with its own kind of animation, given in the .mmd (animdoor:), in place of the one of the .fiz + void UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ); + // sets the update of a door wing animation, for its own kind if the .mmd gives one, otherwise for the .fiz + void bind_door_animation( TAnim &Animation ); + // door wings animated in their own way, from the .mmd (eu07/maszyna#70) + std::vector m_doorwings; void UpdatePant(TAnim *pAnim); // animacja pantografu void UpdatePlatformTranslate(TAnim *pAnim); // doorstep animation, shift void UpdatePlatformRotate(TAnim *pAnim); // doorstep animation, rotate @@ -413,14 +418,14 @@ private: sound_source step_open { sound_placement::general }; sound_source step_close { sound_placement::general }; sound_source permit_granted { sound_placement::general }; - side placement {}; + VehicleSide placement {}; }; struct mirror_sounds { sound_source unfold { sound_placement::general }; sound_source fold { sound_placement::general }; - side placement {}; - int end {}; // of the vehicle, the mirror moves with the cab at this end occupied + VehicleSide placement {}; + VehicleEnd end {}; // of the vehicle, the mirror moves with the cab at this end occupied }; struct exchange_sounds { @@ -474,7 +479,21 @@ private: sound_source retarder { sound_placement::engine }; void position( glm::vec3 const Location ); - void render( TMoverParameters const &Vehicle, double const Deltatime ); + void render( physics::Vehicle const &Vehicle, double const Deltatime ); + private: + // the parts of render(), by subsystem + void renderPumpSounds( physics::Vehicle const &Vehicle ); + void renderIgnitionSounds( physics::Vehicle const &Vehicle ); + void renderEngineSounds( physics::Vehicle const &Vehicle, double const Deltatime ); + void renderTurboSound( physics::Vehicle const &Vehicle, double const Deltatime ); + void renderClutchSound( physics::Vehicle const &Vehicle ); + void renderRetarderSound( physics::Vehicle const &Vehicle ); + void renderTractionMotorSounds( physics::Vehicle const &Vehicle, double const Deltatime ); + void renderMotorBlowerSounds( physics::Vehicle const &Vehicle ); + void renderInverterSound( physics::Vehicle const &Vehicle ); + void renderFanSounds( physics::Vehicle const &Vehicle ); + void renderRelaySounds( physics::Vehicle const &Vehicle ); + void renderTransmissionSound( physics::Vehicle const &Vehicle ); }; // single source per door (pair) on the centreline struct doorspeaker_sounds { @@ -507,7 +526,7 @@ private: // members AirCoupler btCoupler1; // sprzegi AirCoupler btCoupler2; - std::array m_coupleradapters = { nullptr, nullptr }; + ByEnd m_coupleradapters = { nullptr, nullptr }; AirCoupler btCPneumatic1; // sprzegi powietrzne //yB - zmienione z Button na AirCoupler - krzyzyki AirCoupler btCPneumatic2; AirCoupler btCPneumatic1r; // ABu: to zeby nie bylo problemow przy laczeniu wagonow, @@ -596,12 +615,12 @@ private: // moving part and other external sounds sound_source m_startjolt { sound_placement::general }; // movement start jolt, played once on initial acceleration at slow enough speed bool m_startjoltplayed { false }; - std::array m_couplersounds; // always front and rear + ByEnd m_couplersounds; // always front and rear std::vector m_pantographsounds; // typically 2 but can be less (or more?) std::vector m_doorsounds; // can expect symmetrical arrangement, but don't count on it bool m_doorlocks { false }; // sound helper, current state of door locks std::vector m_mirrorsounds; - std::array m_mirrormotion; // indexed by side: right, left + BySide m_mirrormotion; // indexed by side: right, left sound_source sHorn1 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; sound_source sHorn2 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; sound_source sHorn3 { sound_placement::external, 5 * EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; @@ -634,7 +653,7 @@ private: bool renderme; // yB - czy renderowac float ModCamRot; - int iInventory[ 2 ] { 0, 0 }; // flagi bitowe posiadanych submodeli (np. świateł) + ByEnd iInventory { 0, 0 }; // flagi bitowe posiadanych submodeli (np. świateł) bool btnOn; // ABu: czy byly uzywane buttony, jesli tak, to po renderingu wylacz // bo ten sam model moze byc jeszcze wykorzystany przez inny obiekt! @@ -646,7 +665,7 @@ private: std::string asModel; private: - TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler ) const; + TDynamicObject *ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine = false ) const; void ABuCheckMyTrack(); std::string rTypeName; // nazwa typu pojazdu @@ -658,16 +677,13 @@ private: bool HeadlightsAoff{false}; // wygaszone swiatelki A bool HeadlightsBoff{false}; // wygaszone swiatelki B // checks whether there's unbroken connection of specified type to specified vehicle - bool is_connected( TDynamicObject const *Vehicle, coupling const Coupling = coupling::coupler ) const; + bool is_connected( TDynamicObject const *Vehicle, CouplingSet const couplings = Coupling::coupler ) const; TDynamicObject * PrevAny() const; - TDynamicObject * Prev(int C = -1) const; - TDynamicObject * Next(int C = -1) const; - void SetdMoveLen(double dMoveLen) { - MoverParameters->dMoveLen = dMoveLen; } - void ResetdMoveLen() { - MoverParameters->dMoveLen = 0; } - double GetdMoveLen() { - return MoverParameters->dMoveLen; } + TDynamicObject * Prev(CouplingSet couplings = CouplingSet::All()) const; // the vehicle coupled with any of the couplings given + TDynamicObject * Next(CouplingSet couplings = CouplingSet::All()) const; + void SetdMoveLen(double dMoveLen); + void ResetdMoveLen(); + double GetdMoveLen(); int GetPneumatic(bool front, bool red); void SetPneumatic(bool front, bool red); @@ -688,7 +704,7 @@ private: TDynamicObject * ABuScanNearestObject(glm::vec3 pos, TTrack *Track, double ScanDir, double ScanDist, int &CouplNr); - TDynamicObject * GetFirstDynamic(int cpl_type, int cf = 1); + TDynamicObject * GetFirstDynamic(VehicleEnd cpl_type, CouplingSet cf = Coupling::coupler); void ABuSetModelShake(glm::dvec3 mShake); // place in vehicle_table::m_items, set by its update for the groups of the physics steps on many threads @@ -740,12 +756,110 @@ private: // feeds the script destination sign with fresh data, when it is shown and due void update_script_destination(); bool Update(double dt, double dt1); +private: + // the steps of Update() (vehicle/dynamic/update.cpp) + void updateTrackParameters(); + void updateCouplingState(); + void updateTractionVoltage( double dt1 ); + void updateDriver( double dt1 ); + void distributeInductionBraking( double dt1 ); + void switchOffMainsWithoutBattery(); + double moveByPhysics( double dt, double dt1 ); + void updateAxleClatter( double dDOMoveLen ); + void applyJointJolt( int axleindex ); + void updateWheelAngles( double dt1 ); + void updateCurrentCollectors( double dt1 ); + void updatePantograph( int i, double fPantCurrent, double &fCurrent, double dt1 ); + void updatePantographVoltage( int i, TAnimPant const *p, double PantDiff, double fPantCurrent, double &fCurrent, double dt1 ); + void updatePantographMotion( int i, TAnimPant *p, double PantDiff, double dt1 ); + void playPantographDropSounds(); + void updateWipers( double dt1 ); + void updateMirrors( double dt1 ); +public: bool FastUpdate(double dt); void Move(double fDistance); void FastMove(double fDistance); + // physics.derailment new, the vehicle off the track (vehicle/derailmotion.h): the offset of its body from the axis of + // the track at the place nearest to it, to the left of its front positive [m]; 0 while it's on the track + double off_track_offset() const; + // the gap between the ends of the vehicle and the one at its End, as they meet off the track [m]: negative the + // buffers pressed in + double off_track_gap( VehicleEnd End ) const; +private: + // the axles moved along their tracks by the distance + void move_axles( double Distance ); + // the vehicle placed on the track by its axles + void place_by_axles(); + // the vehicle leaves the track: its motion on the ground begun, with the terrain around it + void begin_off_track(); + // the vehicle off the track moved on the ground, by the distance along its heading, in the time of the frame + void move_off_track( double Distance ); + // the terrain of the scenery around the vehicle off the track, as far as it may slide, for the ground under it: the + // one gathered for another vehicle where it covers that, gathered anew where it doesn't + void gather_off_track_terrain(); + // at rest it keeps only the terrain under it, the rest of what was gathered (shared with others, perhaps) let go + void crop_off_track_terrain(); + // the bed of the track at the axles, the level direction of the track there, and the side the derailment throws the + // vehicle to (1 the left of the front, -1 the right, 0 none): out of the curve of the track as designed, into it + // where a buckle bends the line the other way more (physics/derailment.h); on a straight track out of the turn of + // the path as it lies, a buckle on it + derail_motion::formation track_bed() const; + glm::dvec3 track_front() const; + int outward_side() const; + // the couplings of this vehicle off the track pull the vehicles coupled to it off the rails sideways, over the step + // of the time [s] + void pull_neighbours( double Time ); + // the scraping of the vehicle off the track, until it stops, and its state to the log every second + void update_off_track( double Deltatime ); + + std::shared_ptr m_offtrackterrain; // none in a scenery without terrain + glm::dvec2 m_offtrackmin { 0.0 }; // what the terrain was gathered for + glm::dvec2 m_offtrackmax { 0.0 }; + bool m_offtrackcropped { false }; // the terrain cut down to the one under it at rest + derail_motion::site m_offtracksite; + double m_offtracktime { 0.0 }; // of the frame, for the motion + double m_offtracklogdue { 0.0 }; + double m_offtracktotal { 0.0 }; // the time off the track [s] + double m_offtrackgathered { 0.0 }; // the time the terrain was gathered at [s] + double m_offtrackslowdue { 0.0 }; // till another warning of a slow frame [s] + double m_offtrackupdatedue { 0.0 }; // and of a slow update + double m_offtrackaxles { 0.0 }; // the move along the track the axles didn't make yet [m] + glm::dvec3 m_offtrackfrom { 0.0 }; // where the body was when its move went into the axles last + bool m_offtrackscraping { false }; // the scraping of the vehicle off the track plays, looped + // the most triangles of terrain taken around the vehicle off the track + static constexpr std::size_t off_track_triangles { 400000 }; + bool m_offtrackplaced { false }; // placed off the track: placed on it again once it's back on the rails + ByEnd m_pulledoff; // the distance the coupling of an end pulled the vehicle coupled there over the climbing limit + derailment::stretch m_struck; // on the rails: the distance a body off the track pushed it sideways over the climbing limit + // the model, the axes and the coupling points placed by the motion off the track + void place_off_track(); +public: void RenderSounds(); +private: + // the parts of RenderSounds(), by subsystem + void renderAuxiliarySounds(); + void renderBrakeCylinderSounds( double const brakepressureratio ); + void renderEpBrakeSounds( double const dt ); + void renderEmergencyBrakeSound(); + void renderAirReleaseSounds( double const dt, double const brakepressureratio ); + void renderSlipAndSandSounds(); + double renderBrakeFrictionSounds( double const dt ); + void renderSpringBrakeSounds(); + void renderLoadExchangeSounds(); + void renderDepartureSignalSounds(); + void renderAnnouncementSounds(); + void renderDoorSounds(); + void renderHornSounds(); + void renderRunningNoise( double const brakeforceratio ); + void renderWheelFlatSound(); + void renderCurveSound(); + void renderStartJoltSound(); + void renderPhysicsEventSounds(); + void renderCouplerSounds(); + void renderDerailmentSounds(); +public: // plays the sounds of the mirrors on the Side, of the occupied cab, starting the Event - void play_mirror_sounds( side const Side, mirror_moves::event const Event ); + void play_mirror_sounds( VehicleSide const Side, mirror_moves::event const Event ); inline glm::dvec3 GetPosition() const { return vPosition; }; // converts location from vehicle coordinates frame to world frame @@ -757,7 +871,7 @@ private: // pobranie współrzędnych tyłu inline glm::dvec3 RearPosition() const { return vCoulpler[iDirection]; }; - inline glm::dvec3 CouplerPosition( end const End ) const { + inline glm::dvec3 CouplerPosition( VehicleEnd const End ) const { return vCoulpler[ End ]; } inline glm::dvec3 AxlePositionGet() { return iAxleFirst ? @@ -785,12 +899,26 @@ private: return glm::value_ptr(mMatrix); }; inline double * Matrix() { return glm::value_ptr(mMatrix); }; - inline double GetVelocity() const { - return MoverParameters->Vel; }; - inline double GetLength() const { - return MoverParameters->Dim.L; }; - inline double GetWidth() const { - return MoverParameters->Dim.W; }; + double GetVelocity() const; + double GetLength() const; + double GetWidth() const; + // what the renderer reads of the physics of the vehicle (vehicle/dynamic/lights.cpp), so that it doesn't reach into it + TDimension const &Dimensions() const; + double Speed() const; // along the vehicle, signed [m/s] + int ActiveCab() const; // the cab the vehicle is driven from: 1 the front one, -1 the rear one, 0 none + float CompartmentLightIntensity() const; + double CouplerAdapterHeight( VehicleEnd End ) const; + double CouplerAdapterLength( VehicleEnd End ) const; + // the shares of the launch velocity and of the opacity of the smoke of the engine's exhaust, from the engine + void ExhaustScales( float &Velocity, float &Opacity ) const; + // the low voltage circuits have their power, for the lights + bool LowVoltagePowered() const; + // the lights switched on at an end, as the bits of light:: + int LightsSwitchedOn( VehicleEnd End ) const; + // the factor of the intensity of the headlights by the dimming and the high beam switches (DimHeadlights, HighBeamLights) + double HeadlightsMultiplier() const; + // the colour of the headlights, 0..1 + glm::vec3 HeadlightsColor() const; double radius() const; // calculates distance between event-starting axle and front of the vehicle double tracing_offset() const; @@ -799,6 +927,39 @@ private: // McZapkie-260202 void LoadMMediaFile(std::string const &TypeName, std::string const &ReplacableSkin); + // the parts of LoadMMediaFile (vehicle/dynamic/mmd.cpp): the sections of the .mmd file, their groups of keywords and the end of loading +private: + void loadModelsSection( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName, std::string const &ReplacableSkin ); + void loadModelsKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsGeneralKeyword( cParser &parser, std::string &token, std::string &asAnimName ); + bool loadModelsWheelKeyword( cParser &parser, std::string &token, std::string &asAnimName ); + bool loadModelsPantographLowerKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsPantographUpperKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsLinkageKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + bool loadModelsDoorKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ); + void loadModelsMirrorWiperKeyword( cParser &parser, std::string &token, std::string &asAnimName ); + void loadSoundsSection( cParser &parser, std::string &token ); + void loadSoundsKeyword( cParser &parser, std::string &token ); + bool loadSoundsEngineKeyword( cParser &parser, std::string &token ); + bool loadSoundsMotorKeyword( cParser &parser, std::string_view token ); + bool loadSoundsBrakeKeyword( cParser &parser, std::string_view token ); + bool loadSoundsDeviceKeyword( cParser &parser, std::string_view token ); + bool loadSoundsDoorKeyword( cParser &parser, std::string_view token ); + bool loadSoundsOtherKeyword( cParser &parser, std::string_view token ); + void loadSoundsAnnouncementKeyword( cParser &parser, std::string &token ); + void loadLocationsSection( cParser &parser, std::string &token ); + void loadInternalDataSection( cParser &parser, std::string &token ); + // cabplaces: what the section says of the cabs 1 and 2, for the driver figures + void loadInternalDataKeyword( cParser &parser, std::string &token, std::array &cabplaces ); + bool loadInternalDataDeviceKeyword( cParser &parser, std::string &token, std::array &cabplaces ); + bool loadInternalDataCouplerKeyword( cParser &parser, std::string_view token ); + bool loadInternalDataBufferKeyword( cParser &parser, std::string_view token ); + void loadInternalDataCabKeyword( cParser &parser, std::string_view token, std::array &cabplaces ); + void finishLoadingMMediaFile( std::string const &asFileName, std::string const &ReplacableSkin ); + void assignDefaultMMediaSounds(); + void initMMediaModels(); + void positionMMediaSoundEmitters(); +public: TModel3d *LoadMMediaFile_mdload( std::string const &Name ) const; inline double ABuGetDirection() const { // ABu. @@ -819,23 +980,23 @@ private: Axle1.GetTrack() : Axle0.GetTrack(); }; - void couple( int const Side ); - int uncouple( int const Side ); - bool attach_coupler_adapter( int const Side, bool const Enforce = false ); - bool remove_coupler_adapter( int const Side ); + void couple( VehicleEnd const Side ); + int uncouple( VehicleEnd const Side ); + bool attach_coupler_adapter( VehicleEnd const Side, bool const Enforce = false ); + bool remove_coupler_adapter( VehicleEnd const Side ); void RadioStop(); void Damage(char flag); void pants_up(); void SetLights(); void SetLightDimmings(); void RaLightsSet(int head, int rear); - int LightList( end const Side ) const { return iInventory[ Side ]; } + int LightList( VehicleEnd const Side ) const { return iInventory[ Side ]; } bool has_signal_pc1_on() const; bool has_signal_pc2_on() const; bool has_signal_pc5_on() const; - bool has_signal_on( int const Side, int const Pattern ) const; + bool has_signal_on( VehicleEnd const Side, int const Pattern ) const; void set_cab_lights( int const Cab, float const Level ); - TDynamicObject * FirstFind(int &coupler_nr, int cf = 1); + TDynamicObject * FirstFind(int &coupler_nr, CouplingSet cf = Coupling::coupler); float GetEPP(); // wyliczanie sredniego cisnienia w PG int DirectionSet(int d); // ustawienie kierunku w składzie // odczyt kierunku w składzie; returns 1 if true, -1 otherwise @@ -846,15 +1007,19 @@ private: TDynamicObject * Neighbour(int &dir); // updates potential collision sources void update_neighbours(); - // locates potential collision source within specified range, scanning its route in specified direction - auto find_vehicle( int const Direction, double const Range ) const -> std::tuple; + // physics.derailment new: the vehicle and the other one, one of them off the track, are in line, close enough + // across to run into each other + bool in_line_with( TDynamicObject const &Other ) const; + // locates potential collision source within specified range, scanning its route in specified direction. InLine: + // physics.derailment new, the scan goes on past a vehicle off the track beside the line (or beside this one off it) + auto find_vehicle( int const Direction, double const Range, bool const InLine = false ) const -> std::tuple; // locates potential vehicle connected with specific coupling type and satisfying supplied predicate template - auto find_vehicle( coupling const Coupling, Predicate_ const Predicate ) -> TDynamicObject *; + auto find_vehicle( CouplingSet const couplings, Predicate_ const Predicate ) -> TDynamicObject *; TDynamicObject * FindPowered(); TDynamicObject * FindPantographCarrier(); template - void for_each( coupling const Coupling, UnaryFunction_ const Function ); + void for_each( CouplingSet const couplings, UnaryFunction_ const Function ); void ParamSet(int what, int into); // zapytanie do AI, po którym segmencie skrzyżowania jechać int RouteWish(TTrack *tr); @@ -879,13 +1044,10 @@ private: float soundproofing( int const Placement, int const Listener ) const { return m_soundproofing[ Placement - 1 ][ Listener + 1 ]; } - double MED[9][8]; // lista zmiennych do debugowania hamulca ED - static std::string const MED_labels[ 8 ]; - std::ofstream MEDLogFile; // zapis parametrów hamowania - double MEDLogTime = 0; - double MEDLogInactiveTime = 0; - int MEDLogCount = 0; - double MED_oldFED = 0; + // the blending of the ED and EP brakes of the consist this vehicle leads, with induction motors + physics::ConsistBrakeBlending brakeBlending; + // the state of each pantograph the sounds last followed, up or down + ByEnd m_pantographsoundstate{ false, false }; // vehicle shaking calculations // TBD, TODO: make an object out of it @@ -948,6 +1110,13 @@ public: // records the odometer states of the vehicles and saves them for the next sessions void save_odometers(); + // physics.derailment new: the terrain gathered for a vehicle off the track which covers the rectangle from Min to Max + // (x, z), shared by the vehicles which slide over it; none where no vehicle has one. it lives as long as one of them + // keeps it + std::shared_ptr + off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ); + void + share_off_track_terrain( std::shared_ptr const &Terrain ); private: // maintenance; removes from tracks consists with vehicles marked as disabled @@ -965,25 +1134,41 @@ private: // the trains it closes in on void update_coupler_physics() const; + // the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did + void + update_brake_pipes( double const Deltatime ); + // physics.derailment new: the bodies of the vehicles off the track and those near them run into each other instead + // of into one another: the impulses of the hits, the bodies moved apart, a vehicle on the rails pushed off them; + // what the bodies overlap by goes to the log every second + void + update_off_track_contacts( double const Deltatime ); double m_odometersavetimer { 0.0 }; // simulation time since the odometers were last saved + // the most the bodies overlapped by, of the vehicles of update_off_track_contacts(), since it was logged last [m], and + // which ones; till the next line in the log [s]; once all of them came to rest it is logged no more + double m_overlapmost { 0.0 }; + std::string m_overlappair; + double m_overlapdue { 1.0 }; + bool m_overlaplogged { false }; + std::vector m_brakepipes; // the vehicles of update_brake_pipes(), kept for the memory + std::vector> m_offtrackterrains; // of off_track_terrain() }; template auto -TDynamicObject::find_vehicle( coupling const Coupling, Predicate_ const Predicate ) -> TDynamicObject * { +TDynamicObject::find_vehicle( CouplingSet const couplings, Predicate_ const Predicate ) -> TDynamicObject * { if( Predicate( this ) ) { return this; } // try first to look towards the rear auto *vehicle { this }; - while( ( vehicle = vehicle->Next( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { if( Predicate( vehicle ) ) { return vehicle; } } // if we didn't yet find a suitable vehicle try in the other direction vehicle = this; - while( ( vehicle = vehicle->Prev( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { if( Predicate( vehicle ) ) { return vehicle; } } // if we still don't have a match give up @@ -992,16 +1177,16 @@ TDynamicObject::find_vehicle( coupling const Coupling, Predicate_ const Predicat template void -TDynamicObject::for_each( coupling const Coupling, UnaryFunction_ const Function ) { +TDynamicObject::for_each( CouplingSet const couplings, UnaryFunction_ const Function ) { Function( this ); // walk first towards the rear auto *vehicle { this }; - while( ( vehicle = vehicle->Next( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { Function( vehicle ); } // then towards the front vehicle = this; - while( ( vehicle = vehicle->Prev( Coupling ) ) != nullptr ) { + while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { Function( vehicle ); } } diff --git a/vehicle/Gauge.cpp b/vehicle/Gauge.cpp index 52bf7795d..48b21ac1c 100644 --- a/vehicle/Gauge.cpp +++ b/vehicle/Gauge.cpp @@ -17,6 +17,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Gauge.h" #include "vehicle/gaugepositions.h" #include "vehicle/gaugeduplicates.h" +#include "vehicle/gaugewrap.h" #include "utilities/parser.h" #include "model/Model3d.h" #include "vehicle/DynObj.h" @@ -121,8 +122,9 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu Parser.getTokens(); if( Parser.peek() != "{" ) { // old fixed size config - // it has no scaletable:, drop the one of an earlier definition of the same control + // it has no scaletable: nor drag:, drop the ones of an earlier definition of the same control m_scaletable.clear(); + m_drag = universal_drag::direction::none; Parser >> submodelname; gaugetypename = Parser.getToken( true ); Parser.getTokens( 3, false ); @@ -168,6 +170,7 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu } gauge_scale::sort( scratchpad.scaletable ); m_scaletable = std::move( scratchpad.scaletable ); + m_drag = scratchpad.drag; // post-deserialization cleanup // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) if( scratchpad.soundproofing ) { @@ -209,15 +212,15 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu m_sourcemodel = nullptr; std::array sources { Owner->mdKabina, Owner->mdLowPolyInt }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodel = source->GetFromName( submodelname ) ) != nullptr ) { - // got what we wanted, bail out - m_sourcemodel = source; - break; + if( source == nullptr ) { + continue; } - // there's a possibility the default submodel was named with _off suffix - if( source != nullptr - && ( submodel = source->GetFromName( submodelname + "_off" ) ) != nullptr ) { + submodel = source->GetFromName( submodelname ); + if( submodel == nullptr ) { + // there's a possibility the default submodel was named with _off suffix + submodel = source->GetFromName( submodelname + "_off" ); + } + if( submodel != nullptr ) { // got what we wanted, bail out m_sourcemodel = source; break; @@ -229,8 +232,11 @@ void TGauge::Load( cParser &Parser, TDynamicObject const *Owner, double const mu // see if we can locate optional submodel for active state, with _on suffix TSubModel *submodelon { nullptr }; for( auto const *source : sources ) { - if( source != nullptr - && ( submodelon = source->GetFromName( submodelname + "_on" ) ) != nullptr ) { + if( source == nullptr ) { + continue; + } + submodelon = source->GetFromName( submodelname + "_on" ); + if( submodelon != nullptr ) { // got what we wanted, bail out break; } @@ -308,6 +314,16 @@ TGauge::Load_mapping( cParser &Input, TGauge::scratch_data &Scratchpad ) { >> soundproofing[ 5 ]; Scratchpad.soundproofing = soundproofing; } + else if( key == "drag:" ) { + // the mouse drags the control to any position between its ends, moving in the given direction to open it + // (MaSzyna-EU07/maszyna#62) + auto const value { Input.getToken( true, "\n\r\t ,;" ) }; + auto const drag { universal_drag::parse( value ) }; + if( false == drag.has_value() ) { + ErrorLog( "Bad model: unknown drag direction \"" + value + "\" of a cab control, it takes up, down, left, right, yes or no", logtype::model ); + } + Scratchpad.drag = drag.value_or( universal_drag::direction::none ); + } else if( key == "scaletable:" ) { // non-uniform scale in format [ value1 scaled1, value2 scaled2, ... ] return Load_scaletable( Input, Scratchpad ); @@ -386,6 +402,26 @@ TGauge::UpdateValue( float fNewDesired ) { return false; // no suitable sound was found } +void +TGauge::UpdateValueWrapped( float const fNewDesired, bool const Forward, int const Positions, std::optional &Fallbacksound ) { + + if( auto const turn { ( + m_animation == TGaugeAnimation::gt_Rotate && false == m_interpolatescale && m_scaletable.empty() ? + gauge_wrap::full_turn( m_scale, Positions ) : + std::nullopt ) }; + turn.has_value() ) { + // the knob stands the same one turn earlier (later), from there it turns on to the new position + // rather than all the way back, sounding the position it reaches + m_value = gauge_wrap::turned_round( m_value, *turn, Forward ); + m_targetvalue = gauge_wrap::turned_round( m_targetvalue, *turn, Forward ); + UpdateValue( fNewDesired, Fallbacksound ); + return; + } + // a switch that doesn't turn all the way round jumps to the new position, which still sounds + UpdateValue( fNewDesired, Fallbacksound ); + m_value = m_targetvalue; +} + void TGauge::PutValue(float fNewDesired) { // McZapkie-281102: natychmiastowe wpisanie wartosci m_targetvalue = fNewDesired; @@ -473,25 +509,25 @@ TGauge TGauge::MirrorCopy() const { return mirror; } -void TGauge::AssignFloat(float *fValue) +void TGauge::AssignFloat(float const *fValue) { m_datatype = 'f'; fData = fValue; }; -void TGauge::AssignDouble(double *dValue) +void TGauge::AssignDouble(double const *dValue) { m_datatype = 'd'; dData = dValue; }; -void TGauge::AssignInt(int *iValue) +void TGauge::AssignInt(int const *iValue) { m_datatype = 'i'; iData = iValue; }; -void TGauge::AssignBool(bool *bValue) +void TGauge::AssignBool(bool const *bValue) { m_datatype = 'b'; bData = bValue; diff --git a/vehicle/Gauge.h b/vehicle/Gauge.h index c16509f79..0bda4f2b6 100644 --- a/vehicle/Gauge.h +++ b/vehicle/Gauge.h @@ -12,6 +12,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" #include "vehicle/gaugescale.h" +#include "vehicle/universaldrag.h" enum class TGaugeAnimation { // typ ruchu @@ -46,14 +47,18 @@ public: void Load(cParser &Parser, TDynamicObject const *Owner, double const mul = 1.0); bool UpdateValue( float fNewDesired ); bool UpdateValue( float fNewDesired, std::optional &Fallbacksound ); + // sets a multi-position switch of Positions positions, turned on past its last position to the first one (Forward) + // or back past the first one to the last, to the position at fNewDesired. A knob which turns all the way round + // turns on the same way, others jump there; either way the position reached sounds + void UpdateValueWrapped( float fNewDesired, bool Forward, int Positions, std::optional &Fallbacksound ); void PutValue(float fNewDesired); float GetValue() const; float GetDesiredValue() const; void Update( bool const Power = true ); - void AssignFloat(float *fValue); - void AssignDouble(double *dValue); - void AssignInt(int *iValue); - void AssignBool(bool *bValue); + void AssignFloat(float const *fValue); + void AssignDouble(double const *dValue); + void AssignInt(int const *iValue); + void AssignBool(bool const *bValue); void UpdateValue(); void AssignState( bool const *State ); // copies of the control animated along with it, from its definitions marked duplicate: yes @@ -86,6 +91,10 @@ public: // true if the gauge was given a non-uniform scale (scaletable:) bool has_scaletable() const { return false == m_scaletable.empty(); } + // the direction the mouse drags the control in to any position between its ends (drag:, MaSzyna-EU07/maszyna#62), + // none for a control set only to its ends. a push control springs back, so it isn't dragged + universal_drag::direction drag() const { + return universal_drag::effective( m_drag, is_push() ); } // members TSubModel *SubModel { nullptr }; // McZapkie-310302: zeby mozna bylo sprawdzac czy zainicjowany poprawnie TSubModel *SubModelOn { nullptr }; // optional submodel visible when the state input is set @@ -96,6 +105,7 @@ private: std::optional< std::array > soundproofing; bool duplicate { false }; // the definition is a duplicate submodel of the control defined before std::vector scaletable; // as read, in the units of the config + universal_drag::direction drag { universal_drag::direction::none }; }; // methods // imports member data pair from the config file @@ -127,14 +137,15 @@ private: float m_endvalue { -1.f }; // end value of accepted value range bool m_interpolatescale { false }; std::vector m_scaletable; // optional non-uniform scale, sorted by value; replaces scale and offset + universal_drag::direction m_drag { universal_drag::direction::none }; // the mouse drags the control smoothly, drag: char m_datatype { '\0' }; // typ zmiennej parametru: f-float, d-double, i-int, b-bool; none until one is assigned union { // wskaźnik na parametr pokazywany przez animację - float *fData; - double *dData { nullptr }; - int *iData; - bool *bData; + float const *fData; + double const *dData { nullptr }; + int const *iData; + bool const *bData; }; bool m_state { false }; // visibility of the control's submodel(s); false : default, true: active bool const *m_stateinput { nullptr }; // bound variable determining visibility of the control's submodel(s) diff --git a/vehicle/Train.cpp b/vehicle/Train.cpp deleted file mode 100644 index ee1b07038..000000000 --- a/vehicle/Train.cpp +++ /dev/null @@ -1,13145 +0,0 @@ -/* -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/. -*/ -/* - MaSzyna EU07 locomotive simulator - Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others - -*/ - -#include "stdafx.h" -#include "vehicle/Train.h" -#include "vehicle/horn.h" -#include "vehicle/linebreaker.h" -#include "vehicle/holdcoillever.h" -#include "vehicle/odometer.h" -#include "vehicle/mainctrlact.h" - -#include "utilities/Globals.h" -#include "simulation/simulation.h" -#include "simulation/blackboxrecorder.h" -#include "world/Event.h" -#include "simulation/simulationtime.h" -#include "vehicle/Camera.h" -#include "utilities/Logs.h" -#include "model/MdlMngr.h" -#include "model/Model3d.h" -#include "utilities/Timer.h" -#include "vehicle/Driver.h" -#include "vehicle/DynObj.h" -#include "world/mtable.h" -#include "Console.h" -#include "application/application.h" -#include "rendering/renderer.h" -#include -#include -#include -#include -#include -/* -namespace input { - -extern user_command command; - -} -*/ -void control_mapper::clear() -{ - - *this = control_mapper(); -} - -void control_mapper::insert(TGauge const &Gauge, std::string const &Label) -{ - - if (Gauge.SubModel != nullptr) - { - m_controlnames.try_emplace(Gauge.SubModel, Label); - } - if (Gauge.SubModelOn != nullptr) - { - m_controlnames.try_emplace(Gauge.SubModelOn, Label); - } - // the duplicate submodels of a control (duplicate: yes) work the control as well (eu07/maszyna#527) - for (auto const &mirror : Gauge.mirrors()) - { - insert(mirror, Label); - } - - m_names.emplace(Label); -} - -std::string control_mapper::find(TSubModel const *Control) const -{ - - auto const lookup = m_controlnames.find(Control); - if (lookup != m_controlnames.end()) - { - return lookup->second; - } - else - { - return ""; - } -} - -bool control_mapper::contains(std::string const &Control) const -{ - - return m_names.contains(Control); -} - -void TTrain::screen_entry::deserialize(cParser &Input) -{ - - while (true == deserialize_mapping(Input)) - { - // all work done by while() - } -} - -bool TTrain::screen_entry::deserialize_mapping(cParser &Input) -{ - // token can be a key or block end - auto const key{Input.getToken(true, "\n\r\t ,;[]")}; - - if (true == key.empty() || key == "}") - { - return false; - } - - if (key == "{") - { - script = Input.getToken(); - } - else if (key == "target:") - { - target = Input.getToken(); - } - else if (key == "updatetime:") - { - updatetime = Input.getToken(); - } - else if (key == "parameters:") - { - parameters = dictionary_source(Input.getToken()); - } - else - { - // HACK: we expect this to be true only if the screen entry doesn't start with a { which means legacy configuration format - target = key; - script = Input.getToken(); - return false; - } - - return true; -} - -void TCab::Load(cParser &Parser) -{ - // NOTE: clearing control tables here is bit of a crutch, imposed by current scheme of loading compartments anew on each cab change - ggList.clear(); - btList.clear(); - - std::string token; - Parser.getTokens(); - Parser >> token; - if (token == "cablight:") - { - Parser.getTokens(9, false); - /* - Parser - >> dimm.r - >> dimm.g - >> dimm.b - >> intlit.r - >> intlit.g - >> intlit.b - >> intlitlow.r - >> intlitlow.g - >> intlitlow.b; - */ - Parser.getTokens(); - Parser >> token; - } - CabPos1.x = static_cast(std::stod(token)); - Parser.getTokens(5, false); - Parser >> CabPos1.y >> CabPos1.z >> CabPos2.x >> CabPos2.y >> CabPos2.z; - - bEnabled = true; - bOccupied = true; -} - -TGauge &TCab::Gauge(int n) -{ // pobranie adresu obiektu aniomowanego ruchem - /* - if (n < 0) - { // rezerwacja wolnego - ggList[iGauges].Clear(); - return ggList + iGauges++; - } - else if (n < iGauges) - return ggList + n; - return NULL; - */ - if (n < 0) - { - ggList.emplace_back(); - return ggList.back(); - } - else - { - return ggList[n]; - } -}; - -TButton &TCab::Button(int n) -{ // pobranie adresu obiektu animowanego wyborem 1 z 2 - /* - if (n < 0) - { // rezerwacja wolnego - return btList + iButtons++; - } - else if (n < iButtons) - return btList + n; - return NULL; - */ - if (n < 0) - { - btList.emplace_back(); - return btList.back(); - } - else - { - return btList[n]; - } -}; - -void TCab::Update(bool const Power) -{ // odczyt parametrów i ustawienie animacji submodelom - for (auto &gauge : ggList) - { - // animacje izometryczne - gauge.UpdateValue(); // odczyt parametru i przeliczenie na kąt - gauge.Update(); // ustawienie animacji - } - - for (auto &button : btList) - { - // animacje dwustanowe - button.Update(Power); // odczyt parametru i wybór submodelu - } -}; - -// NOTE: we're currently using universal handlers and static handler map but it may be beneficial to have these implemented on individual class instance basis -// TBD, TODO: consider this approach if we ever want to have customized consist behaviour to received commands, based on the consist/vehicle type or whatever -TTrain::commandhandler_map const TTrain::m_commandhandlers = { - - {user_command::aidriverenable, &TTrain::OnCommand_aidriverenable}, - {user_command::aidriverdisable, &TTrain::OnCommand_aidriverdisable}, - {user_command::jointcontrollerset, &TTrain::OnCommand_jointcontrollerset}, - {user_command::mastercontrollerincrease, &TTrain::OnCommand_mastercontrollerincrease}, - {user_command::mastercontrollerincreasefast, &TTrain::OnCommand_mastercontrollerincreasefast}, - {user_command::mastercontrollerdecrease, &TTrain::OnCommand_mastercontrollerdecrease}, - {user_command::mastercontrollerdecreasefast, &TTrain::OnCommand_mastercontrollerdecreasefast}, - {user_command::mastercontrollerset, &TTrain::OnCommand_mastercontrollerset}, - {user_command::secondcontrollerincrease, &TTrain::OnCommand_secondcontrollerincrease}, - {user_command::secondcontrollerincreasefast, &TTrain::OnCommand_secondcontrollerincreasefast}, - {user_command::secondcontrollerdecrease, &TTrain::OnCommand_secondcontrollerdecrease}, - {user_command::secondcontrollerdecreasefast, &TTrain::OnCommand_secondcontrollerdecreasefast}, - {user_command::secondcontrollerset, &TTrain::OnCommand_secondcontrollerset}, - {user_command::dynamicbrakecontrollerincrease, &TTrain::OnCommand_DynamicBrakeControllerIncrease}, - {user_command::dynamicbrakecontrollerincreasefast, &TTrain::OnCommand_DynamicBrakeControllerIncreaseFast}, - {user_command::dynamicbrakecontrollerdecrease, &TTrain::OnCommand_DynamicBrakeControllerDecrease}, - {user_command::dynamicbrakecontrollerdecreasefast, &TTrain::OnCommand_DynamicBrakeControllerDecreaseFast}, - {user_command::dynamicbrakecontrollerset, &TTrain::OnCommand_DynamicBrakeControllerSet}, - {user_command::notchingrelaytoggle, &TTrain::OnCommand_notchingrelaytoggle}, - {user_command::tempomattoggle, &TTrain::OnCommand_tempomattoggle}, - {user_command::mucurrentindicatorothersourceactivate, &TTrain::OnCommand_mucurrentindicatorothersourceactivate}, - {user_command::independentbrakeincrease, &TTrain::OnCommand_independentbrakeincrease}, - {user_command::independentbrakeincreasefast, &TTrain::OnCommand_independentbrakeincreasefast}, - {user_command::independentbrakedecrease, &TTrain::OnCommand_independentbrakedecrease}, - {user_command::independentbrakedecreasefast, &TTrain::OnCommand_independentbrakedecreasefast}, - {user_command::independentbrakeset, &TTrain::OnCommand_independentbrakeset}, - {user_command::independentbrakebailoff, &TTrain::OnCommand_independentbrakebailoff}, - {user_command::universalbrakebutton1, &TTrain::OnCommand_universalbrakebutton1}, - {user_command::universalbrakebutton2, &TTrain::OnCommand_universalbrakebutton2}, - {user_command::universalbrakebutton3, &TTrain::OnCommand_universalbrakebutton3}, - {user_command::trainbrakeincrease, &TTrain::OnCommand_trainbrakeincrease}, - {user_command::trainbrakedecrease, &TTrain::OnCommand_trainbrakedecrease}, - {user_command::trainbrakeset, &TTrain::OnCommand_trainbrakeset}, - {user_command::trainbrakecharging, &TTrain::OnCommand_trainbrakecharging}, - {user_command::trainbrakerelease, &TTrain::OnCommand_trainbrakerelease}, - {user_command::trainbrakefirstservice, &TTrain::OnCommand_trainbrakefirstservice}, - {user_command::trainbrakeservice, &TTrain::OnCommand_trainbrakeservice}, - {user_command::trainbrakefullservice, &TTrain::OnCommand_trainbrakefullservice}, - {user_command::trainbrakehandleoff, &TTrain::OnCommand_trainbrakehandleoff}, - {user_command::trainbrakeemergency, &TTrain::OnCommand_trainbrakeemergency}, - {user_command::trainbrakebasepressureincrease, &TTrain::OnCommand_trainbrakebasepressureincrease}, - {user_command::trainbrakebasepressuredecrease, &TTrain::OnCommand_trainbrakebasepressuredecrease}, - {user_command::trainbrakebasepressurereset, &TTrain::OnCommand_trainbrakebasepressurereset}, - {user_command::trainbrakeoperationtoggle, &TTrain::OnCommand_trainbrakeoperationtoggle}, - {user_command::manualbrakeincrease, &TTrain::OnCommand_manualbrakeincrease}, - {user_command::manualbrakedecrease, &TTrain::OnCommand_manualbrakedecrease}, - {user_command::alarmchaintoggle, &TTrain::OnCommand_alarmchaintoggle}, - {user_command::alarmchainenable, &TTrain::OnCommand_alarmchainenable}, - {user_command::alarmchaindisable, &TTrain::OnCommand_alarmchaindisable}, - {user_command::wheelspinbrakeactivate, &TTrain::OnCommand_wheelspinbrakeactivate}, - {user_command::sandboxactivate, &TTrain::OnCommand_sandboxactivate}, - {user_command::autosandboxtoggle, &TTrain::OnCommand_autosandboxtoggle}, - {user_command::autosandboxactivate, &TTrain::OnCommand_autosandboxactivate}, - {user_command::autosandboxdeactivate, &TTrain::OnCommand_autosandboxdeactivate}, - {user_command::epbrakecontroltoggle, &TTrain::OnCommand_epbrakecontroltoggle}, - {user_command::epbrakecontrolenable, &TTrain::OnCommand_epbrakecontrolenable}, - {user_command::epbrakecontroldisable, &TTrain::OnCommand_epbrakecontroldisable}, - {user_command::trainbrakeoperationmodeincrease, &TTrain::OnCommand_trainbrakeoperationmodeincrease}, - {user_command::trainbrakeoperationmodedecrease, &TTrain::OnCommand_trainbrakeoperationmodedecrease}, - {user_command::brakeactingspeedincrease, &TTrain::OnCommand_brakeactingspeedincrease}, - {user_command::brakeactingspeeddecrease, &TTrain::OnCommand_brakeactingspeeddecrease}, - {user_command::brakeactingspeedsetcargo, &TTrain::OnCommand_brakeactingspeedsetcargo}, - {user_command::brakeactingspeedsetpassenger, &TTrain::OnCommand_brakeactingspeedsetpassenger}, - {user_command::brakeactingspeedsetrapid, &TTrain::OnCommand_brakeactingspeedsetrapid}, - {user_command::brakeloadcompensationincrease, &TTrain::OnCommand_brakeloadcompensationincrease}, - {user_command::brakeloadcompensationdecrease, &TTrain::OnCommand_brakeloadcompensationdecrease}, - {user_command::mubrakingindicatortoggle, &TTrain::OnCommand_mubrakingindicatortoggle}, - {user_command::reverserincrease, &TTrain::OnCommand_reverserincrease}, - {user_command::reverserdecrease, &TTrain::OnCommand_reverserdecrease}, - {user_command::reverserforwardhigh, &TTrain::OnCommand_reverserforwardhigh}, - {user_command::reverserforward, &TTrain::OnCommand_reverserforward}, - {user_command::reverserneutral, &TTrain::OnCommand_reverserneutral}, - {user_command::reverserbackward, &TTrain::OnCommand_reverserbackward}, - {user_command::alerteracknowledge, &TTrain::OnCommand_alerteracknowledge}, - {user_command::cabsignalacknowledge, &TTrain::OnCommand_cabsignalacknowledge}, - {user_command::batterytoggle, &TTrain::OnCommand_batterytoggle}, - {user_command::batteryenable, &TTrain::OnCommand_batteryenable}, - {user_command::batterydisable, &TTrain::OnCommand_batterydisable}, - {user_command::cabactivationtoggle, &TTrain::OnCommand_cabactivationtoggle}, - {user_command::cabactivationenable, &TTrain::OnCommand_cabactivationenable}, - {user_command::cabactivationdisable, &TTrain::OnCommand_cabactivationdisable}, - {user_command::pantographcompressorvalvetoggle, &TTrain::OnCommand_pantographcompressorvalvetoggle}, - {user_command::pantographcompressorvalveenable, &TTrain::OnCommand_pantographcompressorvalveenable}, - {user_command::pantographcompressorvalvedisable, &TTrain::OnCommand_pantographcompressorvalvedisable}, - {user_command::pantographcompressoractivate, &TTrain::OnCommand_pantographcompressoractivate}, - {user_command::pantographtogglefront, &TTrain::OnCommand_pantographtogglefront}, - {user_command::pantographtogglerear, &TTrain::OnCommand_pantographtogglerear}, - {user_command::pantographraisefront, &TTrain::OnCommand_pantographraisefront}, - {user_command::pantographraiserear, &TTrain::OnCommand_pantographraiserear}, - {user_command::pantographlowerfront, &TTrain::OnCommand_pantographlowerfront}, - {user_command::pantographlowerrear, &TTrain::OnCommand_pantographlowerrear}, - - {user_command::wiperswitchincrease, &TTrain::OnCommand_wiperswitchincrease}, - {user_command::wiperswitchdecrease, &TTrain::OnCommand_wiperswitchdecrease}, - - {user_command::lightsset, &TTrain::OnCommand_lightsset}, - - {user_command::pantographlowerall, &TTrain::OnCommand_pantographlowerall}, - {user_command::pantographselectnext, &TTrain::OnCommand_pantographselectnext}, - {user_command::pantographselectprevious, &TTrain::OnCommand_pantographselectprevious}, - {user_command::pantographtoggleselected, &TTrain::OnCommand_pantographtoggleselected}, - {user_command::pantographraiseselected, &TTrain::OnCommand_pantographraiseselected}, - {user_command::pantographlowerselected, &TTrain::OnCommand_pantographlowerselected}, - {user_command::pantographvalvesupdate, &TTrain::OnCommand_pantographvalvesupdate}, - {user_command::pantographvalvesoff, &TTrain::OnCommand_pantographvalvesoff}, - {user_command::linebreakertoggle, &TTrain::OnCommand_linebreakertoggle}, - {user_command::linebreakeropen, &TTrain::OnCommand_linebreakeropen}, - {user_command::linebreakerclose, &TTrain::OnCommand_linebreakerclose}, - {user_command::linebreakertoggleb, &TTrain::OnCommand_linebreakertoggleremote}, - {user_command::linebreakeropenb, &TTrain::OnCommand_linebreakeropenremote}, - {user_command::linebreakercloseb, &TTrain::OnCommand_linebreakercloseremote}, - {user_command::linebreakertogglec, &TTrain::OnCommand_linebreakertoggleremote}, - {user_command::linebreakeropenc, &TTrain::OnCommand_linebreakeropenremote}, - {user_command::linebreakerclosec, &TTrain::OnCommand_linebreakercloseremote}, - {user_command::fuelpumptoggle, &TTrain::OnCommand_fuelpumptoggle}, - {user_command::fuelpumpenable, &TTrain::OnCommand_fuelpumpenable}, - {user_command::fuelpumpdisable, &TTrain::OnCommand_fuelpumpdisable}, - {user_command::oilpumptoggle, &TTrain::OnCommand_oilpumptoggle}, - {user_command::oilfuelpumptoggle, &TTrain::OnCommand_oilfuelpumptoggle}, - {user_command::oilpumpenable, &TTrain::OnCommand_oilpumpenable}, - {user_command::oilpumpdisable, &TTrain::OnCommand_oilpumpdisable}, - {user_command::waterheaterbreakertoggle, &TTrain::OnCommand_waterheaterbreakertoggle}, - {user_command::waterheaterbreakerclose, &TTrain::OnCommand_waterheaterbreakerclose}, - {user_command::waterheaterbreakeropen, &TTrain::OnCommand_waterheaterbreakeropen}, - {user_command::waterheatertoggle, &TTrain::OnCommand_waterheatertoggle}, - {user_command::waterheaterenable, &TTrain::OnCommand_waterheaterenable}, - {user_command::waterheaterdisable, &TTrain::OnCommand_waterheaterdisable}, - {user_command::waterpumpbreakertoggle, &TTrain::OnCommand_waterpumpbreakertoggle}, - {user_command::waterpumpbreakerclose, &TTrain::OnCommand_waterpumpbreakerclose}, - {user_command::waterpumpbreakeropen, &TTrain::OnCommand_waterpumpbreakeropen}, - {user_command::waterpumptoggle, &TTrain::OnCommand_waterpumptoggle}, - {user_command::waterpumpenable, &TTrain::OnCommand_waterpumpenable}, - {user_command::waterpumpdisable, &TTrain::OnCommand_waterpumpdisable}, - {user_command::watercircuitslinktoggle, &TTrain::OnCommand_watercircuitslinktoggle}, - {user_command::watercircuitslinkenable, &TTrain::OnCommand_watercircuitslinkenable}, - {user_command::watercircuitslinkdisable, &TTrain::OnCommand_watercircuitslinkdisable}, - {user_command::convertertoggle, &TTrain::OnCommand_convertertoggle}, - {user_command::converterenable, &TTrain::OnCommand_converterenable}, - {user_command::converterdisable, &TTrain::OnCommand_converterdisable}, - {user_command::convertertogglelocal, &TTrain::OnCommand_convertertogglelocal}, - {user_command::converteroverloadrelayreset, &TTrain::OnCommand_converteroverloadrelayreset}, - {user_command::compressortoggle, &TTrain::OnCommand_compressortoggle}, - {user_command::compressorenable, &TTrain::OnCommand_compressorenable}, - {user_command::compressordisable, &TTrain::OnCommand_compressordisable}, - {user_command::compressortogglelocal, &TTrain::OnCommand_compressortogglelocal}, - {user_command::compressorpresetactivatenext, &TTrain::OnCommand_compressorpresetactivatenext}, - {user_command::compressorpresetactivateprevious, &TTrain::OnCommand_compressorpresetactivateprevious}, - {user_command::compressorpresetactivatedefault, &TTrain::OnCommand_compressorpresetactivatedefault}, - {user_command::motorblowerstogglefront, &TTrain::OnCommand_motorblowerstogglefront}, - {user_command::motorblowerstogglerear, &TTrain::OnCommand_motorblowerstogglerear}, - {user_command::motorblowersdisableall, &TTrain::OnCommand_motorblowersdisableall}, - {user_command::coolingfanstoggle, &TTrain::OnCommand_coolingfanstoggle}, - {user_command::motorconnectorsopen, &TTrain::OnCommand_motorconnectorsopen}, - {user_command::motorconnectorsclose, &TTrain::OnCommand_motorconnectorsclose}, - {user_command::motordisconnect, &TTrain::OnCommand_motordisconnect}, - {user_command::motoroverloadrelaythresholdtoggle, &TTrain::OnCommand_motoroverloadrelaythresholdtoggle}, - {user_command::motoroverloadrelaythresholdsetlow, &TTrain::OnCommand_motoroverloadrelaythresholdsetlow}, - {user_command::motoroverloadrelaythresholdsethigh, &TTrain::OnCommand_motoroverloadrelaythresholdsethigh}, - {user_command::motoroverloadrelayreset, &TTrain::OnCommand_motoroverloadrelayreset}, - {user_command::universalrelayreset1, &TTrain::OnCommand_universalrelayreset}, - {user_command::universalrelayreset2, &TTrain::OnCommand_universalrelayreset}, - {user_command::universalrelayreset3, &TTrain::OnCommand_universalrelayreset}, - {user_command::heatingtoggle, &TTrain::OnCommand_heatingtoggle}, - {user_command::heatingenable, &TTrain::OnCommand_heatingenable}, - {user_command::heatingdisable, &TTrain::OnCommand_heatingdisable}, - {user_command::lightspresetactivatenext, &TTrain::OnCommand_lightspresetactivatenext}, - {user_command::lightspresetactivateprevious, &TTrain::OnCommand_lightspresetactivateprevious}, - {user_command::headlighttoggleleft, &TTrain::OnCommand_headlighttoggleleft}, - {user_command::headlightenableleft, &TTrain::OnCommand_headlightenableleft}, - {user_command::headlightdisableleft, &TTrain::OnCommand_headlightdisableleft}, - {user_command::headlighttoggleright, &TTrain::OnCommand_headlighttoggleright}, - {user_command::headlightenableright, &TTrain::OnCommand_headlightenableright}, - {user_command::headlightdisableright, &TTrain::OnCommand_headlightdisableright}, - {user_command::headlighttoggleupper, &TTrain::OnCommand_headlighttoggleupper}, - {user_command::headlightenableupper, &TTrain::OnCommand_headlightenableupper}, - {user_command::headlightdisableupper, &TTrain::OnCommand_headlightdisableupper}, - {user_command::redmarkertoggleleft, &TTrain::OnCommand_redmarkertoggleleft}, - {user_command::redmarkerenableleft, &TTrain::OnCommand_redmarkerenableleft}, - {user_command::redmarkerdisableleft, &TTrain::OnCommand_redmarkerdisableleft}, - {user_command::redmarkertoggleright, &TTrain::OnCommand_redmarkertoggleright}, - {user_command::redmarkerenableright, &TTrain::OnCommand_redmarkerenableright}, - {user_command::redmarkerdisableright, &TTrain::OnCommand_redmarkerdisableright}, - {user_command::headlighttogglerearleft, &TTrain::OnCommand_headlighttogglerearleft}, - {user_command::headlightenablerearleft, &TTrain::OnCommand_headlightenablerearleft}, - {user_command::headlightdisablerearleft, &TTrain::OnCommand_headlightdisablerearleft}, - {user_command::headlighttogglerearright, &TTrain::OnCommand_headlighttogglerearright}, - {user_command::headlightenablerearright, &TTrain::OnCommand_headlightenablerearright}, - {user_command::headlightdisablerearright, &TTrain::OnCommand_headlightdisablerearright}, - {user_command::headlighttogglerearupper, &TTrain::OnCommand_headlighttogglerearupper}, - {user_command::headlightenablerearupper, &TTrain::OnCommand_headlightenablerearupper}, - {user_command::headlightdisablerearupper, &TTrain::OnCommand_headlightdisablerearupper}, - {user_command::modernlightdimmerdecrease, &TTrain::OnCommand_modernlightdimmerdecrease}, - {user_command::modernlightdimmerincrease, &TTrain::OnCommand_modernlightdimmerincrease}, - {user_command::redmarkertogglerearleft, &TTrain::OnCommand_redmarkertogglerearleft}, - {user_command::redmarkerenablerearleft, &TTrain::OnCommand_redmarkerenablerearleft}, - {user_command::redmarkerdisablerearleft, &TTrain::OnCommand_redmarkerdisablerearleft}, - {user_command::redmarkertogglerearright, &TTrain::OnCommand_redmarkertogglerearright}, - {user_command::redmarkerenablerearright, &TTrain::OnCommand_redmarkerenablerearright}, - {user_command::redmarkerdisablerearright, &TTrain::OnCommand_redmarkerdisablerearright}, - {user_command::redmarkerstoggle, &TTrain::OnCommand_redmarkerstoggle}, - {user_command::endsignalstoggle, &TTrain::OnCommand_endsignalstoggle}, - {user_command::headlightsdimtoggle, &TTrain::OnCommand_headlightsdimtoggle}, - {user_command::headlightsdimenable, &TTrain::OnCommand_headlightsdimenable}, - {user_command::headlightsdimdisable, &TTrain::OnCommand_headlightsdimdisable}, - {user_command::interiorlighttoggle, &TTrain::OnCommand_interiorlighttoggle}, - {user_command::interiorlightenable, &TTrain::OnCommand_interiorlightenable}, - {user_command::interiorlightdisable, &TTrain::OnCommand_interiorlightdisable}, - {user_command::interiorlightdimtoggle, &TTrain::OnCommand_interiorlightdimtoggle}, - {user_command::interiorlightdimenable, &TTrain::OnCommand_interiorlightdimenable}, - {user_command::interiorlightdimdisable, &TTrain::OnCommand_interiorlightdimdisable}, - {user_command::compartmentlightstoggle, &TTrain::OnCommand_compartmentlightstoggle}, - {user_command::compartmentlightsenable, &TTrain::OnCommand_compartmentlightsenable}, - {user_command::compartmentlightsdisable, &TTrain::OnCommand_compartmentlightsdisable}, - {user_command::instrumentlighttoggle, &TTrain::OnCommand_instrumentlighttoggle}, - {user_command::instrumentlightenable, &TTrain::OnCommand_instrumentlightenable}, - {user_command::instrumentlightdisable, &TTrain::OnCommand_instrumentlightdisable}, - {user_command::dashboardlighttoggle, &TTrain::OnCommand_dashboardlighttoggle}, - {user_command::dashboardlightenable, &TTrain::OnCommand_dashboardlightenable}, - {user_command::dashboardlightdisable, &TTrain::OnCommand_dashboardlightdisable}, - {user_command::timetablelighttoggle, &TTrain::OnCommand_timetablelighttoggle}, - {user_command::timetablelightenable, &TTrain::OnCommand_timetablelightenable}, - {user_command::timetablelightdisable, &TTrain::OnCommand_timetablelightdisable}, - {user_command::doorlocktoggle, &TTrain::OnCommand_doorlocktoggle}, - {user_command::doortoggleleft, &TTrain::OnCommand_doortoggleleft}, - {user_command::doortoggleright, &TTrain::OnCommand_doortoggleright}, - {user_command::doorpermitleft, &TTrain::OnCommand_doorpermitleft}, - {user_command::doorpermitright, &TTrain::OnCommand_doorpermitright}, - {user_command::doorpermitpresetactivatenext, &TTrain::OnCommand_doorpermitpresetactivatenext}, - {user_command::doorpermitpresetactivateprevious, &TTrain::OnCommand_doorpermitpresetactivateprevious}, - {user_command::dooropenleft, &TTrain::OnCommand_dooropenleft}, - {user_command::dooropenright, &TTrain::OnCommand_dooropenright}, - {user_command::doorcloseleft, &TTrain::OnCommand_doorcloseleft}, - {user_command::doorcloseright, &TTrain::OnCommand_doorcloseright}, - {user_command::dooropenall, &TTrain::OnCommand_dooropenall}, - {user_command::doorcloseall, &TTrain::OnCommand_doorcloseall}, - {user_command::doorsteptoggle, &TTrain::OnCommand_doorsteptoggle}, - {user_command::doormodetoggle, &TTrain::OnCommand_doormodetoggle}, - {user_command::mirrorstoggle, &TTrain::OnCommand_mirrorstoggle}, - {user_command::nearestcarcouplingincrease, &TTrain::OnCommand_nearestcarcouplingincrease}, - {user_command::nearestcarcouplingdisconnect, &TTrain::OnCommand_nearestcarcouplingdisconnect}, - {user_command::nearestcarcoupleradapterattach, &TTrain::OnCommand_nearestcarcoupleradapterattach}, - {user_command::nearestcarcoupleradapterremove, &TTrain::OnCommand_nearestcarcoupleradapterremove}, - {user_command::occupiedcarcouplingdisconnect, &TTrain::OnCommand_occupiedcarcouplingdisconnect}, - {user_command::departureannounce, &TTrain::OnCommand_departureannounce}, - {user_command::hornlowactivate, &TTrain::OnCommand_hornlowactivate}, - {user_command::hornhighactivate, &TTrain::OnCommand_hornhighactivate}, - {user_command::whistleactivate, &TTrain::OnCommand_whistleactivate}, - {user_command::radiotoggle, &TTrain::OnCommand_radiotoggle}, - {user_command::radioenable, &TTrain::OnCommand_radioenable}, - {user_command::radiodisable, &TTrain::OnCommand_radiodisable}, - {user_command::radiochannelincrease, &TTrain::OnCommand_radiochannelincrease}, - {user_command::radiochanneldecrease, &TTrain::OnCommand_radiochanneldecrease}, - {user_command::radiochannelset, &TTrain::OnCommand_radiochannelset}, - {user_command::radiostopsend, &TTrain::OnCommand_radiostopsend}, - {user_command::radiostopenable, &TTrain::OnCommand_radiostopenable}, - {user_command::radiostopdisable, &TTrain::OnCommand_radiostopdisable}, - {user_command::radiostoptest, &TTrain::OnCommand_radiostoptest}, - {user_command::radiocall1send, &TTrain::OnCommand_radiocall1send}, - {user_command::radiocall3send, &TTrain::OnCommand_radiocall3send}, - {user_command::radiovolumeincrease, &TTrain::OnCommand_radiovolumeincrease}, - {user_command::radiovolumedecrease, &TTrain::OnCommand_radiovolumedecrease}, - {user_command::radiovolumeset, &TTrain::OnCommand_radiovolumeset}, - {user_command::fmradiotoggle, &TTrain::OnCommand_fmradiotoggle}, - {user_command::fmradiovolumeincrease, &TTrain::OnCommand_fmradiovolumeincrease}, - {user_command::fmradiovolumedecrease, &TTrain::OnCommand_fmradiovolumedecrease}, - {user_command::fmradiovolumeset, &TTrain::OnCommand_fmradiovolumeset}, - {user_command::fmradiotuneincrease, &TTrain::OnCommand_fmradiotuneincrease}, - {user_command::fmradiotunedecrease, &TTrain::OnCommand_fmradiotunedecrease}, - {user_command::fmradiotuneset, &TTrain::OnCommand_fmradiotuneset}, - {user_command::radiofusetoggle, &TTrain::OnCommand_radiofusetoggle}, - {user_command::radiofuseenable, &TTrain::OnCommand_radiofuseenable}, - {user_command::radiofusedisable, &TTrain::OnCommand_radiofusedisable}, - {user_command::cabchangeforward, &TTrain::OnCommand_cabchangeforward}, - {user_command::cabchangebackward, &TTrain::OnCommand_cabchangebackward}, - {user_command::generictoggle0, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle1, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle2, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle3, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle4, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle5, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle6, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle7, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle8, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle9, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle10, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle11, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle12, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle13, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle14, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle15, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle16, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle17, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle18, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle19, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle20, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle21, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle22, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle23, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle24, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle25, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle26, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle27, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle28, &TTrain::OnCommand_generictoggle}, - {user_command::generictoggle29, &TTrain::OnCommand_generictoggle}, - {user_command::vehiclemoveforwards, &TTrain::OnCommand_vehiclemoveforwards}, - {user_command::vehiclemovebackwards, &TTrain::OnCommand_vehiclemovebackwards}, - {user_command::vehicleboost, &TTrain::OnCommand_vehicleboost}, - {user_command::springbraketoggle, &TTrain::OnCommand_springbraketoggle}, - {user_command::springbrakeenable, &TTrain::OnCommand_springbrakeenable}, - {user_command::springbrakedisable, &TTrain::OnCommand_springbrakedisable}, - {user_command::springbrakeshutofftoggle, &TTrain::OnCommand_springbrakeshutofftoggle}, - {user_command::springbrakeshutoffenable, &TTrain::OnCommand_springbrakeshutoffenable}, - {user_command::springbrakeshutoffdisable, &TTrain::OnCommand_springbrakeshutoffdisable}, - {user_command::springbrakerelease, &TTrain::OnCommand_springbrakerelease}, - {user_command::distancecounteractivate, &TTrain::OnCommand_distancecounteractivate}, - {user_command::speedcontrolincrease, &TTrain::OnCommand_speedcontrolincrease}, - {user_command::speedcontroldecrease, &TTrain::OnCommand_speedcontroldecrease}, - {user_command::speedcontrolpowerincrease, &TTrain::OnCommand_speedcontrolpowerincrease}, - {user_command::speedcontrolpowerdecrease, &TTrain::OnCommand_speedcontrolpowerdecrease}, - {user_command::speedcontrolbutton0, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton1, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton2, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton3, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton4, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton5, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton6, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton7, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton8, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::speedcontrolbutton9, &TTrain::OnCommand_speedcontrolbutton}, - {user_command::inverterenable1, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable2, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable3, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable4, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable5, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable6, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable7, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable8, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable9, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable10, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable11, &TTrain::OnCommand_inverterenable}, - {user_command::inverterenable12, &TTrain::OnCommand_inverterenable}, - {user_command::inverterdisable1, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable2, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable3, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable4, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable5, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable6, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable7, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable8, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable9, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable10, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable11, &TTrain::OnCommand_inverterdisable}, - {user_command::inverterdisable12, &TTrain::OnCommand_inverterdisable}, - {user_command::invertertoggle1, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle2, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle3, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle4, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle5, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle6, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle7, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle8, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle9, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle10, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle11, &TTrain::OnCommand_invertertoggle}, - {user_command::invertertoggle12, &TTrain::OnCommand_invertertoggle}, -}; - -std::vector const TTrain::fPress_labels = { - - "ch1: ", "ch2: ", "ch3: ", "ch4: ", "ch5: ", "ch6: ", "ch7: ", "ch8: ", "ch9: ", "ch0: "}; - -TTrain::TTrain() -{ - - // McZapkie-240302 - przyda sie do tachometru - - // asMessage=""; - DynamicSet(nullptr); // ustawia wszystkie mv* - //----- - - // - for (int i = 0; i < 8; i++) - { - bMains[i] = false; - fCntVol[i] = 0.0f; - bPants[i][0] = false; - bPants[i][1] = false; - bFuse[i] = false; - bBatt[i] = false; - bConv[i] = false; - bComp[i][0] = false; - bComp[i][1] = false; - // bComp[ i ][ 2 ] = false; - // bComp[ i ][ 3 ] = false; - bHeat[i] = false; - } - bCompressors.clear(); - for (int i = 0; i < 9; ++i) - for (int j = 0; j < 10; ++j) - { - fEIMParams[i][j] = 0.0; - fDieselParams[i][j] = 0.0; - } - - for (int i = 0; i < 20; ++i) - { - for (auto &press : fPress[i]) - press = 0.0; - bBrakes[i][0] = false; - bBrakes[i][1] = false; - } -} - -TTrain::~TTrain() = default; - -bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) -{ // powiązanie ręcznego sterowania kabiną z pojazdem - if (NewDynamicObject->Mechanik == nullptr) - { - /* - ErrorLog( "Bad config: can't take control of inactive vehicle \"" + NewDynamicObject->asName + "\"" ); - return false; - */ - auto const activecab{(NewDynamicObject->MoverParameters->CabOccupied > 0 ? "1" : NewDynamicObject->MoverParameters->CabOccupied < 0 ? "2" : "p")}; - NewDynamicObject->create_controller(activecab, NewDynamicObject->ctOwner != nullptr); - } - - DynamicSet(NewDynamicObject); - if (!e3d && DynamicObject->Mechanik == nullptr) - return false; - - DynamicObject->MechInside = true; - - fMainRelayTimer = 0; // Hunter, do k...y nędzy, ustawiaj wartości początkowe zmiennych! - - iCabn = mvOccupied->CabOccupied > 0 ? 1 : mvOccupied->CabOccupied < 0 ? 2 : 0; - - { - Global.CurrentMaxTextureSize = Global.iMaxCabTextureSize; - - auto const filename{mvOccupied->TypeName + ".mmd"}; - LoadMMediaFile(filename); - InitializeCab(mvOccupied->CabOccupied, filename); - - Global.CurrentMaxTextureSize = Global.iMaxTextureSize; - - if (DynamicObject->Controller == Humandriver) - { - // McZapkie-030303: mozliwosc wyswietlania kabiny, w przyszlosci dac opcje w mmd - DynamicObject->bDisplayCab = true; - } - } - - // Ra: taka proteza - przesłanie kierunku do członów connected - /* - if (mvControlled->DirActive > 0) - { // było do przodu - mvControlled->DirectionBackward(); - mvControlled->DirectionForward(); - } - else if (mvControlled->DirActive < 0) - { - mvControlled->DirectionForward(); - mvControlled->DirectionBackward(); - } - */ - if (false == DynamicObject->Mechanik->AIControllFlag) - { - DynamicObject->Mechanik->sync_consist_reversers(); - } - - return true; -} - -std::shared_ptr TTrain::GetTrainState(dictionary_source const &Extraparameters) -{ - - if (mvOccupied == nullptr || mvControlled == nullptr) - { - return nullptr; - } - - auto dict = std::make_shared(Extraparameters); - if (dict == nullptr) - { - return nullptr; - } - - dict->insert("name", DynamicObject->asName); - dict->insert("cab", mvOccupied->CabOccupied); - dict->insert("cabactive", mvOccupied->CabActive); - dict->insert("master", mvOccupied->CabMaster); - // basic systems state data - dict->insert("battery", mvOccupied->Power24vIsAvailable); - dict->insert("linebreaker", mvControlled->Mains); - dict->insert("main_init", mvControlled->MainsInitTimeCountdown < mvControlled->MainsInitTime && mvControlled->MainsInitTimeCountdown > 0.0); - dict->insert("main_ready", false == mvControlled->Mains && fHVoltage > 0.0 && mvControlled->MainsInitTimeCountdown <= 0.0); - dict->insert("converter", mvOccupied->Power110vIsAvailable); - dict->insert("converter_overload", mvControlled->ConvOvldFlag); - dict->insert("compress", mvControlled->CompressorFlag); - dict->insert("pant_compressor", mvPantographUnit->PantCompFlag); - dict->insert("lights_front", mvOccupied->iLights[end::front]); - dict->insert("lights_rear", mvOccupied->iLights[end::rear]); - dict->insert("off_from_dimmer", mvOccupied->currentDimPosition().isOff); - dict->insert("lights_compartments", mvOccupied->CompartmentLights.is_active || mvOccupied->CompartmentLights.is_disabled); - if (Dynamic()->Mechanik) - { - auto const *controller{Dynamic()->Mechanik}; - auto const cabmodifier{cab_to_end() == end::front ? 1 : -1}; - auto const traindirection{controller->Direction() * cabmodifier}; - auto const *frontvehicle{controller->Vehicle(traindirection >= 0 ? end::front : end::rear)}; - auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? end::rear : end::front)}; - auto const frontvehicledirection{(frontvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; - auto const rearvehicledirection{(rearvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; - auto const fronttrainlights{frontvehicle->MoverParameters->iLights[frontvehicledirection * cabmodifier >= 0 ? end::front : end::rear]}; - auto const reartrainlights{rearvehicle->MoverParameters->iLights[rearvehicledirection * cabmodifier >= 0 ? end::rear : end::front]}; - dict->insert("lights_train_front", fronttrainlights); - dict->insert("lights_train_rear", reartrainlights); - } - else - { - // fallback, in the unlikely case we lose the controller - dict->insert("lights_train_front", mvOccupied->iLights[end::front]); - dict->insert("lights_train_rear", mvOccupied->iLights[end::rear]); - } - // reverser - dict->insert("direction", mvOccupied->DirActive); - // throttle - dict->insert("mainctrl_pos", mvControlled->MainCtrlPos); - dict->insert("mainctrl_pos_count", mvControlled->MainCtrlPosNo); - dict->insert("main_ctrl_actual_pos", mvControlled->MainCtrlActualPos); - dict->insert("scndctrl_pos", mvControlled->ScndCtrlPos); - dict->insert("dynamicbrake_pos", mvControlled->DynamicBrakeCtrlPos); - dict->insert("scnd_ctrl_actual_pos", mvControlled->ScndCtrlActualPos); - dict->insert("brakectrl_pos", mvControlled->fBrakeCtrlPos); - dict->insert("localbrake_pos", mvControlled->LocalBrakePosA); - dict->insert("new_speed", mvOccupied->NewSpeed); - dict->insert("speedctrl", mvOccupied->SpeedCtrlValue); - dict->insert("speedctrlpower", mvOccupied->SpeedCtrlUnit.DesiredPower); - dict->insert("speedctrlactive", mvOccupied->SpeedCtrlUnit.IsActive); - dict->insert("speedctrlstandby", mvOccupied->SpeedCtrlUnit.Standby); - // brakes - dict->insert("manual_brake", mvOccupied->ManualBrakePos > 0); - bool const bEP = mvControlled->LocHandle->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; - dict->insert("dir_brake", bEP); - bool bPN{false}; - auto const &brakevalve{*mvOccupied->Hamulec}; - if (auto const &brakevalvetype{typeid(brakevalve)}; brakevalvetype == typeid(TLSt) || brakevalvetype == typeid(TEStED)) - { - - TBrake *temp_ham = mvOccupied->Hamulec.get(); - bPN = static_cast(temp_ham)->GetEDBCP() > 0.2; - } - dict->insert("indir_brake", bPN); - dict->insert("emergency_brake", mvOccupied->AlarmChainFlag); - dict->insert("brake_delay_flag", mvOccupied->BrakeDelayFlag); - dict->insert("brake_op_mode_flag", mvOccupied->BrakeOpModeFlag); - dict->insert("pipelock", mvOccupied->LockPipe); - // other controls - dict->insert("ca", mvOccupied->SecuritySystem.is_vigilance_blinking()); - dict->insert("shp", mvOccupied->SecuritySystem.is_cabsignal_blinking()); - dict->insert("distance_counter", m_distancecounter); - dict->insert("pantpress", std::abs(mvPantographUnit->PantPress)); - dict->insert("universal3", InstrumentLightActive); - for (auto idx = 0; idx < ggUniversals.size(); idx++) - { - if (idx != 3) - { - dict->insert("universal" + std::to_string(idx), ggUniversals[idx].GetValue() > 0.5); - } - } - dict->insert("radio", mvOccupied->Radio); - dict->insert("radio_fuse", mvOccupied->RadioFuse); - dict->insert("radio_channel", RadioChannel()); - dict->insert("radio_volume", m_radiovolume); - dict->insert("door_lock", mvOccupied->Doors.lock_enabled); - dict->insert("door_step", mvOccupied->Doors.step_enabled); - dict->insert("door_permit_left", mvOccupied->Doors.instances[side::left].open_permit); - dict->insert("door_permit_right", mvOccupied->Doors.instances[side::right].open_permit); - // movement data - dict->insert("velocity", std::abs(mvOccupied->Vel)); - dict->insert("tractionforce", std::abs(mvOccupied->Ft)); - dict->insert("slipping_wheels", mvOccupied->SlippingWheels); - dict->insert("sanding", mvOccupied->SandDose); - dict->insert("odometer", mvOccupied->DistCounter); // distance run in the session, km - dict->insert("odometer_total", mvOccupied->Odometer.km); // the vehicle's odometer, kept between the sessions - // electric current data - dict->insert("traction_voltage", std::abs(mvPantographUnit->PantographVoltage)); - dict->insert("voltage", std::abs(mvControlled->EngineVoltage)); - dict->insert("im", std::abs(mvControlled->Im)); - dict->insert("fuse", mvControlled->FuseFlag); - dict->insert("epfuse", mvOccupied->EpFuse); - dict->insert("power_drawn", mvOccupied->EnergyMeter.first); - dict->insert("power_returned", mvOccupied->EnergyMeter.second); - - // induction motor state data - std::array const TXTT{"fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3"}; - std::array const TXTC{"fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv"}; - std::array const TXTD{"enrot", "nrot", "fill_des", "fill_real", "clutch_des", "clutch_real", "water_temp", "oil_press", "engine_temp", "retarder_fill"}; - std::array const TXTP{"bc", "bp", "sp", "cp", "rp", "mass", "spring"}; - char const *TXTB[2] = {"spring_active", "spring_shutoff"}; - for (int j = 0; j < 10; ++j) - dict->insert("eimp_t_" + std::string(TXTT[j]), fEIMParams[0][j]); - for (int i = 0; i < 8; ++i) - { - auto const idx{std::to_string(i + 1)}; - for (int j = 0; j < 10; ++j) - dict->insert("eimp_c" + idx + "_" + std::string(TXTC[j]), fEIMParams[i + 1][j]); - - for (int j = 0; j < 10; ++j) - dict->insert("diesel_param_" + idx + "_" + std::string(TXTD[j]), fDieselParams[i + 1][j]); - - dict->insert("eimp_c" + idx + "_ms", bMains[i]); - dict->insert("eimp_c" + idx + "_cv", fCntVol[i]); - dict->insert("eimp_c" + idx + "_fuse", bFuse[i]); - dict->insert("eimp_c" + idx + "_batt", bBatt[i]); - dict->insert("eimp_c" + idx + "_conv", bConv[i]); - dict->insert("eimp_c" + idx + "_heat", bHeat[i]); - - dict->insert("eimp_u" + idx + "_pf", bPants[i][0]); - dict->insert("eimp_u" + idx + "_pr", bPants[i][1]); - dict->insert("eimp_u" + idx + "_comp_a", bComp[i][0]); - dict->insert("eimp_u" + idx + "_comp_w", bComp[i][1]); - } - - dict->insert("compressors_no", (int)bCompressors.size()); - for (int i = 0; i < bCompressors.size(); i++) - { - auto const idx{std::to_string(i + 1)}; - dict->insert("compressors_" + idx + "_allow", std::get<0>(bCompressors[i])); - dict->insert("compressors_" + idx + "_work", std::get<1>(bCompressors[i])); - dict->insert("compressors_" + idx + "_car_no", std::get<2>(bCompressors[i])); - } - - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); - int in = 0; - while (p && in < 8) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - in++; - dict->insert("eimp_c" + std::to_string(in) + "_invno", p->MoverParameters->InvertersNo); - for (int j = 0; j < p->MoverParameters->InvertersNo; j++) - { - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->MoverParameters->Inverters[j].IsActive); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->MoverParameters->Inverters[j].Error); - dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->MoverParameters->Inverters[j].Activate); - } - } - p = kier ? p->Next(4) : p->Prev(4); - } - for (int i = 0; i < 20; ++i) - { - for (int j = 0; j < 7; ++j) - { - dict->insert("eimp_pn" + std::to_string(i + 1) + "_" + TXTP[j], fPress[i][j]); - } - for (int j = 0; j < 2; ++j) - { - dict->insert("brakes_" + std::to_string(i + 1) + "_" + TXTB[j], bBrakes[i][j]); - } - } - // multi-unit state data - dict->insert("car_no", iCarNo); - dict->insert("power_no", iPowerNo); - dict->insert("unit_no", iUnitNo); - - for (int i = 0; i < 20; i++) - { - auto const caridx{std::to_string(i + 1)}; - dict->insert("doors_" + caridx, bDoors[i][0]); - dict->insert("doors_l_" + caridx, bDoors[i][1]); - dict->insert("doors_r_" + caridx, bDoors[i][2]); - dict->insert("doorstep_l_" + caridx, bDoors[i][3]); - dict->insert("doorstep_r_" + caridx, bDoors[i][4]); - dict->insert("doors_no_" + caridx, iDoorNo[i]); - dict->insert("code_" + caridx, std::to_string(iUnits[i]) + cCode[i]); - dict->insert("car_name" + caridx, asCarName[i]); - dict->insert("slip_" + caridx, bSlip[i]); - } - // ai state data - auto const *vehicledriver{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; - - dict->insert("velocity_desired", vehicledriver->VelDesired); - dict->insert("velroad", vehicledriver->VelRoad); - dict->insert("vellimitlast", vehicledriver->VelLimitLast); - dict->insert("velsignallast", vehicledriver->VelSignalLast); - dict->insert("velsignalnext", vehicledriver->VelSignalNext); - dict->insert("velnext", vehicledriver->VelNext); - dict->insert("actualproximitydist", vehicledriver->ActualProximityDist); - // train data - vehicledriver->TrainTimetable().serialize(dict.get()); - dict->insert("train_atpassengerstop", vehicledriver->IsAtPassengerStop); - dict->insert("train_length", vehicledriver->fLength); - // world state data - dict->insert("scenario", Global.SceneryFile); - dict->insert("hours", static_cast(simulation::Time.data().wHour)); - dict->insert("minutes", static_cast(simulation::Time.data().wMinute)); - dict->insert("seconds", static_cast(simulation::Time.second())); - dict->insert("air_temperature", Global.AirTemperature); - dict->insert("light_level", Global.fLuminance - std::max(0.f, Global.Overcast - 1.f)); - - return dict; -} - -TTrain::state_t TTrain::get_state() const -{ - - return { - btLampkaSHP.GetValue(), - btLampkaCzuwaka.GetValue(), - btLampkaRadioStop.GetValue(), - btLampkaOpory.GetValue(), - btLampkaWylSzybki.GetValue(), - btLampkaPrzekRozn.GetValue(), - btLampkaNadmSil.GetValue(), - btLampkaStyczn.GetValue(), - btLampkaPoslizg.GetValue(), - btLampkaNadmPrzetw.GetValue(), - btLampkaPrzetwOff.GetValue(), - btLampkaNadmSpr.GetValue(), - btLampkaNadmWent.GetValue(), - btLampkaWysRozr.GetValue(), - btLampkaOgrzewanieSkladu.GetValue(), - static_cast(iCabn), - btHaslerBrakes.GetValue(), - btHaslerCurrent.GetValue(), - mvOccupied->SecuritySystem.is_beeping(), - btLampkaHVoltageB.GetValue(), - fTachoVelocity, - static_cast(mvOccupied->Compressor), - static_cast(mvOccupied->PipePress), - static_cast(mvOccupied->BrakePress), - static_cast(mvPantographUnit->PantPress), - fHVoltage, - {fHCurrent[mvControlled->TrainType & dt_EZT ? 0 : 1], fHCurrent[2], fHCurrent[3]}, - ggLVoltage.GetValue(), - mvOccupied->DistCounter, - static_cast(RadioChannel()), - btLampkaSpringBrakeActive.GetValue(), - btLampkaNapNastHam.GetValue(), - mvOccupied->DirActive > 0, - mvOccupied->DirActive < 0, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::right : side::left].is_open, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].open_permit, - mvOccupied->Doors.instances[mvOccupied->CabOccupied < 0 ? side::left : side::right].is_open, - mvOccupied->Doors.step_enabled, - mvOccupied->Power24vIsAvailable, - 0, - mvOccupied->LockPipe, - btLampkaRadioMessage.GetValue(), - }; -} - -bool TTrain::is_eztoer() const -{ - - return mvControlled->TrainType == dt_EZT && mvOccupied->BrakeSubsystem == TBrakeSubSystem::ss_ESt && mvControlled->Power24vIsAvailable == true && mvControlled->EpFuse == true && - mvControlled->DirActive != 0; // od yB -} - -// mover master controller to specified position -void TTrain::set_master_controller(double const Position) -{ - - auto positionchange{std::min(static_cast(Position), mvControlled->CoupledCtrl ? mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : mvControlled->MainCtrlPosNo) - - (mvControlled->CoupledCtrl ? mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos : mvControlled->MainCtrlPos)}; - while (positionchange < 0 && true == mvControlled->DecMainCtrl(1)) - { - ++positionchange; - } - while (positionchange > 0 && true == mvControlled->IncMainCtrl(1)) - { - --positionchange; - } -} - -// moves train brake lever to specified position, potentially emits switch sound if conditions are met -void TTrain::set_train_brake(double const Position) -{ - - auto const originalbrakeposition{static_cast(100.0 * mvOccupied->fBrakeCtrlPos)}; - mvOccupied->BrakeLevelSet(Position); - - if (static_cast(100.0 * mvOccupied->fBrakeCtrlPos) == originalbrakeposition) - { - return; - } - - // sound feedback if the lever movement activates one of the switches - if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (mvOccupied->BrakeCtrlPos == 0 || mvOccupied->BrakeCtrlPos >= 5)) && dsbPneumaticSwitch) - { - dsbPneumaticSwitch->play(); - } -} - -void TTrain::zero_charging_train_brake() -{ - using enum TBrakeHandle; - - if (mvOccupied->BrakeCtrlPos == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && - (mvOccupied->BrakeHandle == FVel6 || mvOccupied->BrakeHandle == MHZ_EN57 || mvOccupied->BrakeHandle == MHZ_K8P)) - { - // Odskakiwanie hamulce EP - set_train_brake(0); - } -} - -void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) -{ - - // visual feedback - // TODO: add setting indicator to vehicle class, for external lever/indicator - if (true == Vehicle->MoverParameters->BrakeDelaySwitch(Speed) && Vehicle == DynamicObject) - { - if (ggBrakeProfileCtrl.SubModel != nullptr) - { - ggBrakeProfileCtrl.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.0 : static_cast(mvOccupied->BrakeDelayFlag - 1), dsbSwitch); - } - if (ggBrakeProfileG.SubModel != nullptr) - { - ggBrakeProfileG.UpdateValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.0 : 0.0, dsbSwitch); - } - if (ggBrakeProfileR.SubModel != nullptr) - { - ggBrakeProfileR.UpdateValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); - } - } -} - -void TTrain::set_paired_open_motor_connectors_button(bool const State) -{ - - if (mvControlled->TrainType == dt_ET41 || mvControlled->TrainType == dt_ET42) - { - // crude implementation of the button affecting entire unit for multi-unit engines - // TODO: rework it into part of standard command propagation system - if (mvControlled->Couplers[end::front].Connected != nullptr && true == TestFlag(mvControlled->Couplers[end::front].CouplingFlag, coupling::permanent)) - { - mvControlled->Couplers[end::front].Connected->StLinSwitchOff = State; - } - if (mvControlled->Couplers[end::rear].Connected != nullptr && true == TestFlag(mvControlled->Couplers[end::rear].CouplingFlag, coupling::permanent)) - { - mvControlled->Couplers[end::rear].Connected->StLinSwitchOff = State; - } - } -} - -// locates nearest vehicle belonging to the consist -TDynamicObject *TTrain::find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const -{ - if (!freefly) - return DynamicObject; - - auto couplerindex{-2}; // scan for vehicle, not any specific coupler - auto *vehicle{DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), 1, 1500, couplerindex)}; - if (vehicle == nullptr) - vehicle = DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), -1, 1500, couplerindex); - // TBD, TODO: perform owner test for the located vehicle - return vehicle; -} - -// command handlers -void TTrain::OnCommand_aidriverenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // on press - if (Train->DynamicObject->Mechanik == nullptr) - { - return; - } - - if (true == Train->DynamicObject->Mechanik->AIControllFlag) - { - // żeby nie trzeba było rozłączać dla zresetowania - Train->DynamicObject->Mechanik->TakeControl(false); - } - Train->DynamicObject->Mechanik->TakeControl(true); - } -} - -void TTrain::OnCommand_aidriverdisable(TTrain *Train, command_data const &Command) -{ - - // on press - if (Command.action == GLFW_PRESS && Train->DynamicObject->Mechanik) - Train->DynamicObject->Mechanik->TakeControl(false); -} - -auto const EU07_CONTROLLER_BASERETURNDELAY{0.5f}; -auto const EU07_CONTROLLER_KEYBOARDETURNDELAY{1.5f}; - -void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - // value controls brake in range 0-0.5, master controller in range 0.5-1.0 - if (Command.param1 >= 0.5) - { - Train->set_master_controller((Command.param1 * 2 - 1) * - (Train->mvControlled->CoupledCtrl ? Train->mvControlled->MainCtrlPosNo + Train->mvControlled->ScndCtrlPosNo : Train->mvControlled->MainCtrlPosNo)); - Train->m_mastercontrollerinuse = true; - // when SplitEDPneumaticBrake is active the joint controller's negative range - // commands the dedicated dynamic-brake lever instead of the local pneumatic brake - if (Train->mvControlled->SplitEDPneumaticBrake) - { - Train->mvControlled->DynamicBrakeLevelSet(0.0); - } - else - { - Train->mvOccupied->LocalBrakePosA = 0; - } - } - else - { - auto const negativeRange{std::clamp(1.0 - Command.param1 * 2, 0.0, 1.0)}; - if (Train->mvControlled->SplitEDPneumaticBrake) - { - // negative range of jointctrl drives only ED braking, local pneumatic brake stays untouched. - // snap to DBPN discrete stops so the lever animates step-by-step - auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; - auto const snapped{std::round(negativeRange * stepCount) / stepCount}; - Train->mvControlled->DynamicBrakeLevelSet(snapped); - } - else - { - Train->mvOccupied->LocalBrakePosA = negativeRange; - } - if (Train->mvControlled->MainCtrlPowerPos() > 0) - { - Train->set_master_controller(Train->mvControlled->MainCtrlNoPowerPos()); - } - } - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources - } -} - -void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - // when SplitEDPneumaticBrake is true the joint controller's negative range maps - // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake - auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; - if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) - { - if (splitMode) - { - OnCommand_DynamicBrakeControllerDecrease(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakedecrease(Train, Command); - } - } - else - { - Train->mvControlled->IncMainCtrl(1); - Train->m_mastercontrollerinuse = true; - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const negativeRangeActive{splitMode ? Train->mvControlled->DynamicBrakeCtrlPos > 0.0 : Train->mvOccupied->LocalBrakePosA > 0.0}; - if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) - { - if (splitMode) - { - OnCommand_DynamicBrakeControllerDecreaseFast(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakedecreasefast(Train, Command); - } - } - else - { - Train->mvControlled->IncMainCtrl(Train->mvControlled->MainCtrlPosNo); - Train->m_mastercontrollerinuse = true; - } - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerdecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) - { - // negative range of jointctrl: ED brake when split, otherwise pneumatic local brake - if (splitMode) - { - OnCommand_DynamicBrakeControllerIncrease(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakeincrease(Train, Command); - } - } - else - { - Train->mvControlled->DecMainCtrl(1); - Train->m_mastercontrollerinuse = true; - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerdecreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - if (Train->ggJointCtrl.SubModel != nullptr && Train->mvControlled->IsMainCtrlNoPowerPos()) - { - if (splitMode) - { - OnCommand_DynamicBrakeControllerIncreaseFast(Train, Command); - Train->m_mastercontrollerinuse = true; - } - else - { - OnCommand_independentbrakeincreasefast(Train, Command); - } - } - else - { - Train->mvControlled->DecMainCtrl(Train->mvControlled->MainCtrlPowerPos()); - Train->m_mastercontrollerinuse = true; - } - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; - } -} - -void TTrain::OnCommand_mastercontrollerset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - Train->set_master_controller(Command.param1); - Train->m_mastercontrollerinuse = true; - } - else - { - // release - Train->m_mastercontrollerinuse = false; - Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources - } -} -void TTrain::OnCommand_DynamicBrakeControllerIncrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_RELEASE) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl - Train->mvControlled->IncDynamicBrakeLevel(1.0f); -} - -void TTrain::OnCommand_DynamicBrakeControllerIncreaseFast(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - Train->mvControlled->IncDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); -} - -void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_RELEASE) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl - Train->mvControlled->DecDynamicBrakeLevel(1.0f); -} - -void TTrain::OnCommand_DynamicBrakeControllerDecreaseFast(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - Train->mvControlled->DecDynamicBrakeLevel(static_cast(Train->mvControlled->DynamicBrakeCtrlPosNo)); -} - -void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_RELEASE) - { - return; - } - if (false == Train->mvControlled->SplitEDPneumaticBrake) - { - return; - } - - // when input source uses raw 0..1 value, snap to nearest DBPN step - auto const target{std::clamp(Command.param1, 0.0, 1.0)}; - auto const stepCount{std::max(1, Train->mvControlled->DynamicBrakeCtrlPosNo)}; - auto const snapped{std::round(target * stepCount) / stepCount}; - Train->mvControlled->DynamicBrakeLevelSet(snapped); -} - -void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntModeAllow && true == Train->mvControlled->ShuntMode) - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos + 0.025, 0.0, 1.0); - } - } - else - { - // regular mode - // push or pushtoggle control type - if (Train->ggScndCtrl.is_push()) - { - if (Command.action == GLFW_PRESS) - { - // activate on press - Train->mvControlled->IncScndCtrl(1); - } - } - // toggle control type - else - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->IncScndCtrl(1); - } - } - // HACK: potentially animate push or pushtoggle control - if (Train->ggScndCtrl.is_push()) - { - auto const activeposition{1.f}; - auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; - Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); - } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) - { - Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_secondcontrollerincreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) - { - Train->mvControlled->AnPos = 1.0; - } - else - { - Train->mvControlled->IncScndCtrl(2); - } - } -} - -void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->AutoRelayFlag) - { - // turn on - Train->mvOccupied->AutoRelaySwitch(true); - } - else - { - // turn off - Train->mvOccupied->AutoRelaySwitch(false); - } - } -} - -void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggScndCtrlButton.is_push()) - { - // impulse switch - if (Command.action == GLFW_RELEASE) - { - // just move the button(s) back to default position - // visual feedback - Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggScndCtrlOffButton.UpdateValue(0.0, Train->dsbSwitch); - return; - } - // glfw_press - if (Train->mvControlled->ScndCtrlPos == 0) - { - // turn on if it's not active - Train->mvControlled->IncScndCtrl(1); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // otherwise turn off - Train->mvControlled->DecScndCtrl(2); - // visual feedback - if (Train->m_controlmapper.contains("tempomatoff_sw:")) - { - Train->ggScndCtrlOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (Train->mvControlled->ScndCtrlPos == 0) - { - // turn on - Train->mvControlled->IncScndCtrl(1); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // turn off - Train->mvControlled->DecScndCtrl(2); - // visual feedback - Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_distancecounteractivate(TTrain *Train, command_data const &Command) -{ - // NOTE: distance meter activation button is presumed to be of impulse type - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggDistanceCounterButton.UpdateValue(1.0, Train->dsbSwitch); - // activate or start anew - if (Train->mvOccupied->isDoubleClickForMeasureNeeded) - { - // handler tempomatu dla podwojnego kliku - if (Train->trainLenghtMeasureTimer >= 0.f) // jesli zdazylismy w czasie sekundy - Train->m_distancecounter = 0.f; // rozpoczynamy pomiar - else - Train->trainLenghtMeasureTimer = Train->mvOccupied->DistanceCounterDoublePressPeriod; // odpalamy zegarek od nowa - } - else - { - // dla pojedynczego kliku - Train->m_distancecounter = 0.f; - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggDistanceCounterButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_mucurrentindicatorothersourceactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggNextCurrentButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Current Indicator Source switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // turn on - Train->ShowNextCurrent = true; - // visual feedback - Train->ggNextCurrentButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->ShowNextCurrent = false; - // visual feedback - Train->ggNextCurrentButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->AnPos = std::clamp(Train->mvControlled->AnPos - 0.025, 0.0, 1.0); - } - } - else - { - // regular mode - // push or pushtoggle control type - if (Train->ggScndCtrl.is_push()) - { - // basic push control can't decrease state, but pushtoggle can - if (true == Train->ggScndCtrl.is_toggle() && Command.action == GLFW_PRESS) - { - // activate on press - Train->mvControlled->DecScndCtrl(1); - } - } - // toggle control type - else - { - if (Command.action != GLFW_RELEASE) - { - Train->mvControlled->DecScndCtrl(1); - } - } - // HACK: potentially animate push or pushtoggle control - if (Train->ggScndCtrl.is_push()) - { - auto const activeposition{Train->ggScndCtrl.is_toggle() ? 0.f : 1.f}; - auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; - Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); - } - // potentially animate tempomat button - if (Train->ggScndCtrlButton.is_push() && Train->mvControlled->ScndCtrlPos <= 1) - { - if (Train->m_controlmapper.contains("tempomatoff_sw:")) - { - Train->ggScndCtrlOffButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); - } - else - { - Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // on press or hold - if (Train->mvControlled->EngineType == TEngineType::DieselElectric && true == Train->mvControlled->ShuntMode) - { - Train->mvControlled->AnPos = 0.0; - } - else - { - Train->mvControlled->DecScndCtrl(2); - } - } -} - -void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Command) -{ - - auto const targetposition{std::min(static_cast(Command.param1), Train->mvControlled->ScndCtrlPosNo)}; - // HACK: potentially animate push or pushtoggle control - if (Train->ggScndCtrl.is_push()) - { - auto const activeposition{Train->ggScndCtrl.is_toggle() ? - (targetposition < Train->mvControlled->ScndCtrlPos ? 0.f : - targetposition > Train->mvControlled->ScndCtrlPos ? 1.f : - Train->ggScndCtrl.GetDesiredValue()) : // leave the control in its current position if it hits the limit - targetposition == 0 ? 0.f : - 1.f}; - auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; - Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); - } - // update control value - if (Command.action != GLFW_RELEASE) - { - // on press or hold - while (targetposition < Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->DecScndCtrl(1)) - { - // all work is done in the header - } - while (targetposition > Train->mvControlled->GetVirtualScndPos() && true == Train->mvControlled->IncScndCtrl(1)) - { - // all work is done in the header - } - } -} - -void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - // when SplitEDPneumaticBrake is active the local brake key always operates - // the pneumatic local brake directly, never piggy-backing on the joint controller - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) - { - OnCommand_mastercontrollerdecrease(Train, Command); - } - else - { - Train->mvOccupied->IncLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); - if (useStepped) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->MainCtrlPos > 0) - { - OnCommand_mastercontrollerdecreasefast(Train, Command); - } - else - { - Train->mvOccupied->IncLocalBrakeLevel(LocalBrakePosNo); - if (useJointAnim) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake - // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba - // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->mvOccupied->LocalBrakePosA > 0) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) - { - OnCommand_mastercontrollerincrease(Train, Command); - } - else - { - Train->mvOccupied->DecLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); - if (useStepped) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto const splitMode{Train->mvControlled->SplitEDPneumaticBrake}; - auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; - if (Train->mvOccupied->LocalBrake != TLocalBrake::ManualBrake - // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba - // TODO: sort AI out so it doesn't do things it doesn't have equipment for - || Train->mvOccupied->LocalBrakePosA > 0) - { - if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->mvOccupied->LocalBrakePosA == 0.0) - { - OnCommand_mastercontrollerincreasefast(Train, Command); - } - else - { - Train->mvOccupied->DecLocalBrakeLevel(LocalBrakePosNo); - if (useJointAnim) - { - Train->m_mastercontrollerinuse = true; - } - } - } - } -} - -void TTrain::OnCommand_independentbrakeset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - Train->mvOccupied->LocalBrakePosA = std::clamp(Command.param1, 0.0, 1.0); - } - /* - Train->mvControlled->LocalBrakePos = ( - std::round( - interpolate( - 0.0, - LocalBrakePosNo, - clamp( - Command.param1, - 0.0, 1.0 ) ) ) ); - */ -} - -void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const &Command) -{ - - if (false == Command.freefly) - { - // TODO: check if this set of conditions can be simplified. - // it'd be more flexible to have an attribute indicating whether bail off position is supported - if (Train->mvControlled->TrainType != dt_EZT && - (Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor || Train->mvControlled->EngineType == TEngineType::DieselElectric || - Train->mvControlled->EngineType == TEngineType::ElectricInductionMotor) && - Train->mvOccupied->BrakeCtrlPosNo > 0) - { - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggReleaserButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->BrakeReleaser(1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggReleaserButton.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->BrakeReleaser(0); - } - } - } - else - { - // car brake handling, while in walk mode - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle != nullptr) - { - if (Command.action == GLFW_PRESS) - { - // press or hold - vehicle->MoverParameters->BrakeReleaser(1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - vehicle->MoverParameters->BrakeReleaser(0); - } - } - } -} - -void TTrain::OnCommand_universalbrakebutton1(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggUniveralBrakeButton1.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(0, 1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggUniveralBrakeButton1.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(0, 0); - } -} - -void TTrain::OnCommand_universalbrakebutton2(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggUniveralBrakeButton2.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(1, 1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggUniveralBrakeButton2.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(1, 0); - } -} - -void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold - // visual feedback - Train->ggUniveralBrakeButton3.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(2, 1); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggUniveralBrakeButton3.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvOccupied->UniversalBrakeButton(2, 0); - } -} - -void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - Train->mvOccupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos + Global.fBrakeStep); -} - -void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_REPEAT && Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - Train->mvOccupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->mvOccupied->BrakeCtrlPosNo); - else if (Command.action == GLFW_PRESS && Train->mvOccupied->BrakeHandle != TBrakeHandle::FV4a) - Train->set_train_brake(Train->mvOccupied->fBrakeCtrlPos - Global.fBrakeStep); - else if (Command.action == GLFW_RELEASE) - { - // release - Train->zero_charging_train_brake(); - } -} - -void TTrain::OnCommand_trainbrakeset(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // press or hold - Train->mvOccupied->BrakeLevelSet(std::lerp(Train->mvOccupied->Handle->GetPos(bh_MIN), Train->mvOccupied->Handle->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); - } - else - { - // release - Train->zero_charging_train_brake(); - } -} - -void TTrain::OnCommand_trainbrakecharging(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - // press or hold - Train->set_train_brake(-1); - } - else - { - // release - Train->zero_charging_train_brake(); - } -} - -void TTrain::OnCommand_trainbrakerelease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(0); - } -} - -void TTrain::OnCommand_trainbrakefirstservice(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(1); - } -} - -void TTrain::OnCommand_trainbrakeservice(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo / 2 + (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a ? 1 : 0)); - } -} - -void TTrain::OnCommand_trainbrakefullservice(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->BrakeCtrlPosNo - 1); - } -} - -void TTrain::OnCommand_trainbrakehandleoff(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_NP)); - } -} - -void TTrain::OnCommand_trainbrakeemergency(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->set_train_brake(Train->mvOccupied->Handle->GetPos(bh_EB)); - /* - if( Train->mvOccupied->BrakeCtrlPosNo <= 0.1 ) { - // hamulec bezpieczeństwa dla wagonów - Train->mvOccupied->RadioStopFlag = true; - } - */ - } -} - -void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 - 0.01, -1.5, 2.0); - } - else - { - Train->mvOccupied->BrakeLevelAdd(0.01); - } - } -} - -void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - Train->mvOccupied->BrakeCtrlPos2 = std::clamp(Train->mvOccupied->BrakeCtrlPos2 + 0.01, -1.5, 2.0); - } - else - { - Train->mvOccupied->BrakeLevelAdd(-0.01); - } - } -} - -void TTrain::OnCommand_trainbrakebasepressurereset(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->BrakeCtrlPos2 = 0; - } -} - -void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - vehicle->MoverParameters->Hamulec->SetBrakeStatus(vehicle->MoverParameters->Hamulec->GetBrakeStatus() ^ b_dmg); - // the brake is the player's now, the wagon inspector won't put it back on its own - vehicle->MoverParameters->BrakeCutOutByInspector = false; - } -} - -void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) - { - - vehicle->MoverParameters->IncManualBrakeLevel(1); - } - } -} - -void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_RELEASE) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if (vehicle->MoverParameters->LocalBrake == TLocalBrake::ManualBrake || vehicle->MoverParameters->MBrake == true) - { - - vehicle->MoverParameters->DecManualBrakeLevel(1); - } - } -} - -void TTrain::OnCommand_alarmchaintoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - if (false == Train->mvOccupied->AlarmChainFlag) - { - OnCommand_alarmchainenable(Train, Command); - } - else - { - OnCommand_alarmchaindisable(Train, Command); - } - } -} - -void TTrain::OnCommand_alarmchainenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - - // pull - Train->mvOccupied->AlarmChainSwitch(true); - // visual feedback - Train->ggAlarmChain.UpdateValue(1.0); - } -} - -void TTrain::OnCommand_alarmchaindisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - - // release - Train->mvOccupied->AlarmChainSwitch(false); - // visual feedback - Train->ggAlarmChain.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const &Command) -{ - - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - if (Train->ggAntiSlipButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Wheelspin Brake button is missing, or wasn't defined"); - } - return; - } - - if (Train->mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic) - { - // standard behaviour - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbSwitch); - - // NOTE: system activation is (repeatedly) done in the train update routine - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(0.0); - } - } - else - { - // electro-pneumatic, custom case - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbPneumaticSwitch); - - // the EP fuse is the cab car's (Ctrl+Z switches mvOccupied's), checked by SwitchEPBrake with the rest of - // the control's supply - if (Train->mvOccupied->BrakeHandle == TBrakeHandle::St113) - { - Train->mvOccupied->SwitchEPBrake(1); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggAntiSlipButton.UpdateValue(0.0); - - Train->mvOccupied->SwitchEPBrake(0); - } - } -} - -void TTrain::OnCommand_sandboxactivate(TTrain *Train, command_data const &Command) -{ - - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - if (Train->ggSandButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Sandbox activation button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggSandButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->SandboxManual(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggSandButton.UpdateValue(0.0); - - Train->mvControlled->SandboxManual(false); - } -} - -void TTrain::OnCommand_autosandboxtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SandDoseAutoAllow) - { - // turn on - OnCommand_autosandboxactivate(Train, Command); - } - else - { - // turn off - OnCommand_autosandboxdeactivate(Train, Command); - } - } -}; - -void TTrain::OnCommand_autosandboxactivate(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SandboxAutoAllow(true); - Train->ggAutoSandButton.UpdateValue(1.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_autosandboxdeactivate(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SandboxAutoAllow(false); - Train->ggAutoSandButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_epbrakecontrolenable(TTrain *Train, command_data const &Command) -{ - auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - // command only works for bistable switch - if (Command.action == GLFW_PRESS && istoggle) - { - if (Train->mvOccupied->EpFuseSwitch(true)) - { - // audio feedback - if (Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - Train->ggEPFuseButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_epbrakecontroldisable(TTrain *Train, command_data const &Command) -{ - auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - // command only works for bistable switch - if (Command.action == GLFW_PRESS && istoggle) - { - if (Train->mvOccupied->EpFuseSwitch(false)) - { - Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - auto const ispush{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::push)) != 0}; - auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - - if (Command.action == GLFW_PRESS) - { - if (istoggle) - { - // switch state - if (false == Train->mvOccupied->EpFuse) - { - // turn on - // audio feedback - if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - } - else - { - // turn off - Train->mvOccupied->EpFuseSwitch(false); - } - } - else if (ispush) - { - // potentially turn on - // audio feedback - if (Train->mvOccupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) - { - Train->dsbPneumaticSwitch->play(); - } - } - // visual feedback - Train->ggEPFuseButton.UpdateValue(ispush ? 1.0f : // push or pushtoggle - Train->mvOccupied->EpFuse ? 1.0f : - 0.0f, // toggle - Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE && ispush) - { - // return the switch to neutral position - Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_data const &Command) -{ - - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag << 1 & Train->mvOccupied->BrakeOpModes) != 0) - { - // next mode - Train->mvOccupied->BrakeOpModeFlag <<= 1; - // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); // audio fallback - } -} - -void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_data const &Command) -{ - - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action == GLFW_PRESS && (Train->mvOccupied->BrakeOpModeFlag >> 1 & Train->mvOccupied->BrakeOpModes) != 0) - { - // previous mode - Train->mvOccupied->BrakeOpModeFlag >>= 1; - // visual feedback - Train->ggBrakeOperationModeCtrl.UpdateValue(Train->mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(Train->mvOccupied->BrakeOpModeFlag)) : 0); - } -} - -void TTrain::OnCommand_brakeactingspeedincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if ((vehicle->MoverParameters->BrakeDelayFlag & bdelay_M) != 0) - { - // can't speed it up any more than this - return; - } - auto const fasterbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_R ? vehicle->MoverParameters->BrakeDelayFlag << 1 : vehicle->MoverParameters->BrakeDelayFlag | bdelay_M; - - Train->set_train_brake_speed(vehicle, fasterbrakesetting); - } -} - -void TTrain::OnCommand_brakeactingspeeddecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - if (vehicle->MoverParameters->BrakeDelayFlag == bdelay_G) - { - // can't slow it down any more than this - return; - } - auto const slowerbrakesetting = vehicle->MoverParameters->BrakeDelayFlag < bdelay_M ? vehicle->MoverParameters->BrakeDelayFlag >> 1 : vehicle->MoverParameters->BrakeDelayFlag ^ bdelay_M; - - Train->set_train_brake_speed(vehicle, slowerbrakesetting); - } -} - -void TTrain::OnCommand_brakeactingspeedsetcargo(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - Train->set_train_brake_speed(vehicle, bdelay_G); - } -} - -void TTrain::OnCommand_brakeactingspeedsetpassenger(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - Train->set_train_brake_speed(vehicle, bdelay_P); - } -} - -void TTrain::OnCommand_brakeactingspeedsetrapid(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle == nullptr) - { - return; - } - - Train->set_train_brake_speed(vehicle, bdelay_R); - } -} - -void TTrain::OnCommand_brakeloadcompensationincrease(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle != nullptr) - { - vehicle->MoverParameters->IncBrakeMult(); - } - } -} - -void TTrain::OnCommand_brakeloadcompensationdecrease(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; - if (vehicle != nullptr) - { - vehicle->MoverParameters->DecBrakeMult(); - } - } -} - -void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data const &Command) -{ - - if (Train->ggSignallingButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Braking Indicator switch is missing, or wasn't defined"); - } - return; - } - if (Train->mvControlled->TrainType != dt_EZT) - { - // - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->Signalling) - { - // turn on - Train->mvControlled->Signalling = true; - // visual feedback - Train->ggSignallingButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // turn off - Train->mvControlled->Signalling = false; - // visual feedback - Train->ggSignallingButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_wiperswitchincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->wiperSwitchPos++; - if (Train->mvOccupied->wiperSwitchPos > Train->mvOccupied->WiperListSize - 1) - Train->mvOccupied->wiperSwitchPos = Train->mvOccupied->WiperListSize - 1; - - // Visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); - } -} -void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->wiperSwitchPos--; - if (Train->mvOccupied->wiperSwitchPos < 0) - Train->mvOccupied->wiperSwitchPos = 0; - - // visual feedback - Train->ggWiperSw.UpdateValue(static_cast(Train->mvOccupied->wiperSwitchPos), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_reverserincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirectionForward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } -} - -void TTrain::OnCommand_reverserdecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirectionBackward() && Train->mvOccupied->DirActive && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } -} - -void TTrain::OnCommand_reverserforwardhigh(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // HACK: try to move the reverser one position back, in case it's set to "high forward" - OnCommand_reverserdecrease(Train, Command); - - if (Train->mvOccupied->DirActive < 1) - { - - while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) - { - // all work is done in the header - } - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } - OnCommand_reverserincrease(Train, Command); - } -} - -void TTrain::OnCommand_reverserforward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - - // HACK: try to move the reverser one position back, in case it's set to "high forward" - // OnCommand_reverserdecrease( Train, Command ); - // visual feedback - Train->ggDirForwardButton.UpdateValue(1.0, Train->dsbSwitch); - - if (Train->mvOccupied->DirActive == 0) - { - - while (Train->mvOccupied->DirActive < 1 && true == Train->mvOccupied->DirectionForward()) - { - // all work is done in the header - } - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == 1 && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggDirForwardButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_reverserneutral(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - // visual feedback - Train->ggDirNeutralButton.UpdateValue(1.0, Train->dsbSwitch); - while (Train->mvOccupied->DirActive < 0 && true == Train->mvOccupied->DirectionForward()) - { - // all work is done in the header - } - while (Train->mvOccupied->DirActive > 0 && true == Train->mvOccupied->DirectionBackward()) - { - // all work is done in the header - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggDirNeutralButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_reverserbackward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - // HACK: master controller position isn't set in occupied vehicle in E(D)MUs - // so we do a manual check in relevant vehicle here - if (false == Train->mvControlled->EIMDirectionChangeAllow()) - { - return; - } - Train->ggDirBackwardButton.UpdateValue(1.0, Train->dsbSwitch); - if (Train->mvOccupied->DirActive == 0) - { - - while (Train->mvOccupied->DirActive > -1 && true == Train->mvOccupied->DirectionBackward()) - { - // all work is done in the header - } - // aktualizacja skrajnych pojazdów w składzie - if (Train->mvOccupied->DirActive == -1 && Train->DynamicObject->Mechanik) - { - - Train->DynamicObject->Mechanik->DirectionChange(); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggDirBackwardButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggSecurityResetButton.UpdateValue(1.0, Train->dsbSwitch); - - if (Train->mvOccupied->TrainType == dt_EZT || Train->mvOccupied->DirActive != 0) - Train->mvOccupied->SecuritySystem.acknowledge_press(); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggSecurityResetButton.UpdateValue(0.0); - - if (Train->mvOccupied->TrainType == dt_EZT || Train->mvOccupied->DirActive != 0) - Train->mvOccupied->SecuritySystem.acknowledge_release(); - } -} - -void TTrain::OnCommand_cabsignalacknowledge(TTrain *Train, command_data const &Command) -{ - // TODO: visual feedback - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->SecuritySystem.has_separate_acknowledge()) - { - Train->mvOccupied->SecuritySystem.cabsignal_reset(); - Train->ggSHPResetButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - Train->ggSHPResetButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) -{ - if (Train->allowBatteryToggle || Command.action != GLFW_REPEAT) - { - // keep the switch from flipping back and forth if key is held down - if (false == Train->mvOccupied->Power24vIsAvailable) - { - // turn on - OnCommand_batteryenable(Train, Command); - } - else - { - // turn off - OnCommand_batterydisable(Train, Command); - } - } -} - -void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->isBatteryButtonImpulse) - { // regular button behavior - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - - Train->mvOccupied->BatterySwitch(true); - Train->allowBatteryToggle = false; - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->ggBatteryButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggBatteryButton.UpdateValue(0.5f); - } - Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->allowBatteryToggle = true; - } - } - else // impulse button behavior - { - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->shouldHoldBatteryButton) - { - // jesli przycisk trzeba przytrzymac - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer - } - else - { - // jesli przycisk dziala od razu - Train->mvOccupied->BatterySwitch(true); - Train->allowBatteryToggle = false; - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - - // visual feedback - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->fBatteryTimer = -1.f; // - Train->allowBatteryToggle = true; - Train->mvOccupied->batterySwAlreadyFired = false; - } - else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) - { - // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == false && !Train->mvOccupied->batterySwAlreadyFired) - { - Train->mvOccupied->BatterySwitch(true); - Train->mvOccupied->batterySwAlreadyFired = true; - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - Train->allowBatteryToggle = false; - } - } - } -} - -void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->isBatteryButtonImpulse) - { // regular button behavior - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - - Train->mvOccupied->BatterySwitch(false); - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->ggBatteryButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggBatteryButton.UpdateValue(0.5f); - } - Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } - else // impulse button behavior - { - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->shouldHoldBatteryButton) - { - // jesli przycisk trzeba przytrzymac - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->fBatteryTimer = Train->mvOccupied->BatteryButtonHoldTime; // start timer - } - else - { - // jesli przycisk dziala od razu - Train->mvOccupied->BatterySwitch(false); - Train->allowBatteryToggle = false; - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - // visual feedback - Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); - Train->allowBatteryToggle = true; - Train->mvOccupied->batterySwAlreadyFired = false; - } - else if (Command.action == GLFW_REPEAT && Train->mvOccupied->shouldHoldBatteryButton) - { - // trzymamy przycisk - if (Train->fBatteryTimer <= 0.0 && Train->mvOccupied->Battery == true && !Train->mvOccupied->batterySwAlreadyFired) - { - Train->mvOccupied->BatterySwitch(false); - Train->mvOccupied->batterySwAlreadyFired = true; - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - Train->allowBatteryToggle = false; - } - } - } -} - -void TTrain::OnCommand_cabactivationtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_REPEAT) - { - // keep the switch from flipping back and forth if key is held down - if (0 == Train->mvOccupied->CabActive) - { - // turn on - OnCommand_cabactivationenable(Train, Command); - } - else - { - // turn off - OnCommand_cabactivationdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_cabactivationenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (Train->ggCabActivationButton.type() == TGaugeType::push) - { - Train->ggCabActivationButton.UpdateValue(1.0f, Train->dsbSwitch); - } - - Train->mvOccupied->CabActivisation(); - - // side-effects - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggCabActivationButton.UpdateValue(0.5f); - } -} - -void TTrain::OnCommand_cabactivationdisable(TTrain *Train, command_data const &Command) -{ - // TBD, TODO: ewentualnie zablokować z FIZ, np. w samochodach się nie odłącza akumulatora - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (Train->ggCabActivationButton.type() == TGaugeType::push) - { - Train->ggCabActivationButton.UpdateValue(0.0f, Train->dsbSwitch); - } - - Train->mvOccupied->CabDeactivisation(); - if (Train->mvOccupied->LightsPosNo > 0 && Train->mvOccupied->InactiveCabFlag & activation::redmarkers) - { - Train->Dynamic()->SetLights(); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->ggCabActivationButton.UpdateValue(0.5f); - } -} - -void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[end::front]}; - auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches - if (state) - { - OnCommand_pantographlowerfront(Train, Command); - } - else - { - OnCommand_pantographraisefront(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // impulse switches return automatically to neutral position - if (Train->mvOccupied->PantSwitchType == "impulse") - { - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, operation_t::none, ismanual ? range_t::local : range_t::consist); - } - } -} - -void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const &pantograph{Train->mvPantographUnit->Pantographs[end::rear]}; - auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches - if (state) - { - OnCommand_pantographlowerrear(Train, Command); - } - else - { - OnCommand_pantographraiserear(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // impulse switches return automatically to neutral position - if (Train->mvOccupied->PantSwitchType == "impulse") - { - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); - } - } -} - -void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantfront_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglefront(Train, Command); - } -} - -void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantrear_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::enable_on : operation_t::enable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglerear(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - // prevent operation without submodel outside of engine compartment - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::front, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglefront(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Command) -{ - - // HACK: presence of pantograph selector prevents manual operation of the individual valves - if (Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->mvOccupied->PantSwitchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers - auto const ismanual{Train->iCabn == 0}; - Train->mvOccupied->OperatePantographValve(end::rear, Train->mvOccupied->PantSwitchType == "impulse" ? operation_t::disable_on : operation_t::disable, - ismanual ? range_t::local : range_t::consist); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtogglerear(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerall(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggPantAllDownButton.SubModel == nullptr) - { - // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch - if (Command.action == GLFW_PRESS) - { - WriteLog("Lower All Pantographs switch is missing, or wasn't defined"); - } - return; - } - - if (Train->ggPantAllDownButton.type() == TGaugeType::toggle) - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - Train->mvPantographUnit->DropAllPantographs(false == Train->mvPantographUnit->PantAllDown); - // visual feedback - Train->ggPantAllDownButton.UpdateValue(Train->mvPantographUnit->PantAllDown ? 1.0 : 0.0, Train->dsbSwitch); - } - } - else - { - // impulse switch - Train->mvControlled->DropAllPantographs(Command.action == GLFW_PRESS); - // visual feedback - Train->ggPantAllDownButton.UpdateValue(Command.action == GLFW_PRESS ? 1.0 : 0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_pantographselectnext(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - if (false == Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - Train->change_pantograph_selection(1); -} - -void TTrain::OnCommand_pantographselectprevious(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - if (false == Train->m_controlmapper.contains("pantselect_sw:")) - { - return; - } - - Train->change_pantograph_selection(-1); -} - -void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // recalculate pantograph state (hujhujhuj) - Train->change_pantograph_selection(1); - Train->change_pantograph_selection(-1); - - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const state{Train->mvPantographUnit->PantsValve.is_enabled || Train->mvPantographUnit->PantsValve.is_active}; // fallback for impulse switches - if (state) - { - OnCommand_pantographlowerselected(Train, Command); - } - else - { - OnCommand_pantographraiseselected(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // impulse switches return automatically to neutral position - if (Train->m_controlmapper.contains("pantselectedoff_sw:")) - { - // two buttons setup - if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) - { - Train->mvOccupied->OperatePantographsValve(operation_t::enable_off); - // visual feedback - Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); - } - if (Train->ggPantSelectedDownButton.type() != TGaugeType::toggle) - { - Train->mvOccupied->OperatePantographsValve(operation_t::disable_off); - // visual feedback - Train->ggPantSelectedDownButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else - { - if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) - { - // special case, just one impulse switch controlling both states - // with neutral position mid-way - Train->mvOccupied->OperatePantographsValve(operation_t::none); - // visual feedback - Train->ggPantSelectedButton.UpdateValue(0.5, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_pantographraiseselected(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // raise selected - Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedButton.type() != TGaugeType::toggle ? operation_t::enable_on : operation_t::enable); - // visual feedback - Train->ggPantSelectedButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtoggleselected(Train, Command); - } -} - -void TTrain::OnCommand_pantographlowerselected(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // lower selected - Train->mvOccupied->OperatePantographsValve(Train->ggPantSelectedDownButton.type() != TGaugeType::toggle ? operation_t::disable_on : operation_t::disable); - // visual feedback - if (Train->m_controlmapper.contains("pantselectedoff_sw:")) - { - // two button setup - Train->ggPantSelectedDownButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single button - Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch - OnCommand_pantographtoggleselected(Train, Command); - } -} - -void TTrain::update_pantograph_valves() -{ - using enum operation_t; - - auto const &presets{mvOccupied->PantsPreset.first}; - auto const &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; - - auto const preset{presets[selection] - '0'}; - auto const swapends{cab_to_end() != end::front}; - // check desired states for both pantographs; value: whether the pantograph should be raised - auto const frontstate{preset & (swapends ? 2 : 1)}; - auto const rearstate{preset & (swapends ? 1 : 2)}; - mvOccupied->OperatePantographValve(end::front, frontstate ? enable : disable); - mvOccupied->OperatePantographValve(end::rear, rearstate ? enable : disable); -} - -void TTrain::change_pantograph_selection(int const Change) -{ - - auto const &presets{mvOccupied->PantsPreset.first}; - auto &selection{mvOccupied->PantsPreset.second[cab_to_end()]}; - auto const initialstate{selection}; - selection = std::clamp(selection + Change, 0, std::max(static_cast(presets.size() - 1), 0)); - - if (selection == initialstate) - { - return; - } // no change, nothing to do - - // potentially adjust pantograph valves to match the new state - if (false == m_controlmapper.contains("pantvalves_sw:")) - { - update_pantograph_valves(); - } -} - -void TTrain::OnCommand_pantographvalvesupdate(TTrain *Train, command_data const &Command) -{ - - bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - if (hasSeparateSwitches) - { - // implement action - Train->update_pantograph_valves(); - // visual feedback - Train->ggPantValvesUpdate.UpdateValue(1.0, Train->dsbSwitch); - } - - // Old logic to maintain compatibility - else - { - Train->update_pantograph_valves(); - Train->ggPantValvesButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - // NOTE: pantvalves_sw: is a specialized button, with no toggle behavior support - if (hasSeparateSwitches) - Train->ggPantValvesUpdate.UpdateValue(0.5, Train->dsbSwitch); - - // Old logic to maintain compatibility - else - Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_pantographvalvesoff(TTrain *Train, command_data const &Command) -{ - - bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // implement action - Train->mvOccupied->OperatePantographValve(end::front, operation_t::disable); - Train->mvOccupied->OperatePantographValve(end::rear, operation_t::disable); - // visual feedback - if (hasSeparateSwitches) - Train->ggPantValvesOff.UpdateValue(1.0, Train->dsbSwitch); - else - Train->ggPantValvesButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - // NOTE: pantvalves_sw: is a speciali zed button, with no toggle behavior support - if (hasSeparateSwitches) - Train->ggPantValvesOff.UpdateValue(0.f, Train->dsbSwitch); - else - Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only react to press - if (Train->mvControlled->bPantKurek3 == false) - { - // connect pantographs with primary tank - OnCommand_pantographcompressorvalveenable(Train, Command); - } - else - { - // connect pantograps with pantograph compressor - OnCommand_pantographcompressorvalvedisable(Train, Command); - } - } -} - -void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_data const &Command) -{ - - - if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) - { - // tylko w maszynowym, unless actual device is present - return; - } - - if (Command.action == GLFW_PRESS) - { - // only react to press - // connect pantographs with primary tank - Train->mvControlled->bPantKurek3 = true; - // visual feedback: - Train->ggPantCompressorValve.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_data const &Command) -{ - - - if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == valveispresent) - { - // tylko w maszynowym, unless actual device is present - return; - } - - if (Command.action == GLFW_PRESS) - { - // only react to press - // connect pantograps with pantograph compressor - Train->mvControlled->bPantKurek3 = false; - // visual feedback: - Train->ggPantCompressorValve.UpdateValue(1.0); - } -} - -void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data const &Command) -{ - - // tylko w maszynowym, unless actual device is present - if (auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->mvOccupied == Train->mvPantographUnit && Train->iCabn == 0)}; false == switchispresent) - { - return; - } - - if (Command.action != GLFW_RELEASE) - { - // press or hold to activate - if (Train->mvPantographUnit->PantPress < 4.8 && true == Train->mvPantographUnit->Power24vIsAvailable) - { - // needs live power source and low enough pressure to work - Train->mvPantographUnit->PantCompFlag = true; - } - // visual feedback - Train->ggPantCompressorButton.UpdateValue(1.0); - } - else - { - // release to disable - Train->mvPantographUnit->PantCompFlag = false; - // visual feedback - Train->ggPantCompressorButton.UpdateValue(0.0); - } -} - -namespace -{ -// whether the cab's main_off_bt is the bistable lever of the line breaker's hold coil (eu07/maszyna#364) -bool is_hold_coil_lever(TGauge const &Button) -{ - return Button.SubModel != nullptr && hold_coil_lever::is_bistable(Button.type_declared(), Button.type() == TGaugeType::toggle); -} -} // namespace - -void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // press or hold... - // a single two-state lever stays where it was put, also when the line breaker gets knocked out - auto const latchinglever{Train->ggMainOnButton.SubModel == nullptr && Train->ggMainOffButton.SubModel == nullptr && Train->ggMainButton.SubModel != nullptr && - Train->ggMainButton.type() == TGaugeType::toggle}; - switch (linebreaker::pressed(Train->m_linebreakerstate, latchinglever, Train->ggMainButton.GetDesiredValue() > 0.5)) - { - case linebreaker::toggle::close: - // ...to close the circuit - if (is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue())) - { - // the one key works both controls: the hold coil lever goes back on first, or the line breaker couldn't close - Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - // NOTE: bit of a dirty shortcut here - OnCommand_linebreakerclose(Train, Command); - break; - case linebreaker::toggle::open: - // ...to open the circuit, or to put the lever off if the circuit was already opened - OnCommand_linebreakeropen(Train, Command); - break; - default: - break; - } - } - else if (Command.action == GLFW_RELEASE) - { - // release... - if (Train->ggMainOnButton.SubModel != nullptr || Train->ggMainButton.type() != TGaugeType::toggle) - { - // only impulse switches react to release events - // NOTE: we presume dedicated state switch is of impulse type - if (Train->m_linebreakerstate == 0) - { - // ...after opening circuit, or holding for too short time to close it - OnCommand_linebreakeropen(Train, Command); - } - else - { - // ...after closing the circuit - // NOTE: bit of a dirty shortcut here - OnCommand_linebreakerclose(Train, Command); - } - } - // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls - Train->ggIgnitionKey.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (is_hold_coil_lever(Train->ggMainOffButton)) - { - // the bistable lever goes over to its other position and stays there - auto const position{hold_coil_lever::operated(Train->ggMainOffButton.GetDesiredValue())}; - Train->ggMainOffButton.UpdateValue(position, Train->dsbSwitch); - if (false == hold_coil_lever::cuts_off(position)) - { - // the hold coil is fed again, which by itself doesn't close the line breaker - return; - } - } - else if (Train->ggMainOffButton.SubModel != nullptr) - { - Train->ggMainOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Train->ggMainButton.SubModel != nullptr) - { - Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->mvControlled->MainCircuitOpensWithStarterOnly()) - { - // NOTE: legacy behaviour, for vehicles equipped only with impulse close switch - // it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress - Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); - return; - } - // a diesel with only the starter button gets its engine stopped. the button stays put: held down, it would start the engine again - // play sound immediately when the switch is hit, not after release - Train->fMainRelayTimer = 0.0f; - - if (Train->m_linebreakerstate == 0) - { - return; - } // already in the desired state - - if (true == Train->mvControlled->MainSwitch(false, Train->mvControlled->MainSwitchRange())) - { - Train->m_linebreakerstate = 0; - if (Train->mvControlled->MainSwitchRange() != range_t::local) - { - // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on - // they'd start them again after the delay - for (auto &controls : Train->m_remotelinebreakers) - { - if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) - { - controls.main_switch.UpdateValue(0.0); - } - } - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - // we don't exactly know which of the two buttons was used, so reset both - // for setup with two separate swiches - if (Train->ggMainOnButton.SubModel != nullptr) - { - Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - if (Train->ggMainOffButton.SubModel != nullptr && false == is_hold_coil_lever(Train->ggMainOffButton)) - { - // (the bistable hold coil lever stays where it was put) - Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - // and the two-state switch too, for good measure - if (Train->ggMainButton.SubModel != nullptr) - { - Train->ggMainButton.UpdateValue(Train->ggMainButton.type() != TGaugeType::toggle ? 0.5 : 0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (Train->ggMainOnButton.SubModel != nullptr) - { - // two separate switches to close and break the circuit - Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Train->ggMainButton.SubModel != nullptr) - { - // single two-state switch - Train->ggMainButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // no switch capable of doing the job - // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls - Train->ggIgnitionKey.UpdateValue(1.0); - return; - } - // the actual closing of the line breaker is handled in the train update routine - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - if (Train->ggMainOnButton.SubModel != nullptr) - { - // setup with two separate switches - Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Train->ggMainButton.SubModel != nullptr && Train->ggMainButton.type() != TGaugeType::toggle) - { - Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); - } - - if (Train->m_linebreakerstate == 1) - { - return; - } // already in the desired state - - // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched - // NOTE: this behaviour should depend on MainOnButton presence and type_delayed - // TODO: change it when/if vehicle definition files get their proper switch types - if (Train->m_linebreakerstate == 2 && Train->mvControlled->EngineType == TEngineType::ElectricSeriesMotor) - { - // try to finalize state change of the line breaker, set the state based on the outcome - Train->m_linebreakerstate = Train->mvControlled->MainSwitch(true, Train->mvControlled->MainSwitchRange()) ? 1 : 0; - } - // on button release reset the closing timer - Train->fMainRelayTimer = 0.0f; - } -} - -namespace -{ - -// which of the switches of the other vehicles in multiple a command works: 0 the second vehicle's, 1 the third one's -std::size_t remote_linebreaker_index(user_command const Command) -{ - using enum user_command; - return (Command == linebreakertogglec || Command == linebreakeropenc || Command == linebreakerclosec) ? 1 : 0; -} - -// the impulse switches of another vehicle's line breaker spring back when let go, whichever way they were pressed -void release_remote_linebreaker(TTrain::remote_linebreaker &Controls, std::optional &Sound) -{ - if (Controls.on_button.SubModel != nullptr) - { - Controls.on_button.UpdateValue(0.0, Sound); - } - if (Controls.off_button.SubModel != nullptr) - { - Controls.off_button.UpdateValue(0.0, Sound); - } - if (Controls.main_switch.SubModel != nullptr && Controls.main_switch.type() != TGaugeType::toggle) - { - Controls.main_switch.UpdateValue(0.5, Sound); - } - Controls.held_without_switch = false; -} - -} // namespace - -TMoverParameters *TTrain::remote_engine(std::size_t const Index) const -{ - return engine_start::engine(*mvOccupied, *mvControlled, static_cast(Index) + 2); -} - -void TTrain::OnCommand_linebreakertoggleremote(TTrain *Train, command_data const &Command) -{ - auto const index{remote_linebreaker_index(Command.command)}; - auto &controls{Train->m_remotelinebreakers[index]}; - - if (Command.action == GLFW_PRESS) - { - // a two-state switch goes the other way than it stands, an impulse one the other way than the engine is - bool close{false}; - if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) - { - close = controls.main_switch.GetDesiredValue() < 0.5; - } - else - { - auto const *engine{Train->remote_engine(index)}; - close = engine == nullptr || false == engine_start::remote_switch::is_running(*engine); - } - if (close) - { - OnCommand_linebreakercloseremote(Train, Command); - } - else - { - OnCommand_linebreakeropenremote(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (controls.on_button.SubModel != nullptr || controls.main_switch.type() != TGaugeType::toggle) - { - // only impulse switches react to release events - release_remote_linebreaker(controls, Train->dsbSwitch); - } - controls.held_without_switch = false; - } -} - -void TTrain::OnCommand_linebreakeropenremote(TTrain *Train, command_data const &Command) -{ - auto const index{remote_linebreaker_index(Command.command)}; - auto &controls{Train->m_remotelinebreakers[index]}; - - if (Command.action == GLFW_PRESS) - { - // visual feedback - if (controls.off_button.SubModel != nullptr) - { - controls.off_button.UpdateValue(1.0, Train->dsbSwitch); - } - else if (controls.main_switch.SubModel != nullptr) - { - controls.main_switch.UpdateValue(0.0, Train->dsbSwitch); - } - controls.held_without_switch = false; - if (auto *engine{Train->remote_engine(index)}; engine != nullptr) - { - engine_start::remote_switch::open(*engine); - } - } - else if (Command.action == GLFW_RELEASE) - { - release_remote_linebreaker(controls, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_linebreakercloseremote(TTrain *Train, command_data const &Command) -{ - auto const index{remote_linebreaker_index(Command.command)}; - auto &controls{Train->m_remotelinebreakers[index]}; - - if (Command.action == GLFW_PRESS) - { - // visual feedback; the line breaker closes in the train update, once the switch was held long enough - if (controls.on_button.SubModel != nullptr) - { - controls.on_button.UpdateValue(1.0, Train->dsbSwitch); - } - else if (controls.main_switch.SubModel != nullptr) - { - controls.main_switch.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // no switch in the cab, the command alone holds it - controls.held_without_switch = true; - } - } - else if (Command.action == GLFW_RELEASE) - { - release_remote_linebreaker(controls, Train->dsbSwitch); - } -} - -void TTrain::update_remote_linebreakers(double const Deltatime) -{ - for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) - { - auto &controls{m_remotelinebreakers[index]}; - auto *engine{remote_engine(index)}; - auto const closeheld{controls.held_without_switch || (controls.main_switch.SubModel != nullptr && controls.main_switch.GetDesiredValue() > 0.95) || - (controls.on_button.SubModel != nullptr && controls.on_button.GetDesiredValue() > 0.95)}; - auto const openheld{controls.off_button.SubModel != nullptr && controls.off_button.GetDesiredValue() > 0.95}; - // as with the cab's own switch, an electric locomotive's impulse switch closes the line breaker when let go - auto const closesonrelease{engine != nullptr && controls.on_button.SubModel != nullptr && engine->EngineType == TEngineType::ElectricSeriesMotor}; - controls.state.update(engine, closeheld, openheld, Deltatime, closesonrelease); - } -} - -void TTrain::OnCommand_fuelpumptoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_fuelpumpenable(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->FuelPump.is_enabled) - { - // turn on - OnCommand_fuelpumpenable(Train, Command); - } - else - { - // turn off - OnCommand_fuelpumpdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_fuelpumpenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(false); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(true); - Train->mvControlled->FuelPumpSwitchOff(false); - } - } -} - -void TTrain::OnCommand_fuelpumpdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->FuelPumpSwitch(false); - Train->mvControlled->FuelPumpSwitchOff(true); - } - } -} - -void TTrain::OnCommand_oilpumptoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggOilPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_oilpumpenable(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->OilPump.is_enabled) - { - // turn on - OnCommand_oilpumpenable(Train, Command); - } - else - { - // turn off - OnCommand_oilpumpdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_oilpumpenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggOilPumpButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(false); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(true); - Train->mvControlled->OilPumpSwitchOff(false); - } - } -} - -void TTrain::OnCommand_oilpumpdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggOilPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->OilPumpSwitch(false); - Train->mvControlled->OilPumpSwitchOff(true); - } - } -} - -void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_REPEAT) - { - return; - } - - auto *vehicle{Train->mvControlled}; - if (Train->ggOilFuelPumpButton.type() == TGaugeType::push) - { - // impulse switch, as the separate ones: held to start both pumps - auto const pressed{Command.action == GLFW_PRESS}; - Train->ggOilFuelPumpButton.UpdateValue(pressed ? 1.0 : 0.0, Train->dsbSwitch); - vehicle->FuelPumpSwitch(pressed); - vehicle->OilPumpSwitch(pressed); - return; - } - // two-state switch, only cares about press events - if (Command.action != GLFW_PRESS) - { - return; - } - // both pumps go off if both were on, otherwise both go on; a pump started automatically doesn't take part - auto const enable{false == vehicle->OilFuelPumpsEnabled()}; - Train->ggOilFuelPumpButton.UpdateValue(enable ? 1.0 : 0.0, Train->dsbSwitch); - vehicle->FuelPumpSwitch(enable); - vehicle->FuelPumpSwitchOff(false == enable); - vehicle->OilPumpSwitch(enable); - vehicle->OilPumpSwitchOff(false == enable); -} - -void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterHeater.breaker) - { - // turn on - OnCommand_waterheaterbreakerclose(Train, Command); - } - else - { - // turn off - OnCommand_waterheaterbreakeropen(Train, Command); - } - } -} - -void TTrain::OnCommand_waterheaterbreakerclose(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterBreakerButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterHeater.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterHeaterBreakerSwitch(true); - } -} - -void TTrain::OnCommand_waterheaterbreakeropen(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterBreakerButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterHeater.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterHeaterBreakerSwitch(false); - } -} - -void TTrain::OnCommand_waterheatertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterHeater.is_enabled) - { - // turn on - OnCommand_waterheaterenable(Train, Command); - } - else - { - // turn off - OnCommand_waterheaterdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_waterheaterenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterHeater.is_enabled) - { - return; - } // already enabled - - Train->mvControlled->WaterHeaterSwitch(true); - } -} - -void TTrain::OnCommand_waterheaterdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterHeaterButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterHeater.is_enabled) - { - return; - } // already disabled - - Train->mvControlled->WaterHeaterSwitch(false); - } -} - -void TTrain::OnCommand_waterpumpbreakertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterPump.breaker) - { - // turn on - OnCommand_waterpumpbreakerclose(Train, Command); - } - else - { - // turn off - OnCommand_waterpumpbreakeropen(Train, Command); - } - } -} - -void TTrain::OnCommand_waterpumpbreakerclose(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpBreakerButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterPump.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterPumpBreakerSwitch(true); - } -} - -void TTrain::OnCommand_waterpumpbreakeropen(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpBreakerButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterPump.breaker) - { - return; - } // already enabled - - Train->mvControlled->WaterPumpBreakerSwitch(false); - } -} - -void TTrain::OnCommand_waterpumptoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggWaterPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_waterpumpenable(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->WaterPump.is_enabled) - { - // turn on - OnCommand_waterpumpenable(Train, Command); - } - else - { - // turn off - OnCommand_waterpumpdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_waterpumpenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggWaterPumpButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(true); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(false); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(true); - Train->mvControlled->WaterPumpSwitchOff(false); - } - } -} - -void TTrain::OnCommand_waterpumpdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggWaterPumpButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); - Train->mvControlled->WaterPumpSwitch(false); - Train->mvControlled->WaterPumpSwitchOff(true); - } - } -} - -void TTrain::OnCommand_watercircuitslinktoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->WaterCircuitsLink) - { - // turn on - OnCommand_watercircuitslinkenable(Train, Command); - } - else - { - // turn off - OnCommand_watercircuitslinkdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_watercircuitslinkenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterCircuitsLinkButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->mvControlled->WaterCircuitsLink) - { - return; - } // already enabled - - Train->mvControlled->WaterCircuitsLinkSwitch(true); - } -} - -void TTrain::OnCommand_watercircuitslinkdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggWaterCircuitsLinkButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->mvControlled->WaterCircuitsLink) - { - return; - } // already disabled - - Train->mvControlled->WaterCircuitsLinkSwitch(false); - } -} - -void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : Train->mvOccupied->ConvOvldFlag)}; - - if (Train->mvOccupied->ConvSwitchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->mvOccupied->Power110vIsAvailable && false == overloadrelayisopen) - { - // turn on - OnCommand_converterenable(Train, Command); - } - else - { - // turn off - OnCommand_converterdisable(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // on button release... - if (Train->mvOccupied->ConvSwitchType == "impulse") - { - // ...return switches to start position if applicable - Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggConverterOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_converterenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggConverterButton.UpdateValue(1.0, Train->dsbSwitch); - - // impulse type switch has no effect if there's no power - // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - if (Train->mvOccupied->ConvSwitchType != "impulse" || Train->mvControlled->Mains) - { - // won't start if the line breaker button is still held - Train->mvOccupied->ConverterSwitch(true); - } - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_convertertoggle(Train, Command); - } -} - -void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggConverterOffButton.SubModel != nullptr) - { - Train->ggConverterOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - - Train->mvOccupied->ConverterSwitch(false); - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_convertertoggle(Train, Command); - } -} - -void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->ConverterStart == start_t::automatic) - { - // let the automatic thing do its automatic thing... - return; - } - if (Train->ggConverterLocalButton.SubModel == nullptr) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->ConverterAllowLocal && Train->ggConverterLocalButton.GetValue() < 0.5) - { - // turn on - // visual feedback - Train->ggConverterLocalButton.UpdateValue(1.0, Train->dsbSwitch); - // effect - Train->mvOccupied->ConverterAllowLocal = true; - /* - if( true == Train->mvControlled->ConverterSwitch( true, range::local ) ) { - // side effects - // control the compressor, if it's paired with the converter - if( Train->mvControlled->CompressorPower == 2 ) { - // hunter-091012: tak jest poprawnie - Train->mvControlled->CompressorSwitch( true, range::local ); - } - } - */ - } - else - { - // turn off - // visual feedback - Train->ggConverterLocalButton.UpdateValue(0.0, Train->dsbSwitch); - // effect - Train->mvOccupied->ConverterAllowLocal = false; - /* - if( true == Train->mvControlled->ConverterSwitch( false, range::local ) ) { - // side effects - // control the compressor, if it's paired with the converter - if( Train->mvControlled->CompressorPower == 2 ) { - // hunter-091012: tak jest poprawnie - Train->mvControlled->CompressorSwitch( false, range::local ); - } - // if there's no (low voltage) power source left, drop pantographs - if( false == Train->mvControlled->Battery ) { - Train->mvControlled->PantFront( false, range::local ); - Train->mvControlled->PantRear( false, range::local ); - } - } - */ - } - } -} - -void TTrain::OnCommand_converteroverloadrelayreset(TTrain *Train, command_data const &Command) -{ - - if (Train->ggConverterFuseButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Converter Overload Relay Reset button is missing, or wasn't defined"); - } - // return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggConverterFuseButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->RelayReset(relay_t::primaryconverteroverload); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggConverterFuseButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->IsAnyCompressorEnabled : Train->mvOccupied->CompressorAllow)}; - - if (false == compressorisenabled) - { - // turn on - OnCommand_compressorenable(Train, Command); - } - else - { - // turn off - OnCommand_compressordisable(Train, Command); - } - } - /* - // disabled because we don't have yet support for compressor switch type definition - else if( Command.action == GLFW_RELEASE ) { - // on button release... - if( Train->mvOccupied->CompSwitchType == "impulse" ) { - // ...return switches to start position if applicable - Train->ggCompressorButton.UpdateValue( 0.0, Train->dsbSwitch ); - Train->ggCompressorOffButton.UpdateValue( 0.0, Train->dsbSwitch ); - } - } - */ -} - -void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggCompressorButton.UpdateValue(1.0, Train->dsbSwitch); - - // impulse type switch has no effect if there's no power - // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway - // if( ( Train->mvOccupied->CompSwitchType != "impulse" ) - // || ( Train->mvControlled->Mains ) ) { - - Train->mvOccupied->CompressorSwitch(true); - // } - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_compressortoggle(Train, Command); - } -} - -void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->CompressorPower >= 2) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggCompressorButton.UpdateValue(0.0, Train->dsbSwitch); - /* - if( Train->ggCompressorOffButton.SubModel != nullptr ) { - Train->ggCompressorOffButton.UpdateValue( 1.0, Train->dsbSwitch ); - } - */ - Train->mvOccupied->CompressorSwitch(false); - } - else if (Command.action == GLFW_RELEASE) - { - // potentially reset impulse switch position, using shared code branch - OnCommand_compressortoggle(Train, Command); - } -} - -void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorPower >= 2) - { - return; - } - if (Train->ggCompressorLocalButton.SubModel == nullptr) - { - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->CompressorAllowLocal) - { - // turn on - // visual feedback - Train->ggCompressorLocalButton.UpdateValue(1.0, Train->dsbSwitch); - // effect - Train->mvOccupied->CompressorAllowLocal = true; - } - else - { - // turn off - // visual feedback - Train->ggCompressorLocalButton.UpdateValue(0.0, Train->dsbSwitch); - // effect - Train->mvOccupied->CompressorAllowLocal = false; - } - } -} - -void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorListPosNo == 0) - { - return; - } - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggCompressorListButton.type() == TGaugeType::push) - { - // impulse switch - if (Train->mvOccupied->CompressorListPosNo < Train->mvOccupied->CompressorListDefPos + 1) - { - return; - } - - Train->mvOccupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->mvOccupied->CompressorListDefPos + 1 : Train->mvOccupied->CompressorListDefPos); - // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } - else - { - // multi-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo || true == Train->mvOccupied->CompressorListWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos < Train->mvOccupied->CompressorListPosNo ? Train->mvOccupied->CompressorListPos + 1 : 1); // wrap mode - // visual feedback - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorListPosNo == 0) - { - return; - } - if (Command.action != GLFW_PRESS) - { - return; - } // one change per key press - - if (Train->ggCompressorListButton.type() == TGaugeType::push) - { - // impulse switch toggles only between positions 'default' and 'default+1' - return; - } - - if (Train->mvOccupied->CompressorListPos > 1 || true == Train->mvOccupied->CompressorListWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListPos > 1 ? Train->mvOccupied->CompressorListPos - 1 : Train->mvOccupied->CompressorListPosNo); // wrap mode - - // visual feedback - if (Train->ggCompressorListButton.SubModel != nullptr) - { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->CompressorListPosNo == 0) - { - return; - } - if (Command.action != GLFW_PRESS) - { - return; - } // one change per key press - - Train->mvOccupied->ChangeCompressorPreset(Train->mvOccupied->CompressorListDefPos); - - // visual feedback - if (Train->ggCompressorListButton.SubModel != nullptr) - { - Train->ggCompressorListButton.UpdateValue(static_cast(Train->mvOccupied->CompressorListPos - 1), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_motorblowerstogglefront(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_motorblowersenablefront(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->MotorBlowers[end::front].is_enabled) - { - // turn on - OnCommand_motorblowersenablefront(Train, Command); - } - else - { - // turn off - OnCommand_motorblowersdisablefront(Train, Command); - } - } -} - -void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::front); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::front); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - } - } -} - -void TTrain::OnCommand_motorblowersdisablefront(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - } - } -} - -void TTrain::OnCommand_motorblowerstogglerear(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no off button so we always try to turn it on - OnCommand_motorblowersenablerear(Train, Command); - } - else - { - // two-state switch - if (Command.action == GLFW_RELEASE) - { - return; - } - - if (false == Train->mvControlled->MotorBlowers[end::rear].is_enabled) - { - // turn on - OnCommand_motorblowersenablerear(Train, Command); - } - else - { - // turn off - OnCommand_motorblowersdisablerear(Train, Command); - } - } -} - -void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::rear); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::rear); - } - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(true, end::rear); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); - } - } -} - -void TTrain::OnCommand_motorblowersdisablerear(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) - { - // impulse switch - // currently there's no disable return type switch - return; - } - else - { - // two-state switch, only cares about press events - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitch(false, end::rear); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); - } - } -} - -void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - if (Train->ggMotorBlowersAllOffButton.type() == TGaugeType::push) - { - // impulse switch - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggMotorBlowersAllOffButton.UpdateValue(1.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggMotorBlowersAllOffButton.UpdateValue(0.f, Train->dsbSwitch); - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); - } - } - else - { - // two-state switch, only cares about press events - // NOTE: generally this switch doesn't come in two-state form - if (Command.action == GLFW_PRESS) - { - if (Train->ggMotorBlowersAllOffButton.GetDesiredValue() < 0.5f) - { - // switch is off, activate - Train->mvControlled->MotorBlowersSwitchOff(true, end::front); - Train->mvControlled->MotorBlowersSwitchOff(true, end::rear); - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); - } - else - { - // deactivate - Train->mvControlled->MotorBlowersSwitchOff(false, end::front); - Train->mvControlled->MotorBlowersSwitchOff(false, end::rear); - // visual feedback - Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); - } - } - } -} - -void TTrain::OnCommand_coolingfanstoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - Train->mvControlled->RVentForceOn = !Train->mvControlled->RVentForceOn; -} - -void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Command) -{ - - // TODO: don't rely on presense of 3d model to determine presence of the switch - if (Train->ggStLinOffButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); - } - return; - } - // HACK: because we don't have modeled actual circuits this is a simplification of the real mechanics - // namely, pressing the button will flip it in the entire unit, which isn't exactly physically possible - if (Command.action == GLFW_PRESS) - { - // button works while it's held down but we can ignore repeats - if (false == Train->mvControlled->StLinSwitchOff) - { - // open the connectors - // visual feedback - Train->ggStLinOffButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->StLinSwitchOff = true; - Train->set_paired_open_motor_connectors_button(true); - } - else - { - // potentially close the connectors - OnCommand_motorconnectorsclose(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // button released - if (Train->mvControlled->StLinSwitchType != "toggle") - { - // default button type (impulse) ceases its work on button release - // visual feedback - Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); - - Train->mvControlled->StLinSwitchOff = false; - Train->set_paired_open_motor_connectors_button(false); - } - } -} - -void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &Command) -{ - - // TODO: don't rely on presense of 3d model to determine presence of the switch - if (Train->ggStLinOffButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - if (Train->mvControlled->StLinSwitchType == "toggle") - { - // default type of button (impulse) has only one effect on press, but the toggle type can toggle the state - // visual feedback - Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - - if (false == Train->mvControlled->StLinSwitchOff) - { - return; - } // already closed - - Train->mvControlled->StLinSwitchOff = false; - Train->set_paired_open_motor_connectors_button(false); - } -} - -void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Command) -{ - - if (Train->mvControlled->TrainType == dt_EZT ? Train->mvControlled != Train->mvOccupied : Train->iCabn != 0) - { - // tylko w maszynowym - return; - } - - if (Command.action == GLFW_PRESS) - { - Train->mvControlled->CutOffEngine(); - } -} - -void TTrain::OnCommand_motoroverloadrelaythresholdtoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (true == Train->mvControlled->ShuntModeAllow ? false == Train->mvControlled->ShuntMode : false == Train->mvControlled->MotorOverloadRelayHighThreshold) - { - // turn on - OnCommand_motoroverloadrelaythresholdsethigh(Train, Command); - } - else - { - // turn off - OnCommand_motoroverloadrelaythresholdsetlow(Train, Command); - } - } -} - -void TTrain::OnCommand_motoroverloadrelaythresholdsetlow(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvControlled->CurrentSwitch(false); - // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_motoroverloadrelaythresholdsethigh(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvControlled->CurrentSwitch(true); - // visual feedback - Train->ggMaxCurrentCtrl.UpdateValue(Train->mvControlled->MotorOverloadRelayHighThreshold ? 1 : 0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_motoroverloadrelayreset(TTrain *Train, command_data const &Command) -{ - - if (Train->ggFuseButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Motor Overload Relay Reset button is missing, or wasn't defined"); - } - // return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggFuseButton.UpdateValue(1.0, Train->dsbSwitch); - - Train->mvControlled->FuseOn(); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggFuseButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_universalrelayreset(TTrain *Train, command_data const &Command) -{ - - auto const itemindex = static_cast(Command.command) - static_cast(user_command::universalrelayreset1); - auto &item = Train->ggRelayResetButtons[itemindex]; - - // NOTE: relay reset switches are impulse-only - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->UniversalResetButton(itemindex); - // visual feedback - item.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - item.UpdateValue(0.0); - } -} - -// the cab interior light set by the light preset just selected, if the preset sets one (eu07/maszyna#529). -// the cab light switch (cablight_sw:) is bound to the light state and follows it by itself -void TTrain::set_cab_light_from_lights_preset() -{ - auto const cablight{mvOccupied->LightsPresetCabLight(mvOccupied->LightsPos)}; - if (false == cablight.has_value()) - { - return; - } - auto const set{[&cablight](TCab &Cab) { - Cab.bLight = cablight->light; - Cab.bLightDim = cablight->dim; - }}; - if (false == DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - set(Cabine[iCabn]); - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Cabine) - { - set(cab); - } - } - // the dimmer switch is driven by commands only, move it along - if (ggCabLightDimButton.SubModel != nullptr) - { - ggCabLightDimButton.UpdateValue(cablight->dim ? 1.f : 0.f); - } -} - -void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo == 0) - { - // no preset selector - return; - } - if (Command.action != GLFW_PRESS) - { - // one change per key press - return; - } - - if (Train->mvOccupied->LightsPos < Train->mvOccupied->LightsPosNo || true == Train->mvOccupied->LightsWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->mvOccupied->LightsPos >= Train->mvOccupied->LightsPosNo}; - Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos + 1 : 1; // wrap mode - - Train->Dynamic()->SetLights(); - Train->set_cab_light_from_lights_preset(); - // visual feedback - if (Train->ggLightsButton.SubModel != nullptr) - { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction - if (false == restartcycle) - { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); - } - else - { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); - } - } - } -} - -void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo == 0) - { - // no preset selector - return; - } - if (Command.action != GLFW_PRESS) - { - // one change per key press - return; - } - - if (Train->mvOccupied->LightsPos > 1 || true == Train->mvOccupied->LightsWrap) - { - // active light preset is stored as value in range 1-LigthPosNo - auto const restartcycle{Train->mvOccupied->LightsPos <= 1}; - Train->mvOccupied->LightsPos = false == restartcycle ? Train->mvOccupied->LightsPos - 1 : Train->mvOccupied->LightsPosNo; // wrap mode - - Train->Dynamic()->SetLights(); - Train->set_cab_light_from_lights_preset(); - // visual feedback - if (Train->ggLightsButton.SubModel != nullptr) - { - // HACK: skip submodel animation when restarting cycle, since it plays in the 'wrong' direction - if (false == restartcycle) - { - Train->ggLightsButton.UpdateValue(static_cast(Train->mvOccupied->LightsPos - 1), Train->dsbSwitch); - } - else - { - Train->ggLightsButton.PutValue(static_cast(Train->mvOccupied->LightsPos - 1)); - } - } - } -} - -void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Command) -{ - - auto const vehicleend{Train->cab_to_end()}; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - - if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr) - { - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) - { - // turn on - OnCommand_headlightenableleft(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableleft(Train, Command); - } - } else { - // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0 && - (Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) - { - // turn on - OnCommand_headlightenableleft(Train, Command); - } - else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_left) - { - // switch to red - OnCommand_redmarkerenableleft(Train, Command); - } - else - { - // disable - OnCommand_redmarkerdisableleft(Train, Command); - } - } - } -} - -void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) -{ - // set custom item in Lights inventory - Train->mvOccupied->Lights[end::front][17] = static_cast(Command.param1); - Train->mvOccupied->Lights[end::rear][17] = static_cast(Command.param2); - Train->mvOccupied->LightsPos = 18; // nasza custom pozycja - Train->Dynamic()->SetLights(); -} - -void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); - // implementation - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) - { - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; - } - // if the light is controlled by 3-way switch, disable marker light - if (Train->ggLeftEndLightButton.SubModel == nullptr) - { - Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_left; - } - } -} - -void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - int const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_left) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_left; - // visual feedback - Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &Command) -{ - - auto const vehicleend{Train->cab_to_end()}; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - - if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr) - { - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) - { - // turn on - OnCommand_headlightenableright(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableright(Train, Command); - } - } else { - // if the light is controlled by 3-way switch, handle both headlight and redmarker - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0 && - (Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) - { - // turn on - OnCommand_headlightenableright(Train, Command); - } - else if (Train->mvOccupied->iLights[vehicleend] & light::headlight_right) - { - // switch to red - OnCommand_redmarkerenableright(Train, Command); - } - else - { - // disable - OnCommand_redmarkerdisableright(Train, Command); - } - } - } -} - -void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->ggRightLightButton.UpdateValue(1.0, Train->dsbSwitch); - // implementation - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) - { - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; - } - // if the light is controlled by 3-way switch, disable marker light - if (Train->ggRightEndLightButton.SubModel == nullptr) - { - Train->mvOccupied->iLights[vehicleend] &= ~light::redmarker_right; - } - } -} - -void TTrain::OnCommand_headlightdisableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_right) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_right; - // visual feedback - Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttoggleupper(TTrain *Train, command_data const &Command) -{ - - auto const vehicleend{Train->cab_to_end()}; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) - { - // turn on - OnCommand_headlightenableupper(Train, Command); - } - else - { - // turn off - OnCommand_headlightdisableupper(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) - { - return; - } // already enabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; - // visual feedback - Train->ggUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlightdisableupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::headlight_upper) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::headlight_upper; - // visual feedback - Train->ggUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkertoggleleft(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) - { - // turn on - OnCommand_redmarkerenableleft(Train, Command); - } - else - { - // turn off - OnCommand_redmarkerdisableleft(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) - { - return; - } // already enabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; - // visual feedback - if (Train->ggLeftEndLightButton.SubModel != nullptr) - { - Train->ggLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggLeftLightButton.UpdateValue(-1.0, Train->dsbSwitch); - // if the light is controlled by 3-way switch, disable the headlight - Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_left; - } - } -} - -void TTrain::OnCommand_redmarkerdisableleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_left) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_left; - // visual feedback - if (Train->ggLeftEndLightButton.SubModel != nullptr) - { - Train->ggLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_redmarkertoggleright(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) - { - // turn on - OnCommand_redmarkerenableright(Train, Command); - } - else - { - // turn off - OnCommand_redmarkerdisableright(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) - { - return; - } // already enabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; - // visual feedback - if (Train->ggRightEndLightButton.SubModel != nullptr) - { - Train->ggRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggRightLightButton.UpdateValue(-1.0, Train->dsbSwitch); - // if the light is controlled by 3-way switch, disable the headlight - Train->mvOccupied->iLights[vehicleend] &= ~light::headlight_right; - } - } -} - -void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleend{Train->cab_to_end()}; - - if ((Train->mvOccupied->iLights[vehicleend] & light::redmarker_right) == 0) - { - return; - } // already disabled - - Train->mvOccupied->iLights[vehicleend] ^= light::redmarker_right; - // visual feedback - if (Train->ggRightEndLightButton.SubModel != nullptr) - { - Train->ggRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - else - { - // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch - // this is crude, but for now will do - Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) - { - OnCommand_headlightenablerearleft(Train, Command); - } - else - { - OnCommand_headlightdisablerearleft(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already enabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; - // visual feedback - Train->ggRearLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - if (Command.action == GLFW_PRESS) - { - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already disabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_right) == 0) - { - return; - } - - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_right; - // visual feedback - Train->ggRearLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) - { - OnCommand_headlightenablerearright(Train, Command); - } - else - { - OnCommand_headlightdisablerearright(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; - // visual feedback - Train->ggRearRightLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data const &Command) -{ - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already disabled - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_left) == 0) - { - return; - } - - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_left; - // visual feedback - Train->ggRearRightLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) - { - OnCommand_headlightenablerearupper(Train, Command); - } - else - { - OnCommand_headlightdisablerearupper(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; - // visual feedback - Train->ggRearUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // already disabled? - if ((Train->mvOccupied->iLights[vehicleotherend] & light::headlight_upper) == 0) - { - return; - } - - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::headlight_upper; - // visual feedback - Train->ggRearUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->enableModernDimmer) - return; // if modern dimmer is disabled, skip entire command - if (Command.action == GLFW_PRESS) - { - // update modern dimmer state - if (false == Train->mvOccupied->stepDimmerPosition(1)) - return; // już na maksimum i nie można cyklicznie - auto const dimPos = Train->mvOccupied->modernDimmerPosition; - // update lightning - // Train->Dynamic()->SetLights(); - Train->Dynamic()->SetLightDimmings(); - - // visual feedback - if (Train->ggModernLightDimSw.SubModel != nullptr) - Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); - } -} -void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data const &Command) -{ - if (!Train->mvOccupied->enableModernDimmer) - return; // jeśli dimmer jest wyłączony, olewamy - - if (Command.action == GLFW_PRESS) - { - if (false == Train->mvOccupied->stepDimmerPosition(-1)) - return; // już na minimum i nie można cyklicznie - auto const dimPos = Train->mvOccupied->modernDimmerPosition; - - // Train->Dynamic()->SetLights(); - Train->Dynamic()->SetLightDimmings(); - - if (Train->ggModernLightDimSw.SubModel != nullptr) - Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) - { - OnCommand_redmarkerenablerearleft(Train, Command); - } - else - { - OnCommand_redmarkerdisablerearleft(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; - // visual feedback - Train->ggRearLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_right) == 0) - { - return; - } - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_right; - // visual feedback - Train->ggRearLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) - { - OnCommand_redmarkerenablerearright(Train, Command); - } - else - { - OnCommand_redmarkerdisablerearright(Train, Command); - } - } -} - -void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) - { - // turn on - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; - // visual feedback - Train->ggRearRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data const &Command) -{ - - if (Train->mvOccupied->LightsPosNo > 0) - { - // lights are controlled by preset selector - return; - } - - if (Command.action == GLFW_PRESS) - { - // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc - auto const vehicleotherend{(Train->cab_to_end() == end::front ? end::rear : end::front)}; - if ((Train->mvOccupied->iLights[vehicleotherend] & light::redmarker_left) == 0) - { - return; - } - // turn off - Train->mvOccupied->iLights[vehicleotherend] ^= light::redmarker_left; - // visual feedback - Train->ggRearRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_redmarkerstoggle(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; - - if (vehicle == nullptr) - { - return; - } - - auto locationHead = vehicle->HeadPosition() - glm::dvec3(Command.location); // TODO: Maybe command_data should be dvec3? - auto locationRear = vehicle->RearPosition() - glm::dvec3(Command.location); - int const CouplNr{std::clamp(vehicle->DirectionGet() * (glm::dot(locationHead, locationHead) > glm::dot(locationRear, locationRear) ? 1 : -1), 0, 1)}; // z [-1,1] zrobić [0,1] - - auto const lightset{light::redmarker_left | light::redmarker_right}; - - vehicle->MoverParameters->iLights[CouplNr] = - false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? - vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on - vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off - } -} - -void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; - - if (vehicle == nullptr) - { - return; - } - int const CouplNr{ - std::clamp(vehicle->DirectionGet() * (glm::length2(vehicle->HeadPosition() - glm::dvec3(Command.location)) > glm::length2(vehicle->RearPosition() - glm::dvec3(Command.location)) ? 1 : -1), 0, - 1)}; // z [-1,1] zrobić [0,1] - - auto const lightset{light::rearendsignals}; - - vehicle->MoverParameters->iLights[CouplNr] = - false == TestFlag(vehicle->MoverParameters->iLights[CouplNr], lightset) ? - vehicle->MoverParameters->iLights[CouplNr] |= lightset : // turn signals on - vehicle->MoverParameters->iLights[CouplNr] ^= lightset; // turn signals off - } -} - -void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Command) -{ - if (Train->DynamicObject->MoverParameters->enableModernDimmer) - return; - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->DynamicObject->MoverParameters->modernDimmerPosition == 0) - { - // turn on - OnCommand_headlightsdimenable(Train, Command); - } - else - { - // turn off - OnCommand_headlightsdimdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Command) -{ - - if (Train->DynamicObject->MoverParameters->enableModernDimmer) - return; - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggDimHeadlightsButton.SubModel != nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - // visual feedback - Train->ggDimHeadlightsButton.UpdateValue(1.0, Train->dsbSwitch); - } - - /* // to jest stara logika - if (true == Train->DynamicObject->DimHeadlights) - { - return; - } // already enabled - - Train->DynamicObject->DimHeadlights = true; - */ - Train->DynamicObject->MoverParameters->modernDimmerPosition = Train->DynamicObject->MoverParameters->clampDimmerPosition(1); // ustawiamy modern dimmer na flage przyciemnienia - Train->DynamicObject->SetLightDimmings(); - } -} - -void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &Command) -{ - - if (Train->DynamicObject->MoverParameters->enableModernDimmer) // nie wiem dlaczego to tak dziala ze jest odwrocona logika - return; - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggDimHeadlightsButton.SubModel != nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - // visual feedback - Train->ggDimHeadlightsButton.UpdateValue(0.0, Train->dsbSwitch); - } - - /* // stara logika przyciemniania - if( false == Train->DynamicObject->DimHeadlights ) { return; } // already enabled - - Train->DynamicObject->DimHeadlights = false; - - */ - Train->DynamicObject->MoverParameters->modernDimmerPosition = 0; // ustawiamy modern dimmer na flage rozjasnienia - Train->DynamicObject->SetLightDimmings(); - } -} - -void TTrain::OnCommand_interiorlighttoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->Cabine[Train->iCabn].bLight) - { - // turn on - OnCommand_interiorlightenable(Train, Command); - } - else - { - // turn off - OnCommand_interiorlightdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_interiorlightenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->m_controlmapper.contains("cablight_sw:")) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Interior Light switch is missing, or wasn't defined"); - return; - } - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLight = true; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLight = true; - } - } - } -} - -void TTrain::OnCommand_interiorlightdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->m_controlmapper.contains("cablight_sw:")) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Interior Light switch is missing, or wasn't defined"); - return; - } - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLight = false; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLight = false; - } - } - } -} - -void TTrain::OnCommand_interiorlightdimtoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->Cabine[Train->iCabn].bLightDim) - { - // turn on - OnCommand_interiorlightdimenable(Train, Command); - } - else - { - // turn off - OnCommand_interiorlightdimdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_interiorlightdimenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggCabLightDimButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dim Interior Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggCabLightDimButton.UpdateValue(1.0, Train->dsbSwitch); - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLightDim = true; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLightDim = true; - } - } - } -} - -void TTrain::OnCommand_interiorlightdimdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggCabLightDimButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dim Interior Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggCabLightDimButton.UpdateValue(0.0, Train->dsbSwitch); - // store lighting switch states - if (false == Train->DynamicObject->JointCabs) - { - // vehicles with separate cabs get separate lighting switch states - Train->Cabine[Train->iCabn].bLightDim = false; - } - else - { - // joint virtual cabs share lighting switch states - for (auto &cab : Train->Cabine) - { - cab.bLightDim = false; - } - } - } -} - -void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - - // keep the switch from flipping back and forth if key is held down - if (false == Train->mvOccupied->CompartmentLights.is_active && false == Train->mvOccupied->CompartmentLights.is_enabled) - { - // turn on - OnCommand_compartmentlightsenable(Train, Command); - } - else - { - // turn off - OnCommand_compartmentlightsdisable(Train, Command); - } -} - -void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->CompartmentLightsSwitch(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) - { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitchOff(false); - } - } - // visual feedback - if (Train->m_controlmapper.contains("compartmentlights_sw:")) - { - Train->ggCompartmentLightsButton.UpdateValue(1.0f, Train->dsbSwitch); - } - if (Train->m_controlmapper.contains("compartmentlightson_sw:")) - { - Train->ggCompartmentLightsOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsButton.UpdateValue(0.5f); - } - if (Train->m_controlmapper.contains("compartmentlightson_sw:")) - { - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->ggCompartmentLightsOnButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->CompartmentLightsSwitchOff(true); - if (Train->m_controlmapper.contains("compartmentlights_sw:")) - { - auto const istoggle{(static_cast(Train->ggCompartmentLightsButton.type()) & static_cast(TGaugeType::toggle)) != 0}; - if (istoggle) - { - Train->mvOccupied->CompartmentLightsSwitch(false); - } - } - // visual feedback - if (Train->m_controlmapper.contains("compartmentlights_sw:")) - { - Train->ggCompartmentLightsButton.UpdateValue(0.0f, Train->dsbSwitch); - } - if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) - { - Train->ggCompartmentLightsOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) - { - // return the switch to neutral position - Train->mvOccupied->CompartmentLightsSwitch(false); - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsButton.UpdateValue(0.5f); - } - if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) - { - Train->mvOccupied->CompartmentLightsSwitchOff(false); - Train->ggCompartmentLightsOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_instrumentlighttoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->InstrumentLightActive) - { - // turn on - OnCommand_instrumentlightenable(Train, Command); - } - else - { - // turn off - OnCommand_instrumentlightdisable(Train, Command); - } - } -} - -void TTrain::OnCommand_instrumentlightenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggInstrumentLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Instrument Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggInstrumentLightButton.UpdateValue(1.0, Train->dsbSwitch); - - if (true == Train->InstrumentLightActive) - { - return; - } // already enabled - - Train->InstrumentLightActive = true; - } -} - -void TTrain::OnCommand_instrumentlightdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Train->ggInstrumentLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Instrument Light switch is missing, or wasn't defined"); - return; - } - // visual feedback - Train->ggInstrumentLightButton.UpdateValue(0.0, Train->dsbSwitch); - - if (false == Train->InstrumentLightActive) - { - return; - } // already disabled - - Train->InstrumentLightActive = false; - } -} - -void TTrain::OnCommand_dashboardlighttoggle(TTrain *Train, command_data const &Command) -{ - if (false == Train->DashboardLightActive) - { - OnCommand_dashboardlightenable(Train, Command); - } - else - { - OnCommand_dashboardlightdisable(Train, Command); - } -} - -void TTrain::OnCommand_dashboardlightenable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggDashboardLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dashboard Light switch is missing, or wasn't defined"); - return; - } - - if (false == Train->DashboardLightActive) - { - // turn on - Train->DashboardLightActive = true; - // visual feedback - Train->ggDashboardLightButton.UpdateValue(1.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dashboardlightdisable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggDashboardLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Dashboard Light switch is missing, or wasn't defined"); - return; - } - - if (Train->DashboardLightActive) - { - // turn off - Train->DashboardLightActive = false; - // visual feedback - Train->ggDashboardLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_timetablelighttoggle(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (false == Train->TimetableLightActive) - { - OnCommand_timetablelightenable(Train, Command); - } - else - { - OnCommand_timetablelightdisable(Train, Command); - } -} - -void TTrain::OnCommand_timetablelightenable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggTimetableLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Timetable Light switch is missing, or wasn't defined"); - return; - } - - if (false == Train->TimetableLightActive) - { - // turn on - Train->TimetableLightActive = true; - // visual feedback - Train->ggTimetableLightButton.UpdateValue(1.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_timetablelightdisable(TTrain *Train, command_data const &Command) -{ - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (Command.action != GLFW_PRESS) - { - return; - } - - if (Train->ggTimetableLightButton.SubModel == nullptr) - { - // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels - WriteLog("Timetable Light switch is missing, or wasn't defined"); - return; - } - if (Train->TimetableLightActive) - { - // turn off - Train->TimetableLightActive = false; - // visual feedback - Train->ggTimetableLightButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) -{ - - if (Train->ggTrainHeatingButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Train Heating switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // ignore repeats so the switch doesn't flip back and forth if key is held down - if (false == Train->mvControlled->HeatingAllow) - { - // turn on - OnCommand_heatingenable(Train, Command); - } - else - { - // turn off - OnCommand_heatingdisable(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->mvOccupied->HeatingSwitchImpulse)) - { - // impulse switch - // visual feedback - Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->HeatingSwitch(true); - // visual feedback - Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) - { - // the switch springs back to the middle - Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->HeatingSwitch(false); - // visual feedback: an impulse switch is pushed the other way, down - auto position{0.0}; - if (Train->mvOccupied->HeatingSwitchImpulse) - { - position = -1.0; - } - else if (Train->ggTrainHeatingButton.type() == TGaugeType::push) - { - position = 1.0; - } - Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE && Train->mvOccupied->HeatingSwitchImpulse) - { - Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) -{ - - auto const itemindex = static_cast(Command.command) - static_cast(user_command::generictoggle0); - auto &item = Train->ggUniversals[itemindex]; - /* - if( item.SubModel == nullptr ) { - if( Command.action == GLFW_PRESS ) { - WriteLog( "Train generic item " + std::to_string( itemindex ) + " is missing, or wasn't defined" ); - } - return; - } - */ - - if (Command.action == GLFW_PRESS) - { - - if (item.type() == TGaugeType::push) - { - // impulse switch - // turn on - // visual feedback - item.UpdateValue(1.0); - } - else - { - // two-state switch - if (item.GetDesiredValue() < 0.5) - { - // turn on - // visual feedback - item.UpdateValue(1.0); - } - else - { - // turn off - // visual feedback - item.UpdateValue(0.0); - } - } - } - else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) - { - // impulse switch - // turn off - // visual feedback - item.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SpringBrake.Activate) - { - // turn on - OnCommand_springbrakeenable(Train, Command); - } - else - { - // turn off - OnCommand_springbrakedisable(Train, Command); - } - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_springbrakeenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeActivate(true); - // visual feedback - Train->ggSpringBrakeOnButton.UpdateValue(1.0, Train->dsbSwitch); - Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_springbrakedisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeActivate(false); - // visual feedback - Train->ggSpringBrakeOffButton.UpdateValue(1.0, Train->dsbSwitch); - Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; -void TTrain::OnCommand_springbrakeshutofftoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - if (false == Train->mvOccupied->SpringBrake.ShuttOff) - { - // turn on - OnCommand_springbrakeshutoffenable(Train, Command); - } - else - { - // turn off - OnCommand_springbrakeshutoffdisable(Train, Command); - } - } -}; - -void TTrain::OnCommand_springbrakeshutoffenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeShutOff(true); - } -}; - -void TTrain::OnCommand_springbrakeshutoffdisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpringBrakeShutOff(false); - } -}; - -void TTrain::OnCommand_springbrakerelease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - - if (auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; vehicle == nullptr) - { - return; - } - Train->mvOccupied->SpringBrakeRelease(); - } -}; - -void TTrain::OnCommand_speedcontrolincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlInc(); - // visual feedback - Train->ggSpeedControlIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontroldecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlDec(); - // visual feedback - Train->ggSpeedControlDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontrolpowerincrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlPowerInc(); - // visual feedback - Train->ggSpeedControlPowerIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlPowerIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontrolpowerdecrease(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlPowerDec(); - // visual feedback - Train->ggSpeedControlPowerDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedControlPowerDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_speedcontrolbutton(TTrain *Train, command_data const &Command) -{ - - auto const itemindex = static_cast(Command.command) - static_cast(user_command::speedcontrolbutton0); - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - Train->mvOccupied->SpeedCtrlButton(itemindex); - // visual feedback - Train->ggSpeedCtrlButtons[itemindex].UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - Train->ggSpeedCtrlButtons[itemindex].UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command) -{ - - auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterenable1); - auto &item = Train->ggInverterEnableButtons[itemindex]; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - p->MoverParameters->Inverters[itemindex].Activate = true; - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - // visual feedback - item.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - item.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Command) -{ - - auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterdisable1); - auto &item = Train->ggInverterDisableButtons[itemindex]; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - p->MoverParameters->Inverters[itemindex].Activate = false; - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - // visual feedback - item.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // release - // visual feedback - item.UpdateValue(0.0, Train->dsbSwitch); - } -}; - -void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command) -{ - - auto itemindex = static_cast(Command.command) - static_cast(user_command::invertertoggle1); - auto &item = Train->ggInverterToggleButtons[itemindex]; - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the switch doesn't flip back and forth if key is held down - bool kier = Train->DynamicObject->DirectionGet() * Train->mvOccupied->CabOccupied > 0; - int flag = Train->DynamicObject->MoverParameters->InverterControlCouplerFlag; - TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - p->MoverParameters->Inverters[itemindex].Activate = !p->MoverParameters->Inverters[itemindex].Activate; - // visual feedback - item.UpdateValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - } -}; - -void TTrain::OnCommand_doorlocktoggle(TTrain *Train, command_data const &Command) -{ - - if (Train->ggDoorSignallingButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Door Lock switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->Doors.lock_enabled) - { - // turn on - // TODO: door lock command to send through consist - Train->mvOccupied->LockDoors(true); - // visual feedback - Train->ggDoorSignallingButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // turn off - // TODO: door lock command to send through consist - Train->mvOccupied->LockDoors(false); - // visual feedback - Train->ggDoorSignallingButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_doortoggleleft(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors - if (false == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) - { - // open - OnCommand_dooropenleft(Train, Command); - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseleft(Train, Command); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (true == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) - { - // open - if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) - { - // complete closing the doors - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseleft(Train, Command); - } - } - else - { - OnCommand_dooropenleft(Train, Command); - } - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseleft(Train, Command); - } - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - // NOTE: temporary arrangement, can be removed when LD system is in place - if (Train->ggDoorLeftOffButton.SubModel) - Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggDoorLeftOnButton.SubModel) - Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - if (false == Train->mvOccupied->Doors.permit_presets.empty()) - { - return; - } - - auto const side{(Train->cab_to_end() == end::front ? side::left : side::right)}; - - if (Command.action == GLFW_PRESS) - { - - if (Train->ggDoorLeftPermitButton.is_push()) - { - // impulse switch - Train->mvOccupied->PermitDoors(side); - // visual feedback - Train->ggDoorLeftPermitButton.UpdateValue(1.0, Train->dsbSwitch); - // start potential timer for remote door control - Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; - } - else - { - // two-state switch - auto const newstate{!(Train->ggDoorLeftPermitButton.GetDesiredValue() > 0.5)}; - - Train->mvOccupied->PermitDoors(side, newstate); - // visual feedback - Train->ggDoorLeftPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggDoorLeftPermitButton.is_push()) - { - // impulse switch - // visual feedback - Train->ggDoorLeftPermitButton.UpdateValue(0.0, Train->dsbSwitch); - // reset potential remote door control timer - Train->m_doorpermittimers[side] = -1.f; - } -} - -void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_REPEAT) - { - return; - } - if (false == Train->mvOccupied->Doors.permit_presets.empty()) - { - return; - } - - auto const side{(Train->cab_to_end() == end::front ? side::right : side::left)}; - - if (Command.action == GLFW_PRESS) - { - - if (Train->ggDoorRightPermitButton.type() == TGaugeType::push) - { - // impulse switch - Train->mvOccupied->PermitDoors(side); - // visual feedback - Train->ggDoorRightPermitButton.UpdateValue(1.0, Train->dsbSwitch); - // start potential timer for remote door control - Train->m_doorpermittimers[side] = Train->mvOccupied->DoorsOpenWithPermitAfter; - } - else - { - // two-state switch - auto const newstate{!(Train->ggDoorRightPermitButton.GetDesiredValue() > 0.5)}; - - Train->mvOccupied->PermitDoors(side, newstate); - // visual feedback - Train->ggDoorRightPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE && Train->ggDoorRightPermitButton.type() == TGaugeType::push) - { - // impulse switch - // visual feedback - Train->ggDoorRightPermitButton.UpdateValue(0.0, Train->dsbSwitch); - // reset potential remote door control timer - Train->m_doorpermittimers[side] = -1.f; - } -} - -void TTrain::OnCommand_doorpermitpresetactivatenext(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->ChangeDoorPermitPreset(1); - // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_doorpermitpresetactivateprevious(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->ChangeDoorPermitPreset(-1); - // visual feedback - Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->mvOccupied->Doors.permit_preset), Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) - { - return; - } - - if (Train->ggDoorLeftOnButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, true); - // visual feedback - if (Train->ggDoorLeftOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorLeftOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorLeftButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - if (Train->ggDoorLeftOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) - { - return; - } - - if (Train->ggDoorLeftOffButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(true); - } - else - { - // TODO: move door opening/closing to the update, so the switch animation doesn't hinge on door working - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); - } - // visual feedback - if (Train->ggDoorLeftOffButton.SubModel != nullptr) - { - // two separate switches to open and close the door - Train->ggDoorLeftOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(false); - // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::left : side::right, false); - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - if (Train->ggDoorLeftOffButton.SubModel) - Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_doortoggleright(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors - if (false == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) - { - // open - OnCommand_dooropenright(Train, Command); - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseright(Train, Command); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (true == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) - { - // open - if (Train->mvOccupied->Doors.has_autowarning && Train->mvOccupied->DepartureSignal) - { - // complete closing the doors - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseright(Train, Command); - } - } - else - { - OnCommand_dooropenright(Train, Command); - } - } - else - { - // close - if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) - { - // OnCommand_doorcloseall( Train, Command ); - // if two-button setup lacks dedicated closing button require the user to press appropriate button manually - return; - } - else - { - OnCommand_doorcloseright(Train, Command); - } - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - // NOTE: temporary arrangement, can be removed when LD system is in place - if (Train->ggDoorRightOffButton.SubModel) - Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggDoorRightOnButton.SubModel) - Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) - { - return; - } - - if (Train->ggDoorRightOnButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, true); - // visual feedback - if (Train->ggDoorRightOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorRightOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorRightButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - if (Train->ggDoorRightOnButton.SubModel != nullptr) - { - // two separate impulse switches - Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) - { - return; - } - - if (Train->ggDoorRightOffButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) - { - - return; - } - - if (Command.action == GLFW_PRESS) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(true); - } - else - { - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); - } - // visual feedback - if (Train->ggDoorRightOffButton.SubModel != nullptr) - { - // two separate switches to open and close the door - Train->ggDoorRightOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else - { - // single two-state switch - Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - // automatic departure signal delays actual door closing until the button is released - Train->mvOccupied->signal_departure(false); - // now we can actually close the door - Train->mvOccupied->OperateDoors(Train->cab_to_end() == end::front ? side::right : side::left, false); - } - // visual feedback - // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position - if (Train->ggDoorRightOffButton.SubModel) - Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteopencontrol{Train->mvOccupied->Doors.open_control == control_t::driver || Train->mvOccupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) - { - return; - } - - if (Train->ggDoorAllOnButton.SubModel == nullptr) - { - // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch - if (Command.action == GLFW_PRESS) - { - WriteLog("Open All Doors switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - - Train->mvOccupied->OperateDoors(side::right, true); - Train->mvOccupied->OperateDoors(side::left, true); - // visual feedback - Train->ggDoorAllOnButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggDoorAllOnButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) -{ - - - if (auto const remoteclosecontrol{Train->mvOccupied->Doors.close_control == control_t::driver || Train->mvOccupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) - { - return; - } - - if (Train->ggDoorAllOffButton.SubModel == nullptr) - { - // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch - if (Command.action == GLFW_PRESS) - { - WriteLog("Close All Doors switch is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - - if (Train->mvOccupied->Doors.has_autowarning) - { - Train->mvOccupied->signal_departure(true); - } - if (Train->ggDoorAllOffButton.type() != TGaugeType::push_delayed) - { - // delays the action until the button is released - Train->mvOccupied->OperateDoors(side::right, false); - Train->mvOccupied->OperateDoors(side::left, false); - } - // visual feedback - Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); - Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); - if (Train->ggDoorAllOffButton.SubModel) - Train->ggDoorAllOffButton.UpdateValue(1.0, Train->dsbSwitch); - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->mvOccupied->Doors.has_autowarning) - { - Train->mvOccupied->signal_departure(false); - } - if (Train->ggDoorAllOffButton.type() == TGaugeType::push_delayed) - { - // now we can actually close the door - Train->mvOccupied->OperateDoors(side::right, false); - Train->mvOccupied->OperateDoors(side::left, false); - } - // visual feedback - if (Train->ggDoorAllOffButton.SubModel) - Train->ggDoorAllOffButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_doorsteptoggle(TTrain *Train, command_data const &Command) -{ - // TODO: move logic/visualization code to the gauge, on_command() should return hint whether it should invoke a reaction - if (Command.action == GLFW_PRESS) - { - // effect - if (false == Train->ggDoorStepButton.is_delayed()) - { - Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); - } - // visual feedback - auto const isactive{(Train->ggDoorStepButton.is_push() // always press push button - || Train->mvOccupied->Doors.step_enabled)}; // for toggle buttons indicate item state - Train->ggDoorStepButton.UpdateValue(isactive ? 1 : 0); - } - else if (Command.action == GLFW_RELEASE) - { - // effect - if (Train->ggDoorStepButton.is_delayed()) - { - Train->mvOccupied->PermitDoorStep(false == Train->mvOccupied->Doors.step_enabled); - } - // visual feedback - if (Train->ggDoorStepButton.is_push()) - { - Train->ggDoorStepButton.UpdateValue(0); - } - } -} - -void TTrain::OnCommand_doormodetoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->ChangeDoorControlMode(false == Train->mvOccupied->Doors.remote_only); - } -} - -void TTrain::OnCommand_mirrorstoggle(TTrain *Train, command_data const &Command) -{ - - if (Command.action != GLFW_PRESS) - { - return; - } - - // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->MirrorForbidden) - { - // turn on - Train->mvOccupied->MirrorForbidden = true; - } - else - { - // turn off - Train->mvOccupied->MirrorForbidden = false; - } -} - -void TTrain::OnCommand_nearestcarcouplingincrease(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto couplerindex{-1}; - auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; - if (vehicle == nullptr) - vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); - - if (couplerindex != -1 && vehicle != nullptr) - { - - vehicle->couple(couplerindex); - } - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Connect); - } - } -} - -void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto couplerindex{-1}; - auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; - if (vehicle == nullptr) - vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); - - if (couplerindex != -1 && vehicle != nullptr) - { - - vehicle->uncouple(couplerindex); - } - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Disconnect); - } - } -} - -void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; - if (vehicle == nullptr) - { - return; - } - - auto const couplerindex = - glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; - - vehicle->attach_coupler_adapter(couplerindex); - } -} - -void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain * /*Train*/, command_data const &Command) -{ - - if (true == Command.freefly && Command.action == GLFW_PRESS) - { - // tryb freefly, press only - auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; - if (vehicle == nullptr) - { - return; - } - - auto const couplerindex = - glm::length2(glm::vec3{vehicle->CouplerPosition(end::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(end::rear)} - Command.location) ? end::front : end::rear; - - vehicle->remove_coupler_adapter(couplerindex); - } -} - -void TTrain::OnCommand_occupiedcarcouplingdisconnect(TTrain *Train, command_data const &Command) -{ - - // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->m_couplingdisconnect = true; - - if (Train->iCabn == 0) - { - return; - } - - if (Train->DynamicObject) - { - Train->DynamicObject->uncouple(Train->cab_to_end()); - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Disconnect); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->m_couplingdisconnect = false; - } -} - -void TTrain::OnCommand_occupiedcarcouplingdisconnectback(TTrain *Train, command_data const &Command) -{ - - // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } - - if (Command.action == GLFW_PRESS) - { - // visual feedback - Train->m_couplingdisconnectback = true; - - if (Train->iCabn == 0) - { - return; - } - - if (Train->DynamicObject) - { - Train->DynamicObject->uncouple(1 - Train->cab_to_end()); - if (Train->DynamicObject->Mechanik) - { - // aktualizacja flag kierunku w składzie - Train->DynamicObject->Mechanik->CheckVehicles(Disconnect); - } - } - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->m_couplingdisconnectback = false; - } -} - -void TTrain::OnCommand_departureannounce(TTrain *Train, command_data const &Command) -{ - - if (Train->ggDepartureSignalButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Departure Signal button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only reacting to press, so the sound can loop uninterrupted - if (false == Train->mvOccupied->DepartureSignal) - { - // turn on - Train->mvOccupied->signal_departure(true); - // visual feedback - Train->ggDepartureSignalButton.UpdateValue(1.0, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->signal_departure(false); - // visual feedback - Train->ggDepartureSignalButton.UpdateValue(0.0, Train->dsbSwitch); - } -} - -void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggHornButton.SubModel == nullptr && Train->ggHornLowButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Horn button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::low)) - { - // turn on - Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::low, Train->has_single_horn_lever()); - // visual feedback - Train->ggHornButton.UpdateValue(-1.0); - Train->ggHornLowButton.UpdateValue(1.0); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::low); - // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::high))) - { - // leave the single lever alone if it was moved to the other tone in the meantime - Train->ggHornButton.UpdateValue(0.0); - } - Train->ggHornLowButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggHornButton.SubModel == nullptr && Train->ggHornHighButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Horn button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, horn::high)) - { - // turn on - Train->mvOccupied->WarningSignal = horn::pressed(Train->mvOccupied->WarningSignal, horn::high, Train->has_single_horn_lever()); - // visual feedback - Train->ggHornButton.UpdateValue(1.0); - Train->ggHornHighButton.UpdateValue(1.0); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->WarningSignal = horn::released(Train->mvOccupied->WarningSignal, horn::high); - // visual feedback - if (false == (Train->has_single_horn_lever() && TestFlag(Train->mvOccupied->WarningSignal, horn::low))) - { - // leave the single lever alone if it was moved to the other tone in the meantime - Train->ggHornButton.UpdateValue(0.0); - } - Train->ggHornHighButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Command) -{ - - if (Train->ggWhistleButton.SubModel == nullptr) - { - if (Command.action == GLFW_PRESS) - { - WriteLog("Whistle button is missing, or wasn't defined"); - } - return; - } - - if (Command.action == GLFW_PRESS) - { - // only need to react to press, sound will continue until stopped - if (false == TestFlag(Train->mvOccupied->WarningSignal, 4)) - { - // turn on - Train->mvOccupied->WarningSignal |= 4; - // visual feedback - Train->ggWhistleButton.UpdateValue(1.0); - } - } - else if (Command.action == GLFW_RELEASE) - { - // turn off - Train->mvOccupied->WarningSignal &= ~4; - // visual feedback - Train->ggWhistleButton.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - - // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal - // only reacting to press, so the sound can loop uninterrupted - // NOTE: flips the state directly rather than through radioenable/radiodisable, so it doesn't move the radioon_sw:/radiooff_sw: buttons - Train->mvOccupied->Radio = (false == Train->mvOccupied->Radio); -} - -void TTrain::OnCommand_radioenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->Radio = true; - // visual feedback - if (Train->m_controlmapper.contains("radioon_sw:")) - { - Train->ggRadioOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radioon_sw:")) - { - Train->ggRadioOnButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->Radio = false; - // visual feedback - if (Train->m_controlmapper.contains("radiooff_sw:")) - { - Train->ggRadioOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radiooff_sw:")) - { - Train->ggRadioOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -// the cut-off in the radio's power supply (eu07/maszyna#438); opening it works like switching the radio off, the -// radio-stop flag included -void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_PRESS) - { - return; - } - - // NOTE: flips the state directly rather than through radiofuseenable/radiofusedisable, so it doesn't move the - // radiofuseon_sw:/radiofuseoff_sw: buttons - Train->mvOccupied->RadioFuse = (false == Train->mvOccupied->RadioFuse); -} - -void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->RadioFuse = true; - // visual feedback - if (Train->m_controlmapper.contains("radiofuseon_sw:")) - { - Train->ggRadioFuseOnButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radiofuseon_sw:")) - { - Train->ggRadioFuseOnButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - Train->mvOccupied->RadioFuse = false; - // visual feedback - if (Train->m_controlmapper.contains("radiofuseoff_sw:")) - { - Train->ggRadioFuseOffButton.UpdateValue(1.0f, Train->dsbSwitch); - } - } - else if (Command.action == GLFW_RELEASE) - { - if (Train->m_controlmapper.contains("radiofuseoff_sw:")) - { - Train->ggRadioFuseOffButton.UpdateValue(0.0f, Train->dsbSwitch); - } - } -} - -void TTrain::OnCommand_radiochannelincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // the channel buttons of a radio switched off or without power do nothing - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->RadioChannel() + 1; - OnCommand_radiochannelset(Train, newCommand); - } - - Train->ggRadioChannelNext.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioChannelNext.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiochanneldecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->RadioChannel() - 1; - OnCommand_radiochannelset(Train, newCommand); - } - - Train->ggRadioChannelPrevious.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioChannelPrevious.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiochannelset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE) - { - // on press or hold - Train->RadioChannel() = std::clamp((int)Command.param1, 1, 10); - Train->ggRadioChannelSelector.UpdateValue(static_cast(Train->RadioChannel() - 1)); - } -} - -void TTrain::OnCommand_radiostopsend(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->RadioPowered()) - { - simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioStop.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioStop.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiostopenable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() == 0) - { - if (Train->mvOccupied->RadioPowered()) - { - simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioStop.UpdateValue(1.0); - } -} - -void TTrain::OnCommand_radiostopdisable(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() > 0) - { - // visual feedback - Train->ggRadioStop.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiostoptest(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->RadioChannel() == 10 && Train->mvOccupied->RadioPowered()) - { - Train->Dynamic()->RadioStop(); - } - // visual feedback - Train->ggRadioTest.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioTest.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiocall1send(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS) - { - if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) - { - simulation::Events.queue_receivers(radio_message::call1, Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioCall1.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioCall1.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiocall3send(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->RadioChannel() != 10 && Train->mvOccupied->RadioPowered()) - { - simulation::Events.queue_receivers(radio_message::call3, Train->Dynamic()->GetPosition()); - } - // visual feedback - Train->ggRadioCall3.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioCall3.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - // so do the volume buttons - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->m_radiovolume + 0.125; - OnCommand_radiovolumeset(Train, newCommand); - } - Train->ggRadioVolumeNext.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioVolumeNext.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (Train->mvOccupied->RadioPowered()) - { - command_data newCommand = Command; - newCommand.param1 = Train->m_radiovolume - 0.125; - OnCommand_radiovolumeset(Train, newCommand); - } - Train->ggRadioVolumePrevious.UpdateValue(1.0); - } - else if (Command.action == GLFW_RELEASE) - { - // visual feedback - Train->ggRadioVolumePrevious.UpdateValue(0.0); - } -} - -void TTrain::OnCommand_radiovolumeset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE) - { - // on press or hold - Train->m_radiovolume = static_cast(std::clamp(Command.param1, 0.0, 1.0)); - Train->ggRadioVolumeSelector.UpdateValue(Train->m_radiovolume); - audio::event_volume_change = true; - } -} - -void TTrain::OnCommand_fmradiotoggle(TTrain *Train, command_data const &Command) -{ - if (Command.action == GLFW_PRESS && Train->m_fmradiopresent) - { - Train->m_fmradiopower = !Train->m_fmradiopower; - } -} - -void TTrain::OnCommand_fmradiovolumeincrease(TTrain *Train, command_data const &Command) -{ - // the knob keeps turning for as long as the control is held, the actual movement takes place in the update - Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); -} - -void TTrain::OnCommand_fmradiovolumedecrease(TTrain *Train, command_data const &Command) -{ - Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); -} - -void TTrain::OnCommand_fmradiovolumeset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) - { - Train->m_fmradiovolume = std::clamp(static_cast(Command.param1), 0.f, 1.f); - if (false == Train->m_controlmapper.contains("fmradio_sw:")) - { - // receivers without dedicated switch are switched with the volume knob - Train->m_fmradiopower = Train->m_fmradiovolume > 0.f; - } - } -} - -void TTrain::OnCommand_fmradiotuneincrease(TTrain *Train, command_data const &Command) -{ - Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); -} - -void TTrain::OnCommand_fmradiotunedecrease(TTrain *Train, command_data const &Command) -{ - Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); -} - -// sets the receiver to frequency specified in MHz -void TTrain::OnCommand_fmradiotuneset(TTrain *Train, command_data const &Command) -{ - if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) - { - Train->m_fmradiodial = std::clamp(100.f * (static_cast(Command.param1) - audio::EU07_FMRADIO_BANDSTART) / (audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART), 0.f, 100.f); - Train->m_fmradiotuned = true; - } -} - -void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (auto const movedirection{1}; false == Train->CabChange(movedirection)) - { - auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; - if (TestFlag(Train->mvOccupied->Couplers[exitdirection].CouplingFlag, coupling::gangway)) - { - // przejscie do nastepnego pojazdu - auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; - Train->MoveToVehicle(targetvehicle); - } - } - // HACK: match consist door permit state with the preset in the active cab - if (Train->ggDoorPermitPresetButton.SubModel != nullptr) - { - Train->mvOccupied->ChangeDoorPermitPreset(0); - } - // HACK: update lights state - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->DynamicObject->SetLights(); - } - } -} - -void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Command) -{ - - if (Command.action == GLFW_PRESS) - { - if (auto const movedirection{-1}; false == Train->CabChange(movedirection)) - { - // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to - auto const exitdirection{(movedirection > 0 ? end::front : end::rear)}; - if (TestFlag(Train->mvOccupied->Couplers[exitdirection].CouplingFlag, coupling::gangway)) - { - // przejscie do nastepnego pojazdu - auto *targetvehicle = exitdirection == end::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); - targetvehicle->MoverParameters->CabOccupied = Train->mvOccupied->Neighbours[exitdirection].vehicle_end ? -1 : 1; - Train->MoveToVehicle(targetvehicle); - } - } - // HACK: match consist door permit state with the preset in the active cab - if (Train->ggDoorPermitPresetButton.SubModel != nullptr) - { - Train->mvOccupied->ChangeDoorPermitPreset(0); - } - // HACK: update lights state - if (Train->mvOccupied->LightsPosNo > 0) - { - Train->DynamicObject->SetLights(); - } - } -} - -void TTrain::OnCommand_vehiclemoveforwards(TTrain *Train, const command_data &Command) -{ - if (Command.action == GLFW_RELEASE || !DebugModeFlag) - return; - - Train->DynamicObject->move_set(100.0); -} - -void TTrain::OnCommand_vehiclemovebackwards(TTrain *Train, const command_data &Command) -{ - if (Command.action == GLFW_RELEASE || !DebugModeFlag) - return; - - Train->DynamicObject->move_set(-100.0); -} - -void TTrain::OnCommand_vehicleboost(TTrain *Train, const command_data &Command) -{ - if (Command.action == GLFW_RELEASE || !DebugModeFlag) - return; - - double boost = Command.param1 != 0.0 ? Command.param1 : 2.78; - - if (Train->DynamicObject == nullptr) - { - return; - } - - auto *vehicle{Train->DynamicObject}; - while (vehicle) - { - vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; - vehicle = vehicle->Next(); // pozostałe też - } - vehicle = Train->DynamicObject->Prev(); - while (vehicle) - { - vehicle->MoverParameters->V += vehicle->DirectionGet() * boost; - vehicle = vehicle->Prev(); // w drugą stronę też - } -} - -// cab movement update, fixed step part -void TTrain::UpdateCab() -{ - - // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... - if (DynamicObject->Mechanik // może nie być? - && DynamicObject->Mechanik->AIControllFlag && iCabn != ( // numer kabiny (-1: kabina B) - mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied)) - { - - InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd"); - } - iCabn = mvOccupied->CabOccupied == -1 ? 2 : mvOccupied->CabOccupied; -} - -bool TTrain::Update(double const Deltatime) -{ - // train state update - // line breaker: - if (m_linebreakerstate == 0 && true == mvControlled->Mains) - { - // crude way to sync state of the linebreaker with ai-issued commands - m_linebreakerstate = 1; - } - if (m_linebreakerstate == 1 && false == (mvControlled->Mains || mvControlled->dizel_startup)) - { - // crude way to catch cases where the main was knocked out - // because the state of the line breaker isn't changed to match, we need to do it here manually - m_linebreakerstate = 0; - } - if (is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) - { - if (true == mvControlled->Mains) - { - // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: - // put the lever back on to match, like the line breaker state above - ggMainOffButton.UpdateValue(0.0); - } - else if (m_linebreakerstate == 2) - { - // the hold coil was cut off while the closing button was held, the line breaker won't close on its release - m_linebreakerstate = 0; - } - } - - if ((ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || - ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95 || - ggIgnitionKey.GetDesiredValue() > 0.95) - { // HACK: fallback - // keep track of period the line breaker button is held down, to determine when/if circuit closes - if (mvControlled->MainSwitchCheck()) - { - fMainRelayTimer += static_cast(Deltatime); - } - } - else - { - // button isn't down, reset the timer - fMainRelayTimer = 0.0f; - } - if (ggMainOffButton.GetDesiredValue() > 0.95) - { - // if the button disconnecting the line breaker is down prevent the timer from accumulating - fMainRelayTimer = 0.0f; - } - if (m_linebreakerstate == 0 && fMainRelayTimer > mvControlled->InitialCtrlDelay) - { - // wlaczanie WSa z opoznieniem - // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release - m_linebreakerstate = 2; - } - // for diesels and/or vehicles with toggle switch setup we complete the engine start here - // TODO: make it a test for main_on_bt of type push_delayed instead - if (m_linebreakerstate == 2 && (ggMainOnButton.SubModel == nullptr || mvControlled->EngineType != TEngineType::ElectricSeriesMotor)) - { - // try to finalize state change of the line breaker, set the state based on the outcome - m_linebreakerstate = mvControlled->MainSwitch(true, mvControlled->MainSwitchRange()) ? 1 : 0; - } - // the switches of the other vehicles in multiple - update_remote_linebreakers(Deltatime); - // door permits - for (auto idx = 0; idx < 2; ++idx) - { - auto &doorpermittimer{m_doorpermittimers[idx]}; - if (doorpermittimer < 0.f) - { - continue; - } - doorpermittimer -= static_cast(Deltatime); - if (doorpermittimer < 0.f) - { - mvOccupied->OperateDoors(static_cast(idx), true); - } - } - - // train measurement timer - if (trainLenghtMeasureTimer >= 0.f) - { - trainLenghtMeasureTimer -= static_cast(Deltatime); - if (trainLenghtMeasureTimer < 0.f) - trainLenghtMeasureTimer = -1.f; - } - - // battery timer - if (fBatteryTimer >= 0.f) - { - fBatteryTimer -= static_cast(Deltatime); - if (fBatteryTimer < 0.f) - fBatteryTimer = -1.f; - } - - // helper variables - if (DynamicObject->Mechanik != nullptr) - { - m_doors = DynamicObject->Mechanik->IsAnyDoorOpen[side::right] || DynamicObject->Mechanik->IsAnyDoorOpen[side::left]; - m_doorpermits = DynamicObject->Mechanik->IsAnyDoorPermitActive[side::right] || DynamicObject->Mechanik->IsAnyDoorPermitActive[side::left]; - m_doorspermitleft = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::left : side::right])); - m_doorspermitright = mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit && - (simulation::Time.data().wSecond % 2 < 1 || mvOccupied->DoorsPermitLightBlinking < 1 || - mvOccupied->DoorsPermitLightBlinking < 2 && DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left] || - (mvOccupied->DoorsPermitLightBlinking < 3 && DynamicObject->Mechanik->IsAnyDoorOnlyOpen[cab_to_end() == end::front ? side::right : side::left])); - } - m_dirforward = mvControlled->DirActive > 0; - m_dirneutral = mvControlled->DirActive == 0; - m_dirbackward = mvControlled->DirActive < 0; - - // check for received user commands - // NOTE: this is a temporary arrangement, for the transition period from old command setup to the new one - // eventually commands are going to be retrieved directly by the vehicle, filtered through active control stand - // and ultimately executed, provided the stand allows it. - command_data commanddata; - while (simulation::Commands.pop(commanddata, static_cast(command_target::vehicle) | id())) - { - simulation::Blackbox.command(DynamicObject, commanddata.command, commanddata.action, commanddata.param1, commanddata.param2); - - auto lookup = m_commandhandlers.find(commanddata.command); - if (lookup != m_commandhandlers.end()) - { - // debug data - if (commanddata.action == GLFW_PRESS) - { - WriteLog(mvOccupied->Name + " received command: [" + simulation::Commands_descriptions[static_cast(commanddata.command)].name + "]"); - } - // pass the command to the assigned handler - lookup->second(this, commanddata); - } - } - - UpdateCab(); - - // nie blokujemy AI - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag && (mvOccupied->TrainType == dt_ET40 || mvOccupied->TrainType == dt_EP05 || mvOccupied->HasCamshaft)) - { - // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... - // TODO: use deltatime to stabilize speed - /* - if( false == ( - ( input::command == user_command::mastercontrollerset ) - || ( input::command == user_command::mastercontrollerincrease ) - || ( input::command == user_command::mastercontrollerdecrease ) ) ) { - */ - if (false == (m_mastercontrollerinuse || Global.ctrlState)) - { - m_mastercontrollerreturndelay -= static_cast(Deltatime); - if (m_mastercontrollerreturndelay < 0.f) - { - m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; - if (mvOccupied->MainCtrlPos > mvOccupied->MainCtrlActualPos) - { - mvOccupied->DecMainCtrl(1); - } - else if (mvOccupied->MainCtrlPos < mvOccupied->MainCtrlActualPos) - { - // Ra 15-01: a to nie miało być tylko cofanie? - mvOccupied->IncMainCtrl(1); - } - } - } - } - - // McZapkie: predkosc wyswietlana na tachometrze brana jest z obrotow kol - auto const maxtacho{3.0}; - - double maxSpeed = mvControlled->Vmax * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki - if (mvOccupied->maxTachoSpeed != 0) - { - maxSpeed = mvOccupied->maxTachoSpeed; - } - fTachoVelocity = static_cast(std::min(std::abs(11.31 * mvControlled->WheelDiameter * mvControlled->nrot), maxSpeed)); - { // skacze osobna zmienna - float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy - // pomiar, pol sekundy ustawienie - if (ff != fTachoTimer) // jesli w tej sekundzie nie zmienial - { - if (fTachoVelocity >= 5) // jedzie - fTachoVelocityJump = static_cast(fTachoVelocity + (2.0 - LocalRandom(3) + LocalRandom(3)) * 0.5); - else if (fTachoVelocity < 5 && fTachoVelocity > 1) - fTachoVelocityJump = static_cast(Random(0, 4)); // tu ma sie bujac jak wariat i zatrzymac na jakiejs predkosci - // fTachoVelocityJump = 0; // stoi - fTachoTimer = ff; // juz zmienil - } - } - if (fTachoVelocity > 1) // McZapkie-270503: podkrecanie tachometru - { - // szybciej zacznij stukac - fTachoCount = static_cast(std::min(maxtacho, fTachoCount + Deltatime * 3)); - } - else if (fTachoCount > 0) - { - // schodz powoli - niektore haslery to ze 4 sekundy potrafia stukac - fTachoCount = static_cast(std::max(0.0, fTachoCount - Deltatime * 0.66)); - } - - // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys - if (mvControlled->EngineType != TEngineType::DieselElectric && mvControlled->EngineType != TEngineType::ElectricInductionMotor) - { // Ra 2014-09: czy taki rozdzia? ma sens? - fHVoltage = static_cast(std::max(mvControlled->PantographVoltage, - mvControlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? - } - // *mvControlled->Mains); - else - { - fHVoltage = static_cast(mvControlled->EngineVoltage); - } - if (ShowNextCurrent) - { // jeśli pokazywać drugi człon - if (mvSecond) - { // o ile jest ten drugi - fHCurrent[0] = static_cast(mvSecond->ShowCurrent(0) * 1.05); - fHCurrent[1] = static_cast(mvSecond->ShowCurrent(1) * 1.05); - fHCurrent[2] = static_cast(mvSecond->ShowCurrent(2) * 1.05); - fHCurrent[3] = static_cast(mvSecond->ShowCurrent(3) * 1.05); - } - else - { - fHCurrent[0] = 0.0; // gdy nie ma człona - fHCurrent[1] = 0.0; - fHCurrent[2] = 0.0; - fHCurrent[3] = 0.0; - } - } - else - { // normalne pokazywanie - fHCurrent[0] = static_cast(mvControlled->ShowCurrent(0)); - fHCurrent[1] = static_cast(mvControlled->ShowCurrent(1)); - fHCurrent[2] = static_cast(mvControlled->ShowCurrent(2)); - fHCurrent[3] = static_cast(mvControlled->ShowCurrent(3)); - } - - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, 4); - int in = 0; - fEIMParams[0][6] = 0; - iCarNo = 0; - iPowerNo = 0; - iUnitNo = 1; - - for (int i = 0; i < 8; i++) - { - bMains[i] = false; - fCntVol[i] = 0.0f; - bPants[i][0] = false; - bPants[i][1] = false; - bFuse[i] = false; - bBatt[i] = false; - bConv[i] = false; - bComp[i][0] = false; - bComp[i][1] = false; - // bComp[i][2] = false; - // bComp[i][3] = false; - bHeat[i] = false; - } - bCompressors.clear(); - for (int i = 0; i < 20; i++) - { - if (p) - { - fPress[i][0] = static_cast(p->MoverParameters->BrakePress); - fPress[i][1] = static_cast(p->MoverParameters->PipePress); - fPress[i][2] = static_cast(p->MoverParameters->ScndPipePress); - fPress[i][3] = static_cast(p->MoverParameters->CntrlPipePress); - fPress[i][4] = static_cast(p->MoverParameters->Hamulec->GetBRP()); - fPress[i][5] = static_cast((p->MoverParameters->TotalMass - p->MoverParameters->Mred) * 0.001); - fPress[i][6] = static_cast(p->MoverParameters->SpringBrake.SBP); - bBrakes[i][0] = p->MoverParameters->SpringBrake.IsActive; - bBrakes[i][1] = p->MoverParameters->SpringBrake.ShuttOff; - bDoors[i][1] = p->MoverParameters->Doors.instances[side::left].position > 0.f; - bDoors[i][2] = p->MoverParameters->Doors.instances[side::right].position > 0.f; - bDoors[i][3] = p->MoverParameters->Doors.instances[side::left].step_position > 0.f; - bDoors[i][4] = p->MoverParameters->Doors.instances[side::right].step_position > 0.f; - bDoors[i][0] = bDoors[i][1] || bDoors[i][2]; - iDoorNo[i] = p->iAnimType[ANIM_DOORS]; - iUnits[i] = iUnitNo; - cCode[i] = p->MoverParameters->TypeName[p->MoverParameters->TypeName.length() - 1]; - asCarName[i] = p->name(); - if (p->MoverParameters->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) - { - bPants[iUnitNo - 1][end::front] = bPants[iUnitNo - 1][end::front] || p->MoverParameters->Pantographs[end::front].is_active; - bPants[iUnitNo - 1][end::rear] = bPants[iUnitNo - 1][end::rear] || p->MoverParameters->Pantographs[end::rear].is_active; - } - // TBD, TODO: clean up compressor data arrangement? - if (iUnitNo <= 8) - { - bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic; - } - if (p->MoverParameters->CompressorSpeed > 0.00001) - { - if (iUnitNo <= 8) - { - bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->MoverParameters->CompressorFlag; - } - bCompressors.emplace_back(p->MoverParameters->CompressorAllow || p->MoverParameters->CompressorStart == start_t::automatic, p->MoverParameters->CompressorFlag, i); - } - bSlip[i] = p->MoverParameters->SlippingWheels; - if (in < 8 && p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - fEIMParams[1 + in][0] = static_cast(p->MoverParameters->eimv[eimv_Fmax]); - fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); - fEIMParams[1 + in][3] = static_cast(p->MoverParameters->eimv[eimv_Fmax] / std::max(p->MoverParameters->eimv[eimv_Fful], 1.)); - fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); - fEIMParams[1 + in][6] = static_cast(p->MoverParameters->eimv[eimv_If]); - fEIMParams[1 + in][7] = static_cast(p->MoverParameters->eimv[eimv_U]); - fEIMParams[1 + in][8] = static_cast(p->MoverParameters->Itot); // p->MoverParameters->eimv[eimv_Ipoj]; - fEIMParams[1 + in][9] = static_cast(p->MoverParameters->EngineVoltage); - fEIMParams[0][6] += fEIMParams[1 + in][8]; - bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); - bFuse[in] = p->MoverParameters->FuseFlag; - bBatt[in] = p->MoverParameters->Battery; - bConv[in] = p->MoverParameters->ConverterFlag; - bHeat[in] = p->MoverParameters->Heating; - // bComp[in][2] = (p->MoverParameters->CompressorAllow || (p->MoverParameters->CompressorStart == start_t::automatic)); - // bComp[in][3] = (p->MoverParameters->CompressorFlag); - in++; - iPowerNo = in; - } - if (in < 8 && (p->MoverParameters->EngineType == TEngineType::DieselEngine || p->MoverParameters->EngineType == TEngineType::DieselElectric)) - { - fDieselParams[1 + in][0] = static_cast(p->MoverParameters->enrot * 60); - fDieselParams[1 + in][1] = static_cast(p->MoverParameters->nrot); - fDieselParams[1 + in][2] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].R); - fDieselParams[1 + in][3] = static_cast(p->MoverParameters->dizel_fill); - fDieselParams[1 + in][4] = static_cast(p->MoverParameters->RList[p->MoverParameters->MainCtrlPos].Mn); - fDieselParams[1 + in][5] = static_cast(p->MoverParameters->dizel_engage); - fDieselParams[1 + in][6] = p->MoverParameters->dizel_heat.Twy; - fDieselParams[1 + in][7] = p->MoverParameters->OilPump.pressure; - fDieselParams[1 + in][8] = p->MoverParameters->dizel_heat.Ts; - fDieselParams[1 + in][9] = static_cast(p->MoverParameters->hydro_R_Fill); - bMains[in] = p->MoverParameters->Mains; - fCntVol[in] = static_cast(p->MoverParameters->BatteryVoltage); - bFuse[in] = p->MoverParameters->FuseFlag; - bBatt[in] = p->MoverParameters->Battery; - bConv[in] = p->MoverParameters->ConverterFlag; - bHeat[in] = p->MoverParameters->Heating; - in++; - iPowerNo = in; - } - if ((kier ? p->Next(coupling::permanent) : p->Prev(coupling::permanent)) != (kier ? p->Next(coupling::control) : p->Prev(coupling::control))) - iUnitNo++; - p = kier ? p->Next(coupling::control) : p->Prev(coupling::control); - iCarNo = i + 1; - } - else - { - fPress[i][0] = 0; - fPress[i][1] = 0; - fPress[i][2] = 0; - fPress[i][3] = 0; - fPress[i][4] = 0; - fPress[i][5] = 0; - bDoors[i][0] = false; - bDoors[i][1] = false; - bDoors[i][2] = false; - bDoors[i][3] = false; - bDoors[i][4] = false; - bBrakes[i][0] = false; - bBrakes[i][1] = false; - bSlip[i] = false; - iUnits[i] = 0; - cCode[i] = 0; //'0'; - asCarName[i] = ""; - } - } - - // if (mvControlled == mvOccupied) - // fEIMParams[0][3] = mvControlled->eimv[eimv_Fzad]; // procent zadany - // else - // fEIMParams[0][3] = - // mvControlled->eimv[eimv_Fzad] - mvOccupied->LocalBrakeRatio(); // procent zadany - fEIMParams[0][3] = static_cast(mvOccupied->eimic_real); - fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); - fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); - fEIMParams[0][1] = static_cast(fEIMParams[0][4] * mvControlled->eimv[eimv_Fful]); - fEIMParams[0][2] = static_cast(fEIMParams[0][5] * mvControlled->eimv[eimv_Fful]); - fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; - fEIMParams[0][7] = 0; - fEIMParams[0][8] = 0; - fEIMParams[0][9] = 0; - - for (int i = in; i < 8; i++) - { - for (int j = 0; j <= 9; j++) - { - fEIMParams[1 + i][j] = 0; - fDieselParams[1 + i][j] = 0; - } - } -#ifdef _WIN32 - if (Global.iFeedbackMode == 4) - { - // wykonywać tylko gdy wyprowadzone na pulpit - // Ra: sterowanie miernikiem: zbiornik główny - Console::ValueSet(0, mvOccupied->Compressor); - // Ra: sterowanie miernikiem: przewód główny - Console::ValueSet(1, mvOccupied->PipePress); - // Ra: sterowanie miernikiem: cylinder hamulcowy - Console::ValueSet(2, mvOccupied->BrakePress); - // woltomierz wysokiego napięcia - Console::ValueSet(3, fHVoltage); - // Ra: sterowanie miernikiem: drugi amperomierz - Console::ValueSet(4, fHCurrent[2]); - // pierwszy amperomierz; dla EZT prąd całkowity - Console::ValueSet(5, fHCurrent[mvControlled->TrainType & dt_EZT ? 0 : 1]); - // Ra: prędkość na pin 43 - wyjście analogowe (to nie jest PWM); skakanie zapewnia mechanika napędu - Console::ValueSet(6, fTachoVelocity); - } -#endif - //------------------ - // hunter-261211: nadmiarowy przetwornicy i ogrzewania - // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie - if (mvControlled->ConverterFlag == true) - { - fConverterTimer += static_cast(Deltatime); - if (mvControlled->CompressorFlag == true && mvControlled->CompressorPower == 1 && (mvControlled->EngineType == TEngineType::ElectricSeriesMotor || mvControlled->TrainType == dt_EZT) && - DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT - && false == DynamicObject->Mechanik->AIControllFlag) - { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) - if (fConverterTimer < fConverterPrzekaznik) - { - mvControlled->ConvOvldFlag = true; - if (mvControlled->TrainType != dt_EZT) - mvControlled->MainSwitch(false, mvControlled->TrainType == dt_EZT ? range_t::unit : range_t::local); - } - else if (fConverterTimer >= fConverterPrzekaznik) - { - // changed switch from always true to take into account state of the compressor switch - mvControlled->CompressorSwitch(mvControlled->CompressorAllow); - } - } - } - else - fConverterTimer = 0; - //------------------ - auto const lowvoltagepower{mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable}; - - // youBy - prad w drugim czlonie: galaz lub calosc - { - TDynamicObject const *tmp{nullptr}; - if (DynamicObject->NextConnected() && TestFlag(mvControlled->Couplers[end::rear].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == 1) - tmp = DynamicObject->NextConnected(); - if (DynamicObject->PrevConnected() && TestFlag(mvControlled->Couplers[end::front].CouplingFlag, coupling::control) && mvOccupied->CabOccupied == -1) - tmp = DynamicObject->PrevConnected(); - if (tmp && tmp->MoverParameters->Power > 0) - { - if (ggI1B.SubModel) - { - ggI1B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(1))); - ggI1B.Update(); - } - if (ggI2B.SubModel) - { - ggI2B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(2))); - ggI2B.Update(); - } - if (ggI3B.SubModel) - { - ggI3B.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(3))); - ggI3B.Update(); - } - if (ggItotalB.SubModel) - { - ggItotalB.UpdateValue(static_cast(tmp->MoverParameters->ShowCurrent(0))); - ggItotalB.Update(); - } - if (ggWater1TempB.SubModel) - { - ggWater1TempB.UpdateValue(tmp->MoverParameters->dizel_heat.temperatura1); - ggWater1TempB.Update(); - } - if (ggOilPressB.SubModel) - { - ggOilPressB.UpdateValue(tmp->MoverParameters->OilPump.pressure); - ggOilPressB.Update(); - } - } - } - // McZapkie-300302: zegarek - if (ggClockMInd.SubModel) - { - ggClockSInd.UpdateValue(simulation::Time.data().wSecond); - ggClockSInd.Update(); - ggClockMInd.UpdateValue(simulation::Time.data().wMinute); - ggClockMInd.Update(); - ggClockHInd.UpdateValue(static_cast(simulation::Time.data().wHour + simulation::Time.data().wMinute / 60.0)); - ggClockHInd.Update(); - } - - Cabine[iCabn].Update(lowvoltagepower); // nowy sposób ustawienia animacji - /* - if (ggZbS.SubModel) - { - ggZbS.UpdateValue(mvOccupied->Handle->GetCP()); - ggZbS.Update(); - } - */ - // replacement for the above. TODO: move it to a more suitable place - m_brakehandlecp = mvOccupied->Handle->GetCP(); - - // youBy - napiecie na silnikach - if (ggEngineVoltage.SubModel) - { - if (mvControlled->DynamicBrakeFlag) - { - ggEngineVoltage.UpdateValue(static_cast(std::abs(mvControlled->Im * 5))); - } - else - { - int x; - if (mvControlled->TrainType == dt_ET42 && mvControlled->Imax == mvControlled->ImaxHi) - x = 1; - else - x = 2; - if (mvControlled->RList[mvControlled->MainCtrlActualPos].Mn > 0 && std::abs(mvControlled->Im) > 0) - { - ggEngineVoltage.UpdateValue(static_cast(x * (std::abs(mvControlled->EngineVoltage) - mvControlled->RList[mvControlled->MainCtrlActualPos].R * std::abs(mvControlled->Im)) / - mvControlled->RList[mvControlled->MainCtrlActualPos].Mn)); - } - else - { - ggEngineVoltage.UpdateValue(0); - } - } - ggEngineVoltage.Update(); - } - - // Winger 140404 - woltomierz NN - if (ggLVoltage.SubModel) - { - // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on - // TODO: implement object-based circuits and power systems model so we can have this working more properly - ggLVoltage.UpdateValue(static_cast(std::max(mvOccupied->Power110vIsAvailable ? mvOccupied->NominalBatteryVoltage : 0.0, mvOccupied->Power24vIsAvailable ? mvOccupied->BatteryVoltage : 0.0))); - ggLVoltage.Update(); - } - - if (mvControlled->EngineType == TEngineType::DieselElectric) - { // ustawienie zmiennych dla silnika spalinowego - fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); - fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); - } - - else if (mvControlled->EngineType == TEngineType::DieselEngine) - { // albo dla innego spalinowego - fEngine[1] = static_cast(mvControlled->ShowEngineRotation(1)); - fEngine[2] = static_cast(mvControlled->ShowEngineRotation(2)); - fEngine[3] = static_cast(mvControlled->ShowEngineRotation(3)); - if (ggMainGearStatus.SubModel) - { - if (mvControlled->Mains) - ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(mvControlled->dizel_automaticgearstatus))); - else - ggMainGearStatus.UpdateValue(0.0); - ggMainGearStatus.Update(); - } - if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) - { - ggIgnitionKey.UpdateValue(mvControlled->Mains || mvControlled->dizel_startup || fMainRelayTimer > 0.f || - (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || - (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); - } - ggIgnitionKey.Update(); - } - - if (mvControlled->SlippingWheels) - { - // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax; - // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza - if (veldiff < -0.01 && std::abs(mvControlled->Im) > 10.0) - { - btLampkaPoslizg.Turn(true); - } - } - else - { - btLampkaPoslizg.Turn(false); - } - - // Lampka pracujacej sprezacki - if (mvControlled->CompressorFlag || mvOccupied->CompressorFlag) - btCompressors.Turn(true); - else - btCompressors.Turn(false); - - // Lampka zezwolenia na hamowanie ED - if (mvControlled->EpFuse) - btEDenabled.Turn(true); - else - btEDenabled.Turn(false); - - // Lampka aktywowanej kabiny - if (mvControlled->CabActive != 0) - { - btCabActived.Turn(true); - } - else - { - btCabActived.Turn(false); - } - - if (mvControlled->Battery && mvControlled->CabActive != 0) - btAKLVents.Turn(true); - else - btAKLVents.Turn(false); - - if (true == lowvoltagepower) - { - // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa - if (mvOccupied->SecuritySystem.is_vigilance_blinking()) - { - if (fBlinkTimer > fCzuwakBlink) - fBlinkTimer = -fCzuwakBlink; - else - fBlinkTimer += Deltatime; - - btLampkaCzuwaka.Turn(fBlinkTimer > 0); - } - else - { - fBlinkTimer = 0.0; - btLampkaCzuwaka.Turn(false); - } - - btLampkaSHP.Turn(mvOccupied->SecuritySystem.is_cabsignal_blinking()); - btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); - - btLampkaWylSzybki.Turn(m_linebreakerstate == 2 || mvControlled->Mains); - btLampkaWylSzybkiOff.Turn(m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerReady.Turn(mvControlled->MainsInitTimeCountdown <= 0.0 && m_linebreakerstate != 2 && !mvControlled->Mains); - btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == 2 || mvControlled->Mains || mvControlled->MainsInitTimeCountdown < 0.0 && simulation::Time.data().wMilliseconds > 500); - - btLampkaPrzetw.Turn(mvOccupied->Power110vIsAvailable); - btLampkaPrzetwOff.Turn(!mvOccupied->Power110vIsAvailable); - btLampkaPrzetwAOff.Turn(!mvControlled->ConverterFlag); - btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->IsAnyConverterOverloadRelayOpen : mvControlled->ConvOvldFlag); - - btLampkaOpory.Turn(mvControlled->StLinFlag && mvControlled->ResistorsFlagCheck()); - btLampkaBezoporowa.Turn(mvControlled->ResistorsFlagCheck() || mvControlled->MainCtrlActualPos == 0); // do EU04 - btLampkaStyczn.Turn(mvControlled->LineContactorsLampLit()); // mozna prowadzic rozruch - btLampkaPrzekRozn.Turn(!mvControlled->GroundRelay && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaNadmSil.Turn(mvControlled->FuseFlagCheck() && mvControlled->MainCircuitLampsEnabled()); // relay is off and needs a reset - btLampkaUkrotnienie.Turn(TestFlag(mvControlled->Couplers[mvControlled->CabOccupied == 1 ? rear : front].CouplingFlag, control)); - btLampkaHamPosp.Turn(TestFlag(mvOccupied->Hamulec->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania - // TODO: youBy wyciągnąć flagę wysokiego stopnia - btLampkaNadmWent.Turn(mvControlled->RventRot < 5.0 && mvControlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow - btLampkaWysRozr.Turn(mvControlled->Imax >= mvControlled->ImaxHi); - - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0); // napiecie na nastawniku hamulcowym - btLampkaSprezarka.Turn(mvControlled->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaOff.Turn(!mvControlled->CompressorFlag); - btLampkaFuelPumpOff.Turn(!mvControlled->FuelPump.is_active); - btLampkaOilPump.Turn(mvControlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started - - // boczniki - // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos - // - pokićkał ktoś? - int scp = mvControlled->RList[mvControlled->MainCtrlPos].ScndAct; - scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? - btLampkaBoczniki.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik1.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 0 || mvControlled->ScndCtrlActualPos > 0 || scp > 0); - btLampkaBocznik2.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 1 || mvControlled->ScndCtrlActualPos > 1 || scp > 1); - btLampkaBocznik3.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 2 || mvControlled->ScndCtrlActualPos > 2 || scp > 2); - btLampkaBocznik4.Turn(!mvControlled->DelayCtrlFlag && mvControlled->ScndCtrlPos > 3 || mvControlled->ScndCtrlActualPos > 3 || scp > 3); - - // biegi dla motoraka - btLampkaGear1.Turn(mvControlled->ScndCtrlActualPos == 1 && mvControlled->dizel_engagestate > 0); // bieg 1 - btLampkaGear2.Turn(mvControlled->ScndCtrlActualPos == 2 && mvControlled->dizel_engagestate > 0); // bieg 2 - btLampkaHydroLockup.Turn(mvControlled->hydro_TC_Lockup); // zblokowanie skrzyni z silnikiem - - if (mvControlled->Signalling == true) - { - if (mvOccupied->BrakePress >= 1.45f) - { - btLampkaHamowanie1zes.Turn(true); - } - if (mvControlled->BrakePress < 0.75f) - { - btLampkaHamowanie1zes.Turn(false); - } - } - else - { - btLampkaHamowanie1zes.Turn(false); - } - - switch (mvControlled->TrainType) - { - // zależnie od typu lokomotywy - case dt_EZT: - { - btLampkaHamienie.Turn(mvControlled->BrakePress >= 0.2 && mvControlled->Signalling); - break; - } - case dt_ET41: - { - // odhamowanie drugiego członu - if (mvSecond) - { - // bo może komuś przyjść do głowy jeżdżenie jednym członem - btLampkaHamienie.Turn(mvSecond->BrakePress < 0.4); - } - break; - } - default: - { - btLampkaHamienie.Turn(mvOccupied->BrakePress >= 0.1 || mvControlled->DynamicBrakeFlag); - btLampkaBrakingOff.Turn(mvOccupied->BrakePress < 0.1 && !mvControlled->DynamicBrakeFlag); - break; - } - } - // KURS90 - btLampkaMaxSila.Turn(abs(mvControlled->Im) >= 350); - btLampkaPrzekrMaxSila.Turn(abs(mvControlled->Im) >= 450); - btLampkaRadio.Turn(mvOccupied->Radio && mvOccupied->RadioFuse); - btLampkaRadioMessage.Turn(radio_message_played); - btLampkaRadioStop.Turn(mvOccupied->Radio && mvOccupied->RadioFuse && mvOccupied->RadioStopFlag); - btLampkaHamulecReczny.Turn(mvOccupied->ManualBrakePos > 0); - // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu - if (DynamicObject->Mechanik != nullptr) - { - btLampkaDoorLeft.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::left : side::right]); - btLampkaDoorRight.Turn(DynamicObject->Mechanik->IsAnyDoorOpen[cab_to_end() == end::front ? side::right : side::left]); - } - if (DynamicObject->Mechanik != nullptr) - { - // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole - // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. - // without it, the lock of the vehicle's own doors, as before - btLampkaBlokadaDrzwi.Turn(mvOccupied->door_closure_lamp_lit(DynamicObject->Mechanik->DoorClosure, simulation::Time.data().wSecond % 2 < 1)); - } - else - { - btLampkaBlokadaDrzwi.Turn(mvOccupied->Doors.is_locked); - } - btLampkaDoorLockOff.Turn(false == mvOccupied->Doors.lock_enabled); - btLampkaDepartureSignal.Turn(mvControlled->DepartureSignal); - btLampkaNapNastHam.Turn(mvControlled->DirActive != 0 && mvOccupied->EpFuse); // napiecie na nastawniku hamulcowym - - // Wylaczanie lampek kierunku gdy jedziemy - // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) - if (mvOccupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona - mvOccupied->Vel > mvOccupied->HideDirStatusSpeed) // Uzaleznienie od predkosci - { - btLampkaForward.Turn(false); - btLampkaBackward.Turn(false); - btLampkaNeutral.Turn(false); - } - else - { - btLampkaForward.Turn(mvControlled->DirActive > 0); // jazda do przodu - btLampkaBackward.Turn(mvControlled->DirActive < 0); // jazda do tyłu - btLampkaNeutral.Turn(mvControlled->DirActive == 0); // kierunek neutral - } - - btLampkaED.Turn(mvControlled->DynamicBrakeFlag); // hamulec ED - btLampkaBrakeProfileG.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_G)); - btLampkaBrakeProfileP.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_P)); - btLampkaBrakeProfileR.Turn(TestFlag(mvOccupied->BrakeDelayFlag, bdelay_R)); - btLampkaSpringBrakeActive.Turn(mvOccupied->SpringBrake.IsActive); - btLampkaSpringBrakeInactive.Turn(!mvOccupied->SpringBrake.IsActive); - // light indicators - // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators - btLampkaUpperLight.Turn((mvOccupied->iLights[end::front] & light::headlight_upper) != 0); - btLampkaLeftLight.Turn((mvOccupied->iLights[end::front] & light::headlight_left) != 0); - btLampkaRightLight.Turn((mvOccupied->iLights[end::front] & light::headlight_right) != 0); - btLampkaLeftEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_left) != 0); - btLampkaRightEndLight.Turn((mvOccupied->iLights[end::front] & light::redmarker_right) != 0); - btLampkaRearUpperLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_upper) != 0); - btLampkaRearLeftLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_left) != 0); - btLampkaRearRightLight.Turn((mvOccupied->iLights[end::rear] & light::headlight_right) != 0); - btLampkaRearLeftEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_left) != 0); - btLampkaRearRightEndLight.Turn((mvOccupied->iLights[end::rear] & light::redmarker_right) != 0); - // others - btLampkaMalfunction.Turn(mvControlled->dizel_heat.PA); - // overheat indicator lamps - btLampkaOilOverheat.Turn(mvControlled->dizel_heat.oil.is_hot); - btLampkaWaterOverheat.Turn(mvControlled->dizel_heat.water.is_hot); - btLampkaWaterAuxOverheat.Turn(mvControlled->dizel_heat.water_aux.is_hot); - btLampkaEngineOverheat.Turn(mvControlled->dizel_heat.engine_is_hot); - btLampkaMotorBlowers.Turn(mvControlled->MotorBlowers[end::front].is_active && mvControlled->MotorBlowers[end::rear].is_active); - btLampkaCoolingFans.Turn(mvControlled->RventRot > 1.0); - btLampkaLouvresClosed.Turn(mvControlled->LouvresClosed()); - btLampkaTempomat.Turn(mvOccupied->SpeedCtrlUnit.IsActive); - btLampkaDistanceCounter.Turn(m_distancecounter >= 0.f); - // universal devices state indicators - for (auto idx = 0; idx < btUniversals.size(); ++idx) - { - btUniversals[idx].Turn(ggUniversals[idx].GetValue() > 0.5); - } - } - else - { - // wylaczone - btLampkaCzuwaka.Turn(false); - btLampkaSHP.Turn(false); - btLampkaCzuwakaSHP.Turn(false); - btLampkaWylSzybki.Turn(false); - btLampkaWylSzybkiOff.Turn(false); - btLampkaMainBreakerReady.Turn(false); - btLampkaMainBreakerBlinkingIfReady.Turn(false); - btLampkaWysRozr.Turn(false); - btLampkaOpory.Turn(false); - btLampkaStyczn.Turn(false); - btLampkaPrzekRozn.Turn(false); - btLampkaNadmSil.Turn(false); - btLampkaUkrotnienie.Turn(false); - btLampkaHamPosp.Turn(false); - btLampkaBoczniki.Turn(false); - btLampkaBocznik1.Turn(false); - btLampkaBocznik2.Turn(false); - btLampkaBocznik3.Turn(false); - btLampkaBocznik4.Turn(false); - btLampkaGear1.Turn(false); - btLampkaGear2.Turn(false); - btLampkaHydroLockup.Turn(false); - btLampkaNapNastHam.Turn(false); - btLampkaPrzetw.Turn(false); - btLampkaPrzetwOff.Turn(false); - btLampkaPrzetwAOff.Turn(false); - btLampkaNadmPrzetw.Turn(false); - btLampkaSprezarka.Turn(false); - btLampkaSprezarkaOff.Turn(false); - btLampkaFuelPumpOff.Turn(false); - btLampkaOilPump.Turn(false); - btLampkaBezoporowa.Turn(false); - btLampkaHamowanie1zes.Turn(false); - btLampkaHamienie.Turn(false); - btLampkaBrakingOff.Turn(false); - btLampkaBrakeProfileG.Turn(false); - btLampkaBrakeProfileP.Turn(false); - btLampkaBrakeProfileR.Turn(false); - btLampkaSpringBrakeActive.Turn(false); - btLampkaSpringBrakeInactive.Turn(false); - // overheat indicator lamps off - btLampkaOilOverheat.Turn(false); - btLampkaWaterOverheat.Turn(false); - btLampkaWaterAuxOverheat.Turn(false); - btLampkaEngineOverheat.Turn(false); - btLampkaMaxSila.Turn(false); - btLampkaPrzekrMaxSila.Turn(false); - btLampkaRadio.Turn(false); - btLampkaRadioMessage.Turn(false); - btLampkaRadioStop.Turn(false); - btLampkaHamulecReczny.Turn(false); - btLampkaDoorLeft.Turn(false); - btLampkaDoorRight.Turn(false); - btLampkaBlokadaDrzwi.Turn(false); - btLampkaDoorLockOff.Turn(false); - btLampkaDepartureSignal.Turn(false); - btLampkaNapNastHam.Turn(false); - btLampkaForward.Turn(false); - btLampkaBackward.Turn(false); - btLampkaNeutral.Turn(false); - btLampkaED.Turn(false); - // light indicators - btLampkaUpperLight.Turn(false); - btLampkaLeftLight.Turn(false); - btLampkaRightLight.Turn(false); - btLampkaLeftEndLight.Turn(false); - btLampkaRightEndLight.Turn(false); - btLampkaRearUpperLight.Turn(false); - btLampkaRearLeftLight.Turn(false); - btLampkaRearRightLight.Turn(false); - btLampkaRearLeftEndLight.Turn(false); - btLampkaRearRightEndLight.Turn(false); - // others - btLampkaMalfunction.Turn(false); - btLampkaMotorBlowers.Turn(false); - btLampkaCoolingFans.Turn(false); - btLampkaLouvresClosed.Turn(false); - btLampkaTempomat.Turn(false); - btLampkaDistanceCounter.Turn(false); - // universal devices state indicators - for (auto &universal : btUniversals) - { - universal.Turn(false); - } - } - - { // yB - wskazniki drugiego czlonu - TDynamicObject const *tmp{nullptr}; //=mvControlled->mvSecond; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... - // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce - if (TestFlag(mvControlled->Couplers[1].CouplingFlag, coupling::control) && mvOccupied->CabOccupied > 0) - tmp = DynamicObject->NextConnected(); - if (TestFlag(mvControlled->Couplers[0].CouplingFlag, coupling::control) && mvOccupied->CabOccupied < 0) - tmp = DynamicObject->PrevConnected(); - - if (tmp) - { - if (lowvoltagepower) - { - - auto const *mover{tmp->MoverParameters}; - - btLampkaWylSzybkiB.Turn(mover->Mains); - btLampkaWylSzybkiBOff.Turn(false == mover->Mains - /*&& ( mover->MainsInitTimeCountdown <= 0.0 )*/ - /*&& ( fHVoltage != 0.0 )*/); - - btLampkaOporyB.Turn(mover->ResistorsFlagCheck()); - btLampkaBezoporowaB.Turn(true == mover->ResistorsFlagCheck() || mover->MainCtrlActualPos == 0); // do EU04 - - btLampkaStycznB.Turn(mover->LineContactorsLampLit()); // mozna prowadzic rozruch - // hunter-271211: sygnalizacja poslizgu w pierwszym pojezdzie, gdy wystapi w drugim - if (mover->SlippingWheels) - { - // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały - auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / mvControlled->Vmax}; - if (veldiff < -0.01) - { - // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza - auto const lightstate{std::abs(mover->Im) > 10.0}; - btLampkaPoslizg.Turn(btLampkaPoslizg.GetValue() || lightstate); - } - } - - btLampkaSprezarkaB.Turn(mover->CompressorFlag); // mutopsitka dziala - btLampkaSprezarkaBOff.Turn(false == mover->CompressorFlag); - if (mvControlled->Signalling == true) - { - if (mover->BrakePress >= 1.45f) - { - btLampkaHamowanie2zes.Turn(true); - } - if (mover->BrakePress < 0.75f) - { - btLampkaHamowanie2zes.Turn(false); - } - } - else - { - btLampkaHamowanie2zes.Turn(false); - } - btLampkaNadmPrzetwB.Turn(mover->ConvOvldFlag); // nadmiarowy przetwornicy? - btLampkaPrzetwB.Turn(mover->ConverterFlag); // zalaczenie przetwornicy - btLampkaPrzetwBOff.Turn(false == mover->ConverterFlag); - btLampkaHVoltageB.Turn(mover->NoVoltRelay && mover->OvervoltageRelay); - btLampkaMalfunctionB.Turn(mover->dizel_heat.PA); - // motor fuse indicator turns on if the fuse was blown in any unit under control - if (mover->Mains) - { - btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || mover->FuseFlagCheck()); - } - } - else // wylaczone - { - btLampkaWylSzybkiB.Turn(false); - btLampkaWylSzybkiBOff.Turn(false); - btLampkaOporyB.Turn(false); - btLampkaStycznB.Turn(false); - btLampkaSprezarkaB.Turn(false); - btLampkaSprezarkaBOff.Turn(false); - btLampkaBezoporowaB.Turn(false); - btLampkaHamowanie2zes.Turn(false); - btLampkaNadmPrzetwB.Turn(false); - btLampkaPrzetwB.Turn(false); - btLampkaPrzetwBOff.Turn(false); - btLampkaHVoltageB.Turn(false); - btLampkaMalfunctionB.Turn(false); - } - } - } - // McZapkie-080602: obroty (albo translacje) regulatorow - if (ggJointCtrl.SubModel != nullptr) - { - // joint master controller moves forward to adjust power and backward to adjust brakes - auto const brakerangemultiplier{/* NOTE: scaling disabled as it was conflicting with associating sounds with control positions - ( mvControlled->CoupledCtrl ? - mvControlled->MainCtrlPosNo + mvControlled->ScndCtrlPosNo : - mvControlled->MainCtrlPosNo ) - / static_cast(LocalBrakePosNo) - */ - 1}; - // when SplitEDPneumaticBrake is active the negative range of the joint controller - // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake - auto const negativePart{mvControlled->SplitEDPneumaticBrake ? - (mvControlled->DynamicBrakeCtrlPos > 0.0 ? mvControlled->DynamicBrakeCtrlPos * mvControlled->DynamicBrakeCtrlPosNo * -1 * brakerangemultiplier : 0.0) : - mvOccupied->LocalBrakePosA > 0.0 ? mvOccupied->LocalBrakePosA * LocalBrakePosNo * -1 * brakerangemultiplier : - 0.0}; - ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : - mvControlled->CoupledCtrl ? static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)) : - static_cast(double(mvControlled->MainCtrlPos)), - dsbNastawnikJazdy); - ggJointCtrl.Update(); - } - if (ggMainCtrl.SubModel != nullptr) - { - -#ifdef _WIN32 - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI - && Global.iFeedbackMode == 4 && Global.fCalibrateIn[2][1] != 0.0) - { - - set_master_controller(Console::AnalogCalibrateGet(2) * mvOccupied->MainCtrlPosNo); - mvOccupied->eimic_analog = Console::AnalogCalibrateGet(2); - } -#endif - - if (mvControlled->CoupledCtrl) - { - ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos + mvControlled->ScndCtrlPos)), dsbNastawnikJazdy); - } - else - { - ggMainCtrl.UpdateValue(static_cast(double(mvControlled->MainCtrlPos)), dsbNastawnikJazdy); - } - ggMainCtrl.Update(); - } - if (ggMainCtrlAct.SubModel != nullptr) - { - ggMainCtrlAct.UpdateValue(main_ctrl_act::position(*mvControlled, ggMainCtrlAct.has_scaletable())); - ggMainCtrlAct.Update(); - } - if (ggScndCtrl.SubModel != nullptr) - { - // Ra: od byte odejmowane boolean i konwertowane potem na double? - if (false == ggScndCtrl.is_push()) - { - ggScndCtrl.UpdateValue(static_cast(double(mvControlled->ScndCtrlPos - (mvControlled->TrainType == dt_ET42 && mvControlled->DynamicBrakeFlag))), dsbNastawnikBocz); - } - ggScndCtrl.Update(); - } - if (ggScndCtrlButton.SubModel != nullptr) - { - if (ggScndCtrlButton.is_toggle()) - { - ggScndCtrlButton.UpdateValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f, dsbSwitch); - } - ggScndCtrlButton.Update(lowvoltagepower); - } - if (ggScndCtrlOffButton.SubModel != nullptr) - { - ggScndCtrlOffButton.Update(lowvoltagepower); - } - if (ggDistanceCounterButton.SubModel != nullptr) - { - ggDistanceCounterButton.Update(); - } - if (ggDirKey.SubModel != nullptr) - { - if (mvControlled->TrainType != dt_EZT) - { - ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive)), dsbReverserKey); - } - else - { - ggDirKey.UpdateValue(static_cast(double(mvControlled->DirActive) + double(mvControlled->Imin == mvControlled->IminHi)), dsbReverserKey); - } - ggDirKey.Update(); - } - if (ggBrakeCtrl.SubModel != nullptr) - { -#ifdef _WIN32 - if (DynamicObject->Mechanik ? (DynamicObject->Mechanik->AIControllFlag ? false : Global.iFeedbackMode == 4 /*|| (Global.bMWDmasterEnable && Global.bMWDBreakEnable)*/) : - false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI - { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba - // Firleju: dlatego kasujemy i zastepujemy funkcją w Console - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a) - { - double b = Console::AnalogCalibrateGet(0); - b = b * 8.0 - 2.0; - b = safe_clamp(b, -2.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic - ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); - } - else if (mvOccupied->BrakeHandle == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? - { - double b = Console::AnalogCalibrateGet(0); - b = b * 7.0 - 1.0; - b = safe_clamp(b, -1.0, (double)mvOccupied->BrakeCtrlPosNo); // przycięcie zmiennej do granic - ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); - } - else - { - double b = Console::AnalogCalibrateGet(0); - b = b * (mvOccupied->Handle->GetPos(bh_MAX) - mvOccupied->Handle->GetPos(bh_MIN)) + mvOccupied->Handle->GetPos(bh_MIN); - b = safe_clamp(b, mvOccupied->Handle->GetPos(bh_MIN), mvOccupied->Handle->GetPos(bh_MAX)); // przycięcie zmiennej do granic - ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia - mvOccupied->BrakeLevelSet(b); - } - } - else -#endif - { - // else //standardowa prodedura z kranem powiązanym z klawiaturą - // ggBrakeCtrl.UpdateValue(double(mvOccupied->BrakeCtrlPos)); - ggBrakeCtrl.UpdateValue(static_cast(mvOccupied->fBrakeCtrlPos)); - ggBrakeCtrl.Update(); - } - } - - if (ggLocalBrake.SubModel != nullptr) - { -#ifdef _WIN32 - if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag // nie blokujemy AI - && mvOccupied->BrakeLocHandle == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) - { - // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba - // Firleju: dlatego kasujemy i zastepujemy funkcją w Console - auto const b = std::clamp(Console::AnalogCalibrateGet(1), 0.f, 1.f); - mvOccupied->LocalBrakePosA = b; - ggLocalBrake.UpdateValue(b * LocalBrakePosNo); - } - else -#endif - { - // standardowa prodedura z kranem powiązanym z klawiaturą - ggLocalBrake.UpdateValue(static_cast(mvOccupied->LocalBrakePosA * LocalBrakePosNo)); - } - ggLocalBrake.Update(); - } - ggDirForwardButton.Update(lowvoltagepower); - ggDirNeutralButton.Update(lowvoltagepower); - ggDirBackwardButton.Update(lowvoltagepower); - ggAlarmChain.Update(); - ggBrakeProfileCtrl.Update(); - ggBrakeProfileG.Update(); - ggBrakeProfileR.Update(); - ggBrakeOperationModeCtrl.Update(); - ggWiperSw.Update(); - ggMaxCurrentCtrl.UpdateValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); - ggMaxCurrentCtrl.Update(); - // NBMX wrzesien 2003 - drzwi - ggDoorLeftPermitButton.Update(lowvoltagepower); - ggDoorRightPermitButton.Update(lowvoltagepower); - ggDoorPermitPresetButton.Update(lowvoltagepower); - ggDoorLeftButton.Update(lowvoltagepower); - ggDoorRightButton.Update(lowvoltagepower); - ggDoorLeftOnButton.Update(lowvoltagepower); - ggDoorRightOnButton.Update(lowvoltagepower); - ggDoorLeftOffButton.Update(lowvoltagepower); - ggDoorRightOffButton.Update(lowvoltagepower); - ggDoorAllOnButton.Update(lowvoltagepower); - ggDoorAllOffButton.Update(lowvoltagepower); - ggDoorSignallingButton.Update(lowvoltagepower); - ggDoorStepButton.Update(lowvoltagepower); - // NBMX dzwignia sprezarki - ggCompressorButton.Update(); - ggCompressorLocalButton.Update(); - ggCompressorListButton.Update(); - - //--------- - // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy - if (mvControlled->Heating == true && mvControlled->ConvOvldFlag == false) - btLampkaOgrzewanieSkladu.Turn(true); - else - btLampkaOgrzewanieSkladu.Turn(false); - - //---------- - - // lights - auto const lightpower{(InstrumentLightType == 0 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - InstrumentLightType == 1 ? mvControlled->Mains : - InstrumentLightType == 2 ? mvOccupied->Power110vIsAvailable : - InstrumentLightType == 3 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - InstrumentLightType == 4 ? mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable : - false)}; - InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key - InstrumentLightType == 4 ? mvOccupied->iLights[end::front] != 0 || mvOccupied->iLights[end::rear] != 0 : - InstrumentLightActive; - btInstrumentLight.Turn(InstrumentLightActive && lightpower); - btDashboardLight.Turn(DashboardLightActive && lightpower); - btTimetableLight.Turn(TimetableLightActive && lightpower); - - // guziki: - ggMainOffButton.Update(); - ggMainOnButton.Update(); - ggMainButton.Update(); - for (auto &remotelinebreaker : m_remotelinebreakers) - { - remotelinebreaker.main_switch.Update(); - remotelinebreaker.on_button.Update(); - remotelinebreaker.off_button.Update(); - } - ggSecurityResetButton.Update(); - ggSHPResetButton.Update(); - ggReleaserButton.Update(); - ggSpringBrakeOnButton.Update(); - ggSpringBrakeOffButton.Update(); - ggUniveralBrakeButton1.Update(); - ggUniveralBrakeButton2.Update(); - ggUniveralBrakeButton3.Update(); - ggEPFuseButton.Update(); - ggAntiSlipButton.Update(); - ggSandButton.Update(); - ggAutoSandButton.Update(); - ggFuseButton.Update(); - ggConverterFuseButton.Update(); - ggStLinOffButton.Update(); - ggRadioChannelSelector.Update(); - ggRadioChannelPrevious.Update(); - ggRadioChannelNext.Update(); - ggRadioStop.Update(); - ggRadioTest.Update(); - ggRadioCall1.Update(); - ggRadioCall3.Update(); - ggRadioVolumeSelector.Update(); - ggRadioVolumePrevious.Update(); - ggRadioVolumeNext.Update(); - ggRadioOnButton.Update(); - ggRadioOffButton.Update(); - ggRadioFuseOnButton.Update(); - ggRadioFuseOffButton.Update(); - ggDepartureSignalButton.Update(); - /* - ggPantFrontButton.Update(); - ggPantRearButton.Update(); - ggPantFrontButtonOff.Update(); - ggPantRearButtonOff.Update(); - */ - ggPantAllDownButton.Update(); - ggPantSelectedDownButton.Update(); - ggPantSelectedButton.Update(); - ggPantValvesButton.Update(); - ggPantCompressorButton.Update(); - ggPantCompressorValve.Update(); - - ggPantValvesOff.Update(); - ggPantValvesUpdate.Update(); - - ggLightsButton.Update(); - ggUpperLightButton.Update(); - ggLeftLightButton.Update(); - ggRightLightButton.Update(); - ggLeftEndLightButton.Update(); - ggRightEndLightButton.Update(); - ggModernLightDimSw.Update(); - // hunter-230112 - ggRearUpperLightButton.Update(); - ggRearLeftLightButton.Update(); - ggRearRightLightButton.Update(); - ggRearLeftEndLightButton.Update(); - ggRearRightEndLightButton.Update(); - ggDimHeadlightsButton.Update(); - ggDimHeadlightsButton.Update(); - //------------ - ggConverterButton.Update(); - ggConverterLocalButton.Update(); - ggConverterOffButton.Update(); - ggTrainHeatingButton.Update(); - ggSignallingButton.Update(); - ggNextCurrentButton.Update(); - ggHornButton.Update(); - ggHornLowButton.Update(); - ggHornHighButton.Update(); - ggWhistleButton.Update(); - if (DynamicObject->Mechanik != nullptr) - { - ggHelperButton.UpdateValue(static_cast(DynamicObject->Mechanik->HelperState)); - } - ggHelperButton.Update(); - - ggSpeedControlIncreaseButton.Update(lowvoltagepower); - ggSpeedControlDecreaseButton.Update(lowvoltagepower); - ggSpeedControlPowerIncreaseButton.Update(lowvoltagepower); - ggSpeedControlPowerDecreaseButton.Update(lowvoltagepower); - for (auto &speedctrlbutton : ggSpeedCtrlButtons) - { - speedctrlbutton.Update(lowvoltagepower); - } - for (auto &universal : ggUniversals) - { - universal.Update(); - } - for (auto &item : ggInverterEnableButtons) - { - item.Update(); - } - for (auto &item : ggInverterDisableButtons) - { - item.Update(); - } - for (auto &item : ggInverterToggleButtons) - { - item.Update(); - } - for (auto &relayresetbutton : ggRelayResetButtons) - { - relayresetbutton.Update(); - } - // hunter-091012 - ggInstrumentLightButton.Update(); - ggDashboardLightButton.Update(); - ggTimetableLightButton.Update(); - ggCabLightDimButton.Update(); - ggCompartmentLightsButton.Update(); - ggCompartmentLightsOnButton.Update(); - ggCompartmentLightsOffButton.Update(); - ggBatteryButton.Update(); - ggBatteryOnButton.Update(); - ggBatteryOffButton.Update(); - if (ggCabActivationButton.SubModel != nullptr && ggCabActivationButton.type() != TGaugeType::push) - { - ggCabActivationButton.UpdateValue(mvOccupied->IsCabMaster() ? 1.0 : 0.0); - } - ggCabActivationButton.Update(); - - ggWaterPumpBreakerButton.Update(); - ggWaterPumpButton.Update(); - ggWaterHeaterBreakerButton.Update(); - ggWaterHeaterButton.Update(); - ggWaterCircuitsLinkButton.Update(); - ggFuelPumpButton.Update(); - ggOilPumpButton.Update(); - ggOilFuelPumpButton.Update(); - ggMotorBlowersFrontButton.Update(); - ggMotorBlowersRearButton.Update(); - ggMotorBlowersAllOffButton.Update(); - - // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) - btHaslerBrakes.Turn(mvOccupied->BrakePress > 0.4); // ciśnienie w cylindrach - btHaslerCurrent.Turn(mvOccupied->Im != 0.0); // prąd na silnikach - - // calculate current level of interior illumination - { - // TODO: organize it along with rest of train update in a more sensible arrangement - // Ra: uzeleżnic od napięcia w obwodzie sterowania - // hunter-091012: uzaleznienie jasnosci od przetwornicy - int cabidx{0}; - for (auto &cab : Cabine) - { - - auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (mvOccupied->Power110vIsAvailable ? 1.f : 0.5f); - - if (cab.LightLevel != cablightlevel) - { - cab.LightLevel = cablightlevel; - DynamicObject->set_cab_lights(cabidx, cab.LightLevel); - } - if (cabidx == iCabn) - { - DynamicObject->InteriorLightLevel = cablightlevel; - } - - ++cabidx; - } - } - - // anti slip system activation, maintained while the control button is down - if (mvOccupied->BrakeSystem != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) - { - mvControlled->AntiSlippingBrake(); - } - // screens - - if (!FreeFlyModeFlag && simulation::Train == this) // don't bother if we're outside - { - update_screens(Deltatime); - update_script_screens(); - } - - // update direction relay - if (prevBatState != mvOccupied->Power24vIsAvailable) - SetupDirectionRelays(); - if (prevDirection != mvOccupied->DirActive) - UpdateDirectionRelays(); - - prevBatState = mvOccupied->Power24vIsAvailable; - prevDirection = mvOccupied->DirActive; - - // sounds - update_sounds(Deltatime); - - return true; //(DynamicObject->Update(dt)); -} // koniec update - -void TTrain::UpdateDirectionRelays() -{ - if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz - Dynamic()->sDirectionRelayR.play(); - if (mvOccupied->DirActive == 0 && mvOccupied->Power24vIsAvailable) // neutral - Dynamic()->sDirectionRelayN.play(); - if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod - Dynamic()->sDirectionRelayD.play(); -} - -void TTrain::SetupDirectionRelays() -{ - if (mvOccupied->Power24vIsAvailable) - { - if (mvOccupied->DirActive < 0 && mvOccupied->Power24vIsAvailable) // wstecz - Dynamic()->sDirectionRelayR.play(); - if (mvOccupied->DirActive > 0 && mvOccupied->Power24vIsAvailable) // przod - Dynamic()->sDirectionRelayD.play(); - } - else if (mvOccupied->DirActive != 0) // neutral - Dynamic()->sDirectionRelayN.play(); -} - -void TTrain::update_sounds(double const Deltatime) -{ - - double volume{0.0}; - double const brakevolumescale{0.5}; - - // Winger-160404 - syczenie pomocniczego (luzowanie) - if (m_lastlocalbrakepressure != -1.f) - { - // calculate rate of pressure drop in local brake cylinder, once it's been initialized - auto const brakepressuredifference{mvOccupied->LocBrakePress - m_lastlocalbrakepressure}; - m_localbrakepressurechange = static_cast(std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f)); - } - m_lastlocalbrakepressure = static_cast(mvOccupied->LocBrakePress); - // local brake, release - if (rsSBHiss) - { - if (m_localbrakepressurechange < -0.05f && mvOccupied->LocBrakePress > mvOccupied->BrakePress - 0.05) - { - rsSBHiss->gain(static_cast(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5))); - rsSBHiss->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - // don't stop the sound too abruptly - volume = std::max(0.0, rsSBHiss->gain() - 0.1 * Deltatime); - rsSBHiss->gain(static_cast(volume)); - if (volume < 0.05) - { - rsSBHiss->stop(); - } - } - } - // local brake, engage - if (rsSBHissU) - { - if (m_localbrakepressurechange > 0.05f) - { - rsSBHissU->gain(static_cast(std::clamp(rsSBHissU->m_amplitudeoffset + rsSBHissU->m_amplitudefactor * m_localbrakepressurechange * 0.05, 0.0, 1.5))); - rsSBHissU->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - // don't stop the sound too abruptly - volume = std::max(0.0, rsSBHissU->gain() - 0.1 * Deltatime); - rsSBHissU->gain(static_cast(volume)); - if (volume < 0.05) - { - rsSBHissU->stop(); - } - } - } - - // McZapkie-280302 - syczenie - // TODO: softer volume reduction than plain abrupt stop, perhaps as reusable wrapper? - if (mvOccupied->BrakeHandle == TBrakeHandle::FV4a || mvOccupied->BrakeHandle == TBrakeHandle::FVel6) - { - // upuszczanie z PG - if (rsHiss) - { - fPPress = std::lerp(fPPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_b)), 0.05f); - volume = fPPress > 0 ? rsHiss->m_amplitudefactor * fPPress * 0.25 + rsHiss->m_amplitudeoffset : 0; - if (volume * brakevolumescale > 0.05) - { - rsHiss->gain(static_cast(volume * brakevolumescale)); - rsHiss->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHiss->stop(); - } - } - // napelnianie PG - if (rsHissU) - { - fNPress = std::lerp(fNPress, static_cast(mvOccupied->Handle->GetSound(s_fv4a_u)), 0.25f); - volume = fNPress > 0 ? rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0; - if (volume * brakevolumescale > 0.05) - { - rsHissU->gain(static_cast(volume * brakevolumescale)); - rsHissU->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissU->stop(); - } - } - // upuszczanie przy naglym - if (rsHissE) - { - volume = mvOccupied->Handle->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; - if (volume * brakevolumescale > 0.05) - { - rsHissE->gain(static_cast(volume * brakevolumescale)); - rsHissE->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissE->stop(); - } - } - // upuszczanie sterujacego fala - if (rsHissX) - { - volume = mvOccupied->Handle->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; - if (volume * brakevolumescale > 0.05) - { - rsHissX->gain(static_cast(volume * brakevolumescale)); - rsHissX->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissX->stop(); - } - } - // upuszczanie z czasowego - if (rsHissT) - { - volume = mvOccupied->Handle->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; - if (volume * brakevolumescale > 0.05) - { - rsHissT->gain(static_cast(volume * brakevolumescale)); - rsHissT->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissT->stop(); - } - } - } - else - { - // jesli nie FV4a - // upuszczanie z PG - if (rsHiss) - { - fPPress = static_cast((4.0f * fPPress + std::max(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); - volume = fPPress > 0.0f ? 2.0 * rsHiss->m_amplitudefactor * fPPress + rsHiss->m_amplitudeoffset : 0.0; - if (volume > 0.05) - { - rsHiss->gain(static_cast(volume)); - rsHiss->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHiss->stop(); - } - } - // napelnianie PG - if (rsHissU) - { - fNPress = static_cast((4.0f * fNPress + std::min(0.0, mvOccupied->dpMainValve)) / (4.0f + 1.0f)); - volume = fNPress < 0.0f ? -1.0 * rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0.0; - if (volume > 0.01) - { - rsHissU->gain(static_cast(volume)); - rsHissU->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsHissU->stop(); - } - } - } // koniec nie FV4a - - // brakes - if (rsBrake) - { - if (mvOccupied->UnitBrakeForce > 10.0 && mvOccupied->Vel > 0.05) - { - - auto const brakeforceratio{ - std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0)}; - // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside - volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, mvOccupied->Vel / (1 + mvOccupied->Vmax))) * rsBrake->m_amplitudefactor; - rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + mvOccupied->Vel * rsBrake->m_frequencyfactor)); - rsBrake->gain(static_cast(volume)); - rsBrake->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - rsBrake->stop(); - } - } - - // ambient sound - // since it's typically ticking of the clock we can center it on tachometer or on middle of compartment bounding area - if (rsFadeSound) - { - rsFadeSound->play(sound_flags::exclusive | sound_flags::looping); - } - - if (dsbSlipAlarm) - { - // alarm przy poslizgu dla 181/182 - BOMBARDIER - if (mvControlled->SlippingWheels && DynamicObject->GetVelocity() > 1.0) - { - dsbSlipAlarm->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - dsbSlipAlarm->stop(); - } - } - - // dzwiek wiatru rozbijajacego sie o szyby w kabinie - if (rsWindSound) - { - if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) - update_sounds_resonancenoise(*rsWindSound); - else - rsWindSound->stop(FreeFlyModeFlag); - } - - // dzwiek rezonansu (taki drugi runningnoise w sumie) - if (rsResonanceNoise) - { - if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) - { - - update_sounds_resonancenoise(*rsResonanceNoise); - } - else - rsResonanceNoise->stop(FreeFlyModeFlag); - } - - // szum w czasie jazdy - if (rsRunningNoise) - { - if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) - { - - update_sounds_runningnoise(*rsRunningNoise); - } - else - { - // don't play the optional ending sound if the listener switches views - rsRunningNoise->stop(true == FreeFlyModeFlag); - } - } - // hunting oscillation noise - if (rsHuntingNoise) - { - if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5 && DynamicObject->IsHunting) - { - - update_sounds_runningnoise(*rsHuntingNoise); - // modify calculated sound volume by hunting amount - auto const huntingamount = std::lerp( - 0.0, 1.0, std::clamp((mvOccupied->Vel - DynamicObject->HuntingShake.fadein_begin) / (DynamicObject->HuntingShake.fadein_end - DynamicObject->HuntingShake.fadein_begin), 0.0, 1.0)); - - rsHuntingNoise->gain(static_cast(rsHuntingNoise->gain() * huntingamount)); - } - else - { - // don't play the optional ending sound if the listener switches views - rsHuntingNoise->stop(true == FreeFlyModeFlag); - } - } - // rain sound - if (m_rainsound) - { - if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && Global.Weather == "rain:") - { - if (m_rainsound->is_combined()) - { - m_rainsound->pitch(static_cast(Global.Overcast - 1.0)); - } - m_rainsound->gain(m_rainsound->m_amplitudeoffset + m_rainsound->m_amplitudefactor * 1.f); - m_rainsound->play(sound_flags::exclusive | sound_flags::looping); - } - else - { - m_rainsound->stop(); - } - } - - if (dsbHasler) - { - if (fTachoCount >= 3.f) - { - auto const soundfrequency{(true == dsbHasler->is_combined() ? fTachoVelocity * 0.01 : dsbHasler->m_frequencyoffset + dsbHasler->m_frequencyfactor)}; - dsbHasler->pitch(static_cast(soundfrequency)); - dsbHasler->gain(dsbHasler->m_amplitudeoffset + dsbHasler->m_amplitudefactor); - dsbHasler->play(sound_flags::exclusive | sound_flags::looping); - } - else if (fTachoCount < 1.f) - { - dsbHasler->stop(); - } - } - - // power-reliant sounds - if (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable) - { - - // buzzer shp - if (mvOccupied->SecuritySystem.is_cabsignal_beeping()) - { - if (dsbBuzzerShp && false == dsbBuzzerShp->is_playing()) - { - dsbBuzzerShp->pitch(dsbBuzzerShp->m_frequencyoffset + dsbBuzzerShp->m_frequencyfactor); - dsbBuzzerShp->gain(dsbBuzzerShp->m_amplitudeoffset + dsbBuzzerShp->m_amplitudefactor); - dsbBuzzerShp->play(sound_flags::looping); - } - } - else - { - if (dsbBuzzerShp && true == dsbBuzzerShp->is_playing()) - { - dsbBuzzerShp->stop(); - } - } - - // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa - // hunter-091012: rozdzielenie alarmow - if (mvOccupied->SecuritySystem.is_beeping()) - { - if (dsbBuzzer && false == dsbBuzzer->is_playing()) - { - dsbBuzzer->pitch(dsbBuzzer->m_frequencyoffset + dsbBuzzer->m_frequencyfactor); - dsbBuzzer->gain(dsbBuzzer->m_amplitudeoffset + dsbBuzzer->m_amplitudefactor); - dsbBuzzer->play(sound_flags::looping); -#ifdef _WIN32 - Console::BitsSet(1 << 14); // ustawienie bitu 16 na PoKeys -#endif - } - } - else - { - if (dsbBuzzer && true == dsbBuzzer->is_playing()) - { - dsbBuzzer->stop(); -#ifdef _WIN32 - Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys -#endif - } - } - // distance meter alert - if (m_distancecounterclear) - { - auto const *owner{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; - if (m_distancecounter > owner->fLength) - { - // play assigned sound if the train travelled its full length since meter activation - // TBD: check all combinations of directions and active cab - m_distancecounter = -1.f; // turn off the meter after its task is done - m_distancecounterclear->pitch(m_distancecounterclear->m_frequencyoffset + m_distancecounterclear->m_frequencyfactor); - m_distancecounterclear->gain(m_distancecounterclear->m_amplitudeoffset + m_distancecounterclear->m_amplitudefactor); - m_distancecounterclear->play(sound_flags::exclusive); - } - } - } - else - { - // stop power-reliant sounds if power is cut - if (dsbBuzzer && true == dsbBuzzer->is_playing()) - { - dsbBuzzer->stop(); -#ifdef _WIN32 - Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys -#endif - } - - if (dsbBuzzerShp && dsbBuzzerShp->is_playing()) - { - dsbBuzzerShp->stop(); - } - - if (m_distancecounterclear) - { - m_distancecounterclear->stop(); - } - } - - update_sounds_radio(); - update_sounds_fmradio(Deltatime); -} - -void TTrain::update_sounds_resonancenoise(sound_source &Sound) const -{ - // frequency calculation - auto const normalizer{mvOccupied->Vmax * 0.01f}; - auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; - - // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, 0.5); // scale base volume between 0.5-1.0 - - if (volume > 0.05) - { - Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); - } - else - { - Sound.stop(); - } -} - -void TTrain::update_sounds_runningnoise(sound_source &Sound) -{ - // frequency calculation - auto const normalizer{(true == Sound.is_combined() ? mvOccupied->Vmax * 0.01f : 1.f)}; - auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * mvOccupied->Vel * normalizer}; - - // volume calculation - auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(mvOccupied->Vel / (1 + mvOccupied->Vmax), 1.0, - 0.5); // scale base volume between 0.5-1.0 - if (std::abs(mvOccupied->nrot) > 0.01) - { - // hamulce wzmagaja halas - auto const brakeforceratio{(std::clamp(mvOccupied->UnitBrakeForce / std::max(1.0, mvOccupied->BrakeForceR(1.0, mvOccupied->Vel) / (mvOccupied->NAxles * std::max(1, mvOccupied->NBpA))), 0.0, 1.0))}; - - volume *= 1 + 0.125 * brakeforceratio; - } - // scale volume by track quality - // TODO: track quality and/or environment factors as separate subroutine - volume *= std::lerp(0.8, 1.2, std::clamp(DynamicObject->MyTrack->iQualityFlag / 20.0, 0.0, 1.0)); - // for single sample sounds muffle the playback at low speeds - if (false == Sound.is_combined()) - { - volume *= std::lerp(0.0, 1.0, std::clamp(mvOccupied->Vel / 25.0, 0.0, 1.0)); - } - - if (volume > 0.05) - { - Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); - } - else - { - Sound.stop(); - } -} - -void TTrain::update_sounds_radio() -{ - - radio_message_played = false; - if (false == m_radiomessages.empty()) - { - // erase completed radio messages from the list - std::erase_if(m_radiomessages, [](auto const &source) { return false == source.second->is_playing(); }); - } - // adjust audibility of remaining messages based on current radio conditions - auto const radioenabled{mvOccupied->RadioPowered()}; - for (auto const &[messagechannel, messagesound] : m_radiomessages) - { - auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel() ? m_radiovolume : 0.0}; - messagesound->gain(static_cast(volume)); - radio_message_played |= true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel(); - } - // radiostop - if (m_radiostop) - { - if (true == radioenabled && true == mvOccupied->RadioStopFlag) - { - m_radiostop->play(sound_flags::exclusive | sound_flags::looping); - radio_message_played |= true; - } - else - { - m_radiostop->stop(); - } - } - if (radio_message_played) - { - btLampkaRadioMessage.gain(m_radiovolume); - } -} - -// operates the broadcast radio receiver -void TTrain::update_sounds_fmradio(double const Deltatime) -{ - // NOTE: there's a single receiver in the simulation, it plays in the cab occupied by the user - if (simulation::Train != this || false == m_fmradiopresent || false == Global.fmradio_enabled) - { - return; - } - auto &fmradio{audio::renderer.fmradio()}; - auto const bandwidth{audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART}; - if (false == m_fmradiotuned) - { - // initially the receiver is tuned to the first station on the list - m_fmradiodial = 100.f * (fmradio.default_frequency() - audio::EU07_FMRADIO_BANDSTART) / bandwidth; - m_fmradiotuned = true; - } - // knobs - if (m_fmradiovolumechange != 0) - { - m_fmradiovolume = std::clamp(m_fmradiovolume + m_fmradiovolumechange * 0.5f * static_cast(Deltatime), 0.f, 1.f); - if (false == m_controlmapper.contains("fmradio_sw:")) - { - // receivers without dedicated switch are switched with the volume knob - m_fmradiopower = m_fmradiovolume > 0.f; - } - } - if (m_fmradiotunechange != 0) - { - // the knob moves slowly at first to allow fine tuning, then speeds up - m_fmradiotunetime += static_cast(Deltatime); - auto const tunerate{std::lerp(0.15f, 2.5f, std::clamp(m_fmradiotunetime * 0.5f, 0.f, 1.f))}; // MHz per second - m_fmradiodial = std::clamp(m_fmradiodial + 100.f * m_fmradiotunechange * tunerate * static_cast(Deltatime) / bandwidth, 0.f, 100.f); - } - else - { - m_fmradiotunetime = 0.f; - } - - fmradio.type(m_fmradiotype); - fmradio.tune(audio::EU07_FMRADIO_BANDSTART + m_fmradiodial * 0.01f * bandwidth); - fmradio.volume(m_fmradiovolume); - fmradio.placement(m_fmradiosound.location(), m_fmradiosound.soundproofing_factor(), m_fmradiosound.range()); - // NOTE: the receiver runs on batteries of its own, so it doesn't care about the state of the vehicle - fmradio.power(m_fmradiopower); -} - -void TTrain::update_screens(double dt) -{ - for (auto &screen : m_screens) - { - if (screen.updatetimecounter >= 0) - screen.updatetimecounter += dt; - - if (screen.updatetimecounter <= screen.updatetime) - continue; - - screen.updatetimecounter = screen.updatetime > 0 ? 0 : -1; - - auto state_dict = GetTrainState(screen.parameters); - - state_dict->insert("touches", *screen.touch_list); - screen.touch_list->clear(); - - Application.request({screen.script, state_dict, screen.rt}); - } -} - -void TTrain::update_script_screens() -{ - auto &queue{Application.screens()}; - for (auto &entry : m_scriptscreens) - { - if (false == queue.due(*entry.screen)) - { - continue; - } - auto input{GetTrainState(entry.parameters)}; - input->insert("touches", *entry.touch_list); - entry.touch_list->clear(); - queue.submit(entry.screen, std::move(input), id()); - } -} - -bool TTrain::find_screen_surface(std::string const &Target, std::string_view const Kind, TSubModel *&Submodel, ITexture *&Texture) const -{ - Submodel = DynamicObject->mdKabina ? DynamicObject->mdKabina->GetFromName(Target) : - DynamicObject->mdLowPolyInt ? DynamicObject->mdLowPolyInt->GetFromName(Target) : - nullptr; - if (Submodel == nullptr) - { - WriteLog(std::format("{}: submodel {} not found - Ignoring screen", Kind, Target)); - return false; - } - auto const material{Submodel->GetMaterial()}; - if (material <= 0) - { - // sub model nie posiada tekstury lub tekstura wymienna - nie obslugiwana - WriteLog(std::format("{}: invalid texture id {} - Ignoring screen", Kind, material)); - return false; - } - - Texture = &GfxRenderer->Texture(GfxRenderer->Material(material)->GetTexture(0)); - return true; -} - -void TTrain::load_script_screen(cParser &Parser, script_language const Language) -{ - script_screen_entry entry; - // the block is read whole even when the script screens are off - entry.config.deserialize(Parser); - if (entry.config.script.empty()) - { - return; - } - if (substr_path(entry.config.script).empty()) - { - entry.config.script = DynamicObject->asBaseDir + entry.config.script; - } - - TSubModel *submodel{nullptr}; - ITexture *texture{nullptr}; - auto &queue{Application.screens()}; - if (false == queue.runs(Language)) - { - // the screens of the language are off - return; - } - if (entry.config.target != "none" && - false == find_screen_surface(entry.config.target, Language == script_language::lua ? "Lua Screen" : "WASM Screen", submodel, texture)) - { - return; - } - - entry.screen = queue.acquire({.kind = script_screen_kind::cab, - .language = Language, - .script = entry.config.script, - .key = std::format("cab:{}:{}:{}", DynamicObject->name(), entry.config.target, entry.config.script), - .texture = texture, - .frames = entry.config.frames}); - if (entry.screen == nullptr) - { - return; - } - if (texture != nullptr) - { - // make the surface static so it doesn't get destroyed by garbage collector if the user spends long time outside cab - texture->create(true); - } - if (false == entry.config.parameters.empty()) - { - entry.parameters = dictionary_source(entry.config.parameters); - } - entry.touch_list = std::make_shared>(); - if (submodel != nullptr) - { - submodel->screen_touch_list = entry.touch_list; - } - m_scriptscreens.emplace_back(std::move(entry)); -} - -void TTrain::add_distance(double const Distance) -{ - - auto const meterenabled{m_distancecounter >= 0 && (mvOccupied->Power24vIsAvailable || mvOccupied->Power110vIsAvailable)}; - - if (true == meterenabled) - { - m_distancecounter += static_cast(Distance * Occupied()->CabOccupied); - } - else - { - m_distancecounter = -1.f; - } -} - -bool TTrain::CabChange(int iDirection) -{ // McZapkie-090902: zmiana kabiny 1->0->2 i z powrotem - if (DynamicObject->Mechanik == nullptr || true == DynamicObject->Mechanik->AIControllFlag) - { - // jeśli prowadzi AI albo jest w innym członie - // jak AI prowadzi, to nie można mu mieszać - if (std::abs(mvOccupied->CabOccupied + iDirection) > 1) - return false; // ewentualna zmiana pojazdu - mvOccupied->CabOccupied += iDirection; - } - else - { // jeśli pojazd prowadzony ręcznie albo wcale (wagon) - mvOccupied->CabDeactivisationAuto(); - if (mvOccupied->ChangeCab(iDirection) && InitializeCab(mvOccupied->CabOccupied, mvOccupied->TypeName + ".mmd")) - { - // zmiana kabiny w ramach tego samego pojazdu - mvOccupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) - DynamicObject->Mechanik->DirectionChange(); - return true; // udało się zmienić kabinę - } - // aktywizacja poprzedniej, bo jeszcze nie wiadomo, czy jakiś pojazd jest - mvOccupied->CabActivisationAuto(); - } - return false; // ewentualna zmiana pojazdu -} - -// McZapkie-310302 -// wczytywanie pliku z danymi multimedialnymi (dzwieki, kontrolki, kabiny) -bool TTrain::LoadMMediaFile(std::string const &asFileName) -{ - using enum sound_placement; - using enum sound_type; - // initialize sounds so potential entries from previous vehicle don't stick around - std::unordered_map &, sound_placement, float, sound_type, int, double>> internalsounds = { - {"ctrl:", {dsbNastawnikJazdy, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"ctrlscnd:", {dsbNastawnikBocz, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"reverserkey:", {dsbReverserKey, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"buzzer:", {dsbBuzzer, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"buzzershp:", {dsbBuzzerShp, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"radiostop:", {m_radiostop, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"slipalarm:", {dsbSlipAlarm, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"distancecounter:", {m_distancecounterclear, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"tachoclock:", {dsbHasler, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"switch:", {dsbSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"pneumaticswitch:", {dsbPneumaticSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"airsound:", {rsHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound2:", {rsHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound3:", {rsHissE, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound4:", {rsHissX, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"airsound5:", {rsHissT, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"localbrakesound:", {rsSBHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"localbrakesound2:", {rsSBHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, - {"brakesound:", {rsBrake, internal, -1, single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, - {"fadesound:", {rsFadeSound, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, - {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, mvOccupied->Vmax}}, - {"rainsound:", {m_rainsound, internal, -1, single, 0, 100.0}}, - }; - for (auto &[soundname, soundsource] : internalsounds) - { - std::get &>(soundsource).reset(); - } - // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment - m_radiosound.owner(DynamicObject); - m_fmradiosound.owner(DynamicObject); - CabSoundLocations.clear(); - - cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); - // NOTE: yaml-style comments are disabled until conflict in use of # is resolved - // parser.addCommentStyle( "#", "\n" ); - std::string token; - do - { - token = ""; - parser.getTokens(); - parser >> token; - } while (token != "" && token != "internaldata:"); - - if (token == "internaldata:") - { - - do - { - token = ""; - parser.getTokens(); - parser >> token; - - auto lookup{internalsounds.find(token)}; - if (lookup == internalsounds.end()) - { - continue; - } - - auto const soundconfig{lookup->second}; - sound_source sound{std::get(soundconfig), std::get(soundconfig)}; - sound.deserialize(parser, std::get(soundconfig), std::get(soundconfig), static_cast(std::get(soundconfig))); - sound.owner(DynamicObject); - std::get &>(soundconfig) = sound; - } while (token != ""); - - // assign default samples to sound emitters which weren't included in the config file - if (!m_rainsound) - { - sound_source rainsound; - rainsound.deserialize("rainsound_default", single); - rainsound.owner(DynamicObject); - m_rainsound = rainsound; - } - if (!rsSBHiss) - { - // fallback for vehicles without defined local brake hiss sound - rsSBHiss = rsHiss; - } - if (!rsSBHissU) - { - // fallback for vehicles without defined local brake hiss sound - rsSBHissU = rsHissU; - } - if (rsBrake) - { - rsBrake->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsResonanceNoise) - { - rsResonanceNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsWindSound) - { - rsWindSound->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsRunningNoise) - { - rsRunningNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - if (rsHuntingNoise) - { - rsHuntingNoise->m_frequencyfactor /= static_cast(1 + mvOccupied->Vmax); - } - } - std::vector>> sounds = { - dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, - rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, - m_rainsound, m_radiostop}; - for (auto &sound : sounds) - { - if (sound.get()) - { - CabSoundLocations.emplace_back(sound, sound.get()->offset()); - } - } - - return true; -} - -bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) -{ - m_controlmapper.clear(); - // clear python screens - m_screens.clear(); - m_scriptscreens.clear(); - // reset sound positions - auto const nullvector{glm::vec3()}; - std::vector>> sounds = { - dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, - rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, - m_rainsound, m_radiostop}; - for (auto const &sound : sounds) - { - if (sound.get()) - { - sound.get()->offset(nullvector); - } - } - m_radiosound.offset(nullvector); - m_fmradiosound.offset(nullvector); - m_fmradiopresent = false; - for (auto const &[soundsource, soundoffset] : CabSoundLocations) - { - if (soundsource.get() && soundsource.get()->offset() == nullvector) - { - soundsource.get()->offset(soundoffset); - } - } - // reset view angles - pMechViewAngle = {0.0, 0.0}; - - is_cab_initialized = true; // the attempt may fail, but it's the attempt that counts - - bool parse = false; - int cabindex = 0; - DynamicObject->mdKabina = nullptr; // likwidacja wskaźnika na dotychczasową kabinę - switch (NewCabNo) - { // ustalenie numeru kabiny do wczytania - case -1: - cabindex = 2; - break; - case 1: - cabindex = 1; - break; - case 0: - cabindex = 0; - break; - default: - break; - } - iCabn = cabindex; - - std::string cabstr("cab" + std::to_string(cabindex) + "definition:"); - - cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); - // NOTE: yaml-style comments are disabled until conflict in use of # is resolved - // parser.addCommentStyle( "#", "\n" ); - std::string token; - do - { - // szukanie kabiny - token = ""; - parser.getTokens(); - parser >> token; - } while (token != "" && token != cabstr); - - if (token == cabstr) - { - // jeśli znaleziony wpis kabiny - Cabine[cabindex].Load(parser); - // NOTE: the position and angle definitions depend on strict entry order - // TODO: refactor into more flexible arrangement - parser.getTokens(); - parser >> token; - if (token == std::string("driver" + std::to_string(cabindex) + "angle:")) - { - // camera view angle - parser.getTokens(2, false); - // angle is specified in degrees but internally stored in radians - glm::vec2 viewangle; - parser >> viewangle.y // yaw first, then pitch - >> viewangle.x; - pMechViewAngle = glm::radians(viewangle); - - Global.pCamera.Angle.x = pMechViewAngle.x; - Global.pCamera.Angle.y = pMechViewAngle.y; - - parser.getTokens(); - parser >> token; - } - if (token == std::string("driver" + std::to_string(cabindex) + "pos:")) - { - // pozycja poczatkowa maszynisty - parser.getTokens(3, false); - parser >> pMechOffset.x >> pMechOffset.y >> pMechOffset.z; - pMechSittingPosition = pMechOffset; - - parser.getTokens(); - parser >> token; - } - // ABu: pozycja siedzaca mechanika - if (token == std::string("driver" + std::to_string(cabindex) + "sitpos:")) - { - // ABu 180404 pozycja siedzaca maszynisty - parser.getTokens(3, false); - parser >> pMechSittingPosition.x >> pMechSittingPosition.y >> pMechSittingPosition.z; - - parser.getTokens(); - parser >> token; - } - // else parse=false; - do - { - if (parse == true) - { - token = ""; - parser.getTokens(); - parser >> token; - } - else - { - parse = true; - } - // inicjacja kabiny - // Ra 2014-08: zmieniamy zasady - zamiast przypisywać submodel do - // istniejących obiektów animujących - // będziemy teraz uaktywniać obiekty animujące z tablicy i podawać im - // submodel oraz wskaźnik na parametr - if (token == std::string("cab" + std::to_string(cabindex) + "model:")) - { - // model kabiny - parser.getTokens(); - parser >> token; - std::ranges::replace(token, '\\', '/'); - if (token != "none") - { - // bieżąca sciezka do tekstur to dynamic/... - Global.asCurrentTexturePath = DynamicObject->asBaseDir; - // szukaj kabinę jako oddzielny model - // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory - replace_slashes(token); - erase_leading_slashes(token); - if (token[0] == '/') - { - token.erase(0, 1); - } - TModel3d *kabina = TModelsManager::GetModel(DynamicObject->asBaseDir + token, true, true, Global.network_servers.empty() && !Global.network_client ? 0 : id()); - // z powrotem defaultowa sciezka do tekstur - Global.asCurrentTexturePath = paths::textures; - // if (DynamicObject->mdKabina!=k) - if (kabina != nullptr) - { - DynamicObject->mdKabina = kabina; // nowa kabina - } - //(mdKabina) może zostać to samo po przejściu do innego członu bez - // zmiany kabiny, przy powrocie musi być wiązanie ponowne - // else - // break; //wyjście z pętli, bo model zostaje bez zmian - } - else if (cabindex == 1) - { - // model tylko, gdy nie ma kabiny 1 - // McZapkie-170103: szukaj elementy kabiny w glownym modelu - DynamicObject->mdKabina = DynamicObject->mdModel; - } - clear_cab_controls(); - } - /* - if (nullptr == DynamicObject->mdKabina) - { - // don't bother with other parts until the cab is initialised - continue; - } - */ - else if (true == initialize_gauge(parser, token, cabindex)) - { - // matched the token, grab the next one - continue; - } - else if (true == initialize_button(parser, token, cabindex)) - { - // matched the token, grab the next one - continue; - } - // TODO: add "pydestination:" - else if (token == "pyscreen:") - { - screen_entry screen; - screen.deserialize(parser); - if (false == screen.script.empty() && substr_path(screen.script).empty()) - { - screen.script = DynamicObject->asBaseDir + screen.script; - } - - ITexture *tex = nullptr; - TSubModel *submodel = nullptr; - if (screen.target != "none") - { - if (false == find_screen_surface(screen.target, "Python Screen", submodel, tex)) - { - continue; - } - } - else - { - // TODO: fix leak - tex = ITexture::null_texture(); - tex->make_stub(); - } - - tex->create(true); // make the surface static so it doesn't get destroyed by garbage - // collector if the user spends long time outside cab - // TBD, TODO: keep texture handles around, so we can undo the static switch when the - // user changes cabs? - auto rt = std::make_shared(); - rt->shared_tex = tex; - - // record renderer and material binding for future update requests - m_screens.emplace_back(screen); - m_screens.back().rt = rt; - - m_screens.back().touch_list = std::make_shared>(); - if (submodel) - submodel->screen_touch_list = m_screens.back().touch_list; - - if (Global.python_displaywindows) - m_screens.back().viewer = std::make_unique(rt, m_screens.back().touch_list, m_screens.back().script); - } - else if (token == "luascreen:") - { - load_script_screen(parser, script_language::lua); - } - else if (token == "wasmscreen:") - { - load_script_screen(parser, script_language::wasm); - } - else if (token == "pyscreenupdatetime:") - { - parser.getTokens(); - parser >> ScreenUpdateRate; - } - else if (token == "fmradio:") - { - // broadcast radio receiver, the parameter selects character of its sound - std::string fmradiotype; - parser.getTokens(); - parser >> fmradiotype; - m_fmradiotype = (fmradiotype == "wooden" ? audio::fmradio_type::wooden : audio::fmradio_type::cheap); - m_fmradiopresent = true; - } - else if (token == "fmradiospeaker:") - { - // submodel marking location of the receiver speaker, the sound is emitted from there - std::string speakername; - parser.getTokens(); - parser >> speakername; - TSubModel *speaker{nullptr}; - for (auto const *source : {DynamicObject->mdKabina, DynamicObject->mdLowPolyInt}) - { - if (source != nullptr && (speaker = source->GetFromName(speakername)) != nullptr) - { - break; - } - } - if (speaker != nullptr) - { - m_fmradiosound.offset(speaker->offset(1.f)); - } - else - { - ErrorLog("Bad config: failed to locate fm radio speaker submodel \"" + speakername + "\"", logtype::model); - } - m_fmradiopresent = true; - } - // btLampkaUnknown`"unknown",mdKabina,false); - } while (token != "" - // TODO: enable full per-cab deserialization when/if .mmd files get proper per-cab switch configuration - // && ( token != "cab1definition:" ) - // && ( token != "cab2definition:" ) - && token != "cab0definition:"); - for (auto &screen : m_screens) - { - if (screen.updatetime > 0) - { - screen.updatetime = std::max((int)screen.updatetime, Global.PythonScreenUpdateRate) * 0.001; - } - if (screen.updatetime == 0) - { - screen.updatetime = std::max(Global.PythonScreenUpdateRate, ScreenUpdateRate) * 0.001; - } - if (screen.updatetime < -1) - { - screen.updatetime = -screen.updatetime * 0.001; - } - } - } - else - { - return false; - } - /* - if (DynamicObject->mdKabina) - { - */ - // configure placement of sound emitters which aren't bound with any device model, and weren't placed manually - auto const caboffset{glm::dvec3{(Cabine[cabindex].CabPos1 + Cabine[cabindex].CabPos2) * 0.5f} + glm::dvec3{0, 1, 0}}; - // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment - if (m_radiosound.offset() == nullvector) - { - m_radiosound.offset(btLampkaRadio.model_offset()); - } - if (m_radiosound.offset() == nullvector) - { - m_radiosound.offset(caboffset); - } - if (m_fmradiosound.offset() == nullvector) - { - m_fmradiosound.offset(caboffset); - } - if (m_fmradiopresent && false == m_fmradiopower && m_controlmapper.contains("fmradiovolume_sw:") && false == m_controlmapper.contains("fmradio_sw:")) - { - // receivers without dedicated switch are switched with the volume knob, so it has to start at the off position - m_fmradiovolume = 0.f; - } - std::vector>, glm::vec3>> soundlocations = { - {dsbReverserKey, ggDirKey.model_offset()}, - {dsbNastawnikJazdy, ggJointCtrl.model_offset()}, - {dsbNastawnikJazdy, ggMainCtrl.model_offset()}, // NOTE: fallback for vehicles without universal controller - {dsbNastawnikBocz, ggScndCtrl.model_offset()}, - {dsbSwitch, caboffset}, - {dsbPneumaticSwitch, caboffset}, - {rsHiss, ggBrakeCtrl.model_offset()}, - {rsHissU, ggBrakeCtrl.model_offset()}, - {rsHissE, ggBrakeCtrl.model_offset()}, - {rsHissX, ggBrakeCtrl.model_offset()}, - {rsHissT, ggBrakeCtrl.model_offset()}, - {rsSBHiss, ggLocalBrake.model_offset()}, - {rsSBHiss, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located - {rsSBHissU, ggLocalBrake.model_offset()}, - {rsSBHissU, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located - {rsFadeSound, caboffset}, - {rsRunningNoise, caboffset}, - {rsResonanceNoise, caboffset}, - {rsWindSound, caboffset}, - {rsHuntingNoise, caboffset}, - {dsbHasler, caboffset}, - {dsbBuzzer, btLampkaCzuwaka.model_offset()}, - {dsbBuzzerShp, btLampkaCzuwaka.model_offset()}, - {dsbSlipAlarm, caboffset}, - {m_distancecounterclear, btLampkaCzuwaka.model_offset()}, - {m_rainsound, caboffset}, - {m_radiostop, m_radiosound.offset()}, - }; - for (auto const &[soundsource, soundoffset] : soundlocations) - { - if (soundsource.get() && soundsource.get()->offset() == nullvector) - { - soundsource.get()->offset(soundoffset); - } - } - // second pass, in case some items received no positioning due to missing submodels etc - for (auto const &[soundsource, soundoffset] : soundlocations) - { - if (soundsource.get() && soundsource.get()->offset() == nullvector) - { - soundsource.get()->offset(caboffset); - } - } - - if (DynamicObject->mdKabina) - { - DynamicObject->mdKabina->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego - // the vehicle has a cab, a player is in it: the odometer store keeps the vehicle also when its type has no - // driver's brake valve (eu07/maszyna#72) - DynamicObject->MoverParameters->Odometer.shown = true; - } - - set_cab_controls(NewCabNo < 0 ? 2 : NewCabNo); - - // set pantograpths (hujhujhuj) - change_pantograph_selection(0); - - /* - return true; -} -return (token == "none"); -*/ - return true; -} - -glm::dvec3 TTrain::MirrorPosition(bool lewe) -{ // zwraca współrzędne widoku kamery z lusterka - auto const shiftdirection{(lewe ? -1 : 1) * (iCabn == 2 ? 1 : -1)}; - - return DynamicObject->mMatrix * - glm::dvec4(mvOccupied->Dim.W * (0.5 * shiftdirection) + 0.2 * shiftdirection, 1.5 + Cabine[iCabn].CabPos1.y, std::lerp(Cabine[iCabn].CabPos1.z, Cabine[iCabn].CabPos2.z, 0.5), 1.0); -}; - -void TTrain::DynamicSet(TDynamicObject *d) -{ // taka proteza: chcę podłączyć - // kabinę EN57 bezpośrednio z - // silnikowym, aby nie robić tego - // przez ukrotnienie - // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka - // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą - // świecić się w rozrządczych - // dla EZT światła czołowe będą "zapalane w silnikowym", ale widziane z - // rozrządczych - // również wczytywanie MMD powinno dotyczyć aktualnego członu - // problematyczna może być kwestia wybranej kabiny (w silnikowym...) - // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno - // jeździć dobrze - // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... - DynamicObject = d; // jedyne miejsce zmiany - mvControlled = d ? DynamicObject->MoverParameters : nullptr; // albo silnikowy w EZT - mvOccupied = mvControlled; - - if (DynamicObject == nullptr) - { - return; - } - - mvControlled = DynamicObject->FindPowered()->MoverParameters; - mvSecond = nullptr; // gdyby się nic nie znalazło - if (mvOccupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo - { - if (mvOccupied->Couplers[1].Connected ? mvOccupied->Couplers[1].AllowedFlag & coupling::control : false) - { // gdy jest człon od sprzęgu 1, a sprzęg łączony - // warsztatowo (powiedzmy) - if (mvOccupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc - mvSecond = mvOccupied->Couplers[1].Connected; // wskaźnik na drugiego - } - else if (mvOccupied->Couplers[0].Connected ? mvOccupied->Couplers[0].AllowedFlag & coupling::control : false) - { // gdy jest człon od sprzęgu 0, a sprzęg łączony - // warsztatowo (powiedzmy) - if (mvOccupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc - mvSecond = mvOccupied->Couplers[0].Connected; // wskaźnik na drugiego - } - } - // cache nearest unit equipped with pantographs - { - auto *lookup{DynamicObject->FindPantographCarrier()}; - // HACK: set pointer to existing vehicle to avoid error checking all over the place - mvPantographUnit = lookup != nullptr ? lookup->MoverParameters : mvControlled; - } -}; - -void TTrain::MoveToVehicle(TDynamicObject *target) -{ - // > Ra: to nie może być tak robione, to zbytnia proteza jest - // indeed, too much hacks... - // TODO: cleanup - TTrain *target_train = simulation::Trains.find(target->name()); - if (target_train) - { - // let's try to destroy this TTrain and move to already existing one - - if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) - { - // tylko jeśli ręcznie prowadzony - // jeśli prowadzi AI, to mu nie robimy dywersji! - Occupied()->CabDeactivisation(); - Occupied()->CabOccupied = 0; - Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 - Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); - Occupied()->ScndCtrlPos = 0; - Dynamic()->MechInside = false; - Dynamic()->Controller = AIdriver; - - Dynamic()->bDisplayCab = false; - Dynamic()->ABuSetModelShake({}); - - if (Dynamic()->Mechanik) - Dynamic()->Mechanik->MoveTo(target); - - target_train->Occupied()->LimPipePress = target_train->Occupied()->PipePress; - target_train->Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) - target_train->Dynamic()->MechInside = true; - if (target_train->Dynamic()->Mechanik) - { - target_train->Dynamic()->Controller = target_train->Dynamic()->Mechanik->AIControllFlag; - target_train->Dynamic()->Mechanik->DirectionChange(); - } - else - { - target_train->Dynamic()->Controller = Humandriver; - } - } - else - { - target_train->Dynamic()->bDisplayCab = false; - target_train->Dynamic()->ABuSetModelShake({}); - } - - target_train->Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? - - // potentially move player - if (simulation::Train == this) - { - simulation::Train = target_train; - // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization - target_train->Dynamic()->bDisplayCab |= !FreeFlyModeFlag; - } - - // delete this TTrain - pending_delete = true; - } - else - { - // move this TTrain to other dynamic - - // remove TTrain from global list, we're going to change dynamic anyway - simulation::Trains.detach(Dynamic()->name()); - - if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag) - { - // tylko jeśli ręcznie prowadzony - // jeśli prowadzi AI, to mu nie robimy dywersji! - - Occupied()->CabDeactivisation(); - Occupied()->CabOccupied = 0; - Occupied()->BrakeLevelSet(Occupied()->Handle->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 - Occupied()->MainCtrlPos = Occupied()->MainCtrlNoPowerPos(); - Occupied()->ScndCtrlPos = 0; - Dynamic()->MechInside = false; - Dynamic()->Controller = AIdriver; - - Dynamic()->bDisplayCab = false; - Dynamic()->ABuSetModelShake({}); - - if (Dynamic()->Mechanik) - Dynamic()->Mechanik->MoveTo(target); - - DynamicSet(target); - - Dynamic()->MechInside = true; - if (Dynamic()->Mechanik) - { - Dynamic()->Controller = Dynamic()->Mechanik->AIControllFlag; - Dynamic()->Mechanik->DirectionChange(); - } - else - { - Dynamic()->Controller = Humandriver; - } - - Occupied()->LimPipePress = Occupied()->PipePress; - Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) - } - else - { - Dynamic()->bDisplayCab = false; - Dynamic()->ABuSetModelShake({}); - - DynamicSet(target); - } - - { - auto const filename{Occupied()->TypeName + ".mmd"}; - LoadMMediaFile(filename); - InitializeCab(Occupied()->CabActive, filename); - } - - Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? - - if (simulation::Train == this) - { - // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization - Dynamic()->bDisplayCab |= !FreeFlyModeFlag; - } - - // add it back with updated dynamic name - simulation::Trains.insert(this); - } -} - -// checks whether specified point is within boundaries of the active cab -bool TTrain::point_inside(glm::dvec3 const Point) const -{ - - return Point.x >= Cabine[iCabn].CabPos1.x && Point.x <= Cabine[iCabn].CabPos2.x && Point.y >= Cabine[iCabn].CabPos1.y + 0.5 && Point.y <= Cabine[iCabn].CabPos2.y + 1.8 && - Point.z >= Cabine[iCabn].CabPos1.z && Point.z <= Cabine[iCabn].CabPos2.z; -} - -glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const -{ - - if (DebugModeFlag) - { - return Point; - } - - // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, - // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds - // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did - return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), - safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; -} - -const TTrain::screenentry_sequence &TTrain::get_screens() -{ - update_screens(Timer::GetDeltaTime()); - return m_screens; -} - -void TTrain::radio_message(sound_source *Message, int const Channel) -{ - - if (auto const soundrange{Message->range()}; soundrange > 0 && glm::length2(Message->location() - glm::dvec3{DynamicObject->GetPosition()}) > sq(soundrange)) - { - // skip message playback if the receiver is outside of the emitter's range - return; - } - // NOTE: we initiate playback of all sounds in range, in case the user switches on the radio or tunes to the right channel mid-play - m_radiomessages.emplace_back(Channel, std::make_shared(m_radiosound)); - // assign sound to the template and play it - auto &message = *m_radiomessages.back().second.get(); - auto const radioenabled{mvOccupied->RadioPowered()}; - auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && Channel == RadioChannel() ? 1.0 : 0.0}; - message.copy_sounds(*Message).gain(static_cast(volume)).play(); -} - -// clears state of all cabin controls -void TTrain::clear_cab_controls() -{ - // indicators exposed to custom control devices - btLampkaSHP.Clear(0); - btLampkaCzuwaka.Clear(1); - btLampkaOpory.Clear(2); - btLampkaWylSzybki.Clear(3); - btLampkaNadmSil.Clear(4); - btLampkaStyczn.Clear(5); - btLampkaPoslizg.Clear(6); - btLampkaNadmPrzetw.Clear((mvControlled->TrainType & dt_EZT) != 0 ? -1 : 7); // EN57 nie ma tej lampki - btLampkaPrzetwOff.Clear((mvControlled->TrainType & dt_EZT) != 0 ? 7 : -1); // za to ma tę - btLampkaNadmSpr.Clear(8); - btLampkaNadmWent.Clear(9); - btLampkaWysRozr.Clear((mvControlled->TrainType & dt_ET22) != 0 ? -1 : 10); // ET22 nie ma tej lampki - btLampkaOgrzewanieSkladu.Clear(11); - // overheat indicator lamps - btLampkaOilOverheat.Clear(-1); - btLampkaWaterOverheat.Clear(-1); - btLampkaWaterAuxOverheat.Clear(-1); - btLampkaEngineOverheat.Clear(-1); - btHaslerBrakes.Clear(12); // ciśnienie w cylindrach do odbijania na haslerze - btHaslerCurrent.Clear(13); // prąd na silnikach do odbijania na haslerze - // Numer 14 jest używany dla buczka SHP w update_sounds() - // Jeśli ustawiamy nową wartość dla PoKeys wolna jest 15 - - // other cab controls - // TODO: arrange in more readable manner, and eventually refactor - ggJointCtrl.Clear(); - ggMainCtrl.Clear(); - ggMainCtrlAct.Clear(); - ggScndCtrl.Clear(); - ggScndCtrlButton.Clear(); - ggScndCtrlOffButton.Clear(); - ggDistanceCounterButton.Clear(); - ggDirKey.Clear(); - ggDirForwardButton.Clear(); - ggDirNeutralButton.Clear(); - ggDirBackwardButton.Clear(); - ggBrakeCtrl.Clear(); - ggLocalBrake.Clear(); - ggAlarmChain.Clear(); - ggBrakeProfileCtrl.Clear(); - ggBrakeProfileG.Clear(); - ggBrakeProfileR.Clear(); - ggBrakeOperationModeCtrl.Clear(); - ggWiperSw.Clear(); - ggMaxCurrentCtrl.Clear(); - ggMainOffButton.Clear(); - ggMainOnButton.Clear(); - for (auto &remotelinebreaker : m_remotelinebreakers) - { - remotelinebreaker.main_switch.Clear(); - remotelinebreaker.on_button.Clear(); - remotelinebreaker.off_button.Clear(); - remotelinebreaker.held_without_switch = false; - } - ggSecurityResetButton.Clear(); - ggSHPResetButton.Clear(); - ggReleaserButton.Clear(); - ggSpringBrakeOnButton.Clear(); - ggSpringBrakeOffButton.Clear(); - ggUniveralBrakeButton1.Clear(); - ggUniveralBrakeButton2.Clear(); - ggUniveralBrakeButton3.Clear(); - ggEPFuseButton.Clear(); - ggSandButton.Clear(); - ggAutoSandButton.Clear(); - ggAntiSlipButton.Clear(); - ggHornButton.Clear(); - ggHornLowButton.Clear(); - ggHornHighButton.Clear(); - ggWhistleButton.Clear(); - ggHelperButton.Clear(); - ggNextCurrentButton.Clear(); - ggSpeedControlIncreaseButton.Clear(); - ggSpeedControlDecreaseButton.Clear(); - ggSpeedControlPowerIncreaseButton.Clear(); - ggSpeedControlPowerDecreaseButton.Clear(); - for (auto &speedctrlbutton : ggSpeedCtrlButtons) - { - speedctrlbutton.Clear(); - } - for (auto &universal : ggUniversals) - { - universal.Clear(); - } - for (auto &item : ggInverterEnableButtons) - { - item.Clear(); - } - for (auto &item : ggInverterDisableButtons) - { - item.Clear(); - } - for (auto &item : ggInverterToggleButtons) - { - item.Clear(); - } - for (auto &relayresetbutton : ggRelayResetButtons) - { - relayresetbutton.Clear(); - } - ggInstrumentLightButton.Clear(); - ggDashboardLightButton.Clear(); - ggTimetableLightButton.Clear(); - // hunter-091012 - ggCabLightDimButton.Clear(); - ggCompartmentLightsButton.Clear(); - ggCompartmentLightsOnButton.Clear(); - ggCompartmentLightsOffButton.Clear(); - ggBatteryButton.Clear(); - ggBatteryOnButton.Clear(); - ggBatteryOffButton.Clear(); - ggCabActivationButton.Clear(); - //------- - ggFuseButton.Clear(); - ggConverterFuseButton.Clear(); - ggStLinOffButton.Clear(); - ggRadioChannelSelector.Clear(); - ggRadioChannelPrevious.Clear(); - ggRadioChannelNext.Clear(); - ggRadioStop.Clear(); - ggRadioTest.Clear(); - ggRadioCall1.Clear(); - ggRadioCall3.Clear(); - ggRadioVolumeSelector.Clear(); - ggRadioVolumePrevious.Clear(); - ggRadioVolumeNext.Clear(); - ggRadioOnButton.Clear(); - ggRadioOffButton.Clear(); - ggRadioFuseOnButton.Clear(); - ggRadioFuseOffButton.Clear(); - ggDoorLeftPermitButton.Clear(); - ggDoorRightPermitButton.Clear(); - ggDoorPermitPresetButton.Clear(); - ggDoorLeftButton.Clear(); - ggDoorRightButton.Clear(); - ggDoorLeftOnButton.Clear(); - ggDoorRightOnButton.Clear(); - ggDoorLeftOffButton.Clear(); - ggDoorRightOffButton.Clear(); - ggDoorAllOnButton.Clear(); - ggDoorAllOffButton.Clear(); - ggTrainHeatingButton.Clear(); - ggSignallingButton.Clear(); - ggDoorSignallingButton.Clear(); - ggDoorStepButton.Clear(); - ggDepartureSignalButton.Clear(); - ggCompressorButton.Clear(); - ggCompressorLocalButton.Clear(); - ggConverterButton.Clear(); - ggConverterOffButton.Clear(); - ggConverterLocalButton.Clear(); - ggMainButton.Clear(); - /* - ggPantFrontButton.Clear(); - ggPantRearButton.Clear(); - ggPantFrontButtonOff.Clear(); - ggPantRearButtonOff.Clear(); - */ - ggPantAllDownButton.Clear(); - ggPantSelectedButton.Clear(); - ggPantSelectedDownButton.Clear(); - ggPantValvesButton.Clear(); - ggPantCompressorButton.Clear(); - ggPantCompressorValve.Clear(); - - ggPantValvesOff.Clear(); - ggPantValvesUpdate.Clear(); - - ggI1B.Clear(); - ggI2B.Clear(); - ggI3B.Clear(); - ggItotalB.Clear(); - ggOilPressB.Clear(); - ggWater1TempB.Clear(); - - ggClockSInd.Clear(); - ggClockMInd.Clear(); - ggClockHInd.Clear(); - ggEngineVoltage.Clear(); - ggLVoltage.Clear(); - ggMainGearStatus.Clear(); - ggIgnitionKey.Clear(); - - ggWaterPumpBreakerButton.Clear(); - ggWaterPumpButton.Clear(); - ggWaterHeaterBreakerButton.Clear(); - ggWaterHeaterButton.Clear(); - ggWaterCircuitsLinkButton.Clear(); - ggFuelPumpButton.Clear(); - ggOilPumpButton.Clear(); - ggOilFuelPumpButton.Clear(); - ggMotorBlowersFrontButton.Clear(); - ggMotorBlowersRearButton.Clear(); - ggMotorBlowersAllOffButton.Clear(); - - btLampkaPrzetw.Clear(); - btLampkaPrzetwB.Clear(); - btLampkaPrzetwBOff.Clear(); - btLampkaPrzetwAOff.Clear(); - btLampkaPrzekRozn.Clear(); - btLampkaPrzekRoznPom.Clear(); - btLampkaUkrotnienie.Clear(); - btLampkaHamPosp.Clear(); - btLampkaWylSzybkiOff.Clear(); - btLampkaWylSzybkiB.Clear(); - btLampkaWylSzybkiBOff.Clear(); - btLampkaMainBreakerReady.Clear(); - btLampkaMainBreakerBlinkingIfReady.Clear(); - btLampkaBezoporowa.Clear(); - btLampkaBezoporowaB.Clear(); - btLampkaMaxSila.Clear(); - btLampkaPrzekrMaxSila.Clear(); - btLampkaRadio.Clear(); - btLampkaRadioMessage.Clear(); - btLampkaRadioStop.Clear(); - btLampkaHamulecReczny.Clear(); - btLampkaBlokadaDrzwi.Clear(); - btLampkaDoorLockOff.Clear(); - for (auto &universal : btUniversals) - { - universal.Clear(); - } - btInstrumentLight.Clear(); - btDashboardLight.Clear(); - btTimetableLight.Clear(); - btLampkaWentZaluzje.Clear(); - btLampkaDoorLeft.Clear(); - btLampkaDoorRight.Clear(); - btLampkaDepartureSignal.Clear(); - btLampkaRezerwa.Clear(); - btLampkaBoczniki.Clear(); - btLampkaBocznik1.Clear(); - btLampkaBocznik2.Clear(); - btLampkaBocznik3.Clear(); - btLampkaBocznik4.Clear(); - btLampkaGear1.Clear(); - btLampkaGear2.Clear(); - btLampkaHydroLockup.Clear(); - btLampkaRadiotelefon.Clear(); - btLampkaHamienie.Clear(); - btLampkaBrakingOff.Clear(); - btLampkaED.Clear(); - btLampkaBrakeProfileG.Clear(); - btLampkaBrakeProfileP.Clear(); - btLampkaBrakeProfileR.Clear(); - btLampkaSpringBrakeActive.Clear(); - btLampkaSpringBrakeInactive.Clear(); - btLampkaSprezarka.Clear(); - btLampkaSprezarkaB.Clear(); - btLampkaSprezarkaOff.Clear(); - btLampkaSprezarkaBOff.Clear(); - btLampkaFuelPumpOff.Clear(); - btLampkaOilPump.Clear(); - btLampkaNapNastHam.Clear(); - btLampkaOporyB.Clear(); - btLampkaStycznB.Clear(); - btLampkaHamowanie1zes.Clear(); - btLampkaHamowanie2zes.Clear(); - btLampkaNadmPrzetwB.Clear(); - btLampkaHVoltageB.Clear(); - btLampkaForward.Clear(); - btLampkaBackward.Clear(); - btLampkaNeutral.Clear(); - // light indicators - btLampkaUpperLight.Clear(); - btLampkaLeftLight.Clear(); - btLampkaRightLight.Clear(); - btLampkaLeftEndLight.Clear(); - btLampkaRightEndLight.Clear(); - btLampkaRearUpperLight.Clear(); - btLampkaRearLeftLight.Clear(); - btLampkaRearRightLight.Clear(); - btLampkaRearLeftEndLight.Clear(); - btLampkaRearRightEndLight.Clear(); - // others - btLampkaMalfunction.Clear(); - btLampkaMalfunctionB.Clear(); - btLampkaMotorBlowers.Clear(); - btLampkaCoolingFans.Clear(); - btLampkaLouvresClosed.Clear(); - btLampkaTempomat.Clear(); - btLampkaDistanceCounter.Clear(); - - ggLeftLightButton.Clear(); - ggRightLightButton.Clear(); - ggUpperLightButton.Clear(); - ggDimHeadlightsButton.Clear(); - ggModernLightDimSw.Clear(); - ggLeftEndLightButton.Clear(); - ggRightEndLightButton.Clear(); - ggLightsButton.Clear(); - ggCompressorListButton.Clear(); - // hunter-230112 - ggRearLeftLightButton.Clear(); - ggRearRightLightButton.Clear(); - ggRearUpperLightButton.Clear(); - ggRearLeftEndLightButton.Clear(); - ggRearRightEndLightButton.Clear(); -} - -// NOTE: we can get rid of this function once we have per-cab persistent state -void TTrain::set_cab_controls(int const Cab) -{ - // switches - // battery - ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : mvOccupied->Power24vIsAvailable ? 1.f : 0.f); - // activation - ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : mvOccupied->IsCabMaster() ? 1.f : 0.f); - // line breaker - if (ggMainButton.SubModel != nullptr) - { // instead of single main button there can be on/off pair - ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate > 0 ? 1.f : 0.f); - } - // line breakers of the other vehicles in multiple - for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) - { - auto &mainswitch{m_remotelinebreakers[index].main_switch}; - if (mainswitch.SubModel == nullptr) - { - continue; - } - if (mainswitch.type() == TGaugeType::push) - { - mainswitch.PutValue(0.5f); - continue; - } - auto const *engine{remote_engine(index)}; - mainswitch.PutValue(engine != nullptr && engine_start::remote_switch::is_running(*engine) ? 1.f : 0.f); - } - - if (ggModernLightDimSw.SubModel != nullptr) - { - mvOccupied->modernDimmerPosition = mvOccupied->modernDimmerDefaultPosition; - ggModernLightDimSw.PutValue(static_cast(mvOccupied->modernDimmerDefaultPosition)); - } - - // Init separate buttons - if (ggPantValvesUpdate.SubModel != nullptr) - { - ggPantValvesUpdate.PutValue(0.f); - } - if (ggPantValvesOff.SubModel != nullptr) - { - ggPantValvesOff.PutValue(0.f); - } - - // motor connectors - ggStLinOffButton.PutValue(mvControlled->StLinSwitchOff ? 1.f : 0.f); - // radio - ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1) - 1)); - // pantographs - /* - if( mvOccupied->PantSwitchType != "impulse" ) { - if( ggPantFrontButton.SubModel ) { - ggPantFrontButton.PutValue( - ( mvControlled->Pantographs[end::front].valve.is_enabled ? - 1.f : - 0.f ) ); - } - if( ggPantFrontButtonOff.SubModel ) { - ggPantFrontButtonOff.PutValue( - ( mvControlled->Pantographs[end::front].valve.is_disabled ? - 1.f : - 0.f ) ); - } - } - if( mvOccupied->PantSwitchType != "impulse" ) { - if( ggPantRearButton.SubModel ) { - ggPantRearButton.PutValue( - ( mvControlled->Pantographs[end::rear].valve.is_enabled ? - 1.f : - 0.f ) ); - } - if( ggPantRearButtonOff.SubModel ) { - ggPantRearButtonOff.PutValue( - ( mvControlled->Pantographs[end::rear].valve.is_disabled ? - 1.f : - 0.f ) ); - } - } - */ - // front/end pantograph selection is relative to occupied cab - if (ggPantSelectedButton.type() == TGaugeType::toggle) - { - ggPantSelectedButton.PutValue(mvPantographUnit->PantsValve.is_enabled ? 1.f : 0.f); - } - else - { - if (false == m_controlmapper.contains("pantselectedoff_sw:")) - { - // single impulse switch arrangement, with neutral position mid-way - ggPantSelectedButton.PutValue(0.5f); - } - } - if (ggPantSelectedDownButton.type() == TGaugeType::toggle) - { - ggPantSelectedDownButton.PutValue(mvPantographUnit->PantsValve.is_disabled ? 1.f : 0.f); - } - - ggPantValvesButton.PutValue(0.5f); - - // auxiliary compressor - ggPantCompressorValve.PutValue(mvControlled->bPantKurek3 ? 0.f : // default setting is pantographs connected with primary tank - 1.f); - ggPantCompressorButton.PutValue(mvPantographUnit->PantCompFlag ? 1.f : 0.f); - // converter - if (mvOccupied->ConvSwitchType != "impulse") - { - ggConverterButton.PutValue(mvControlled->ConverterAllow ? 1.f : 0.f); - } - ggConverterLocalButton.PutValue(mvControlled->ConverterAllowLocal ? 1.f : 0.f); - // compressor - ggCompressorButton.PutValue(mvControlled->CompressorAllow ? 1.f : 0.f); - ggCompressorLocalButton.PutValue(mvControlled->CompressorAllowLocal ? 1.f : 0.f); - ggCompressorListButton.PutValue(static_cast(mvOccupied->CompressorListPos - 1)); - // motor overload relay threshold / shunt mode - ggMaxCurrentCtrl.PutValue(true == mvControlled->ShuntModeAllow ? (true == mvControlled->ShuntMode ? 1.f : 0.f) : mvControlled->MotorOverloadRelayHighThreshold ? 1.f : 0.f); - // lights - ggLightsButton.PutValue(static_cast(mvOccupied->LightsPos - 1)); - - auto const vehicleend{cab_to_end(Cab)}; - - if ((mvOccupied->iLights[vehicleend] & light::headlight_left) != 0) - { - ggLeftLightButton.PutValue(1.f); - } - if ((mvOccupied->iLights[vehicleend] & light::headlight_right) != 0) - { - ggRightLightButton.PutValue(1.f); - } - if ((mvOccupied->iLights[vehicleend] & light::headlight_upper) != 0) - { - ggUpperLightButton.PutValue(1.f); - } - if ((mvOccupied->iLights[vehicleend] & light::redmarker_left) != 0) - { - if (ggLeftEndLightButton.SubModel != nullptr) - { - ggLeftEndLightButton.PutValue(1.f); - } - else - { - ggLeftLightButton.PutValue(-1.f); - } - } - if ((mvOccupied->iLights[vehicleend] & light::redmarker_right) != 0) - { - if (ggRightEndLightButton.SubModel != nullptr) - { - ggRightEndLightButton.PutValue(1.f); - } - else - { - ggRightLightButton.PutValue(-1.f); - } - } - if (1 == DynamicObject->MoverParameters->modernDimmerPosition) - { - ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->MoverParameters->modernDimmerPosition)); - } - // cab lights - if (true == Cabine[Cab].bLightDim) - { - ggCabLightDimButton.PutValue(1.f); - } - // compartment lights - ggCompartmentLightsButton.PutValue(ggCompartmentLightsButton.type() == TGaugeType::push ? 0.5f : mvOccupied->CompartmentLights.is_enabled ? 1.f : 0.f); - // instrument lights - ggInstrumentLightButton.PutValue(InstrumentLightActive ? 1.f : 0.f); - ggDashboardLightButton.PutValue(DashboardLightActive ? 1.f : 0.f); - ggTimetableLightButton.PutValue(TimetableLightActive ? 1.f : 0.f); - // doors permits - if (false == ggDoorLeftPermitButton.is_push()) - { - ggDoorLeftPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].open_permit ? 1.f : 0.f); - } - if (false == ggDoorRightPermitButton.is_push()) - { - ggDoorRightPermitButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].open_permit ? 1.f : 0.f); - } - ggDoorPermitPresetButton.PutValue(static_cast(mvOccupied->Doors.permit_preset)); - // door controls - ggDoorLeftButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::left : side::right].is_closed ? 0.f : 1.f); - ggDoorRightButton.PutValue(mvOccupied->Doors.instances[cab_to_end() == end::front ? side::right : side::left].is_closed ? 0.f : 1.f); - // door lock - ggDoorSignallingButton.PutValue(mvOccupied->Doors.lock_enabled ? 1.f : 0.f); - // door step - if (false == ggDoorStepButton.is_push()) - { - ggDoorStepButton.PutValue(mvOccupied->Doors.step_enabled ? 1.f : 0.f); - } - // heating - if (false == ggTrainHeatingButton.is_push() && false == mvOccupied->HeatingSwitchImpulse) - { - ggTrainHeatingButton.PutValue(mvControlled->Heating ? 1.f : 0.f); - } - // brake acting time - if (ggBrakeProfileCtrl.SubModel != nullptr) - { - ggBrakeProfileCtrl.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 2.f : static_cast(mvOccupied->BrakeDelayFlag - 1)); - } - if (ggBrakeProfileG.SubModel != nullptr) - { - ggBrakeProfileG.PutValue(mvOccupied->BrakeDelayFlag == bdelay_G ? 1.f : 0.f); - } - if (ggBrakeProfileR.SubModel != nullptr) - { - ggBrakeProfileR.PutValue((mvOccupied->BrakeDelayFlag & bdelay_R) != 0 ? 1.f : 0.f); - } - - if (ggWiperSw.SubModel != nullptr) - { - ggWiperSw.PutValue(static_cast(mvOccupied->wiperSwitchPos)); - } - - if (ggBrakeOperationModeCtrl.SubModel != nullptr) - { - ggBrakeOperationModeCtrl.PutValue(mvOccupied->BrakeOpModeFlag > 0 ? static_cast(std::log2(mvOccupied->BrakeOpModeFlag)) : 0); - } - // alarm chain - ggAlarmChain.PutValue(mvControlled->AlarmChainFlag ? 1.f : 0.f); - // brake signalling - ggSignallingButton.PutValue(mvControlled->Signalling ? 1.f : 0.f); - // multiple-unit current indicator source - ggNextCurrentButton.PutValue(ShowNextCurrent ? 1.f : 0.f); - // water pump - ggWaterPumpBreakerButton.PutValue(mvControlled->WaterPump.breaker ? 1.f : 0.f); - if (ggWaterPumpButton.type() != TGaugeType::push) - { - ggWaterPumpButton.PutValue(mvControlled->WaterPump.is_enabled ? 1.f : 0.f); - } - // water heater - ggWaterHeaterBreakerButton.PutValue(mvControlled->WaterHeater.breaker ? 1.f : 0.f); - ggWaterHeaterButton.PutValue(mvControlled->WaterHeater.is_enabled ? 1.f : 0.f); - ggWaterCircuitsLinkButton.PutValue(mvControlled->WaterCircuitsLink ? 1.f : 0.f); - // fuel pump - if (ggFuelPumpButton.type() != TGaugeType::push) - { - ggFuelPumpButton.PutValue(mvControlled->FuelPump.is_enabled ? 1.f : 0.f); - } - // oil pump - if (ggOilPumpButton.type() != TGaugeType::push) - { - ggOilPumpButton.PutValue(mvControlled->OilPump.is_enabled ? 1.f : 0.f); - } - // joint oil and fuel pump - if (ggOilFuelPumpButton.type() != TGaugeType::push) - { - ggOilFuelPumpButton.PutValue(mvControlled->OilFuelPumpsEnabled() ? 1.f : 0.f); - } - // traction motor fans - if (ggMotorBlowersFrontButton.type() != TGaugeType::push) - { - ggMotorBlowersFrontButton.PutValue(mvControlled->MotorBlowers[end::front].is_enabled ? 1.f : 0.f); - } - if (ggMotorBlowersRearButton.type() != TGaugeType::push) - { - ggMotorBlowersRearButton.PutValue(mvControlled->MotorBlowers[end::rear].is_enabled ? 1.f : 0.f); - } - if (ggMotorBlowersAllOffButton.type() != TGaugeType::push) - { - ggMotorBlowersAllOffButton.PutValue(mvControlled->MotorBlowers[end::front].is_disabled || mvControlled->MotorBlowers[end::rear].is_disabled ? 1.f : 0.f); - } - // second controller - if (ggScndCtrl.is_push()) - { - ggScndCtrl.PutValue(ggScndCtrl.is_toggle() ? 0.5f : // pushtoggle is two-way control with neutral position in the middle - 0.f); // push is on/off control, active while held down, due to legacy use - } - // tempomat - if (false == ggScndCtrlButton.is_push()) - { - ggScndCtrlButton.PutValue(mvControlled->ScndCtrlPos > 0 ? 1.f : 0.f); - } - // sandbox - if (ggAutoSandButton.type() != TGaugeType::push) - { - ggAutoSandButton.PutValue(mvControlled->SandDoseAutoAllow ? 1.f : 0.f); - } - // radio - ggRadioVolumeSelector.PutValue(m_radiovolume); - - // finding each inverter - not so optimal, but action ins performed only during changing cabin - bool kier = DynamicObject->DirectionGet() * mvOccupied->CabOccupied > 0; - int flag = DynamicObject->MoverParameters->InverterControlCouplerFlag; - int itemstart = 0; - for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button - { - int itemindex = itemstart; - itemstart++; - TDynamicObject *p = DynamicObject->GetFirstDynamic(mvOccupied->CabOccupied < 0 ? end::rear : end::front, flag); - while (p) - { - if (p->MoverParameters->eimc[eimc_p_Pmax] > 1) - { - if (itemindex < p->MoverParameters->InvertersNo) - { - // visual feedback - ggInverterToggleButtons[itemstart - 1].PutValue(p->MoverParameters->Inverters[itemindex].Activate ? 1.0 : 0.0); - break; - } - else - { - itemindex -= p->MoverParameters->InvertersNo; - } - } - p = kier ? p->Next(flag) : p->Prev(flag); - } - } - - // we reset all indicators, as they're set during the update pass - // TODO: when cleaning up break setting indicator state into a separate function, so we can reuse it -} - -// initializes a button matching provided label. returns: true if the label was found, false otherwise -// TODO: refactor the cabin controls into some sensible structure -bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int const Cabindex) -{ - - std::unordered_map const lights = { - {"i-maxft:", btLampkaMaxSila}, - {"i-maxftt:", btLampkaPrzekrMaxSila}, - {"i-radio:", btLampkaRadio}, - {"i-radiomessage:", btLampkaRadioMessage}, - {"i-radiostop:", btLampkaRadioStop}, - {"i-manual_brake:", btLampkaHamulecReczny}, - {"i-door_blocked:", btLampkaBlokadaDrzwi}, - {"i-door_blockedoff:", btLampkaDoorLockOff}, - {"i-slippery:", btLampkaPoslizg}, - {"i-contactors:", btLampkaStyczn}, - {"i-conv_ovld:", btLampkaNadmPrzetw}, - {"i-converter:", btLampkaPrzetw}, - {"i-converteroff:", btLampkaPrzetwOff}, - {"i-converteraoff:", btLampkaPrzetwAOff}, - {"i-converterb:", btLampkaPrzetwB}, - {"i-converterboff:", btLampkaPrzetwBOff}, - {"i-diff_relay:", btLampkaPrzekRozn}, - {"i-diff_relay2:", btLampkaPrzekRoznPom}, - {"i-motor_ovld:", btLampkaNadmSil}, - {"i-train_controll:", btLampkaUkrotnienie}, - {"i-brake_delay_r:", btLampkaHamPosp}, - {"i-mainbreaker:", btLampkaWylSzybki}, - {"i-mainbreakerb:", btLampkaWylSzybkiB}, - {"i-mainbreakeroff:", btLampkaWylSzybkiOff}, - {"i-mainbreakerboff:", btLampkaWylSzybkiBOff}, - {"i-mainbreakerready:", btLampkaMainBreakerReady}, - {"i-mainbreakerblinking:", btLampkaMainBreakerBlinkingIfReady}, - {"i-vent_ovld:", btLampkaNadmWent}, - {"i-comp_ovld:", btLampkaNadmSpr}, - // overheat indicator lamps - {"i-oil_overheat:", btLampkaOilOverheat}, - {"i-water_overheat:", btLampkaWaterOverheat}, - {"i-wateraux_overheat:", btLampkaWaterAuxOverheat}, - {"i-engine_overheat:", btLampkaEngineOverheat}, - {"i-resistors:", btLampkaOpory}, - {"i-no_resistors:", btLampkaBezoporowa}, - {"i-no_resistors_b:", btLampkaBezoporowaB}, - {"i-highcurrent:", btLampkaWysRozr}, - {"i-vent_trim:", btLampkaWentZaluzje}, - {"i-motorblowers:", btLampkaMotorBlowers}, - {"i-coolingfans:", btLampkaCoolingFans}, - {"i-louvresclosed:", btLampkaLouvresClosed}, - {"i-tempomat:", btLampkaTempomat}, - {"i-distancecounter:", btLampkaDistanceCounter}, - {"i-trainheating:", btLampkaOgrzewanieSkladu}, - {"i-security_aware:", btLampkaCzuwaka}, - {"i-security_cabsignal:", btLampkaSHP}, - {"i-security_aware_cabsignal:", btLampkaCzuwakaSHP}, - {"i-door_left:", btLampkaDoorLeft}, - {"i-door_right:", btLampkaDoorRight}, - {"i-departure_signal:", btLampkaDepartureSignal}, - {"i-reserve:", btLampkaRezerwa}, - {"i-scnd:", btLampkaBoczniki}, - {"i-scnd1:", btLampkaBocznik1}, - {"i-scnd2:", btLampkaBocznik2}, - {"i-scnd3:", btLampkaBocznik3}, - {"i-scnd4:", btLampkaBocznik4}, - {"i-gear1:", btLampkaGear1}, - {"i-gear2:", btLampkaGear2}, - {"i-hydrolockup:", btLampkaHydroLockup}, - {"i-braking:", btLampkaHamienie}, - {"i-brakingoff:", btLampkaBrakingOff}, - {"i-dynamicbrake:", btLampkaED}, - {"i-brakeprofileg:", btLampkaBrakeProfileG}, - {"i-brakeprofilep:", btLampkaBrakeProfileP}, - {"i-brakeprofiler:", btLampkaBrakeProfileR}, - {"i-springbrakeactive:", btLampkaSpringBrakeActive}, - {"i-springbrakeinactive:", btLampkaSpringBrakeInactive}, - {"i-braking-ezt:", btLampkaHamowanie1zes}, - {"i-braking-ezt2:", btLampkaHamowanie2zes}, - {"i-compressor:", btLampkaSprezarka}, - {"i-compressorb:", btLampkaSprezarkaB}, - {"i-compressoroff:", btLampkaSprezarkaOff}, - {"i-compressorboff:", btLampkaSprezarkaBOff}, - {"i-fuelpumpoff:", btLampkaFuelPumpOff}, - {"i-oilpump:", btLampkaOilPump}, - {"i-voltbrake:", btLampkaNapNastHam}, - {"i-resistorsb:", btLampkaOporyB}, - {"i-contactorsb:", btLampkaStycznB}, - {"i-conv_ovldb:", btLampkaNadmPrzetwB}, - {"i-hvoltageb:", btLampkaHVoltageB}, - {"i-malfunction:", btLampkaMalfunction}, - {"i-malfunctionb:", btLampkaMalfunctionB}, - {"i-forward:", btLampkaForward}, - {"i-backward:", btLampkaBackward}, - {"i-neutral:", btLampkaNeutral}, - {"i-upperlight:", btLampkaUpperLight}, - {"i-leftlight:", btLampkaLeftLight}, - {"i-rightlight:", btLampkaRightLight}, - {"i-leftend:", btLampkaLeftEndLight}, - {"i-rightend:", btLampkaRightEndLight}, - {"i-rearupperlight:", btLampkaRearUpperLight}, - {"i-rearleftlight:", btLampkaRearLeftLight}, - {"i-rearrightlight:", btLampkaRearRightLight}, - {"i-rearleftend:", btLampkaRearLeftEndLight}, - {"i-rearrightend:", btLampkaRearRightEndLight}, - {"i-dashboardlight:", btDashboardLight}, - {"i-timetablelight:", btTimetableLight}, - {"i-universal0:", btUniversals[0]}, - {"i-universal1:", btUniversals[1]}, - {"i-universal2:", btUniversals[2]}, - {"i-universal3:", btUniversals[3]}, - {"i-universal4:", btUniversals[4]}, - {"i-universal5:", btUniversals[5]}, - {"i-universal6:", btUniversals[6]}, - {"i-universal7:", btUniversals[7]}, - {"i-universal8:", btUniversals[8]}, - {"i-universal9:", btUniversals[9]}, - {"i-cabactived:", btCabActived}, - {"i-aklvents:", btAKLVents}, - {"i-compressorany:", btCompressors}, - {"i-edenabled", btEDenabled}, - }; - { - auto lookup = lights.find(Label); - if (lookup != lights.end()) - { - lookup->second.Load(Parser, DynamicObject); - return true; - } - } - // TODO: move viable dedicated lights to the automatic light array - std::unordered_map const autolights = { - {"i-doors:", &m_doors}, - {"i-doorpermit_left:", &m_doorspermitleft}, - {"i-doorpermit_right:", &m_doorspermitright}, - {"i-doorpermit_any:", &m_doorpermits}, - {"i-doorstep:", &mvOccupied->Doors.step_enabled}, - {"i-mainpipelock:", &mvOccupied->LockPipe}, - {"i-battery:", &mvOccupied->Power24vIsAvailable}, - {"i-cablight:", &Cabine[iCabn].bLight}, - }; - { - auto lookup = autolights.find(Label); - if (lookup != autolights.end()) - { - auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka - button.Load(Parser, DynamicObject); - button.AssignBool(lookup->second); - return true; - } - } - // custom lights - if (Label == "i-instrumentlight:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 0; - } - else if (Label == "i-instrumentlight_m:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 1; - } - else if (Label == "i-instrumentlight_c:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 2; - } - else if (Label == "i-instrumentlight_a:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 3; - } - else if (Label == "i-instrumentlight_l:") - { - btInstrumentLight.Load(Parser, DynamicObject); - InstrumentLightType = 4; - } - else if (Label == "i-doors:") - { - int i = Parser.getToken() - 1; - auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka - button.Load(Parser, DynamicObject); - button.AssignBool(bDoors[0] + 3 * i); - } - else - { - // failed to match the label - return false; - } - - return true; -} - -// initializes a gauge matching provided label. returns: true if the label was found, false otherwise -// TODO: refactor the cabin controls into some sensible structure -bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int const Cabindex) -{ - - std::unordered_map const gauges = {{"jointctrl:", ggJointCtrl}, - {"mainctrl:", ggMainCtrl}, - {"scndctrl:", ggScndCtrl}, - {"dirkey:", ggDirKey}, - {"brakectrl:", ggBrakeCtrl}, - {"localbrake:", ggLocalBrake}, - {"alarmchain:", ggAlarmChain}, - {"brakeprofile_sw:", ggBrakeProfileCtrl}, - {"brakeprofileg_sw:", ggBrakeProfileG}, - {"brakeprofiler_sw:", ggBrakeProfileR}, - {"brakeopmode_sw:", ggBrakeOperationModeCtrl}, - {"maxcurrent_sw:", ggMaxCurrentCtrl}, - {"main_off_bt:", ggMainOffButton}, - {"main_on_bt:", ggMainOnButton}, - {"mainb_sw:", m_remotelinebreakers[0].main_switch}, - {"mainb_off_bt:", m_remotelinebreakers[0].off_button}, - {"mainb_on_bt:", m_remotelinebreakers[0].on_button}, - {"mainc_sw:", m_remotelinebreakers[1].main_switch}, - {"mainc_off_bt:", m_remotelinebreakers[1].off_button}, - {"mainc_on_bt:", m_remotelinebreakers[1].on_button}, - {"security_reset_bt:", ggSecurityResetButton}, - {"shp_reset_bt:", ggSHPResetButton}, - {"releaser_bt:", ggReleaserButton}, - {"springbrakeon_bt:", ggSpringBrakeOnButton}, - {"springbrakeoff_bt:", ggSpringBrakeOffButton}, - {"universalbrake1_bt:", ggUniveralBrakeButton1}, - {"universalbrake2_bt:", ggUniveralBrakeButton2}, - {"universalbrake3_bt:", ggUniveralBrakeButton3}, - {"epbrake_bt:", ggEPFuseButton}, - {"sand_bt:", ggSandButton}, - {"autosandallow_sw:", ggAutoSandButton}, - {"antislip_bt:", ggAntiSlipButton}, - {"horn_bt:", ggHornButton}, - {"hornlow_bt:", ggHornLowButton}, - {"hornhigh_bt:", ggHornHighButton}, - {"whistle_bt:", ggWhistleButton}, - {"helper_bt:", ggHelperButton}, - {"fuse_bt:", ggFuseButton}, - {"converterfuse_bt:", ggConverterFuseButton}, - {"stlinoff_bt:", ggStLinOffButton}, - {"doorpermitpreset_sw:", ggDoorPermitPresetButton}, - {"door_left_sw:", ggDoorLeftButton}, - {"door_right_sw:", ggDoorRightButton}, - {"doorlefton_sw:", ggDoorLeftOnButton}, - {"doorrighton_sw:", ggDoorRightOnButton}, - {"doorleftoff_sw:", ggDoorLeftOffButton}, - {"doorrightoff_sw:", ggDoorRightOffButton}, - {"doorallon_sw:", ggDoorAllOnButton}, - {"departure_signal_bt:", ggDepartureSignalButton}, - {"upperlight_sw:", ggUpperLightButton}, - {"leftlight_sw:", ggLeftLightButton}, - {"rightlight_sw:", ggRightLightButton}, - {"dimheadlights_sw:", ggDimHeadlightsButton}, - {"leftend_sw:", ggLeftEndLightButton}, - {"rightend_sw:", ggRightEndLightButton}, - {"lights_sw:", ggLightsButton}, - {"moderndimmer_sw:", ggModernLightDimSw}, - {"rearupperlight_sw:", ggRearUpperLightButton}, - {"rearleftlight_sw:", ggRearLeftLightButton}, - {"rearrightlight_sw:", ggRearRightLightButton}, - {"rearleftend_sw:", ggRearLeftEndLightButton}, - {"rearrightend_sw:", ggRearRightEndLightButton}, - {"compressor_sw:", ggCompressorButton}, - {"compressorlocal_sw:", ggCompressorLocalButton}, - {"compressorlist_sw:", ggCompressorListButton}, - {"converter_sw:", ggConverterButton}, - {"converterlocal_sw:", ggConverterLocalButton}, - {"converteroff_sw:", ggConverterOffButton}, - {"main_sw:", ggMainButton}, - {"waterpumpbreaker_sw:", ggWaterPumpBreakerButton}, - {"waterpump_sw:", ggWaterPumpButton}, - {"waterheaterbreaker_sw:", ggWaterHeaterBreakerButton}, - {"waterheater_sw:", ggWaterHeaterButton}, - {"water1tempb:", ggWater1TempB}, - {"watercircuitslink_sw:", ggWaterCircuitsLinkButton}, - {"fuelpump_sw:", ggFuelPumpButton}, - {"oilpump_sw:", ggOilPumpButton}, - {"oilfuelpump_sw:", ggOilFuelPumpButton}, - {"oilpressb:", ggOilPressB}, - {"motorblowersfront_sw:", ggMotorBlowersFrontButton}, - {"motorblowersrear_sw:", ggMotorBlowersRearButton}, - {"motorblowersalloff_sw:", ggMotorBlowersAllOffButton}, - {"radiochannel_sw:", ggRadioChannelSelector}, - {"radiochannelprev_sw:", ggRadioChannelPrevious}, - {"radiochannelnext_sw:", ggRadioChannelNext}, - {"radiostop_sw:", ggRadioStop}, - {"radiotest_sw:", ggRadioTest}, - {"radiocall1_sw:", ggRadioCall1}, - {"radiocall3_sw:", ggRadioCall3}, - {"radiovolume_sw:", ggRadioVolumeSelector}, - {"radiovolumeprev_sw:", ggRadioVolumePrevious}, - {"radiovolumenext_sw:", ggRadioVolumeNext}, - {"radioon_sw:", ggRadioOnButton}, - {"radiooff_sw:", ggRadioOffButton}, - {"radiofuseon_sw:", ggRadioFuseOnButton}, - {"radiofuseoff_sw:", ggRadioFuseOffButton}, - /* - { "pantfront_sw:", ggPantFrontButton }, - { "pantrear_sw:", ggPantRearButton }, - { "pantfrontoff_sw:", ggPantFrontButtonOff }, - { "pantrearoff_sw:", ggPantRearButtonOff }, - */ - {"pantalloff_sw:", ggPantAllDownButton}, - {"pantselected_sw:", ggPantSelectedButton}, - {"pantselectedoff_sw:", ggPantSelectedDownButton}, - {"pantvalves_sw:", ggPantValvesButton}, - {"pantcompressor_sw:", ggPantCompressorButton}, - {"pantcompressorvalve_sw:", ggPantCompressorValve}, - {"trainheating_sw:", ggTrainHeatingButton}, - {"signalling_sw:", ggSignallingButton}, - {"door_signalling_sw:", ggDoorSignallingButton}, - {"nextcurrent_sw:", ggNextCurrentButton}, - {"instrumentlight_sw:", ggInstrumentLightButton}, - {"dashboardlight_sw:", ggDashboardLightButton}, - {"timetablelight_sw:", ggTimetableLightButton}, - {"cablightdim_sw:", ggCabLightDimButton}, - {"compartmentlights_sw:", ggCompartmentLightsButton}, - {"compartmentlightson_sw:", ggCompartmentLightsOnButton}, - {"compartmentlightsoff_sw:", ggCompartmentLightsOffButton}, - {"battery_sw:", ggBatteryButton}, - {"batteryon_sw:", ggBatteryOnButton}, - {"batteryoff_sw:", ggBatteryOffButton}, - {"cabactivation_sw:", ggCabActivationButton}, - {"distancecounter_sw:", ggDistanceCounterButton}, - {"relayreset1_bt:", ggRelayResetButtons[0]}, - {"relayreset2_bt:", ggRelayResetButtons[1]}, - {"relayreset3_bt:", ggRelayResetButtons[2]}, - {"universal0:", ggUniversals[0]}, - {"universal1:", ggUniversals[1]}, - {"universal2:", ggUniversals[2]}, - {"universal3:", ggUniversals[3]}, - {"universal4:", ggUniversals[4]}, - {"universal5:", ggUniversals[5]}, - {"universal6:", ggUniversals[6]}, - {"universal7:", ggUniversals[7]}, - {"universal8:", ggUniversals[8]}, - {"universal9:", ggUniversals[9]}, - {"universal10:", ggUniversals[10]}, - {"universal11:", ggUniversals[11]}, - {"universal12:", ggUniversals[12]}, - {"universal13:", ggUniversals[13]}, - {"universal14:", ggUniversals[14]}, - {"universal15:", ggUniversals[15]}, - {"universal16:", ggUniversals[16]}, - {"universal17:", ggUniversals[17]}, - {"universal18:", ggUniversals[18]}, - {"universal19:", ggUniversals[19]}, - {"universal20:", ggUniversals[20]}, - {"universal21:", ggUniversals[21]}, - {"universal22:", ggUniversals[22]}, - {"universal23:", ggUniversals[23]}, - {"universal24:", ggUniversals[24]}, - {"universal25:", ggUniversals[25]}, - {"universal26:", ggUniversals[26]}, - {"universal27:", ggUniversals[27]}, - {"universal28:", ggUniversals[28]}, - {"universal29:", ggUniversals[29]}, - {"inverterenable1_bt:", ggInverterEnableButtons[0]}, - {"inverterenable2_bt:", ggInverterEnableButtons[1]}, - {"inverterenable3_bt:", ggInverterEnableButtons[2]}, - {"inverterenable4_bt:", ggInverterEnableButtons[3]}, - {"inverterenable5_bt:", ggInverterEnableButtons[4]}, - {"inverterenable6_bt:", ggInverterEnableButtons[5]}, - {"inverterenable7_bt:", ggInverterEnableButtons[6]}, - {"inverterenable8_bt:", ggInverterEnableButtons[7]}, - {"inverterenable9_bt:", ggInverterEnableButtons[8]}, - {"inverterenable10_bt:", ggInverterEnableButtons[9]}, - {"inverterenable11_bt:", ggInverterEnableButtons[10]}, - {"inverterenable12_bt:", ggInverterEnableButtons[11]}, - {"inverterdisable1_bt:", ggInverterDisableButtons[0]}, - {"inverterdisable2_bt:", ggInverterDisableButtons[1]}, - {"inverterdisable3_bt:", ggInverterDisableButtons[2]}, - {"inverterdisable4_bt:", ggInverterDisableButtons[3]}, - {"inverterdisable5_bt:", ggInverterDisableButtons[4]}, - {"inverterdisable6_bt:", ggInverterDisableButtons[5]}, - {"inverterdisable7_bt:", ggInverterDisableButtons[6]}, - {"inverterdisable8_bt:", ggInverterDisableButtons[7]}, - {"inverterdisable9_bt:", ggInverterDisableButtons[8]}, - {"inverterdisable10_bt:", ggInverterDisableButtons[9]}, - {"inverterdisable11_bt:", ggInverterDisableButtons[10]}, - {"inverterdisable12_bt:", ggInverterDisableButtons[11]}, - {"invertertoggle1_bt:", ggInverterToggleButtons[0]}, - {"invertertoggle2_bt:", ggInverterToggleButtons[1]}, - {"invertertoggle3_bt:", ggInverterToggleButtons[2]}, - {"invertertoggle4_bt:", ggInverterToggleButtons[3]}, - {"invertertoggle5_bt:", ggInverterToggleButtons[4]}, - {"invertertoggle6_bt:", ggInverterToggleButtons[5]}, - {"invertertoggle7_bt:", ggInverterToggleButtons[6]}, - {"invertertoggle8_bt:", ggInverterToggleButtons[7]}, - {"invertertoggle9_bt:", ggInverterToggleButtons[8]}, - {"invertertoggle10_bt:", ggInverterToggleButtons[9]}, - {"invertertoggle11_bt:", ggInverterToggleButtons[10]}, - {"invertertoggle12_bt:", ggInverterToggleButtons[11]}, - {"pantvalvesupdate_bt:", ggPantValvesUpdate}, - {"pantvalvesoff_bt:", ggPantValvesOff}, - {"wipers_sw:", ggWiperSw}}; - { - auto const lookup{gauges.find(Label)}; - if (lookup != gauges.end()) - { - lookup->second.Load(Parser, DynamicObject); - m_controlmapper.insert(lookup->second, lookup->first); - return true; - } - } - // dedicated gauges with state-driven optional submodel - // TODO: move viable gauges here - // TODO: convert dedicated gauges to auto-allocated ones, replace dedicated references in command handlers to mapper lookups - std::unordered_map> const stategauges = { - {"tempomat_sw:", {ggScndCtrlButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"tempomatoff_sw:", {ggScndCtrlOffButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedinc_bt:", {ggSpeedControlIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speeddec_bt:", {ggSpeedControlDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedctrlpowerinc_bt:", {ggSpeedControlPowerIncreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedctrlpowerdec_bt:", {ggSpeedControlPowerDecreaseButton, &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton0:", {ggSpeedCtrlButtons[0], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton1:", {ggSpeedCtrlButtons[1], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton2:", {ggSpeedCtrlButtons[2], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton3:", {ggSpeedCtrlButtons[3], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton4:", {ggSpeedCtrlButtons[4], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton5:", {ggSpeedCtrlButtons[5], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton6:", {ggSpeedCtrlButtons[6], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton7:", {ggSpeedCtrlButtons[7], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton8:", {ggSpeedCtrlButtons[8], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"speedbutton9:", {ggSpeedCtrlButtons[9], &mvOccupied->SpeedCtrlUnit.IsActive}}, - {"doorleftpermit_sw:", {ggDoorLeftPermitButton, &m_doorspermitleft}}, - {"doorrightpermit_sw:", {ggDoorRightPermitButton, &m_doorspermitright}}, - {"dooralloff_sw:", {ggDoorAllOffButton, &m_doors}}, - {"doorstep_sw:", {ggDoorStepButton, &mvOccupied->Doors.step_enabled}}, - {"dirforward_bt:", {ggDirForwardButton, &m_dirforward}}, - {"dirneutral_bt:", {ggDirNeutralButton, &m_dirneutral}}, - {"dirbackward_bt:", {ggDirBackwardButton, &m_dirbackward}}, - }; - { - auto const lookup{stategauges.find(Label)}; - if (lookup != stategauges.end()) - { - auto &gauge{std::get(lookup->second)}; - gauge.Load(Parser, DynamicObject); - gauge.AssignState(std::get(lookup->second)); - m_controlmapper.insert(gauge, lookup->first); - return true; - } - } - // TODO: move viable dedicated gauges to the automatic array - std::unordered_map const autoboolgauges = { - {"doormode_sw:", &mvOccupied->Doors.remote_only}, - {"coolingfans_sw:", &mvControlled->RVentForceOn}, - {"pantfront_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_enabled}, - {"pantrear_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_enabled}, - {"pantfrontoff_sw:", &mvPantographUnit->Pantographs[end::front].valve.is_disabled}, - {"pantrearoff_sw:", &mvPantographUnit->Pantographs[end::rear].valve.is_disabled}, - {"radio_sw:", &mvOccupied->Radio}, - {"radiofuse_sw:", &mvOccupied->RadioFuse}, - {"cablight_sw:", &Cabine[iCabn].bLight}, - {"springbraketoggle_bt:", &mvOccupied->SpringBrake.Activate}, - {"couplingdisconnect_sw:", &m_couplingdisconnect}, - {"couplingdisconnectback_sw:", &m_couplingdisconnectback}, - {"mirrors_sw:", &mvOccupied->MirrorForbidden}, - }; - { - auto lookup = autoboolgauges.find(Label); - if (lookup != autoboolgauges.end()) - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka - gauge.Load(Parser, DynamicObject); - gauge.AssignBool(lookup->second); - m_controlmapper.insert(gauge, lookup->first); - return true; - } - } - // TODO: move viable dedicated gauges to the automatic array - std::unordered_map const autointgauges = { - {"manualbrake:", &mvOccupied->ManualBrakePos}, - {"pantselect_sw:", &mvOccupied->PantsPreset.second[cab_to_end()]}, - }; - { - auto lookup = autointgauges.find(Label); - if (lookup != autointgauges.end()) - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka - gauge.Load(Parser, DynamicObject); - gauge.AssignInt(lookup->second); - m_controlmapper.insert(gauge, lookup->first); - return true; - } - } - - // broadcast radio receiver - if (Label == "fmradio_sw:" || Label == "fmradiovolume_sw:" || Label == "fmradiotune_sw:" || Label == "fmradioscale:") - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - if (Label == "fmradio_sw:") - { - gauge.AssignBool(&m_fmradiopower); - } - else - { - gauge.AssignFloat(Label == "fmradiovolume_sw:" ? &m_fmradiovolume : &m_fmradiodial); - } - if (Label != "fmradioscale:") - { - // the scale pointer is an indicator, the rest are controls - m_controlmapper.insert(gauge, Label); - } - m_fmradiopresent = true; - // unless the speaker location is defined explicitly, the sound comes from the first defined element of the receiver - if (m_fmradiosound.offset() == glm::vec3()) - { - m_fmradiosound.offset(gauge.model_offset()); - } - return true; - } - - // ABu 090305: uniwersalne przyciski lub inne rzeczy - if (Label == "mainctrlact:") - { - ggMainCtrlAct.Load(Parser, DynamicObject); - } - // SEKCJA WSKAZNIKOW - else if (Label == "tachometer:" || Label == "tachometerb:") - { - // predkosciomierz wskaźnikowy z szarpaniem - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fTachoVelocityJump); - // bind tachometer sound location to the meter - if (dsbHasler && dsbHasler->offset() == glm::vec3()) - { - dsbHasler->offset(gauge.model_offset()); - } - } - else if (Label == "tachometern:") - { - // predkosciomierz wskaźnikowy bez szarpania - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fTachoVelocity); - // bind tachometer sound location to the meter - if (dsbHasler && dsbHasler->offset() == glm::vec3()) - { - dsbHasler->offset(gauge.model_offset()); - } - } - else if (Label == "tachometerd:") - { - // predkosciomierz cyfrowy - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fTachoVelocity); - // bind tachometer sound location to the meter - if (dsbHasler && dsbHasler->offset() == glm::vec3()) - { - dsbHasler->offset(gauge.model_offset()); - } - } - else if (Label == "hvcurrent1:" || Label == "hvcurrent1b:") - { - // 1szy amperomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent + 1); - } - else if (Label == "hvcurrent2:" || Label == "hvcurrent2b:") - { - // 2gi amperomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent + 2); - } - else if (Label == "hvcurrent3:" || Label == "hvcurrent3b:") - { - // 3ci amperomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałska - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent + 3); - } - else if (Label == "hvcurrent:" || Label == "hvcurrentb:") - { - // amperomierz calkowitego pradu - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fHCurrent); - } - else if (Label == "eimscreen:") - { - // amperomierz calkowitego pradu - int i; - int j; - Parser.getTokens(2, false); - Parser >> i >> j; - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fEIMParams[i][j]); - } - else if (Label == "brakes:") - { - // specified pipe pressure of specified consist vehicle - int i; - int j; - Parser.getTokens(2, false); - Parser >> i >> j; - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignFloat(&fPress[std::clamp(i, 1, 20) - 1][std::clamp(j, 0, 3)]); - } - else if (Label == "brakepress:" || Label == "brakepressb:") - { - // manometr cylindrow hamulcowych - // Ra 2014-08: przeniesione do TCab - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->BrakePress); - } - else if (Label == "pipepress:" || Label == "pipepressb:") - { - // manometr przewodu hamulcowego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->PipePress); - } - else if (Label == "scndpress:") - { - // manometr przewodu hamulcowego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->ScndPipePress); - } - else if (Label == "limpipepress:") - { - // manometr zbiornika sterujacego zaworu maszynisty - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&m_brakehandlecp); - } - else if (Label == "cntrlpress:") - { - // manometr zbiornika kontrolnego/rorzďż˝du - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvPantographUnit->PantPress); - } - else if (Label == "springbrakepress:") - { - // manometr cylindra hamulca sprężynowego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->SpringBrake.SBP); - } - else if (Label == "epctrlvalue:") - { - // wskazowka sterowania sila hamulca ep - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->EpForce); - } - else if (Label == "compressor:" || Label == "compressorb:") - { - // manometr sprezarki/zbiornika glownego - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvOccupied->Compressor); - } - else if (Label == "oilpress:") - { - // oil pressure - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->OilPump.pressure); - } - else if (Label == "oiltemp:") - { - // oil temperature - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.To); - } - else if (Label == "water1temp:") - { - // main circuit water temperature - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.temperatura1); - } - else if (Label == "water2temp:") - { - // auxiliary circuit water temperature - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&mvControlled->dizel_heat.temperatura2); - } - else if (Label == "pantpress:") - { - // pantograph tank pressure - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject, 0.1); - gauge.AssignDouble(&mvPantographUnit->PantPress); - } - // yB - dla drugiej sekcji - else if (Label == "hvbcurrent1:") - { - // 1szy amperomierz - ggI1B.Load(Parser, DynamicObject); - } - else if (Label == "hvbcurrent2:") - { - // 2gi amperomierz - ggI2B.Load(Parser, DynamicObject); - } - else if (Label == "hvbcurrent3:") - { - // 3ci amperomierz - ggI3B.Load(Parser, DynamicObject); - } - else if (Label == "hvbcurrent:") - { - // amperomierz calkowitego pradu - ggItotalB.Load(Parser, DynamicObject); - } - //************************************************************* - else if (Label == "clock:") - { - // zegar analogowy - if (Parser.getToken() == "analog" && DynamicObject->mdKabina) - { - // McZapkie-300302: zegarek - ggClockSInd.Init(DynamicObject->mdKabina->GetFromName("ClockShand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); - ggClockMInd.Init(DynamicObject->mdKabina->GetFromName("ClockMhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); - ggClockHInd.Init(DynamicObject->mdKabina->GetFromName("ClockHhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 12.0)); - } - } - else if (Label == "clock_seconds:") - { - ggClockSInd.Load(Parser, DynamicObject); - } - else if (Label == "evoltage:") - { - // woltomierz napiecia silnikow - ggEngineVoltage.Load(Parser, DynamicObject); - } - else if (Label == "hvoltage:") - { - // woltomierz wysokiego napiecia - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(&fHVoltage); - } - else if (Label == "lvoltage:") - { - // woltomierz niskiego napiecia - ggLVoltage.Load(Parser, DynamicObject); - } - else if (Label == "enrot1m:") - { - // obrotomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fEngine + 1); - } // ggEnrot1m.Load(Parser,DynamicObject->mdKabina); - else if (Label == "enrot2m:") - { - // obrotomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fEngine + 2); - } // ggEnrot2m.Load(Parser,DynamicObject->mdKabina); - else if (Label == "enrot3m:") - { // obrotomierz - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignFloat(fEngine + 3); - } // ggEnrot3m.Load(Parser,DynamicObject->mdKabina); - else if (Label == "engageratio:") - { - // np. ciśnienie sterownika sprzęgła - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->dizel_engage); - } // ggEngageRatio.Load(Parser,DynamicObject->mdKabina); - else if (Label == "maingearstatus:") - { - // np. ciśnienie sterownika skrzyni biegów - ggMainGearStatus.Load(Parser, DynamicObject); - } - else if (Label == "ignitionkey:") - { - ggIgnitionKey.Load(Parser, DynamicObject); - } - else if (Label == "distcounter:") - { - // Ra 2014-07: licznik kilometrów - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - // the counter shows the odometer of the vehicle, kept between the sessions (eu07/maszyna#72). its offset - // was the state it started each session with, now it is that only for a vehicle with no known state - if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}; seed.has_value()) - mvControlled->Odometer.seed(*seed); - gauge.offset(0.f); - gauge.AssignDouble(&mvControlled->Odometer.km); - // the vehicle the counter counts for is one the odometer store keeps, also in the sessions the counter seeds - // nothing (its state is a saved one by then) and when it's the motor car of the unit the cab is in - mvControlled->Odometer.shown = true; - } - else if (Label == "shuntmodepower:") - { - // shunt mode power slider - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->AnPos); - m_controlmapper.insert(gauge, "shuntmodepower:"); - } - else if (Label == "heatingvoltage:") - { - if (mvControlled->HeatingPowerSource.SourceType == TPowerSource::Generator) - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->HeatingPowerSource.EngineGenerator.voltage); - } - } - else if (Label == "heatingcurrent:") - { - auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka - gauge.Load(Parser, DynamicObject); - gauge.AssignDouble(&mvControlled->TotalCurrent); - } - else - { - // failed to match the label - return false; - } - - return true; -} - -uint16_t TTrain::id() -{ - if (vid == 0) - { - vid = ++simulation::prev_train_id; - WriteLog("net: assigning id " + std::to_string(vid) + " to vehicle " + Dynamic()->name(), logtype::net); - } - return vid; -} - -namespace -{ -// updates trains in range [Start, End) -void update_trains(std::deque const &Trains, std::size_t const Start, std::size_t const End, double const Dt) -{ - for (std::size_t j = Start; j < End; ++j) - { - if (Trains[j]) - Trains[j]->Update(Dt); - } -} -} // namespace - -void train_table::updateAsync(double dt) -{ - const int threads = std::max(1, Global.trainThreads); - const size_t total = m_items.size(); - const size_t chunkSize = (total + threads - 1) / threads; - auto const instance{TSubModel::iInstance}; - - std::vector workers; - std::vector> results; // przekazują wyjątki z wątków do głównego wątku - workers.reserve(threads); - results.reserve(threads); - - for (int i = 0; i < threads; ++i) - { - const size_t start = i * chunkSize; - const size_t end = std::min(start + chunkSize, total); - - if (start >= end) - break; // brak więcej danych - - // the instance whose animations the gauges set (TSubModel::iInstance, per thread since the walks of the vulkan renderer went on - // several threads) is the one the main thread set for the driven vehicle - std::packaged_task task([this, start, end, dt, instance]() { - TSubModel::iInstance = instance; - update_trains(m_items, start, end, dt); - }); - results.emplace_back(task.get_future()); - workers.emplace_back(std::move(task)); - } - - // Poczekaj aż wszystkie wątki skończą - for (auto &worker : workers) - worker.join(); - - for (auto &result : results) - result.get(); - - // Teraz kasowanie (tylko w głównym wątku) - for (TTrain *train : m_items) - { - if (!train) - continue; - - if (train->pending_delete) - { - purge(train->Dynamic()->name()); - if (simulation::Train == train) - simulation::Train = nullptr; - } - else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) - { - purge(train->Dynamic()->name()); - } - } -} - -void train_table::update(double dt) -{ - for (TTrain *train : m_items) - { - if (!train) - continue; - - train->Update(dt); - - if (train->pending_delete) - { - purge(train->Dynamic()->name()); - if (simulation::Train == train) - simulation::Train = nullptr; - } - // for single-player destroy non-player trains - else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) - { - purge(train->Dynamic()->name()); - } - } -} - -TTrain *train_table::find_id(std::uint16_t const Id) const -{ - - if (Id == 0) - { - return nullptr; - } - - for (TTrain *train : m_items) - { - if (!train) - { - continue; - } - if (train->id() == Id) - { - return train; - } - } - return nullptr; -} diff --git a/vehicle/Train.h b/vehicle/Train.h index 819e8a454..e77e8ffc4 100644 --- a/vehicle/Train.h +++ b/vehicle/Train.h @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/Button.h" #include "vehicle/Gauge.h" #include "vehicle/enginestart.h" +#include "vehicle/linebreaker.h" #include "audio/sound.h" #include "scripting/PyInt.h" #include "input/command.h" @@ -172,8 +173,43 @@ class TTrain { inline std::string GetLabel( TSubModel const *Control ) const { return m_controlmapper.find( Control ); } + // the direction the mouse drags universal control Index in to any position between its ends, none if the control + // is only set to its ends (MaSzyna-EU07/maszyna#62) + universal_drag::direction universal_drag_direction( int const Index ) const; + // the position universal control Index is set to, from 0 to 1 + float universal_position( int const Index ) const; void UpdateCab(); bool Update( double const Deltatime ); + // the parts of Update, in the order it calls them (vehicle/cab/update.cpp) + private: + void updateLineBreakerState( double const Deltatime ); + void updateTimers( double const Deltatime ); + void updateDoorAndDirectionStates(); + void processReceivedCommands(); + void returnMasterController( double const Deltatime ); + void updateTachometer( double const Deltatime ); + void updateVoltagesAndCurrents(); + void resetUnitStates(); + void updateUnitStates(); + void completeUnitStates( int const in ); + void updateFeedbackGauges() const; + void updateConverterOverload( double const Deltatime ); + void updateSecondUnitGauges(); + void updateClock(); + void updateEngineGauges(); + void updateBasicLamps(); + void updateCircuitLamps( double const Deltatime ); + void updateTrainLamps(); + void turnOffLamps(); + void updateSecondUnitLamps( bool const lowvoltagepower ); + void updateMasterControllers( bool const lowvoltagepower ); + void updateBrakeControllers(); + void updateCabSwitches( bool const lowvoltagepower ); + void updateHeatingAndInstrumentLights(); + void updateButtons(); + void updateAuxiliaryButtons( bool const lowvoltagepower ); + void updateCabLightLevels(); + public: void UpdateDirectionRelays(); void SetupDirectionRelays(); bool prevBatState = false; @@ -212,7 +248,7 @@ class TTrain { return ggHornButton.SubModel != nullptr && ggHornLowButton.SubModel == nullptr && ggHornHighButton.SubModel == nullptr; } // locates nearest vehicle belonging to the consist TDynamicObject *find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const; - // mover master controller to specified position + // move the master controller to specified position void set_master_controller( double const Position ); // moves train brake lever to specified position, potentially emits switch sound if conditions are met void set_train_brake( double const Position ); @@ -227,7 +263,7 @@ class TTrain { // helper, common part of pantograh valves state update methods void update_pantograph_valves(); // the Index-th other vehicle in multiple whose engine the cab starts with its own switches (0: mainb_*, 1: mainc_*) - TMoverParameters *remote_engine( std::size_t const Index ) const; + physics::Vehicle *remote_engine( std::size_t const Index ) const; // the switches starting the engines of the other vehicles in multiple, for Deltatime seconds void update_remote_linebreakers( double const Deltatime ); // update function subroutines @@ -237,10 +273,10 @@ class TTrain { void update_sounds_radio(); void update_sounds_fmradio( double const Deltatime ); inline - end cab_to_end( int const End ) const { - return End == 2 ? end::rear : end::front; } + VehicleEnd cab_to_end( int const End ) const { + return End == 2 ? VehicleEnd::rear : VehicleEnd::front; } inline - end cab_to_end() const { + VehicleEnd cab_to_end() const { return cab_to_end( iCabn ); } void update_screens(double dt); void update_script_screens(); @@ -369,6 +405,12 @@ class TTrain { static void OnCommand_oilfuelpumptoggle( TTrain *Train, command_data const &Command ); static void OnCommand_oilpumpenable( TTrain *Train, command_data const &Command ); static void OnCommand_oilpumpdisable( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodetoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodecatenary( TTrain *Train, command_data const &Command ); + static void OnCommand_tractionmodegenset( TTrain *Train, command_data const &Command ); + static void OnCommand_gensettoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_gensetenable( TTrain *Train, command_data const &Command ); + static void OnCommand_gensetdisable( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakertoggle( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakerclose( TTrain *Train, command_data const &Command ); static void OnCommand_waterheaterbreakeropen( TTrain *Train, command_data const &Command ); @@ -526,6 +568,7 @@ class TTrain { static void OnCommand_cabchangeforward( TTrain *Train, command_data const &Command ); static void OnCommand_cabchangebackward( TTrain *Train, command_data const &Command ); static void OnCommand_generictoggle( TTrain *Train, command_data const &Command ); + static void OnCommand_genericset( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemoveforwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehiclemovebackwards( TTrain *Train, command_data const &Command ); static void OnCommand_vehicleboost( TTrain *Train, command_data const &Command ); @@ -549,13 +592,13 @@ class TTrain { // members TDynamicObject *DynamicObject { nullptr }; // przestawia zmiana pojazdu [F5] - TMoverParameters *mvControlled { nullptr }; // człon, w którym sterujemy silnikiem - TMoverParameters *mvOccupied { nullptr }; // człon, w którym sterujemy hamulcem - TMoverParameters *mvSecond { nullptr }; // drugi człon (ET40, ET41, ET42, ukrotnienia) - TMoverParameters *mvThird { nullptr }; // trzeci człon (SN61) - TMoverParameters *mvPantographUnit { nullptr }; // nearest pantograph equipped unit + physics::Vehicle *controlled { nullptr }; // człon, w którym sterujemy silnikiem + physics::Vehicle *occupied { nullptr }; // człon, w którym sterujemy hamulcem + physics::Vehicle *secondUnit { nullptr }; // drugi człon (ET40, ET41, ET42, ukrotnienia) + physics::Vehicle *thirdUnit { nullptr }; // trzeci człon (SN61) + physics::Vehicle *pantographUnit { nullptr }; // nearest pantograph equipped unit // helper variable, to prevent immediate switch between closing and opening line breaker circuit - int m_linebreakerstate { 0 }; // 0: open, 1: closed, 2: freshly closed (and yes this is awful way to go about it) + linebreaker::state m_linebreakerstate { linebreaker::state::open }; static const commandhandler_map m_commandhandlers; control_mapper m_controlmapper; @@ -600,6 +643,7 @@ public: // reszta może by?publiczna TGauge ggWiperSw; // przelacznik wycieraczek TGauge ggMaxCurrentCtrl; + TGauge ggAutoRelayButton; // przełącznik AutoRelay: rozruch automatyczny, załączenie bocznikowania spalinowozu TGauge ggMainOffButton; TGauge ggMainOnButton; @@ -745,6 +789,8 @@ public: // reszta może by?publiczna TGauge ggFuelPumpButton; // fuel pump switch TGauge ggOilPumpButton; // oil pump switch TGauge ggOilFuelPumpButton; // joint oil and fuel pump switch + TGauge ggTractionModeSwitch; // traction selector of a dual-mode vehicle (catenary/genset) + TGauge ggGensetButton; // genset start switch of a dual-mode vehicle TGauge ggMotorBlowersFrontButton; // front traction motor fan switch TGauge ggMotorBlowersRearButton; // rear traction motor fan switch TGauge ggMotorBlowersAllOffButton; // motor fans shutdown switch @@ -924,6 +970,7 @@ private: float fMainRelayTimer; // hunter-141211: zalaczanie WSa z opoznieniem float fBatteryTimer = {-1.f}; // Hirek: zalaczanie baterii z opoznieniem (tylko gdy zdefiniowano takie zachowanie w fiz) bool allowBatteryToggle = true; // Hirek: zabezpieczenie przed przelaczaniem bateri on/off + bool batteryButtonFired{false}; // the battery button held down has switched the battery already, until it is let go int ScreenUpdateRate { 0 }; // vehicle specific python screen update rate override // McZapkie-240302 - przyda sie do tachometru @@ -945,7 +992,7 @@ private: std::string asCarName[20]; // nazwa czlonu bool bMains[8]; // WSy float fCntVol[8]; // napiecie NN - bool bPants[8][2]; // podniesienie pantografow + std::array, 8> bPants; // podniesienie pantografow bool bFuse[8]; // nadmiarowe bool bBatt[8]; // baterie bool bConv[8]; // przetwornice @@ -969,7 +1016,7 @@ private: bool m_dirneutral{ false }; // helper, true if direction set to neutral bool m_dirbackward{ false }; // helper, true if direction set to backward bool m_doorpermits{ false }; // helper, true if any door permit is active - float m_doorpermittimers[2] = { -1.f, -1.f }; + BySide m_doorpermittimers = { -1.f, -1.f }; float trainLenghtMeasureTimer = { -1.f }; // ld substitute bool m_couplingdisconnect { false }; @@ -996,14 +1043,14 @@ private: // plays provided sound from position of the radio bool radio_message_played; void radio_message( sound_source *Message, int const Channel ); - inline auto RadioChannel() const { return Dynamic()->Mechanik ? Dynamic()->Mechanik->iRadioChannel : 1; } - inline auto &RadioChannel() { return Dynamic()->Mechanik->iRadioChannel; } + inline auto RadioChannel() const { return Dynamic()->Mechanik ? Dynamic()->Mechanik->RadioChannel() : 1; } + inline void SetRadioChannel( int const Channel ) { Dynamic()->Mechanik->SetRadioChannel( Channel ); } inline TDynamicObject *Dynamic() { return DynamicObject; }; inline TDynamicObject const *Dynamic() const { return DynamicObject; }; - inline TMoverParameters *Controlled() { return mvControlled; }; - inline TMoverParameters const *Controlled() const { return mvControlled; }; - inline TMoverParameters *Occupied() { return mvOccupied; }; - inline TMoverParameters const *Occupied() const { return mvOccupied; }; + inline physics::Vehicle *Controlled() { return controlled; }; + inline physics::Vehicle const *Controlled() const { return controlled; }; + inline physics::Vehicle *Occupied() { return occupied; }; + inline physics::Vehicle const *Occupied() const { return occupied; }; void DynamicSet(TDynamicObject *d); void MoveToVehicle( TDynamicObject *target ); // checks whether specified point is within boundaries of the active cab diff --git a/vehicle/ai/consist.cpp b/vehicle/ai/consist.cpp new file mode 100644 index 000000000..ec7ef7a13 --- /dev/null +++ b/vehicle/ai/consist.cpp @@ -0,0 +1,958 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the consist the driver runs: its vehicles, their direction, their brakes, the cab taken + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +void TController::Activation() +{ // umieszczenie obsady w odpowiednim członie, wykonywane wyłącznie gdy steruje AI + iDirection = iDirectionOrder; // kierunek (względem sprzęgów pojazdu z AI) właśnie został ustalony (zmieniony) + if (iDirection) + { // jeśli jest ustalony kierunek + auto *initialvehicle { pVehicle }; +/* + auto const initiallocalbrakelevel { occupied->LocalBrakePosA }; +*/ + auto const initialspringbrakestate { occupied->brakes.spring.activate }; + // switch off tempomat + SpeedCntrl( 0.0 ); + mvControlling->DecScndCtrl( 2 ); + // reset controls + ZeroSpeed(); + ZeroDirection(); + occupied->SetCabOccupied(occupied->CabActive); // użytkownik moze zmienić CabOccupied wychodząc + occupied->CabDeactivisation(); // tak jest w Train.cpp + if (pVehicle->physics->Couplers[iDirectionOrder < 0 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)) { + ZeroLocalBrake(); + if( initialspringbrakestate ) { + occupied->SpringBrakeActivate( false ); + } + // odcięcie na zaworze maszynisty, FVel6 po drugiej stronie nie luzuje + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos(bh_NP) ); // odcięcie na zaworze maszynisty + BrakeLevelSet( occupied->brakes.HandlePosition() ); //ustawienie zmiennej GBH + } + // przejście AI na drugą stronę EN57, ET41 itp. + // TODO: clean this up, there's lot of redundancy with physics::Vehicle::ChangeCab() and TTrain::MoveToVehicle() + { + int movedirection { NumberOf( iDirection < 0 ? VehicleEnd::rear : VehicleEnd::front ) }; + auto *targetvehicle { pVehicle->FirstFind( movedirection, Coupling::control ) }; + if( pVehicle != targetvehicle ) { + auto *targetvehicledriver { targetvehicle->Mechanik }; // zapamiętanie tego, co ewentualnie tam siedzi, żeby w razie dwóch zamienić miejscami + // move to the new vehicle + targetvehicle->Mechanik = this; // na razie bilokacja + targetvehicle->physics->SetInternalCommand(VehicleCommand::none, 0, 0); // usunięcie ewentualnie zalegającej komendy (Change_direction?) + if( targetvehicle->DirectionGet() != pVehicle->DirectionGet() ) { + // jeśli są przeciwne do siebie to będziemy jechać w drugą stronę względem zasiedzianego pojazdu + iDirection = -iDirection; + } + // move the other driver to our old vehicle + pVehicle->Mechanik = targetvehicledriver; // wsadzamy tego, co ewentualnie był (podwójna trakcja) + // NOTE: having caboccupied != 0 (by swapping in the driver from the target vehicle) may lead to dysfunctional brake + // TODO: investigate and resolve if necessary + pVehicle->physics->SetCabOccupied(targetvehicle->physics->CabOccupied()); + if( pVehicle->Mechanik ) { // not guaranteed, as target vehicle can be empty + pVehicle->Mechanik->BrakeLevelSet( pVehicle->physics->brakes.HandlePosition() ); + } + // finish driver swap + pVehicle = targetvehicle; + } + } + if (pVehicle != initialvehicle) + { // jeśli zmieniony został pojazd prowadzony + ControllingSet(); // utworzenie połączenia do sterowanego pojazdu (może się zmienić) - silnikowy dla EZT + if( occupied->brakes.config.handlePositions > 0 + && ( BrakeSystem == TBrakeSystem::Pneumatic + || BrakeSystem == TBrakeSystem::ElectroPneumatic ) ) { + occupied->ResetPipeStabiliser(); + } + BrakeLevelSet( occupied->brakes.HandlePosition() ); + } + if( mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->ShuntModeAllow ) { + // dla 2Ls150 - przed ustawieniem kierunku - można zmienić tryb pracy + mvControlling->CurrentSwitch(OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt) || fMass > 224000.0); // do tego na wzniesieniu może nie dać rady na liniowym + } + // Ra: to przełączanie poniżej jest tu bez sensu + occupied->SetCabOccupied(iDirection); // aktywacja kabiny w prowadzonym pojeżdzie (silnikowy może być odwrotnie?) + occupied->CabActivisation(); // uruchomienie kabin w członach + DirectionForward(true); // nawrotnik do przodu + occupied->SpringBrakeActivate( initialspringbrakestate ); +/* + // NOTE: this won't restore local brake if the vehicle has integrated local brake control + // TBD, TODO: fix or let the ai activate the brake again as part of its standard logic? + if (initiallocalbrakelevel > 0.0) // hamowanie tylko jeśli był wcześniej zahamowany (bo możliwe, że jedzie!) + occupied->LocalBrakePosA = initiallocalbrakelevel; // zahamuj jak wcześniej +*/ + if( pVehicle != initialvehicle ) { + auto *train { simulation::Trains.find( initialvehicle->name() ) }; + if( train ) { + train->MoveToVehicle( pVehicle ); + } + } + + CheckVehicles(); // sprawdzenie składu, AI zapali światła + TableClear(); // resetowanie tabelki skanowania torów + } +}; + +void TController::AutoRewident() +{ // autorewident: nastawianie hamulców w składzie + // 1. Zebranie informacji o składzie pociągu, od czoła do końca + std::vector consist; + for (auto const *d = pVehicles[0]; d != nullptr; d = d->Next()) { + consist.emplace_back(brake_setting::describe(*d->physics, d == pVehicle)); + } + // 2. Określenie typu pociągu i nastaw: by the brake instruction Cw-1 (eu07/maszyna#350), or as the releases before it did. + // brakes are cut out (Cw-1 §19.9) only in a train (a bank engine's run included), not in a consist being shunted + auto const train{brake_setting::runs_as_train(OrderCurrentGet())}; + auto const settings{Global.AIBrakeSettingCw1 ? brake_setting::choose(consist, train) : brake_setting::choose_legacy(consist)}; + // and only at a standstill, the train creeping to a stop included: a check on the run (the order changed mid-run, or + // the train was just formed by coupling, which the AI does above that speed) leaves them to reinspect_brakes() + auto const standstill{brake_setting::at_standstill(occupied->Vel)}; + auto reinspect{false}; + // a light engine counts as a passenger train for the braking below + auto const passengertrain{brake_setting::passenger(brake_setting::choose_train_setting(consist))}; + // 3. Nastawianie + auto setting{settings.begin()}; + for (auto *d = pVehicles[0]; d != nullptr && setting != settings.end(); d = d->Next(), ++setting) { + if (false == aiControlled && d == pVehicle) { + // don't touch human-controlled vehicle, but others are free game + continue; + } + // the setting, a brake cut out in a train on G (Cw-1 §19.9) or put back when the train no longer needs it cut out + if (brake_setting::apply(*d->physics, *setting, standstill)) { + // a brake to cut out, with the train moving: left for the next standstill + reinspect = true; + } + // potentially release manual brake + d->physics->DecManualBrakeLevel( ManualBrakePosNo ); + d->physics->ReleaseSpringBrake(); + } + BrakeReinspectionPending = reinspect; + //ustawianie trybu pracy zadajnika hamulca, wystarczy raz po inicjalizacji AI + if( true == aiControlled ) { + // if a human is in charge leave the brake mode up to them, otherwise do as you like + for( int i = 1; i <= 8; i *= 2 ) { + if( ( occupied->brakes.config.availableOperatingModes & i ) > 0 ) { + occupied->SetBrakeOperatingMode(i); + } + } + } + + // teraz zerujemy tabelkę opóźnienia hamowania + for (int i = 0; i < BrakeAccTableSize; ++i) + { + fBrake_a0[i+1] = 0; + fBrake_a1[i+1] = 0; + } + + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt ) ) { + // for uniform behaviour and compatibility with older scenarios set default acceleration table values for shunting + fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; + // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors + if( is_emu() + && mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { + fAccThreshold += 0.10; + } + fNominalAccThreshold = fAccThreshold; + } + + BrakeSystem = consist_brake_system(); + // Change the EP fuse state only when AI is in charge, don't fiddle with controls when the user is controlling the vehicle + if (aiControlled) { + occupied->EpFuseSwitch(BrakeSystem == TBrakeSystem::ElectroPneumatic); + } + + if( OrderCurrentGet() & ( DriverOrder::obeyTrain | DriverOrder::bank ) ) { + // 4. Przeliczanie siły hamowania + double const velstep = occupied->Vmax() * 0.5 / BrakeAccTableSize; + auto *d = pVehicles[0]; // pojazd na czele składu + while (d) { + // a vehicle with its brake cut out (by the inspector above or for a reason of its own) adds its mass only; + // the inspector of the earlier releases counted its brake in + auto const brakes{false == Global.AIBrakeSettingCw1 || false == brake_setting::is_cut_out(*d->physics)}; + for( int i = 0; i < BrakeAccTableSize && brakes; ++i ) { + fBrake_a0[ i + 1 ] += d->physics->BrakeForceR( 0.25, velstep*( 1 + 2 * i ) ); + fBrake_a1[ i + 1 ] += d->physics->BrakeForceR( 1.00, velstep*( 1 + 2 * i ) ); + } + d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + for (int i = 0; i < BrakeAccTableSize; ++i) + { + fBrake_a1[i+1] -= fBrake_a0[i+1]; + fBrake_a0[i+1] /= fMass; + fBrake_a0[i + 1] += 0.001*velstep*(1 + 2 * i); + fBrake_a1[i+1] /= 12 * fMass; + } + + IsPassengerTrain = is_train() && false == is_emu() && false == is_dmu() && (occupied->brakes.delaySetting & bdelay_G) == 0; + IsCargoTrain = is_train() && (occupied->brakes.delaySetting & bdelay_G) != 0; + IsHeavyCargoTrain = true == IsCargoTrain && fBrake_a0[1] > 0.4 && iVehicles - ControlledEnginesCount > 0 && fMass / iVehicles > 50000; + + BrakingInitialLevel = IsHeavyCargoTrain ? 1.25 : IsCargoTrain ? 1.25 : 1.00; + + BrakingLevelIncrease = 0.25; + + if( is_emu() ) { + auto ep_factor { ( BrakeSystem == TBrakeSystem::ElectroPneumatic ? 8 : 4 ) }; + if( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) { + // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors + fNominalAccThreshold = std::max( -0.60, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); + } + else { + fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - ep_factor * fBrake_a1[ BrakeAccTableSize ] ); + } + fBrakeReaction = 0.25; + } + else if( is_dmu() ) { + fNominalAccThreshold = std::max( -0.75, -fBrake_a0[ BrakeAccTableSize ] - 8 * fBrake_a1[ BrakeAccTableSize ] ); + fBrakeReaction = 0.25; + } + else if (passengertrain) { + fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 4 * fBrake_a1[ BrakeAccTableSize ]; + fBrakeReaction = 1.00 + fLength*0.004; + } + else { + fNominalAccThreshold = -fBrake_a0[ BrakeAccTableSize ] - 1 * fBrake_a1[ BrakeAccTableSize ]; + fBrakeReaction = 1.00 + fLength*0.005; + } + fAccThreshold = fNominalAccThreshold; + } + +} + +// a brake the inspector had to cut out (Cw-1 §19.9) while the train was moving gets cut out once the train stands. +// a train formed by coupling is looked at as the buffers meet, above the speed the inspector takes for a standstill, +// and with no stop ahead nothing would look at it standing again (eu07/maszyna#350) +void TController::reinspect_brakes() +{ + if (false == BrakeReinspectionPending) { + return; + } + if (false == brake_setting::runs_as_train(OrderCurrentGet())) { + // no longer a train: nothing is cut out in a consist being shunted + BrakeReinspectionPending = false; + return; + } + if (brake_setting::at_standstill(occupied->Vel)) { + // standing, the inspector leaves nothing for later: this clears the flag + AutoRewident(); + } +} + +int TController::CheckDirection() { + + int d = occupied->DirAbsolute; // który sprzęg jest z przodu + if( !d ) { + // jeśli nie ma ustalonego kierunku to jedziemy wg aktualnej kabiny + d = occupied->CabActive; + } + return d; +} + +bool TController::CheckVehicles(DriverOrders user) +{ // sprawdzenie stanu posiadanych pojazdów w składzie i zapalenie świateł + TDynamicObject *p; // roboczy wskaźnik na pojazd + iVehicles = 0; // ilość pojazdów w składzie + auto d = CheckDirection(); + d = d >= 0 ? 0 : 1; // kierunek szukania czoła (numer sprzęgu) + p = pVehicle->FirstFind(d); // pojazd na czele składu + if (!p) + p = pVehicle; + auto *const frontvehicle { p }; // stays the consist head for the rest of this check + pVehicles[VehicleEnd::front] = frontvehicle; + // liczenie pojazdów w składzie i ustalenie parametrów + auto dir = d = 1 - d; // a dalej będziemy zliczać od czoła do tyłu + fLength = 0.0; // długość składu do badania wyjechania za ograniczenie + fMass = 0.0; // całkowita masa do liczenia stycznej składowej grawitacji + fVelMax = -1; // ustalenie prędkości dla składu + bool main = true; // czy jest głównym sterującym + drivingFlags.oerlikons = true; // zakładamy, że są same Oerlikony + // Ra 2014-09: ustawić moveMultiControl, jeśli wszystkie są w ukrotnieniu (i skrajne mają kabinę?) + while (p) + { // sprawdzanie, czy jest głównym sterującym, żeby nie było konfliktu + if( p->Mechanik // jeśli ma obsadę + && p->Mechanik != this && p->Mechanik->drivingFlags.primary ) { // ale chodzi o inny pojazd, niż aktualnie sprawdzający + // a tamten ma priorytet + // TODO: take into account drivers' operating modes, one or more of them might be on banking duty + if (drivingFlags.primary && occupied->DirAbsolute && occupied->brakes.HandlePosition() >= -1) + { + // jeśli rządzi i ma kierunek + p->Mechanik->primary(false); // dezaktywuje tamtego + p->Mechanik->ZeroLocalBrake(); + p->physics->BrakeLevelSet(p->physics->brakes.driverValve->GetPos(bh_NP)); // odcięcie na zaworze maszynisty + p->Mechanik->BrakeLevelSet(p->physics->brakes.HandlePosition()); // ustawienie zmiennej GBH + } + else + { + main = false; // nici z rządzenia + } + } + ++iVehicles; // jest jeden pojazd więcej + pVehicles[VehicleEnd::rear] = p; // zapamiętanie ostatniego + fLength += p->physics->Dim.L; // dodanie długości pojazdu + fMass += p->physics->TotalMass(); // dodanie masy łącznie z ładunkiem + fVelMax = min_speed( fVelMax, p->physics->Vmax() ); // ustalenie maksymalnej prędkości dla składu + // reset oerlikon brakes consist flag as different type was detected + if( p->physics->brakes.config.subsystem != TBrakeSubSystem::ss_ESt + && p->physics->brakes.config.subsystem != TBrakeSubSystem::ss_LSt ) { + drivingFlags.oerlikons = false; + } + p = p->Neighbour(dir); // pojazd podłączony od wskazanej strony + } + if( main ) { + drivingFlags.primary = true; // nie znaleziono innego, można się porządzić + } + + ControllingSet(); // ustalenie członu do sterowania (może być inny niż zasiedziany) + + if (drivingFlags.primary) + { // jeśli jest aktywnie prowadzącym pojazd, może zrobić własny porządek + auto pantmask = 1; + p = frontvehicle; + // establish ownership and vehicle order + while (p) + { + if (p->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + { // jeśli pojazd posiada pantograf, to przydzielamy mu maskę, którą będzie informował o jeździe bezprądowej + p->iOverheadMask = pantmask; + pantmask = pantmask << 1; // przesunięcie bitów, max. 32 pojazdy z pantografami w składzie + } + + d = p->DirectionSet(d ? 1 : -1); // zwraca położenie następnego (1=zgodny,0=odwrócony - względem czoła składu) + p->ctOwner = this; // dominator oznacza swoje terytorium + p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) + } + // with the order established the virtual train manager can do their work + p = frontvehicle; + ControlledEnginesCount = p->physics->Power > 1.0 ? 1 : 0; + auto hasheaters { false }; + while (p) + { + if( p != pVehicle ) { + if( false == p->is_connected( pVehicle, Coupling::control ) ) { + // NOTE: don't set battery in controllable vehicles, let the user/ai do it explicitly + // HACK: wagony muszą mieć baterię załączoną do otwarcia drzwi... + p->physics->BatterySwitch( true ); + // enable heating and converter in carriages with can be heated + if( p->physics->trainHeating.config.power > 0 ) { + p->physics->trainHeating.Allow(true); + p->physics->ConverterSwitch( true, range_t::local ); + hasheaters = true; + } + } + else { + if( p->physics->Power > 1.0 ) { + ++ControlledEnginesCount; + } + } + } + + if( p->asDestination == "none" ) { + p->DestinationSet( TrainParams.Relation2, TrainParams.TrainName ); // relacja docelowa, jeśli nie było + } + if( aiControlled ) { // jeśli prowadzi komputer + p->RaLightsSet( 0, 0 ); // gasimy światła + } + p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) + } + + if( user == DriverOrder::connect && true == main ) { + // HACK: with additional vehicles in the consist ensure all linked vehicles are set to move in the same direction + if( pVehicle->Prev(Coupling::control) != nullptr + || pVehicle->Next(Coupling::control) != nullptr ) { + sync_consist_reversers(); + } + // potentially sync compartment lighting state for the newly connected vehicles + if( occupied->CompartmentLights.start_type == start_t::manual ) { + occupied->CompartmentLightsSwitchOff( occupied->CompartmentLights.is_disabled ); + occupied->CompartmentLightsSwitch( occupied->CompartmentLights.is_enabled ); + } + } + + // kasowanie pamieci hamowania kontrolnego + if (OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection)) { + brakeTest = {}; + } + + if( brake_setting::inspects_train( OrderCurrentGet(), user == DriverOrder::connect ) ) { + // nastawianie hamulca do jazdy pociągowej + AutoRewident(); +/* + if( ( true == drivingFlags.connect ) + && ( true == OrderCurrentGet().HasAll(DriverOrder::connect) ) ) { + iCoupler = {}; // dalsza jazda manewrowa już bez łączenia + drivingFlags.connect = false; // zdjęcie flagi doczepiania + SetVelocity( 0, 0, stopJoin ); // wyłączyć przyspieszanie + JumpToNextOrder(); // wykonanie następnej komendy + } +*/ + } + + // detect push-pull train configurations and mark them accordingly + if( frontvehicle->is_connected( pVehicles[ VehicleEnd::rear ], Coupling::control ) ) { + // zmiana czoła przez zmianę kabiny + drivingFlags.pushPull = true; + } + else { + // zmiana czoła przez manewry + drivingFlags.pushPull = false; + } + + // HACK: ensure vehicle lights are active from the beginning, if it had pre-activated battery + if( occupied->LightsPosNo > 0 ) { + pVehicle->SetLights(); + } + if( iEngineActive ) { + // potentially adjust light state + control_lights(); + // custom ai action for disconnect mode: switch off lights on disconnected vehicle(s) + if( is_train() && true == OrderCurrentGet().HasAll(DriverOrder::disconnect) && aiControlled ) { + // światła manewrowe (Tb1) tylko z przodu, aby nie pozostawić odczepionego ze światłem + if (occupied->DirActive >= 0) + { // jak ma kierunek do przodu + pVehicles[VehicleEnd::rear]->RaLightsSet(-1, 0); + } + else + { // jak dociska + frontvehicle->RaLightsSet(0, -1); + } + } + // enable door locks + cue_action( driver_hint::consistdoorlockson ); + // potentially enable train heating + { + auto const ispassengertrain { IsPassengerTrain && iVehicles - ControlledEnginesCount > 0 }; + // TODO: replace connection test with connection check between last engine and first car, specifically + auto const isheatingcouplingactive { ( + ControlledEnginesCount == 1 ? + frontvehicle->is_connected( pVehicles[ VehicleEnd::rear ], Coupling::heating ) : + true ) }; + auto const isheatingneeded { + (is_emu() || is_dmu() ? true : + false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain | DriverOrder::bank) ? false : + false == isheatingcouplingactive ? false : + ispassengertrain ? hasheaters : + false) }; + if( mvControlling->trainHeating.IsAllowed() != isheatingneeded ) { + cue_action( + isheatingneeded ? + driver_hint::consistheatingon : + driver_hint::consistheatingoff ); + } + } + } + + if( user == DriverOrder::connect + || user == DriverOrder::disconnect ) { + // HACK: force route table update on consist change, new consist length means distances to points of interest are now wrong + iTableDirection = 0; + } + } // blok wykonywany, gdy aktywnie prowadzi + return true; +} + +void TController::Lights(int head, int rear) +{ // zapalenie świateł w skłądzie + pVehicles[ VehicleEnd::front ]->RaLightsSet(head, -1); // zapalenie przednich w pierwszym + pVehicles[ VehicleEnd::rear ]->RaLightsSet(-1, rear); // zapalenie końcówek w ostatnim +} + +void TController::DirectionInitial() +{ // ustawienie kierunku po wczytaniu trainset (może jechać na wstecznym + occupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) + if (occupied->Vel > EU07_AI_NOMOVEMENT) + { // jeśli na starcie jedzie + iDirection = iDirectionOrder = + occupied->V() > 0 ? 1 : -1; // początkowa prędkość wymusza kierunek jazdy + DirectionForward(occupied->V() * occupied->CabActive >= 0.0); // a dalej ustawienie nawrotnika + } + CheckVehicles(); // sprawdzenie świateł oraz skrajnych pojazdów do skanowania +}; + +void TController::DirectionChange() { + + auto const initialstate { iDirection }; + iDirection = CheckDirection(); + if( iDirection != initialstate ) { + CheckVehicles( DriverOrder::changeDirection ); + } +} + +int TController::OrderDirectionChange(int newdir, physics::Vehicle *Vehicle) +{ // zmiana kierunku jazdy, niezależnie od kabiny + int testd = newdir; + if (Vehicle->Vel < 0.5) + { // jeśli prawie stoi, można zmienić kierunek, musi być wykonane dwukrotnie, bo za pierwszym razem daje na zero + switch (newdir * Vehicle->CabActive) + { // DirectionBackward() i DirectionForward() to zmiany względem kabiny + case -1: // if (!Vehicle->DirectionBackward()) testd=0; break; + DirectionForward(false); + break; + case 1: // if (!Vehicle->DirectionForward()) testd=0; break; + DirectionForward(true); + break; + } + if (testd == 0) + VelforDriver = -1; // kierunek został zmieniony na żądany, można jechać + } + else // jeśli jedzie + VelforDriver = 0; // ma się zatrzymać w celu zmiany kierunku + if (Vehicle->DirActive == 0 && VelforDriver < Vehicle->Vel) // Ra: to jest chyba bez sensu + IncBrake(); // niech hamuje + if (Vehicle->DirActive == testd * Vehicle->CabActive) + VelforDriver = -1; // można jechać, bo kierunek jest zgodny z żądanym + if (is_emu() && Vehicle->DirActive > 0) + // if () //tylko jeśli jazda pociągowa (tego nie wiemy w momencie odpalania silnika) + Vehicle->DirectionForward(); + // Ra: z przekazaniem do silnikowego + return (int)VelforDriver; // zwraca prędkość mechanika +} + +void TController::DirectionForward(bool forward) +{ // ustawienie jazdy do przodu dla true i do tyłu dla false (zależy od kabiny) + ZeroSpeed( true ); // TODO: check if force switch is needed anymore here + // HACK: make sure the master controller isn't set in position which prevents direction change + mvControlling->SetMainCtrlPos(std::min( mvControlling->MainCtrlPos(), mvControlling->MainCtrlMaxDirChangePos() )); + + if( forward ) { + // do przodu w obecnej kabinie + while( occupied->DirActive <= 0 + && occupied->DirectionForward() ) { + // force scan table update + iTableDirection = 0; + } + } + else { + // do tyłu w obecnej kabinie + while( occupied->DirActive >= 0 + && occupied->DirectionBackward() ) { + // force scan table update + iTableDirection = 0; + } + } + if( occupied->TrainType() == train_type::sn61 ) { + // specjalnie dla SN61 żeby nie zgasł + while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn == 0 + && mvControlling->IncMainCtrl(1) ) { + ; // all work is done in the header + } + } +} + +void TController::ZeroDirection() { + + while( occupied->DirActive > 0 && occupied->DirectionBackward() ) { ; } + while( occupied->DirActive < 0 && occupied->DirectionForward() ) { ; } +} + +void TController::sync_consist_reversers() { + + auto const currentdirection { occupied->DirActive }; + auto const fastforward { is_emu() && occupied->EngineType != TEngineType::ElectricInductionMotor + && occupied->Imin() == occupied->IminHi }; + + // move reverser all way in the opposite direction... + for( auto idx = 0; idx < 3; ++idx ) { + if( currentdirection >= 0 ) { + occupied->DirectionBackward(); + } + else { + occupied->DirectionForward(); + + } + } + // ...then restore original setting + while( occupied->DirActive != currentdirection ) { + if( false == ( + currentdirection >= 0 ? + occupied->DirectionForward() : + occupied->DirectionBackward() ) ) { + // sanity check for potential endless loop + break; + } + } + // potentially restore 'fast forward' setting + if( currentdirection > 0 && true == fastforward ) { + occupied->DirectionForward(); + } +} + +void TController::MoveTo(TDynamicObject *to) +{ // przesunięcie AI do innego pojazdu (przy zmianie kabiny) + if( to->Mechanik != nullptr + && to->Mechanik != this ) { + // ai controller thunderdome, there can be only one + if( to->Mechanik->aiControlled ) { + if( to->Mechanik->primary() ) { + // take over boss duties + primary( true ); + } + SafeDelete( to->Mechanik ); + } + else { + // can't quite delete a human + if( aiControlled ) { + delete this; + } + return; + } + } + pVehicle->Mechanik = nullptr; + pVehicle = to; + ControllingSet(); // utworzenie połączenia do sterowanego pojazdu + pVehicle->Mechanik = this; + +}; + +void TController::ControllingSet() +{ // znajduje człon do sterowania w EZT będzie to silnikowy + // problematyczne jest sterowanie z członu biernego, dlatego damy AI silnikowy + // dzięki temu będzie wirtualna kabina w silnikowym, działająca w rozrządczym + // w plikach FIZ zostały zgubione ujemne maski sprzęgów, stąd problemy z EZT + if( pVehicle == nullptr ) { + // a driver of no vehicle has nothing to control + return; + } + occupied = pVehicle->physics; // domyślny skrót do obiektu parametrów + BrakeSystem = occupied->brakes.config.kind; // domyślny sposób hamowania + mvControlling = pVehicle->FindPowered()->physics; // poszukiwanie członu sterowanego + { + auto *lookup { pVehicle->FindPantographCarrier() }; + pantographUnit = lookup != nullptr ? lookup->physics : mvControlling; + } + BrakeSystem = consist_brake_system(); +}; + +void +TController::determine_consist_state() { + // ABu-160305 testowanie gotowości do jazdy + // Ra: przeniesione z DynObj, skład użytkownika też jest testowany, żeby mu przekazać, że ma odhamować + + if (occupied->CabActive == 0 && occupied->lowVoltage.Is24vAvailable()) + { + cue_action( driver_hint::cabactivation ); + } + else if (!occupied->AutomaticCabActivation + && ( occupied->CabActive == -occupied->CabOccupied() || !occupied->CabMaster() || !occupied->lowVoltage.Is24vAvailable() ) ) + { + cue_action( driver_hint::cabdeactivation ); + } + + int index = double(BrakeAccTableSize) * (occupied->Vel / occupied->Vmax()); + index = std::min(BrakeAccTableSize, std::max(1, index)); + fBrake_a0[0] = fBrake_a0[index]; + fBrake_a1[0] = fBrake_a1[index]; + + if (is_emu() || is_dmu()) { + auto Coeff = std::clamp( occupied->Vel*0.015 , 0.5 , 1.0); + fAccThreshold = fNominalAccThreshold * Coeff - fBrake_a0[BrakeAccTableSize] * (1.0 - Coeff); + } + + Ready = true; // wstępnie gotowy + fReady = 0.0; // założenie, że odhamowany + IsConsistBraked = occupied->brakes.config.kind == TBrakeSystem::ElectroPneumatic && false == ForcePNBrake ? occupied->brakes.cylinderPressure > 2.0 : + occupied->brakePipe.Pressure() < std::max(3.9, occupied->brakes.actualPressure.PipePressureVal) + 0.1; + fAccGravity = 0.0; // przyspieszenie wynikające z pochylenia + IsAnyCouplerStretched = false; + IsAnyDoorOnlyOpen[ VehicleSide::right ] = IsAnyDoorOnlyOpen[ VehicleSide::left ] = false; + IsAnyDoorOpen[ VehicleSide::right ] = IsAnyDoorOpen[ VehicleSide::left ] = false; + IsAnyDoorPermitActive[ VehicleSide::right ] = IsAnyDoorPermitActive[ VehicleSide::left ] = false; + auto doorclosure { door_closure_t::none }; + ConsistShade = 0.0; + auto *p { pVehicles[ VehicleEnd::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 { uphillStart.IsActive() }; + 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->physics }; + auto const bp { std::max( 0.0, vehicle->brakes.cylinderPressure - ( vehicle->SpeedCtrlUnit.Parking ? vehicle->brakes.config.maxCylinderPressure[ 0 ] * vehicle->brakes.holding.deceleration : 0.0 ) ) }; + momentum += vehicle->TotalMass() * vehicle->V() * ( p->DirectionGet() == iDirection ? 1 : -1 ); + mostapplied = std::max( bp, mostapplied ); + if( ( vehicle->brakes.config.kind != TBrakeSystem::Individual ) + && ( vehicle->brakes.config.maxCylinderPressure[ 3 ] > 0.0 ) + && ( false == TestFlag( vehicle->brakes.distributor->GetBrakeStatus(), b_dmg ) ) ) { // a brake cut out doesn't count + chargelevel = std::min( { chargelevel, vehicle->brakePipe.Pressure(), vehicle->brakes.distributor->GetBRP() } ); + } + auto const wasready { Ready }; + if( released || Ready ) { + // bo jak coś nie odhamowane, to dalej nie ma co sprawdzać + auto const isbraking { TestFlagAny( vehicle->brakes.distributor->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 + 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 && ( uphillStart.IsReleasing() || ( vehicle->Vel < 1.0 ) ); + } + } + if( wasready ) { + // Ra: odluźnianie przeładowanych lokomotyw, ciągniętych na zimno - prowizorka... + if( bp >= 0.4 && (aiControlled || Global.AITrainman && occupied->Vel < EU07_AI_NOMOVEMENT && !is_emu() && !is_dmu()) && BrakeCtrlPosition == gbh_RP // jest pozycja jazdy + && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken + && vehicle->brakePipe.Pressure() - occupied->brakes.driverValve->GetRP() > -0.1 // jeśli ciśnienie jak dla jazdy + && vehicle->brakes.distributor->GetCRP() > vehicle->brakePipe.Pressure() + 0.12 ) { // wg UIC określone sztywno na 0.04 + // za dużo w zbiorniku + // indywidualne luzowanko + vehicle->BrakeReleaser(1); + } + if (bp < 0.1 && (aiControlled || Global.AITrainman) && false == TestFlag(vehicle->brakes.distributor->GetBrakeStatus(), b_dmg) // brake isn't broken + && vehicle->brakes.distributor->GetCRP() < vehicle->brakePipe.Pressure() - 0.1) { + // już nie jest za dużo w zbiorniku + // koniec indywidualnego luzowanka + vehicle->BrakeReleaser(0); + } + } + // the brake held for the start counts again once it is being released + fReady = std::max( ( heldforstart && ( false == uphillStart.IsReleasing() ) ) ? 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 + fAccGravity -= vehicle->TotalMassxg * dy * ( p->DirectionGet() == iDirection ? 1 : -1 ); + } + // check coupler state + IsAnyCouplerStretched = + IsAnyCouplerStretched + || vehicle->Couplers[VehicleEnd::front].stretch_duration > 0.0 + || vehicle->Couplers[VehicleEnd::rear].stretch_duration > 0.0; + // check door state + { + auto const switchsides{ p->DirectionGet() != (iDirection == 0 ? occupied->CabOccupied() : iDirection) }; + auto const &rightdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::left : VehicleSide::right ) ] }; + auto const &leftdoor { vehicle->Doors.instances[ ( switchsides ? VehicleSide::right : VehicleSide::left ) ] }; + if( vehicle->Doors.close_control != control_t::autonomous ) { + IsAnyDoorOpen[ VehicleSide::right ] |= false == rightdoor.is_closed; + IsAnyDoorOpen[ VehicleSide::left ] |= false == leftdoor.is_closed; + } + if (vehicle->Doors.close_control != control_t::autonomous) { + IsAnyDoorOnlyOpen[ VehicleSide::right ] |= false == rightdoor.is_door_closed; + IsAnyDoorOnlyOpen[ VehicleSide::left ] |= false == leftdoor.is_door_closed; + } + if( vehicle->Doors.permit_needed ) { + IsAnyDoorPermitActive[ VehicleSide::right ] |= rightdoor.open_permit; + IsAnyDoorPermitActive[ VehicleSide::left ] |= leftdoor.open_permit; + } + doorclosure = std::max( doorclosure, vehicle->door_closure() ); + } + // measure lighting level + // TBD: apply weight (multiplier) to partially lit vehicles? + ConsistShade += p->fShade > 0.0 ? p->fShade : 1.0; + p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) + } + DoorClosure = doorclosure; + // calculate average amount of received sunlight + ConsistShade /= iVehicles; + + // test state of main devices in all vehicles under control + IsAnyConverterOverloadRelayOpen = false; + IsAnyMotorOverloadRelayOpen = false; + IsAnyGroundRelayOpen = false; + IsAnyLineBreakerOpen = false; + IsAnyCompressorPresent = false; + IsAnyCompressorEnabled = false; + IsAnyCompressorExplicitlyEnabled = false; + IsAnyConverterPresent = false; + IsAnyConverterEnabled = false; + IsAnyConverterExplicitlyEnabled = false; + // whether the line contactors of a vehicle wait for its own converter (LineContactorsInterlock), off with its local switch + auto islocalconverterswitchoff { false }; + + pVehicle->for_each( + Coupling::control, + [this, &islocalconverterswitchoff]( TDynamicObject * Vehicle ) { + auto const *vehicle { Vehicle->physics }; + islocalconverterswitchoff |= vehicle->LineContactorsHeldByLocalConverterSwitch(); + IsAnyConverterOverloadRelayOpen |= vehicle->converter.IsOverloaded(); + IsAnyMotorOverloadRelayOpen |= vehicle->FuseFlag; + IsAnyGroundRelayOpen |= !vehicle->protection.GroundHolds(); + IsAnyCompressorPresent |= vehicle->air.compressor.config.speed > 0.0; + IsAnyCompressorEnabled |= vehicle->air.compressor.config.speed > 0.0 ? (vehicle->air.compressor.IsAllowed() || vehicle->air.compressor.config.start == start_t::automatic) && vehicle->air.compressor.LocalSwitchOn() : false; + IsAnyCompressorExplicitlyEnabled |= vehicle->air.compressor.config.speed > 0.0 ? vehicle->air.compressor.IsAllowed() && vehicle->air.compressor.LocalSwitchOn() : false; + IsAnyConverterPresent |= vehicle->converter.config.start != start_t::disabled; + IsAnyConverterEnabled |= ( vehicle->converter.IsAllowed() || vehicle->converter.config.start == start_t::automatic ) && vehicle->converter.LocalSwitchOn(); + IsAnyConverterExplicitlyEnabled |= vehicle->converter.IsAllowed() && vehicle->converter.LocalSwitchOn(); + if( vehicle->Power > 0.01 ) { + IsAnyLineBreakerOpen |= !vehicle->lineBreaker.IsClosed(); } } ); + + // siłę generują pojazdy na pochyleniu ale działa ona całość składu, więc a=F/m + fAccGravity *= iDirection >= 0 ? 1 : -1; + fAccGravity /= fMass; + { + auto absaccs { fAccGravity }; // Ra 2014-03: jesli skład stoi, to działa na niego składowa styczna grawitacji + if( occupied->Vel > EU07_AI_NOMOVEMENT ) { + absaccs = 0; + auto *d = pVehicles[ VehicleEnd::front ]; // pojazd na czele składu + while( d ) { + absaccs += d->physics->TotalMass() * d->physics->AccS() * ( d->DirectionGet() == iDirection ? 1 : -1 ); + d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + absaccs *= iDirection >= 0 ? 1 : -1; + absaccs /= fMass; + } + AbsAccS = absaccs; + } +#if LOGVELOCITY + WriteLog( "Vel=" + to_string( DirectionalVel() ) + ", AbsAccS=" + to_string( AbsAccS ) + ", AccGrav=" + to_string( fAccGravity ) ); +#endif + + if( !Ready // v367: jeśli wg powyższych warunków skład nie jest odhamowany + && fAccGravity < -0.05 // jeśli ma pod górę na tyle, by się stoczyć + && 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( occupied->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 ) + && ( occupied->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 { + aiControlled ? + BrakeCtrlPosition > 0.0 : + // a human driver's handle, which BrakeCtrlPosition doesn't follow + occupied->brakes.HandlePositionSmooth() > occupied->brakes.driverValve->GetPos( bh_RP ) + 0.2 }; + auto const reference { + brake_charge::reference( occupied->brakePipe.Pressure(), std::min( occupied->brakes.driverValve->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->air.MainReservoirPressure(), occupied->air.MainReservoirPressure() ) > reference ) + && ( occupied->brakePipe.Pressure() >= 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: " + occupied->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( aiControlled + && ( false == IsConsistCharged ) + && ( false == heldforstart ) ) { + Ready = false; + } + auto const departblocked { + aiControlled + && occupied->Vel < EU07_AI_NOMOVEMENT + && VelDesired > 0.0 + && ( false == Ready || fReady > 0.4 ) }; + if( false == departblocked ) { + DepartBlockedStart = -1.0; + } + else if( DepartBlockedStart < 0.0 ) { + DepartBlockedStart = ElapsedTime; + } + // second pass, for diesel engines verify the (live) engines are fully started + // TODO: cache presence of diesel engines in the consist, to skip this test if there isn't any + p = pVehicles[ VehicleEnd::front ]; // pojazd na czole składu + while( true == Ready + && p != nullptr ) { + + auto const *vehicle { p->physics }; + + if( has_diesel_engine() ) { + + Ready = vehicle->Vel > EU07_AI_MOVEMENT // already moving + || false == vehicle->lineBreaker.IsClosed() // deadweight vehicle + || vehicle->enrot > 0.8 * (vehicle->EngineType == TEngineType::DieselEngine ? vehicle->diesel.minRevolutions : vehicle->DElist[0].RPM / 60.0); + } + p = p->Next(); // pojazd podłączony z tyłu (patrząc od czoła) + } + // test consist state for external events and/or weird things human user could've done + iEngineActive &= + false == IsAnyConverterOverloadRelayOpen + && false == IsAnyLineBreakerOpen + && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) + && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) + // the ai goes back to preparing the engine and switches that converter on, the human driver may run with it off + && ( false == aiControlled || false == islocalconverterswitchoff ); +} diff --git a/vehicle/ai/controls.cpp b/vehicle/ai/controls.cpp new file mode 100644 index 000000000..e532afe60 --- /dev/null +++ b/vehicle/ai/controls.cpp @@ -0,0 +1,1390 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the controllers and the brake handles the driver works + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +// one step more of the train brake, sized from the consist brake table against the deceleration asked for +bool +TController::increase_train_brake() { + + // dodane dla towarowego + float pos_corr = 0; + + TDynamicObject *d; + d = pVehicles[0]; // pojazd na czele składu + while (d) + { // przeliczanie dodatkowego potrzebnego spadku ciśnienia + if( ( d->physics->brakes.distributor->GetBrakeStatus() & b_dmg ) == 0 ) { + pos_corr -= ( std::min( 5.0, d->physics->brakes.distributor->GetCRP() ) - 5.0 ) * d->physics->TotalMass(); + } + d = d->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + pos_corr = pos_corr / fMass * 2.5; + + if (occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + { + pos_corr += occupied->brakes.driverValve->GetCP()*0.2; + + } + if( double const deltaAcc = -AccDesired*BrakeAccFactor() - (fBrake_a0[0] + 4.0 * (/*GBH occupied->BrakeCtrlPosR*/BrakeCtrlPosition - 1 - pos_corr)*fBrake_a1[0]); + deltaAcc > brake_increase_margin() ) + { + if( /*GBH occupied->BrakeCtrlPosR*/BrakeCtrlPosition < 0.1 ) { + auto const OK { /*occupied->*/BrakeLevelAdd( BrakingInitialLevel ) }; //GBH + // HACK: stronger braking to overcome SA134 engine behaviour + if( is_dmu() + && VelNext == 0.0 + && fBrakeDist < 200.0 ) { + BrakeLevelAdd( + fBrakeDist / ActualProximityDist < 0.8 ? + 0.5 : + 1.0 ); + } + return OK; + } + auto const OK { /*occupied->*/BrakeLevelAdd( BrakingLevelIncrease ) }; //GBH + // brake harder if the acceleration is much higher than desired + /*if( ( deltaAcc > 2 * fBrake_a1[ 0 ] ) + && ( occupied->BrakeCtrlPosR + BrakingLevelIncrease <= 5.0 ) ) { + occupied->BrakeLevelAdd( BrakingLevelIncrease ); + } GBH */ + if( deltaAcc > 2 * fBrake_a1[0] + && BrakeCtrlPosition + BrakingLevelIncrease <= 5.0 ) { + /*occupied->*/BrakeLevelAdd( BrakingLevelIncrease ); + } + return OK; + } + if( BrakeCtrlPosition > 0.0 + && AccDesired < 0.0 // only while braking is asked for, not when called for a train slipping back while starting + && ( fBrakeHeldTime > ( + occupied->brakes.delaySetting > bdelay_G ? + occupied->brakes.config.delays[ 1 ] : + occupied->brakes.config.delays[ 3 ] ) + // a train falling further behind needs no full fill time to be seen not to get enough + || ( ( brakingShortfall.value > 0.02 ) + && ( fBrakeHeldTime > vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) ) { + // the table says the present position is enough, but the brake has had its full fill + // time since the handle last moved and the train is still not slowing down as asked: + // believe the train rather than the table + return BrakeLevelAdd( BrakingLevelIncrease ); + } + return false; +} + +bool TController::IncBrake() +{ // zwiększenie hamowania + auto OK { false }; + auto const bs { + BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? + TBrakeSystem::Pneumatic : + BrakeSystem }; + switch( bs ) { + case TBrakeSystem::Individual: { + if( occupied->brakes.config.localKind == TLocalBrake::ManualBrake ) { + OK = occupied->IncManualBrakeLevel( 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); + } + else { + OK = occupied->IncLocalBrakeLevel( std::floor( 1.5 + std::abs( AccDesired ) ) ); + } + break; + } + case TBrakeSystem::Pneumatic: { + if (bs != occupied->brakes.config.kind) + { + while (occupied->brakes.operatingMode > bom_PN) + { + occupied->brakes.operatingMode >>= 1; + } + } + // NOTE: can't perform just test whether connected vehicle == nullptr, due to virtual couplers formed with nearby vehicles + auto standalone { true }; + if( occupied->TrainType() == train_type::et41 + || occupied->TrainType() == train_type::et42 ) { + // NOTE: we're doing simplified checks full of presuptions here. + // they'll break if someone does strange thing like turning around the second unit + if( occupied->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::permanent + && occupied->Couplers[VehicleEnd::rear].Connected->Couplers[VehicleEnd::rear].Connected != nullptr ) { + standalone = false; + } + if( occupied->Couplers[VehicleEnd::front].CouplingFlag & Coupling::permanent + && occupied->Couplers[VehicleEnd::front].Connected->Couplers[VehicleEnd::front].Connected != nullptr ) { + standalone = false; + } + } + else if( is_dmu() ) { + // enforce use of train brake for DMUs + standalone = false; + } + else if( OrderCurrentGet().HasAny(DriverOrder::looseShunt) + && occupied->Vel - VelDesired < fVelPlus + fVelMinus ) { + // try to reduce train brake use in loose shunting mode + standalone = true; + } + else { +/* + standalone = + ( ( occupied->Couplers[ 0 ].CouplingFlag.Empty() ) + && ( occupied->Couplers[ 1 ].CouplingFlag.Empty() ) ); +*/ + if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { + // more detailed version, will use manual braking also for coupled sets of controlled vehicles + auto *vehicle = pVehicles[ VehicleEnd::front ]; // start from first + while( true == standalone + && vehicle != nullptr ) { + // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself + // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction + standalone = + (vehicle->physics->Couplers[VehicleEnd::front].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::front].Connected->Power > 1)) && + (vehicle->physics->Couplers[VehicleEnd::rear].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::rear].Connected->Power > 1)); + vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + } + } + + //standalone = standalone && ( mvControlling->EIMCtrlType == 0 ); + + if( true == standalone && false == ForcePNBrake ) { + if( mvControlling->EIMCtrlType > 0 ) { + OK = IncBrakeEIM(); + } + else { + OK = occupied->IncLocalBrakeLevel( + 1 + static_cast( std::floor( 0.5 + std::fabs( AccDesired ) ) ) ); // hamowanie lokalnym bo luzem jedzie + } + } + else { + if( /*GBH occupied->BrakeCtrlPos*/ BrakeCtrlPosition + 1 == gbh_MAX ) { + if (AccDesired < -1.5) // hamowanie nagle + OK = /*occupied->*/BrakeLevelAdd(1.0); //GBH + else + OK = false; + } + else { + OK = increase_train_brake(); + } + } + if( /*GBH occupied->BrakeCtrlPos*/ + /*GBH occupied->BrakeCtrlPos*/ BrakeCtrlPosition > 0 && occupied->brakes.distributor->Releaser() ) { + occupied->BrakeReleaser(0); + } + break; + } + case TBrakeSystem::ElectroPneumatic: { + while( occupied->brakes.operatingMode << 1 <= occupied->brakes.config.availableOperatingModes ) { + occupied->brakes.operatingMode <<= 1; + } + if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { + if (occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57) { + if (occupied->brakes.HandlePosition() < occupied->brakes.driverValve->GetPos(bh_FB)) + OK = occupied->BrakeLevelAdd(1.0); + } + else { + OK = IncBrakeEIM(); + } + } + else if( occupied->brakes.driverValve->TimeEP == false ) { + auto const initialbrakeposition { occupied->brakes.HandlePositionSmooth() }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; + occupied->BrakeLevelSet( + std::lerp( + occupied->brakes.driverValve->GetPos( bh_EPR ), + occupied->brakes.driverValve->GetPos( bh_EPB ), + std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor(), 0.0, 1.0 ) ) ); + OK = occupied->brakes.HandlePositionSmooth() != initialbrakeposition; + } + else if( occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos( bh_EPB ) ) { + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPB ) ); + if( occupied->brakes.driverValve->GetPos( bh_EPR ) - occupied->brakes.driverValve->GetPos( bh_EPN ) < 0.1 ) + occupied->SwitchEPBrake( 1 ); // to nie chce działać + OK = true; + } + else if( ( occupied->brakes.driverValve->GetPos( bh_EPR ) - occupied->brakes.driverValve->GetPos( bh_EPN ) < 0.1 ) + && ( occupied->EpForce <= 0.0 ) + && ( occupied->EPBrakeControlPowered() ) ) { + // the handle already in the EP brake position, but the EP brake dropped out with the control's + // supply (e.g. the EP fuse off in the running brake test): switch it on again + occupied->SwitchEPBrake( 1 ); + OK = ( occupied->EpForce > 0.0 ); + } + else + OK = false; + break; + } + default: { break; } + } + return OK; +} + +bool TController::IncBrakeEIM() +{ // zwiększenie hamowania + bool OK = false; + switch (occupied->EIMCtrlType) + { + case 0: { + if( occupied->brakes.blending.maxDeceleration != 9.81 ) { + auto const maxpos{occupied->EIMCtrlEmergency() ? 0.9 : 1.0 }; + auto const brakelimit{ -2.2 * AccDesired / fMedAmax - 1.0}; //additional limit when hinted is too low + auto const brakehinted{ -1.0 * occupied->AIHintLocalBrakeAccFactor() * AccDesired / fMedAmax }; //preffered by AI + auto const brakeposition{ maxpos * std::clamp(std::max(brakelimit, brakehinted), 0.0, 1.0)}; + OK = brakeposition != occupied->brakes.IndependentPosition(); + occupied->brakes.SetIndependentPosition(brakeposition); + } + else { + OK = occupied->IncLocalBrakeLevel( 1 ); + } + break; + } + case 1: { + OK = occupied->MainCtrlPos() > 0; + if( OK ) + occupied->SetMainCtrlPos(0); + break; + } + case 2: { + // the braking position, above the emergency brake one where the controller has it + auto const brakepos{1 + occupied->EIMCtrlEmergencyPositions()}; + OK = occupied->MainCtrlPos() > brakepos; + if( OK ) + occupied->SetMainCtrlPos(brakepos); + break; + } + case 3: { + if( occupied->UniCtrlIntegratedLocalBrakeCtrl() ) { + OK = occupied->MainCtrlPos() > 0; + if( OK ) + occupied->SetMainCtrlPos(0); + } + else { + OK = occupied->IncLocalBrakeLevel( 1 ); + } + break; + } + default: { + break; + } + } + return OK; +} + +// zmniejszenie siły hamowania +bool TController::DecBrake() { + + auto OK { false }; + auto const bs { + BrakeSystem == TBrakeSystem::ElectroPneumatic && ForcePNBrake ? + TBrakeSystem::Pneumatic : + BrakeSystem }; + switch( bs ) { + case TBrakeSystem::Individual: { + auto const positionchange { 1 + std::floor( 0.5 + std::abs( AccDesired ) ) }; + OK = occupied->brakes.config.localKind == TLocalBrake::ManualBrake ? occupied->DecManualBrakeLevel(positionchange) : occupied->DecLocalBrakeLevel(positionchange); + break; + } + case TBrakeSystem::Pneumatic: { + auto deltaAcc { -1.0 }; + if( fBrake_a0[0] != 0.0 + || fBrake_a1[0] != 0.0 ) { + auto const pos_diff { ( is_dmu() ? 0.25 : 1.0 ) }; + // a distributor applied at all gives at least its minimum stage, about what the first position does, so + // 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( uphillStart.IsHolding() ) { + // starting uphill the train brake holds the train until the power does + break; + } + if( ( BrakeCtrlPosition > 0.0 ) + && ( uphill_stop_hold() ) ) { + // 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, occupied->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 occupied->BrakeCtrlPosR*/ BrakeCtrlPosition > 0) { + OK = /*occupied->*/ BrakeLevelAdd(-0.25); + // if ((deltaAcc < 5 * fBrake_a1[0]) && (occupied->BrakeCtrlPosR >= 1.2)) + // occupied->BrakeLevelAdd(-1.0); + /* if (occupied->BrakeCtrlPosR < 0.74) GBH */ + if (BrakeCtrlPosition < 0.74) + /*occupied->*/ BrakeLevelSet(gbh_RP); + } + // 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 ) + && ( occupied->Vel < EU07_AI_NOMOVEMENT ) }; + if( ( !OK ) && ( false == holdlocomotive ) ) { + OK = occupied->DecLocalBrakeLevel(2); + } + if( ( !OK ) && ( false == holdlocomotive ) ) { + OK = DecBrakeEIM(); + } + /* + // NOTE: disabled, duplicate of AI's behaviour in UpdateSituation() + if (occupied->PipePress < 3.0) + Need_BrakeRelease = true; + */ + break; + } + case TBrakeSystem::ElectroPneumatic: { + if( occupied->EngineType == TEngineType::ElectricInductionMotor ) { + if( occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ) { + if( occupied->brakes.HandlePosition() > occupied->brakes.driverValve->GetPos( bh_RP ) ) { + OK = occupied->BrakeLevelAdd( -1.0 ); + } + } + else { + OK = DecBrakeEIM(); + } + } + else if( occupied->brakes.driverValve->TimeEP == false ) { + auto const initialbrakeposition { occupied->brakes.HandlePositionSmooth() }; + auto const AccMax { std::min( fBrake_a0[ 0 ] + 12 * fBrake_a1[ 0 ], occupied->brakes.blending.maxDeceleration ) }; + occupied->BrakeLevelSet( + std::lerp( + occupied->brakes.driverValve->GetPos( bh_EPR ), + occupied->brakes.driverValve->GetPos( bh_EPB ), + std::clamp( -AccDesired / AccMax * occupied->AIHintLocalBrakeAccFactor(), 0.0, 1.0 ) ) ); + OK = occupied->brakes.HandlePositionSmooth() != initialbrakeposition; + } + else { + OK = false; + if (occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos(bh_EPR)) { + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_EPR)); + OK = true; + } + if (occupied->brakes.driverValve->GetPos(bh_EPR) - occupied->brakes.driverValve->GetPos(bh_EPN) < 0.1) { + OK = OK || occupied->SwitchEPBrake(1); + } + } + if( !OK ) { + OK = occupied->DecLocalBrakeLevel( 2 ); + } + break; + } + default: { + break; + } + } + return OK; +} + +void TController::LapBrake() { + + if( occupied->brakes.driverValve->TimeEP ) { + if( occupied->brakes.driverValve->GetPos( bh_EPR ) - occupied->brakes.driverValve->GetPos( bh_EPN ) < 0.1 ) { + occupied->SwitchEPBrake( 0 ); + } + else { + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_EPN ) ); + } + } +} + +void TController::ZeroLocalBrake() { + + if( occupied->UniCtrlIntegratedLocalBrakeCtrl() ) { + while( DecBrakeEIM() ) { + ; + } + } + else { + occupied->DecLocalBrakeLevel( LocalBrakePosNo ); + } +} + +bool TController::DecBrakeEIM() +{ // zmniejszenie siły hamowania + bool OK = false; + switch (occupied->EIMCtrlType) + { + case 0: { + if( occupied->brakes.blending.maxDeceleration != 9.81 ) { + auto const desiredacceleration { ( occupied->Vel > EU07_AI_NOMOVEMENT ? AccDesired : std::max( 0.0, AccDesired ) ) }; + auto const brakeposition { std::clamp( -1.0 * occupied->AIHintLocalBrakeAccFactor() * desiredacceleration / occupied->brakes.blending.maxDeceleration, 0.0, 1.0 ) }; + OK = brakeposition != occupied->brakes.IndependentPosition(); + occupied->brakes.SetIndependentPosition(brakeposition); + } + else { + OK = occupied->DecLocalBrakeLevel( 1 ); + } + break; + } + case 1: { + OK = occupied->MainCtrlPos() < 2; + if( OK ) + occupied->SetMainCtrlPos(2); + break; + } + case 2: { + auto const neutralpos{occupied->MainCtrlNoPowerPos()}; + OK = occupied->MainCtrlPos() < neutralpos; + if( OK ) + occupied->SetMainCtrlPos(neutralpos); + break; + } + case 3: { + OK = occupied->MainCtrlPos() < occupied->MainCtrlMaxDirChangePos(); + if( OK ) + occupied->SetMainCtrlPos(occupied->MainCtrlMaxDirChangePos()); + break; + } + } + return OK; +} + +bool TController::IncSpeed() +{ // zwiększenie prędkości; zwraca false, jeśli dalej się nie da zwiększać + auto OK { false }; + switch (occupied->EngineType) + { + case TEngineType::None: // McZapkie-041003: wagon sterowniczy + if (mvControlling->MainCtrlPosNo > 0) // jeśli ma czym kręcić + drivingFlags.incSpeed = true; // ustawienie flagi jazdy + return false; + case TEngineType::ElectricSeriesMotor: + if (pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) // jeśli pantografujący + { + if (fOverhead2 >= 0.0) // a jazda bezprądowa ustawiana eventami (albo opuszczenie) + return false; // to nici z ruszania + if (iOverheadZero) // jazda bezprądowa z poziomu toru ustawia bity + return false; // to nici z ruszania + } + // TODO: move all fVoltage assignments to a single, more generic place + if( mvControlling->EnginePowerSource.SourceType == TPowerSource::Accumulator ) { + fVoltage = mvControlling->lowVoltage.BatteryVoltage(); + } + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.PressureSwitchTripped() && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.IsClosed()) && (Ready || drivingFlags.press)) { + // youBy polecił dodać 2012-09-08 v367 + // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) + auto const usehighoverloadrelaythreshold{mvControlling->TrainType() != train_type::et42 // ET42 uses these variables for different purpose. TODO: fix this + && mvControlling->ImaxHi() > mvControlling->ImaxLo() && occupied->Vel < (mvControlling->IsMotorOverloadRelayHighThresholdOn() ? 30.0 : 20.0) && + iVehicles - ControlledEnginesCount > 0 + // && ( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) + && mvControlling->Imax * mvControlling->EngineVoltage * ControlledEnginesCount / + (fMass * (fAccGravity == 0.025 ? -0.01 : // prevent div/0 + fAccGravity - 0.025)) < + -2.8}; + // use series mode: + // if high threshold is set for motor overload relay, + // if the power station is heavily burdened, + // if it generates enough traction force + // to build up speed to 30/40 km/h for passenger/cargo train (10 km/h less if going uphill) + auto const sufficienttractionforce{std::abs(mvControlling->Ft()) * ControlledEnginesCount > (IsHeavyCargoTrain ? 75 : 50) * 1000.0}; + auto const sufficientacceleration{AbsAccS >= (IsHeavyCargoTrain ? 0.03 : IsCargoTrain ? 0.06 : 0.09)}; + auto const seriesmodefieldshunting{mvControlling->ScndCtrlPos() > 0 && mvControlling->RList[mvControlling->MainCtrlPos()].Bn == 1}; + auto const parallelmodefieldshunting{mvControlling->ScndCtrlPos() > 0 && mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1}; + auto const minvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MinV : 0.0)}; + auto const maxvoltage{(pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ? pantographUnit->EnginePowerSource.CollectorParameters.MaxV : 0.0)}; + auto const seriesmodevoltage{std::lerp(minvoltage, maxvoltage, IsHeavyCargoTrain ? 0.35 : 0.40)}; + auto const useseriesmode = mvControlling->Imax > mvControlling->ImaxLo() || true == usehighoverloadrelaythreshold || fVoltage < seriesmodevoltage || + (true == sufficientacceleration && true == sufficienttractionforce && + occupied->Vel <= (IsCargoTrain ? 40 : 30) + (seriesmodefieldshunting ? 5 : 0) - (fAccGravity < -0.025 ? 10 : 0)); + // when not in series mode use the first available parallel mode configuration until 50/60 km/h for passenger/cargo train + // (if there's only one parallel mode configuration it'll be used regardless of current speed) + auto const usefieldshunting = mvControlling->lineContactors.IsClosed() && mvControlling->RList[mvControlling->MainCtrlPos()].R < 0.01 && false == mvControlling->IsScndCtrlLockedByMainCtrl() && + (useseriesmode ? mvControlling->RList[mvControlling->MainCtrlPos()].Bn == 1 : + true == sufficientacceleration && true == sufficienttractionforce && occupied->Vel <= (IsCargoTrain ? 60 : 50) + (parallelmodefieldshunting ? 5 : 0) ? + mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1 : + mvControlling->MainCtrlPos() == mvControlling->MainCtrlPosNo); + + // if needed enable high threshold for overload relay... + if (mvControlling->TrainType() != train_type::et42) + { // ET42 uses these variables for different purpose. TODO: fix this + if (usehighoverloadrelaythreshold) + { + if (mvControlling->Imax < mvControlling->ImaxHi()) + { + // to enable this setting we'll typically need the main controller in series mode (which is not guaranteed) + if (mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1) + { + if (false == mvControlling->IsScndCtrlNoPowerPos()) + { + mvControlling->DecScndCtrl(2); + } + while (false == mvControlling->IsMainCtrlNoPowerPos() && mvControlling->RList[mvControlling->MainCtrlPos()].Bn > 1) + { + mvControlling->DecMainCtrl(1); // kręcimy nastawnik jazdy o 1 wstecz + } + } + mvControlling->CurrentSwitch(true); // rozruch wysoki (za to może się ślizgać) + } + } + // ...or disable high threshold for overload relay if no longer needed + else + { + if (mvControlling->IsMotorOverloadRelayHighThresholdOn() && std::fabs(mvControlling->Im) < mvControlling->ImaxLo()) + { + mvControlling->CurrentSwitch(false); // rozruch wysoki wyłącz + } + } + } + + double Vs = 99999; + if (usefieldshunting ? mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo() : mvControlling->MainCtrlPos() < mvControlling->MainCtrlPosNo) + { + Vs = ESMVelocity(!usefieldshunting); + } + + if (std::abs(mvControlling->Im) < (fReady < 0.4 ? mvControlling->Imin() : mvControlling->IminLo) || mvControlling->Vel > Vs) + { + // Ra: wywalał nadmiarowy, bo Im może być ujemne; jak nie odhamowany, to nie przesadzać z prądem + if (usefieldshunting) + { + // to dać bocznik + // engage the shuntfield only if there's sufficient power margin to draw from + auto const sufficientpowermargin{fVoltage - seriesmodevoltage > (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; + + OK = sufficientpowermargin ? mvControlling->IncScndCtrl(1) : true; + } + else + { + // jeśli ustawiony bocznik to bocznik na zero po chamsku + if (mvControlling->ScndCtrlPos()) + { + mvControlling->DecScndCtrl(2); + } + // kręcimy nastawnik jazdy + // don't draw too much power; + // keep from dropping into series mode when entering/using parallel mode, and from shutting down in the series mode + auto const sufficientpowermargin{fVoltage - + (mvControlling->RList[std::min(mvControlling->MainCtrlPos() + 1, mvControlling->MainCtrlPosNo)].Bn == 1 ? minvoltage : seriesmodevoltage) > + (IsHeavyCargoTrain ? 100.0 : 75.0) * ControlledEnginesCount}; + + OK = sufficientpowermargin && false == mvControlling->DelayCtrlFlag() ? mvControlling->IncMainCtrl(1) : true; + // czekaj na 1 pozycji, zanim się nie włączą liniowe + if (true == mvControlling->lineContactors.IsClosed()) + { + drivingFlags.incSpeed = true; + } + else + { + drivingFlags.incSpeed = false; + } + + if (mvControlling->Im == 0 && mvControlling->MainCtrlPowerPos() > 1) + { + // brak prądu na dalszych pozycjach + // nie załączona lokomotywa albo wywalił nadmiarowy + Need_TryAgain = true; + } + } + } + else + { + OK = false; + } + } +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + break; + case TEngineType::Dumb: + if (!IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press)) + //{(BrakePress<=0.01*MaxBrakePress)} + { + OK = IncSpeedEIM(); + if (!OK) + OK = mvControlling->IncMainCtrl(1); + if (!OK) + OK = mvControlling->IncScndCtrl(1); + } + break; + case TEngineType::DieselElectric: + if (!IsAnyMotorOverloadRelayOpen && !mvControlling->protection.PressureSwitchTripped() && (mvControlling->IsMainCtrlNoPowerPos() || mvControlling->lineContactors.IsClosed()) && (Ready || drivingFlags.press)) { + // youBy polecił dodać 2012-09-08 v367 + // na pozycji 0 przejdzie, a na pozostałych będzie czekać, aż się załączą liniowe (zgaśnie DelayCtrlFlag) + //{(BrakePress<=0.01*MaxBrakePress)} + OK = IncSpeedEIM(); + if (!OK) + OK = mvControlling->IncMainCtrl(1); + if (!OK) + OK = mvControlling->IncScndCtrl(1); + } + break; + case TEngineType::ElectricInductionMotor: + if( !IsAnyMotorOverloadRelayOpen && (Ready || drivingFlags.press || occupied->ShuntMode) ) { + //{(BrakePress<=0.01*MaxBrakePress)} + OK = IncSpeedEIM(); + if (mvControlling->SpeedCtrl() && mvControlling->lineBreaker.IsClosed()) + { + // cruise control + auto const couplinginprogress{true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect)}; + auto const SpeedCntrlVel{(ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? VelDesired : min_speed(VelDesired, VelNext))}; + if (SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity && + SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep)) + { + SpeedCntrl(SpeedCntrlVel); + } + else if (SpeedCntrlVel > 0.1) + { + SpeedCntrl(0.0); + mvControlling->DecScndCtrl(2); + } + } + } + break; + case TEngineType::WheelsDriven: + if (!mvControlling->CabActive) + mvControlling->CabActivisation(); + if (sin(mvControlling->eAngle()) > 0) + mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + else + mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + break; + case TEngineType::DieselEngine: + if (mvControlling->ShuntModeAllow) + { // dla 2Ls150 można zmienić tryb pracy, jeśli jest w liniowym i nie daje rady (wymaga zerowania kierunku) + // mvControlling->ShuntMode=(OrderList[OrderPos]&Shunt)||(fMass>224000.0); + } + if (mvControlling->SpeedCtrl() && mvControlling->lineBreaker.IsClosed()) {// cruise control + auto const couplinginprogress { true == drivingFlags.connect && true == OrderCurrentGet().HasAll(DriverOrder::connect) }; + auto const SpeedCntrlVel { ( + ActualProximityDist > std::max(50.0, fMaxProximityDist) || couplinginprogress ? + VelDesired : + min_speed( VelDesired, VelNext ) ) }; + if( SpeedCntrlVel >= mvControlling->SpeedCtrlUnit.MinVelocity + && SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity == quantize(SpeedCntrlVel - mvControlling->SpeedCtrlUnit.MinVelocity, mvControlling->SpeedCtrlUnit.VelocityStep) ) { + SpeedCntrl(SpeedCntrlVel); + } + else if (SpeedCntrlVel > 0.1) { + SpeedCntrl(0.0); + mvControlling->DecScndCtrl( 2 ); + } + } + if (mvControlling->EIMCtrlType > 0) { + if (true == Ready) + { + bool max = mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity + || (mvControlling->SpeedCtrl() && mvControlling->ScndCtrlPos() > 0); + DizelPercentage = max ? 100 : 1; + } + break; + } + else { + if( true == Ready ) { + if( mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity + && mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 ) { + OK = mvControlling->IncMainCtrl( 1 ); + } + if( mvControlling->RList[ mvControlling->MainCtrlPos() ].Mn == 0 ) { + OK = mvControlling->IncMainCtrl( 1 ); + } + } + } + // TODO: move this check to a more suitable place, or scrap it + if( false == mvControlling->lineBreaker.IsClosed() ) { + SpeedCntrl(0.0); + mvControlling->DecScndCtrl( 2 ); + cue_action( driver_hint::linebreakerclose ); + cue_action( driver_hint::converteron ); + cue_action( driver_hint::compressoron ); + } + break; + } + return OK; +} + +void TController::ZeroSpeed( bool const Enforce ) { + + while( DecSpeed( Enforce ) ) { + ; + } +} + +bool TController::DecSpeed(bool force) +{ // zmniejszenie prędkości (ale nie hamowanie) + bool OK = false; // domyślnie false, aby wyszło z pętli while + switch (occupied->EngineType) + { + case TEngineType::None: // McZapkie-041003: wagon sterowniczy + drivingFlags.incSpeed = false; // usunięcie flagi jazdy + if (force && mvControlling->MainCtrlPosNo > 0) // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania + // McZapkie-041003: wagon sterowniczy, np. EZT + mvControlling->DecMainCtrl(std::min(mvControlling->MainCtrlPowerPos(), 2)); + // mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + return false; + case TEngineType::ElectricSeriesMotor: + OK = mvControlling->DecScndCtrl(2); // najpierw bocznik na zero + if (!OK) + OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 ) ); +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + break; + case TEngineType::Dumb: + case TEngineType::DieselElectric: + OK = mvControlling->DecScndCtrl(2); + if (!OK) + OK = mvControlling->DecMainCtrl( std::min( mvControlling->MainCtrlPowerPos(), 2 + mvControlling->MainCtrlPowerPos() / 2 ) ); + break; + case TEngineType::ElectricInductionMotor: + OK = DecSpeedEIM(); + break; + case TEngineType::WheelsDriven: + if (!mvControlling->CabActive) + mvControlling->CabActivisation(); + if (sin(mvControlling->eAngle()) < 0) + mvControlling->IncMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + else + mvControlling->DecMainCtrl(3 + 3 * floor(0.5 + fabs(AccDesired))); + break; + case TEngineType::DieselEngine: + if (mvControlling->EIMCtrlType > 0) + { + DizelPercentage = 0; + if (force) { + SpeedCntrl(0.0); //wylacz od razu tempomat + mvControlling->DecScndCtrl(2); + } + if (VelDesired > 0.1 && mvControlling->SpeedCtrlUnit.MinVelocity > VelDesired) { + SpeedCntrl(0.0); //wylacz od razu tempomat + mvControlling->DecScndCtrl(2); + } + break; + } + + if (mvControlling->Vel > mvControlling->diesel.fullEngageMinVelocity) + { + if (mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0) + OK = mvControlling->DecMainCtrl(1); + } + else { + while( mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 + && mvControlling->MainCtrlPowerPos() > 1 ) { + OK = mvControlling->DecMainCtrl( 1 ); + } + } + if (force) { // przy aktywacji kabiny jest potrzeba natychmiastowego wyzerowania + OK = mvControlling->DecMainCtrl(mvControlling->MainCtrlPowerPos() > 2 ? 2 : 1); + SpeedCntrl(0.0); //wylacz od razu tempomat + mvControlling->DecScndCtrl( 2 ); + } + break; + } + return OK; +}; + +bool TController::IncSpeedEIM() { + + bool OK = false; // domyślnie false, aby wyszło z pętli while + switch( mvControlling->EIMCtrlType ) { + case 0: + OK = mvControlling->IncMainCtrl( 1 ); + break; + case 1: + OK = mvControlling->MainCtrlPos() < 6; + if( OK ) { + mvControlling->SetMainCtrlPos(6); + } +/* + // TBD, TODO: set position based on desired acceleration? + OK = mvControlling->MainCtrlPos() < mvControlling->MainCtrlPosNo; + if( OK ) { + mvControlling->SetMainCtrlPos(safe_clamp( mvControlling->MainCtrlPos() + 1, 6, mvControlling->MainCtrlPosNo )); + } +*/ + break; + case 2: { + auto const powerpos{4 + mvControlling->EIMCtrlEmergencyPositions()}; + OK = mvControlling->MainCtrlPos() < powerpos; + if( OK ) { + mvControlling->SetMainCtrlPos(powerpos); + } + break; + } + } + return OK; +} + +bool TController::DecSpeedEIM( int const Amount ) +{ // zmniejszenie prędkości (ale nie hamowanie) + bool OK = false; // domyślnie false, aby wyszło z pętli while + switch( mvControlling->EIMCtrlType ) { + case 0: { + OK = mvControlling->DecMainCtrl( Amount ); + break; + } + case 1: { + OK = mvControlling->MainCtrlPos() > 4; + if( OK ) { + mvControlling->SetMainCtrlPos(4); + } + break; + } + case 2: { + if( AccDesired > 0 + && mvControlling->SpeedCtrlUnit.IsActive + && mvControlling->SpeedCtrlUnit.PowerStep > 0 + && mvControlling->SpeedCtrlUnit.DesiredPower > mvControlling->SpeedCtrlUnit.MinPower ) { + mvControlling->SpeedCtrlPowerDec(); + } + else { + auto const holdpos{2 + mvControlling->EIMCtrlEmergencyPositions()}; + OK = mvControlling->MainCtrlPos() > holdpos; + if( OK ) { + mvControlling->SetMainCtrlPos(holdpos); + } + } + break; + } + default: { + break; + } + } + return OK; +} + +void TController::BrakeLevelSet(double b) +{ // ustawienie pozycji hamulca na wartość (b) w zakresie od -2 do BrakeCtrlPosNo + // jedyny dopuszczalny sposób przestawienia hamulca zasadniczego + if (BrakeCtrlPosition == b) + return; // nie przeliczać, jak nie ma zmiany + BrakeCtrlPosition = std::clamp(b, (double)gbh_MIN, (double)gbh_MAX); + fBrakeHeldTime = 0.0; +} + +bool TController::BrakeLevelAdd(double b) +{ // dodanie wartości (b) do pozycji hamulca (w tym ujemnej) + // zwraca false, gdy po dodaniu było by poza zakresem + BrakeLevelSet(BrakeCtrlPosition + b); + return b > 0.0 ? BrakeCtrlPosition < gbh_MAX : + BrakeCtrlPosition > -1.0; // true, jeśli można kontynuować +} + +// Ra: regulacja prędkości, wykonywana w każdym przebłysku świadomości AI +// ma dokręcać do bezoporowych i zdejmować pozycje w przypadku przekroczenia prądu +void TController::SpeedSet() { + + if( false == aiControlled ) { return; } + + switch (occupied->EngineType) + { + case TEngineType::None: { // McZapkie-041003: wagon sterowniczy + if (mvControlling->MainCtrlPosNo > 0) + { // jeśli ma czym kręcić + // TODO: sprawdzanie innego czlonu //if (!FuseFlagCheck()) + if( ( false == drivingFlags.incSpeed ) ) { + // przetok rozłączać od razu (no dependency on fActionTime) + while( mvControlling->MainCtrlPos() + && mvControlling->DecMainCtrl(1) ) { + ; // na zero + } + if( fActionTime >= 0.0 ) { + fActionTime = -5.0; // niech trochę potrzyma + } +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + } + else { + // jak ma jechać + if( fActionTime < 0.0 ) { break; } + if( false == Ready ) { break; } + + if( occupied->DirActive > 0 ) { + occupied->DirectionForward(); //żeby EN57 jechały na drugiej nastawie + } + + if( mvControlling->MainCtrlPos() > 0 + && false == mvControlling->lineContactors.IsClosed() ) { + // jak niby jedzie, ale ma rozłączone liniowe to na zero i czekać na przewalenie kułakowego + mvControlling->DecMainCtrl( 2 ); + } + else { + // ruch nastawnika uzależniony jest od aktualnie ustawionej pozycji + switch( mvControlling->MainCtrlPos() ) { + case 0: + if( mvControlling->MainCtrlActualPos ) { + // jeśli kułakowy nie jest wyzerowany to czekać na wyzerowanie + break; + } + mvControlling->IncMainCtrl( 1 ); // przetok; bez "break", bo nie ma czekania na 1. pozycji + case 1: + if( VelDesired >= 20 ) + mvControlling->IncMainCtrl( 1 ); // szeregowa + case 2: + if( VelDesired >= 50 ) + mvControlling->IncMainCtrl( 1 ); // równoległa + case 3: + if( VelDesired >= 80 ) + mvControlling->IncMainCtrl( 1 ); // bocznik 1 + case 4: + if( VelDesired >= 90 ) + mvControlling->IncMainCtrl( 1 ); // bocznik 2 + case 5: + if( VelDesired >= 100 ) + mvControlling->IncMainCtrl( 1 ); // bocznik 3 + } + } + if( mvControlling->MainCtrlPos() ) // jak załączył pozycję + { + fActionTime = -5.0; // niech trochę potrzyma +// mvControlling->AutoRelayCheck(); // sprawdzenie logiki sterowania + } + } + } + break; + } + case TEngineType::ElectricSeriesMotor: { +/* + if (Ready || (drivingFlags.press)) { // o ile może jechać +// if (fAccGravity < -0.10) // i jedzie pod górę większą niż 10 promil + { // procedura wjeżdżania na ekstremalne wzniesienia + if( std::fabs( mvControlling->Im ) > 0.85 * mvControlling->Imax ) { // a prąd jest większy niż 85% nadmiarowego + if( mvControlling->Imax * mvControlling->EngineVoltage / ( fMass * fAccGravity ) < -2.8 ) // a na niskim się za szybko nie pojedzie + { // włączenie wysokiego rozruchu; + // (I*U)[A*V=W=kg*m*m/sss]/(m[kg]*a[m/ss])=v[m/s]; 2.8m/ss=10km/h + if( mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1 ) { // jeśli jedzie na równoległym, to zbijamy do szeregowego, aby włączyć wysoki rozruch + if( mvControlling->ScndCtrlPos() > 0 ) { // jeżeli jest bocznik + mvControlling->DecScndCtrl( 2 ); // wyłączyć bocznik, bo może blokować skręcenie NJ + } + do { // skręcanie do bezoporowej na szeregowym + mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz + } + while( ( false == mvControlling->IsMainCtrlNoPowerPos() ) + && ( mvControlling->RList[ mvControlling->MainCtrlPos() ].Bn > 1 ) ); // oporowa zapętla + } + if( mvControlling->Imax < mvControlling->ImaxHi() ) { // jeśli da się na wysokim + mvControlling->CurrentSwitch( true ); // rozruch wysoki (za to może się ślizgać) + } + if( ReactionTime > 0.1 ) { + ReactionTime = 0.1; // orientuj się szybciej + } + } // if (Im>Imin) + } + if( std::fabs( mvControlling->Im ) > 0.96 * mvControlling->Imax ) {// jeśli prąd jest duży (można 690 na 750) + if( mvControlling->ScndCtrlPos() > 0 ) { // jeżeli jest bocznik + mvControlling->DecScndCtrl( 2 ); // zmniejszyć bocznik + } + else { + mvControlling->DecMainCtrl( 1 ); // kręcimy nastawnik jazdy o 1 wstecz + } + } + } +// else // gdy nie jedzie ambitnie pod górę + { // sprawdzenie, czy rozruch wysoki jest potrzebny + if( ( mvControlling->Imax > mvControlling->ImaxLo() ) + && ( occupied->Vel >= 30.0 ) ) { // jak się rozpędził +// if (fAccGravity > -0.02) // a i pochylenie mnijsze niż 2‰ + mvControlling->CurrentSwitch( false ); // rozruch wysoki wyłącz + } + } + } +*/ + break; + } + case TEngineType::Dumb: { + break; + } + case TEngineType::DieselElectric: { + break; + } + case TEngineType::ElectricInductionMotor: { + break; + } + case TEngineType::DieselEngine: { + // Ra 2014-06: "automatyczna" skrzynia biegów... + auto const &motorparams { mvControlling->MotorParam[ mvControlling->ScndCtrlPos() ] }; + auto const velocity { ( mvControlling->ShuntMode ? mvControlling->AnPos() : 1.0 ) * mvControlling->Vel }; + if( false == motorparams.AutoSwitch ) { + // gdy biegi ręczne + // jak prędkość większa niż procent maksymalnej na danym biegu, wrzucić wyższy + if( velocity > 0.75 * motorparams.mfi ) { + // ...presuming there is a higher gear + if( mvControlling->ScndCtrlPos() < mvControlling->ScndCtrlPosNo() ) { + mvControlling->DecMainCtrl( 2 ); + while( mvControlling->IncScndCtrl(1) + && mvControlling->MotorParam[mvControlling->ScndCtrlPos()].mIsat == 0.0 ) { // jeśli bieg jałowy to kolejny + ; + } + } + } + // jak prędkość mniejsza niż minimalna na danym biegu, wrzucić niższy + else if( velocity < motorparams.fi && mvControlling->ScndCtrlPos() > 1 ) { + // ... but ensure we don't switch all way down to 0 + mvControlling->DecMainCtrl(2); + while (mvControlling->ScndCtrlPos() > 1 // repeat the entry check as we're working in a loop + && mvControlling->DecScndCtrl(1) && mvControlling->MotorParam[mvControlling->ScndCtrlPos()].mIsat == 0.0) + { // jeśli bieg jałowy to kolejny + ; + } + } + } + break; + } + default: { + break; + } + } // enginetype +}; + +void TController::SpeedCntrl(double DesiredSpeed) +{ + if( false == mvControlling->SpeedCtrl() ) { return; } + + if (mvControlling->IsSpeedCtrlSeparate()) + { + // a switch of its own, the secondary controller left to the field shunting (eu07/maszyna#69) + if (DesiredSpeed < 0.1) { + DesiredSpeed = 0; + } + mvControlling->SpeedCtrlSwitch(DesiredSpeed > 0); + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); + } + else if (mvControlling->EngineType == TEngineType::DieselEngine) + { + if (DesiredSpeed < 0.1) { + mvControlling->DecScndCtrl(2); + DesiredSpeed = 0; + } + else if (mvControlling->ScndCtrlPos() < 1) { + mvControlling->IncScndCtrl(1); + } + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); + } + else + if (mvControlling->ScndCtrlPosNo() == 1) + { + mvControlling->IncScndCtrl(1); + mvControlling->RunCommand(VehicleCommand::speedControl, DesiredSpeed, mvControlling->CabActive); + } + else if (mvControlling->ScndCtrlPosNo() > 1 && !occupied->SpeedCtrlTypeTime()) + { + int DesiredPos = 1 + mvControlling->ScndCtrlPosNo() * ((DesiredSpeed - 1.0) / mvControlling->Vmax()); + while( mvControlling->ScndCtrlPos() > DesiredPos && true == mvControlling->DecScndCtrl(1) ) { ; } // all work is done in the condition loop + while( mvControlling->ScndCtrlPos() < DesiredPos && true == mvControlling->IncScndCtrl(1) ) { ; } // all work is done in the condition loop + } + + if( mvControlling->SpeedCtrlUnit.PowerStep > 0 && mvControlling->IsSpeedCtrlEngaged() ) { + while (mvControlling->SpeedCtrlUnit.DesiredPower < mvControlling->SpeedCtrlUnit.MaxPower) + { + mvControlling->SpeedCtrlPowerInc(); + } + } +}; + +void TController::SetTimeControllers() +{ + // TBD, TODO: rework this method to use hint system and regardless of driver type + if( false == aiControlled || 0 == occupied->CabActive ) { return; } + + //1. Check the type of Main Brake Handle + if( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) + { + if (occupied->brakes.driverValve->Time) + { + auto const pressuredifference { occupied->brakes.driverValve->GetCP() - ( occupied->brakes.config.pipeHighPressure - BrakeCtrlPosition * 0.25*occupied->brakes.config.pipePressureRange ) }; + if (BrakeCtrlPosition > 0 && pressuredifference > 0.05) + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_FB)); + else if (BrakeCtrlPosition > 0 && pressuredifference < -0.05) + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_RP)); + else if (BrakeCtrlPosition == 0) + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_RP)); + else if (BrakeCtrlPosition == -1) + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_FS)); + else if (BrakeCtrlPosition == -2) + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_NP)); + } + if( occupied->brakes.config.driverValveType == TBrakeHandle::FV4a ) { + occupied->BrakeLevelSet( BrakeCtrlPosition ); + } + if( occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_EN57 ) { + if( BrakeCtrlPosition == 0 ) { + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_RP ) ); + } + else if( BrakeCtrlPosition == -1 ) { + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_FS ) ); + } + else if( BrakeCtrlPosition == -2 ) { + occupied->BrakeLevelSet( occupied->brakes.driverValve->GetPos( bh_NP ) ); + } + else if( BrakeCtrlPosition > 4.5 ) { + occupied->BrakeLevelSet( 10 ); + } + else if( BrakeCtrlPosition > 3.70 ) { + occupied->BrakeLevelSet( 9 ); + } + else { + occupied->BrakeLevelSet( round( ( BrakeCtrlPosition * 0.4 - 0.1 ) / 0.15 ) ); + } + } + } + //2. Check the type of Secondary Brake Handle + + //3. Check the type od EIMCtrlType +/* + if (occupied->EIMCtrlType > 0) + { + if (occupied->EIMCtrlType == 1) //traxx + { + if (occupied->LocalBrakePosA > 0.95) occupied->SetMainCtrlPos(0); + } + else if (occupied->EIMCtrlType == 2) //elf + { + if (occupied->LocalBrakePosA > 0.95) occupied->SetMainCtrlPos(1); + } + } +*/ + if( occupied->UniCtrlIntegratedLocalBrakeCtrl() + && occupied->brakes.IndependentPosition() > 0.95 ) { + while( IncBrakeEIM() ) { ; } + } + + //4. Check Speed Control System + if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo() > 1 && occupied->SpeedCtrlTypeTime()) + { + double SpeedCntrlVel = + ActualProximityDist > std::max(50.0, fMaxProximityDist) ? + VelDesired : + min_speed(VelDesired, VelNext); + SpeedCntrlVel = 10 * std::floor(SpeedCntrlVel*0.1); + if (occupied->ScndCtrlPosNo() == 4) + { + if (occupied->NewSpeed() + 0.1 < SpeedCntrlVel) + occupied->SetScndCtrlPos(3); + if (occupied->NewSpeed() - 0.1 > SpeedCntrlVel) + occupied->SetScndCtrlPos(1); + } + } + //5. Check Main Controller in Dizels + //5.1. Digital controller in DMUs with hydro + if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) + { + + DizelPercentage_Speed = DizelPercentage; //wstepnie procenty + auto MinVel{ std::min(mvControlling->torqueConverter.lockupSpeed, mvControlling->Vmax() / 6) }; //minimal velocity + //when speed controll unit is active - start with the procedure + if (mvControlling->SpeedCtrl() && mvControlling->ScndCtrlPos() > 0) { + if (mvControlling->ScndCtrlPos() > 0 && mvControlling->Vel < 1 + mvControlling->SpeedCtrlUnit.StartVelocity && DizelPercentage > 0) + DizelPercentage_Speed = 101; //keep last position to start + } + else if (VelDesired > MinVel) //more power for faster ride + { + auto const Factor{ 10 * mvControlling->Vmax() / (mvControlling->Vmax() + 3 * mvControlling->Vel) }; + auto DesiredPercentage{ std::clamp( + VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0, + 0.0, 1.0) }; //correction for reaching desired velocity + if (VelDesired < 0.5 * mvControlling->Vmax() //low velocity and reaching desired + && VelDesired - mvControlling->Vel < 10) { + DesiredPercentage = std::min(DesiredPercentage, 0.75); + } + DizelPercentage_Speed = std::round(DesiredPercentage * DizelPercentage); + } + else //slow acceleration during shunting wth minimal velocity + { + DizelPercentage_Speed = std::min(DizelPercentage, mvControlling->Vel < 0.99 * VelDesired ? 1 : 0); + } + + auto const DizelActualPercentage { int(100.4 * mvControlling->EimicReal()) }; + + auto const PosInc { mvControlling->MainCtrlPosNo }; + auto PosDec { 0 }; + for( int i = PosInc; i >= 0; --i ) { + if( mvControlling->UniCtrlList[i].SetCtrlVal <= 0 + && mvControlling->UniCtrlList[i].SpeedDown > 0.01 ) { + PosDec = i; + break; + } + } + + if( std::abs( DizelPercentage_Speed - DizelActualPercentage ) > 0 ) { + + if( PosDec > 0 + && ( DizelActualPercentage - DizelPercentage_Speed > 50 + || ( DizelPercentage_Speed == 0 + && DizelActualPercentage > 10 ) ) ) { + //one position earlier should be fast decreasing + PosDec -= 1; + } + auto const DesiredPos { ( + DizelPercentage_Speed > DizelActualPercentage ? + PosInc : + PosDec ) }; + while( mvControlling->MainCtrlPos() > DesiredPos ) { mvControlling->DecMainCtrl( 1 ); } + while( mvControlling->MainCtrlPos() < DesiredPos ) { mvControlling->IncMainCtrl( 1 ); } + } + if (BrakeCtrlPosition < 0.1) //jesli nie hamuje + occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos()].mode); //zeby nie bruzdzilo machanie zespolonym + } + else + //5.2. Analog direct controller + if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->Vmax() > 30) + { + int MaxPos = mvControlling->MainCtrlPosNo; + int MinPos = MaxPos; + for (int i = MaxPos; i > 1 && mvControlling->RList[i].Mn > 0; i--) MinPos = i; + if (MaxPos > MinPos && mvControlling->MainCtrlPos() > 0 && AccDesired > 0) + { + double Factor = 5 * mvControlling->Vmax() / (mvControlling->Vmax() + mvControlling->Vel); + int DesiredPos = MinPos + (MaxPos - MinPos)*(VelDesired > mvControlling->Vel ? (VelDesired - mvControlling->Vel) / Factor : 0); + if (DesiredPos > MaxPos) DesiredPos = MaxPos; + if (DesiredPos < MinPos) DesiredPos = MinPos; + if (!mvControlling->SlippingWheels()) + { + while (mvControlling->MainCtrlPos() > DesiredPos) mvControlling->DecMainCtrl(1); + if (mvControlling->Vel>mvControlling->diesel.fullEngageMinVelocity) + while (mvControlling->MainCtrlPos() < DesiredPos) mvControlling->IncMainCtrl(1); + } + } + } + // 5.5 universal control for diesel electric vehicles + if (mvControlling->EngineType == TEngineType::DieselElectric && mvControlling->EIMCtrlType == 3 && AccDesired >= 0.0 && mvControlling->lineContactors.IsClosed()) + { + // NOTE: partial implementation for speedinc/dec + // TBD, TODO: implement fully? + auto const PosInc{mvControlling->MainCtrlPosNo}; + auto PosKeep{0}; + auto PosDec{0}; + for (int i = PosInc; i >= 0; --i) + { + if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0) + { + if (mvControlling->UniCtrlList[i].SpeedDown == 0.0) + { + PosKeep = i; + } + if (mvControlling->UniCtrlList[i].SpeedDown > 0.01) + { + PosDec = i; + break; + } + } + } + + auto const DesiredPos{(AccDesired > AbsAccS + 0.05 ? PosInc : AccDesired < AbsAccS - 0.05 ? PosDec : PosKeep)}; + + while (mvControlling->MainCtrlPos() > DesiredPos && mvControlling->DecMainCtrl(1)) + { + ; + } + while (mvControlling->MainCtrlPos() < DesiredPos && mvControlling->IncMainCtrl(1)) + { + ; + } + } + //6. UniversalBrakeButtons + //6.1. Checking flags for Over pressure + if (std::abs(BrakeCtrlPosition - gbh_FS)<0.5) { + UniversalBrakeButtons |= TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload; + } + else { + UniversalBrakeButtons &= ~(TUniversalBrake::ub_HighPressure | TUniversalBrake::ub_Overload); + } + //6.2. Setting buttons + for (int i = 0; i < 3; i++) { + occupied->UniversalBrakeButton(i, UniversalBrakeButtons & occupied->brakes.config.universalButtonActions[i]); + } +}; + +void TController::CheckTimeControllers() +{ + // TODO: rework this method to use hint system and regardless of driver type + if( false == aiControlled || 0 == mvControlling->CabActive ) { return; } + + //1. Check the type of Main Brake Handle + if( BrakeSystem == TBrakeSystem::ElectroPneumatic && occupied->brakes.driverValve->TimeEP && !ForcePNBrake ) + { + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_EPN)); + } + if( ( BrakeSystem == TBrakeSystem::Pneumatic || ForcePNBrake ) && occupied->brakes.driverValve->Time ) + { + if (BrakeCtrlPosition > 0) + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_MB)); + else + occupied->BrakeLevelSet(occupied->brakes.driverValve->GetPos(bh_RP)); + } + //2. Check the type of Secondary Brake Handle + + //3. Check the type od EIMCtrlType + if (occupied->EIMCtrlType > 0) + { + if (occupied->EIMCtrlType == 1) //traxx + { + if (occupied->MainCtrlPos() > 3) occupied->SetMainCtrlPos(5); + if (occupied->MainCtrlPos() < 3) occupied->SetMainCtrlPos(1); + } + else if (occupied->EIMCtrlType == 2) //elf + { + auto const emergencypositions{occupied->EIMCtrlEmergencyPositions()}; + if (occupied->eimic > 0) occupied->SetMainCtrlPos(3 + emergencypositions); + if (occupied->eimic < 0) occupied->SetMainCtrlPos(2 + emergencypositions); + } + } + //4. Check Speed Control System + if (occupied->EngineType == TEngineType::ElectricInductionMotor && occupied->ScndCtrlPosNo() > 1 && occupied->SpeedCtrlTypeTime() && occupied->ScndCtrlPosNo() == 4) + { + occupied->SetScndCtrlPos(2); + } + + //5. Check Main Controller in Dizels + //5.1. Digital controller in DMUs with hydro + if (mvControlling->EngineType == TEngineType::DieselEngine && mvControlling->EIMCtrlType == 3) + { + int DizelActualPercentage = 100.4 * mvControlling->EimicReal(); + int NeutralPos = mvControlling->MainCtrlPosNo - 1; //przedostatnia powinna wstrzymywać - hipoteza robocza + for (int i = mvControlling->MainCtrlPosNo; i >= 0; i--) + if (mvControlling->UniCtrlList[i].SetCtrlVal <= 0 && mvControlling->UniCtrlList[i].SpeedDown < 0.01) //niby zero, ale nie zmniejsza procentów + { + NeutralPos = i; + break; + } + if (BrakeCtrlPosition < 0.1) //jesli nie hamuje + { + if (DizelActualPercentage >= DizelPercentage_Speed && mvControlling->MainCtrlPos() > NeutralPos) + while (mvControlling->MainCtrlPos() > NeutralPos) mvControlling->DecMainCtrl(1); + if (DizelActualPercentage <= DizelPercentage_Speed && mvControlling->MainCtrlPos() < NeutralPos) + while (mvControlling->MainCtrlPos() < NeutralPos) mvControlling->IncMainCtrl(1); + occupied->BrakeLevelSet(mvControlling->UniCtrlList[mvControlling->MainCtrlPos()].mode); //zeby nie bruzdzilo machanie zespolonym + } + } +}; diff --git a/vehicle/ai/doors.cpp b/vehicle/ai/doors.cpp new file mode 100644 index 000000000..2c6855409 --- /dev/null +++ b/vehicle/ai/doors.cpp @@ -0,0 +1,294 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the doors, the stops and the departure + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +// otwieranie/zamykanie drzwi w składzie albo (tylko AI) EZT +void TController::Doors( bool const Open, int const Side ) { + // otwieranie drzwi + if( true == Open ) { + + auto const lewe = pVehicle->DirectionGet() > 0 ? 1 : 2; + auto const prawe = 3 - lewe; + // doorsteps as the timetable asks, before the doors open (eu07/maszyna#95) + if( auto const doorstep { timetable::doorstep( m_stopflags ) }; + doorstep.has_value() && occupied->Doors.step_enabled != *doorstep ) { + cue_action( *doorstep ? driver_hint::doorstepon : driver_hint::doorstepoff ); + } + // grant door control permission if it's not automatic + // TBD: stricter requirements? + if( true == pVehicle->physics->Doors.permit_needed ) { + if( Side & prawe ) { + cue_action( driver_hint::doorrightpermiton ); + } + if( Side & lewe ) { + cue_action( driver_hint::doorleftpermiton ); + } + } + // consist-wide remote signals to open doors doors + // NOTE: mixed controls are left up to passengers to open doors by themselves, unless the timetable has + // the driver open all the doors + if( true == timetable::opens_doors( *pVehicle->physics, m_stopflags ) ) { + if( Side & prawe ) { + cue_action( driver_hint::doorrightopen ); + } + if( Side & lewe ) { + cue_action( driver_hint::doorleftopen ); + } + } + } + // zamykanie drzwi + else { + // if the doors are already closed and locked then there's nothing to do + if( false == doors_permit_active() + && false == doors_open() ) { + drivingFlags.doorOpened = false; + drivingFlags.departureWarned = false; + return; + } + + if (occupied->Doors.has_warning && !drivingFlags.departureWarned) + { + if (!occupied->DepartureSignal()) + { + // Not warned yet, not warning yet - start the warning signal. + cue_action( driver_hint::departuresignalon ); // załącenie bzyczka + fActionTime = Random( -0.8, -0.3 ); // 0.3-0.8 second buzzer + return; + } + // Not warned yet, warning now - stop the warning signal and mark it as done. + cue_action( driver_hint::departuresignaloff ); + fActionTime = Random( -0.2, 0.0 ); // Wait just a bit more before departing + drivingFlags.departureWarned = true; + return; + } + + if( true == doors_open() && (pVehicle->physics->Doors.close_control == control_t::conductor || pVehicle->physics->Doors.close_control == control_t::driver || + pVehicle->physics->Doors.close_control == control_t::mixed) ) { + // consist-wide remote signals to close doors + cue_action(driver_hint::doorrightclose); + cue_action(driver_hint::doorleftclose); + } + if( true == doors_permit_active() ) { + cue_action( driver_hint::doorrightpermitoff ); + cue_action( driver_hint::doorleftpermitoff ); + } + // if applicable close manually-operated doors in vehicles which may ignore remote signals + { + const auto *vehicle = pVehicles[ VehicleEnd::front ]; // pojazd na czole składu + while( vehicle != nullptr ) { + // zamykanie drzwi w pojazdach - flaga zezwolenia była by lepsza + auto const ismanualdoor { + vehicle->physics->Doors.auto_velocity == -1.f + && ( vehicle->physics->Doors.close_control == control_t::passenger + || vehicle->physics->Doors.close_control == control_t::mixed ) }; + + if( true == ismanualdoor + && ( vehicle->LoadExchangeTime() == 0.f + || vehicle->physics->Vel > EU07_AI_MOVEMENT ) ) { + vehicle->physics->OperateDoors( VehicleSide::right, false, range_t::local ); + vehicle->physics->OperateDoors( VehicleSide::left, false, range_t::local ); + } + vehicle = vehicle->Next(); // pojazd podłączony z tyłu (patrząc od czoła) + } + } + fActionTime = Random(-3.5, -1.0); // 1.0-3.5 sec wait + drivingFlags.doorOpened = false; // zostały zamknięte - nie wykonywać drugi raz + drivingFlags.departureWarned = false; + } +} + +// returns true if any vehicle in the consist has open doors +bool +TController::doors_open() const { + + return IsAnyDoorOpen[VehicleSide::right] || IsAnyDoorOpen[VehicleSide::left]; +} + +bool +TController::doors_permit_active() const { + + return IsAnyDoorPermitActive[VehicleSide::right] || IsAnyDoorPermitActive[VehicleSide::left]; +} + +void +TController::announce( announcement_t const Announcement ) { + + m_lastannouncement = Announcement; + + if( IsCargoTrain ) { + // cargo trains aren't likely to have announcement systems, so we can skip the procedure altogether + return; + } + + auto *vehicle { pVehicles[ VehicleEnd::front ] }; + while( vehicle ) { + vehicle->announce( Announcement ); + vehicle = vehicle->Next(); + } +} + +void +TController::control_doors() { + + if( false == doors_open() ) { return; } + // jeżeli jedzie + // nie zamykać drzwi przy drganiach, bo zatrzymanie na W4 akceptuje niewielkie prędkości + if( occupied->Vel > EU07_AI_MOVEMENT ) { + Doors( false ); + return; + } + // HACK: crude way to deal with automatic door opening on W4 preventing further ride + // for human-controlled vehicles with no door control and dynamic brake auto-activating with door open + // TODO: check if this situation still happens and the hack is still needed + if( false == aiControlled && (mvControlling->EngineType == TEngineType::DieselEngine ? mvControlling->RList[mvControlling->MainCtrlPos()].Mn > 0 : mvControlling->MainCtrlPowerPos() > 0) ) { + // for diesel engines react when engine is put past idle revolutions + // for others straightforward master controller check + Doors(false); + return; + } +} + +void +TController::check_departure() { + + if(false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect ) ) { return; } + // odjechać sam może tylko jeśli jest w trybie jazdy + // automatyczne ruszanie po odstaniu albo spod SBL + if( VelSignal == 0.0 + && WaitingTime > 0.0 + && occupied->RunningTrack.Velmax != 0.0 ) { + // jeśli stoi, a upłynął czas oczekiwania i tor ma niezerową prędkość + if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) + && drivingFlags.stopHere ) { + // zakaz ruszania z miejsca bez otrzymania wolnej drogi + WaitingTime = -WaitingExpireTime; + } + else { + if( occupied->CategoryFlag & 1 ) { // jeśli pociąg + PrepareDirection(); // zmieni ustawiony kierunek + SetVelocity( 20, 20 ); // jak się nastał, to niech jedzie 20km/h + WaitingTime = 0.0; + fWarningDuration = 1.5; // a zatrąbić trochę + } + else { // samochód ma stać, aż dostanie odjazd, chyba że stoi przez kolizję + if( eStopReason == stopBlock + && Obstacle.distance > fDriverDist ) { + PrepareDirection(); // zmieni ustawiony kierunek + SetVelocity( -1, -1 ); // jak się nastał, to niech jedzie + WaitingTime = 0.0; + } + } + } + } + else if( VelSignal == 0.0 && VelNext > 0.0 && occupied->Vel < 1.0 && (false == iCoupler.Empty() || ( false == drivingFlags.stopHere )) ) { + // Ra: tu jest coś nie tak, bo bez tego warunku ruszało w manewrowym !!!! + SetVelocity(VelNext, VelNext, stopSem); // omijanie SBL + } +} + +// verify progress of load exchange +void +TController::check_load_exchange() { + + ExchangeTime = 0.f; + DoesAnyDoorNeedOpening = false; + + if( fStopTime > 0 ) { return; } + + // czas postoju przed dalszą jazdą (np. na przystanku) + auto *vehicle { pVehicles[ VehicleEnd::front ] }; + while( vehicle != nullptr ) { + auto const vehicleexchangetime { vehicle->LoadExchangeTime() }; + DoesAnyDoorNeedOpening |= vehicleexchangetime > 0 && vehicle->LoadExchangeSpeed() == 0; + ExchangeTime = std::max( ExchangeTime, vehicleexchangetime ); + vehicle = vehicle->Next(); + } + + if( pVehicle->DirectionGet() != m_lastexchangedirection ) { + // generally means the ai driver moved to the opposite end of the consist + // TODO: investigate whether user playing with the reverser can mess this up + auto const left { m_lastexchangedirection > 0 ? 1 : 2 }; + auto const right { 3 - left }; + m_lastexchangeplatforms = + ( ( m_lastexchangeplatforms & left ) != 0 ? right : 0 ) + + ( ( m_lastexchangeplatforms & right ) != 0 ? left : 0 ); + m_lastexchangedirection = pVehicle->DirectionGet(); + } + if( false == TrainParams.IsMaintenance() + && ( false == drivingFlags.doorOpened + || true == DoesAnyDoorNeedOpening ) ) { + drivingFlags.doorOpened = true; // nie wykonywać drugi raz + remove_hint( driver_hint::doorleftopen ); + remove_hint( driver_hint::doorrightopen ); + Doors( true, m_lastexchangeplatforms ); + } +} + +void +TController::GuardOpenDoor() { + if (drivingFlags.guardOpenDoor) { + auto *vehicle{ pVehicles[VehicleEnd::front] }; + while (vehicle != nullptr && vehicle->physics->Doors.range == 0) { + vehicle = vehicle->Next(); + } + if (vehicle != nullptr && vehicle->physics->Doors.range > 0) { + auto const lewe = vehicle->DirectionGet() > 0 ? 1 : 2; + auto const prawe = 3 - lewe; + if (m_lastexchangeplatforms & lewe) { + vehicle->physics->OperateDoors(VehicleSide::left, true, range_t::local); + } + if (m_lastexchangeplatforms & prawe) { + vehicle->physics->OperateDoors(VehicleSide::right, true, range_t::local); + } + } + else { + drivingFlags.guardOpenDoor = false; + } + } +} diff --git a/vehicle/ai/driver.cpp b/vehicle/ai/driver.cpp new file mode 100644 index 000000000..544c7e7e0 --- /dev/null +++ b/vehicle/ai/driver.cpp @@ -0,0 +1,599 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the AI driver: construction, its update, taking over a vehicle, what it tells about itself + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +const double HardReactionTime = 0.2; +const double EasyAcceleration = 0.85; //[m/ss] +const double HardAcceleration = 9.81; +bool WriteLogFlag = false; + +//--------------------------------------------------------------------------- + +TController::TController(bool AI, TDynamicObject *NewControll, bool InitPsyche, bool Primary) :// czy ma aktywnie prowadzić? + aiControlled( AI ), pVehicle( NewControll ) +{ + if( pVehicle != nullptr ) { + pVehicles[ VehicleEnd::front ] = pVehicle->GetFirstDynamic( VehicleEnd::front ); // pierwszy w kierunku jazdy (Np. Pc1) + pVehicles[ VehicleEnd::rear ] = pVehicle->GetFirstDynamic( VehicleEnd::rear ); // ostatni w kierunku jazdy (końcówki) + } + else { + pVehicles[ VehicleEnd::front ] = nullptr; + pVehicles[ VehicleEnd::rear ] = nullptr; + } + ControllingSet(); // utworzenie połączenia do sterowanego pojazdu + if( occupied != nullptr ) { + iDirectionOrder = occupied->CabActive; // 1=do przodu (w kierunku sprzęgu 0) + VehicleName = occupied->Name; + + if( is_car() ) { // samochody: na podst. http://www.prawko-kwartnik.info/hamowanie.html + // fDriverBraking=0.0065; //mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] + fDriverBraking = 0.03; // coś nie hamują te samochody zbyt dobrze + fDriverDist = 5.0; // 5m - zachowywany odstęp przed kolizją + fVelPlus = 10.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 2.0; // margines prędkości powodujący załączenie napędu + } + else { // pociągi i statki + fDriverBraking = 0.06; // mnożone przez (v^2+40*v) [km/h] daje prawie drogę hamowania [m] + fDriverDist = 50.0; // 50m - zachowywany odstęp przed kolizją + fVelPlus = 5.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu + } + + // fAccThreshold może podlegać uczeniu się - hamowanie powinno być rejestrowane, a potem analizowane + // próg opóźnienia dla zadziałania hamulca + fAccThreshold = is_emu() ? -0.55 : is_dmu() ? -0.45 : -0.2; +/* + // HACK: emu with induction motors need to start their braking a bit sooner than the ones with series motors + if( ( occupied->TrainType() == train_type::emu ) + && ( mvControlling->EngineType == TEngineType::ElectricInductionMotor ) ) { + fAccThreshold += 0.10; + } +*/ + } + // TrainParams=NewTrainParams; + // if (TrainParams) + // asNextStop=TrainParams.NextStop(); + // else + TrainParams = TTrainParameters("none"); // rozkład jazdy + // OrderCommand=""; + // OrderValue=0; + OrdersClear(); + + if( true == Primary ) { + drivingFlags.primary = true; // aktywnie prowadzące pojazd + } + + if( occupied != nullptr ) { + SetDriverPsyche(); // na końcu, bo wymaga ustawienia zmiennych + } + TableClear(); + + // the logs of all, begun at once as they always were. one of a train only at its first line (update_logs): every + // crew is made primary here, and the drivers but one of a train with crews in more vehicles are made passive + // before it starts, so they get no file with only the header + if( WriteLogFlag ) { + begin_physicslog(); + } + + // HACK: give the simulation a small window to potentially replace the AI with a human driver + fActionTime = -5.0; +}; + +TController::~TController() +{ // wykopanie mechanika z roboty +}; + +TBrakeSystem TController::consist_brake_system() const { + + if( occupied->brakes.config.kind != TBrakeSystem::ElectroPneumatic ) { return occupied->brakes.config.kind; } + + auto isepcapable = true; + if( pVehicles[ VehicleEnd::front ] != pVehicles[ VehicleEnd::rear ] ) { + // more detailed version, will use manual braking also for coupled sets of controlled vehicles + auto *vehicle = pVehicles[ VehicleEnd::front ]; // start from first + while( true == isepcapable + && vehicle != nullptr ) { + // NOTE: we could simplify this by doing only check of the rear coupler, but this can be quite tricky in itself + // TODO: add easier ways to access front/rear coupler taking into account vehicle's direction + isepcapable = (vehicle->physics->Couplers[VehicleEnd::front].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::front].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::front].Connected->Power > -1)) && + (vehicle->physics->Couplers[VehicleEnd::rear].Connected == nullptr || + (vehicle->physics->Couplers[VehicleEnd::rear].CouplingFlag & Coupling::control && vehicle->physics->Couplers[VehicleEnd::rear].Connected->Power > -1)); + vehicle = vehicle->Next(); // kolejny pojazd, podłączony od tyłu (licząc od czoła) + } + } + return isepcapable ? TBrakeSystem::ElectroPneumatic : TBrakeSystem::Pneumatic; +} + +std::pair TController::next_speed_limit() const { + + auto const speedlimit { static_cast( VelDesired ) }; + auto nextspeedlimit { speedlimit }; + auto nextspeedlimitdistance { std::numeric_limits::max() }; + if( speedlimit == 0 ) { + // if we aren't allowed to move then any next speed limit is irrelevant + return { nextspeedlimit, nextspeedlimitdistance }; + } + // nie przekraczać rozkladowej + auto const schedulespeedlimit { ( + OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) && TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : + false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ? static_cast( fShuntVelocity ) : + -1 ) }; + // first take note of any speed change which should occur after passing potential current speed limit + if( VelLimitLastDist.second > 0 ) { + nextspeedlimit = min_speed( schedulespeedlimit, static_cast( VelLimitLastDist.first ) ); + nextspeedlimitdistance = VelLimitLastDist.second; + } + // then take into account speed change ahead, compare it with speed after potentially clearing last limit + // lower of these two takes priority; otherwise limit lasts at least until potential last limit is cleared + auto const noactivespeedlimit { VelLimitLastDist.second < 0 }; + if( auto const speedatproximitydistance { min_speed( schedulespeedlimit, static_cast( VelNext ) ) }; speedatproximitydistance == nextspeedlimit ) { + if( noactivespeedlimit ) { + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + } + else if( speedatproximitydistance < nextspeedlimit ) { + // if the speed limit ahead is more strict than our current limit, it's important enough to report + if( speedatproximitydistance < VelDesired ) { + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + // otherwise report it only if it's located after our current (lower) limit ends + else if( ActualProximityDist > nextspeedlimitdistance ) { + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + } + else if( noactivespeedlimit ) { // implicit proximity > last, report only if last limit isn't present + nextspeedlimit = speedatproximitydistance; + nextspeedlimitdistance = ActualProximityDist; + } + // HACK: if our current speed limit extends beyond our scan range don't display potentially misleading information about its length + if( nextspeedlimitdistance >= EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE ) { + nextspeedlimit = speedlimit; + } + // HACK: hide next speed limit if the 'limit' is a vehicle in front of us + else if( ActualProximityDist == std::abs( TrackObstacle() ) ) { + nextspeedlimit = speedlimit; + } + return { nextspeedlimit, nextspeedlimitdistance }; +} + +blackbox::ai_reference TController::ai_reference() const { + + blackbox::ai_reference ai; + ai.target_kmh = static_cast( VelDesired ); + if( auto const [ limit, distance ] { next_speed_limit() }; limit != static_cast( VelDesired ) ) { + ai.next_limit_kmh = static_cast( limit ); + ai.next_limit_distance = static_cast( distance ); + } + ai.acceleration = static_cast( AccDesired ); + ai.braking_distance = static_cast( fBrakeDist ); + ai.timetable_vmax_kmh = ( TrainParams.TTVmax > 0.0 ? static_cast( TrainParams.TTVmax ) : -1.0f ); + ai.track_vmax_kmh = static_cast( occupied->RunningTrack.Velmax ); + return ai; +} + +void TController::record_station( TSpeedPos const &Point, std::uint8_t const Kind ) const { + + if( Point.evEvent == nullptr ) { return; } + blackbox::station_event entry; + entry.kind = Kind; + auto const row { TrainParams.StationIndex }; + entry.row = static_cast( std::max( 0, row ) ); + entry.station = asNextStop; + entry.position = Point.evEvent->input_location(); + // the stop point may be moved back from the indicator, to where the head of the train is to stop + entry.distance = static_cast( Point.fDist + Point.fMoved ); + entry.stop_at = static_cast( Point.fMoved ); + entry.train_length = static_cast( fLength ); + entry.platform = static_cast( Point.evEvent->input_value( 2 ) ); + if( row >= 0 && row <= TrainParams.StationCount ) { + auto const &line { TrainParams.TimeTable[ row ] }; + entry.arrival = ( line.Ah >= 0 ? static_cast( line.Ah * 60 ) + line.Am : -1.0f ); + entry.departure = ( line.Dh >= 0 ? static_cast( line.Dh * 60 ) + line.Dm : -1.0f ); + } + simulation::Blackbox.station( pVehicles[ VehicleEnd::front ], std::move( entry ) ); +} + +void TController::WaitingSet(double Seconds) +{ // ustawienie odczekania po zatrzymaniu (ustawienie w trakcie jazdy zatrzyma) + fStopTime = -Seconds; // ujemna wartość oznacza oczekiwanie (potem >=0.0) +} + +void TController::SetVelocity(double NewVel, double NewVelNext, TStopReason r) +{ // ustawienie nowej prędkości + WaitingTime = -WaitingExpireTime; // przypisujemy -WaitingExpireTime, a potem porównujemy z zerem + if (NewVel == 0.0) { // jeśli ma stanąć + if (r != stopNone) // a jest powód podany + eStopReason = r; // to zapamiętać nowy powód + } + else { + eStopReason = stopNone; // podana prędkość, to nie ma powodów do stania + // to całe poniżej to warunki zatrąbienia przed ruszeniem + if( is_train() // tylko pociągi trąbią (unimogi tylko na torach, więc trzeba raczej sprawdzać tor) + && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::connect | DriverOrder::prepareEngine) // jeśli jedzie w dowolnym trybie + && drivingFlags.startHorn // jezeli trąbienie włączone + && ( false == drivingFlags.startHornDone && false == drivingFlags.connect ) // jeśli nie zatrąbione i nie jest to moment podłączania składu + && occupied->Vel < 1.0 // jesli stoi (na razie, bo chyba powinien też, gdy hamuje przed semaforem) + && ( NewVel >= 1.0 || NewVel < 0.0 ) ) { // o ile prędkość jest znacząca zatrąb po odhamowaniu + drivingFlags.startHornNow = true; + } + } + VelSignal = NewVel; // prędkość zezwolona na aktualnym odcinku + VelNext = NewVelNext; // prędkość przy następnym obiekcie +} + +double TController::BrakeAccFactor() const +{ + double Factor = 1.0; + + if( fAccThreshold != 0.0 + && AccDesired < 0.0 + && ( ActualProximityDist > fMinProximityDist + || occupied->Vel > VelDesired + fVelPlus ) ) { + Factor += fBrakeReaction * (/*occupied->BrakeCtrlPosR*/ BrakeCtrlPosition < 0.5 ? 1.5 : 1) * occupied->Vel / ( std::max( 0.0, ActualProximityDist ) + 1 ) * ( ( AccDesired - AbsAccS ) / fAccThreshold ); + } +/* + if (occupied->TrainType() == train_type::dmu && occupied->Vel > 40 && VelNext<40) + Factor *= 1 + 0.25 * ( (1600 - VelNext * VelNext) / (occupied->Vel * occupied->Vel) ); +*/ + return Factor; +} + +void TController::SetDriverPsyche() { + + if (Psyche == Aggressive && OrderCurrentGet() == DriverOrder::obeyTrain) { + ReactionTime = HardReactionTime; // w zaleznosci od charakteru maszynisty + if (is_car()) { + WaitingExpireTime = 1; // tyle ma czekać samochód, zanim się ruszy + AccPreferred = 3.0; //[m/ss] agresywny + } + else { + WaitingExpireTime = 61; // tyle ma czekać, zanim się ruszy + AccPreferred = HardAcceleration; // agresywny + } + } + else { + ReactionTime = EasyReactionTime; // spokojny + if (is_car()) { + WaitingExpireTime = 3; // tyle ma czekać samochód, zanim się ruszy + AccPreferred = 2.0; //[m/ss] + } + else { + WaitingExpireTime = 65; // tyle ma czekać, zanim się ruszy + AccPreferred = EasyAcceleration; + } + } +} + +void +TController::Update( double const Timedelta ) { + // uruchamiać przynajmniej raz na sekundę + if( ( false == drivingFlags.primary ) ) { return; } // pasywny nic nie robi + if( false == simulation::is_ready ) { return; } + + update_timers( Timedelta ); + update_logs( Timedelta ); + + auto const reactiontime { std::min( ReactionTime, 2.0 ) }; + + if( LastReactionTime < reactiontime ) { return; } + LastReactionTime -= reactiontime; +/* + // TBD, TODO: put this in an appropriate place, or get rid of it + // NOTE: this section moved all cars to the edge of their respective roads + // it may have some use eventually for collision avoidance, + // but when enabled all the time it produces silly effect + if( occupied->Vel > 1.0 ) { + // przy prowadzeniu samochodu trzeba każdą oś odsuwać oddzielnie, inaczej kicha wychodzi + if (occupied->CategoryFlag & 2) // jeśli samochód + // if (fabs(occupied->OffsetTrackH())Dim.W) //Ra: szerokość drogi tu powinna być? + if (!occupied->ChangeOffsetH(-0.01 * occupied->Vel * dt)) // ruch w poprzek drogi + occupied->ChangeOffsetH(0.01 * occupied->Vel * dt); // Ra: co to miało być, to nie wiem + } +*/ + update_hints(); + // main ai update routine + determine_consist_state(); + determine_braking_distance(); + determine_proximity_ranges(); + // vicinity check + auto const awarenessrange { + std::max( + 750.0, + occupied->Vel > EU07_AI_MOVEMENT ? + 400 + fBrakeDist : + 30.0 * fDriverDist ) }; // 1500m dla stojących pociągów; + if( is_active() ) { + scan_route( awarenessrange ); + } + scan_obstacles( awarenessrange ); + // generic actions + control_security_system( reactiontime ); + if( iEngineActive ) { + control_wheelslip(); + control_horns( reactiontime ); + control_pantographs(); + if( fActionTime > 0.0 ) { + // potentially delayed and/or low priority actions + control_lights(); + control_doors(); + control_compartment_lights(); + } + } + CheckTimeControllers(); + // external command actions + UpdateCommand(); + // mode specific actions + handle_engine(); + handle_orders(); + // a brake the wagon inspector left to cut out while the train was moving + reinspect_brakes(); + // situational velocity and acceleration adjustments + pick_optimal_speed( awarenessrange ); + if( iEngineActive ) { + control_tractive_and_braking_force(); + } + SetTimeControllers(); +} + +//-----------koniec skanowania semaforow + +void TController::TakeControl( bool const Aidriver, bool const Forcevehiclecheck ) +{ // przejęcie kontroli przez AI albo oddanie + if (aiControlled == Aidriver && !Forcevehiclecheck) + return; // już jest jak ma być + if( aiControlled != Aidriver ) { + // the autopilot switched on or off + simulation::Blackbox.driver_changed( pVehicle, Aidriver ); + } + if (Aidriver) //żeby nie wykonywać dwa razy + { // teraz AI prowadzi + aiControlled = AIdriver; + pVehicle->Controller = AIdriver; + // the AI doesn't operate the headlight dimmer, drop the state left by the human driver + // so the lights set by the AI aren't hidden (dimmer in off position) or dimmed + pVehicle->HeadlightsAoff = false; + pVehicle->HeadlightsBoff = false; + pVehicle->DimHeadlights = false; + pVehicle->HighBeamLights = false; + control_lights(); // reinicjalizacja swiatel + occupied->CabActivisation(true); + iDirection = 0; // kierunek jazdy trzeba dopiero zgadnąć + TableClear(); // ponowne utworzenie tabelki, bo człowiek mógł pojechać niezgodnie z sygnałami + if( action() != TAction::actSleep ) { + // gdy zgaszone światła, flaga podjeżdżania pod semafory pozostaje bez zmiany + // conditional below disabled to get around the situation where the AI train does nothing ever + // because it is waiting for orders which don't come until the engine is engaged, i.e. effectively never + if( OrderCurrentGet() ) { + // jeśli coś robi + PrepareEngine(); // niech sprawdzi stan silnika + } + else { + // jeśli nic nie robi + OrderNext( DriverOrder::prepareEngine ); + if( pVehicle->physics->LitLights()[ ( occupied->CabActive < 0 ? + VehicleEnd::rear : + VehicleEnd::front ) ] + & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) // któreś ze świateł zapalone? + { // od wersji 357 oczekujemy podania komend dla AI przez scenerię +/* + if( pVehicle->physics->LitLights()[ occupied->CabActive < 0 ? VehicleEnd::rear : VehicleEnd::front ] & light::headlight_upper ) // górne światło zapalone + OrderNext( DriverOrder::obeyTrain ); // jazda pociągowa + else + OrderNext( DriverOrder::shunt ); // jazda manewrowa +*/ + if( occupied->Vel >= 1.0 ) // jeśli jedzie (dla 0.1 ma stać) + drivingFlags.stopHere = false; // to ma nie czekać na sygnał, tylko jechać + else + drivingFlags.stopHere = true; // a jak stoi, to niech czeka + } + } + CheckVehicles(); // ustawienie świateł + } + } + else + { // a teraz użytkownik + if (eAction == TAction::actSleep || OrderCurrentGet() == DriverOrder::waitForOrders) // gasimy swiatla jesli przejmujemy odstawione + pVehicle->RaLightsSet(0, 0); + auto const aiwasdriving { aiControlled == AIdriver }; + if( aiwasdriving ) { + // the horn, sandbox, departure signal and brake releaser the AI may have latched are momentary for the human driver + handover::release_ai_controls( *occupied, *mvControlling ); + fWarningDuration = 0.0; + remove_hint( driver_hint::hornon ); + // the AI sets the lights directly, leave the selector in matching position so it doesn't revert them later + sync_lights_selector(); + } + aiControlled = Humandriver; + pVehicle->Controller = Humandriver; + if( aiwasdriving ) { + // same with the headlight dimmer, which is only applied for the human driver + sync_lights_dimmer(); + } + if( eAction == TAction::actSleep ) { + eAction = TAction::actUnknown; + } + if( Forcevehiclecheck ) { + // update consist ownership and other consist data + CheckVehicles(); + } + } +}; + +Mtable::TTrainParameters const & +TController::TrainTimetable() const { + return TrainParams; +} + +std::string TController::Relation() const +{ // zwraca relację pociągu + return TrainParams.ShowRelation(); +}; + +const std::string& TController::TrainName() const +{ // zwraca numer pociągu + return TrainParams.TrainName; +}; + +int TController::StationCount() const +{ // zwraca ilość stacji (miejsc zatrzymania) + return TrainParams.StationCount; +}; + +int TController::StationIndex() const +{ // zwraca indeks aktualnej stacji (miejsca zatrzymania) + return TrainParams.StationIndex; +}; + +bool TController::IsStop() const +{ // informuje, czy jest zatrzymanie na najbliższej stacji + return TrainParams.IsStop(); +}; + +std::string TController::TableText( std::size_t const Index ) const +{ // pozycja tabelki prędkości + if( Index < sSpeedTable.size() ) { + return sSpeedTable[ Index ].TableText(); + } + else { + return ""; + } +}; + +int TController::CrossRoute(TTrack *tr) +{ // zwraca numer segmentu dla skrzyżowania (tr) + // pożądany numer segmentu jest określany podczas skanowania drogi + // droga powinna być określona sposobem przejazdu przez skrzyżowania albo współrzędnymi miejsca + // docelowego + for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) + { // trzeba przejrzeć tabelę skanowania w poszukiwaniu (tr) + // i jak się znajdzie, to zwrócić zapamiętany numer segmentu i kierunek przejazdu + // (-6..-1,1..6) + if( true == sSpeedTable[i].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::track) + && sSpeedTable[i].trTrack == tr ) { + // jeśli pozycja odpowiadająca skrzyżowaniu (tr) + return sSpeedTable[i].crossRoute; // -8..7 + } + } + return 0; // nic nie znaleziono? +}; +/* +void TController::RouteSwitch(int d) +{ // ustawienie kierunku jazdy z kabiny + d &= 3; + if( ( d != 0 ) + && ( iRouteWanted != d ) ) { // nowy kierunek + iRouteWanted = d; // zapamiętanie + if( occupied->CategoryFlag & 2 ) { + // jeśli samochód + for( std::size_t i = 0; i < sSpeedTable.size(); ++i ) { + // szukanie pierwszego skrzyżowania i resetowanie kierunku na nim + if( true == sSpeedTable[ i ].flags.HasAll(spEnabled | spTrack) ) { + // jeśli pozycja istotna (1) oraz odcinek (2) + if( false == sSpeedTable[ i ].flags.HasAll(spElapsed) ) { + // odcinek nie może być miniętym + if( sSpeedTable[ i ].trTrack->eType == tt_Cross ) // jeśli skrzyżowanie + { + while( sSpeedTable.size() >= i ) { + // NOTE: we're ignoring semaphor flags and not resetting them like we do for train route trimming + // but what if there's street lights? + // TODO: investigate + sSpeedTable.pop_back(); + } + iLast = sSpeedTable.size(); + } + } + } + } + } + } +}; +*/ +std::string TController::OwnerName() const +{ + return pVehicle ? pVehicle->physics->Name : "none"; +}; + +bool TController::is_train() const { + return TestFlag( occupied->CategoryFlag, 1 ); } + +bool TController::is_car() const { + return TestFlag( occupied->CategoryFlag, 2 ); } + +bool TController::is_emu() const { + return mvControlling->TrainType() == train_type::emu; } + +bool TController::is_dmu() const { + return mvControlling->TrainType() == train_type::dmu; } + +bool TController::has_diesel_engine() const { + return mvControlling->EngineType == TEngineType::DieselElectric || mvControlling->EngineType == TEngineType::DieselEngine; } + +double TController::DirectionalVel() const { + return occupied->Vel * sign( iDirection * occupied->V() ); } + +std::vector DrivingFlags::ActiveNames() const { + std::vector> const flags { + { stopCloser, "StopCloser" }, { stopPoint, "StopPoint" }, { active, "Active" }, { press, "Press" }, + { connect, "Connect" }, { primary, "Primary" }, { late, "Late" }, { stopHere, "StopHere" }, + { startHorn, "StartHorn" }, { startHornNow, "StartHornNow" }, { startHornDone, "StartHornDone" }, + { oerlikons, "Oerlikons" }, { incSpeed, "IncSpeed" }, { trackEnd, "TrackEnd" }, { switchFound, "SwitchFound" }, + { guardSignal, "GuardSignal" }, { visibility, "Visibility" }, { doorOpened, "DoorOpened" }, + { pushPull, "PushPull" }, { signalFound, "SignalFound" }, { stopPointFound, "StopPointFound" }, + { guardOpenDoor, "GuardOpenDoor" }, { departureWarned, "DepartureWarned" } }; + std::vector names; + for( auto const &[ set, name ] : flags ) { + if( set ) { + names.emplace_back( name ); + } + } + return names; +} diff --git a/vehicle/ai/engine.cpp b/vehicle/ai/engine.cpp new file mode 100644 index 000000000..25fff0e9b --- /dev/null +++ b/vehicle/ai/engine.cpp @@ -0,0 +1,449 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// preparing the vehicle and shutting it down: the engine, the heating, the direction + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +// closes the line breaker, or starts the engine, the relays reset first +void TController::close_line_breaker() +{ + cue_action( driver_hint::mastercontrollersetzerospeed ); + // consist-wide ground relay reset + cue_action( driver_hint::maincircuitgroundreset ); + cue_action( driver_hint::tractionnmotoroverloadreset ); + if( occupied->EngineType == TEngineType::DieselEngine ) { + // specjalnie dla SN61 żeby nie zgasł + cue_action( driver_hint::mastercontrollersetidle ); + } + cue_action( driver_hint::linebreakerclose ); +} + +bool TController::PrepareEngine() +{ // odpalanie silnika + // HACK: don't immediately activate inert vehicle in case the simulation is about to replace us with human driver + if( occupied->Vel < 1.0 && fActionTime < 0.0 ) { return false; } + + LastReactionTime = 0.0; + ReactionTime = occupied->Vel < 5 ? PrepareTime : EasyReactionTime; // react faster with rolling start + + cue_action( driver_hint::batteryon ); + cue_action( driver_hint::cabactivation); + cue_action( driver_hint::radiofuseon ); + cue_action( driver_hint::radioon ); + + if( has_diesel_engine() ) { + cue_action( driver_hint::oilpumpon ); + PrepareHeating(); + if( true == IsHeatingTemperatureOK ) { + cue_action( driver_hint::fuelpumpon ); + } + else { + cue_action( driver_hint::waittemperaturetoolow ); + } + } + + if( mvControlling->lineBreaker.config.pantographsRequireIt + && IsAnyLineBreakerOpen ) { + // the pantographs rise only through the closed line breaker, which closes without their voltage + PrepareDirection(); + close_line_breaker(); + } + + auto const sufficientpantographpressure { ( + is_emu() ? + 2.5 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 + 3.5 ) + + 0.1 }; // leeway margin + + if( pantographUnit->EnginePowerSource.SourceType == TPowerSource::CurrentCollector + && pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 0 ) { + // if our pantograph unit isn't a pantograph-devoid fallback + if (pantographUnit->pantographAir.Pressure() < sufficientpantographpressure) { + // załączenie małej sprężarki + if( false == pantographUnit->pantographAir.config.autoValve ) { + // odłączenie zbiornika głównego, bo z nim nie da rady napompować + cue_action( driver_hint::pantographairsourcesetauxiliary ); + } + cue_action( driver_hint::pantographcompressoron ); // załączenie sprężarki pantografów + if( pantographUnit->pantographAir.IsCompressorRunning() ) { + cue_action( driver_hint::waitpantographpressuretoolow ); + } + } + else { + // jeżeli jest wystarczające ciśnienie w pantografach + if( false == pantographUnit->pantographAir.IsConnectedToMainReservoir() + || pantographUnit->pantographAir.Pressure() <= pantographUnit->mainPipe.Pressure() ) { // kurek przełączony albo główna już pompuje + cue_action( driver_hint::pantographcompressoroff ); // sprężarkę pantografów można już wyłączyć + } + } + // TODO: make pantograph setup a part of control_pantographs() and call it here instead + if( fOverhead2 == -1.0 && iOverheadDown == 0 ) { + cue_action( driver_hint::pantographsvalveon ); + cue_action( driver_hint::frontpantographvalveon, iDirection >= 0 ? 5 : 0 ); + cue_action( driver_hint::rearpantographvalveon, iDirection >= 0 ? 0 : 5 ); + } + } + + auto const ispoweravailable = + mvControlling->EnginePowerSource.SourceType != TPowerSource::CurrentCollector + || std::max(mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.SupplyVoltage()) > mvControlling->EnginePowerSource.CollectorParameters.MinV; + // standing with the pantographs up and no voltage, nothing the driver does starts the vehicle. it says so, and keeps + // trying: towed back under the wire, or with the power switched on, the vehicle gets prepared after all + report_power_stall( ispoweravailable, sufficientpantographpressure ); + + bool isready = false; + + if( IsHeatingTemperatureOK + && ispoweravailable ) { + // najpierw ustalamy kierunek, jeśli nie został ustalony + PrepareDirection(); + + if( IsAnyConverterOverloadRelayOpen ) { + // wywalił bezpiecznik nadmiarowy przetwornicy + cue_action( driver_hint::compressoroff ); // TODO: discern whether compressor needs converter to operate + cue_action( driver_hint::converteroff ); + cue_action( driver_hint::primaryconverteroverloadreset ); // reset nadmiarowego + } + if( IsAnyLineBreakerOpen ) { + // activate main circuit or engine + close_line_breaker(); + } + else { + // main circuit or engine is on, set up vehicle devices and controls + if( false == IsAnyConverterOverloadRelayOpen ) { + if( IsAnyConverterPresent ) { + cue_action( driver_hint::converteron ); + } + // w EN57 sprężarka w ra jest zasilana z silnikowego + // TODO: change condition to presence of required voltage type + if( IsAnyCompressorPresent && IsAnyConverterEnabled ) { + cue_action( driver_hint::compressoron ); + } + if( mvControlling->mainPipe.Pressure() < 4.5 && mvControlling->air.config.mainReservoirVolume > 0.0 ) { + cue_action( driver_hint::waitpressuretoolow ); + } + // enable motor blowers + if( occupied->MotorBlowers[ VehicleEnd::front ].speed != 0 ) { + cue_action( driver_hint::frontmotorblowerson ); + } + if( occupied->MotorBlowers[ VehicleEnd::rear ].speed != 0 ) { + cue_action( driver_hint::rearmotorblowerson ); + } + } + control_field_shunting(); + // sync virtual brake state with the 'real' one + if( occupied->brakes.config.driverValveType != TBrakeHandle::NoHandle ) { + std::unordered_map const brakepositions{ + { static_cast( occupied->brakes.driverValve->GetPos( bh_RP ) ), gbh_RP }, + { static_cast( occupied->brakes.driverValve->GetPos( bh_NP ) ), gbh_NP }, + { static_cast( occupied->brakes.driverValve->GetPos( bh_FS ) ), gbh_FS } }; + auto const lookup{ brakepositions.find( static_cast( occupied->brakes.HandlePositionSmooth() ) ) }; + if( lookup != brakepositions.end() ) { + BrakeLevelSet( lookup->second ); // GBH + } + } + // set up train brake + if( occupied->Vel < EU07_AI_NOMOVEMENT ) { + // standing: the locomotive brake first, then the pipe is filled + secure_standing_train(); + } + else if( ( occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos( bh_RP ) ) + && ( ( false == occupied->brakes.driverValve->Time ) + || ( occupied->brakes.driverValve->GetCP() < occupied->brakes.config.pipeHighPressure - 0.05 ) ) ) { + cue_action( driver_hint::trainbrakerelease ); + } + // sync spring brake state across consist + cue_action( + occupied->brakes.spring.activate ? + driver_hint::springbrakeon : + driver_hint::springbrakeoff ); + } + isready = false == IsAnyConverterOverloadRelayOpen + && occupied->DirActive != 0 + && false == IsAnyLineBreakerOpen + && ( false == IsAnyConverterPresent || true == IsAnyConverterEnabled ) + && ( false == IsAnyCompressorPresent || true == IsAnyCompressorEnabled ) + && ( mvControlling->mainPipe.Pressure() > 4.5 || mvControlling->air.config.mainReservoirVolume == 0.0 ); + } + + if( true == isready ) { + // jeśli dotychczas spał teraz nie ma powodu do stania + eAction = TAction::actUnknown; + if( eStopReason == stopSleep ) { + eStopReason = stopNone; + } + // może skanować sygnały i reagować na komendy + drivingFlags.active = true; + } + + iEngineActive = isready; + + return iEngineActive; +} + +// tells in the log, once, of standing with the pantographs up and no voltage at them, past the end of the overhead +// wire or under a wire switched off (eu07/maszyna#421). Poweravailable is what PrepareEngine() found, Pantographpressure +// the air the pantographs need to rise +void +TController::report_power_stall( bool const Poweravailable, double const Pantographpressure ) { + + ai_power::state state; + state.collector = mvControlling->EnginePowerSource.SourceType == TPowerSource::CurrentCollector; + state.power = Poweravailable; + state.standing = occupied->Vel < EU07_AI_NOMOVEMENT; + if( pantographUnit->pantographAir.Pressure() >= Pantographpressure ) { + state.pantographs_up = + pantographUnit->pantographs[ VehicleEnd::front ].is_active + || pantographUnit->pantographs[ VehicleEnd::rear ].is_active; + } + // the pantographs of the vehicle carrying them hold the wire they found above them + if( auto const *carrier { pVehicle->FindPantographCarrier() }; + carrier != nullptr && carrier->physics == pantographUnit ) { + auto const pantographcount { std::min( carrier->iAnimType[ ANIM_PANTS ], static_cast( carrier->physics->pantographs.size() ) ) }; + for( auto index { 0 }; index < pantographcount; ++index ) { + if( true == carrier->physics->pantographs[ index ].is_active + && carrier->pants[ index ].fParamPants->hvPowerWire != nullptr ) { + state.wire = true; + } + } + } + // a user driving the vehicle sees the voltmeters for themselves + if( auto const stall { m_powerstall.update( aiControlled ? ai_power::check( state ) : ai_power::stall::waiting, ElapsedTime ) }; + stall.has_value() ) { + ErrorLog( ai_power::message( *stall, pVehicle->asName, pVehicle->GetPosition() ), logtype::traction ); + } +} + +// wyłączanie silnika (test wyłączenia, a część wykonawcza tylko jeśli steruje komputer) +bool TController::ReleaseEngine() { +/* + if( occupied->Vel > 0.01 ) { + VelDesired = 0.0; + AccDesired = std::min( AccDesired, -1.25 ); // hamuj solidnie + if( true == aiControlled ) { + // TBD, TODO: make a dedicated braking procedure out of it for potential reuse + ZeroSpeed(); + IncBrake(); + ReactionTime = 0.1; + } + // don't bother with the rest until we're standing still + return false; + } +*/ + // don't bother with the rest until we're standing still + if( occupied->Vel > EU07_AI_NOMOVEMENT ) { return false; } + + LastReactionTime = 0.0; + ReactionTime = PrepareTime; + + cue_action( driver_hint::releaseroff ); + // release train brake if on flats... + if( std::abs( fAccGravity ) < 0.01 ) { + apply_independent_brake_only(); + } + // ... but on slopes engage train brake + else { +// AccDesired = std::min( AccDesired, -0.9 ); + cue_action( driver_hint::trainbrakeapply ); + } + + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( driver_hint::directionnone ); + // zamykanie drzwi + cue_action( driver_hint::doorrightclose ); + cue_action( driver_hint::doorleftclose ); + // heating + cue_action( driver_hint::consistheatingoff ); + // devices + cue_action( driver_hint::compressoroff ); + cue_action( driver_hint::converteroff ); + // line breaker/engine + cue_action( driver_hint::linebreakeropen ); + // pantographs + cue_action( driver_hint::frontpantographvalveoff ); + cue_action( driver_hint::rearpantographvalveoff ); + + if( false == mvControlling->lineBreaker.IsClosed() ) { + // finish vehicle shutdown + if( has_diesel_engine() ) { + // heating/cooling subsystem + cue_action( driver_hint::waterheateroff ); + // optionally turn off the water pump as well + if( mvControlling->WaterPump.start_type != start_t::battery ) { + cue_action( driver_hint::waterpumpoff ); + } + // fuel and oil subsystems + cue_action( driver_hint::fuelpumpoff ); + cue_action( driver_hint::oilpumpoff ); + } + // gasimy światła + cue_action( driver_hint::lightsoff ); + // activate parking brake + // TBD: do it earlier? + cue_action( driver_hint::springbrakeon ); + if( occupied->brakes.config.localKind == TLocalBrake::ManualBrake + || occupied->brakes.config.hasHandBrake == true ) { + cue_action( driver_hint::manualbrakon ); + } + // switch off remaining power + cue_action( driver_hint::radiooff ); + cue_action( driver_hint::batteryoff ); + } + + auto const OK { + occupied->DirActive == 0 +// && ( false == IsAnyCompressorEnabled ) +// && ( false == IsAnyConverterEnabled ) + && false == mvControlling->lineBreaker.IsClosed() + && false == occupied->lowVoltage.Is24vAvailable() }; + + if (OK) { + // jeśli się zatrzymał + iEngineActive = false; + eStopReason = stopSleep; // stoimy z powodu wyłączenia + eAction = TAction::actSleep; //śpi (wygaszony) + + OrderNext(DriverOrder::waitForOrders); //żeby nie próbował coś robić dalej + drivingFlags.active = false; // ma nie skanować sygnałów i nie reagować na komendy + TableClear(); // zapominamy ograniczenia + VelSignalLast = -1.0; + } + return OK; +} + +// configures vehicle heating given current situation; returns: true if vehicle can be operated normally, false otherwise +bool +TController::PrepareHeating() { + + switch( mvControlling->EngineType ) { + + case TEngineType::DieselElectric: + case TEngineType::DieselEngine: { + + auto const &heat { mvControlling->diesel.heat }; + + // determine whether there's need to enable the water heater + // if the heater has configured maximum temperature, it'll disable itself automatically, so we can leave it always running + // otherwise enable the heater only to maintain minimum required temperature + auto const lowtemperature { ( + ( heat.water.config.temp_min > 0 && heat.temperatura1 < heat.water.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) + || ( heat.water_aux.config.temp_min > 0 && heat.temperatura2 < heat.water_aux.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) + || ( heat.oil.config.temp_min > 0 && heat.To < heat.oil.config.temp_min + (mvControlling->WaterHeater.is_active ? 5 : 0) ) ) }; + auto const heateron { ( + mvControlling->WaterHeater.config.temp_max > 0 + || true == lowtemperature ) }; + if( true == heateron ) { + // make sure the water pump is running before enabling the heater + if( false == mvControlling->WaterPump.is_active ) { + cue_action( driver_hint::waterpumpbreakeron ); + cue_action( driver_hint::waterpumpon ); + } + if( true == mvControlling->WaterPump.is_active ) { + cue_action( driver_hint::waterheaterbreakeron ); + cue_action( driver_hint::waterheateron ); + cue_action( driver_hint::watercircuitslinkon ); + } + } + else { + // no need to heat anything up, switch the heater off + cue_action( driver_hint::watercircuitslinkoff ); + cue_action( driver_hint::waterheateroff ); + cue_action( driver_hint::waterheaterbreakeroff ); + // optionally turn off the water pump as well + if( mvControlling->WaterPump.start_type != start_t::battery ) { + cue_action( driver_hint::waterpumpoff ); + cue_action( driver_hint::waterpumpbreakeroff ); + } + } + + IsHeatingTemperatureTooLow = lowtemperature; + break; + } + default: { + IsHeatingTemperatureTooLow = false; + break; + } + } + // TBD, TODO: potentially pay attention to too high temperature as well? + IsHeatingTemperatureOK = false == IsHeatingTemperatureTooLow; + + return IsHeatingTemperatureOK; +} + +void +TController::PrepareDirection() { + + if( iDirection == 0 ) { + // jeśli nie ma ustalonego kierunku + if( occupied->Vel < EU07_AI_NOMOVEMENT ) { // ustalenie kierunku, gdy stoi + iDirection = occupied->CabActive; // wg wybranej kabiny +/* + if( iDirection == 0 ) { + // jeśli nie ma ustalonego kierunku + if( occupied->Couplers[ VehicleEnd::rear ].Connected == nullptr ) { + // jeśli z tyłu nie ma nic + iDirection = -1; // jazda w kierunku sprzęgu 1 + } + if( occupied->Couplers[ VehicleEnd::front ].Connected == nullptr ) { + // jeśli z przodu nie ma nic + iDirection = 1; // jazda w kierunku sprzęgu 0 + } + } +*/ + } + else { + // ustalenie kierunku, gdy jedzie + iDirection = occupied->V() >= 0 ? 1 : // jazda w kierunku sprzęgu 0 + -1; // jazda w kierunku sprzęgu 1 + } + } + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( + iDirection > 0 ? + driver_hint::directionforward : + driver_hint::directionbackward ); +} diff --git a/vehicle/ai/force.cpp b/vehicle/ai/force.cpp new file mode 100644 index 000000000..2869c2174 --- /dev/null +++ b/vehicle/ai/force.cpp @@ -0,0 +1,771 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the traction and the brakes the driver applies for the speed it aims for + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +const double FSOverchargePipePress = 5.2; +const double FSOverchargeTime = 2.0; +const double FSOverchargeCRP = 0.05; +const double FSMaxTime = 10.0; +const double DepartBlockedFSDelay = 10.0; + +void +TController::control_tractive_and_braking_force() { + +#if LOGVELOCITY + WriteLog("Dist=" + FloatToStrF(ActualProximityDist, ffFixed, 7, 1) + + ", VelDesired=" + FloatToStrF(VelDesired, ffFixed, 7, 1) + + ", AccDesired=" + FloatToStrF(AccDesired, ffFixed, 7, 3) + + ", VelSignal=" + AnsiString(VelSignal) + ", VelNext=" + + AnsiString(VelNext)); +#endif + + if (iDriverFailCount > maxdriverfails) { + Psyche = Easyman; + if (iDriverFailCount > maxdriverfails * 2) + SetDriverPsyche(); + } + + control_relays(); + control_motor_connectors(); + + // if the radio-stop was issued don't waste effort trying to fight it + if( true == occupied->RadioStopFlag() // radio-stop + && occupied->Vel > EU07_AI_NOMOVEMENT ) { // and still moving + cue_action( driver_hint::mastercontrollersetzerospeed ); // just throttle down... + return; // ...and don't touch any other controls + } + // if we're slipping leave the controls alone, there's a separate logic section trying to deal with it + if( true == mvControlling->SlippingWheels() ) { + return; + } + + // ensure train brake isn't locked + if( BrakeCtrlPosition == gbh_NP ) { + cue_action( driver_hint::trainbrakerelease ); + } + control_releaser(); + control_main_pipe(); + + control_tractive_force(); + control_braking_force(); + +#if LOGVELOCITY + WriteLog("BrakePos=" + AnsiString(occupied->brakes.HandlePosition()) + ", MainCtrl=" + + AnsiString(mvControlling->MainCtrlPos())); +#endif +} + +// the switch of the field shunting of a diesel-electric that has one (AutoRelay=Optional with FieldShuntSwitch=Yes): off, +// the field stays full. checked while running too, since a vehicle taken over with its engine running doesn't go through +// PrepareEngine(). a diesel-electric with AutoRelay=Optional alone is left as before, shunting by hand with the switch off +void TController::control_field_shunting() { + + if( aiControlled + && mvControlling->EngineType == TEngineType::DieselElectric + && fieldshunting::has_switch( mvControlling->AutoRelayType(), mvControlling->FieldShuntSwitch() ) + && false == mvControlling->AutoRelayFlag() ) { + mvControlling->AutoRelaySwitch( true ); + } +} + +// ensure relays are active +void TController::control_relays() { + + control_field_shunting(); + + if( fActionTime < 0.0 ) { return; } + + if( IsAnyMotorOverloadRelayOpen ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + cue_action( driver_hint::tractionnmotoroverloadreset ); + ++iDriverFailCount; + } + if( IsAnyGroundRelayOpen ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + cue_action( driver_hint::maincircuitgroundreset ); + ++iDriverFailCount; + } +} + +void TController::control_motor_connectors() { + // ensure motor connectors are active + if( (mvControlling->EngineType == TEngineType::ElectricSeriesMotor || mvControlling->EngineType == TEngineType::DieselElectric || is_emu()) && Need_TryAgain ) { + // true, jeśli druga pozycja w elektryku nie załapała + cue_action(driver_hint::mastercontrollersetzerospeed); + Need_TryAgain = false; + } +} + +void TController::control_tractive_force() { + + control_uphill_start(); + + auto const velocity { DirectionalVel() }; + // jeśli przyspieszenie pojazdu jest mniejsze niż żądane oraz... + 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 )*/ || occupied->SpeedCtrlUnit.IsActive && velocity < occupied->SpeedCtrlUnit.FullPowerVelocity) && + false == drivingFlags.press && + // starting uphill against the releasing brake, no more power than holds the train + uphill_start::may_add_power( uphillStart.IsReleasing(), uphillStart.tractiveForce, uphillStart.holdingForce ) && + // nor while the train brake is still being applied further to hold the train + false == uphillStart.toppingUp && + velocity < (VelDesired == 1.0 ? // work around for trains getting stuck on tracks with speed limit = 1 + VelDesired : + VelDesired - fVelMinus) && + (ActualProximityDist > (is_car() ? fMinProximityDist : // cars are allowed to move within min proximity distance + fMaxProximityDist) ? // other vehicle types keep wider margin + true : + velocity + 1.0 < VelNext + // uphill, a train told to hold its speed on the way to a stop needs the power to do it + || VelNext == 0.0 && OrderCurrentGet().HasAny(DriverOrder::obeyTrain) && AccDesired >= 0.0 && fAccGravity < -0.025 && ActualProximityDist > fMinProximityDist) ) { + // ...jeśli prędkość w kierunku czoła jest mniejsza od dozwolonej o margines... + // within proximity margin don't exceed next scheduled speed, outside of the margin accelerate as you like + // ...to można przyspieszyć + increase_tractive_force(); + } + // zmniejszanie predkosci + // margines dla prędkości jest doliczany tylko jeśli oczekiwana prędkość jest większa od 5km/h + if( false == drivingFlags.press ) { + double SpeedCtrlMargin = mvControlling->SpeedCtrlUnit.IsActive && VelDesired > 5 ? 3 : 0; + // jeśli nie dociskanie + if( AccDesired <= EU07_AI_NOACCELERATION ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + else if( velocity > VelDesired + SpeedCtrlMargin + || ( fAccGravity < -0.01 ? is_too_fast_uphill() : AbsAccS > AccDesired + 10.05 ) + || IsAnyCouplerStretched ) { + // jak za bardzo przyspiesza albo prędkość przekroczona + // dodany wyjatek na "pelna w przod" + cue_action( driver_hint::tractiveforcedecrease ); + } + } + + control_handles(); + SpeedSet(); // ciągla regulacja prędkości +} + +bool TController::is_too_fast_uphill() const { + + if( AccDesired < 0.0 ) { return true; } + // holding the speed uphill on the way to a stop asks for no speeding up + return ( VelNext == 0.0 && ActualProximityDist <= fMaxProximityDist && AbsAccS > AccDesired + 0.05 ); +} + +// starting uphill a driver of a heavy train keeps the train brake applied, lets the locomotive's own brake off (the +// independent brake, and its share of the train brake with the releaser), applies the power, and releases the train +// brake only once the power holds the train. releasing everything first lets the train roll back before the power is +// there, and holding the train on the locomotive brake is no way out where that brake cuts the power (asynchronous +// drives, the control pressure switch) +void TController::control_uphill_start() { + + auto const velocity { DirectionalVel() }; + if( auto const uphill { + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && is_train() + && ( false == is_emu() ) && ( false == is_dmu() ) // a multiple unit has no locomotive to hold a train behind it + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) }; + false == uphill ) { + end_uphill_start(); + return; + } + uphillStart.tractiveForce = 0.0; + for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + // Ft is signed in the vehicle's own frame, and turned into the direction of travel as AbsAccS is + uphillStart.tractiveForce += std::max( 0.0, vehicle->physics->Ft() * ( vehicle->DirectionGet() == iDirection ? 1 : -1 ) * ( iDirection >= 0 ? 1 : -1 ) ); + } + uphillStart.holdingForce = fMass * -fAccGravity; + uphill_start::situation const now { + .standing = std::abs( velocity ) < EU07_AI_NOMOVEMENT, + .velocity = velocity, + .consist_velocity = fConsistVelocity, + .speed_up = AccDesired > EU07_AI_NOACCELERATION, + .speed_asked = VelDesired > 0.0, + .train_brake_applied = BrakeCtrlPosition > 0.0, + .tractive_force = uphillStart.tractiveForce, + .grade_force = uphillStart.holdingForce, + .consist_released = IsConsistReleased, + .consist_charged = IsConsistCharged }; + if( false == uphillStart.IsActive() ) { + if( false == uphill_start::begins( now ) ) { + return; + } + uphillStart.Begin( ElapsedTime ); + } + if( false == now.speed_up ) { + // no longer to start: the standing rules take over + end_uphill_start(); + return; + } + if( uphill_start::rolls_back( now ) ) { + // the rules for a train slipping back take over and apply the brakes + end_uphill_start(); + return; + } + uphillStart.toppingUp = false; + if( false == uphillStart.IsReleasing() ) { + uphillStart.toppingUp = uphill_brake_top_up(); + if( uphillStart.toppingUp ) { + return; + } + if( ( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) + && ( occupied->brakes.IndependentPosition() > 0.0 ) ) { + cue_action( driver_hint::independentbrakerelease ); + } + if( uphill_start::power_holds( now, ElapsedTime - uphillStart.startTime ) ) { + // the power holds the train: the train brake can be released + uphillStart.Release( 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( uphill_start::released( now, ElapsedTime - uphillStart.releaseTime ) ) { + 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[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + if( vehicle->physics->Power < 0.01 ) { + trainbrakeforce += vehicle->physics->Fb(); + haswagons = true; + } + } + if( false == haswagons ) { + return false; + } + auto const action { uphill_start::brake_top_up( + uphillStart.brakeTopUp, trainbrakeforce, uphillStart.holdingForce, BrakeCtrlPosition, fBrakeHeldTime, + occupied->brakes.config.delays[ occupied->brakes.delaySetting > 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 + uphillStart.startTime = ElapsedTime; + if( action == uphill_start::top_up_action::step ) { + BrakeLevelAdd( BrakingLevelIncrease ); + } + return true; +} + +void TController::end_uphill_start() { + + uphillStart.End(); +} + +// 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( occupied->brakes.config.localKind != 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( aiControlled + && ( ( 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( ( occupied->brakes.config.localKind == TLocalBrake::ManualBrake ) + || ( occupied->brakes.config.maxCylinderPressure[ 0 ] <= 0.0 ) ) { + return 0.0; + } + return brake_charge::locomotive_brake_force( + occupied->BrakeForceP( occupied->brakes.config.maxCylinderPressure[ 0 ], 0.0 ), + occupied->TotalMassxg ); +} + +void TController::increase_tractive_force() { + + if( fActionTime < 0.0 ) { return; } // gdy jest nakaz poczekać z jazdą, to nie ruszać + if( IsAnyCouplerStretched ) { return; } // train is already stretched past its limits, don't pull even harder + + if( occupied->brakes.spring.activate ) { + cue_action( driver_hint::springbrakeoff ); + } + if( VelDesired > 0.0 // to prevent door shuffle on stop + && ( doors_open() || doors_permit_active() ) ) { + // zamykanie drzwi - tutaj wykonuje tylko AI (zmienia fActionTime) + Doors( false ); + // Doors() call can potentially adjust fActionTime + if( fActionTime < 0.0 ) { return; } + } + if( true == occupied->DepartureSignal() ) { + cue_action( driver_hint::departuresignaloff ); + } + + cue_action( driver_hint::tractiveforceincrease ); +} + +// how far the deceleration may fall short of the demand before the brake is applied harder. approaching a lower +// speed, a pneumatic brake given a full step only once that much is missing acts too late: the demand +// creeps up meanwhile, and in a long G train the next step takes many seconds to act, so half a step is enough +double +TController::brake_increase_margin() const { + + if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( VelNext > 0.0 ) + && ( VelNext < DirectionalVel() ) ) { + return 0.5 * fBrake_a1[ 0 ]; + } + return fBrake_a1[ 0 ]; +} + +// a train coming to a stand with at least part of it on an up gradient: a long train brake released now cannot be +// applied again before the train stops and starts to roll back, so the train brake is not released any further, and the +// locomotive brake, which acts at once, helps to hold the train +bool +TController::uphill_stop_hold() const { + + return ( + ( BrakeSystem == TBrakeSystem::Pneumatic ) && is_train() && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) + && ( VelNext == 0.0 ) + && ( ActualProximityDist <= fMaxProximityDist ) + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) + && ( std::abs( DirectionalVel() ) < 10.0 ) + // not while the train is to be driven on + && ( AccDesired <= 0.0 ) ); +} + +// uphill with the train brake applied, the gradient brings a slow train to a stand sooner than the brake of the consist +// can be released: letting the train roll on (or pulling up) at this speed only releases the brake for nothing, and the +// train stands with the brake on its way off instead +bool +TController::uphill_brake_committed( double const Velocity ) const { + + return ( + ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( BrakeCtrlPosition > 0.0 ) + && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) + && ( Velocity / 3.6 / -fAccGravity < vehicle_ai::brake_response_horizon( occupied, BrakeSystem, -1.0, fBrake_a0[ 0 ] ) ) ); +} + +void TController::control_braking_force() { + + // don't touch the brakes when compressing buffers during coupling/uncoupling + if( drivingFlags.press ) { 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 == uphillStart.IsActive() ) }; + + // jeśli przyspieszamy, to nie hamujemy + if( AccDesired > 0.0 && OrderCurrentGet() != DriverOrder::disconnect // przy odłączaniu nie zwalniamy tu hamulca + && false == drivingFlags.press + && false == slippingbackuphill ) { + cue_action(driver_hint::brakingforcesetzero); + } + + // AbsAccS is the resultant acceleration, gravity included, so it is compared with the + // resultant the AI asks for, not with the brake-only demand AccDesired holds on a descent + auto const accdesiredresultant { AccDesired + fAccDesiredGravity }; + + // every few seconds, note how far the train falls short of the demand and whether that is getting worse: a brake + // still filling, or blocks gripping harder as the train slows down, make up a shortfall on their own, but a + // shortfall that keeps growing at a constant handle means the train is falling further behind its braking curve + if( ElapsedTime - brakingShortfall.time >= 3.0 ) { + auto const shortfall { AbsAccS - accdesiredresultant }; + brakingShortfall.growth = ( + ( ( AccDesired < 0.0 ) && ( shortfall > brakingShortfall.value + 0.005 ) ) ? + brakingShortfall.growth + 1 : + 0 ); + brakingShortfall.value = shortfall; + brakingShortfall.time = ElapsedTime; + } + + if( is_emu() && !ForcePNBrake ) { + // właściwie, to warunek powinien być na działający EP + // Ra: to dobrze hamuje EP w EZT + auto const accthreshold { ( + fAccGravity < 0.025 ? // HACK: when going downhill be more responsive to desired deceleration + fAccThreshold : + std::max( -0.2, fAccThreshold ) ) }; + auto const AccMax{ std::min(fBrake_a0[0] + 12 * fBrake_a1[0], occupied->brakes.blending.maxDeceleration) }; + auto const accmargin = AccMax > 1.1 * AccDesired && fAccGravity < 0.025 ? + 0.05 : 0.0; + if( ( AccDesired < accthreshold // jeśli hamować - u góry ustawia się hamowanie na fAccThreshold + && ( AbsAccS > accdesiredresultant + accmargin + || BrakeCtrlPosition < 0 ) ) + || ( fAccGravity < -0.05 && velocity < -0.1 && AccDesired < 0.0 ) ) { // also brake if uphill and slipping back + // hamować bardziej, gdy aktualne opóźnienie hamowania mniejsze niż (AccDesired) + cue_action( driver_hint::brakingforceincrease ); + } + else if( OrderCurrentGet() != DriverOrder::disconnect ) { // przy odłączaniu nie zwalniamy tu hamulca + if( AbsAccS < accdesiredresultant - 0.05 ) { + // jeśli opóźnienie większe od wymaganego (z histerezą) luzowanie, gdy za dużo + // TBD: check if the condition isn't redundant with the DecBrake() code + if( BrakeCtrlPosition >= 0 && VelDesired > 0.0 ) { + // sanity check to prevent unintended brake release on sharp slopes + cue_action(driver_hint::brakingforcedecrease); + } + } + else { + cue_action( driver_hint::brakingforcelap ); + } + } + } // type & dt_ezt + 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 + || 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) + || AccDesired < fAccGravity - 0.5 || BrakeCtrlPosition <= 0) ) { + // u góry ustawia się hamowanie na fAccThreshold + // jeśli upłynął czas reakcji hamulca, chyba że nagłe albo luzował + // TODO: check whether brake delay variable still has any purpose + cue_action(driver_hint::brakingforceincrease, + // Ra: ten czas należy zmniejszyć, jeśli czas dojazdu do zatrzymania jest mniejszy + (3.0 + 0.5 * ((occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.config.delays[1] : occupied->brakes.config.delays[3]) - 3.0)) * 0.5); // Ra: tymczasowo, bo przeżyna S1 + } + else if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( AccDesired < 0.0 ) + && ( BrakeCtrlPosition > 0.0 ) + && ( brakingShortfall.value > 0.02 ) + && ( brakingShortfall.growth >= 2 ) + && ( fBrakeHeldTime > vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) { + // the train has been falling further behind the demand for a while at a handle left alone for longer than + // the brake takes to respond: a small step now, while it still is small, rather than the deep one the + // margin above would allow only once the train is far behind + cue_action( driver_hint::brakingforceincrease ); + brakingShortfall.growth = 0; + } + 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() != DriverOrder::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() + && ( aiControlled + || ( false == brake_charge::release_waits( + IsConsistCharged, + occupied->Vel < EU07_AI_NOMOVEMENT, + occupied->brakes.HandlePositionSmooth() > occupied->brakes.driverValve->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 + // sanity check to prevent unintended brake release on sharp slopes + // TODO: check whether brake delay variable still has any purpose + cue_action(driver_hint::brakingforcedecrease, + (occupied->brakes.delaySetting > bdelay_G ? occupied->brakes.config.delays[0] : occupied->brakes.config.delays[2]) / 3.0 * 0.5); // Ra: tymczasowo, bo przeżyna S1 + } + // uphill, the locomotive brake acts at once while the train brake of a long train takes many seconds to apply: + // put it on as the train comes to a stand, and at once if the train has started to roll back + if( ( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) + && ( occupied->brakes.IndependentPosition() < 1.0 ) + && ( ( uphill_stop_hold() && ( std::abs( velocity ) < 3.0 ) + // a train that has slowed down short of where it is to stop and is to pull up further does not get it + && ( VelDesired <= std::abs( velocity ) + 0.5 ) + && ( ActualProximityDist - vehicle_ai::uphill_stopping_distance( std::abs( velocity ), fAccGravity ) <= stopping_margin() ) ) + || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) && ( fAccGravity < EU07_AI_UPHILLGRAVITY ) && ( velocity < -0.1 ) && ( AccDesired <= 0.0 ) ) ) ) { + cue_action( driver_hint::independentbrakeapply ); + } + // stop-gap measure to ensure cars actually brake to stop even when above calculactions go awry + // instead of releasing the brakes and creeping into obstacle at 1-2 km/h + if( is_car() && VelDesired == 0.0 && velocity > VelDesired && ActualProximityDist <= fMinProximityDist && occupied->brakes.IndependentPosition() < 0.01 ) { + cue_action(driver_hint::brakingforceincrease); + } + } + + // odhamowywanie składu po zatrzymaniu i zabezpieczanie lokomotywy + if( occupied->Vel < EU07_AI_NOMOVEMENT + && ( VelDesired == 0.0 + || AccDesired <= EU07_AI_NOACCELERATION ) ) { + + if( false == OrderCurrentGet().HasAny(DriverOrder::disconnect | DriverOrder::connect | DriverOrder::changeDirection) // przy (p)odłączaniu nie zwalniamy tu hamulca + && std::abs(fAccGravity) < 0.01 ) { // only do this on flats, on slopes keep applied the train brake + apply_independent_brake_only(); + } + // if told to change direction don't confuse human driver with request to leave applied brake in the cab they're about to leave + if( OrderCurrentGet().HasAny(DriverOrder::changeDirection) ) { + cue_action( driver_hint::independentbrakerelease ); + } + } +} + +void TController::apply_independent_brake_only() { + + if( occupied->brakes.config.localKind != TLocalBrake::ManualBrake ) { + if( false == occupied->ShuntMode // no need for independent brake if autobrake is active + && is_equal(occupied->brakes.HandlePositionSmooth(), occupied->brakes.driverValve->GetPos(bh_RP), 0.2) ) { + cue_action( driver_hint::independentbrakeapply ); + } + else { + cue_action( driver_hint::trainbrakerelease ); + } + } +} + +void TController::control_releaser() { + // HACK: don't immediately touch releaser in inert vehicle, in case the simulation is about to replace us with human driver + if( occupied->Vel < 1.0 && fActionTime < 0.0 ) { return; } + // TODO: combine all releaser handling in single decision tree instead of having bits all over the place + // TODO: replace handle and system conditions with flag indicating releaser presence + if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } + + auto const hasreleaser { + false == (is_dmu() || is_emu()) // TODO: a more refined test than rejecting these types wholesale + && ( occupied->brakes.config.driverValveType == TBrakeHandle::FV4a + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_6P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K5P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.config.driverValveType == TBrakeHandle::M394 ) }; + + if( false == hasreleaser ) { return; } + + brake_releaser::conditions state; + state.acceleration_desired = AccDesired; + state.pipe_pressure = occupied->brakePipe.Pressure(); + state.cylinder_pressure = occupied->brakes.cylinderPressure; + state.control_pressure = occupied->brakes.distributor->GetCRP(); + state.velocity = occupied->Vel; + state.uphill_start = uphillStart.IsActive(); + state.pressing = drivingFlags.press; + // stage 3 of uncoupling (UpdateDisconnect), from the direction change until the coupler lets go + state.compressing_buffers = + state.pressing && OrderCurrentGet().HasAny(DriverOrder::disconnect) && 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 + && ( occupied->Vel < EU07_AI_NOMOVEMENT ) + && ( ( occupied->brakes.pipeLock.unlockHandlePosition == -3 ) || ( BrakeCtrlPosition <= 0.0 ) ); + auto const wanted { brake_releaser::decide( state ) }; + auto const actuate { wanted.actuate }; + auto isbrakehandleinrightposition { true }; + + // some vehicles require brake handle to be moved to specific position to fill up the brake pipe + if( wanted.fill_pipe + && occupied->brakes.pipeLock.unlockHandlePosition != -3 ) { + cue_action( driver_hint::trainbrakesetpipeunlock ); + isbrakehandleinrightposition = ( BrakeCtrlPosition == occupied->brakes.pipeLock.unlockHandlePosition ); + } + + if( actuate ) { + // some vehicles may require master controller in neutral position + cue_action( driver_hint::mastercontrollersetzerospeed ); + if( false == occupied->brakes.distributor->Releaser() + && isbrakehandleinrightposition ) { + cue_action( driver_hint::releaseron ); + } + } + else { + if( true == occupied->brakes.distributor->Releaser() ) { + cue_action( driver_hint::releaseroff ); + } + } +} + +void TController::control_main_pipe() { + + // unlocking main pipe + if( ( AccDesired > -0.03 + // standing to charge before the first start, as in control_releaser() + || ( bBrakeChargeStart && ( occupied->Vel < EU07_AI_NOMOVEMENT ) ) ) + && true == occupied->brakes.pipeLock.locked ) { + UniversalBrakeButtons |= TUniversalBrake::ub_UnlockPipe; + } + else if (false == occupied->brakes.pipeLock.locked ) { + UniversalBrakeButtons &= ~TUniversalBrake::ub_UnlockPipe; + } + + // napełnianie uderzeniowe + if( BrakeSystem != TBrakeSystem::Pneumatic ) { return; } + + if( occupied->brakes.config.driverValveType == TBrakeHandle::FV4a + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_6P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K5P + || occupied->brakes.config.driverValveType == TBrakeHandle::MHZ_K8P + || occupied->brakes.config.driverValveType == TBrakeHandle::M394 ) { + + auto const departblocked { is_departure_blocked( DepartBlockedFSDelay ) }; + if( (drivingFlags.oerlikons || true == IsCargoTrain || departblocked) && BrakeCtrlPosition == gbh_RP && AbsAccS < 0.03 && AccDesired > -0.03 && VelDesired - occupied->Vel > 2.0 && fReady > 0.35 && + ( occupied->brakes.equivalentPipePressure < 4.5 || departblocked ) // don't charge with a risk of overcharging the main pipe + && occupied->air.MainReservoirPressure() >= 7.5 // don't charge without sufficient pressure in the tank + && BrakeChargingCooldown >= 0.0 // don't charge while cooldown is active + && (ActualProximityDist > 100.0 // don't charge if we're about to be braking soon + || min_speed(occupied->Vel, VelNext) >= occupied->Vel) ) { + + BrakeLevelSet(gbh_FS); + // don't charge the brakes too often, or we risk overcharging + BrakeChargingCooldown = -1 * std::clamp(iVehicles * 3, 30, 90); + } + + update_brake_charging(); + + if( ( occupied->air.MainReservoirPressure() < 5.0 + || ( BrakeCtrlPosition < gbh_RP + && ( occupied->brakes.equivalentPipePressure > (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, occupied->Vel < EU07_AI_NOMOVEMENT, BrakeCtrlPosition ) ) ) { + cue_action( driver_hint::trainbrakerelease ); + } + } +} + +void TController::update_brake_charging() { + + if( std::abs( BrakeCtrlPosition - gbh_FS ) >= 0.5 ) { + BrakeChargingStart = -1.0; + BrakeChargingPipeOverchargeStart.clear(); + return; + } + if( BrakeChargingStart < 0.0 ) { + BrakeChargingStart = ElapsedTime; + } + for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + auto const isovercharged { + vehicle->physics != occupied + && vehicle->physics->brakePipe.Pressure() > FSOverchargePipePress }; + if( isovercharged ) { + BrakeChargingPipeOverchargeStart.try_emplace( vehicle, ElapsedTime ); + } + else { + BrakeChargingPipeOverchargeStart.erase( vehicle ); + } + } +} + +bool TController::is_departure_blocked( double const Delay ) const { + + return DepartBlockedStart >= 0.0 + && ElapsedTime - DepartBlockedStart > Delay; +} + +double TController::consist_max_crp() const { + + auto result { 0.0 }; + for( auto const *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + result = std::max( result, vehicle->physics->brakes.distributor->GetCRP() ); + } + return result; +} + +bool TController::is_brake_charging_done() const { + + if( BrakeChargingStart < 0.0 ) { + return false; + } + return ElapsedTime - BrakeChargingStart > FSMaxTime + || consist_max_crp() > occupied->brakes.config.pipeHighPressure + FSOverchargeCRP + || std::ranges::any_of( + BrakeChargingPipeOverchargeStart, + [this]( auto const &Vehicle ) { return ElapsedTime - Vehicle.second > FSOverchargeTime; } ); +} + +void +TController::UpdateBrakingHelper() { + + if (HelperState > 0 && -AccDesired < fBrake_a0[0] + 2 * fBrake_a1[0] && occupied->Vel > EU07_AI_NOMOVEMENT) { + HelperState = 0; + } + + switch( HelperState ) { + case 0: { + if( -AccDesired > fBrake_a0[0] + 8 * fBrake_a1[0] ) { + HelperState = 1; + } + break; + } + case 1: { + if( -AccDesired > fBrake_a0[0] + 12 * fBrake_a1[0] ) { + HelperState = 2; + } + break; + } + case 2: { + if( -AccDesired > 0 && -ActualProximityDist > 5 ) { + HelperState = 3; + } + break; + } + default: { + break; + } + } +} diff --git a/vehicle/ai/internal.h b/vehicle/ai/internal.h new file mode 100644 index 000000000..adda3a7ea --- /dev/null +++ b/vehicle/ai/internal.h @@ -0,0 +1,120 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the constants and helpers the files of the AI driver share: only they include this header + +#pragma once + +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include + +#define LOGVELOCITY 0 +#define LOGORDERS 1 +#define LOGSTOPS 1 +#define LOGBACKSCAN 0 +#define LOGPRESS 0 + + +/* + +Moduł obsługujący sterowanie pojazdami (składami pociągów, samochodami). +Ma działać zarówno jako AI oraz przy prowadzeniu przez człowieka. W tym +drugim przypadku jedynie informuje za pomocą napisów o tym, co by zrobił +w tym pierwszym. Obejmuje zarówno maszynistę jak i kierownika pociągu +(dawanie sygnału do odjazdu). + +Przeniesiona tutaj została zawartość ai_driver.pas przerobiona na C++. +Również niektóre funkcje dotyczące składów z DynObj.cpp. + +Teoria jest wtedy kiedy wszystko wiemy, ale nic nie działa. +Praktyka jest wtedy, kiedy wszystko działa, ale nikt nie wie dlaczego. +Tutaj łączymy teorię z praktyką - tu nic nie działa i nikt nie wie dlaczego… + +*/ + +// zrobione: +// 0. pobieranie komend z dwoma parametrami +// 1. przyspieszanie do zadanej predkosci, ew. hamowanie jesli przekroczona +// 2. hamowanie na zadanym odcinku do zadanej predkosci (ze stabilizacja przyspieszenia) +// 3. wychodzenie z sytuacji awaryjnych: bezpiecznik nadmiarowy, poslizg +// 4. przygotowanie pojazdu do drogi, zmiana kierunku ruchu +// 5. dwa sposoby jazdy - manewrowy i pociagowy +// 6. dwa zestawy psychiki: spokojny i agresywny +// 7. przejscie na zestaw spokojny jesli wystepuje duzo poslizgow lub wybic nadmiarowego. +// 8. lagodne ruszanie (przedluzony czas reakcji na 2 pierwszych nastawnikach) +// 9. unikanie jazdy na oporach rozruchowych +// 10. logowanie fizyki //Ra: nie przeniesione do C++ +// 11. kasowanie czuwaka/SHP +// 12. procedury wspomagajace "patrzenie" na odlegle semafory +// 13. ulepszone procedury sterowania +// 14. zglaszanie problemow z dlugim staniem na sygnale S1 +// 15. sterowanie EN57 +// 16. zmiana kierunku //Ra: z przesiadką po ukrotnieniu +// 17. otwieranie/zamykanie drzwi +// 18. Ra: odczepianie z zahamowaniem i podczepianie +// 19. dla Humandriver: tasma szybkosciomierza - zapis do pliku! +// 20. wybór pozycji zaworu maszynisty w oparciu o zadane opoznienie hamowania + + +// do zrobienia: +// 1. kierownik pociagu +// 2. madrzejsze unikanie grzania oporow rozruchowych i silnika +// 3. unikanie szarpniec, zerwania pociagu itp +// 4. obsluga innych awarii +// 5. raportowanie problemow, usterek nie do rozwiazania +// 7. samouczacy sie algorytm hamowania + +// stałe +const double EasyReactionTime = 0.5; //[s] przebłyski świadomości dla zwykłej jazdy + +const double PrepareTime = 2.0; //[s] przebłyski świadomości przy odpalaniu + +// what the split parts of TController share, kept out of the global namespace +namespace vehicle_ai { + +double brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ); + +double +uphill_stopping_distance( double const Velocity, double const Gravity ); + +} // namespace vehicle_ai + diff --git a/vehicle/ai/obstacles.cpp b/vehicle/ai/obstacles.cpp new file mode 100644 index 000000000..d1e4f660f --- /dev/null +++ b/vehicle/ai/obstacles.cpp @@ -0,0 +1,496 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the obstacles and the signals behind and ahead of the train + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +basic_event * TController::CheckTrackEventBackward(double fDirection, TTrack *Track, TDynamicObject *Vehicle, int const Eventdirection, VehicleEnd const End) +{ // sprawdzanie eventu w torze, czy jest sygnałowym - skanowanie do tyłu + // NOTE: this method returns only one event which meets the conditions, due to limitations in the caller + // TBD, TODO: clean up the caller and return all suitable events, as in theory things will go awry if the track has more than one signal + auto const dir{ Vehicle->VectorFront() * (double)Vehicle->DirectionGet() }; + auto const pos{ End == VehicleEnd::front ? Vehicle->RearPosition() : Vehicle->HeadPosition() }; + auto const &eventsequence { ( fDirection * Eventdirection > 0 ? Track->m_events2 : Track->m_events1 ) }; + for( auto const &event : eventsequence ) { + if( event.second != nullptr + && event.second->m_passive + && typeid(*event.second) == typeid(getvalues_event) ) { + // since we're checking for events behind us discard the sources in front of the scanning vehicle + auto const sl{ event.second->input_location() }; // położenie komórki pamięci + auto const sem{ sl - pos }; // wektor do komórki pamięci od końca składu + auto const isahead { dir.x * sem.x + dir.z * sem.z > 0 }; + if( End == VehicleEnd::front ? isahead : !isahead ) { + // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu + return event.second; + } + } + } + return nullptr; +}; + +TTrack * TController::BackwardTraceRoute(double &fDistance, double &fDirection, TDynamicObject *Vehicle, basic_event *&Event, int const Eventdirection, VehicleEnd const End, bool const Untiloccupied ) +{ // szukanie sygnalizatora w kierunku przeciwnym jazdy (eventu odczytu komórki pamięci) + auto *Track = Vehicle->GetTrack(); + double fCurrentDistance = Vehicle->RaTranslationGet(); // aktualna pozycja na torze + if (fDirection > 0) // jeśli w kierunku Point2 toru + fCurrentDistance = Track->Length() - fCurrentDistance; + double s = 0; + + if( Track->VelocityGet() == 0.0 ) { // jak prędkosć 0 albo uszkadza, to nie ma po co skanować + fDistance = s; // to na tym torze stoimy + return nullptr; // stop, skanowanie nie dało sensownych rezultatów + } + // jak tor zajęty innym składem, to nie ma po co skanować + if( Untiloccupied && IsOccupiedByAnotherConsist( Track, fCurrentDistance * fDirection ) ) { + fDistance = s; // to na tym torze stoimy + return nullptr; // stop, skanowanie nie dało sensownych rezultatów + } + if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) + { // jeśli jest semafor na tym torze + fDistance = s; // to na tym torze stoimy + return Track; + } + TTrack *pTrackFrom; // odcinek poprzedni, do znajdywania końca dróg + while (s < fDistance) + { + // Track->ScannedFlag=true; //do pokazywania przeskanowanych torów + pTrackFrom = Track; // zapamiętanie aktualnego odcinka + s += fCurrentDistance; // doliczenie kolejnego odcinka do przeskanowanej długości + if (fDirection > 0) + { // jeśli szukanie od Point1 w kierunku Point2 + if (Track->iNextDirection) + fDirection = -fDirection; + Track = Track->CurrentNext(); // może być NULL + } + else // if (fDirection<0) + { // jeśli szukanie od Point2 w kierunku Point1 + if (!Track->iPrevDirection) + fDirection = -fDirection; + Track = Track->CurrentPrev(); // może być NULL + } + if (Track == pTrackFrom) + Track = nullptr; // koniec, tak jak dla torów + + // gdy dalej toru nie ma albo zerowa prędkość, albo uszkadza pojazd + // zwraca NULL, że skanowanie nie dało sensownych rezultatów + if( Track == nullptr ) { + fDistance = s; + return nullptr; + } + if( Track->VelocityGet() == 0.0 ) + { + fDistance = s; + return nullptr; + } + if( Untiloccupied && IsOccupiedByAnotherConsist( Track ) ) { + fDistance = s; + return nullptr; + } + fCurrentDistance = Track->Length(); + if ((Event = CheckTrackEventBackward(fDirection, Track, Vehicle, Eventdirection, End)) != nullptr) + { // znaleziony tor z eventem + fDistance = s; + return Track; + } + } + Event = nullptr; // jak dojdzie tu, to nie ma semafora + // zwraca ostatni sprawdzony tor + fDistance = s; + return Track; +} + +// sprawdzanie zdarzeń semaforów i ograniczeń szlakowych +void TController::SetProximityVelocity( double dist, double vel, glm::dvec3 const *pos ) +{ // Ra:przeslanie do AI prędkości + /* + //!!!! zastąpić prawidłową reakcją AI na SetProximityVelocity !!!! + if (vel==0) + {//jeśli zatrzymanie, to zmniejszamy dystans o 10m + dist-=10.0; + }; + if (dist<0.0) dist=0.0; + if ((vel<0)?true:dist>0.1*(physics->Vel*physics->Vel-vel*vel)+50) + {//jeśli jest dalej od umownej drogi hamowania + */ + PutCommand( "SetProximityVelocity", dist, vel, pos ); + /* + } + else + {//jeśli jest zagrożenie, że przekroczy + Mechanik->SetVelocity(floor(0.2*sqrt(dist)+vel),vel,stopError); + } + */ +} + +TCommandType TController::BackwardScan( double const Range ) +{ // sprawdzanie zdarzeń semaforów z tyłu pojazdu, zwraca komendę + // dzięki temu będzie można stawać za wskazanym sygnalizatorem, a zwłaszcza jeśli będzie jazda na kozioł + // ograniczenia prędkości nie są wtedy istotne, również koniec toru jest do niczego nie przydatny + // zwraca true, jeśli należy odwrócić kierunek jazdy pojazdu + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) ) { + // skanowanie sygnałów tylko gdy jedzie w trybie manewrowym albo czeka na rozkazy + return TCommandType::cm_Unknown; + } + // kierunek jazdy względem sprzęgów pojazdu na czele + int const startdir = -pVehicles[0]->DirectionGet(); + if( startdir == 0 ) { + // jeśli kabina i kierunek nie jest określony nie robimy nic + return TCommandType::cm_Unknown; + } + // szukamy od pierwszej osi w wybranym kierunku + double scandir = startdir * pVehicles[0]->RaDirectionGet(); + + if( scandir == 0.0 ) { return TCommandType::cm_Unknown; } + + // skanowanie toru w poszukiwaniu eventów GetValues (PutValues nie są przydatne) + // Ra: przy wstecznym skanowaniu prędkość nie ma znaczenia + double scandist = Range; // zmodyfikuje na rzeczywiście przeskanowane + basic_event *e = nullptr; // event potencjalnie od semafora + // opcjonalnie może być skanowanie od "wskaźnika" z przodu, np. W5, Tm=Ms1, koniec toru wg + // drugiej osi w kierunku ruchu + auto const *scantrack{BackwardTraceRoute(scandist, scandir, pVehicles[VehicleEnd::front], e)}; + auto const dir{(double)startdir * + pVehicles[VehicleEnd::front]->VectorFront()}; // wektor w kierunku jazdy/szukania + + // jeśli wstecz wykryto koniec toru to raczej nic się nie da w takiej sytuacji zrobić + if (e == nullptr) + { + return TCommandType::cm_Unknown; + } + if (typeid(*e) != typeid(getvalues_event)) + { + return TCommandType::cm_Unknown; + } + + // jeśli jest jakiś sygnał na widoku + double scanvel; // prędkość ustawiona semaforem +#if LOGBACKSCAN + std::string edir{"Backward scan by " + pVehicle->asName + " - " + + ((scandir > 0) ? "Event2 " : "Event1 ")}; + edir += "(" + (e->name()) + ")"; +#endif + { + // najpierw sprawdzamy, czy semafor czy inny znak został przejechany + auto const sl{e->input_location()}; // położenie komórki pamięci + auto const pos{pVehicles[VehicleEnd::rear]->RearPosition()}; // pozycja tyłu + if (auto const sem{sl - pos}; dir.x * sem.x + dir.z * sem.z < 0) // wektor do komórki pamięci od końca składu + { + // jeśli został minięty + // iloczyn skalarny jest ujemny, gdy sygnał stoi z tyłu +#if LOGBACKSCAN + WriteLog(edir + " - ignored as not passed yet"); +#endif + return TCommandType::cm_Unknown; // nic + } + scanvel = e->input_value(1); // prędkość przy tym semaforze +#if LOGBACKSCAN + // przeliczamy odległość od semafora - potrzebne by były współrzędne początku składu + scandist = std::max(glm::length(sl - pos) - 2.0, 0.0); // 2m luzu przy manewrach wystarczy, ujemnych nie ma po co wysyłać +#endif + } + + auto move{false}; // czy AI w trybie manewerowym ma dociągnąć pod S1 + if (e->input_command() == TCommandType::cm_SetVelocity) + { + if (scanvel == 0.0 ? OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : + OrderCurrentGet() & DriverOrder::connect) + { // przy podczepianiu ignorować wyjazd? + move = true; // AI w trybie manewerowym ma dociągnąć pod S1 + } + else + { + // jeśli semafor jest daleko, a pojazd jedzie, to informujemy o zmianie prędkości + // jeśli jedzie manewrowo, musi dostać SetVelocity, żeby sie na pociągowy przełączył + // w przeciwnym razie ustawiamy prędkość tylko wtedy, gdy ma ruszyć, stanąć albo ma stać + // ruszać stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam +#if LOGBACKSCAN + if (scandist > fMinProximityDist && + occupied->Vel > EU07_AI_NOMOVEMENT && false == OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt)) + { + WriteLog(edir); + } + else + { + WriteLog(edir + " - [SetVelocity] [" + to_string(scanvel, 2) + "] [" + + to_string(e->input_value(2), 2) + "]"); + } +#endif + return scanvel > 0 ? TCommandType::cm_SetVelocity : TCommandType::cm_Unknown; + } + } + // reakcja AI w trybie manewrowym dodatkowo na sygnały manewrowe + if ((false == OrderCurrentGet().Empty() ? OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) : true) && (move || e->input_command() == TCommandType::cm_ShuntVelocity)) // w Wait_for_orders też widzi tarcze + { + // jeśli powyżej było SetVelocity 0 0, to dociągamy pod S1 + /* + if ((scandist > fMinProximityDist) && + ((occupied->Vel > EU07_AI_NOMOVEMENT) || (scanvel == 0.0))) + { + // jeśli tarcza jest daleko, to: + //- jesli pojazd jedzie, to informujemy o zmianie prędkości + //- jeśli stoi, to z własnej inicjatywy może podjechać pod zamkniętą tarczę + if (occupied->Vel > EU07_AI_NOMOVEMENT) // tylko jeśli jedzie + { // Mechanik->PutCommand("SetProximityVelocity",scandist,scanvel,sl); + #if LOGBACKSCAN + // WriteLog(edir+"SetProximityVelocity "+AnsiString(scandist)+" + // "+AnsiString(scanvel)); + WriteLog(edir); + #endif + // SetProximityVelocity(scandist,scanvel,&sl); + // jeśli jedzie na W5 albo koniec toru, to można zmienić kierunek + return (drivingFlags.trackEnd) ? TCommandType::cm_ChangeDirection : + TCommandType::cm_Unknown; + // TBD: request direction change also if VelNext in current direction is 0, + // while signal behind requests movement? + } + } + else + { + // ustawiamy prędkość tylko wtedy, gdy ma ruszyć, albo stanąć albo ma stać pod + // tarczą stop trzeba powtarzać, bo inaczej zatrąbi i pojedzie sam if + // ((physics->Vel==0.0)||(scanvel==0.0)) //jeśli jedzie lub ma stanąć/stać + { // nie dostanie komendy jeśli jedzie i ma jechać + // PutCommand("ShuntVelocity",scanvel,e->Params[9].asMemCell->Value2(),&sl,stopSem); + #if LOGBACKSCAN + WriteLog(edir + " - [ShuntVelocity] [" + to_string(scanvel, 2) + "] [" + + to_string(e->input_value(2), 2) + "]"); + #endif + return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : + TCommandType::cm_Unknown); + } + } + // NOTE: dead code due to returns in branching above + if ((scanvel != 0.0) && (scandist < 100.0)) + { + // jeśli Tm w odległości do 100m podaje zezwolenie na jazdę, to od razu ją + // ignorujemy, aby móc szukać kolejnej eSignSkip=e; //wtedy uznajemy ignorowaną przy + // poszukiwaniu nowej + #if LOGBACKSCAN + WriteLog(edir + " - will be ignored due to Ms2"); + #endif + return (scanvel > 0 ? TCommandType::cm_ShuntVelocity : TCommandType::cm_Unknown); + } + */ + return VelNext > 0 ? + TCommandType::cm_Unknown : // no need to bother if we can continue in current direction + scanvel == 0 ? + TCommandType::cm_Unknown : // no need to bother with a stop signal + TCommandType::cm_ShuntVelocity; // otherwise report a relevant shunt signal behind + // if (move?... + } // if (OrderCurrentGet()==Shunt) + + return e->m_passive && e->is_command() ? TCommandType::cm_Command : TCommandType::cm_Unknown; +}; + +std::string TController::NextStop() const +{ // informacja o następnym zatrzymaniu, wyświetlane pod [F1] + if (asNextStop == "[End of route]") + return ""; // nie zawiera nazwy stacji, gdy dojechał do końca + // dodać godzinę odjazdu + // the name the way the timetable spells it, in utf-8 as the user interface takes it + auto nextstop{ TrainParams.station_caption( asNextStop ) }; + auto const *t{ TrainParams.TimeTable + TrainParams.StationIndex }; + if( t->Ah >= 0 ) { + // przyjazd + nextstop += " przyj." + std::to_string( t->Ah ) + ":" + + to_minutes_str( t->Am, true, 3 ); + + } + if( t->Dh >= 0 ) { + // jeśli jest godzina odjazdu + nextstop += " odj." + std::to_string( t->Dh ) + ":" + + to_minutes_str( t->Dm, true, 3 ); + } + return nextstop; +}; + +void TController::UpdateDelayFlag() { + + if( TrainParams.CheckTrainLatency() < 0.0 ) { + // odnotowano spóźnienie + drivingFlags.late = true; + } + else { + // przyjazd o czasie + drivingFlags.late = false; + } +} + +// returns most recently calculated distance to potential obstacle ahead +double +TController::TrackObstacle() const { + + return Obstacle.distance; +} + +// check for potential collisions +void +TController::scan_obstacles( double const Range ) { + // HACK: vehicle order in the consist is based on intended travel direction + // if our actual travel direction doesn't match that, we should be scanning from the other end of the consist + // we cast to int to avoid getting confused by microstutters + auto *frontvehicle { pVehicles[ ( static_cast( occupied->V() ) * iDirection >= 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; + + int routescandirection; + // for moving vehicle determine heading from velocity; for standing fall back on the set direction + if( std::abs(frontvehicle->physics->V()) > 0.5 ? // ignore potential micro-stutters in oposite direction during "almost stop" + frontvehicle->physics->V() > 0.0 : + pVehicle->DirectionGet() == frontvehicle->DirectionGet() ? iDirection >= 0 : iDirection <= 0 ) { + // towards coupler 0 + routescandirection = NumberOf( VehicleEnd::front ); + } + else { + // towards coupler 1 + routescandirection = NumberOf( VehicleEnd::rear ); + } +/* + if( pVehicle->physics->CabOccupied() < 0 ) { + // flip the scan direction in the rear cab + routescandirection ^= routescandirection; + } +*/ + Obstacle = neighbour_data(); + auto const obstaclescanrange { std::max( is_car() ? 250.0 : 1000.0, Range ) }; + auto const lookup { frontvehicle->find_vehicle( routescandirection, obstaclescanrange ) }; + + if( std::get( lookup ) == true ) { + + Obstacle.vehicle = std::get( lookup ); + Obstacle.vehicle_end = std::get( lookup ); + Obstacle.distance = std::get( lookup ); + + if( Obstacle.distance < ( is_car() ? 50 : 100 ) ) { + // at short distances (re)calculate range between couplers directly + Obstacle.distance = physics::Vehicle::CouplerDist( frontvehicle->physics, Obstacle.vehicle->physics ); + } + } +} + +void +TController::check_route_ahead( double const Range ) { + + auto const comm { TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ) }; + + switch (comm) { + // ustawienie VelSignal - trochę proteza = do przemyślenia + case TCommandType::cm_Ready: { // W4 zezwolił na jazdę + // ewentualne doskanowanie trasy za W4, który zezwolił na jazdę + TableCheck( Range ); + TableUpdate( VelDesired, ActualProximityDist, VelNext, AccDesired ); // aktualizacja po skanowaniu + if( VelNext == 0.0 ) { + break; // ale jak coś z przodu zamyka, to ma stać + } + if( drivingFlags.stopCloser ) { + VelSignal = -1.0; // ma czekać na sygnał z sygnalizatora! + } + break; + } + case TCommandType::cm_SetVelocity: { // od wersji 357 semafor nie budzi wyłączonej lokomotywy + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && std::fabs(VelSignal) >= 1.0 ) { // jedzie w dowolnym trybie albo Wait_for_orders + // 0.1 nie wysyła się do samochodow, bo potem nie ruszą + PutCommand("SetVelocity", VelSignal, VelNext, nullptr); // komenda robi dodatkowe operacje + } + break; + } + case TCommandType::cm_ShuntVelocity: { // od wersji 357 Tm nie budzi wyłączonej lokomotywy + if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ).Empty() ) { // jedzie w dowolnym trybie albo Wait_for_orders + PutCommand( "ShuntVelocity", VelSignal, VelNext, nullptr ); + } + else if( false == iCoupler.Empty() ) { // jeśli jedzie w celu połączenia + SetVelocity( VelSignal, VelNext ); + } + break; + } + case TCommandType::cm_Command: { // komenda z komórki + if( OrderCurrentGet().Without(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank).Empty() && occupied->Vel < 0.1 ) { + // jedzie w dowolnym trybie albo Wait_for_orders + // dopiero jak stanie + /* + PutCommand( eSignNext->text(), eSignNext->value( 1 ), eSignNext->value( 2 ), nullptr ); + eSignNext->StopCommandSent(); // się wykonało już + */ // replacement of the above + eSignNext->send_command(*this); + } + break; + } + default: { + break; + } + } +} + +void +TController::check_route_behind( double const Range ) { + + if( VelNext != 0.0 ) { return; } // not if we can move ahead + if( drivingFlags.connect ) { return; } // not if we're in middle of coupling operation + + if( OrderCurrentGet().Without( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ).Empty() ) { + // jedzie w Shunt albo Connect, albo Wait_for_orders + // w trybie Connect skanować do tyłu tylko jeśli przed kolejnym sygnałem nie ma taboru do podłączenia + auto const couplinginprogress { + OrderCurrentGet().HasAll(DriverOrder::connect) + && ( Obstacle.distance < std::min(2000.0, FirstSemaphorDist) + || drivingFlags.connect ) }; + if( couplinginprogress ) { return; } + + auto const commandbehind { BackwardScan( Range ) }; + if( commandbehind != TCommandType::cm_Unknown ) { + // jeśli w drugą można jechać + // należy sprawdzać odległość od znalezionego sygnalizatora, + // aby w przypadku prędkości 0.1 wyciągnąć najpierw skład za sygnalizator + // i dopiero wtedy zmienić kierunek jazdy, oczekując podania prędkości >0.5 + if( commandbehind == TCommandType::cm_Command ) { + // jeśli komenda Shunt to ją odbierz bez przemieszczania się (np. odczep wagony po dopchnięciu do końca toru) + drivingFlags.stopHere = true; + } + iDirectionOrder = -iDirection; // zmiana kierunku jazdy + // zmiana kierunku bez psucia kolejnych komend + OrderCurrentSet( (OrderCurrentGet() | DriverOrder::changeDirection) ); + } + } +} diff --git a/vehicle/ai/orders.cpp b/vehicle/ai/orders.cpp new file mode 100644 index 000000000..d39ae8e69 --- /dev/null +++ b/vehicle/ai/orders.cpp @@ -0,0 +1,1246 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the orders of the driver and the commands it gets from the scenery + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +std::string StopReasonTable[] = { + // przyczyny zatrzymania ruchu AI + "", // stopNone, //nie ma powodu - powinien jechać + "Off", // stopSleep, //nie został odpalony, to nie pojedzie + "Semaphore", // stopSem, //semafor zamknięty + "Time", // stopTime, //czekanie na godzinę odjazdu + "End of track", // stopEnd, //brak dalszej części toru + "Change direction", // stopDir, //trzeba stanąć, by zmienić kierunek jazdy + "Joining", // stopJoin, //zatrzymanie przy (p)odczepianiu + "Block", // stopBlock, //przeszkoda na drodze ruchu + "A command", // stopComm, //otrzymano taką komendę (niewiadomego pochodzenia) + "Out of station", // stopOut, //komenda wyjazdu poza stację (raczej nie powinna zatrzymywać!) + "Radiostop", // stopRadio, //komunikat przekazany radiem (Radiostop) + "External", // stopExt, //przesłany z zewnątrz + "Error", // stopError //z powodu błędu w obliczeniu drogi hamowania +}; + +// zamiana kodu rozkazu na opis +std::string TController::Order2Str(DriverOrders Order) const { + + if( Order.HasAny(DriverOrder::changeDirection) + && Order != DriverOrder::changeDirection ) { + // może być nałożona na inną i wtedy ma priorytet + return + Order2Str( DriverOrder::changeDirection ) + + " + " + + Order2Str( Order.Without(DriverOrder::changeDirection) ); + } + switch( SingleOrder( Order ) ) { + case DriverOrder::waitForOrders: return "Wait_for_orders"; + case DriverOrder::prepareEngine: return "Prepare_engine"; + case DriverOrder::releaseEngine: return "Release_engine"; + case DriverOrder::changeDirection: return "Change_direction"; + case DriverOrder::connect: return "Connect"; + case DriverOrder::disconnect: return "Disconnect"; + case DriverOrder::shunt: return "Shunt"; + case DriverOrder::looseShunt: return "Loose_shunt"; + case DriverOrder::obeyTrain: return "Obey_train"; + case DriverOrder::bank: return "Bank"; + case DriverOrder::jumpToFirstOrder: return "Jump_to_first_order"; + default: return "Undefined"; + } +} + +std::array orderbuffer; + +std::string TController::OrderCurrent() const +{ // pobranie aktualnego rozkazu celem wyświetlenia + auto const order { OrderCurrentGet() }; + // generally prioritize direction change... + if( order & DriverOrder::changeDirection && false == drivingFlags.connect ) { + // ...but not in the middle of coupling operation + return STR("Change direction"); + } + + switch( SingleOrder( order.Without(DriverOrder::changeDirection) ) ) { + case DriverOrder::waitForOrders: { return STR("Wait for orders"); } + case DriverOrder::prepareEngine: { return STR("Start the engine"); } + case DriverOrder::releaseEngine: { return STR("Shut down the engine"); } + case DriverOrder::changeDirection: { return STR("Change direction"); } + case DriverOrder::connect: { return STR("Couple to consist ahead"); } + case DriverOrder::disconnect: { + if( iVehicleCount < 0 ) { + // done with uncoupling, order should update shortly + return STR("Wait for orders"); + } + // try to provide some task details + auto const count { iVehicleCount }; + + if( iVehicleCount > 1 ) { + std::snprintf( + orderbuffer.data(), orderbuffer.size(), + STR_C("the engine plus %d next vehicles"), // TODO: implement plural forms + count ); + } + auto const countstring { ( + count == 0 ? STR("the engine") : + count == 1 ? STR("the engine plus the next vehicle") : + orderbuffer.data() ) }; + + std::snprintf( + orderbuffer.data(), orderbuffer.size(), + STR_C("Uncouple %s"), + countstring.c_str() ); + return orderbuffer.data(); + } + case DriverOrder::shunt: { return STR("Shunt according to signals"); } + case DriverOrder::looseShunt: { return STR("Loose shunt according to signals"); } + case DriverOrder::obeyTrain: { return STR("Drive according to signals and timetable"); } + case DriverOrder::bank: { return STR("Bank consist ahead"); } + default: { return{}; } + } +}; + +void TController::OrdersClear() +{ // czyszczenie tabeli rozkazów na starcie albo po dojściu do końca + OrderPos = 0; + OrderTop = 1; // szczyt stosu rozkazów + for (int b = 0; b < maxorders; b++) + OrderList[b] = DriverOrder::waitForOrders; +#if LOGORDERS + OrdersDump("OrdersClear", false); +#endif +}; + +void TController::RecognizeCommand() +{ // odczytuje i wykonuje komendę przekazaną lokomotywie + TCommand *c = &occupied->CommandIn; + PutCommand(c->Text, c->Value1, c->Value2, c->Location, stopComm); + c->Command = VehicleCommand::none; + c->Argument.clear(); + c->Text = ""; // usunięcie obsłużonej komendy +} + +void TController::PutCommand(std::string NewCommand, double NewValue1, double NewValue2, const TLocation &NewLocation, TStopReason reason) +{ // wysłanie komendy przez event PutValues, jak pojazd ma obsadę, to wysyła tutaj, a nie do pojazdu bezpośrednio + // zamiana na współrzędne scenerii + glm::dvec3 sl { -NewLocation.X, NewLocation.Z, NewLocation.Y }; + if (!PutCommand(NewCommand, NewValue1, NewValue2, &sl, reason)) + occupied->PutCommand(NewCommand, NewValue1, NewValue2, NewLocation); +} + +bool TController::PutCommand( std::string NewCommand, double NewValue1, double NewValue2, glm::dvec3 const *NewLocation, TStopReason reason ) +{ // analiza komendy + if (NewCommand == "CabSignal") + { // SHP wyzwalane jest przez człon z obsadą, ale obsługiwane przez silnikowy + // nie jest to najlepiej zrobione, ale bez symulacji obwodów lepiej nie będzie + // Ra 2014-04: jednak przeniosłem do rozrządczego + occupied->PutCommand(NewCommand, NewValue1, NewValue2, occupied->Loc()); + occupied->RunInternalCommand(); // rozpoznaj komende bo lokomotywa jej nie rozpoznaje + return true; // załatwione + } + + if (NewCommand == "Overhead") + { // informacja o stanie sieci trakcyjnej + fOverhead1 = NewValue1; // informacja o napięciu w sieci trakcyjnej (0=brak drutu, zatrzymaj!) + fOverhead2 = NewValue2; // informacja o sposobie jazdy (-1=normalnie, 0=bez prądu, >0=z + // opuszczonym i ograniczeniem prędkości) + return true; // załatwione + } + + if (NewCommand == "Emergency_brake") // wymuszenie zatrzymania, niezależnie kto prowadzi + { // Ra: no nadal nie jest zbyt pięknie +// SetVelocity(0, 0, reason); + occupied->PutCommand("Emergency_brake", 1.0, 1.0, occupied->Loc()); + return true; // załatwione + } + + if (NewCommand.compare(0, 10, "Timetable:") == 0) + { // przypisanie nowego rozkładu jazdy, również prowadzonemu przez użytkownika + NewCommand.erase(0, 10); // zostanie nazwa pliku z rozkładem +#if LOGSTOPS + WriteLog("New timetable for " + pVehicle->asName + ": " + NewCommand); // informacja +#endif + TrainParams = TTrainParameters(NewCommand); // rozkład jazdy + tsGuardSignal = sound_source { sound_placement::internal, 2 * EU07_SOUND_CABCONTROLSCUTOFFRANGE }; // wywalenie kierownika + m_lastexchangestop.clear(); + m_stopflags = {}; + if (NewCommand != "none") + { + if (false == TrainParams.LoadTTfile( + std::string(Global.asCurrentSceneryPath.c_str()), floor(NewValue2 + 0.5), + NewValue1)) // pierwszy parametr to przesunięcie rozkładu w czasie + { + if (ConversionError == -8) + ErrorLog("Missed timetable: " + NewCommand); + WriteLog("Cannot load timetable file " + NewCommand + "\r\nError " + + std::to_string(ConversionError) + " in position " + std::to_string(TrainParams.StationCount)); + NewCommand = ""; // puste, dla wymiennej tekstury + } + else + { // inicjacja pierwszego przystanku i pobranie jego nazwy + // HACK: clear the potentially set door state flag to ensure door get opened if applicable + if( true == aiControlled ) { + // simplified door closing procedure, to sync actual door state with the door state flag + // NOTE: this may result in visually ugly quick switch between closing and opening the doors, but eh + if( pVehicle->physics->Doors.close_control == control_t::driver + || pVehicle->physics->Doors.close_control == control_t::mixed ) { + pVehicle->physics->OperateDoors( VehicleSide::right, false ); + pVehicle->physics->OperateDoors( VehicleSide::left, false ); + } + if( pVehicle->physics->Doors.permit_needed ) { + pVehicle->physics->PermitDoors( VehicleSide::right, false ); + pVehicle->physics->PermitDoors( VehicleSide::left, false ); + } + } + drivingFlags.doorOpened = false; + + TrainParams.UpdateMTable( simulation::Time, TrainParams.NextStationName ); + TrainParams.StationIndexInc(); // przejście do następnej + TrainParams.StationStart = TrainParams.StationIndex; + asNextStop = TrainParams.NextStop(); + // the flags of the first station until the train stops there + m_stopflags = TrainParams.stop_flags(); + m_lastannouncement = announcement_t::idle; + drivingFlags.primary = true; // skoro dostał rozkład, to jest teraz głównym +// NewCommand = Global.asCurrentSceneryPath + NewCommand; + auto lookup = + FileExists( + { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, + { ".ogg", ".flac", ".wav" } ); + if( false == lookup.first.empty() ) { + // wczytanie dźwięku odjazdu podawanego bezpośrenido + tsGuardSignal = sound_source( sound_placement::external, 75.f ).deserialize( lookup.first + lookup.second, sound_type::single ); + iGuardRadio = 0; // nie przez radio + } + else { + NewCommand += "radio"; + lookup = + FileExists( + { Global.asCurrentSceneryPath + NewCommand, paths::sounds + NewCommand }, + { ".ogg", ".flac", ".wav" } ); + if( false == lookup.first.empty() ) { + // wczytanie dźwięku odjazdu w wersji radiowej (słychać tylko w kabinie) + tsGuardSignal = sound_source( sound_placement::internal, EU07_SOUND_HANDHELDRADIORANGE ).deserialize( lookup.first + lookup.second, sound_type::single ); + iGuardRadio = iRadioChannel; + } + } + NewCommand = TrainParams.Relation2; // relacja docelowa z rozkładu + } + // jeszcze poustawiać tekstury na wyświetlaczach + TDynamicObject *p = pVehicles[VehicleEnd::front]; + while (p) + { + p->DestinationSet(NewCommand, TrainParams.TrainName); // relacja docelowa + p = p->Next(); // pojazd podłączony od tyłu (licząc od czoła) + } + } + if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład (trainset + // nie podaje) + { + auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego + auto d = pVehicle->VectorFront(); // wektor wskazujący przód + iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? + 1 : + -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie + /* + if (NewValue1!=0.0) //jeśli ma jechać + if (iDirectionOrder==0) //a kierunek nie był określony (normalnie określany przez + reardriver/headdriver) + iDirectionOrder=NewValue1>0?1:-1; //ustalenie kierunku jazdy względem sprzęgów + else + if (NewValue1<0) //dla ujemnej prędkości + iDirectionOrder=-iDirectionOrder; //ma jechać w drugą stronę + */ + if (aiControlled) // jeśli prowadzi komputer + Activation(); // umieszczenie obsługi we właściwym członie, ustawienie nawrotnika w + // przód + } + /* + else + if (!iDirectionOrder) + {//jeśli nie ma kierunku, trzeba ustalić + if (occupied->V()!=0.0) + iDirectionOrder=occupied->V()>0?1:-1; + else + iDirectionOrder=occupied->CabOccupied(); + if (!iDirectionOrder) iDirectionOrder=1; + } + */ + // jeśli wysyłane z Trainset, to wszystko jest już odpowiednio ustawione + // if (!NewLocation) //jeśli wysyłane z Trainset + // if (occupied->CabActive*occupied->V()*NewValue1<0) //jeśli zadana prędkość niezgodna z + // aktualnym kierunkiem jazdy + // DirectionForward(false); //jedziemy do tyłu (nawrotnik do tyłu) + // CheckVehicles(); //sprawdzenie składu, AI zapali światła + TableClear(); // wyczyszczenie tabelki prędkości, bo na nowo trzeba określić kierunek i + // sprawdzić przystanki + OrdersInit(fabs(NewValue1)); // ustalenie tabelki komend wg rozkładu oraz prędkości początkowej + // if (NewValue1!=0.0) if (!AIControllFlag) DirectionForward(NewValue1>0.0); //ustawienie + // nawrotnika użytkownikowi (propaguje się do członów) + // if (NewValue1>0) + // TrainNumber=floor(NewValue1); //i co potem ??? + return true; // załatwione + } + + if (NewCommand == "SetVelocity") + { + if (NewLocation) + vCommandLocation = *NewLocation; + if (NewValue1 != 0.0 && OrderCurrentGet() != DriverOrder::obeyTrain) + { // o ile jazda + if( false == iEngineActive ) { + // trzeba odpalić silnik najpierw, światła ustawi + OrderNext( DriverOrder::prepareEngine ); + } + OrderNext(DriverOrder::obeyTrain); // to uruchomić jazdę pociągową (od razu albo po odpaleniu silnika + OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje + } + if (NewValue1 != 0.0) // jeśli jechać + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone + else + drivingFlags.stopHere = true; // stać do momentu podania komendy jazdy + SetVelocity(NewValue1, NewValue2, reason); // bylo: nic nie rob bo SetVelocity zewnetrznie + // jest wywolywane przez dynobj.cpp + return true; + } + + if( NewCommand == "PointVelocity" ) { + // read by the speed table scan only; when the cell's event runs, there is nothing to do + return true; + } + + if (NewCommand == "SetProximityVelocity") + { + /* + if (SetProximityVelocity(NewValue1,NewValue2)) + if (NewLocation) + vCommandLocation=*NewLocation; + */ + return true; + } + + if (NewCommand == "ShuntVelocity") + { // uruchomienie jazdy manewrowej bądź zmiana prędkości + if (NewLocation) + vCommandLocation = *NewLocation; + // if (OrderList[OrderPos]=Obey_train) and (NewValue1<>0)) + if (false == iEngineActive) + OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw + OrderNext(DriverOrder::shunt); // zamieniamy w aktualnej pozycji, albo dodajey za odpaleniem silnika + if (NewValue1 != 0.0) + { + // if (iVehicleCount>=0) WriteLog("Skasowano ilosć wagonów w ShuntVelocity!"); + iVehicleCount = -2; // wartość neutralna + CheckVehicles(); // zabrać to do OrderCheck() + } + // dla prędkości ujemnej przestawić nawrotnik do tyłu? ale -1=brak ograniczenia !!!! + drivingFlags.press = false; // bez dociskania + SetVelocity(NewValue1, NewValue2, reason); + if (NewValue1 != 0.0) + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone + else + drivingFlags.stopHere = true; // ma stać w miejscu + if (fabs(NewValue1) > 2.0) // o ile wartość jest sensowna (-1 nie jest konkretną wartością) + fShuntVelocity = fabs(NewValue1); // zapamiętanie obowiązującej prędkości dla manewrów + + return true; + } + + if (NewCommand == "Wait_for_orders") + { // oczekiwanie; NewValue1 - czas oczekiwania, -1 = na inną komendę + if (NewValue1 > 0.0 ? NewValue1 > fStopTime : false) + fStopTime = NewValue1; // Ra: włączenie czekania bez zmiany komendy + else + OrderCurrentSet( DriverOrder::waitForOrders ); // czekanie na komendę (albo dać OrderPos=0) + + return true; + } + + if (NewCommand == "Prepare_engine") + { // włączenie albo wyłączenie silnika (w szerokim sensie) + OrdersClear(); // czyszczenie tabelki rozkazów, aby nic dalej nie robił + if (NewValue1 == 0.0) + OrderNext(DriverOrder::releaseEngine); // wyłączyć silnik (przygotować pojazd do jazdy) + else if (NewValue1 > 0.0) + OrderNext(DriverOrder::prepareEngine); // odpalić silnik (wyłączyć wszystko, co się da) + // po załączeniu przejdzie do kolejnej komendy, po wyłączeniu na Wait_for_orders + return true; + } + + if (NewCommand == "Change_direction") + { + DriverOrders o = OrderCurrentGet(); // co robił przed zmianą kierunku + if (false == iEngineActive) + OrderNext(DriverOrder::prepareEngine); // trzeba odpalić silnik najpierw + if (NewValue1 == 0.0) + iDirectionOrder = -iDirection; // zmiana na przeciwny niż obecny + else if (NewLocation) // jeśli podane współrzędne eventu/komórki ustawiającej rozkład + // (trainset nie podaje) + { + auto v = *NewLocation - pVehicle->GetPosition(); // wektor do punktu sterującego + auto d = pVehicle->VectorFront(); // wektor wskazujący przód + iDirectionOrder = (v.x * d.x + v.z * d.z) * NewValue1 > 0 ? + 1 : + -1; // do przodu, gdy iloczyn skalarny i prędkość dodatnie + // iDirectionOrder=1; else if (NewValue1<0.0) iDirectionOrder=-1; + } + if ( + + iDirectionOrder != iDirection) + OrderNext(DriverOrder::changeDirection); // zadanie komendy do wykonania + if (o.HasAny(movingOrders)) // jeśli jazda manewrowa albo pociągowa + OrderNext(o); // to samo robić po zmianie + else if (!o) // jeśli wcześniej było czekanie + OrderNext(DriverOrder::shunt); // to dalej jazda manewrowa + if (occupied->Vel >= EU07_AI_MOVEMENT) // jeśli jedzie + drivingFlags.startHorn = false; // to bez trąbienia po ruszeniu z zatrzymania + // Change_direction wykona się samo i następnie przejdzie do kolejnej komendy + return true; + } + + if (NewCommand == "Obey_train") { + if( false == iEngineActive ) { + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw + } + OrderNext( DriverOrder::obeyTrain ); + // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? + OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje + + return true; + } + + if (NewCommand == "Bank") { + if( false == iEngineActive ) { + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw + } + OrderNext( DriverOrder::bank ); + // if (NewValue1>0) TrainNumber=floor(NewValue1); //i co potem ??? + OrderCheck(); // jeśli jazda pociągowa teraz, to wykonać niezbędne operacje + + return true; + } + + if( NewCommand == "Shunt" || NewCommand == "Loose_shunt" ) + { // NewValue1 - ilość wagonów (-1=wszystkie); NewValue2: 0=odczep, 1..63=dołącz, -1=bez zmian + //-3,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać w trybie pociągowym + //-2,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1), zmienić kierunek i czekać + //-2, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i czekać + //-1,-y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać w powrotną stronę + //-1, y - podłączyć do całego stojącego składu (sprzęgiem y>=1) i jechać dalej + //-1, 0 - tryb manewrowy bez zmian (odczepianie z pozostawieniem wagonów nie ma sensu) + // 0, 0 - odczepienie lokomotywy + // x,-y - podłączyć się do składu (sprzęgiem y>=1), a następnie odczepić i zabrać (x) wagonów + // 1, 0 - odczepienie lokomotywy z jednym wagonem + drivingFlags.stopHere = false; // podjeżanie do semaforów zezwolone + if( false == iEngineActive ) { + OrderNext( DriverOrder::prepareEngine ); // trzeba odpalić silnik najpierw + } + if (NewValue2 != 0) // jeśli podany jest sprzęg + { + iCoupler = CouplingSet::FromBits( static_cast( std::floor( std::abs( NewValue2 ) ) ) ); // jakim sprzęgiem + OrderNext(DriverOrder::connect); // najpierw połącz pojazdy + if (NewValue1 >= 0.0) // jeśli ilość wagonów inna niż wszystkie + { // to po podpięciu należy się odczepić + iDirectionOrder = -iDirection; // zmiana na ciągnięcie + OrderPush(DriverOrder::changeDirection); // najpierw zmień kierunek, bo odczepiamy z tyłu + OrderPush(DriverOrder::disconnect); // a odczep już po zmianie kierunku + if( NewValue2 > 0.0 + && NewCommand == "Loose_shunt" ) { + // after decoupling continue pushing in the original direction + // NOTE: for backward compatibility this option isn't supported for basic shunting mode + iDirectionOrder = iDirection; // back to pushing + OrderPush( DriverOrder::changeDirection ); + } + } + else if (NewValue2 < 0.0) // jeśli wszystkie, a sprzęg ujemny, to tylko zmiana kierunku po podczepieniu + { // np. Shunt -1 -3 + iDirectionOrder = -iDirection; // jak się podczepi, to jazda w przeciwną stronę + OrderNext(DriverOrder::changeDirection); + } + WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie + } + else { // if (NewValue2==0.0) //zerowy sprzęg + if( NewValue1 >= 0.0 ) { + // jeśli ilość wagonów inna niż wszystkie będzie odczepianie, + // ale jeśli wagony są z przodu, to trzeba najpierw zmienić kierunek + if( occupied->Couplers[occupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front].Connected == nullptr // z tyłu nic + && occupied->Couplers[occupied->DirAbsolute > 0 ? VehicleEnd::front : VehicleEnd::rear].Connected != nullptr ) { // a z przodu skład + iDirectionOrder = -iDirection; // zmiana na ciągnięcie + OrderNext( DriverOrder::changeDirection ); // najpierw zmień kierunek (zastąpi Disconnect) + OrderPush( DriverOrder::disconnect ); // a odczep już po zmianie kierunku + } + else if( occupied->Couplers[ occupied->DirAbsolute > 0 ? VehicleEnd::rear : VehicleEnd::front ].Connected != nullptr ) { // z tyłu coś + OrderNext( DriverOrder::disconnect ); // jak ciągnie, to tylko odczep (NewValue1) wagonów + } + else { + // both couplers empty + // NOTE: this condition implements legacy behavior (mis)used by some scenarios to keep vehicle idling without moving + SetVelocity( 0, 0, stopJoin ); + drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + } + WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać, chyba że już jedzie + } + } + if (NewValue1 == -1.0) { + drivingFlags.stopHere = false; // ma jechać + WaitingTime = 0.0; // nie ma co dalej czekać, można zatrąbić i jechać + } + if( NewValue1 < -1.5 ) { // jeśli -2/-3, czyli czekanie z ruszeniem na sygnał + drivingFlags.stopHere = true; // nie podjeżdżać do semafora, jeśli droga nie jest wolna + } + // (nie dotyczy Connect) + if( NewValue1 < -2.5 ) { // jeśli -3 to potem jazda pociągowa + OrderNext( NewCommand == "Shunt" ? DriverOrder::obeyTrain : DriverOrder::bank ); + } + else { // otherwise continue shunting + OrderNext( NewCommand == "Shunt" ? DriverOrder::shunt : DriverOrder::looseShunt ); + } + CheckVehicles(); // sprawdzić światła + iVehicleCount = std::floor( NewValue1 ); + + return true; + } + + if( NewCommand == "Jump_to_first_order" ) { + JumpToFirstOrder(); + return true; + } + + if (NewCommand == "Jump_to_order") + { + if( NewValue1 == -1.0 ) { + JumpToNextOrder(); + } + else if (NewValue1 >= 0 && NewValue1 < maxorders) + { + OrderPos = floor(NewValue1); + if( !OrderPos ) { + // zgodność wstecz: dopiero pierwsza uruchamia + OrderPos = 1; + } +#if LOGORDERS + OrdersDump("Jump_to_order"); +#endif + } + return true; + } + + if (NewCommand == "Warning_signal") + { + if( NewValue1 > 0 && NewValue2 > 0 ) { + fWarningDuration = NewValue1; // czas trąbienia + cue_action( driver_hint::hornon, NewValue2 ); // horn combination flag + simulation::Blackbox.horn_requested( + pVehicles[ VehicleEnd::front ], NewValue1, NewValue2, NewLocation != nullptr ? *NewLocation : pVehicles[ VehicleEnd::front ]->GetPosition() ); + } + return true; + } + + if (NewCommand == "Radio_channel") { + // wybór kanału radiowego (którego powinien używać AI, ręczny maszynista musi go ustawić sam) + if (NewValue1 >= 0) { + // wartości ujemne są zarezerwowane, -1 = nie zmieniać kanału + if( aiControlled ) { + iRadioChannel = NewValue1; + } + if( iGuardRadio ) { + // kierownikowi też zmienić + iGuardRadio = NewValue1; + } + } + // NewValue2 może zawierać dodatkowo oczekiwany kod odpowiedzi, np. dla W29 "nawiązać + // łączność radiową z dyżurnym ruchu odcinkowym" + return true; + } + + if( NewCommand == "SetLights" ) { + // set consist lights pattern hints + m_lighthints[ VehicleEnd::front ] = static_cast( NewValue1 ); + m_lighthints[ VehicleEnd::rear ] = static_cast( NewValue2 ); + if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // light hints only apply in the obey_train mode + CheckVehicles(); + } + return true; + } + + if (NewCommand == "SetSignal") { + auto const signal{std::lrint(NewValue1)}; + + drivingFlags.signalPc6 = false; + drivingFlags.signalA1 = false; + + if (NewValue2 > 0.5) + { + // another number set the bit of a driving flag of that number before + drivingFlags.signalPc6 = signal == Signal_Pc6; + drivingFlags.signalA1 = signal == Signal_A1; + } + else + CheckVehicles(); // restore light state + } + + return false; // nierozpoznana - wysłać bezpośrednio do pojazdu +}; + +void TController::JumpToNextOrder( bool const Ignoremergedchangedirection ) +{ // wykonanie kolejnej komendy z tablicy rozkazów + if (auto const currentorder { OrderCurrentGet() }; currentorder != DriverOrder::waitForOrders) + { + if( currentorder.HasAny(DriverOrder::changeDirection) // jeśli zmiana kierunku + && currentorder != DriverOrder::changeDirection && false == Ignoremergedchangedirection ) { // ale nałożona na coś + + // usunięcie zmiany kierunku z innej komendy + OrderCurrentSet( currentorder.Without(DriverOrder::changeDirection) ); + OrderCheck(); + return; + } + if (OrderPos < maxorders - 1) + ++OrderPos; + else + OrderPos = 0; + } + OrderCheck(); +#if LOGORDERS + OrdersDump("JumpToNextOrder"); // normalnie nie ma po co tego wypisywać +#endif +}; + +void TController::JumpToFirstOrder() +{ // taki relikt + OrderPos = 1; + if (OrderTop == 0) + OrderTop = 1; + OrderCheck(); +#if LOGORDERS + OrdersDump("JumpToFirstOrder"); // normalnie nie ma po co tego wypisywać +#endif +}; + +void TController::OrderCheck() +{ // reakcja na zmianę rozkazu + + if( OrderCurrentGet() != DriverOrder::obeyTrain ) { + // reset light hints + m_lighthints[ VehicleEnd::front ] = m_lighthints[ VehicleEnd::rear ] = -1; + } + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect | DriverOrder::obeyTrain | DriverOrder::bank ) ) { + CheckVehicles(); // sprawdzić światła + } + if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { + // HACK: ensure consist doors will be closed on departure + drivingFlags.doorOpened = true; + } + auto const currentorder { OrderCurrentGet() }; + if (currentorder & DriverOrder::changeDirection) // może być nałożona na inną i wtedy ma priorytet + iDirectionOrder = -iDirection; // trzeba zmienić jawnie, bo się nie domyśli + else if (currentorder == DriverOrder::obeyTrain) + drivingFlags.stopPoint = true; // W4 są widziane + else if (currentorder == DriverOrder::disconnect) + iVehicleCount = iVehicleCount < 0 ? 0 : iVehicleCount; // odczepianie lokomotywy + else if (currentorder == DriverOrder::connect) + drivingFlags.stopPoint = false; // podczas jazdy na połączenie nie zwracać uwagi na W4 + else if (currentorder == DriverOrder::waitForOrders) + OrdersClear(); // czyszczenie rozkazów i przeskok do zerowej pozycji +} + +void TController::OrderNext(DriverOrders NewOrder) +{ // ustawienie rozkazu do wykonania jako następny + if (OrderCurrentGet() == NewOrder) + return; // jeśli robi to, co trzeba, to koniec + if (!OrderPos) + OrderPos = 1; // na pozycji zerowej pozostaje czekanie + OrderTop = OrderPos; // ale może jest czymś zajęty na razie + if (NewOrder.HasAny(movingOrders)) // jeśli ma jechać + { // ale może być zajęty chwilowymi operacjami + while (OrderTop >= 0 && OrderTop < maxorders - 1 + && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders)) // jeśli coś robi + ++OrderTop; // pomijamy wszystkie tymczasowe prace + } + else + { // jeśli ma ustawioną jazdę, to wyłączamy na rzecz operacji + while (OrderTop >= 0 && OrderTop < maxorders - 1 + && OrderList[OrderTop] != DriverOrder::waitForOrders && false == OrderList[OrderTop].HasAny(movingOrders) && OrderList[OrderTop] != NewOrder) // jeśli coś robi + ++OrderTop; // pomijamy wszystkie tymczasowe prace + } + if (OrderTop < 0 || OrderTop >= maxorders) + { + ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); + return; + } + OrderList[OrderTop++] = NewOrder; // dodanie rozkazu jako następnego +#if LOGORDERS + OrdersDump( "OrderNext" ); // normalnie nie ma po co tego wypisywać +#endif +} + +void TController::OrderPush(DriverOrders NewOrder) +{ // zapisanie na stosie kolejnego rozkazu do wykonania + if (OrderPos == OrderTop && false == OrderCurrentGet().HasAny(movingOrders)) // jeśli miałby być zapis na aktalnej pozycji + // ale nie jedzie + ++OrderTop; + // niektóre operacje muszą zostać najpierw dokończone => zapis na kolejnej + if (OrderTop < 0 || OrderTop >= maxorders) + { + ErrorLog("Commands overflow: order \"" + Order2Str(NewOrder) + "\" dropped"); + return; + } + if (OrderList[OrderTop] != NewOrder) // jeśli jest to samo, to nie dodajemy + OrderList[OrderTop++] = NewOrder; // dodanie rozkazu na stos +#if LOGORDERS + OrdersDump( "OrderPush: [" + Order2Str( NewOrder ) + "]" ); // normalnie nie ma po co tego wypisywać +#endif +} + +void TController::OrdersDump( std::string const Neworder, bool const Verbose ) +{ // wypisanie kolejnych rozkazów do logu + WriteLog( "New order for [" + pVehicle->asName + "]: " + Neworder ); + if( false == Verbose ) { return; } + for (int b = 0; b < maxorders; ++b) + { + WriteLog( ( OrderPos == b ? ">" : " " ) + (std::to_string(b) + ": " + Order2Str(OrderList[b]))); + if (b && OrderList[b] == DriverOrder::waitForOrders) // z wyjątkiem pierwszej pozycji + // jeśli końcowa komenda + break; + // dalej nie trzeba + } +}; + +void TController::OrdersInit(double fVel) +{ // wypełnianie tabelki rozkazów na podstawie rozkładu + // ustawienie kolejności komend, niezależnie kto prowadzi + OrdersClear(); // usunięcie poprzedniej tabeli + OrderPush(DriverOrder::prepareEngine); // najpierw odpalenie silnika + if (TrainParams.StationCount == 0) + { // brak rozkładu to jazda manewrowa +// if (fVel > 0.05) // typowo 0.1 oznacza gotowość do jazdy, 0.01 tylko załączenie silnika + OrderPush(DriverOrder::shunt); // jeśli nie ma rozkładu, to manewruje + } + else + { // jeśli z rozkładem, to jedzie na szlak + if (fVel > 0.0 && fVel < 0.02) + OrderPush(DriverOrder::shunt); // dla prędkości 0.01 włączamy jazdę manewrową + else if (TrainParams.DirectionChange() ? // jeśli obrót na pierwszym przystanku + (drivingFlags.pushPull ? // SZT również! SN61 zależnie od wagonów... + TrainParams.TimeTable[1].StationName == TrainParams.Relation1 : + false) : + false) + OrderPush(DriverOrder::shunt); // a teraz start będzie w manewrowym, a tryb pociągowy włączy W4 + else + // jeśli start z pierwszej stacji i jednocześnie jest na niej zmiana kierunku, to EZT ma mieć Shunt + OrderPush(DriverOrder::obeyTrain); // dla starych scenerii start w trybie pociagowym + if (DebugModeFlag) // normalnie nie ma po co tego wypisywać + WriteLog("/* Timetable: " + TrainParams.ShowRelation()); + TMTableLine *t; + for (int i = 0; i <= TrainParams.StationCount; ++i) + { + t = TrainParams.TimeTable + i; + if (DebugModeFlag) { + // normalnie nie ma po co tego wypisywa? + WriteLog( + t->StationName + + " " + std::to_string(t->Ah) + ":" + std::to_string(t->Am) + + ", " + std::to_string(t->Dh) + ":" + std::to_string(t->Dm) + + " " + t->StationWare); + } + if ( contains( t->StationWare, '@' ) ) + { // zmiana kierunku i dalsza jazda wg rozk?adu + if (drivingFlags.pushPull) // SZT również! SN61 zależnie od wagonów... + { // jeśli skład zespolony, wystarczy zmienić kierunek jazdy + OrderPush(DriverOrder::changeDirection); // zmiana kierunku + } + else + { // dla zwykłego składu wagonowego odczepiamy lokomotywę + OrderPush(DriverOrder::disconnect); // odczepienie lokomotywy + OrderPush(DriverOrder::shunt); // a dalej manewry + } + if (i < TrainParams.StationCount) // jak nie ostatnia stacja + OrderPush(DriverOrder::obeyTrain); // to dalej wg rozkładu + } + } + if( DebugModeFlag ) { + // normalnie nie ma po co tego wypisywać + WriteLog( "*/" ); + } + OrderPush(DriverOrder::shunt); // po wykonaniu rozkładu przełączy się na manewry + } + // McZapkie-100302 - to ma byc wyzwalane ze scenerii + if( fVel == 0.0 ) { + // jeśli nie ma prędkości początkowej, to śpi + SetVelocity( 0, 0, stopSleep ); + } + else { + // jeśli podana niezerowa prędkość + if( fVel >= 1.0 + || fVel < 0.02 ) { + // jeśli ma jechać - dla 0.01 ma podjechać manewrowo po podaniu sygnału + // to do następnego W4 ma podjechać blisko + drivingFlags.stopHere = false; + drivingFlags.stopCloser = true; + } + else { + // czekać na sygnał + drivingFlags.stopHere = true; + } + JumpToFirstOrder(); + if (fVel >= 1.0) // jeśli ma jechać + SetVelocity(fVel, -1); // ma ustawić żądaną prędkość + else + SetVelocity(0, 0, stopSleep); // prędkość w przedziale (0;1) oznacza, że ma stać + } +#if LOGORDERS + OrdersDump( "OrdersInit", DebugModeFlag ); // wypisanie kontrolne tabelki rozkazów +#endif + // McZapkie! - zeby w ogole AI ruszyl to musi wykonac powyzsze rozkazy + // Ale mozna by je zapodac ze scenerii +}; + +std::string TController::StopReasonText() const +{ // informacja tekstowa o przyczynie zatrzymania + if (eStopReason != 7) // zawalidroga będzie inaczej + return StopReasonTable[eStopReason]; + else + return "Blocked by " + pVehicles[0]->PrevAny()->name(); +}; + +//---------------------------------------------------------------------------------------------------------------------- +// McZapkie: skanowanie semaforów +// Ra: stare funkcje skanujące, używane podczas manewrów do szukania sygnalizatora z tyłu +//- nie reagują na PutValues, bo nie ma takiej potrzeby +//- rozpoznają tylko zerową prędkość (jako koniec toru i brak podstaw do dalszego skanowania) +//---------------------------------------------------------------------------------------------------------------------- + +bool TController::IsOccupiedByAnotherConsist( TTrack *Track, double const Distance ) +{ // najpierw sprawdzamy, czy na danym torze są pojazdy z innego składu + if( false == Track->Dynamics.empty() ) { + for( auto dynamic : Track->Dynamics ) { + if( dynamic->ctOwner != this ) { + // jeśli jest jakiś cudzy to tor jest zajęty i skanowanie nie obowiązuje + if( Distance == 0 ) { + return true; + } + else { + // based on provided position of scanning vehicle and scan direction, filter out vehicles on irrelevant end + auto const scandirection { Distance > 0 ? 1 : -1 }; // positive value means scan towards point2 end of the track + auto const obstaclelocation { scandirection > 0 ? Track->Length() - dynamic->RaTranslationGet() : dynamic->RaTranslationGet() }; + // if detected vehicle is closer to the end of the track in scanned direction than we are, it means it's blocking our way + if( obstaclelocation < std::abs( Distance ) ) { + return true; + } + } + } + } + } + return false; // wolny +}; + +void +TController::UpdateChangeDirection() { + // TODO: rework into driver mode independent routine + if( false == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { return; } + + if( true == aiControlled && occupied->Vel < EU07_AI_NOMOVEMENT ) { + // sprobuj zmienic kierunek (może być zmieszane z jeszcze jakąś komendą) + // jeśli się zatrzymał, to zmieniamy kierunek jazdy, a nawet kabinę/człon + Activation(); // ustawienie zadanego wcześniej kierunku i ewentualne przemieszczenie AI + // Change_direction (tylko dla AI) + } + // shared part of the routine, implement if direction matches what was requested + if( occupied->Vel < EU07_AI_NOMOVEMENT + && iDirection == iDirectionOrder ) { + // NOTE: we can't be sure there's a visible signal within scan range after direction change + // which would normally overwrite the old limit, so we reset signal value manually here + VelSignal = -1; + VelSignalNext = -1; + PrepareEngine(); + JumpToNextOrder(); // następnie robimy, co jest do zrobienia (Shunt albo Obey_train) + if( OrderCurrentGet() & (DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect) && false == drivingFlags.stopHere ) { + // jeśli dalej mamy manewry + // o ile nie ma stać w miejscu, + // jechać od razu w przeciwną stronę i nie trąbić z tego tytułu: + drivingFlags.startHorn = false; + SetVelocity(fShuntVelocity, fShuntVelocity); + } + } +} + +void +TController::UpdateLooseShunt() { + // when loose shunting try to detect situations where engaged brakes in a consist to be pushed prevent movement + // TODO: run also for potential settings-based virtual assistant + auto const autobrakerelease { ( true == aiControlled ) }; + + if( autobrakerelease + && Obstacle.distance < 1.0 + && AccDesired > 0.1 + && occupied->Vel < 1.0 ) { + + auto *vehicle { Obstacle.vehicle }; + auto const direction { ( vehicle->Prev() != nullptr ? VehicleEnd::front : VehicleEnd::rear ) }; + while( vehicle != nullptr ) { + if( vehicle->physics->brakes.cylinderPressure > 0.2 ) { + vehicle->physics->BrakeLevelSet( 0 ); // hamulec na zero, aby nie hamował + vehicle->physics->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać + } + // NOTE: we trust the consist to be arranged in a valid chain + // TBD, TODO: traversal direction validation? + vehicle = direction == VehicleEnd::front ? vehicle->Prev() : vehicle->Next(); + } + } +} + +void +TController::UpdateObeyTrain() { + + UpdateNextStop(); + + if( drivingFlags.guardSignal + && VelDesired > 0.0 ) { + // komunikat od kierownika tu, bo musi być wolna droga i odczekany czas stania + drivingFlags.guardSignal = false; // tylko raz nadać + drivingFlags.guardOpenDoor = false; // nie trzeba już otwierać drzwi + if( false == tsGuardSignal.empty() ) { + tsGuardSignal.stop(); + // w zasadzie to powinien mieć flagę, czy jest dźwiękiem radiowym, czy bezpośrednim + // albo trzeba zrobić dwa dźwięki, jeden bezpośredni, słyszalny w + // pobliżu, a drugi radiowy, słyszalny w innych lokomotywach + // na razie zakładam, że to nie jest dźwięk radiowy, bo trzeba by zrobić + // obsługę kanałów radiowych itd. + if( iGuardRadio == 0 ) { + // jeśli nie przez radio + tsGuardSignal.owner( pVehicle ); + // place virtual conductor some distance away + tsGuardSignal.offset( { pVehicle->physics->Dim.W * -0.75f, 1.7f, std::min( -20.0, -0.2 * fLength ) } ); + tsGuardSignal.play( sound_flags::exclusive ); + // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera + fActionTime = -5.0; // niech trochę potrzyma + } + else { + // radio message + tsGuardSignal.owner( pVehicle ); +/* + tsGuardSignal.offset( { 0.f, 2.f, pVehicle->physics->Dim.L * 0.4f * ( pVehicle->physics->CabOccupied() < 0 ? -1 : 1 ) } ); + tsGuardSignal.play( sound_flags::exclusive ); +*/ + simulation::radio_message( &tsGuardSignal, iGuardRadio ); + // NOTE: we can't rely on is_playing() check as sound playback is based on distance from local camera + fActionTime = -5.0; // niech trochę potrzyma + } + } + } +} + +void +TController::UpdateConnect() { + // podłączanie do składu + if (drivingFlags.connect) { + // sprzęgi sprawdzamy w pierwszej kolejności, bo jak połączony, to koniec + auto *vehicle { iCouplingVehicle.value().first }; + auto const couplingend { iCouplingVehicle.value().second }; + auto *vehicleparameters { vehicle->physics }; + auto const &neighbour { vehicleparameters->Neighbours[ couplingend ] }; + // vehicles which can't share their control get coupled without the control connection (eu07/maszyna#520) + auto expectedcoupling { iCoupler }; + if( neighbour.vehicle != nullptr ) { + auto const neighbourend { neighbour.vehicle_end != 2 ? neighbour.vehicle_end : vehicleparameters->Couplers[ couplingend ].ConnectedNr }; + expectedcoupling = vehicleparameters->CompatibleCoupling( EndOf( couplingend ), *neighbour.vehicle->physics, EndOf( neighbourend ), iCoupler ); + } + if( vehicleparameters->Couplers[ couplingend ].CouplingFlag != expectedcoupling ) { + if( neighbour.vehicle != nullptr && neighbour.distance < 10 ) { + // check whether we need to attach coupler adapter + auto coupleriscompatible{true}; + auto const &coupler{vehicleparameters->Couplers[couplingend]}; + if (coupler.type() != TCouplerType::Automatic) + { + auto const &othercoupler = neighbour.vehicle->physics->Couplers[(neighbour.vehicle_end != 2 ? neighbour.vehicle_end : coupler.ConnectedNr)]; + if (othercoupler.type() == TCouplerType::Automatic) + { + coupleriscompatible = false; + cue_action(driver_hint::couplingadapterattach, couplingend); + } + } + // próba podczepienia + if ((aiControlled || Global.AITrainman) && coupleriscompatible && neighbour.distance < 2) + { + vehicleparameters->Attach(couplingend, neighbour.vehicle_end, neighbour.vehicle->physics, iCoupler); + } + } + } + // NOTE: no else as the preceeding block can potentially establish expected connection + if( vehicleparameters->Couplers[ couplingend ].CouplingFlag == expectedcoupling ) { + // jeżeli został podłączony + CheckVehicles( DriverOrder::connect ); // sprawdzić światła nowego składu + + iCoupler = {}; // dalsza jazda manewrowa już bez łączenia + iCouplingVehicle.reset(); + drivingFlags.connect = false; // zdjęcie flagi doczepiania + JumpToNextOrder( true ); // wykonanie następnej komendy + } + } // moveConnect + else { + // początek podczepiania, z wyłączeniem sprawdzania fTrackBlock + if( Obstacle.distance <= 20.0 && !iCouplingVehicle ) { + // write down which vehicle should be coupled with the target consist, + // so we don't lose track of it if the user does something unexpected + iCouplingVehicle = {pVehicles[VehicleEnd::front], NumberOf(pVehicles[VehicleEnd::front]->DirectionGet() > 0 ? VehicleEnd::front : VehicleEnd::rear)}; + drivingFlags.connect = true; + } + } +} + +int +TController::unit_count( int const Threshold ) const { + + auto *vehicle { pVehicle }; + auto unitcount { 1 }; + do { + auto const decoupledend{ ( vehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu + VehicleEnd::rear : + VehicleEnd::front ) }; + auto const coupling { vehicle->physics->Couplers[ decoupledend ].CouplingFlag }; + if( coupling == Coupling::none ) { + break; + } + // jeżeli sprzęg zablokowany to liczymy człony jako jeden + if( false == coupling.HasAny( Coupling::permanent ) ) { + ++unitcount; + } + vehicle = vehicle->Next(); + } while( unitcount < Threshold ); + + return unitcount; +} + +void +TController::UpdateDisconnect() { + + if( iVehicleCount >= 0 ) { + // early test for human drivers, who might disregard the proper procedure, or perform it before they receive the order to + if( false == aiControlled && unit_count(iVehicleCount + 2) <= iVehicleCount + 1 ) { + // iVehicleCount = 0 means the consist should be reduced to (1) leading unit, thus we increase our test values by 1 + iVehicleCount = -2; // odczepiono, co było do odczepienia + return; // we'll wrap up the procedure on the next update beat + } + // regular uncoupling procedure, performed by ai and naively expected from the human drivers + // 3rd stage: change direction, compress buffers and uncouple + if( iDirection != iDirectionOrder ) { + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( driver_hint::directionother ); + } + if( drivingFlags.press && iDirection == iDirectionOrder ) { + if( iVehicleCount >= 0 ) { + // zmieni się po odczepieniu + WriteLog( "Uncoupling [" + occupied->Name + "]: actuating and compressing buffers..." ); + cue_action( driver_hint::independentbrakerelease ); + cue_action( driver_hint::bufferscompress ); + } + + WriteLog( "Uncoupling [" + occupied->Name + "]: from " + ( occupied->DirAbsolute > 0 ? "front" : "rear" ) ); + auto *decoupledvehicle { pVehicle }; // pojazd do odczepienia, w (pVehicle) siedzi AI + int decoupledend; // numer sprzęgu, który sprawdzamy albo odczepiamy + auto vehiclecount { iVehicleCount }; // ile wagonów ma zostać + // szukanie pojazdu do odczepienia + do { + decoupledend = NumberOf( decoupledvehicle->DirectionGet() > 0 ? // numer sprzęgu od strony czoła składu + VehicleEnd::front : + VehicleEnd::rear ); + // jeżeli sprzęg zablokowany to liczymy człony jako jeden + if( decoupledvehicle->physics->Couplers[ decoupledend ].CouplingFlag & Coupling::permanent ) { + ++vehiclecount; + } + if( decoupledvehicle != pVehicle ) { + decoupledvehicle->physics->BrakeReleaser( 1 ); // wyluzuj pojazd, aby dało się dopychać + } + if( vehiclecount ) { // jeśli jeszcze nie koniec + decoupledvehicle = decoupledvehicle->Prev(); // kolejny w stronę czoła składu (licząc od tyłu), bo dociskamy + if( decoupledvehicle == nullptr ) { + vehiclecount = 0; // nie ma co dalej sprawdzać, odczepianie zakończone + } + } + } while( vehiclecount-- ); + if( decoupledvehicle == nullptr ) { + // no target, or already just virtual coupling + WriteLog( "Uncoupling [" + occupied->Name + "]: didn't find anything to disconnect" ); + iVehicleCount = -2; // odczepiono, co było do odczepienia + } + else { + if( aiControlled || Global.AITrainman ) { + decoupledvehicle->Dettach( decoupledend ); + } + // tylko jeśli odepnie + if( decoupledvehicle->physics->Couplers[ decoupledend ].CouplingFlag == Coupling::none ) { + WriteLog( "Uncoupling [" + occupied->Name + "]: uncoupled" ); + iVehicleCount = -2; + // update trainset state + CheckVehicles( DriverOrder::disconnect ); + // potentially remove coupler adapter +/* + if( decoupledvehicle->physics->Couplers[ decoupledend ].has_adapter() ) { + decoupledvehicle->remove_coupler_adapter( decoupledend ); + } +*/ + if( pVehicles[ VehicleEnd::front ]->physics->Couplers[ decoupledend ].has_adapter() ) { + cue_action( driver_hint::couplingadapterremove, decoupledend ); + } + } + } // a jak nie, to dociskać dalej + } + // 2nd stage: apply consist brakes and change direction + if( ( false == drivingFlags.press ) ) { + // store initial consist direction + if( !iDirectionBackup ) { + iDirectionBackup = iDirection; + } + if( false == IsConsistBraked ) { + WriteLog( "Uncoupling [" + occupied->Name + "]: applying consist brakes..." ); + cue_action( driver_hint::trainbrakeapply ); + } + // jeśli w miarę został zahamowany (ciśnienie mniejsze niż podane na pozycji 3, zwyle 0.37) + else { + WriteLog( "Uncoupling [" + occupied->Name + "]: direction change" ); +/* // TODO: test if this block is needed + if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { + // wyłączenie EP, gdy wystarczy (może nie być potrzebne, bo na początku jest) + occupied->BrakeLevelSet( 0 ); + } +*/ + iDirectionOrder = -iDirection; // zmiana kierunku jazdy na przeciwny (dociskanie) + drivingFlags.press = true; // następnie będzie dociskanie + } + } + } // odczepianie + if( iVehicleCount < 0 ) { + // 4th stage: restore initial direction + if( iDirectionBackup ) { + iDirectionOrder = iDirectionBackup.value(); + iDirectionBackup.reset(); + } + if( iDirection != iDirectionOrder ) { + WriteLog( "Uncoupling [" + occupied->Name + "]: second direction change" ); + cue_action( driver_hint::mastercontrollersetreverserunlock ); + cue_action( driver_hint::directionother ); // zmiana kierunku jazdy na właściwy + } + // 5th stage: clean up and move on to next order + if( iDirection == iDirectionOrder ) { + drivingFlags.press = false; // koniec dociskania + JumpToNextOrder( true ); // zmieni światła + TableClear(); // skanowanie od nowa + drivingFlags.startHorn = false; // bez trąbienia przed ruszeniem + } + } +} + +void +TController::handle_engine() { + // HACK: activate route scanning if an idling vehicle is activated by a human user + if( OrderCurrentGet() == DriverOrder::waitForOrders + && false == iEngineActive +// && ( false == AIControllFlag ) + && true == occupied->lowVoltage.Is24vAvailable() ) { + OrderNext( DriverOrder::prepareEngine ); + } + // basic engine preparation + if( OrderCurrentGet() == DriverOrder::prepareEngine && PrepareEngine() ) { + // gotowy do drogi? + JumpToNextOrder(); + } + // engine state can potentially deteriorate in one of usual driving modes + if( OrderCurrentGet() & (DriverOrder::changeDirection | DriverOrder::connect | DriverOrder::disconnect | DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) + && false == iEngineActive ) { + // jeśli coś ma robić to niech odpala do skutku + PrepareEngine(); + } +} + +void +TController::handle_orders() { + + switch (SingleOrder(OrderCurrentGet())) + { + case DriverOrder::releaseEngine: { + if( ReleaseEngine() ) { // zdana maszyna? + JumpToNextOrder(); + } + break; + } + case DriverOrder::obeyTrain: { + UpdateObeyTrain(); + break; + } + case DriverOrder::looseShunt: { + UpdateLooseShunt(); + break; + } + case DriverOrder::connect: { + UpdateConnect(); + break; + } + case DriverOrder::disconnect: { + UpdateDisconnect(); + break; + } + case DriverOrder::jumpToFirstOrder: { + if( OrderPos > 1 ) { + OrderPos = 1; // w zerowym zawsze jest czekanie + } + else { + ++OrderPos; + } +#if LOGORDERS + OrdersDump("Jump_to_first_order"); +#endif + break; + } + default: { + // special case, change_direction potentially received during partially completed coupling operation + // this is unlikely to happen for the AI, but can happen for a (slower) human user + if( drivingFlags.connect ) { + UpdateConnect(); + } + break; + } + } // switch OrderList[OrderPos] + UpdateChangeDirection(); +} diff --git a/vehicle/ai/physicslog.cpp b/vehicle/ai/physicslog.cpp new file mode 100644 index 000000000..93af2a6f5 --- /dev/null +++ b/vehicle/ai/physicslog.cpp @@ -0,0 +1,125 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the log of the physics of the train the driver runs + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +std::string_view TController::physicslog_header() { + // the columns of the readers of these logs, the Hasler tape of the starter among them, stay where they are: + // a new one goes at the end + return "Time[s] Velocity[m/s] Acceleration[m/ss] " + "Coupler.Dist[m] Coupler.Force[N] TractionForce[kN] FrictionForce[kN] BrakeForce[kN] " + "BrakePress[MPa] PipePress[MPa] MotorCurrent[A] " + "MCP SCP BCP LBP Direction Command CVal1 CVal2 " + "Security Wheelslip " + "EngineTemp[Deg] OilTemp[Deg] WaterTemp[Deg] WaterAuxTemp[Deg] " + "VehicleVelocity[km/h]" + "\r\n"; +} + +std::string TController::physicslog_line() const { + std::ostringstream line; + line << std::fixed << std::setprecision( 4 ) + << ElapsedTime << " " + << fabs(11.31 * occupied->WheelDiameter() * occupied->nrot()) << " " + << mvControlling->AccS() << " " + << occupied->Couplers[1].Dist << " " + << occupied->Couplers[1].CForce << " " + << occupied->Ft() << " " + << occupied->Ff << " " + << occupied->Fb() << " " + << occupied->brakes.cylinderPressure << " " + << occupied->brakePipe.Pressure() << " " + << mvControlling->Im << " " + << int(mvControlling->MainCtrlPos()) << " " + << int(mvControlling->ScndCtrlPos()) << " " + << occupied->brakes.HandlePositionSmooth() << " " + << occupied->brakes.IndependentPosition() << " " + << int(mvControlling->DirActive) << " " + << ( occupied->CommandIn.Text.empty() ? "none" : occupied->CommandIn.Text.c_str() ) << " " + << occupied->CommandIn.Value1 << " " + << occupied->CommandIn.Value2 << " " + << int(mvControlling->SecuritySystem.is_blinking()) << " " + << int(mvControlling->SlippingWheels()) << " " + << mvControlling->diesel.heat.Ts << " " + << mvControlling->diesel.heat.To << " " + << mvControlling->diesel.heat.temperatura1 << " " + << mvControlling->diesel.heat.temperatura2 << " " + // vehicle speed [km/h], the second column is the wheel speed, which stays at 0 while the wheels are locked in a skid + << occupied->V() * 3.6 + << "\r\n"; + return line.str(); +} + +void TController::begin_physicslog() +{ + // physicslog/.dat, written every two seconds along with the logs of the other drivers +#if LOGPRESS == 0 + PhysicsLogs.begin( VehicleName, physicslog_header() ); +#endif +#if LOGPRESS == 1 + PhysicsLogs.begin( VehicleName, "t\tVel\tAcc\tPP\tVVP\tBP\tBVP\tCVP\n" ); +#endif + PhysicsLogBegun = true; +} + +void TController::PhysicsLog() +{ // zapis logu - na razie tylko wypisanie parametrów +#if LOGPRESS == 0 + PhysicsLogs.append( VehicleName, physicslog_line() ); +#endif +#if LOGPRESS == 1 + std::ostringstream line; + line << ElapsedTime << "\t" << fabs(11.31 * occupied->WheelDiameter() * occupied->nrot()) + << "\t"; + line << mvControlling->AccS() << "\t"; + line << occupied->brakePipe.Pressure() << "\t" << occupied->brakes.controlReservoirPressure << "\t" + << occupied->brakes.cylinderPressure << "\t"; + line << occupied->brakes.reservoirAir << "\t" << occupied->brakes.distributor->GetCRP() << "\n"; + PhysicsLogs.append( VehicleName, line.str() ); +#endif +}; diff --git a/vehicle/ai/routescan.cpp b/vehicle/ai/routescan.cpp new file mode 100644 index 000000000..8c9b2f3ec --- /dev/null +++ b/vehicle/ai/routescan.cpp @@ -0,0 +1,625 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// scanning the route ahead into the speed table, the signals passed + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +// finds point of specified track nearest to specified event. returns: distance to that point from the specified end of the track +// TODO: move this to file with all generic routines, too easy to forget it's here and it may come useful +double +ProjectEventOnTrack( basic_event const *Event, TTrack const *Track, double const Direction ) { + + auto const segment = Track->CurrentSegment(); + auto const nearestpoint = segment->find_nearest_point( Event->input_location() ); + return Direction > 0 ? nearestpoint * segment->GetLength() : // measure from point1 + (1.0 - nearestpoint) * segment->GetLength(); // measure from point2 +}; + +double GetDistanceToEvent(TTrack const *track, basic_event const *event, double scan_dir, double start_dist, int iter = 0, bool back = false) +{ + if( track == nullptr ) { return start_dist; } + + auto const segment = track->CurrentSegment(); + auto const pos_event = event->input_location(); + double len1, len2; + double sd = scan_dir; + double seg_len = scan_dir > 0 ? 0.0 : 1.0; + double const dzielnik = 1.0 / segment->GetLength();// rozdzielczosc mniej wiecej 1m + int krok = 0; // krok obliczeniowy do sprawdzania czy odwracamy + len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); + do + { + len1 = len2; + seg_len += scan_dir > 0 ? dzielnik : -dzielnik; + len2 = glm::length2(pos_event - segment->FastGetPoint(seg_len)); + ++krok; + } while (len1 > len2 && seg_len >= dzielnik && seg_len <= 1.0 - dzielnik); + //trzeba sprawdzić czy seg_len nie osiągnął skrajnych wartości, bo wtedy + // trzeba sprawdzić tor obok + if (1 == krok) + sd = -sd; // jeśli tylko jeden krok tzn, że event przy poprzednim sprawdzaym torze + if ((1 == krok || seg_len <= dzielnik || seg_len > 1.0 - dzielnik) && iter < 3) + { // przejście na inny tor + track = track->Connected(int(sd), sd); + start_dist += 1 == krok ? 0 : back ? -segment->GetLength() : segment->GetLength(); + if( track != nullptr + && track->eType == tt_Cross ) { + // NOTE: tracing through crossroads currently poses risk of tracing through wrong segment + // as it's possible to be performerd before setting a route through the crossroads + // as a stop-gap measure we don't trace through crossroads which should be reasonable in most cases + // TODO: establish route before the scan, or a way for the function to know which route to pick + return start_dist; + } + else { + return GetDistanceToEvent( track, event, sd, start_dist, ++iter, 1 == krok ? true : false ); + } + } + else + { // obliczenie mojego toru + seg_len -= scan_dir > 0 ? dzielnik : -dzielnik; //trzeba wrócić do pozycji len1 + seg_len = scan_dir < 0 ? 1 - seg_len : seg_len; + seg_len = back ? 1 - seg_len : seg_len; // odwracamy jeśli idzie do tyłu + start_dist -= back ? segment->GetLength() : 0; + return start_dist + segment->GetLength() * seg_len; + } +}; +namespace +{ + + +// the low 4 bits of a number as a number -8..7, as the route of a crossing was read from the top of the flags +int signedNibble(unsigned const value) +{ + auto const nibble{static_cast(value & 0xf)}; + return nibble >= 8 ? nibble - 16 : nibble; +} + +} // namespace + +//--------------------------------------------------------------------------- + +void TController::TableClear() +{ // wyczyszczenie tablicy + sSpeedTable.clear(); + iLast = -1; + iTableDirection = 0; // nieznany + tLast = nullptr; + fLastVel = -1.0; + SemNextIndex = npos; + SemNextStopIndex = npos; + eSignSkip = nullptr; // nic nie pomijamy +}; + +std::vector TController::CheckTrackEvent( TTrack *Track, double const fDirection ) const +{ // sprawdzanie eventów na podanym torze do podstawowego skanowania + std::vector events; + auto const &eventsequence { ( fDirection > 0 ? Track->m_events2 : Track->m_events1 ) }; + for( auto const &event : eventsequence ) { + if( event.second != nullptr + && event.second->m_passive ) { + events.emplace_back( event.second ); + } + } + return events; +} + +bool TController::TableAddNew() +{ // zwiększenie użytej tabelki o jeden rekord + sSpeedTable.emplace_back(); // add a new slot + iLast = sSpeedTable.size() - 1; + return true; // false gdy się nałoży +}; + +bool TController::TableNotFound(basic_event const *Event, double const Distance ) const +{ // sprawdzenie, czy nie został już dodany do tabelki (np. podwójne W4 robi problemy) + auto lookup = + std::find_if( + sSpeedTable.begin(), + sSpeedTable.end(), + [Event]( TSpeedPos const &speedpoint ){ + return true == speedpoint.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event) && speedpoint.evEvent == Event; } ); + + if (Global.iWriteLogEnabled & 8 + && lookup != sSpeedTable.end() ) { + WriteLog( "Speed table for " + OwnerName() + " already contains event " + lookup->evEvent->m_name ); + } + + // ignore duplicates which seem to be reasonably apart from each other, on account of looping tracks + // NOTE: since supplied distance is only rough approximation of distance to the event, we're using large safety margin + return lookup == sSpeedTable.end() || Distance - lookup->fDist > 100.0; +}; + +void TController::TableTraceRoute(double fDistance, TDynamicObject *pVehicle) +{ // skanowanie trajektorii na odległość (fDistance) od (pVehicle) w kierunku przodu składu i + // uzupełnianie tabelki + // WriteLog("Starting TableTraceRoute"); + + TTrack *pTrack{ nullptr }; // zaczynamy od ostatniego analizowanego toru + double fTrackLength{ 0.0 }; // długość aktualnego toru (krótsza dla pierwszego) + double fCurrentDistance{ 0.0 }; // aktualna przeskanowana długość + double fLastDir{ 0.0 }; + + if (iTableDirection != iDirection ) { + // jeśli zmiana kierunku, zaczynamy od toru ze wskazanym pojazdem + TableClear(); +/* + // aktualna prędkość // changed to -1 to recognize speed limit, if any + fLastVel = -1.0; + sSpeedTable.clear(); + iLast = -1; + tLast = nullptr; //żaden nie sprawdzony + SemNextIndex = npos; + SemNextStopIndex = npos; +*/ + if( VelSignalLast == 0.0 ) { + // don't allow potential red light overrun keep us from reversing + VelSignalLast = -1.0; + } + iTableDirection = iDirection; // ustalenie w jakim kierunku jest wypełniana tabelka względem pojazdu + pTrack = pVehicle->GetTrack(); // odcinek, na którym stoi + fTrackLength = pVehicle->RaTranslationGet(); // pozycja na tym torze (odległość od Point1) + fLastDir = pVehicle->DirectionGet() * pVehicle->RaDirectionGet(); // ustalenie kierunku skanowania na torze + if( fLastDir < 0.0 ) { + // jeśli w kierunku Point2 toru + fTrackLength = pTrack->Length() - fTrackLength; // przeskanowana zostanie odległość do Point2 + } + // account for the fact tracing begins from active axle, not the actual front of the vehicle + // NOTE: position of the couplers is modified by track offset, but the axles ain't, so we need to account for this as well + fTrackLength -= glm::length( + pVehicle->AxlePositionGet() + - pVehicle->RearPosition() + + pVehicle->VectorLeft() * pVehicle->physics->OffsetTrackH() ); + // aktualna odległość ma być ujemna gdyż jesteśmy na końcu składu + fCurrentDistance = -fLength - fTrackLength; + fTrackLength = pTrack->Length(); //skasowanie zmian w zmiennej żeby poprawnie liczyło w dalszych krokach + MoveDistanceReset(); // AI startuje 1s po zaczęciu jazdy i mógł już coś przejechać + } + else { + if( iTableDirection == 0 ) { return; } + // NOTE: belt and braces; TablePurger() used to leave these pointing past the end of the table. + // nothing is known to do that any more, so say so when it happens + auto const dropstaleindex = [this, fDistance]( std::size_t &Index, std::string_view const Name ) { + if( Index == npos + || Index < sSpeedTable.size() ) { + return; + } + ErrorLog( std::format( + "Speed table for {}: {} {} points past the end of the table ({} records), last track {} at {:.1f} m, scan range {:.1f} m; reset", + OwnerName(), Name, Index, sSpeedTable.size(), + ( iLast >= 0 && sSpeedTable[ iLast ].trTrack != nullptr ? sSpeedTable[ iLast ].trTrack->name() : "none" ), + ( iLast >= 0 ? sSpeedTable[ iLast ].fDist : 0.0 ), fDistance ) ); + Index = npos; }; + dropstaleindex( SemNextIndex, "SemNextIndex" ); + dropstaleindex( SemNextStopIndex, "SemNextStopIndex" ); + // kontynuacja skanowania od ostatnio sprawdzonego toru (w ostatniej pozycji zawsze jest tor) + if( SemNextStopIndex != npos + && sSpeedTable[SemNextStopIndex].fVelNext == 0.0 ) { + // znaleziono semafor lub tarczę lub tor z prędkością zero, trzeba sprawdzić czy to nadał semafor + // jeśli jest następny semafor to sprawdzamy czy to on nadał zero + if( OrderCurrentGet() & DriverOrder::obeyTrain + && sSpeedTable[SemNextStopIndex].flags & SpeedPointFlag::signal ) { + return; + } + else { + if( false == OrderCurrentGet().HasAny(trainOrders) + && sSpeedTable[SemNextStopIndex].flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal | SpeedPointFlag::outsideStation) ) { + return; + } + } + } + + auto const &lastspeedpoint = sSpeedTable[ iLast ]; + pTrack = lastspeedpoint.trTrack; + assert( pTrack != nullptr ); + // flaga ustawiona, gdy Point2 toru jest blizej + fLastDir = lastspeedpoint.flags.HasAny(SpeedPointFlag::reverse) ? -1.0 : 1.0; + fCurrentDistance = lastspeedpoint.fDist; // aktualna odleglosc do jego Point1 + fTrackLength = pTrack->Length(); + } + + if( iTableDirection == 0 ) { + // don't bother + return; + } + + while (fCurrentDistance < fDistance) + { + if (pTrack != tLast) // ostatni zapisany w tabelce nie był jeszcze sprawdzony + { // jeśli tor nie był jeszcze sprawdzany + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table for " + OwnerName() + " tracing through track " + pTrack->name() ); + } + + auto const events { CheckTrackEvent( pTrack, fLastDir ) }; + for( auto *pEvent : events ) { + if( pEvent != nullptr && TableNotFound(pEvent, fCurrentDistance) ) // jeśli jest semafor na tym torze + { // trzeba sprawdzić tabelkę, bo dodawanie drugi raz tego samego przystanku nie jest korzystne + // jeśli nie ma + TableAddNew(); // zawsze jest true + + if (Global.iWriteLogEnabled & 8) + { + WriteLog("Speed table for " + OwnerName() + " found new event, " + pEvent->m_name); + } + auto &newspeedpoint = sSpeedTable[iLast]; + /* + if( newspeedpoint.Set( + pEvent, + fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ), + OrderCurrentGet() ) ) { + */ + // an order of a road junction or a level crossing lies on the lane it's on. it's measured along that lane: the search + // for the events beside the track goes in steps of about a metre, and misplaces the ones on lanes shorter than a few metres + auto const eventdistance{ + typeid( *pEvent ) == typeid( road_order ) ? + fCurrentDistance + ProjectEventOnTrack( pEvent, pTrack, fLastDir ) : + GetDistanceToEvent( pTrack, pEvent, fLastDir, fCurrentDistance ) }; + if (newspeedpoint.Set(pEvent, eventdistance, fLength, OrderCurrentGet(), occupied->Vel < EU07_AI_NOMOVEMENT)) + { + + fDistance = newspeedpoint.fDist; // jeśli sygnał stop, to nie ma potrzeby dalej skanować + SemNextStopIndex = iLast; + if (SemNextIndex == npos) + { + SemNextIndex = iLast; + } + if (Global.iWriteLogEnabled & 8) + { + WriteLog("(stop signal from " + (SemNextStopIndex != npos ? sSpeedTable[SemNextStopIndex].GetName() : "unknown semaphor") + ")"); + } + } + else + { + if (true == newspeedpoint.IsProperSemaphor(OrderCurrentGet()) && SemNextIndex == npos) + { + SemNextIndex = iLast; // sprawdzamy czy pierwszy na drodze + } + if (Global.iWriteLogEnabled & 8) + { + WriteLog("(forward signal for " + (SemNextIndex != npos ? sSpeedTable[SemNextIndex].GetName() : "unknown semaphor") + ")"); + } + } + } + } // event dodajemy najpierw, żeby móc sprawdzić, czy tor został dodany po odczytaniu prędkości następnego + + if( pTrack->VelocityGet() == 0.0 // zatrzymanie + || pTrack->iAction // jeśli tor ma własności istotne dla skanowania + || pTrack->VelocityGet() != fLastVel ) // następuje zmiana prędkości + { // odcinek dodajemy do tabelki, gdy jest istotny dla ruchu + TableAddNew(); + sSpeedTable[ iLast ].Set( + pTrack, fCurrentDistance, + fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::reverse : SpeedPointFlag::enabled ); // dodanie odcinka do tabelki z flagą kierunku wejścia + if (pTrack->eType == tt_Cross) { + // na skrzyżowaniach trzeba wybrać segment, po którym pojedzie pojazd + // dopiero tutaj jest ustalany kierunek segmentu na skrzyżowaniu +/* + // NOTE: manual selection disabled due to multiplayer + int routewanted; + if( false == aiControlled ) { + routewanted = ( + input::keys[ GLFW_KEY_LEFT ] != GLFW_RELEASE ? 1 : + input::keys[ GLFW_KEY_RIGHT ] != GLFW_RELEASE ? 2 : + 3 ); + } + else { + routewanted = 1 + std::floor( Random( static_cast( pTrack->RouteCount() ) - 0.001 ) ); + } +*/ + auto const routewanted { pTrack->RouteDraw() }; + sSpeedTable[iLast].crossRoute = signedNibble( ( static_cast( sSpeedTable[iLast].crossRoute ) | static_cast( pTrack->CrossSegment(fLastDir < 0 ? tLast->iPrevDirection : tLast->iNextDirection, + /* + iRouteWanted ) + */ + routewanted) ) ) & 0xf ); // ostatnie 4 bity pola flag + sSpeedTable[iLast].flags = sSpeedTable[iLast].flags.Without(SpeedPointFlag::reverse); // usunięcie flagi kierunku, bo może być błędna + if (sSpeedTable[iLast].crossRoute < 0) { + sSpeedTable[iLast].flags |= SpeedPointFlag::reverse; // ustawienie flagi kierunku na podstawie wybranego segmentu + } + if (int(fLastDir) * sSpeedTable[iLast].LegacyFlagsValue() < 0) { + fLastDir = -fLastDir; + } +/* + if (aiControlled) { + // dla AI na razie losujemy kierunek na kolejnym skrzyżowaniu + iRouteWanted = 1 + Random(3); + } +*/ + } + } + else if ( (pTrack->fRadius != 0.0 // odległość na łuku lepiej aproksymować cięciwami + || tLast != nullptr && tLast->fRadius != 0.0) && + TableAddNew()) // koniec łuku też jest istotny + { // albo dla liczenia odległości przy pomocy cięciw - te usuwać po przejechaniu + // dodanie odcinka do tabelki + sSpeedTable[iLast].Set(pTrack, fCurrentDistance, fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::curve | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::curve); + } + } + + fCurrentDistance += fTrackLength; // doliczenie kolejnego odcinka do przeskanowanej długości + tLast = pTrack; // odhaczenie, że sprawdzony + fLastVel = pTrack->VelocityGet(); // prędkość na poprzednio sprawdzonym odcinku + pTrack = pTrack->Connected( + pTrack->eType == tt_Cross ? sSpeedTable[iLast].crossRoute : static_cast(fLastDir), + fLastDir); // może być NULL + + if (pTrack != nullptr ) + { // jeśli kolejny istnieje + if( tLast != nullptr && tLast->VelocityGet() > 0 && (tLast->VelocityGet() < pTrack->VelocityGet() || pTrack->VelocityGet() < 0) ) { + + if (iLast != -1 && sSpeedTable[iLast].trTrack == tLast) + { + // if the track is already in the table we only need to mark it as relevant + sSpeedTable[iLast].flags |= SpeedPointFlag::enabled; + } + else + { + // otherwise add it + TableAddNew(); + sSpeedTable[iLast].Set(tLast, + fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track + (fLastDir > 0 ? pTrack->iPrevDirection : pTrack->iNextDirection) ? SpeedPointFlag::enabled : SpeedPointFlag::enabled | SpeedPointFlag::reverse); + } + } + // zwiększenie skanowanej odległości tylko jeśli istnieje dalszy tor + fTrackLength = pTrack->Length(); + } + else + { // definitywny koniec skanowania, chyba że dalej puszczamy samochód po gruncie... + if( iLast == -1 + || ( false == sSpeedTable[iLast].flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::trackEnd) + && sSpeedTable[iLast].trTrack != tLast ) ) { + // only if we haven't already marked end of the track and if the new track doesn't duplicate last one + if( TableAddNew() ) { + // zapisanie ostatniego sprawdzonego toru + sSpeedTable[iLast].Set( + tLast, fCurrentDistance - fTrackLength, // by now the current distance points to beginning of next track, + fLastDir < 0 ? SpeedPointFlag::enabled | SpeedPointFlag::trackEnd | SpeedPointFlag::reverse : SpeedPointFlag::enabled | SpeedPointFlag::trackEnd); + } + } + else if( sSpeedTable[iLast].trTrack == tLast && false == TestFlag(sSpeedTable[iLast].trTrack->iCategoryFlag, 0x100) ) { + // otherwise just mark the last added track as the final one + // TODO: investigate exactly how we can wind up not marking the last existing track as actual end + // don't mark portals, as these aren't exactly track ends, but teleport devices + sSpeedTable[iLast].flags |= SpeedPointFlag::enabled | SpeedPointFlag::trackEnd; + } + // to ostatnia pozycja, bo NULL nic nie da, a może się podpiąć obrotnica, czy jakieś transportery + return; + } + } + if( TableAddNew() ) { + // zapisanie ostatniego sprawdzonego toru + sSpeedTable[ iLast ].Set( + pTrack, fCurrentDistance, + fLastDir < 0 ? SpeedPointFlag::none | SpeedPointFlag::reverse : SpeedPointFlag::none ); + } +}; + +void TController::TableCheck(double fDistance) +{ // przeliczenie odległości w tabelce, ewentualnie doskanowanie (bez analizy prędkości itp.) + if( iTableDirection != iDirection ) { + // jak zmiana kierunku, to skanujemy od końca składu + TableTraceRoute( fDistance, pVehicles[ VehicleEnd::rear ] ); + TableSort(); + } + else if (iTableDirection) + { // trzeba sprawdzić, czy coś się zmieniło + auto const distance = MoveDistanceGet(); + for (auto &sp : sSpeedTable) { + // aktualizacja odległości dla wszystkich pozycji tabeli + sp.UpdateDistance(distance); + } + MoveDistanceReset(); // kasowanie odległości po aktualizacji tabelki + for( int i = 0; i < iLast; ++i ) + { // aktualizacja rekordów z wyjątkiem ostatniego + if (sSpeedTable[i].flags & SpeedPointFlag::enabled) // jeśli pozycja istotna + { + auto const passedbefore { sSpeedTable[ i ].flags.HasAll(SpeedPointFlag::elapsed) }; + if (sSpeedTable[i].Update()) + { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table for " + OwnerName() + " detected switch change at " + sSpeedTable[ i ].trTrack->name() + " (generating fresh trace)" ); + } + // usuwamy wszystko za tym torem + while (sSpeedTable.back().trTrack != sSpeedTable[i].trTrack) + { // usuwamy wszystko dopóki nie trafimy na tą zwrotnicę + sSpeedTable.pop_back(); + --iLast; + } + // a semaphor recorded beyond the switch went away with the discarded entries + if( SemNextIndex != npos + && SemNextIndex >= sSpeedTable.size() ) { + SemNextIndex = npos; + } + if( SemNextStopIndex != npos + && SemNextStopIndex >= sSpeedTable.size() ) { + SemNextStopIndex = npos; + } + tLast = sSpeedTable[ i ].trTrack; + TableTraceRoute( fDistance, pVehicles[ VehicleEnd::rear ] ); + TableSort(); + // nie kontynuujemy pętli, trzeba doskanować ciąg dalszy + break; + } + // a switch is a track, the update of a signal never ends the loop above + CheckSignalPassed( sSpeedTable[ i ], passedbefore ); + if (sSpeedTable[i].flags & SpeedPointFlag::track) // jeśli odcinek + { + if( sSpeedTable[ i ].fDist + sSpeedTable[ i ].trTrack->Length() < -fLength ) // a skład wyjechał całą długością poza + { // degradacja pozycji + sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // nie liczy się + } + else if( sSpeedTable[i].crossRoute == 0 && ( sSpeedTable[i].flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::switchTrack ) ) == SpeedPointFlag::elapsed && sSpeedTable[i].fVelNext < 0 ) { + // jest z tyłu (najechany) i nie jest zwrotnicą ani skrzyżowaniem + // a nie ma ograniczenia prędkości + sSpeedTable[i].ResetFlags(); // to nie ma go po co trzymać (odtykacz usunie ze środka) + } + } + else if (sSpeedTable[i].flags & SpeedPointFlag::event && false == sSpeedTable[i].flags.HasAny(SpeedPointFlag::pointSpeed) && sSpeedTable[i].fDist < (typeid(*sSpeedTable[i].evEvent) == typeid(putvalues_event) ? -fLength : 0) && occupied->CategoryFlag == 2 && + sSpeedTable[i].fDist < -0.75) // jeśli event + { + // jeśli jest z tyłu + // pociąg staje zawsze, a samochód tylko jeśli nie przejedzie całą długością (może być zaskoczony zmianą) + // WriteLog("TableCheck: Event is behind. Delete from table: " + sSpeedTable[i].evEvent->asName); + sSpeedTable[i].flags = sSpeedTable[i].flags.Without(SpeedPointFlag::enabled); // degradacja pozycji dla samochodu; + // semafory usuwane tylko przy sprawdzaniu, bo wysyłają komendy + } + } + } + auto const lastpassedbefore { sSpeedTable[ iLast ].flags.HasAll(SpeedPointFlag::elapsed) }; + sSpeedTable[iLast].Update(); // aktualizacja ostatniego + // a signal at stop often is the last, the scan doesn't go past it + CheckSignalPassed( sSpeedTable[ iLast ], lastpassedbefore ); + // WriteLog("TableCheck: Upate last track. Dist=" + AnsiString(sSpeedTable[iLast].fDist)); + if( sSpeedTable[ iLast ].fDist < fDistance ) { + TableTraceRoute( fDistance, pVehicles[ VehicleEnd::rear ] ); // doskanowanie dalszego odcinka + TableSort(); + } + // garbage collection + TablePurger(); + } +}; +namespace +{ + + +// the position is a signal showing stop (SetVelocity 0 0). SetVelocity 0 x on automatic block isn't: it may be passed after a stop +bool is_signal_at_stop( TSpeedPos const &Point ) +{ + return Point.flags.HasAll(SpeedPointFlag::event) + && Point.flags.HasAll(SpeedPointFlag::signal) + && false == Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) + && std::abs( Point.fVelNext ) <= 0.0 + && Point.evEvent != nullptr; +} + +// the position is a signal, a main or a shunting one: the aspect comes from its memory cell. putvalues events +// set speed limits by the track, and the flags they get don't make them signals +bool is_signal( TSpeedPos const &Point ) +{ + return Point.flags.HasAll(SpeedPointFlag::event) + && ( Point.flags.HasAll(SpeedPointFlag::signal) || Point.flags.HasAll(SpeedPointFlag::shuntSignal) ) + && Point.evEvent != nullptr + && typeid( *Point.evEvent ) == typeid( getvalues_event ); +} + +std::uint8_t passing_flags_of( TSpeedPos const &Point, double const Speedatsignal, bool const Trainmovement ) +{ + std::uint8_t flags { 0 }; + auto const shunting { Point.flags.HasAll(SpeedPointFlag::shuntSignal) }; + if( shunting ) { + flags |= blackbox::passing_flags::shunt; + } + // the speeds of the aspects are whole km/h, -1 for no limit; a shunting signal binds only the shunting + if( std::abs( Speedatsignal ) < 0.5 && ( false == shunting || false == Trainmovement ) ) { + flags |= ( Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? blackbox::passing_flags::automatic_block : blackbox::passing_flags::at_stop ); + } + return flags; +} + +} // namespace + +void TController::CheckSignalPassed( TSpeedPos const &Point, bool const Passedbefore ) const +{ + // not bSeenAhead: found already behind the head, the train stood across it or past it, it didn't pass it + if( false == signal_passing::passed_now( Passedbefore, Point.flags.HasAll(SpeedPointFlag::elapsed), Point.bSeenAhead ) + || ( occupied->CategoryFlag & 1 ) == 0 ) { // railway only + return; + } + if( is_signal_at_stop( Point ) ) { + simulation::test().signal_passed_at_danger( OwnerName(), Point.evEvent->m_name ); + } + if( is_signal( Point ) ) { + // the aspect the train had of it: the table keeps it once the signal is behind, while the memory cell + // may already show stop for the train itself, past the signal on the track it guards. the stop of an + // automatic block signal is kept as the speed allowed after it, with a flag of its own + auto const speedatsignal { Point.flags.HasAll(SpeedPointFlag::stopOnAutomaticBlock) ? 0.0 : Point.fVelNext }; + simulation::Blackbox.signal_passed( + pVehicles[ VehicleEnd::front ], *Point.evEvent, + speedatsignal, Point.evEvent->input_value( 2 ), + occupied->Vel, -Point.fDist, + passing_flags_of( Point, speedatsignal, false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ) ); + } +} + +// the margins of the final approach of a train [m], closer than the first of which it stops at once and within the +// second of which it makes its final approach: at a passenger stop, or at a signal and anything else it stops at +std::pair +TController::train_proximity_margins( bool const Passengerstop ) const { + + auto minproximity { 0.0 }; + auto maxproximity { 0.0 }; + if( Passengerstop ) { + // a stop point keeps the margins its W4 parameters (head or middle of the consist, + // platform length) were set up against + minproximity = std::clamp( 5 + iVehicles, 10, 15 ) + ( IsCargoTrain ? 10.0 : 0.0 ); + maxproximity = std::clamp( 10 + iVehicles, 15, 40 ); + } + else { + // a train stops 8-15 m short of the signal whatever its length; closer than the lower + // edge it stops at once, the braking aims at the middle of the window, 3.5 m further out + minproximity = 8.0; + // the final approach begins far enough out to slow from the coasting speed down to the window, + // and at the same distance whether the train is moving or standing, so it does not flip + // between creeping closer and holding still when it comes to a stand short of the window + maxproximity = 50.0; + } + if( IsCargoTrain ) { + // start the final approach earlier for cargo trains, their brakes react more slowly + maxproximity += 10.0; + } + if( ( Global.FrictionWeatherFactor < 1.f ) + && ( iVehicles > 1 ) ) { + // take into account weather conditions + minproximity += 5.0; + maxproximity += 5.0; + } + if( occupied->Vel < 0.1 ) { + // jak stanie za daleko, to niech nie dociąga paru metrów + maxproximity = std::max( maxproximity, 50.0 ); + } + return { minproximity, maxproximity }; +} diff --git a/vehicle/ai/situation.cpp b/vehicle/ai/situation.cpp new file mode 100644 index 000000000..8d99a00ad --- /dev/null +++ b/vehicle/ai/situation.cpp @@ -0,0 +1,730 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// what the driver sees and keeps an eye on: the consist, the braking distance, the pantographs, the lights, the horns + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +double const deltalog = 0.05; // przyrost czasu + +void +TController::update_timers( double dt ) { + + ElapsedTime += dt; + WaitingTime += dt; + fBrakeTime -= dt; // wpisana wartość jest zmniejszana do 0, gdy ujemna należy zmienić nastawę hamulca + fBrakeHeldTime += dt; + if( occupied->brakes.HandlePositionSmooth() != occupied->brakes.driverValve->GetPos( bh_FS ) ) { + // brake charging timeout starts after charging ends + BrakeChargingCooldown += dt; + } + fStopTime += dt; // zliczanie czasu postoju, nie ruszy dopóki ujemne + fActionTime += dt; // czas używany przy regulacji prędkości i zamykaniu drzwi + LastReactionTime += dt; + if( occupied->Vel < 0.05 + && OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) ) { + IdleTime += dt; + } + else { + IdleTime = 0.0; + } + fWarningDuration -= dt; // horn activation while the value is positive +} + +void +TController::update_logs( double const dt ) { + // log vehicle data + if( false == writes_physicslog() ) { + // not counted while it isn't logged (the driver of a road vehicle, or no logs on): were the logs turned on, + // it would write a line every 0.05 s from then on, not one each update to make up for the time before + LastUpdatedTime = 0.0; + return; + } + LastUpdatedTime += dt; + if( LastUpdatedTime > deltalog ) { + // zapis do pliku DAT + if( false == PhysicsLogBegun ) { + begin_physicslog(); + } + PhysicsLog(); + LastUpdatedTime -= deltalog; + } +} + +void +TController::control_wheelslip() { + // a start that has slipped once keeps the sand on until the train is under way. with the sand off as soon as the + // wheels grip again, the next notch slips again, and a heavy train on poor rails slips, grips and snatches over + // and over, and may never get going (#187). a vehicle without sand starts as before + auto const velocity { std::abs( occupied->Vel ) }; + if( mvControlling->SlippingWheels() + && velocity < EU07_AI_SANDEDSTARTVELOCITY + && false == mvControlling->IsMainCtrlNoPowerPos() + && mvControlling->Sand > 0.0 ) { + sandedStart.active = true; + } + else if( velocity >= EU07_AI_SANDEDSTARTVELOCITY + || ( velocity < EU07_AI_NOMOVEMENT && VelDesired == 0.0 ) ) { + sandedStart.active = false; + } + // wheel slip + if( mvControlling->SlippingWheels() ) { + cue_action( driver_hint::sandingon ); // piasku! + if( false == sandedStart.active ) { + cue_action( driver_hint::tractiveforcedecrease ); + cue_action( driver_hint::antislip ); + } + else if( ElapsedTime - sandedStart.decreaseTime >= 1.0 ) { + // starting, a step down at a time, and no anti-slip brake: taking the power off at once and braking the + // locomotive brings a heavy train that has just got moving to a stand again, and the start begins anew + cue_action( driver_hint::tractiveforcedecrease ); + sandedStart.decreaseTime = ElapsedTime; + } + cue_action( driver_hint::brakingforcedecrease ); + ++iDriverFailCount; + } + else if( ( std::fabs( mvControlling->Im ) > 0.75 * mvControlling->ImaxHi() ) + || ( sandedStart.active && false == mvControlling->IsMainCtrlNoPowerPos() ) ) { + cue_action( driver_hint::sandingon ); // piaskujemy tory, coby się nie ślizgać + } + else { + // deactivate sandbox if we aren't slipping + if( mvControlling->SandDose() ) { + cue_action( driver_hint::sandingoff ); + } + } +} + +void +TController::control_pantographs() { + + if( pantographUnit->EnginePowerSource.SourceType != TPowerSource::CurrentCollector ) { return; } + + if( false == pantographUnit->pantographAir.config.autoValve + && occupied->mainPipe.Pressure() > 4.3 ) { + // gdy główna sprężarka bezpiecznie nabije ciśnienie to można przestawić kurek na zasilanie pantografów z głównej pneumatyki + cue_action( driver_hint::pantographairsourcesetmain ); + } + + // uśrednione napięcie sieci: przy spadku poniżej wartości minimalnej opóźnić rozruch o losowy czas + fVoltage = 0.5 * (fVoltage + std::max( mvControlling->GetTrainsetHighVoltage(), mvControlling->pantographCircuit.SupplyVoltage() ) ); + if( fVoltage < mvControlling->EnginePowerSource.CollectorParameters.MinV && fActionTime >= PrepareTime ) { + // gdy rozłączenie WS z powodu niskiego napięcia + // jeśli czas oczekiwania nie został ustawiony, losowy czas oczekiwania przed ponownym załączeniem jazdy + fActionTime = -2.0 - Random(10); + } + + // the pantograph setup the .fiz suggests for shunting (AI: ShuntPantstate=, eu07/maszyna#461), 0 when there's none + // or the vehicle isn't shunting + auto const shuntpantographsetup { + OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt ) ? + occupied->AIHintShuntPantstate() : + 0 }; + + // raise/lower pantographs as needed + auto const useregularpantographlayout { + pVehicle->Next(Coupling::control) == nullptr // standalone + || is_emu() // special case + || mvControlling->TrainType() == train_type::et41 }; // special case + + if( occupied->Vel > EU07_AI_NOMOVEMENT ) { + + if( fOverhead2 >= 0.0 || iOverheadZero ) { + // jeśli jazda bezprądowa albo z opuszczonym pantografem + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + + if( fOverhead2 > 0.0 || iOverheadDown ) { + // jazda z opuszczonymi pantografami + if( pantographUnit->pantographs[ VehicleEnd::front ].is_active ) { + cue_action( driver_hint::frontpantographvalveoff ); + } + if( pantographUnit->pantographs[ VehicleEnd::rear ].is_active ) { + cue_action( driver_hint::rearpantographvalveoff ); + } + } + else { + // jeśli nie trzeba opuszczać pantografów + // TODO: check if faction alone reduces frequency enough + if( fActionTime > 0.0 ) { + if( shuntpantographsetup != 0 ) { + // shunting with the pantograph setup the .fiz suggests for it + control_pantographs_setup( shuntpantographsetup ); + } + else if( occupied->AIHintPantstate() == 0 ) { + // jazda na tylnym + if( iDirection >= 0 && useregularpantographlayout ) { + // jak jedzie w kierunku sprzęgu 0 + if( pantographUnit->pantographCircuit.RearVoltage() == 0.0 + // filter out cases with single _other_ working pantograph so we don't try to raise something we can't + && ( pantographUnit->pantographCircuit.SupplyVoltage() == 0.0 + || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { + cue_action( driver_hint::rearpantographvalveon ); + } + } + else { + // jak jedzie w kierunku sprzęgu 0 + if( pantographUnit->pantographCircuit.FrontVoltage() == 0.0 + // filter out cases with single _other_ working pantograph so we don't try to raise something we can't + && ( pantographUnit->pantographCircuit.SupplyVoltage() == 0.0 + || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) ) { + cue_action( driver_hint::frontpantographvalveon ); + } + } + + if( occupied->Vel > 5 && pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo > 1 ) { + // opuszczenie przedniego po rozpędzeniu się o ile jest więcej niż jeden + if (iDirection >= 0 && useregularpantographlayout) // jak jedzie w kierunku sprzęgu 0 + { // poczekać na podniesienie tylnego + if (pantographUnit->pantographCircuit.FrontVoltage() != 0.0 && pantographUnit->pantographCircuit.RearVoltage() != 0.0) + { // czy jest napięcie zasilające na tylnym? + cue_action(driver_hint::frontpantographvalveoff); // opuszcza od sprzęgu 0 + } + } + else + { // poczekać na podniesienie przedniego + if (pantographUnit->pantographCircuit.RearVoltage() != 0.0 && pantographUnit->pantographCircuit.FrontVoltage() != 0.0) + { // czy jest napięcie zasilające na przednim? + cue_action(driver_hint::rearpantographvalveoff); // opuszcza od sprzęgu 1 + } + } + } + + } + else { + // use suggested pantograph setup + if( occupied->Vel > 5 ) { + auto const pantographsetup{ occupied->AIHintPantstate() }; + cue_action( + pantographsetup & 1 << 0 ? driver_hint::frontpantographvalveon : driver_hint::frontpantographvalveoff ); + cue_action( + pantographsetup & 1 << 1 ? driver_hint::rearpantographvalveon : driver_hint::rearpantographvalveoff ); + } + } + } + } + } + else if( shuntpantographsetup != 0 ) { + // shunting with the suggested setup, also while standing, and without raising more pantographs when idling + if( fOverhead2 <= 0.0 && iOverheadDown == 0 ) { + control_pantographs_setup( shuntpantographsetup ); + } + } + else { + if( !occupied->AIHintPantUpIfIdle || IdleTime <= 45.0 || std::abs(fStopTime) <= 15.0 || pantographUnit->EnginePowerSource.CollectorParameters.CollectorsNo <= 1 ) + { + } + else + { + // spending a longer at a stop, raise also front pantograph + if (iDirection >= 0 && useregularpantographlayout) + { + // jak jedzie w kierunku sprzęgu 0 + if (pantographUnit->pantographCircuit.FrontVoltage() == 0.0) + { + cue_action(driver_hint::frontpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h + } + } + else + { + if (pantographUnit->pantographCircuit.RearVoltage() == 0.0) + { + cue_action(driver_hint::rearpantographvalveon, 5); // discard the hint if speed exceeds 5 km/h + } + } + } + } +} + +// raises the pantographs of the suggested setup (bit 0: front, bit 1: rear) and lowers the others, these only once +// a pantograph of the setup collects the voltage, so the vehicle doesn't lose its power on the way +void +TController::control_pantographs_setup( int const Setup ) { + + auto const front { ( Setup & 1 << 0 ) != 0 }; + auto const rear { ( Setup & 1 << 1 ) != 0 }; + if( front ) { + cue_action( driver_hint::frontpantographvalveon ); + } + if( rear ) { + cue_action( driver_hint::rearpantographvalveon ); + } + if( auto const setuplive { ( front && pantographUnit->pantographCircuit.FrontVoltage() != 0.0 ) || ( rear && pantographUnit->pantographCircuit.RearVoltage() != 0.0 ) }; + false == setuplive ) { + return; + } + if( false == front ) { + cue_action( driver_hint::frontpantographvalveoff ); + } + if( false == rear ) { + cue_action( driver_hint::rearpantographvalveoff ); + } +} + +void +TController::control_horns( double const Timedelta ) { + // horn control + if( fWarningDuration > 0.0 ) { + // jeśli pozostało coś do wytrąbienia trąbienie trwa nadal + if( occupied->WarningSignal() == 0 ) { + cue_action( driver_hint::hornon, 1 ); // low tone horn by default + } + } + else { + if( occupied->WarningSignal() != 0 ) { + cue_action( driver_hint::hornoff ); // a tu się kończy + } + } + if( occupied->Vel > EU07_AI_MOVEMENT ) { + // jesli jedzie, można odblokować trąbienie, bo się wtedy nie włączy + drivingFlags.startHornDone = false; // zatrąbi dopiero jak następnym razem stanie + drivingFlags.startHorn = true; // i trąbić przed następnym ruszeniem + } + + if( true == drivingFlags.startHornNow + && true == Ready + && true == iEngineActive + && mvControlling->MainCtrlPowerPos() > 0 ) { + // uruchomienie trąbienia przed ruszeniem + fWarningDuration = 0.3; // czas trąbienia + cue_action( driver_hint::hornon, pVehicle->iHornWarning ); // wysokość tonu (2=wysoki) + drivingFlags.startHornDone = true; // nie trąbić aż do ruszenia + drivingFlags.startHornNow = false; // trąbienie zostało zorganizowane + } +} + +void +TController::control_security_system( double const Timedelta ) { + if( occupied->SecuritySystem.is_cabsignal_blinking() && occupied->SecuritySystem.has_separate_acknowledge()) { + // jak zadziałało SHP + if( false == is_emu() + && occupied->DirActive == 0 ) { + cue_action( driver_hint::directionforward ); + } + cue_action( driver_hint::shpsystemreset ); // to skasuj + if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types + && AccDesired > 0.0 + && occupied->SecuritySystem.is_braking() ) { + cue_action( driver_hint::trainbrakerelease ); + } + } + + if( occupied->SecuritySystem.is_blinking() ) { + // jak zadziałało CA/SHP + if( false == is_emu() + && occupied->DirActive == 0 ) { + cue_action( driver_hint::directionforward ); + } + cue_action( driver_hint::securitysystemreset ); // to skasuj + if( BrakeCtrlPosition == 0 // TODO: verify whether it's 0 in all vehicle types + && AccDesired > 0.0 + && occupied->SecuritySystem.is_braking() ) { + cue_action( driver_hint::trainbrakerelease ); + } + } + // basic emergency stop handling, while at it + if( true == occupied->RadioStopFlag() // radio-stop + && occupied->Vel < 0.01 // and actual stop + && true == occupied->Radio() ) { // and we didn't touch the radio yet + // turning off the radio should reset the flag, during security system check + if( m_radiocontroltime > 5.0 ) { // arbitrary delay between stop and disabling the radio + cue_action( driver_hint::radiooff ); + } + else { + m_radiocontroltime += Timedelta; + } + } + if( iEngineActive + && ( false == occupied->Radio() || false == occupied->RadioFuse() ) + && false == occupied->RadioStopFlag() ) { + // otherwise if it's safe to do so, turn the radio back on + // arbitrary 5 sec delay before switching radio back on + m_radiocontroltime = std::min( m_radiocontroltime, 5.0 ); + if( m_radiocontroltime < 0.0 ) { + // hint at whichever of the two is open, the radio's switch or the cut-off in its power supply + if( false == occupied->RadioFuse() ) { + cue_action( driver_hint::radiofuseon ); + } + if( false == occupied->Radio() ) { + cue_action( driver_hint::radioon ); + } + } + else { + m_radiocontroltime -= Timedelta; + } + } +} + +void +TController::control_handles() { + + switch( mvControlling->EngineType ) { + case TEngineType::ElectricSeriesMotor: { + // styczniki liniowe rozłączone yBARC + if( false == mvControlling->lineContactors.IsClosed() + && false == mvControlling->DelayCtrlFlag() + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + // if the power station is heavily burdened drop down to series mode to reduce the load + auto const useseriesmodevoltage { + std::lerp( + mvControlling->EnginePowerSource.CollectorParameters.MinV, + mvControlling->EnginePowerSource.CollectorParameters.MaxV, + IsHeavyCargoTrain ? 0.35 : 0.40 ) }; + + if( fVoltage <= useseriesmodevoltage ) { + cue_action( driver_hint::mastercontrollersetseriesmode ); + } + // sanity check + if( false == Ready + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + break; + } + case TEngineType::DieselElectric: { + // styczniki liniowe rozłączone yBARC + if( false == mvControlling->lineContactors.IsClosed() + && false == mvControlling->DelayCtrlFlag() + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + // sanity check + if( false == Ready + && mvControlling->MainCtrlPowerPos() > 1 ) { + cue_action( driver_hint::mastercontrollersetzerospeed ); + } + break; + } + default: { + break; + } } // enginetype +} + +// moves the light preset selector to the position matching the lights set directly by the AI, +// otherwise the next SetLights() call (e.g. from CheckVehicles()) reverts them to the untouched selector position +void +TController::sync_lights_selector() { + + if( occupied->LightsPosNo <= 0 ) { return; } + + auto const *headvehicle { pVehicles[ VehicleEnd::front ] }; + if( headvehicle == nullptr ) { return; } + // same choice of the light table as in TDynamicObject::SetLights() + auto const lightstable { ( occupied->CabOccupied() * pVehicle->DirectionGet() >= 0 ? VehicleEnd::front : VehicleEnd::rear ) }; + // same choice of the lit vehicle end as in TDynamicObject::RaLightsSet() + auto const headend { ( headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; + auto const position { handover::light_selector_position( + *occupied, NumberOf( lightstable ), headvehicle->physics->LitLights()[ headend ], headvehicle->LightList( headend ) ) }; + if( position == occupied->LightsPos() ) { return; } + + occupied->SetLightsPos(position); + // visual feedback + auto *train { simulation::Trains.find( pVehicle->name() ) }; + if( train != nullptr ) { + train->ggLightsButton.PutValue( static_cast( position - 1 ) ); + } +} + +// re-applies the headlight dimmer state after the AI handed the vehicle over to the human driver, +// moving the dimmer out of the off position if it'd hide the head lights set by the AI +void +TController::sync_lights_dimmer() { + + if( occupied->dimPositions.empty() ) { return; } + + auto const *headvehicle { pVehicles[ VehicleEnd::front ] }; + auto const headend { ( headvehicle != nullptr && headvehicle->iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear ) }; + auto const headlightson { + headvehicle != nullptr + && ( headvehicle->physics->LitLights()[ headend ] & ( light::headlight_left | light::headlight_right | light::headlight_upper ) ) != 0 }; + + auto const position { handover::dimmer_position( *occupied, headlightson ) }; + if( position != occupied->DimmerPosition() ) { + occupied->SetDimmerPosition(position); + // visual feedback + auto *train { simulation::Trains.find( pVehicle->name() ) }; + if( train != nullptr ) { + train->ggModernLightDimSw.PutValue( static_cast( position ) ); + } + } + if( position < 0 || position >= static_cast( occupied->dimPositions.size() ) ) { return; } // SetLightDimmings() doesn't check the range + pVehicle->SetLightDimmings(); +} + +// activate consist lamp codes +void +TController::control_lights() { + + if( is_train() ) { + // jeśli jazda pociągowa + if( true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // head lights + if( m_lighthints[ VehicleEnd::front ] == -1 ) { + cue_action( driver_hint::headcodepc1 ); + } + else if( m_lighthints[ VehicleEnd::front ] == ( light::redmarker_left | light::headlight_right | light::headlight_upper ) ) { + cue_action( driver_hint::headcodepc2 ); + } + else { + // custom light pattern + if( aiControlled ) { + pVehicles[ VehicleEnd::front ]->RaLightsSet( m_lighthints[ VehicleEnd::front ], -1 ); + } + } + // tail lights + if( m_lighthints[ VehicleEnd::rear ] == -1 ) { + cue_action( driver_hint::headcodepc5 ); + } + else { + if( aiControlled ) { + pVehicles[ VehicleEnd::rear ]->RaLightsSet( -1, m_lighthints[ VehicleEnd::rear ] ); + } + } + } + // for shunting mode + else if( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::connect ) ) { + cue_action( driver_hint::headcodetb1 ); + } + } + else if( is_car() ) { + Lights( + light::headlight_left | light::headlight_right, + light::redmarker_left | light::redmarker_right ); + } +} + +void +TController::control_compartment_lights() { + // compartment lights + if( occupied->CompartmentLights.start_type != start_t::manual ) { return; } + + auto const currentlightstate { occupied->CompartmentLights.is_enabled }; + auto const lightlevel { Global.fLuminance * ConsistShade }; + auto const desiredlightstate{ ( + currentlightstate ? + lightlevel < 0.40 : // turn off if lighting level goes above 0.4 + lightlevel < 0.35 ) }; // turn on if lighting level goes below 0.35 + if( desiredlightstate != currentlightstate ) { + cue_action( desiredlightstate ? driver_hint::consistlightson : driver_hint::consistlightsoff ); + } +} + +void +TController::UpdateCommand() { + + if( occupied->CommandIn.Command != VehicleCommand::none && false == occupied->RunInternalCommand() ) { + // rozpoznaj komende bo lokomotywa jej nie rozpoznaje + RecognizeCommand(); // samo czyta komendę wstawioną do pojazdu? + } +} + +void +TController::UpdateNextStop() { + + if( fLastStopExpDist > 0.0 + && occupied->DistCounter() > fLastStopExpDist ) { + // zaktualizować wyświetlanie rozkładu + TrainParams.StationStart = TrainParams.StationIndex; + fLastStopExpDist = -1.0; // usunąć licznik + if( true == m_makenextstopannouncement ) { + announce( announcement_t::next ); + m_makenextstopannouncement = false; // keep next stop announcements suppressed until another scheduled stop + } + } +} + +void +TController::determine_braking_distance() { + // przybliżona droga hamowania + // NOTE: we're ensuring some minimal braking distance to reduce ai flipping states between starting and braking + auto const velceil { std::max( 2.0, std::ceil( occupied->Vel ) ) }; + fBrakeDist = fDriverBraking * velceil * ( 40.0 + velceil ); + if( fMass > 1000000.0 ) { + // korekta dla ciężkich, bo przeżynają - da to coś? + fBrakeDist *= 2.0; + } + if( -fAccThreshold > 0.05 + && occupied->CategoryFlag == 1 ) { + fBrakeDist = velceil * velceil / 25.92 / -fAccThreshold; + } + if( occupied->brakes.delaySetting == bdelay_G ) { + // dla nastawienia G koniecznie należy wydłużyć drogę na czas reakcji + fBrakeDist += 2 * velceil; + } + if( occupied->Vel > 15.0 + && mvControlling->EngineType == TEngineType::ElectricInductionMotor + && is_emu() ) { + // HACK: make the induction motor powered EMUs start braking slightly earlier + fBrakeDist += 10.0; + } +/* + // take into account effect of gravity (but to stay on safe side of calculations, only downhill) + if( fAccGravity > 0.025 ) { + fBrakeDist *= ( 1.0 + fAccGravity ); + // TBD: use version which shortens route going uphill, too + //fBrakeDist = std::max( fBrakeDist, fBrakeDist * ( 1.0 + fAccGravity ) ); + } +*/ +} + +void +TController::scan_route( double const Range ) { + + TableCheck( Range ); +} + +void +TController::determine_proximity_ranges() { + // ustalenie dystansów w pozostałych przypadkach + switch (SingleOrder(OrderCurrentGet())) + { + case DriverOrder::connect: { + // podłączanie do składu + if (drivingFlags.connect) { + // jeśli stanął już blisko, unikając zderzenia i można próbować podłączyć + fMinProximityDist = -1.0; + fMaxProximityDist = 0.0; //[m] dojechać maksymalnie + fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu + } + else { + // jak daleko, to jazda jak dla Shunt na kolizję + fMinProximityDist = 2.0; + fMaxProximityDist = 5.0; //[m] w takim przedziale odległości powinien stanąć + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 1.0; // margines prędkości powodujący załączenie napędu + } + break; + } + case DriverOrder::disconnect: { + // 20.07.03 - manewrowanie wagonami + fMinProximityDist = 1.0; + fMaxProximityDist = 10.0; //[m] + fVelPlus = 1.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu + break; + } + case DriverOrder::shunt: { + // na jaką odleglość i z jaką predkością ma podjechać + // TODO: test if we can use the distances calculation from obey_train + fMinProximityDist = std::min( 5 + iVehicles, 25 ); + fMaxProximityDist = std::min( 10 + iVehicles, 50 ); + // HACK: modern vehicles might brake slower at low speeds, increase safety margin as crude counter + if( mvControlling->EIMCtrlType > 0 ) { + fMinProximityDist += 5.0; + fMaxProximityDist += 5.0; + } + // take into account weather conditions + if (Global.FrictionWeatherFactor < 1.f + && iVehicles > 1 ) { + fMinProximityDist += 5.0; + fMaxProximityDist += 5.0; + } + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + // margines prędkości powodujący załączenie napędu + // były problemy z jazdą np. 3km/h podczas ładowania wagonów + fVelMinus = std::min( 0.1 * fShuntVelocity, 3.0 ); + break; + } + case DriverOrder::looseShunt: { + fMinProximityDist = -1.0; + fMaxProximityDist = 0.0; //[m] dojechać maksymalnie + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 0.5; // margines prędkości powodujący załączenie napędu + break; + } + case DriverOrder::obeyTrain: { + // na jaka odleglosc i z jaka predkoscia ma podjechac do przeszkody + // jeśli pociąg + if( is_train() ) { + auto const [ minproximity, maxproximity ] { train_proximity_margins( IsAtPassengerStop ) }; + fMinProximityDist = minproximity; + fMaxProximityDist = maxproximity; + + if( drivingFlags.late ) { + // jeśli spóźniony, to gna + fVelMinus = 1.0; + // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelPlus = 5.0; + } + else { + // gdy nie musi się sprężać + // margines prędkości powodujący załączenie napędu; min 1.0 żeby nie ruszał przy 0.1 + fVelMinus = std::clamp( std::round( 0.05 * VelDesired ), 1.0, 5.0 ); + // normalnie dopuszczalne przekroczenie to 5% prędkości ale nie więcej niż 5km/h + // bottom margin raised to 2 km/h to give the AI more leeway at low speed limits + fVelPlus = std::clamp( std::ceil( 0.05 * VelDesired ), 2.0, 5.0 ); + } + } + // samochod (sokista też) + else { + fMinProximityDist = std::max( 3.5, occupied->Vel * 0.2 ); + fMaxProximityDist = std::max( 9.5, occupied->Vel * 0.375 ); //[m] + if( Global.FrictionWeatherFactor < 1.f ) { + // take into account weather conditions + fMinProximityDist += 0.75; + fMaxProximityDist += 0.75; + } + // margines prędkości powodujący załączenie napędu + fVelMinus = 2.0; + // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelPlus = std::min( 10.0, occupied->Vel * 0.1 ); + } + break; + } + case DriverOrder::bank: { + // TODO: implement + break; + } + default: { + fMinProximityDist = 5.0; + fMaxProximityDist = 10.0; //[m] + fVelPlus = 2.0; // dopuszczalne przekroczenie prędkości na ograniczeniu bez hamowania + fVelMinus = 5.0; // margines prędkości powodujący załączenie napędu + } + } // switch OrderList[OrderPos] +} diff --git a/vehicle/ai/speed.cpp b/vehicle/ai/speed.cpp new file mode 100644 index 000000000..a0d22367b --- /dev/null +++ b/vehicle/ai/speed.cpp @@ -0,0 +1,913 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the speed the driver aims for + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +const double PassengetTrainAcceleration = 0.40; +const double HeavyPassengetTrainAcceleration = 0.20; +const double CargoTrainAcceleration = 0.25; +const double HeavyCargoTrainAcceleration = 0.10; + +// modifies brake distance for low target speeds, to ease braking rate in such situations +float +TController::braking_distance_multiplier( float const Targetvelocity ) const { + + auto const frictionmultiplier { 1.f / Global.FrictionWeatherFactor }; + + if( Targetvelocity > 65.f ) { return 1.f * frictionmultiplier; } + if( Targetvelocity < 5.f ) { + // HACK: engaged automatic transmission means extra/earlier braking effort is needed for the last leg before full stop + if( is_dmu() + && occupied->Vel < 40.0 + && Targetvelocity == 0.f ) { + auto const multiplier { std::clamp( 1.f + iVehicles * 0.5f, 2.f, 4.f ) }; + return std::lerp(multiplier, 1.f, static_cast(occupied->Vel / 40.0)) * frictionmultiplier; + } + // HACK: cargo trains or trains going downhill with high braking threshold need more distance to come to a full stop + if( fBrake_a0[1] > 0.2 + && ( true == IsCargoTrain + || fAccGravity > 0.025 ) ) { + return std::lerp(1.f, 2.f, std::clamp((fBrake_a0[1] - 0.2) / 0.2, 0.0, 1.0)) * frictionmultiplier; + } + + return 1.f * frictionmultiplier; + } + // stretch the braking distance up to 3 times; the lower the speed, the greater the stretch + return std::lerp(3.f, 1.f, (Targetvelocity - 5.f) / 60.f) * frictionmultiplier; +} + +double TController::ESMVelocity(bool Main) +{ + double fCurrentCoeff = 0.9; + double fFrictionCoeff = 0.85; + double ESMVel = 9999; + int MCPN = mvControlling->MainCtrlActualPos; + int SCPN = mvControlling->ScndCtrlActualPos; + if (Main) + MCPN += 1; + else + SCPN += 1; + if (mvControlling->RList[MCPN].ScndAct < 255 && mvControlling->ScndCtrlActualPos == 0) + SCPN = mvControlling->RList[MCPN].ScndAct; + double FrictionMax = mvControlling->Mass()*9.81*mvControlling->Adhesive(mvControlling->RunningTrack.friction)*fFrictionCoeff; + double IF = mvControlling->Imax; + double MS = 0; + double Fmax = 0; + for (int i = 0; i < 5; i++) + { + MS = mvControlling->MomentumF(IF, IF, SCPN); + Fmax = MS * mvControlling->RList[MCPN].Bn * mvControlling->RList[MCPN].Mn * 2 / mvControlling->WheelDiameter() * mvControlling->Transmision.Ratio; + if( Fmax != 0.0 ) { + IF = 0.5 * IF * ( 1 + FrictionMax / Fmax ); + } + else { + // NOTE: gets trimmed to actual highest acceptable value after the loop + IF = std::numeric_limits::max(); + break; + } + } + IF = std::min(IF, mvControlling->Imax*fCurrentCoeff); + double R = mvControlling->RList[MCPN].R + mvControlling->CircuitRes + mvControlling->RList[MCPN].Mn*mvControlling->WindingRes(); + // SCPN may come from the .fiz (RList ScndAct) unchecked: read it with the bounds-safe accessor, as MomentumF() does + auto const &motorparam{mvControlling->motor_param(SCPN)}; + double pole = motorparam.fi * + std::max(abs(IF) / (abs(IF) + motorparam.Isat) - motorparam.fi0, 0.0); + double Us = abs(mvControlling->EngineVoltage) - IF*R; + double ns = std::max(0.0, Us / (pole*mvControlling->RList[MCPN].Mn)); + ESMVel = ns * mvControlling->WheelDiameter()*M_PI*3.6/mvControlling->Transmision.Ratio; + return ESMVel; +} + +// the stages of uncoupling: each one sets the speed for the next +void +TController::set_velocity_for_uncoupling() { + + if( iVehicleCount < 0 ) { + // 4th stage: restore initial direction + if( drivingFlags.press ) { + SetVelocity( 0, 0, stopJoin ); + } + return; + } + // 3rd stage: compress buffers and uncouple + if( drivingFlags.press && iDirection == iDirectionOrder ) { + SetVelocity( 2, 0 ); // jazda w ustawionym kierunku z prędkością 2 + return; + } + // 1st stage: bring it to stop + // 2nd stage: apply consist brakes and change direction + SetVelocity( 0, 0, stopJoin ); +} + +// uphill, the gradient alone brings a slow train to a stand within metres, far sooner than a released +// brake applies; so the train brake goes on while the train is coming to a stand, stays on while it +// stands, and is applied for real if the train has started to roll back +void +TController::hold_train_coming_to_stand_uphill() { + + if( ( false == is_train() ) + || ( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) + || ( VelNext != 0.0 ) + || ( ActualProximityDist > fMaxProximityDist ) + || ( fAccGravity >= EU07_AI_UPHILLGRAVITY ) ) { + return; + } + auto const vel { DirectionalVel() }; + if( std::abs( vel ) < EU07_AI_NOMOVEMENT ) { + VelDesired = 0.0; + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + return; + } + if( ( vel < 0.0 ) + || ( ( vel < 5.0 ) && ( AccDesired < 0.0 ) ) + // rolling to a stand on the gradient alone, the brake has to be on its way before the train stops: + // once the time left to the stand is no longer than half of what the brake takes to apply, apply it; any + // sooner and the brake takes off more of the distance than the stop was planned with + || ( ( BrakeSystem == TBrakeSystem::Pneumatic ) + // not for a train that is short of where it is to stop and is to pull up further + && ( AccDesired <= 0.0 ) + && ( vel / 3.6 / -fAccGravity <= 0.5 * vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fBrake_a0[ 0 ] ) ) ) ) { + // the gradient alone already slows the train down nearly this much; ask for enough on top of it that + // the brake is applied for sure, not held back by the margin against small corrections + AccDesired = std::min( AccDesired, fAccGravity - std::max( 0.15, fBrake_a0[ 0 ] ) - brake_increase_margin() ); + } +} + +void +TController::pick_optimal_speed( double const Range ) { + +// if( false == OrderCurrentGet().HasAny( Shunt | Loose_shunt | Obey_train | Bank | Connect | Disconnect | Change_direction ) ) { return; } + + // set initial velocity and acceleration values + SetDriverPsyche(); // ustawia AccPreferred (potrzebne tu?) + VelDesired = fVelMax; // wstępnie prędkość maksymalna dla pojazdu(-ów), będzie następnie ograniczana + AccDesired = AccPreferred; // AccPreferred wynika z osobowości mechanika + + // nie przekraczać rozkladowej + if( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) + && TrainParams.TTVmax > 0.0 ) { + VelDesired = + min_speed( + VelDesired, + TrainParams.TTVmax ); + } + +// VelNext = VelDesired; // maksymalna prędkość wynikająca z innych czynników niż trajektoria ruchu + // HACK: -1 means we can pick up 0 speed limits in ( point.velnext > velnext ) tests aimed to find highest next speed, + // but also doubles as 'max speed' in min_speed tests, so it shouldn't interfere if we don't find any speed limits + VelNext = -1.0; + + // basic velocity and acceleration adjustments + // jeśli manewry, to ograniczamy prędkość + if( false == OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { // spokojne manewry + SetVelocity( fShuntVelocity, fShuntVelocity ); + VelDesired = + min_speed( + VelDesired, + fShuntVelocity ); + } + // uncoupling mode changes velocity/acceleration between stages + if( OrderCurrentGet().HasAny(DriverOrder::disconnect) ) { + set_velocity_for_uncoupling(); + } + + VelLimitLastDist = { VelDesired, -1 }; + SwitchClearDist = -1; + ActualProximityDist = Range; // funkcja Update() może pozostawić wartości bez zmian + + // if we're idling bail out early + if( false == is_active() ) { + VelDesired = 0.0; + VelNext = 0.0; + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + return; + } + + // Ra: odczyt (ActualProximityDist), (VelNext) i (AccPreferred) z tabelki prędkosci + check_route_ahead( Range ); + + check_departure(); + + // if ordered to turn off the vehicle, try to stop + if( true == OrderCurrentGet().HasAll(DriverOrder::releaseEngine) ) { + SetVelocity( 0, 0, stopSleep ); + } + // if ordered to change direction, try to stop + if( true == OrderCurrentGet().HasAll(DriverOrder::changeDirection) ) { + SetVelocity( 0, 0, stopDir ); + } + + adjust_desired_speed_for_obstacles(); + adjust_desired_speed_for_limits(); + adjust_desired_speed_for_target_speed( Range ); + adjust_desired_speed_for_current_speed(); + adjust_desired_speed_for_braking_test(); + + // Ra 2F1I: wyłączyć kiedyś to uśrednianie i przeanalizować skanowanie, czemu migocze + if( AccDesired > EU07_AI_NOACCELERATION ) { // hamowania lepeiej nie uśredniać + AccDesired = fAccDesiredAv = + 0.2 * AccDesired + + 0.8 * fAccDesiredAv; // uśrednione, żeby ograniczyć migotanie + } + if( VelDesired == 0.0 ) { + // Ra 2F1J: jeszcze jedna prowizoryczna łatka + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + } + + // last step sanity check, until the whole calculation is straightened out + AccDesired = std::min( AccDesired, AccPreferred ); + AccDesired = std::clamp( + AccDesired, + is_car() ? -2.0 : -0.9, + is_car() ? 2.0 : 0.9 ); + + // done last, so that none of the adjustments above, made for a train moving forward, can undo it + hold_train_coming_to_stand_uphill(); + + // if the route ahead is blocked we might need to head the other way + check_route_behind( 1000 ); // NOTE: legacy scan range value +} + +void +TController::adjust_desired_speed_for_obstacles() { + // prędkość w kierunku jazdy, ujemna gdy jedzie w przeciwną stronę niż powinien + auto const vel { DirectionalVel() }; + + if (VelDesired < 0.0) + VelDesired = fVelMax; // bo VelDesired<0 oznacza prędkość maksymalną + + // Ra: jazda na widoczność + if( Obstacle.distance < 5000 ) { + // mamy coś z przodu + // prędkość pojazdu z przodu (zakładając, że jedzie w tę samą stronę!!!) + auto const k { Obstacle.vehicle->physics->Vel }; + + if( k - vel < 5 ) { + // porównanie modułów prędkości [km/h] + // zatroszczyć się trzeba, jeśli tamten nie jedzie znacząco szybciej + if( Obstacle.distance < ActualProximityDist ) { + // the vehicle ahead, not the stop found by the scan, is what the train is now to stop short of + bStopTargetIsPassengerStop = false; + } + ActualProximityDist = std::min( + ActualProximityDist, + Obstacle.distance ); + + if( Obstacle.distance <= ( + occupied->CategoryFlag & 2 ? + 100.0 : // cars + 250.0 ) ) { // others + // regardless of driving mode at close distance take precaution measures: + // match the other vehicle's speed or slow down if the other vehicle is stopped + VelDesired = + min_speed( + VelDesired, + std::max( + k, + occupied->CategoryFlag & 2 ? + 40.0 : // cars + 20.0 ) ); // others + if( vel > VelDesired + fVelPlus ) { + // if going too fast force some prompt braking + AccPreferred = std::min( + occupied->CategoryFlag & 2 ? -0.65 : // cars + -0.30, // others + AccPreferred ); + } + } + + double const distance = Obstacle.distance - fMaxProximityDist - fBrakeDist * 1.15; // odległość bezpieczna zależy od prędkości + if( distance < 0.0 ) { + // jeśli odległość jest zbyt mała + if( k < 10.0 ) // k - prędkość tego z przodu + { // jeśli tamten porusza się z niewielką prędkością albo stoi + // keep speed difference within a safer margin + VelDesired = std::floor( + min_speed( + VelDesired, + Obstacle.distance > 100 ? k + 20.0 : std::min(8.0, k + 4.0) ) ); + + if( OrderCurrentGet().HasAny( DriverOrder::connect | DriverOrder::looseShunt ) ) { + // jeśli spinanie, to jechać dalej + AccPreferred = std::min( 0.35, AccPreferred ); // nie hamuj + VelNext = std::floor( std::min( 8.0, k + 2.0 ) ); // i pakuj się na tamtego + } + else { + // a normalnie to hamować + VelNext = 0.0; + if( Obstacle.distance <= fMinProximityDist ) { + VelDesired = 0.0; + } + + if( occupied->CategoryFlag & 1 + && OrderCurrentGet() & DriverOrder::obeyTrain ) { + // trains which move normally should try to stop at safe margin + ActualProximityDist -= fDriverDist; + } + } + } + else { + // jeśli oba jadą, to przyhamuj lekko i ogranicz prędkość + if( Obstacle.distance < ( + occupied->CategoryFlag & 2 ? + fMaxProximityDist + 0.5 * vel : // cars + 2.0 * fMaxProximityDist + 2.0 * vel ) ) { //others + // jak tamten jedzie wolniej a jest w drodze hamowania + AccPreferred = std::min( -0.9, AccPreferred ); + VelNext = min_speed( std::round( k ) - 5.0, VelDesired ); + if( Obstacle.distance <= ( + occupied->CategoryFlag & 2 ? + fMaxProximityDist : // cars + 2.0 * fMaxProximityDist ) ) { //others + // try to force speed change if obstacle is really close + VelDesired = VelNext; + } + } + } + ReactionTime = occupied->Vel > EU07_AI_NOMOVEMENT ? 0.1 : // orientuj się, bo jest goraco + 2.0; // we're already standing still, so take it easy + } + else { + if( OrderCurrentGet() & DriverOrder::connect ) { + // if there's something nearby in the connect mode don't speed up too much + VelDesired = + min_speed( + VelDesired, + Obstacle.distance > 100 ? 20.0 : 4.0 ); + } + } + } + } +} + +void +TController::adjust_desired_speed_for_limits() { + // speed caps checks + // sprawdzamy możliwe ograniczenia prędkości + if( VelSignal >= 0 ) { + // jeśli skład był zatrzymany na początku i teraz już może jechać + VelDesired = + min_speed( + VelDesired, + VelSignal ); + } + if( occupied->RunningTrack.Velmax >= 0 ) { + // ograniczenie prędkości z trajektorii ruchu + VelDesired = + min_speed( + VelDesired, + occupied->RunningTrack.Velmax ); // uwaga na ograniczenia szlakowej! + } + if( VelforDriver >= 0 ) { + // tu jest zero przy zmianie kierunku jazdy + // Ra: tu może być 40, jeśli mechanik nie ma znajomości szlaaku, albo kierowca jeździ 70 + VelDesired = + min_speed( + VelDesired, + VelforDriver ); + } + + // recalculate potential load exchange duration + check_load_exchange(); + if( ExchangeTime > 0 + || occupied->Vel > 2.0 ) { // HACK: force timer reset if the load exchange is cancelled due to departure + WaitingSet( ExchangeTime ); + } + if( fStopTime < 0 ) { + VelDesired = 0.0; // jak ma czekać, to nie ma jazdy + cue_action( driver_hint::waitloadexchange ); + return; // speed limit can't get any lower + } + + if( OrderCurrentGet().HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) && drivingFlags.stopHere && occupied->Vel < 0.01 && VelSignalNext == 0.0 ) { + // w Connect nie, bo moveStopHere odnosi się do stanu po połączeniu + // jeśli ma czekać na wolną drogę, stoi a wyjazdu nie ma, to ma stać + VelDesired = 0.0; + return; // speed limit can't get any lower + } + + if( OrderCurrentGet() == DriverOrder::waitForOrders ) { + // wait means sit and wait + VelDesired = 0.0; + return; // speed limit can't get any lower + } +} + +// how long the present acceleration of a consist lasts whatever is done with the handle now: half the time +// its pneumatic brake takes to apply (while speeding up) or to release (while slowing down), which in G +// is tens of seconds; never shorter than the look-ahead the AI has always used +double +vehicle_ai::brake_response_horizon( physics::Vehicle const *Vehicle, TBrakeSystem const Brakesystem, double const Acceleration, double const Brakea0 ) { + + auto horizon { ( 1.0 - Brakea0 ) * 30.0 / 3.6 }; + if( Brakesystem == TBrakeSystem::Pneumatic ) { + // BrakeDelay holds the release and the application time in G, then the same two in P + auto const delays { Vehicle->brakes.delaySetting > bdelay_G ? 0 : 2 }; + auto const isrelease { Acceleration < 0.0 }; + horizon = std::max( horizon, 0.5 * Vehicle->brakes.config.delays[ delays + ( isrelease ? 0 : 1 ) ] ); + } + return horizon; +} + +// distance [m] in which the gradient alone, with no brake and no power, brings a train rolling uphill at Velocity [km/h] to a stand +double +vehicle_ai::uphill_stopping_distance( double const Velocity, double const Gravity ) { + return ( Velocity / 3.6 ) * ( Velocity / 3.6 ) / ( 2.0 * std::max( 0.01, -Gravity ) ); +} + +// speed [km/h] from which the gradient alone brings a train rolling uphill to a stand in Distance [m] +static double +uphill_coasting_speed( double const Distance, double const Gravity ) { + return 3.6 * std::sqrt( 2.0 * std::max( 0.01, -Gravity ) * std::max( 0.0, Distance ) ); +} + +// outside of max safe range: follow the braking curve down to the speed ahead, Vel is the present speed in the +// direction of travel +void +TController::adjust_desired_speed_for_braking_curve( double const Vel ) { + + AccDesired = AccPreferred; + if( Vel <= min_speed( ActualProximityDist > 10.0 ? 10.0 : 5.0, VelDesired ) ) { + return; + } + // allow to coast at reasonably low speed + auto const brakingdistance { fBrakeDist * braking_distance_multiplier( VelNext ) }; + if( auto const slowdowndistance { ( + occupied->CategoryFlag == 2 ? // cars can stop on a dime, for bigger vehicles we enforce some minimal braking distance + brakingdistance : + std::max( + false == OrderCurrentGet().HasAny(DriverOrder::connect) ? 100.0 : 25.0, + brakingdistance ) ) }; + brakingdistance + std::max(slowdowndistance, fMaxProximityDist) < ActualProximityDist - fMaxProximityDist ) { + // don't slow down prematurely; as long as we have room to come to a full stop at a safe distance, we're good + return; + } + // ensure some minimal coasting speed, otherwise a vehicle entering this zone at very low speed will be crawling forever + auto const brakingpointoffset = ( + ( VelNext == 0.0 ) && is_train() && ( OrderCurrentGet() & DriverOrder::obeyTrain ) ? + stopping_margin() : // the same stopping point as the final approach + VelNext * braking_distance_multiplier( static_cast( VelNext ) ) ); + // both plans of a pneumatic brake are made from the brake table of the consist; with none (in shunting it isn't + // worked out) the braking curve is the constant deceleration over the distance left, as before them + braking_curve::brake_table const braketable { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax() }; + // making for a passenger stop only the time the brake takes to fill: the look-ahead the horizon + // keeps as its floor was set for the stops at a signal, and a vehicle that brakes with its + // independent brake, which leaves the train brake handle where it is, kept braking earlier + // and earlier the whole way in, to crawl the last tens of metres to the stop point + auto const fillbrakea0 { bStopTargetIsPassengerStop ? 1.0 : fBrake_a0[ 0 ] }; + // once the brake is on, the room it takes to fill is behind; a vehicle running alone brakes with its + // independent brake and leaves the train brake handle in running, so that brake counts as well + braking_curve::approach const approach { + Vel, VelNext, ActualProximityDist, brakingpointoffset, fAccGravity, AbsAccS, + braking_curve::brake_acting( + BrakeCtrlPosition, + // IncLocalBrakeLevel() moves the independent brake handle on a vehicle without one too + ( occupied->brakes.config.localKind == TLocalBrake::PneumaticBrake || occupied->brakes.config.localKind == TLocalBrake::HydraulicBrake ) ? + occupied->brakes.IndependentPosition() : + 0.0 ), + vehicle_ai::brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ), + vehicle_ai::brake_response_horizon( occupied, BrakeSystem, 1.0, fillbrakea0 ) }; + auto const deceleration { braking_curve::demand( approach, BrakeSystem == TBrakeSystem::Pneumatic ? &braketable : nullptr ) }; + AccDesired = std::min( AccDesired, deceleration ); // najpierw hamuje mocniej, potem zluzuje + if( Vel <= VelNext ) { + return; + } + if( deceleration < fAccGravity - 0.001 ) { + // no power while still above the speed being braked for + AccDesired = std::min( AccDesired, EU07_AI_NOACCELERATION ); + } + else if( ( fAccGravity < -0.025 ) + && ( OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) + && ( false == uphill_brake_committed( Vel ) ) + && ( ActualProximityDist - vehicle_ai::uphill_stopping_distance( Vel, fAccGravity ) > brakingpointoffset ) ) { + // uphill the gradient alone slows the train down more than it is asked to; + // keep it rolling at the present speed until that changes + AccDesired = std::min( 0.0, AccPreferred ); + VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - brakingpointoffset, fAccGravity ) ); + } +} + +// the final approach to a stop, inside the proximity range: Vel is the present speed in the direction of travel +void +TController::adjust_desired_speed_for_final_approach( double const Vel ) { + + if( ( occupied->CategoryFlag & 1 ) == 0 ) { + // for cars (and others) coast at low speed until we hit min proximity range + VelDesired = min_speed( VelDesired, 5.0 ); + return; + } + // trains + if( ( OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::connect ) ) + && ( Obstacle.distance < 50 ) ) { + // crude detection of edge case, if approaching another vehicle coast slowly until min distance + // this should allow to bunch up trainsets more on sidings + VelDesired = min_speed( 5.0, VelDesired ); + return; + } + // hamowanie tak, aby stanąć + if( false == OrderCurrentGet().HasAny(DriverOrder::obeyTrain) ) { + VelDesired = VelNext; + AccDesired = ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * ( ActualProximityDist + 0.1 - 0.5*fMinProximityDist ) ); + AccDesired = std::min( AccDesired, fAccThreshold ); + return; + } + // a train keeps its desired speed until the lower edge of the stopping window (a desired + // speed of 0 here asks for hard braking whatever the distance left), aims at the middle + // of the window, and asks only for what that takes + auto const stoppingroom { std::max( 0.5, ActualProximityDist - stopping_margin() ) }; + AccDesired = ( + BrakeSystem == TBrakeSystem::Pneumatic ? + // cast iron blocks grip harder as the train comes to a stand + braking_curve::shaped_demand( + Vel, VelNext, stoppingroom, fAccGravity, + { fBrake_a0, fBrake_a1, BrakeAccTableSize, occupied->Vmax() } ) : + ( VelNext * VelNext - Vel * Vel ) / ( 25.92 * stoppingroom ) ); + if( ( fAccGravity < -0.025 ) + && ( AccDesired >= fAccGravity - 0.001 ) // no brake needed at all + && ( false == uphill_brake_committed( Vel ) ) + && ( ActualProximityDist - vehicle_ai::uphill_stopping_distance( Vel, fAccGravity ) > stopping_margin() ) ) { + // uphill the gradient alone would bring the train to a stand short of the + // middle of the stopping window; keep it rolling at the present speed until that changes, + // but no faster than the gradient alone can take off by the middle of the window + AccDesired = std::min( 0.0, AccPreferred ); + VelDesired = min_speed( VelDesired, uphill_coasting_speed( ActualProximityDist - stopping_margin(), fAccGravity ) ); + } + if( ( BrakeSystem == TBrakeSystem::Pneumatic ) + && ( braking_curve::stops_where_it_is( Vel, ActualProximityDist - stopping_margin(), fAccGravity ) ) ) { + // down a gradient at walking pace in the last metres before the point it aims at, or past it: it stops here, + // rather than lets off the brake to creep on, which lets the gradient take it again + VelDesired = 0.0; + } +} + +void +TController::adjust_desired_speed_for_target_speed( double const Range ) { + // ustalanie zadanego przyspieszenia + //(ActualProximityDist) - odległość do miejsca zmniejszenia prędkości + //(AccPreferred) - wynika z psychyki oraz uwzglęnia już ewentualne zderzenie z pojazdem z przodu, ujemne gdy należy hamować + //(AccDesired) - uwzględnia sygnały na drodze ruchu, ujemne gdy należy hamować + //(fAccGravity) - chwilowe przspieszenie grawitacyjne, ujemne działa przeciwnie do zadanego kierunku jazdy + //(AbsAccS) - chwilowe przyspieszenie pojazu (uwzględnia grawitację), ujemne działa przeciwnie do zadanego kierunku jazdy + //(AccDesired) porównujemy z (fAccGravity) albo (AbsAccS) + + // gdy jedzie wolniej niż potrzeba, albo nie ma przeszkód na drodze + // normalna jazda + AccDesired = VelDesired != 0.0 ? AccPreferred : -0.01; + fAccDesiredGravity = 0.0; + + auto const vel { DirectionalVel() }; + + if( VelNext >= 0.0 + && ActualProximityDist <= Range + && vel >= VelNext ) { + // gdy zbliża się i jest za szybki do nowej prędkości, albo stoi na zatrzymaniu + if (vel > EU07_AI_NOMOVEMENT) { + // jeśli jedzie + if( vel < VelNext + && ActualProximityDist > fMaxProximityDist * (1.0 + 0.1 * vel) ) { + // jeśli jedzie wolniej niż można i jest wystarczająco daleko, to można przyspieszyć + if( AccPreferred > 0.0 ) { + // jeśli nie ma zawalidrogi dojedz do semafora/przeszkody + AccDesired = AccPreferred; + } + } + else if( ( ActualProximityDist > fMinProximityDist ) + // only a stop has a final approach of its own inside the proximity range; a lower speed ahead + // keeps the braking curve below right up to where it begins, or the train would stop braking + // (and even take power) that far out + && ( VelNext == 0.0 ) + && ( ActualProximityDist < fMaxProximityDist ) ) { + // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko + // jak minął już maksymalny dystans po prostu hamuj (niski stopień) + // ma stanąć, a jest w drodze hamowania albo ma jechać + adjust_desired_speed_for_final_approach( vel ); + AccDesired = std::min( AccDesired, AccPreferred ); + } + else if (ActualProximityDist > fMinProximityDist) { + // jedzie szybciej, niż trzeba na końcu ActualProximityDist, ale jeszcze jest daleko + adjust_desired_speed_for_braking_curve( vel ); + AccDesired = std::min( AccDesired, AccPreferred ); + } + else { + // jest bliżej niż fMinProximityDist + // utrzymuj predkosc bo juz blisko +/* + VelDesired = min_speed( VelDesired, VelNext ); +*/ + if( VelNext == 0.0 ) { + VelDesired = VelNext; + } + else { + if( vel <= VelNext + fVelPlus ) { + // jeśli niewielkie przekroczenie, ale ma jechać + AccDesired = std::max( 0.0, AccPreferred ); // to olej (zacznij luzować) + } + } + ReactionTime = 0.1; // i orientuj się szybciej + } + } + else { + // zatrzymany (vel==0.0) + if( VelNext > 0.0 ) { + // można jechać + AccDesired = AccPreferred; + } + else { + // jeśli daleko jechać nie można + if( ActualProximityDist > ( + occupied->CategoryFlag & 2 ? + fMinProximityDist : // cars + fMaxProximityDist ) ) { // trains and others + // ale ma kawałek do sygnalizatora + if( AccPreferred > 0.0 ) { + // dociagnij do semafora; + AccDesired = AccPreferred; + } + else { + //stoj + VelDesired = 0.0; + } + } + else { + // VelNext=0 i stoi bliżej niż fMaxProximityDist + VelDesired = 0.0; + } + } + } + } +} + +void +TController::adjust_desired_speed_for_current_speed() { + // decisions based on current speed + auto const vel { DirectionalVel() }; + + if( is_train() ) { + // on flats or uphill we can be less careful + if( vel > VelDesired ) { + // jesli jedzie za szybko do AKTUALNEGO + if( VelDesired == 0.0 ) { + // jesli stoj, to hamuj, ale i tak juz za pozno :) + AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie + } + else { + // slow down, not full stop + if( vel > VelDesired + fVelPlus ) { + // hamuj tak średnio + AccDesired = std::min( AccDesired, -0.05 + fAccThreshold ); + } + else { + // o 5 km/h to olej (zacznij luzować) + AccDesired = std::min( + AccDesired, // but don't override decceleration for VelNext + std::max( 0.0, AccPreferred ) ); + } + } + } + + if( fAccGravity > 0.025 ) { + // going sharply downhill we may need to start braking sooner than usual + // try to estimate increase of current velocity before engaged brakes start working + // look ahead for as long as the brake takes to respond, since that is how long the + // present acceleration will last whatever is done with the handle now; a pneumatic + // brake applies and releases on its own time scale, which in G is tens of seconds + auto const horizon { vehicle_ai::brake_response_horizon( occupied, BrakeSystem, AbsAccS, fBrake_a0[ 0 ] ) }; + auto const speedestimate = vel + 3.6 * horizon * AbsAccS; + // already below a lower limit ahead, the train has no business speeding up towards it + auto holdlimit { VelDesired }; + if( ( VelNext > 0.0 ) + && ( VelNext < holdlimit ) + && ( vel <= VelNext + fVelPlus ) + && ( ActualProximityDist < std::max( 2.0 * fBrakeDist, 500.0 ) ) ) { + holdlimit = VelNext; + } + // hold a band just below the limit; the steeper the descent the harder the train pulls + // away once the brake eases, so the band widens with the gradient (about 3 km/h at 20 per mille) + // an electro-pneumatic or electric brake responds at once and needs far less room + auto const holdspeed { holdlimit - ( + BrakeSystem == TBrakeSystem::Pneumatic ? + std::clamp( fAccGravity * 15.0, 1.0, 3.0 ) : + std::clamp( fAccGravity * 7.5, 1.0, 1.5 ) ) }; + // the predicted difference is to be made up over the time the brake takes to respond, not at once: with a + // slow brake, a demand sized to remove it at once comes on as a deep application, which then takes as + // long to let go, and the train ends up well below the speed it was to hold + auto const holdgain { std::min( 0.04, 1.0 / ( 3.6 * std::max( 1.0, horizon ) ) ) }; + if( ( speedestimate > VelDesired ) + && ( VelDesired == 0.0 ) ) { + // jesli stoj, to hamuj, ale i tak juz za pozno :) + AccDesired = std::min( AccDesired, -0.85 ); // hamuj solidnie + } + else { + // one continuous law on both sides of the target, proportional to the predicted + // difference: a demand that jumps to the braking threshold above the target and to + // full acceleration below it alternates, with a brake that responds in seconds, + // between a hard application and a full release + AccDesired = std::min( + AccDesired, // but don't override decceleration for VelNext + std::clamp( + EU07_AI_NOACCELERATION - holdgain * ( speedestimate - holdspeed ), + -0.05 + fAccThreshold, + std::max( EU07_AI_NOACCELERATION, AccPreferred ) ) ); + // HACK: for cargo trains with high braking threshold ensure we cross that threshold + auto const crossthreshold { IsCargoTrain && fBrake_a0[ 0 ] > 0.2 && speedestimate > holdlimit }; + AccDesired -= ( crossthreshold ? std::clamp( fBrake_a0[ 0 ] - 0.2, 0.0, 0.15 ) : 0.0 ); + } + // final tweaks + if( vel > EU07_AI_NOMOVEMENT ) { + // going downhill also take into account impact of gravity + AccDesired -= fAccGravity; + // from here on AccDesired is what the brake alone has to deliver, which is what + // IncBrake() sizes the handle position for; AbsAccS already contains the gravity, + // so the comparisons with it have to add this part back + fAccDesiredGravity = fAccGravity; + // HACK: if the max allowed speed was exceeded something went wrong; brake harder + AccDesired -= 0.15 * std::clamp( vel - VelDesired, 0.0, 5.0 ); + } + } + // HACK: limit acceleration for cargo trains, to reduce probability of breaking couplers on sudden jolts + auto MaxAcc{ 0.5 * occupied->Couplers[(occupied->DirAbsolute >= 0 ? VehicleEnd::rear : VehicleEnd::front)].FmaxC / fMass }; + if( iVehicles - ControlledEnginesCount > 0 ) { + MaxAcc *= std::clamp( vel * 0.025, 0.2, 1.0 ); + } + AccDesired = std::min(AccDesired, safe_clamp(MaxAcc, HeavyCargoTrainAcceleration, AccPreferred)); + // TBD: expand this behaviour to all trains with car(s) exceeding certain weight? + /* + if( ( IsPassengerTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { + AccDesired = std::min( AccDesired, ( iVehicles - ControlledEnginesCount > 8 ? HeavyPassengetTrainAcceleration : PassengetTrainAcceleration ) ); + } + if( ( IsCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { + AccDesired = std::min( AccDesired, CargoTrainAcceleration ); + } + if( ( IsHeavyCargoTrain ) && ( iVehicles - ControlledEnginesCount > 0 ) ) { + AccDesired = std::min( AccDesired, HeavyCargoTrainAcceleration ); + } */ + } + else { + // for cars the older version works better + if( vel > VelDesired ) { + // jesli jedzie za szybko do AKTUALNEGO + if( VelDesired == 0.0 ) { + // jesli stoj, to hamuj, ale i tak juz za pozno :) + AccDesired = std::min( AccDesired, -0.9 ); // hamuj solidnie + } + else { + // slow down, not full stop + if( vel > VelDesired + fVelPlus ) { + // hamuj tak średnio + AccDesired = std::min( AccDesired, -fBrake_a0[ 0 ] * 0.5 ); + } + else { + // o 5 km/h to olej (zacznij luzować) + AccDesired = std::min( + AccDesired, // but don't override decceleration for VelNext + std::max( 0.0, AccPreferred ) ); + } + } + } + } + + // NOTE: as a stop-gap measure the routine is limited to trains only while car calculations seem off + if( is_train() && vel < VelDesired && + -AccDesired * BrakeAccFactor() < (false == Ready || VelNext > vel - 40.0 ? fBrake_a0[0] * 0.8 : -fAccThreshold) / (1.2 * braking_distance_multiplier(VelNext)) ) { + // don't adjust acceleration when going above current target speed + AccDesired = std::max(EU07_AI_NOACCELERATION, AccDesired); + } +} + +// hamowanie kontrolne +void +TController::adjust_desired_speed_for_braking_test() { + +// if( false == Global.DynamicBrakeTest ) { return; } + if( brakeTest.stage == RunningBrakeTest::Stage::done ) { return; } + if( ( brakeTest.stage == RunningBrakeTest::Stage::waiting ) + && ( false == timetable::makes_brake_test( TrainParams.run_flags() ) ) ) { return; } // the timetable says there's none (eu07/maszyna#95) + if( false == is_train() ) { return; } // not applicable + if( occupied->brakes.config.driverValveType == TBrakeHandle::FVel6 ) { return; } // leads to bugs in DecBrake, disable for now + if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } // not applicable + if( false == aiControlled ) { return; } // TBD: add notification about braking test and enable it for human driver as well? + + auto const vel { DirectionalVel() }; + // what the route ahead asks for; the test may brake harder than that, never softer + auto const routeaccdesired { AccDesired }; + auto const routeaccdesiredgravity { fAccDesiredGravity }; + auto const routeveldesired { VelDesired }; + + using enum RunningBrakeTest::Stage; + switch( brakeTest.stage ) { + case waiting: { + if( primary() + && vel < VelDesired + && fAccGravity >= 0.0 // not if going uphill + && AccDesired >= EU07_AI_ACCELERATION + && TrainParams.TTVmax >= 10.0 + && vel > std::min(TrainParams.TTVmax, 60.0) - 2.0 ) { + brakeTest.stage = applying; + brakeTest.brakingTime = ElapsedTime; + brakeTest.velocityBrake = vel; + } + break; + } + case applying: { + AccDesired = EU07_AI_BRAKINGTESTACCELERATION; + fAccDesiredGravity = 0.0; + VelDesired = brakeTest.velocityBrake; + if( ElapsedTime - brakeTest.brakingTime > 1 ) { + ForcePNBrake = true; + occupied->EpFuseSwitch( false ); + brakeTest.stage = switchingToAir; + } + break; + } + case switchingToAir: { + AccDesired = EU07_AI_BRAKINGTESTACCELERATION; + fAccDesiredGravity = 0.0; + VelDesired = brakeTest.velocityBrake; + if( ElapsedTime - brakeTest.brakingTime > 2 ) { + brakeTest.brakingTime = ElapsedTime; + brakeTest.velocityBrake = vel; + brakeTest.velocityRelease = vel - 8.0; + brakeTest.stage = measuring; + } + break; + } + case measuring: { + AccDesired = safe_clamp( -AbsAccS, fAccThreshold * 1.01, fAccThreshold * 1.21 ); + fAccDesiredGravity = 0.0; + VelDesired = brakeTest.velocityBrake; + if( vel <= brakeTest.velocityRelease ) { + brakeTest.stage = releasing; + brakeTest.brakingTime = ElapsedTime - brakeTest.brakingTime; + brakeTest.midPointAcc = AbsAccS; + brakeTest.releasingTime = ElapsedTime; + } + break; + } + case releasing: { + if( Ready ) { + if( BrakeSystem == TBrakeSystem::ElectroPneumatic ) { + occupied->EpFuseSwitch( true ); + } + ForcePNBrake = false; + brakeTest.stage = done; + brakeTest.releasingTime = ElapsedTime - brakeTest.releasingTime; + brakeTest.velocityFinish = vel; + } + break; + } + default: { + break; + } + } + // a stop or a restriction coming up while the test runs takes precedence + if( brakeTest.IsBraking() + && ( routeaccdesired < AccDesired ) ) { + AccDesired = routeaccdesired; + fAccDesiredGravity = routeaccdesiredgravity; + VelDesired = std::min( VelDesired, routeveldesired ); + } +} diff --git a/vehicle/ai/speedpos.cpp b/vehicle/ai/speedpos.cpp new file mode 100644 index 000000000..f783e4591 --- /dev/null +++ b/vehicle/ai/speedpos.cpp @@ -0,0 +1,329 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a position of the speed table: a track, a switch or an event ahead and the speed it asks for + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + + +TSpeedPos::TSpeedPos(TTrack *track, double dist, SpeedPointFlags flag) +{ + Set(track, dist, flag); +}; + +TSpeedPos::TSpeedPos(basic_event *event, double dist, double length, DriverOrders order) +{ + Set(event, dist, length, order); +}; + +void TSpeedPos::Clear() +{ + ResetFlags(); // brak flag to brak reakcji + fVelNext = -1.0; // prędkość bez ograniczeń + fSectionVelocityDist = 0.0; //brak długości + fPointDist = 0.0; + fDist = 0.0; + bSeenAhead = false; + vPos = glm::dvec3(0, 0, 0); + trTrack = nullptr; // brak wskaźnika +}; + +void TSpeedPos::CommandCheck() +{ // sprawdzenie typu komendy w evencie i określenie prędkości + TCommandType command = evEvent->input_command(); + double value1 = evEvent->input_value(1); + double value2 = evEvent->input_value(2); + // the point of a PointVelocity limit is taken anew from the current command + flags = flags.Without(SpeedPointFlag::pointSpeed); + fPointDist = 0.0; + switch (command) + { + case TCommandType::cm_ShuntVelocity: + // prędkość manewrową zapisać, najwyżej AI zignoruje przy analizie tabelki + fVelNext = value1; // powinno być value2, bo druga określa "za"? + flags |= SpeedPointFlag::shuntSignal; + break; + case TCommandType::cm_SetVelocity: + // w semaforze typu "m" jest ShuntVelocity dla Ms2 i SetVelocity dla S1 + // SetVelocity * 0 -> można jechać, ale stanąć przed + // SetVelocity 0 20 -> stanąć przed, potem można jechać 20 (SBL) + // SetVelocity -1 100 -> można jechać, przy następnym ograniczenie (SBL) + // SetVelocity 40 -1 -> PutValues: jechać 40 aż do minięcia (koniec ograniczenia( + fVelNext = value1; + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); + flags |= SpeedPointFlag::signal;// nie manewrowa, nie przystanek, nie zatrzymać na SBL, ale semafor + if (value1 == 0.0 && value2 != 0.0) // jeśli pierwsza zerowa + // a druga nie + { // S1 na SBL, można przejechać po zatrzymaniu (tu nie mamy prędkości ani odległości) + fVelNext = value2; // normalnie będzie zezwolenie na jazdę, aby się usunął z tabelki + flags |= SpeedPointFlag::stopOnAutomaticBlock; // flaga, że ma zatrzymać; na pewno nie zezwoli na manewry + } + break; + case TCommandType::cm_SectionVelocity: + // odcinek z ograniczeniem prędkości + fVelNext = value1; + fSectionVelocityDist = value2; + flags |= SpeedPointFlag::sectionSpeed; + break; + case TCommandType::cm_RoadVelocity: + // prędkość drogowa (od tej pory będzie jako domyślna najwyższa) + fVelNext = value1; + flags |= SpeedPointFlag::roadSpeed; + break; + case TCommandType::cm_PassengerStopPoint: + // nie ma dostępu do rozkładu + // przystanek, najwyżej AI zignoruje przy analizie tabelki + fVelNext = 0.0; + flags |= SpeedPointFlag::passengerStop; // niestety nie da się w tym miejscu współpracować z rozkładem +/* + // NOTE: not used for now as it might be unnecessary + // special case, potentially override any set speed limits if requested + // NOTE: we test it here because for the time being it's only used for passenger stops + if( flags.HasAll(spDontApplySpeedLimit) ) { + fVelNext = -1; + } +*/ + break; + case TCommandType::cm_SetProximityVelocity: + // musi zostać gdyż inaczej nie działają manewry + fVelNext = -1; + flags |= SpeedPointFlag::proximitySpeed; + // fSectionVelocityDist = value2; + break; + case TCommandType::cm_PointVelocity: + // PointVelocity v d: the head has to be at v (-1: no limit) at the point d metres beyond the cell, + // the limit ends when the head passes that point. the cell is read until the head passes the cell, + // what it says then holds for the point (the warning disc of a level crossing, Osp1/Osp2) + fVelNext = value1; + fPointDist = std::max( value2, 0.0 ); + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock | SpeedPointFlag::signal)); // not a signal, even if the cell was one before + flags |= SpeedPointFlag::pointSpeed; + break; + case TCommandType::cm_OutsideStation: + // w trybie manewrowym: skanować od niej wstecz i stanąć po wyjechaniu za sygnalizator i + // zmienić kierunek + // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) + fVelNext = -1; + flags |= SpeedPointFlag::outsideStation; // W5 + break; + case TCommandType::cm_EmergencyBrake: + fVelNext = -1; + break; + case TCommandType::cm_SecuritySystemMagnet: + fVelNext = -1; + break; + case TCommandType::cm_SignalAreaEnd: + // imposes no speed of its own, it only ends the reduced speed of the signal passed last + fVelNext = -1; + flags |= SpeedPointFlag::signalAreaEnd; + break; + default: + // inna komenda w evencie skanowanym powoduje zatrzymanie i wysłanie tej komendy + // nie manewrowa, nie przystanek, nie zatrzymać na SBL + // jak nieznana komenda w komórce sygnałowej, to zatrzymujemy + fVelNext = 0.0; +/* + fVelNext = ( + evEvent->is_command() ? 0.0 : // ask for a stop if we have a command for the vehicle + flags.HasAny(( spSemaphor | spShuntSemaphor )) ? fVelNext : // don't change semafor velocity + -1.0 ); // otherwise don't be a bother +*/ + // TODO: check whether clearing spShuntSemaphor flag doesn't cause problems + // potentially it can invalidate shunt semaphor used to transmit timetable or similar command + flags = flags.Without((SpeedPointFlag::shuntSignal | SpeedPointFlag::passengerStop | SpeedPointFlag::stopOnAutomaticBlock)); + } +}; + +bool TSpeedPos::Update() +{ + if( fDist < 0.0 ) { + // trzeba zazanaczyć, że minięty + flags |= SpeedPointFlag::elapsed; + } + bSeenAhead = signal_passing::seen_ahead_on_update( fDist, bSeenAhead ); + if (flags & SpeedPointFlag::track) { + // road/track + if (trTrack) { + // może być NULL, jeśli koniec toru (???) + fVelNext = trTrack->VelocityGet(); // aktualizacja prędkości (może być zmieniana eventem) + + if( trTrack->iCategoryFlag & 1 ) { + // railways + if( flags & SpeedPointFlag::switchTrack && (trTrack->GetSwitchState() & 1) != 0 != (flags.HasAny(SpeedPointFlag::switchState)) ) { + // jeśli odcinek zmienny + // czy stan się zmienił? + // Ra: zakładam, że są tylko 2 możliwe stany + flags ^= SpeedPointFlag::switchState; + if (false == flags.HasAny(SpeedPointFlag::elapsed)) + { + // jeszcze trzeba skanowanie wykonać od tego toru + // problem jest chyba, jeśli zwrotnica się przełoży zaraz po zjechaniu z niej + // na Mydelniczce potrafi skanować na wprost mimo pojechania na bok + return true; + } + } + } + else { + // roads and others + if( crossRoute != 0 && crossRoute != 1 ) { // as the top 4 bits read without the sign: -1 counts as turning + // jeśli skrzyżowanie, ograniczyć prędkość przy skręcaniu + // ±1 to jazda na wprost, ±2 nieby też, ale z przecięciem głównej drogi - chyba że jest równorzędne... + // TODO: uzależnić prędkość od promienia; + // albo niech będzie ograniczona w skrzyżowaniu (velocity z ujemną wartością) + fVelNext = 30.0; + } + } + } + } + else if (flags & SpeedPointFlag::event && (false == flags.HasAny(SpeedPointFlag::elapsed) || fVelNext == 0.0)) { + // jeśli event + // ignore already passed signals, but keep an eye on overrun stops + // (a PointVelocity cell is latched when the head passes it, except at 0, which has to be released by the cell) + // odczyt komórki pamięci najlepiej by było zrobić jako notyfikację, + // czyli zmiana komórki wywoła jakąś podaną funkcję + CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości + } + return false; +}; + +std::string TSpeedPos::GetName() const +{ + if( flags & SpeedPointFlag::track ) // jeśli tor + return trTrack->name(); + else if( flags & SpeedPointFlag::event ) // jeśli event + return + evEvent->m_name + + " [" + std::to_string( static_cast( evEvent->input_value( 1 ) ) ) + + ", " + std::to_string( static_cast( evEvent->input_value( 2 ) ) ) + + "]"; + else + return ""; +} + +std::string TSpeedPos::TableText() const +{ // pozycja tabelki pr?dko?ci + if (flags & SpeedPointFlag::enabled) + { // o ile pozycja istotna + return to_hex_str(LegacyFlagsValue(), 8) + " " + to_string(fDist, 1, 6) + + " " + (fVelNext == -1.0 ? " -" : to_string(static_cast(fVelNext), 0, 3)) + " " + GetName(); + } + return "Empty"; +} + +bool TSpeedPos::IsProperSemaphor(DriverOrders order) +{ // sprawdzenie czy semafor jest zgodny z trybem jazdy + if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt + { + if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal)) + return true; + else if (flags & SpeedPointFlag::outsideStation) + return true; + } + else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal) + { + return true; + } + return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej +} + +bool TSpeedPos::Set(basic_event *event, double dist, double length, DriverOrders order, bool const Standing) +{ // zapamiętanie zdarzenia + fDist = dist; + // an event already behind the head when found (under a train set across a signal) wasn't passed by it. a moving + // train may be just passing it, and the distance is found in steps of a metre, so for a moving train an event a + // little behind the head still counts as seen ahead. a standing train passes nothing: an event found behind its + // head counts only once an update finds it ahead + bSeenAhead = signal_passing::seen_ahead_when_found( dist, Standing ); + flags = SpeedPointFlag::event; + crossRoute = 0; + evEvent = event; + vPos = event->input_location(); // współrzędne eventu albo komórki pamięci (zrzutować na tor?) + // ignore events located behind the consist, but with exception of stop points which may be needed to update freshly received timetable + if( dist + length < 0 + && event->input_command() != TCommandType::cm_PassengerStopPoint ) { + return false; + } + flags |= SpeedPointFlag::enabled; + CommandCheck(); // sprawdzenie typu komendy w evencie i określenie prędkości + // zależnie od trybu sprawdzenie czy jest tutaj gdzieś semafor lub tarcza manewrowa + // jeśli wskazuje stop wtedy wystawiamy true jako koniec sprawdzania + // WriteLog("EventSet: Vel=" + AnsiString(fVelNext) + " flags=" + AnsiString(flags) + " order="+AnsiString(order)); + if (false == order.HasAny(trainOrders)) // Wait_for_orders, Prepare_engine, Change_direction, Connect, Disconnect, Shunt + { + if (flags & (SpeedPointFlag::signal | SpeedPointFlag::shuntSignal) && fVelNext == 0.0) + return true; + else if (flags & SpeedPointFlag::outsideStation) + return true; + } + else if (order & DriverOrder::obeyTrain && flags & SpeedPointFlag::signal && fVelNext == 0.0) + { + return true; + } + return false; // true gdy zatrzymanie, wtedy nie ma po co skanować dalej +}; + +void TSpeedPos::Set(TTrack *track, double dist, SpeedPointFlags flag) +{ // zapamiętanie zmiany prędkości w torze + fDist = dist; // odległość do początku toru + trTrack = track; // TODO: (t) może być NULL i nie odczytamy końca poprzedniego :/ + if (trTrack) + { + crossRoute = 0; + flags = flag | (trTrack->eType == tt_Normal ? SpeedPointFlag::track : SpeedPointFlag::track | SpeedPointFlag::switchTrack ); // zapamiętanie kierunku wraz z typem + if (flags & SpeedPointFlag::switchTrack && trTrack->GetSwitchState() & 1) + flags |= SpeedPointFlag::switchState; + fVelNext = trTrack->VelocityGet(); + if (trTrack->iDamageFlag & 128) + fVelNext = 0.0; // jeśli uszkodzony, to też stój + if (flags & SpeedPointFlag::trackEnd) + fVelNext = trTrack->iCategoryFlag & 1 ? + 0.0 : + 20.0; // jeśli koniec, to pociąg stój, a samochód zwolnij + vPos = + flags & SpeedPointFlag::reverse ? + trTrack->CurrentSegment()->FastGetPoint_1() : + trTrack->CurrentSegment()->FastGetPoint_0(); + } +}; diff --git a/vehicle/ai/speedtable.cpp b/vehicle/ai/speedtable.cpp new file mode 100644 index 000000000..97a0bd2d3 --- /dev/null +++ b/vehicle/ai/speedtable.cpp @@ -0,0 +1,1362 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the speed table: what each position of it asks of the driver, the stop points, the speed limits and the signals + +#include "stdafx.h" +#include "vehicle/Driver.h" +#include "physics/vehicle.h" +#include "utilities/Globals.h" +#include "utilities/translation.h" +#include "utilities/Logs.h" +#include "utilities/physicslog.h" +#include "vehicle/Train.h" +#include "vehicle/brakereleaser.h" +#include "vehicle/brakesetting.h" +#include "vehicle/brakingcurve.h" +#include "vehicle/fieldshunting.h" +#include "vehicle/handover.h" +#include "vehicle/signalpassing.h" +#include "vehicle/timetableservice.h" +#include "world/mtable.h" +#include "world/stationnames.h" +#include "vehicle/DynObj.h" +#include "world/Event.h" +#include "world/MemCell.h" +#include "world/RoadOrder.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "simulation/simulationtime.h" +#include "simulation/simulationtest.h" +#include "world/Track.h" +#include "world/station.h" +#include "input/keyboardinput.h" +#include +#include +#include +#include "vehicle/ai/internal.h" + +bool WriteTrainLogFlag = false; +namespace +{ + +void clear_signal_area_end( TSpeedPos &Point ) +{ + if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { + Point.Clear(); + } +} + +} // namespace + +auto const passengerstopmaxdistance { 400.0 }; // maximum allowed distance between passenger stop point and consist head + +TCommandType TController::TableUpdate(double &fVelDes, double &fDist, double &fNext, double &fAcc) +{ // ustalenie parametrów, zwraca typ komendy, jeśli sygnał podaje prędkość do jazdy + // fVelDes - prędkość zadana + // fDist - dystans w jakim należy rozważyć ruch + // fNext - prędkość na końcu tego dystansu + // fAcc - zalecane przyspieszenie w chwili obecnej - kryterium wyboru dystansu + auto a { 0.0 }; // przyspieszenie + auto v { 0.0 }; // prędkość + auto d { 0.0 }; // droga + auto d_to_next_sem { 10000.0 }; //ustaiwamy na pewno dalej niż widzi AI + auto go { TCommandType::cm_Unknown }; + auto speedlimitiscontinuous { true }; // stays true if potential active speed limit is unbroken to the last (relevant) point in scan table + eSignNext = nullptr; + IsAtPassengerStop = false; + bStopTargetIsPassengerStop = false; + IsScheduledPassengerStopVisible = false; + occupied->SecuritySystem.set_cabsignal_lock(false); + // te flagi są ustawiane tutaj, w razie potrzeby + drivingFlags.trackEnd = false; + drivingFlags.switchFound = false; + drivingFlags.signalFound = false; + drivingFlags.stopPointFound = false; + SignalAreaEndDist = -1.0; + update_point_limits(); + + for( std::size_t idx = 0; idx < sSpeedTable.size(); ++idx ) { + // o ile dana pozycja tabelki jest istotna + if( false == sSpeedTable[ idx ].flags.HasAny(SpeedPointFlag::enabled) ) { continue; } + + auto &point { sSpeedTable[ idx ] }; + + if( point.flags.HasAll(SpeedPointFlag::passengerStop) ) { + if( TableUpdateStopPoint( go, point, d_to_next_sem ) ) { continue; }; + } + v = point.fVelNext; // odczyt prędkości do zmiennej pomocniczej + if( point.flags.HasAll(SpeedPointFlag::switchTrack) ) { + // zwrotnice są usuwane z tabelki dopiero po zjechaniu z nich + drivingFlags.switchFound = true; // rozjazd z przodu/pod ogranicza np. sens skanowania wstecz + SwitchClearDist = point.fDist + point.trTrack->Length() + fLength; + } + else if ( point.flags.HasAll(SpeedPointFlag::event) && TableUpdateEvent(v, go, point, d_to_next_sem, idx) ) // W4 może się deaktywować + { // jeżeli event, może być potrzeba wysłania komendy, aby ruszył + continue; + } + + auto const railwaytrackend { true == point.flags.HasAll(SpeedPointFlag::trackEnd) && is_train() }; + if( v >= 0.0 // pozycje z prędkością -1 można spokojnie pomijać + || railwaytrackend ) { + + // a PointVelocity limit lies fPointDist beyond its entry and stays ahead of us until the head passes it + auto const ispointlimit { point.flags.HasAll(SpeedPointFlag::pointSpeed) }; + d = point.fDist + point.fPointDist; + + if( v >= 0.0 ) { + // points located in front of us can potentially affect our acceleration and target speed + if( d > 0.0 + && ( false == point.flags.HasAll(SpeedPointFlag::elapsed) || ispointlimit ) ) { + // sygnał lub ograniczenie z przodu (+32=przejechane) + // 2014-02: jeśli stoi, a ma do przejechania kawałek, to niech jedzie + if( occupied->Vel < 0.01 + && true == point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::passengerStop) + && false == IsAtPassengerStop ) { + // ma podjechać bliżej - czy na pewno w tym miejscu taki warunek? + a = d > passengerstopmaxdistance || drivingFlags.stopCloser ? fAcc : 0.0; + } + else { + // przyspieszenie: ujemne, gdy trzeba hamować + if( v >= 0.0 ) { + a = ( v * v - occupied->Vel * occupied->Vel ) / ( 25.92 * d ); + if( occupied->Vel < v + || v == 0.0 ) { + // if we're going slower than the target velocity and there's enough room for safe stop, speed up + auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; + if( brakingdistance > 0.0 ) { + // maintain desired acc while we have enough room to brake safely, when close enough start paying attention + // try to make a smooth transition instead of sharp change + a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); + } + } + if( d < ( ispointlimit && v > 0.0 ? point_limit_approach() : fMinProximityDist ) + && v < fVelDes ) { + // jak jest już blisko, ograniczenie aktualnej prędkości + fVelDes = v; + } + } + } + } + // points located behind can affect our current speed, but little else + else if ( point.flags & SpeedPointFlag::track) // jeśli tor + { // tor ogranicza prędkość, dopóki cały skład nie przejedzie, + if( v >= 1.0 && d + point.trTrack->Length() < -fLength && false == railwaytrackend ) { // EU06 się zawieszało po dojechaniu na koniec toru postojowego + // zapętlenie, jeśli już wyjechał za ten odcinek + continue; + } + if( v < fVelDes ) { + // ograniczenie aktualnej prędkości aż do wyjechania za ograniczenie + fVelDes = v; + } + if( v < VelLimitLastDist.first ) { + VelLimitLastDist.second = d + point.trTrack->Length() + fLength; + } + else if( VelLimitLastDist.second > 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop)) ) { // the speed limit can potentially start afterwards, so don't mark it as broken too soon + speedlimitiscontinuous = false; + } + if( false == railwaytrackend ) { + continue; // i tyle wystarczy + } + } + else { + // event trzyma tylko jeśli VelNext=0, nawet po przejechaniu (nie powinno dotyczyć samochodów?) + a = v > 0.0 ? + fAcc : + occupied->Vel < 0.01 ? + 0.0 : // already standing still so no need to bother with brakes + -2.0; // ruszanie albo hamowanie + } + } + // track can potentially end, which creates another virtual point of interest with speed limit of 0 at the end of it + // TBD, TODO: when tracing the route create a dedicated table entry for it, to simplify the code? + if( railwaytrackend ) { + // if the railway track ends here set the velnext accordingly as well + // TODO: test this with turntables and such + auto const stopatendacceleration = -1.0 * occupied->Vel * occupied->Vel / ( 25.92 * ( d + point.trTrack->Length() ) ); + if( stopatendacceleration < a ) { + a = stopatendacceleration; + v = 0.0; + d += point.trTrack->Length(); + if( d < fMinProximityDist ) { + // jak jest już blisko, ograniczenie aktualnej prędkości + fVelDes = v; + } + } + } + + if( a <= fAcc + && ( v < fNext || fNext < 0 ) ) { // filter out consecutive, farther out blocks with the same speed limit; they'd make us accelerate slower due to their lower a value + // mniejsze przyspieszenie to mniejsza możliwość rozpędzenia się albo konieczność hamowania + // jeśli droga wolna, to może być a>1.0 i się tu nie załapuje + fAcc = a; // zalecane przyspieszenie (nie musi być uwzględniane przez AI) + fNext = v; // istotna jest prędkość na końcu tego odcinka + fDist = d; // dlugość odcinka + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); + } +/* + else if ((fAcc > 0) && (v >= 0) && (v > fNext)) { + // jeśli nie ma wskazań do hamowania, można podać drogę i prędkość na jej końcu + fNext = v; // istotna jest prędkość na końcu tego odcinka + fDist = d; // dlugość odcinka (kolejne pozycje mogą wydłużać drogę, jeśli prędkość jest stała) + } +*/ + // we'll pick first scanned target speed as our goal + // farther scan table points can override it through previous clause, if they require lower acceleration or speed reduction + else if( a > 0 && a <= fAcc && v >= 0 && fNext < 0 ) { + fAcc = a; + fNext = v; + fDist = d; + bStopTargetIsPassengerStop = ( v == 0.0 ) && ( point.flags.HasAny(SpeedPointFlag::passengerStop) ); + } + // potentially update our current speed limit + // a point limit binds only the head at its point, it neither extends nor breaks a limit over a stretch of the line + if( false == ispointlimit + && v < VelLimitLastDist.first + && ( d < 0 // the point counts as part of last speed limit either if it's behind us + || VelLimitLastDist.second > 0 ) ) { // or if we already have the last limit ongoing + VelLimitLastDist.second = d + fLength; + if( point.flags.HasAny(SpeedPointFlag::track) ) { + VelLimitLastDist.second += point.trTrack->Length(); + } + } + else if( false == point.flags.HasAny(( SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed )) ) { + // if we found a point which isn't part of the current speed limit mark the limit as broken + // NOTE: we exclude switches from this rule, as speed limits generally extend through these + speedlimitiscontinuous = false; + } + } // if (v>=0.0) + // finding a point which doesn't impose speed limit means any potential active speed limit can't extend through entire scan table + // NOTE: we test actual speed value for the given point, as events may receive (v = -1) as a way to disable them in irrelevant modes + if( point.fVelNext < 0 && false == point.flags.HasAny((SpeedPointFlag::switchTrack | SpeedPointFlag::passengerStop | SpeedPointFlag::pointSpeed)) ) { + // NOTE: we exclude switches from this rule, as speed limits generally extend through these + // and point limits, which say nothing of the line they lie on + speedlimitiscontinuous = false; + } + if (fNext >= 0.0) + { // jeśli ograniczenie + if( (point.flags & (SpeedPointFlag::enabled | SpeedPointFlag::event)) == (SpeedPointFlag::enabled | SpeedPointFlag::event) && false == point.flags.HasAny(SpeedPointFlag::pointSpeed) && eSignNext == nullptr ) { // tylko sygnał przypisujemy (a point limit isn't one) + // jeśli jeszcze nic nie zapisane tam + eSignNext = point.evEvent; // dla informacji + } + if( fNext == 0.0 ) { + break; // nie ma sensu analizować tabelki dalej + } + } + } + + // the point limits latched before, which aren't in the table any more + apply_point_limits( fVelDes, fDist, fNext, fAcc ); + + // jeśli mieliśmy ograniczenie z semafora i nie ma przed nami + if( VelSignalLast >= 0.0 + && ( false == drivingFlags.signalFound && false == drivingFlags.switchFound && false == drivingFlags.stopPointFound ) + && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + VelSignalLast = -1.0; + } + // if there's unbroken speed limit through our scan table take a note of it + if( VelLimitLastDist.second > 0 + && speedlimitiscontinuous ) { + VelLimitLastDist.second = EU07_AI_SPEEDLIMITEXTENDSBEYONDSCANRANGE; + } + // take into account the effect switches have on duration of signal-imposed speed limit, in calculation of speed limit end point + // a reduced speed ends where the interlocking area does, if that is marked, and not past the switches farther on + if( auto const signallimitend { VelSignalLast > 0.0 && SignalAreaEndDist >= 0.0 ? SignalAreaEndDist : SwitchClearDist }; + VelSignalLast >= 0.0 && signallimitend >= 0.0 ) { + VelLimitLastDist.second = std::max( VelLimitLastDist.second, signallimitend ); + } + + //analiza spisanych z tabelki ograniczeń i nadpisanie aktualnego + // if stopped at a valid passenger stop, hold there + if( true == IsAtPassengerStop && occupied->Vel < 0.01 ) { + fVelDes = 0.0; + } + else { + fVelDes = min_speed( fVelDes, VelSignalLast ); + fVelDes = min_speed( fVelDes, VelLimitLast ); + fVelDes = min_speed( fVelDes, VelRoad ); + fVelDes = min_speed( fVelDes, VelRestricted ); + } + // nastepnego semafora albo zwrotnicy to uznajemy, że mijamy W5 + FirstSemaphorDist = d_to_next_sem; // przepisanie znalezionej wartosci do zmiennej + return go; +}; + +bool +TController::TableUpdateStopPoint( TCommandType &Command, TSpeedPos &Point, double const Signaldistance ) { + // stop points are irrelevant when not in one of the basic modes + if( false == OrderCurrentGet().HasAny( DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank ) ) { return true; } + // jeśli przystanek, trzeba obsłużyć wg rozkładu + drivingFlags.stopPointFound = true; + // the W4 and the timetable name the station each in its own file, so the two spellings are compared by their key: + // with or without the polish letters, in any case, with spaces or underscores + if( false == timetable::stop_point_is_for( Point.evEvent->input_text(), asNextStop ) ) + { // jeśli nazwa nie jest zgodna + if( false == IsScheduledPassengerStopVisible // check if our next scheduled stop didn't show up earlier in the scan + && Point.fDist < 1.15 * fBrakeDist + 300 + && Point.fDist > 0 ) // tylko jeśli W4 jest blisko, przy dwóch może zaczać szaleć + { + // porównuje do następnej stacji, więc trzeba przewinąć do poprzedniej + // nastepnie ustawić następną na aktualną tak żeby prawidłowo ją obsłużył w następnym kroku + if( true == TrainParams.RewindTimeTable( Point.evEvent->input_text() ) ) { + asNextStop = TrainParams.NextStop(); + TrainParams.StationStart = TrainParams.StationIndex; + } + } + else if( Point.fDist < -fLength ) { + // jeśli został przejechany + Point.ResetFlags(); // to można usunąć (nie mogą być usuwane w skanowaniu) + } + return true; // ignorowanie jakby nie było tej pozycji + } + else if (drivingFlags.stopPoint) // jeśli pomijanie W4, to nie sprawdza czasu odjazdu + { // tylko gdy nazwa zatrzymania się zgadza + if( OrderCurrentGet().HasAny( DriverOrder::obeyTrain | DriverOrder::bank ) ) { + // check whether the station specifies radio channel change + // NOTE: we don't do it in shunt mode, as shunting operations tend to use dedicated radio channel + // NOTE: there's a risk radio channel change was specified by a station which we skipped during timetable rewind + // we ignore this for the time being as it's not a high priority error + auto const radiochannel { TrainParams.radio_channel() }; + if( radiochannel > 0 ) { + if( iGuardRadio != 0 ) { + iGuardRadio = radiochannel; + } + if( iRadioChannel != radiochannel ) { + cue_action( driver_hint::radiochannel, radiochannel ); + } + } + } + IsScheduledPassengerStopVisible = true; // block potential timetable rewind if the next stop shows up later in the scan + if (false == TrainParams.IsStop()) + { // jeśli nie ma tu postoju + Point.fVelNext = -1; // maksymalna prędkość w tym miejscu + // przy 160km/h jedzie 44m/s, to da dokładność rzędu 5 sekund + if (Point.fDist < passengerstopmaxdistance * 0.5 ) { + // zaliczamy posterunek w pewnej odległości przed (choć W4 nie zasłania już semafora) +#if LOGSTOPS + WriteLog(std::format( + "{} as {}: at {}:{} passed {}", + pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja +#endif + // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój + fLastStopExpDist = occupied->DistCounter() + 0.250 + 0.001 * fLength; + TrainParams.UpdateMTable( simulation::Time, asNextStop ); + record_station( Point, blackbox::station_kinds::passed ); + UpdateDelayFlag(); + TrainParams.StationIndexInc(); // przejście do następnej + asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania + Point.ResetFlags(); // nie liczy się już + return true; // table entry recognized and handled + } + } // koniec obsługi przelotu na W4 + else { + // zatrzymanie na W4 + // the margins of a passenger stop, whether the train is already making for it or not: the present ones + // depend on this very flag, and a check against them would turn it on and off every other scan + auto const [ stopminproximity, stopmaxproximity ] { + is_train() ? + train_proximity_margins( true ) : + std::pair{ fMinProximityDist, fMaxProximityDist } }; + if ( false == Point.bMoved ) { + // potentially shift the stop point in accordance with its defined parameters + /* + // https://rainsted.com/pl/Wersja/18.2.133#Okr.C4.99gi_dla_W4_i_W32 + Pierwszy parametr ujemny - preferowane zatrzymanie czoła składu (np. przed przejściem). + Pierwszy parametr dodatni - preferowane zatrzymanie środka składu (np. przy wiacie, przejściu podziemnym). + Drugi parametr ujemny - wskazanie zatrzymania dla krótszych składów (W32). + Drugi paramer dodatni - długość peronu (W4). + */ + auto L = 0.0; + auto Par1 = Point.evEvent->input_value(1); + auto Par2 = Point.evEvent->input_value(2); + if (Par2 >= 0 || fLength < -Par2) { //użyj tego W4 + if (Par1 < 0) { + L = -Par1; + } + else { + //środek + L = Par1 - stopminproximity - fLength * 0.5; + } + // the train comes to a stand anywhere up to the margin of a passenger stop short of this point, not + // that of the signals it may be making for when it first sees the W4, so the tail is to keep that far + // inside the platform + L = std::max(0.0, std::min(L, std::abs(Par2) - stopminproximity - fLength)); + Point.UpdateDistance(L); + Point.bMoved = true; + Point.fMoved = L; + } + else { + Point.ResetFlags(); + } + } + // for human-driven vehicles discard the stop point if they leave it far enough behind + if( false == aiControlled + && Point.fDist < -1 * std::max(fLength + 100, 250.0) - Point.fMoved ) { + record_station( Point, blackbox::station_kinds::missed ); + Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.fVelNext = -1; // można jechać za W4 + if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { + // sanity check, if we're held by this stop point, let us go + VelSignalLast = -1; + } + return true; + } + + IsAtPassengerStop = Point.fDist <= passengerstopmaxdistance + // Ra 2F1I: odległość plus długość pociągu musi być mniejsza od długości + // peronu, chyba że pociąg jest dłuższy, to wtedy minimalna. + // jeśli długość peronu ((sSpeedTable[i].evEvent->ValueGet(2)) nie podana, + // przyjąć odległość fMinProximityDist + && (drivingFlags.stopCloser ? + Point.fDist + fLength + (Point.fMoved - stopminproximity * 0.5f) <= std::max(std::abs(Point.evEvent->input_value(2)), + 2.0 * stopmaxproximity + fLength) : + Point.fDist < Signaldistance); + + if( !eSignNext ) { + //jeśli nie widzi następnego sygnału ustawia dotychczasową + eSignNext = Point.evEvent; + } + if( occupied->Vel > EU07_AI_MOVEMENT ) { + // jeśli jedzie (nie trzeba czekać, aż się drgania wytłumią - drzwi zamykane od 1.0) to będzie zatrzymanie + Point.fVelNext = 0; + // potentially announce pending stop + if( m_lastannouncement != announcement_t::approaching + && Point.fDist < 750 + && Point.fDist > 250 ) { + announce( announcement_t::approaching ); + } + } else if( true == IsAtPassengerStop ) { + // jeśli się zatrzymał przy W4, albo stał w momencie zobaczenia W4 + if( !aiControlled ) { + // w razie przełączenia na AI ma nie podciągać do W4, gdy użytkownik zatrzymał za daleko + drivingFlags.stopCloser = false; + } + if (TrainParams.UpdateMTable( simulation::Time, asNextStop) ) { + // to się wykona tylko raz po zatrzymaniu na W4 + record_station( Point, blackbox::station_kinds::stopped ); + // the service flags of this stop hold for its doors and departure + m_stopflags = TrainParams.stop_flags(); + if( TrainParams.StationIndex < TrainParams.StationCount ) { + // jeśli są dalsze stacje, bez trąbienia przed odjazdem + // also ignore any horn cue that may be potentially set below 1 km/h and before the actual full stop + drivingFlags.startHorn = false; + drivingFlags.startHornNow = false; + } + UpdateDelayFlag(); + + // perform loading/unloading + // HACK: manual check if we didn't already do load exchange at this stop + // TODO: remove the check once the station system is in place + if( m_lastexchangestop != asNextStop ) { + m_lastexchangestop = asNextStop; + m_lastexchangedirection = pVehicle->DirectionGet(); + m_lastexchangeplatforms = static_cast( std::floor( std::abs( Point.evEvent->input_value( 2 ) ) ) ) % 10; + auto const exchangetime { simulation::Station.update_load( pVehicles[ VehicleEnd::front ], TrainParams, m_lastexchangeplatforms ) }; + WaitingSet( exchangetime ); + // announce the stop name while at it + announce( announcement_t::current ); + m_makenextstopannouncement = true; + } + + if (TrainParams.DirectionChange()) { + // jeśli "@" w rozkładzie, to wykonanie dalszych komend + // wykonanie kolejnej komendy, nie dotyczy ostatniej stacji + if (drivingFlags.pushPull) { + // SN61 ma się też nie ruszać, chyba że ma wagony + drivingFlags.stopHere = true; // EZT ma stać przy peronie + if (OrderNextGet() != DriverOrder::changeDirection) { + OrderPush(DriverOrder::changeDirection); // zmiana kierunku + OrderPush( + TrainParams.StationIndex < TrainParams.StationCount ? + DriverOrder::obeyTrain : + DriverOrder::shunt); // to dalej wg rozkładu + } + } + else { + // a dla lokomotyw... + // pozwolenie na przejechanie za W4 przed czasem i nie ma stać + drivingFlags.stopPoint = false; + drivingFlags.stopHere = false; + } + // przejście do kolejnego rozkazu (zmiana kierunku, odczepianie) + JumpToNextOrder(); + // ma nie podjeżdżać pod W4 po przeciwnej stronie + drivingFlags.stopCloser = false; + // ten W4 nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.ResetFlags(); + // jechać + Point.fVelNext = -1; + // nie analizować prędkości + return true; + } + } + + if (OrderCurrentGet() & ( DriverOrder::shunt | DriverOrder::looseShunt )) { + OrderNext(DriverOrder::obeyTrain); // uruchomić jazdę pociągową + CheckVehicles(); // zmienić światła + } + + if (TrainParams.StationIndex < TrainParams.StationCount) { + // jeśli są dalsze stacje, czekamy do godziny odjazdu + if ( true == IsCargoTrain + || true == TrainParams.IsMaintenance() + || TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond * 0.0167) ) { + // z dalszą akcją czekamy do godziny odjazdu + // cargo trains and passenger trains at maintenance stop don't need to wait + IsAtPassengerStop = false; + record_station( Point, blackbox::station_kinds::ready ); + // przy jakim dystansie (stanie licznika) ma przesunąć na następny postój + fLastStopExpDist = occupied->DistCounter() + 0.050 + 0.001 * fLength; + TrainParams.StationIndexInc(); // przejście do następnej + asNextStop = TrainParams.NextStop(); // pobranie kolejnego miejsca zatrzymania +#if LOGSTOPS + WriteLog(std::format( + "{} as {}: at {}:{} next {}", + pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute, asNextStop)); // informacja +#endif + // update consist weight, brake settings and ai braking tables + // NOTE: this calculation is expected to run after completing loading/unloading + CheckVehicles(); // nastawianie hamulca do jazdy pociągowej + + if( static_cast( std::floor( std::abs( Point.evEvent->input_value( 1 ) ) ) ) % 2 ) { + // nie podjeżdżać do semafora, jeśli droga nie jest wolna + drivingFlags.stopHere = true; + } + else { + //po czasie jedź dalej + drivingFlags.stopHere = false; + } + drivingFlags.stopCloser = true; // do następnego W4 podjechać blisko (z dociąganiem) + Point.ResetFlags(); // nie liczy się już zupełnie (nie wyśle SetVelocity) + Point.fVelNext = -1; // można jechać za W4 + if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { + // sanity check, if we're held by this stop point, let us go + VelSignalLast = -1; + } + if( Command == TCommandType::cm_Unknown ) { // jeśli nie było komendy wcześniej + Command = TCommandType::cm_Ready; // gotów do odjazdu z W4 (semafor może zatrzymać) + } + if( false == tsGuardSignal.empty() + && true == timetable::has_conductor( m_stopflags ) ) { + // jeśli mamy głos kierownika, to odegrać + drivingFlags.guardSignal = true; + } + return true; // nie analizować prędkości + } // koniec startu z zatrzymania + else { + cue_action(driver_hint::waitdeparturetime); + if (timetable::has_conductor(m_stopflags) // no conductor, no door kept open for him + && TrainParams.IsTimeToGo(simulation::Time.data().wHour, simulation::Time.data().wMinute + simulation::Time.data().wSecond*0.0167 + 0.1)) { //if is less than 6 sec to departure + drivingFlags.guardOpenDoor = true; + GuardOpenDoor(); + } + } + } // koniec obsługi początkowych stacji + else { + // jeśli dojechaliśmy do końca rozkładu +#if LOGSTOPS + WriteLog(std::format( + "{} as {}: at {}:{} end of route.", + pVehicle->asName, TrainParams.TrainName, simulation::Time.data().wHour, simulation::Time.data().wMinute)); // informacja +#endif + asNextStop = TrainParams.NextStop(); // informacja o końcu trasy + TrainParams.NewName("none"); // czyszczenie nieaktualnego rozkładu + // koniec kursu, gasimy wyświetlacze relacji (tablice blaszane zostają) + for( auto *vehicle { pVehicles[ VehicleEnd::front ] }; vehicle != nullptr; vehicle = vehicle->Next() ) { + vehicle->DestinationClear(); + } + // ma nie podjeżdżać pod W4 i ma je pomijać + drivingFlags.stopCloser = false; + if( false == drivingFlags.pushPull ) { + // if the consist can change direction through a simple cab change it doesn't need fiddling with recognition of passenger stops + drivingFlags.stopPoint = false; + } + fLastStopExpDist = -1.0f; // nie ma rozkładu, nie ma usuwania stacji + Point.ResetFlags(); // W4 nie liczy się już (nie wyśle SetVelocity) + Point.fVelNext = -1; // można jechać za W4 + if( Point.fDist <= 0.0 && eSignNext == Point.evEvent ) { + // sanity check, if we're held by this stop point, let us go + VelSignalLast = -1; + } + // wykonanie kolejnego rozkazu (Change_direction albo Shunt) + JumpToNextOrder(); + // ma się nie ruszać aż do momentu podania sygnału + drivingFlags.stopHere = true; + drivingFlags.startHorn = true; + return true; // nie analizować prędkości + } // koniec obsługi ostatniej stacji + } // vel 0, at passenger stop + else { + // HACK: momentarily deactivate W4 to trick the controller into moving closer + Point.fVelNext = -1; + } // vel 0, outside of passenger stop + } // koniec obsługi zatrzymania na W4 + } // koniec warunku pomijania W4 podczas zmiany czoła + else + { // skoro pomijanie, to jechać i ignorować W4 + Point.ResetFlags(); // W4 nie liczy się już (nie zatrzymuje jazdy) + Point.fVelNext = -1; + return true; // nie analizować prędkości + } + + return false; // +} + +// a road speed sign (W27/W27a) passed by the head stays in the table until the rear is past it too. not for cars: their +// passed events leave the table at the latest when the rear passes them (TableCheck), before the table update sees that +bool +TController::is_road_velocity_held( TSpeedPos const &Point ) const { + + return Point.flags.HasAll(SpeedPointFlag::roadSpeed) + && occupied->CategoryFlag != 2 + && Point.fDist >= -fLength; +} + +// a passed event is handled once and then dropped from the table, except a road speed sign held for the rear +void +TController::TableDropPassedEvent( TSpeedPos &Point ) const { + + if( is_road_velocity_held( Point ) ) { + Point.flags |= SpeedPointFlag::roadSpeedHeld; + return; + } + Point.Clear(); +} + +// the lowest road speed of the signs past the given one that the head has passed: held until the rear is past them too, +// or passed in this very tick and not marked as held yet; -1 if there's none +double +TController::held_road_velocity_beyond( TSpeedPos const &Point ) const { + + auto lowest { -1.0 }; + for( auto const &held : sSpeedTable ) { + if( ( held.flags & ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) ) != ( SpeedPointFlag::enabled | SpeedPointFlag::roadSpeed ) + || held.fDist >= 0.0 + || held.fDist <= Point.fDist ) { + continue; + } + lowest = min_speed( lowest, held.fVelNext ); + } + return lowest; +} + +// a road speed (W27/W27a) lower than the one in force holds once the head passes the sign, a higher one only once the +// whole train is past it (a car takes it from the head). the first pass after the head handles the sign as before, the +// entry is then only held for the rear: returns true for it, so the rest of the table update leaves it out +bool +TController::TableUpdateRoadVelocity( TSpeedPos &Point ) { + + if( Point.fDist >= 0.0 ) { return false; } + + if( occupied->CategoryFlag == 2 ) { + VelRoad = Point.fVelNext; + return false; + } + + auto const isrearpast { Point.fDist < -fLength }; + if( isrearpast ) { + // the rear past it, but not past a sign after it the head has passed too: none of those may be exceeded, so a + // lower one (W27a 60 within a train's length after a 120) stays in force + VelRoad = min_speed( Point.fVelNext, held_road_velocity_beyond( Point ) ); + } + else if( Point.fVelNext == min_speed( Point.fVelNext, VelRoad ) ) { + VelRoad = Point.fVelNext; + } + if( false == Point.flags.HasAll(SpeedPointFlag::roadSpeedHeld) ) { + return false; + } + if( isrearpast ) { + Point.Clear(); + } + return true; +} + +// a reduced speed shown by a signal holds to the end of the interlocking area the signal guards (Ie-1), and that end is +// marked on the main track with a SignalAreaEnd event. on a track without the marker the speed holds as it did before: +// until the next signal, or until no signal, switch or stop point is left in the scan +void +TController::TableUpdateSignalAreaEnd( TSpeedPos &Point ) { + + // the switches lie in front of the marker, so the whole train has left them once its rear end is past it + if( Point.fDist >= -fLength ) { + if( SignalAreaEndDist < 0.0 + && OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // the table is sorted by distance, so the first marker is the nearest one + SignalAreaEndDist = Point.fDist + fLength; + } + return; + } + + // in shunting the marker stays, a train order given before the next signal still finds it + if( false == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { return; } + + // a passed signal at stop (0) keeps holding the train, only a reduced speed ends here + if( VelSignalLast > 0.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", left the interlocking area at " + Point.evEvent->m_name ); + } + VelSignalLast = -1.0; + } + Point.Clear(); +} + +bool TController::point_limit_latched( basic_event const *Cell ) const { + + return std::any_of( + m_pointlimits.begin(), m_pointlimits.end(), + [&]( point_limit const &Limit ) { return Limit.source == Cell; } ); +} + +double TController::point_limit_end( glm::dvec3 const &Heading ) const { + + auto const origin { pVehicle->GetPosition() }; + auto result { 0.0 }; + auto first { true }; + for( auto const *vehicle : { pVehicles[ VehicleEnd::front ], pVehicles[ VehicleEnd::rear ] } ) { + if( vehicle == nullptr ) { continue; } + for (auto const side : VehicleEnds) { + auto const along { glm::dot( vehicle->CouplerPosition( side ) - origin, Heading ) }; + result = ( first ? along : std::max( result, along ) ); + first = false; + } + } + return result; +} + +void TController::latch_point_limit( TSpeedPos const &Point ) { + + if( point_limit_latched( Point.evEvent ) ) { return; } + m_pointlimits.push_back( + point_limit { Point.evEvent, Point.fVelNext, Point.fDist + Point.fPointDist, Point.fPointDist, travel_direction() } ); + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", latched point limit of " + Point.evEvent->m_name + + ": " + to_string( Point.fVelNext, 0 ) + " in " + to_string( m_pointlimits.back().distance, 0 ) + " m" ); + } +} + +void TController::update_point_limits() { + + if( pVehicle == nullptr ) { return; } + auto const position { pVehicle->GetPosition() }; + if( m_pointlimitsvehicle == pVehicle ) { + auto const movement { position - m_pointlimitsposition }; + auto const length { glm::length( movement ) }; + if( length >= 200.0 ) { + // a longer jump between two updates isn't driving: the consist was moved elsewhere + m_pointlimits.clear(); + } + else if( length > 0.0 ) { + auto const step { movement / length }; + for( auto &limit : m_pointlimits ) { + if( glm::length( limit.heading ) < 0.5 ) { + // the way wasn't known when the limit was latched, the head was passing the cell + limit.heading = step; + } + auto const along { glm::dot( step, limit.heading ) }; + limit.distance += ( along >= 0.0 ? -length : length ); + // the way towards the point follows the line, step by step; a step far off it + // (a jolt of a standing vehicle) doesn't turn it + if( std::abs( along ) > 0.5 ) { + limit.heading = ( along >= 0.0 ? step : -step ); + } + } + } + } + // a change of the vehicle (another cab) starts the measure from its place + auto const vehiclechanged { m_pointlimitsvehicle != pVehicle }; + auto const previousposition { m_pointlimitsposition }; + m_pointlimitsvehicle = pVehicle; + m_pointlimitsposition = position; + // the consist, as its end vehicles and its length + auto const *front { pVehicles[ VehicleEnd::front ] }; + auto const *rear { pVehicles[ VehicleEnd::rear ] }; + auto const consistchanged { + false == ( ( front == m_pointlimitsends[ 0 ] && rear == m_pointlimitsends[ 1 ] ) + || ( front == m_pointlimitsends[ 1 ] && rear == m_pointlimitsends[ 0 ] ) ) + || std::abs( fLength - m_pointlimitslength ) > 0.5 }; + m_pointlimitsends[ 0 ] = front; + m_pointlimitsends[ 1 ] = rear; + m_pointlimitslength = fLength; + // vehicles coupled or uncoupled at the end towards the point move the head towards it or away. only a change of + // the consist counts, as the end measured from the vehicle shifts on curves. another vehicle measured from (a cab + // change, which may come with a coupling in the same order) moves the end measured before to its place + for( auto &limit : m_pointlimits ) { + if( glm::length( limit.heading ) < 0.5 ) { continue; } + auto const consistend { point_limit_end( limit.heading ) }; + if( limit.endknown && consistchanged ) { + auto const previousend { + vehiclechanged ? + limit.end + glm::dot( previousposition - position, limit.heading ) : + limit.end }; + limit.distance -= consistend - previousend; + } + limit.end = consistend; + limit.endknown = true; + } + + auto const travel { travel_direction() }; + std::erase_if( + m_pointlimits, + [&]( point_limit const &Limit ) { + // passed by the head + if( Limit.distance < 0.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Limit.source->m_name ); + } + return true; + } + // the head backed up behind the cell: the speed table reads it again if it is ahead + if( Limit.distance > Limit.celldistance + 1.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", left behind point limit of " + Limit.source->m_name ); + } + return true; + } + // the cell ahead of the head again, going towards the point after backing up past the cell: it is read anew + // (not while backing up: the cell may as well be scanned from the other side) + return glm::dot( travel, Limit.heading ) > 0.0 + && std::any_of( + sSpeedTable.begin(), sSpeedTable.end(), + [&]( TSpeedPos const &Point ) { + return Point.evEvent == Limit.source + && Point.flags.HasAll(SpeedPointFlag::enabled | SpeedPointFlag::event | SpeedPointFlag::pointSpeed) + && Point.fDist > 0.0; } ); } ); +} + +void TController::apply_point_limits( double &Velocity, double &Distance, double &Next, double &Acceleration ) { + + auto const travel { travel_direction() }; + for( auto const &limit : m_pointlimits ) { + // latched with no limit, or passed (dropped at the next update) + if( limit.velocity < 0.0 || limit.distance <= 0.0 ) { continue; } + // going away from the point, or the way isn't known + if( glm::dot( travel, limit.heading ) <= 0.0 ) { continue; } + // the same as for a point of the speed table ahead + auto const v { limit.velocity }; + auto const d { limit.distance }; + auto a { ( v * v - occupied->Vel * occupied->Vel ) / ( 25.92 * d ) }; + if( occupied->Vel < v ) { + auto const brakingdistance { 1.2 * fBrakeDist * braking_distance_multiplier( v ) }; + if( brakingdistance > 0.0 ) { + a = std::lerp( a, AccPreferred, std::clamp( ( d - brakingdistance ) / brakingdistance, 0.0, 1.0 ) ); + } + } + if( d < point_limit_approach() && v < Velocity ) { + Velocity = v; + } + if( a <= Acceleration + && ( v < Next || Next < 0 ) ) { + Acceleration = a; + Next = v; + Distance = d; + bStopTargetIsPassengerStop = false; + } + } +} + +double TController::point_limit_approach() const { + // a point limit holds at its point and not a metre beyond, so the braking curve alone leaves a slow consist + // coasting above it (the deceleration asked for is below what makes the driver brake). within the final + // approach, and five seconds of the present speed before it, the speed is held down to it already + return fMaxProximityDist + occupied->Vel / 3.6 * 5.0; +} + +glm::dvec3 TController::travel_direction() const { + + if( pVehicle == nullptr || iDirection == 0 ) { return glm::dvec3 { 0.0 }; } + // the direction is given against the couplers of the vehicle the driver is in, which is the vehicle measured; + // along its own length it follows the track, where the chord of a long consist on a curve doesn't + auto const along { pVehicle->CouplerPosition( VehicleEnd::front ) - pVehicle->CouplerPosition( VehicleEnd::rear ) }; + auto const length { glm::length( along ) }; + if( length < 0.001 ) { return glm::dvec3 { 0.0 }; } + return ( iDirection > 0 ? along : -along ) / length; +} + +bool +TController::TableUpdateEvent( double &Velocity, TCommandType &Command, TSpeedPos &Point, double &Signaldistance, int const Pointindex ) { + + if( Point.flags.HasAll(SpeedPointFlag::signalAreaEnd) ) { + // not a signal: it neither sends a command nor counts as the end of a speed limit in the scan + TableUpdateSignalAreaEnd( Point ); + return true; + } + + if( Point.flags.HasAll(SpeedPointFlag::pointSpeed) ) { + // PointVelocity: no signal, no command, only the limit at its point + // done once the head passes the point + if( Point.fDist + Point.fPointDist < 0.0 ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed point limit of " + Point.GetName() ); + } + Point.Clear(); + return true; + } + if( Point.fDist < 0.0 ) { + if( point_limit_latched( Point.evEvent ) ) { + // a table built anew found under the consist a cell whose state holds already + Point.Clear(); + return true; + } + if( Point.fVelNext != 0.0 ) { + // the head passed the cell: what it says now holds at the point, whatever happens to the table. + // a stop at 0 stays in the table, where the cell can still release it + latch_point_limit( Point ); + Point.Clear(); + return true; + } + } + return false; + } + + // sprawdzanie eventów pasywnych miniętych + if( Point.fDist < 0.0 ) { + if( SemNextIndex == Pointindex ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextIndex ].GetName() ); + } + SemNextIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód + } + if( SemNextStopIndex == Pointindex ) { + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", passed semaphor " + sSpeedTable[ SemNextStopIndex ].GetName() ); + } + SemNextStopIndex = npos; // jeśli minęliśmy semafor od ograniczenia to go kasujemy ze zmiennej sprawdzającej dla skanowania w przód + } + switch( Point.evEvent->input_command() ) { + // TBD, TODO: expand emergency_brake handling to a more generic security system signal + case TCommandType::cm_EmergencyBrake: { + pVehicle->RadioStop(); + Point.Clear(); // signal received, deactivate + return true; + } + case TCommandType::cm_SecuritySystemMagnet: { + // NOTE: magnet induction calculation presumes the driver is located in the front vehicle + // TBD, TODO: take into account actual position of controlled/occupied vehicle in the consist, whichever comes first + auto const magnetlocation { pVehicles[ VehicleEnd::front ]->physics->SecuritySystem.MagnetLocation }; + auto const magnetrange { 1.0 }; + auto const ismagnetpassed { Point.fDist < -( magnetlocation + magnetrange ) }; + if( Point.fDist < -magnetlocation && (occupied->Vel > EU07_AI_NOMOVEMENT || false == ismagnetpassed) ) { + // NOTE: normally we'd activate the magnet once the leading vehicle passes it + // but on a fresh scan after direction change it would be detected as long as it's under consist, and meet the (simple) activation condition + // thus we're doing a more precise check in such situation (we presume direction change takes place only if the vehicle is standing still) + occupied->SecuritySystem.set_cabsignal_lock(!aiControlled); // don't make life difficult for the ai, but a human driver is a fair game + PutCommand(Point.evEvent->input_text(), Point.evEvent->input_value(1), Point.evEvent->input_value(2), nullptr); + } + if( ismagnetpassed ) { + Point.Clear(); + occupied->SecuritySystem.set_cabsignal_lock(false); + } + return true; + } + default: { + break; + } + } + } + // check signals ahead + if( Point.fDist > 0.0 ) { + // bail out early for signals which activate when passed + // TBD: make it an event method? + switch( Point.evEvent->input_command() ) { + case TCommandType::cm_EmergencyBrake: { + return true; + } + case TCommandType::cm_SecuritySystemMagnet: { + return true; + } + default: { + break; + } + } + + if( Point.IsProperSemaphor( OrderCurrentGet() ) ) { + // special rule for cars: ignore stop signals at distance too short to come to a stop + // as trying to stop in such situation is likely to place the car on train tracks + if( is_car() + && Point.fVelNext != -1.0 + && Point.fVelNext < 1.0 + && Point.fDist < -0.5 + std::min(fBrakeDist * 0.2, occupied->Vel * 0.2) ) { + Point.Clear(); + return true; + } + // jeśli jest mienięty poprzedni semafor a wcześniej + // byl nowy to go dorzucamy do zmiennej, żeby cały czas widział najbliższy + if( SemNextIndex == npos ) { // NOSONAR + SemNextIndex = Pointindex; + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table update for " + OwnerName() + ", next semaphor is " + sSpeedTable[ SemNextIndex ].GetName() ); + } + } + if( SemNextStopIndex == npos + || ( sSpeedTable[SemNextStopIndex].fVelNext != 0 + && Point.fVelNext == 0 ) ) { + SemNextStopIndex = Pointindex; + } + } + } + if (Point.flags & SpeedPointFlag::outsideStation) + { // jeśli W5, to reakcja zależna od trybu jazdy + if (OrderCurrentGet() & DriverOrder::obeyTrain) + { // w trybie pociągowym: można przyspieszyć do wskazanej prędkości (po zjechaniu z rozjazdów) + Velocity = -1.0; // ignorować? + if ( Point.fDist < 0.0) { // jeśli wskaźnik został minięty + VelSignalLast = Velocity; //ustawienie prędkości na -1 + } + else if( ( false == drivingFlags.switchFound ) ) { // jeśli rozjazdy już minięte + VelSignalLast = Velocity; //!!! to też koniec ograniczenia + } + } + else + { // w trybie manewrowym: skanować od niego wstecz, stanąć po wyjechaniu za sygnalizator i zmienić kierunek + Velocity = 0.0; // zmiana kierunku może być podanym sygnałem, ale wypadało by zmienić światło wcześniej + if( ( false == drivingFlags.switchFound ) ) { // jeśli nie ma rozjazdu + // check for presence of a signal facing the opposite direction + // if there's one, we'll want to pass it before changing direction + basic_event *foundevent = nullptr; + if( Point.fDist - fMaxProximityDist > 0 ) { + auto scandistance{ Point.fDist + fLength - fMaxProximityDist }; + auto *scanvehicle{ pVehicles[ VehicleEnd::rear ] }; + auto scandirection{ scanvehicle->DirectionGet() * scanvehicle->RaDirectionGet() }; + auto *foundtrack = BackwardTraceRoute( scandistance, scandirection, scanvehicle, foundevent, -1, VehicleEnd::front, false ); + } + if( foundevent == nullptr ) { + drivingFlags.trackEnd = true; // to dalsza jazda trwale ograniczona (W5, koniec toru) + } + } + } + } + else if ( Point.flags & SpeedPointFlag::stopOnAutomaticBlock) { + // jeśli S1 na SBL + if( occupied->Vel < 2.0 && Point.fDist < fMaxProximityDist && Obstacle.distance > 1000 ) { + // stanąć nie musi, ale zwolnić przynajmniej + // jest w maksymalnym zasięgu to można go pominąć (wziąć drugą prędkosć) + // as long as there isn't any obstacle in arbitrary view range + eSignSkip = Point.evEvent; + // jazda na widoczność - skanować możliwość kolizji i nie podjeżdżać zbyt blisko + // usunąć flagę po podjechaniu blisko semafora zezwalającego na jazdę + // ostrożnie interpretować sygnały - semafor może zezwalać na jazdę pociągu z przodu! + drivingFlags.visibility = true; + // store the ordered restricted speed and don't exceed it until the flag is cleared + VelRestricted = Point.evEvent->input_value(2); + } + if( eSignSkip != Point.evEvent ) { + // jeśli ten SBL nie jest do pominięcia to ma 0 odczytywać + Velocity = Point.evEvent->input_value( 1 ); + // TODO sprawdzić do której zmiennej jest przypisywane v i zmienić to tutaj + } + } + else if ( Point.IsProperSemaphor(OrderCurrentGet())) + { // to semaphor + if( Point.fDist < 0 ) { + // for human-driven vehicles ignore the signal if it was passed by sufficient distance + if( false == aiControlled + && Point.fDist < -1 * std::max(fLength + 100, 250.0) ) { + VelSignal = -1.0; + Point.Clear(); + return true; + } + // for ai-driven vehicles always play by the rules + else { + VelSignalLast = Point.fVelNext; //minięty daje prędkość obowiązującą + // a marker before this signal ends the interlocking area of an earlier signal, not the area of this one + // (a train longer than the way between the two, or one which started standing over the marker) + std::ranges::for_each( sSpeedTable | std::views::take( Pointindex ), clear_signal_area_end ); + } + } + else { + //jeśli z przodu to dajemy flagę, że jest + drivingFlags.signalFound = true; + Signaldistance = std::min( Point.fDist, Signaldistance ); + // if there's another vehicle closer to the signal, then it's likely its intended recipient + // HACK: if so, make it a stop point, to prevent non-signals farther down affect us + auto const isforsomeoneelse { is_train() && Obstacle.distance < Point.fDist }; + if( Point.fDist <= Signaldistance ) { + if( isforsomeoneelse ) { + VelSignalNext = 0.0; + Velocity = 0.0; + } + else { + VelSignalNext = Point.fVelNext; + if( Velocity < 0 ) { + Velocity = fVelMax; + VelSignal = fVelMax; + } + } + } + } + } + else if ( Point.flags & SpeedPointFlag::roadSpeed) + { // to W27/W27a + if( TableUpdateRoadVelocity( Point ) ) { + return true; + } + } + else if ( Point.flags & SpeedPointFlag::sectionSpeed && Point.fDist < 0) + { // to W9 + // teraz trzeba sprawdzić inne warunki + if (Point.fSectionVelocityDist == 0.0) + { + if (Global.iWriteLogEnabled & 8) + { + WriteLog("TableUpdate: Event is behind. SVD = 0: " + Point.evEvent->m_name); + } + Point.Clear(); // jeśli punktowy to kasujemy i nie dajemy ograniczenia na stałe + } + else if (Point.fSectionVelocityDist < 0.0) + { + // ograniczenie obowiązujące do następnego + if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) + { + // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz + VelLimitLast = Point.fVelNext; + } + else if (Point.fDist < -fLength) + { + // jeśli większe to musi wyjechać za poprzednie + VelLimitLast = Point.fVelNext; + if (Global.iWriteLogEnabled & 8) + { + WriteLog("TableUpdate: Event is behind. SVD < 0: " + Point.evEvent->m_name); + } + Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować + } + } + else + { // jeśli większe to ograniczenie ma swoją długość + if (Point.fVelNext == min_speed(Point.fVelNext, VelLimitLast) && Point.fVelNext != VelLimitLast) + { + // jeśli ograniczenie jest mniejsze niż obecne to obowiązuje od zaraz + VelLimitLast = Point.fVelNext; + } + else if (Point.fDist < -fLength && Point.fVelNext != VelLimitLast) + { + // jeśli większe to musi wyjechać za poprzednie + VelLimitLast = Point.fVelNext; + } + else if (Point.fDist < -fLength - Point.fSectionVelocityDist) + { + VelLimitLast = -1.0; + if (Global.iWriteLogEnabled & 8) + { + WriteLog("TableUpdate: Event is behind. SVD > 0: " + Point.evEvent->m_name); + } + Point.Clear(); // wyjechaliśmy poza poprzednie, można skasować + } + } + } + + //sprawdzenie eventów pasywnych przed nami + { // zawalidrogi nie ma (albo pojazd jest samochodem), sprawdzić sygnał + if ( Point.flags & SpeedPointFlag::shuntSignal) // jeśli Tm - w zasadzie to sprawdzić komendę! + { // jeśli podana prędkość manewrowa + if( Velocity == 0.0 + && true == OrderCurrentGet().HasAll(DriverOrder::obeyTrain) ) { + // jeśli tryb pociągowy a tarcze ma ShuntVelocity 0 0 + Velocity = -1; // ignorować, chyba że prędkość stanie się niezerowa + if( true == Point.flags.HasAll(SpeedPointFlag::elapsed) ) { + // a jak przejechana to można usunąć, bo podstawowy automat usuwa tylko niezerowe + Point.Clear(); + } + } + else if( Command == TCommandType::cm_Unknown && Velocity != 0.0 ) { + // jeśli jeszcze nie ma komendy + // komenda jest tylko gdy ma jechać, bo stoi na podstawie tabelki + // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal + Command = TCommandType::cm_ShuntVelocity; // w trybie pociągowym tylko jeśli włącza tryb manewrowy (v!=0.0) + // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo Tm może być daleko + if (VelSignal == 0.0) + { + // aby stojący ruszył + VelSignal = Velocity; + } + if (Point.fDist < 0.0) + { + // jeśli przejechany + //!!! ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to + VelSignal = Velocity; + // to można usunąć (nie mogą być usuwane w skanowaniu) + Point.Clear(); + } + } + } + else if( false == Point.flags.HasAny(SpeedPointFlag::sectionSpeed) ) { + //jeśli jakiś event pasywny ale nie ograniczenie + if( Command != TCommandType::cm_Unknown ) + { + } + else + { + // jeśli nie było komendy wcześniej - pierwsza się liczy - ustawianie VelSignal + if (Velocity < 0.0 || Velocity >= 1.0) + { + // bo wartość 0.1 służy do hamowania tylko + Command = TCommandType::cm_SetVelocity; // może odjechać + // Ra 2014-06: (VelSignal) nie może być tu ustawiane, bo semafor może być daleko + // VelSignal=v; //nie do końca tak, to jest druga prędkość; -1 nie wpisywać... + if (VelSignal == 0.0) + { + // aby stojący ruszył + VelSignal = -1.0; + } + if (Point.fDist < 0.0) + { + // jeśli przejechany + VelSignal = Velocity == 0.0 ? 0.0 : -1.0; + // ustawienie, gdy przejechany jest lepsze niż wcale, ale to jeszcze nie to + if (Point.flags & SpeedPointFlag::event && (Point.evEvent != eSignSkip || Point.fVelNext != VelRestricted)) + { + // jeśli event + // ale inny niż ten, na którym minięto S1, chyba że się już zmieniło + // sygnał zezwalający na jazdę wyłącza jazdę na widoczność (po S1 na SBL) + drivingFlags.visibility = false; + // remove restricted speed + VelRestricted = -1.0; + } + // jeśli nie jest ograniczeniem prędkości to można usunąć + // (nie mogą być usuwane w skanowaniu) + TableDropPassedEvent( Point ); + } + } + else if (Point.fDist > 0.0 && typeid(*Point.evEvent) == typeid(road_order)) + { + // a level crossing or a junction which holds the vehicle ahead: the road orders past it, which let the traffic + // through, aren't for this vehicle yet. without this the first of them would tell the standing vehicle to drive on + Command = TCommandType::cm_SetProximityVelocity; // taken, and not acted on + } + else if (Point.evEvent->is_command()) + { + // jeśli prędkość jest zerowa, a komórka zawiera komendę + eSignNext = Point.evEvent; // dla informacji + // make sure the command isn't for someone else + // TBD, TODO: revise this check for bank/loose_shunt; we might want to ignore obstacles with no owner in these modes + if (Point.fDist < Obstacle.distance) + { + if (true == drivingFlags.stopHere) + { + // jeśli ma stać, dostaje komendę od razu + Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu + } + // NOTE: human drivers are likely to stop wherever and expect things to still work, so we give them more leeway + else if (Point.fDist <= (aiControlled ? fMaxProximityDist : std::max(250.0, fMaxProximityDist))) + { + // jeśli ma dociągnąć, to niech dociąga + // (moveStopCloser dotyczy dociągania do W4, nie semafora) + Command = TCommandType::cm_Command; // komenda z komórki, do wykonania po zatrzymaniu + } + } + } + } + } + } // jeśli nie ma zawalidrogi + + return false; +} + +void TController::TablePurger() +{ // odtykacz: usuwa mniej istotne pozycje ze środka tabelki, aby uniknąć zatkania + //(np. brak ograniczenia pomiędzy zwrotnicami, usunięte sygnały, minięte odcinki łuku) + if( sSpeedTable.size() < 2 ) { + return; + } + // simplest approach should be good enough for start -- just copy whatever is still relevant, then swap + auto const isexpendable = []( TSpeedPos const &Speedpoint ) { + return + false == Speedpoint.flags.HasAny( SpeedPointFlag::enabled ) + || ( ( Speedpoint.flags & ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve | SpeedPointFlag::switchTrack ) ) == ( SpeedPointFlag::elapsed | SpeedPointFlag::track | SpeedPointFlag::curve ) + && Speedpoint.fVelNext < 0.0 ); }; + // do a trial run first, to see if we need to bother at all + std::size_t trimcount{ 0 }; + for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { + // NOTE: we could break out early here, but running through entire thing gives us exact size needed for new table + if( isexpendable( sSpeedTable[ idx ] ) ) { + ++trimcount; + } + } + if( trimcount == 0 ) { + // there'd be no gain, may as well bail + return; + } + std::vector trimmedtable; trimmedtable.reserve( sSpeedTable.size() - trimcount ); + // the indices are only valid for the old table, so the new placements are recorded separately + // and assigned once the new table is complete + auto semnextindex { std::size_t( -1 ) }; + auto semnextstopindex { std::size_t( -1 ) }; + auto const trackplacement = [&]( std::size_t const Index, bool const Kept ) { + // a trimmed point leaves the index invalid, a kept one lands where the new table ends + if( Index == SemNextIndex ) { + semnextindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); + } + if( Index == SemNextStopIndex ) { + semnextstopindex = ( Kept ? trimmedtable.size() : std::size_t( -1 ) ); + } }; + + for( std::size_t idx = 0; idx < sSpeedTable.size() - 1; ++idx ) { + auto const &speedpoint = sSpeedTable[ idx ]; + auto const kept { false == isexpendable( speedpoint ) }; + trackplacement( idx, kept ); + if( false == kept ) { continue; } + // we're left with useful speed point record we should copy + trimmedtable.emplace_back( speedpoint ); + } + // always copy the last entry; an index pointing at it has to follow it as well + trackplacement( sSpeedTable.size() - 1, true ); + trimmedtable.emplace_back( sSpeedTable.back() ); + + SemNextIndex = semnextindex; + SemNextStopIndex = semnextstopindex; + + if( Global.iWriteLogEnabled & 8 ) { + WriteLog( "Speed table garbage collection for " + OwnerName() + " cut away " + std::to_string( trimcount ) + ( trimcount == 1 ? " record" : " records" ) ); + } + // update the data + std::swap( sSpeedTable, trimmedtable ); + iLast = sSpeedTable.size() - 1; +}; + +void TController::TableSort() { + + if( sSpeedTable.size() < 3 ) { + // we skip last slot and no point in checking if there's only one other entry + return; + } + // the last slot holds the track the scan stopped at and stays where it is. + // a single bubble pass is not enough: TableTraceRoute() adds the events of a track before the + // track itself, so a track with k scanned events lands k places too far and needs k passes + auto const sortedcount { static_cast( iLast ) }; + auto const inrange = [&]( std::size_t const Index ) { + return Index < sortedcount; }; + // the placements point at semaphor entries; remember which ones, the sort moves them around + auto const *semnextevent { inrange( SemNextIndex ) ? sSpeedTable[ SemNextIndex ].evEvent : nullptr }; + auto const *semnextstopevent { inrange( SemNextStopIndex ) ? sSpeedTable[ SemNextStopIndex ].evEvent : nullptr }; + + std::stable_sort( + std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, + []( TSpeedPos const &Left, TSpeedPos const &Right ) { + return Left.fDist < Right.fDist; } ); + + auto const relocate = [&]( basic_event const *Event, std::size_t &Index ) { + if( Event == nullptr ) { return; } + auto const lookup { + std::find_if( + std::begin( sSpeedTable ), std::begin( sSpeedTable ) + sortedcount, + [Event]( TSpeedPos const &Point ) { + return Point.evEvent == Event; } ) }; + Index = ( + lookup != std::begin( sSpeedTable ) + sortedcount ? + static_cast( std::distance( std::begin( sSpeedTable ), lookup ) ) : + std::size_t( -1 ) ); + }; + relocate( semnextevent, SemNextIndex ); + relocate( semnextstopevent, SemNextStopIndex ); +} diff --git a/vehicle/aipower.cpp b/vehicle/aipower.cpp new file mode 100644 index 000000000..8418d5fe1 --- /dev/null +++ b/vehicle/aipower.cpp @@ -0,0 +1,56 @@ +/* +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/aipower.h" + +#include + +namespace ai_power { + +stall check(state const &State) { + using enum stall; + if (false == State.collector || true == State.power) { + return not_stalled; + } + if (false == State.standing || false == State.pantographs_up) { + return waiting; + } + return State.wire ? no_voltage : no_wire; +} + +std::optional reporter::update(stall const Stall, double const Now) { + if (Stall == stall::not_stalled) { + m_since.reset(); + m_reported = false; + return std::nullopt; + } + if (Stall == stall::waiting) { + m_since.reset(); + return std::nullopt; + } + if (false == m_since.has_value()) { + m_since = Now; + } + if (true == m_reported || Now - *m_since < report_delay) { + return std::nullopt; + } + m_reported = true; + return Stall; +} + +std::string message(stall const Stall, std::string const &Name, glm::dvec3 const &Position) { + auto const reason{ + Stall == stall::no_wire ? + "no overhead wire above its raised pantographs" : + "no voltage in the overhead wire at its raised pantographs"}; + return std::format("AI [{}]: can't start, {} (at {:.2f}, {:.2f}, {:.2f}); it waits for the voltage", Name, reason, Position.x, Position.y, Position.z); +} + +} // namespace ai_power diff --git a/vehicle/aipower.h b/vehicle/aipower.h new file mode 100644 index 000000000..4d822980a --- /dev/null +++ b/vehicle/aipower.h @@ -0,0 +1,61 @@ +/* +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 + +#include +#include + +#include + +// an AI driver of an electric vehicle standing with its pantographs up and no voltage at them: past the end of the +// overhead wire, or under a wire which is switched off. no driver can start such a vehicle, it waits in +// TController::PrepareEngine() until the voltage comes, towed back under the wire or the power switched on. the +// driver tells of it in the log, once, instead of waiting without a word (eu07/maszyna#421) +namespace ai_power { + +// what the driver knows of the power of the vehicle when it prepares it +struct state { + bool collector{false}; // the vehicle takes its power from the overhead wire + bool power{false}; // there is the voltage the vehicle needs, at its pantographs or from the rest of the train + bool standing{false}; // the vehicle stands + bool pantographs_up{false}; // a pantograph is raised, with the air to hold it up + bool wire{false}; // a raised pantograph found a wire above it +}; + +enum class stall { + not_stalled, // the voltage is there, or the vehicle doesn't take it from the wire + waiting, // no voltage, but nothing to tell yet: the vehicle moves, or its pantographs aren't up + no_wire, // standing with the pantographs up and no wire above them + no_voltage // standing with a pantograph up at a wire which carries no voltage +}; + +stall check(state const &State); + +// how long [s] the vehicle stands with its pantographs up and no voltage before the driver tells of it. the +// pantographs need a few seconds to rise and the voltage a moment to come, a gap under a section insulator is +// shorter still +inline constexpr double report_delay{30.0}; + +// tells of a stall once: one report while it lasts. the voltage coming back ends it, and the next one is reported +// again; moving, or the pantographs going down, only restarts the count of report_delay +class reporter { +public: + // one look at the vehicle at the time Now [s]: the stall to report now, if any + std::optional update(stall Stall, double Now); + +private: + std::optional m_since; // when the vehicle began to stand with the pantographs up and no voltage + bool m_reported{false}; // the stall has been reported +}; + +// the line of the log telling of the stall of the vehicle Name standing at Position +std::string message(stall Stall, std::string const &Name, glm::dvec3 const &Position); + +} // namespace ai_power diff --git a/vehicle/aiwire.cpp b/vehicle/aiwire.cpp new file mode 100644 index 000000000..999d69075 --- /dev/null +++ b/vehicle/aiwire.cpp @@ -0,0 +1,78 @@ +/* +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/aiwire.h" + +#include + +namespace ai_wire { + +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double const Halfwidth) { + // Winger 170204: the parameter of the span's point in the plane of the pantograph's movement (the plane normal to + // Front through Point). the operations and their order are those the vehicles always had, so they find the same wire + auto const paramfrontdot = glm::dot(Parametric, Front); + auto const parameter = -(glm::dot(Point1, Front) - glm::dot(Point, Front)) / (paramfrontdot != 0.0 ? paramfrontdot : 0.001); + + contact result; + if (parameter < -0.001 || parameter > 1.001) { + return result; + } + // the point where the wire crosses the plane, against the pantograph + auto const crossing = Point1 + parameter * Parametric; + auto const offset = crossing - Point; + result.within = true; + result.vertical = glm::dot(offset, Up); + result.horizontal = std::abs(glm::dot(offset, Left)) - Halfwidth; + return result; +} + +bool reaches(contact const &Contact, double const Minheight, double const Maxheight) { + return Contact.within && Contact.horizontal <= 0.0 && Contact.vertical >= Minheight && Contact.vertical <= Maxheight; +} + +double wire_shortfall(std::function const &Covered, double const Pantograph, double const Stop, + double const Margin, double const Step, double const Walkback) { + if (!Covered || Step <= 0.0) { + return 0.0; + } + auto const fine{[&](double const Place) { return Covered(Place) && Covered(Place + Margin); }}; + // the pantograph at the target of the head + auto const target{Stop - Pantograph}; + if (fine(target)) { + return 0.0; + } + // the places back are counted from the target, not added up, so the steps don't drift + auto const steps{static_cast(std::floor(Walkback / Step + 1e-9))}; + for (int step = 1; step <= steps; ++step) { + auto const back{step * Step}; + if (fine(target - back)) { + return back; + } + } + return 0.0; +} + +bool stops_under_wire(bool const Collector, bool const Livetraction, bool const Overheadrestricted, stop_kind const Kind) { + if (!Collector || !Livetraction || Overheadrestricted) { + return false; + } + switch (Kind) { + case stop_kind::track_end: + case stop_kind::timetable_stop: + return true; + case stop_kind::signal: + case stop_kind::coupling: + default: + return false; + } +} + +} // namespace ai_wire diff --git a/vehicle/aiwire.h b/vehicle/aiwire.h new file mode 100644 index 000000000..89ccb1ecc --- /dev/null +++ b/vehicle/aiwire.h @@ -0,0 +1,75 @@ +/* +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 + +#include + +#include + +// where the overhead contact wire is, for the AI driver to stop its train with the pantograph under the wire, not past +// the end of it. the geometry of a pantograph against a span of the wire is the one the vehicles use to find their wire +// (basic_cell::update_traction), so the AI sees the wire where the pantographs do +namespace ai_wire { + +// a pantograph against one span of the wire +struct contact { + // the plane of the pantograph's movement (across the vehicle, at the pantograph) cuts the span, between its ends + bool within{false}; + // height of the wire above the pantograph's base point, along the up vector. negative for a wire below it + double vertical{0.0}; + // sideways distance of the wire from the working part of the slide: |offset along the left vector| less the slide's + // half width. the wire is on the slide when it's not positive + double horizontal{0.0}; +}; + +// the pantograph with its base point at Point, on a vehicle whose front, up and left vectors are Front, Up and Left, and +// a slide of half width Halfwidth, against the span from Point1 along Parametric (the span's other end is Point1 + +// Parametric). for a span parallel to the plane of the pantograph's movement the distance to the plane is divided by +// 0.001 in place of 0 (the division by zero trap the vehicles always had), which puts the crossing outside the span +// unless the span lies in the plane +contact span_contact(glm::dvec3 const &Point1, glm::dvec3 const &Parametric, glm::dvec3 const &Point, + glm::dvec3 const &Front, glm::dvec3 const &Up, glm::dvec3 const &Left, double Halfwidth); + +// the span is a wire the pantograph can reach: it crosses the plane of the pantograph's movement on the slide, between +// Minheight and Maxheight above the pantograph's base point. the heights keep out the wires of the bridges above the +// line and of the lines below it +bool reaches(contact const &Contact, double Minheight, double Maxheight); + +// the default margin of wire ahead of the pantograph at a stop, the step and the farthest distance back the stop is +// looked for under the wire, in metres +double const stop_margin{3.0}; +double const stop_step{2.0}; +double const stop_walk_back{300.0}; + +// how far short of its target a train has to stop so its pantograph stays under the wire, in metres along the route. +// the distances are along the route from the head of the train: Stop the target of the head, Pantograph the pantograph +// the train relies on (the rearmost one it raises) behind the head. Covered tells whether there's a wire over the +// route at the given distance. the pantograph at the stop is fine when there's wire over it and Margin ahead of it; +// otherwise it's moved back by Step at a time, up to Walkback, to the first place it's fine at. 0 when it's fine at the +// target, and when no place within Walkback is (not an electrified stretch, or a gap too long to tell about: stopping +// short won't help there) +double wire_shortfall(std::function const &Covered, double Pantograph, double Stop, + double Margin = stop_margin, double Step = stop_step, double Walkback = stop_walk_back); + +// what makes the train stop at a place +enum class stop_kind { + track_end, // the end of the track, e.g. a buffer stop, in train or shunting mode + timetable_stop, // a stop of the timetable (W4 indicator) + signal, // a signal at stop + coupling, // a vehicle to couple to or to uncouple from +}; + +// the train stops with its pantograph under the wire. not when it runs without the wire: without a current collector, +// with the voltage made up (livetraction off), on a stretch the scenery tells to coast or to run with the pantographs +// down. not for a signal (a wait, the wire ending before a signal is a fault of the scenery) and not for a coupling +// (the vehicle to couple to may stand on a siding without the wire) +bool stops_under_wire(bool Collector, bool Livetraction, bool Overheadrestricted, stop_kind Kind); + +} // namespace ai_wire diff --git a/vehicle/blackbox.cpp b/vehicle/blackbox.cpp index fc05f7483..0138b6acd 100644 --- a/vehicle/blackbox.cpp +++ b/vehicle/blackbox.cpp @@ -381,6 +381,22 @@ void writer::coupling(coupling_change const &Change) { emit(record::coupling); } +void writer::derailment(derailment_state const &State) { + auto &out{begin()}; + out.f64(State.time); + out.u32(State.vehicle); + out.u8(State.phase); + out.u8(State.cause); + out.dvec3(State.position); + out.f32(State.heading); + out.f32(State.speed_kmh); + out.f32(State.offset); + out.f32(State.roll); + out.f32(State.travelled); + out.u8(State.lying ? 1 : 0); + emit(record::derailment); +} + void writer::clock(double const Time, std::uint16_t const Year, std::uint16_t const Year_day, double const Second_of_day) { auto &out{begin()}; out.f64(Time); diff --git a/vehicle/blackbox.h b/vehicle/blackbox.h index 62fc1df38..26fe5c6a1 100644 --- a/vehicle/blackbox.h +++ b/vehicle/blackbox.h @@ -52,6 +52,7 @@ enum class record : std::uint8_t { station = 0x35, horn_request = 0x36, coupling = 0x37, + derailment = 0x38, end = 0x3f }; @@ -304,7 +305,7 @@ struct station_event { struct camera_state { double time{0.0}; std::uint8_t mode{camera_modes::free}; - std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by + std::uint8_t view{0}; // of an outside view: 0 the front of the train, 1 its rear, 2 a bogie, 3 drive-by, 4 orbit, 5 shunting, 6 coupling, 7 trackside std::uint32_t vehicle{no_vehicle}; // the vehicle the camera goes with, no_vehicle for none glm::dvec3 position{0.0}; float heading{0.0f}; // [rad] of where it looks, from +z towards +x, as the heading of a vehicle @@ -324,6 +325,35 @@ struct coupling_change { glm::dvec3 position{0.0}; // of the coupler }; +// what put a vehicle off the rails, for the derailment record (vehicle/derailmotion.h) +namespace derailment_causes { +inline constexpr std::uint8_t flange_climbed{1}; +inline constexpr std::uint8_t overturned{2}; +inline constexpr std::uint8_t end_of_track{3}; +inline constexpr std::uint8_t pulled_off{4}; // by the coupling of a vehicle off the track +inline constexpr std::uint8_t collision{5}; +} // namespace derailment_causes + +namespace derailment_phases { +inline constexpr std::uint8_t left_track{0}; // it left the track +inline constexpr std::uint8_t at_rest{1}; // it came to rest off the track +} // namespace derailment_phases + +// a vehicle off the track (physics.derailment new): as it leaves it, and where it comes to rest +struct derailment_state { + double time{0.0}; + std::uint32_t vehicle{no_vehicle}; + std::uint8_t phase{derailment_phases::left_track}; + std::uint8_t cause{derailment_causes::flange_climbed}; + glm::dvec3 position{0.0}; // of the vehicle + float heading{0.0f}; // [rad] of its front, from +z towards +x + float speed_kmh{0.0f}; // signed: positive along its front + float offset{0.0f}; // [m] from the axis of the track at the place nearest to it, to the left of its front positive + float roll{0.0f}; // [rad] of its body against the level, to the left positive; 90 degrees on its side + float travelled{0.0f}; // [m] on the ground since it left the rails + bool lying{false}; // on its side +}; + struct vehicle_state { std::uint32_t id{no_vehicle}; glm::vec3 position{0.0f}; @@ -378,6 +408,7 @@ public: void horn_request(double Time, std::uint32_t Vehicle, float Duration, float Tone, glm::dvec3 const &Position); void camera(camera_state const &Camera); void coupling(coupling_change const &Change); + void derailment(derailment_state const &State); void vehicle(vehicle_data const &Vehicle); void vehicle_removed(double Time, std::uint32_t Id); void cab(cab_sample const &Sample); 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 new file mode 100644 index 000000000..e9c189bb2 --- /dev/null +++ b/vehicle/brakereleaser.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/brakereleaser.h" + +namespace brake_releaser { + +namespace { + +// the rules for a driver that wants to speed up +bool wanted_to_start(conditions const &State) { + // fill up the brake pipe if needed + if (State.pipe_pressure < 3.0) { + return true; + } + // wyluzuj lokomotywę, to szybciej ruszymy + // this rule is for starting off, so only below 1 km/h: at speed, just after an application, it would vent + // the control reservoir of a locomotive that may have to brake again before the pipe has refilled it + if (State.cylinder_pressure > 0.4 + && (State.control_pressure > 4.9 + // starting uphill the train brake stays applied on purpose, and the locomotive's own share of it has to go + // for the power to come on (asynchronous drives and the pressure switch cut the power while it is applied) + || State.uphill_start) + && State.velocity < 1.0) { + return true; + } + // keep engine brakes released during coupling/uncoupling + return State.pressing && State.cylinder_pressure > 0.1; +} + +} // namespace + +decision decide(conditions const &State) { + decision result; + if (State.acceleration_desired > no_acceleration) { + 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 + // below no_acceleration, and a locomotive left braked by the consist's brake application never closes the gap + if (State.compressing_buffers && State.cylinder_pressure > 0.1) { + result.actuate = true; + } + // don't overcharge train brake pipe + if (State.pipe_pressure > 5.2) { + result.actuate = false; + } + return result; +} + +} // namespace brake_releaser diff --git a/vehicle/brakereleaser.h b/vehicle/brakereleaser.h new file mode 100644 index 000000000..e4ba14ad6 --- /dev/null +++ b/vehicle/brakereleaser.h @@ -0,0 +1,42 @@ +/* +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 + +// when the AI driver works the brake releaser of its locomotive (TController::control_releaser): it vents the +// locomotive's own train brake cylinders, to start off sooner, to fill up an empty brake pipe, and to let the +// locomotive press the buffers while it (un)couples +namespace brake_releaser { + +// the state of the locomotive and of its driver the decision depends on +struct conditions { + double acceleration_desired{0.0}; // AccDesired of the driver [m/s2]; above no_acceleration it wants to speed up + double pipe_pressure{0.0}; // brake pipe [bar] + double cylinder_pressure{0.0}; // the locomotive's brake cylinders [bar] + double control_pressure{0.0}; // the control reservoir of the locomotive's distributor [bar] + double velocity{0.0}; // [km/h] + 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 { + bool actuate{false}; // the releaser goes on (else off) + bool fill_pipe{false}; // the brake pipe is to be filled up: the brake handle goes to its unlock position +}; + +// AccDesired at or below this asks for no speeding up (EU07_AI_NOACCELERATION of Driver.h) +inline constexpr double no_acceleration{-0.05}; + +decision decide(conditions const &State); + +} // namespace brake_releaser diff --git a/vehicle/brakesetting.cpp b/vehicle/brakesetting.cpp index ceffe3180..7677ff19a 100644 --- a/vehicle/brakesetting.cpp +++ b/vehicle/brakesetting.cpp @@ -10,8 +10,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/brakesetting.h" -#include "McZapkie/MOVER.h" -#include "McZapkie/hamulce.h" +#include "physics/vehicle.h" +#include "physics/brakes.h" #include "vehicle/Driver.h" #include @@ -173,8 +173,12 @@ std::vector choose(std::vector const &Consist, bool const Train) { return settings; } -bool runs_as_train(int const Orders) { - return (Orders & (Obey_train | Bank)) != 0; +bool runs_as_train(DriverOrders const Orders) { + return Orders.HasAny(DriverOrder::obeyTrain | DriverOrder::bank); +} + +bool inspects_train(DriverOrders const Orders, bool const Coupled) { + return Orders.HasAny(DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank) || (Orders.HasAny(DriverOrder::connect) && false == Coupled); } bool at_standstill(double const Velocity) { @@ -244,27 +248,27 @@ std::vector choose_legacy(std::vector const &Consist) { return settings; } -bool is_cut_out(TMoverParameters const &Vehicle) { - return (Vehicle.Hamulec->GetBrakeStatus() & b_dmg) == b_dmg; +bool is_cut_out(physics::Vehicle const &Vehicle) { + return (Vehicle.brakes.distributor->GetBrakeStatus() & b_dmg) == b_dmg; } -vehicle describe(TMoverParameters const &Vehicle, bool const Driven) { +vehicle describe(physics::Vehicle const &Vehicle, bool const Driven) { vehicle described; - described.delays = Vehicle.BrakeDelays; + described.delays = Vehicle.brakes.config.availableDelays; // a locomotive has Power > 1, though it may be a dead one at the end of the train described.powered = Vehicle.Power >= 1.0; described.length = Vehicle.Dim.L; - described.mass = Vehicle.TotalMass; - described.cut_out = is_cut_out(Vehicle) && false == Vehicle.BrakeCutOutByInspector; + described.mass = Vehicle.TotalMass(); + described.cut_out = is_cut_out(Vehicle) && false == Vehicle.brakes.cutOutByInspector; described.driven = Driven; return described; } -bool apply(TMoverParameters &Vehicle, int const Setting, bool const Standstill) { - auto &brake{*Vehicle.Hamulec}; - if (Vehicle.BrakeCutOutByInspector && false == is_cut_out(Vehicle)) { +bool apply(physics::Vehicle &Vehicle, int const Setting, bool const Standstill) { + auto &brake{*Vehicle.brakes.distributor}; + if (Vehicle.brakes.cutOutByInspector && false == is_cut_out(Vehicle)) { // someone put the brake back in the meantime, it's theirs now - Vehicle.BrakeCutOutByInspector = false; + Vehicle.brakes.cutOutByInspector = false; } if (Setting == cut_out) { if (is_cut_out(Vehicle)) { @@ -280,13 +284,13 @@ bool apply(TMoverParameters &Vehicle, int const Setting, bool const Standstill) // distributor, cut off the brake pipe, has no air left to brake with and lets the cylinders go brake.ForceEmptiness(); brake.SetBrakeStatus(brake.GetBrakeStatus() | b_dmg); - Vehicle.BrakeCutOutByInspector = true; + Vehicle.brakes.cutOutByInspector = true; return false; } - if (Vehicle.BrakeCutOutByInspector) { + if (Vehicle.brakes.cutOutByInspector) { // open the cut-out cock: the distributor charges from the brake pipe again brake.SetBrakeStatus(brake.GetBrakeStatus() & ~b_dmg); - Vehicle.BrakeCutOutByInspector = false; + Vehicle.brakes.cutOutByInspector = false; } if (Setting != 0) { Vehicle.BrakeDelaySwitch(Setting); diff --git a/vehicle/brakesetting.h b/vehicle/brakesetting.h index cb7ad5225..d54075110 100644 --- a/vehicle/brakesetting.h +++ b/vehicle/brakesetting.h @@ -11,7 +11,9 @@ http://mozilla.org/MPL/2.0/. #include -class TMoverParameters; +#include "vehicle/driverorders.h" + +namespace physics { class Vehicle; } // the brake setting (G/P/R/Mg) the virtual wagon inspector (TController::AutoRewident) chooses for every // vehicle of a train, by the rules of the brake instruction Cw-1 (Mw56), §18 and §19 (eu07/maszyna#350) @@ -63,7 +65,16 @@ std::vector choose(std::vector const &Consist, bool Train); // the AI runs the consist as a train, rather than shunting it: Obey_train, or Bank, which it drives as a // train run too (with the braking of a train). Orders is the order of the AI (TOrders) -bool runs_as_train(int Orders); +bool runs_as_train(DriverOrders Orders); + +// the AI has the inspector look at its train (TController::AutoRewident(): the brake settings, and the hand and +// spring brakes of the train released) under the orders it drives the train under: shunting, loose shunting, the +// train run, banking, and the run up to the wagons to couple to (Connect), which a locomotive left standing cold, +// with its hand brake on, would make pulling against it. Coupled: the look the AI takes at the moment it couples +// (CheckVehicles(Connect)); Connect doesn't count for it, so the wagons just coupled keep their hand brakes until +// the order after the coupling looks at the new train, as before: those of them to be left standing again +// (Shunt x,-y) stay braked. Orders is the order of the AI (TOrders) +bool inspects_train(DriverOrders Orders, bool Coupled); // the train stands for the inspector: slower than the AI takes for a deliberate movement (EU07_AI_MOVEMENT). // the AI looks at the train while it still creeps to a stop (at a W4, or switching from shunting to the train @@ -78,11 +89,11 @@ bool at_standstill(double Velocity); std::vector choose_legacy(std::vector const &Consist); // the brake of the vehicle is cut out (b_dmg), whoever did it -bool is_cut_out(TMoverParameters const &Vehicle); +bool is_cut_out(physics::Vehicle const &Vehicle); // what choose() needs to know of the vehicle. a brake the inspector cut out itself doesn't count as // cut out: the inspector decides about it anew -vehicle describe(TMoverParameters const &Vehicle, bool Driven); +vehicle describe(physics::Vehicle const &Vehicle, bool Driven); // the inspector puts the vehicle on Setting, as choose() gives it. cut_out cuts the brake out the way // the scenery's '0' does: b_dmg, which cuts the distributor off the brake pipe (as the cab's cut-out, @@ -94,6 +105,6 @@ vehicle describe(TMoverParameters const &Vehicle, bool Driven); // setting as it is). A brake cut out by anyone else stays cut out. // Returns true when a cut-out was left for later because the train was moving: the inspector has to look // at the train again once it stands (TController::reinspect_brakes() does) -bool apply(TMoverParameters &Vehicle, int Setting, bool Standstill); +bool apply(physics::Vehicle &Vehicle, int Setting, bool Standstill); } // namespace brake_setting diff --git a/vehicle/brakingcurve.cpp b/vehicle/brakingcurve.cpp index d39ee2868..f28439ed0 100644 --- a/vehicle/brakingcurve.cpp +++ b/vehicle/brakingcurve.cpp @@ -25,6 +25,10 @@ bool brake_table::known() const { return a0[size] > 0.0; } +bool brake_acting(double const Trainbrakeposition, double const Localbrakeposition) { + return (Trainbrakeposition > 0.0) || (Localbrakeposition > 0.0); +} + double shaped_demand(double const Velocity, double const Target, double const Distance, double const Gravity, brake_table const &Table) { auto const travel = [Velocity, Target, Gravity, &Table](double const Ratio) { @@ -83,4 +87,12 @@ double demand(approach const &Approach, brake_table const *Pneumatictable) { return shaped_demand(velocity, Approach.target, room + 0.1 / 25.92, Approach.gravity, *table); } +bool stops_where_it_is(double const Velocity, double const Room, double const Gravity) { + + constexpr double walking_pace{5.0}; // [km/h] + constexpr double last_metres{2.0}; // [m] + constexpr double descent{0.025}; // [m/s2] about 2.5 per mille down, as the AI takes a gradient going downhill + return (Gravity > descent) && (Velocity < walking_pace) && (Room < last_metres); +} + } // namespace braking_curve diff --git a/vehicle/brakingcurve.h b/vehicle/brakingcurve.h index 6ed40d9bb..ab8371827 100644 --- a/vehicle/brakingcurve.h +++ b/vehicle/brakingcurve.h @@ -40,15 +40,28 @@ struct approach { double offset; // the braking point that far short of it [m] double gravity; // tangential acceleration of the gradient [m/s2], negative uphill double acceleration; // present acceleration of the train [m/s2] - bool brake_applied; // the train brake handle is past running + bool brake_applied; // the brake the train slows down with is applied (brake_acting) double speedup_horizon; // how long the present acceleration lasts while speeding up [s] double fill_horizon; // how long the brake takes to fill once applied [s] }; +// whether the train is braking already, for approach::brake_applied: the train brake handle is past running +// (Trainbrakeposition above 0), or the independent brake is applied (Localbrakeposition above 0). a vehicle that +// runs alone, a light locomotive or a railcar, brakes with the independent brake and leaves the train brake +// handle in running +bool brake_acting(double Trainbrakeposition, double Localbrakeposition); + // acceleration [m/s2] to ask for now, negative to brake. with the worked out table of a pneumatic brake // (Pneumatictable) the demand follows the brake: planned from the state the train is in once the brake has // responded, along the shape of its force over speed. without one (nullptr for another brake, or a table left at // zero, as in shunting) it is the constant deceleration over the distance left double demand(approach const &Approach, brake_table const *Pneumatictable); +// whether a train in the final approach to a stop, down a gradient, stops where it is rather than creeps on to the +// point it aims at: down to walking pace (Velocity [km/h]) within the last metres short of that point, or past it +// (Room [m], negative past it), on a descent (Gravity [m/s2], positive downhill). there the demand of the curve is +// next to nothing; the pneumatic brake let off for it lets the gradient take the train again, and it crept on and +// braked again, a release and an application at a time, for many seconds +bool stops_where_it_is(double Velocity, double Room, double Gravity); + } // namespace braking_curve diff --git a/vehicle/cab/auxiliarycommands.cpp b/vehicle/cab/auxiliarycommands.cpp new file mode 100644 index 000000000..61d419fc6 --- /dev/null +++ b/vehicle/cab/auxiliarycommands.cpp @@ -0,0 +1,1308 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the auxiliaries: the pumps, the genset, the water, the converter, the compressor, the blowers + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_fuelpumptoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_fuelpumpenable(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->controlled->FuelPump.is_enabled) + { + // turn on + OnCommand_fuelpumpenable(Train, Command); + } + else + { + // turn off + OnCommand_fuelpumpdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_fuelpumpenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->controlled->FuelPumpSwitch(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->controlled->FuelPumpSwitch(false); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->controlled->FuelPumpSwitch(true); + Train->controlled->FuelPumpSwitchOff(false); + } + } +} + +void TTrain::OnCommand_fuelpumpdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuelPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->controlled->FuelPumpSwitch(false); + Train->controlled->FuelPumpSwitchOff(true); + } + } +} + +void TTrain::OnCommand_oilpumptoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggOilPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_oilpumpenable(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->controlled->OilPump.is_enabled) + { + // turn on + OnCommand_oilpumpenable(Train, Command); + } + else + { + // turn off + OnCommand_oilpumpdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_oilpumpenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggOilPumpButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->controlled->OilPumpSwitch(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->controlled->OilPumpSwitch(false); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->controlled->OilPumpSwitch(true); + Train->controlled->OilPumpSwitchOff(false); + } + } +} + +void TTrain::OnCommand_oilpumpdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggOilPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggOilPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->controlled->OilPumpSwitch(false); + Train->controlled->OilPumpSwitchOff(true); + } + } +} + +void TTrain::OnCommand_oilfuelpumptoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_REPEAT) + { + return; + } + + auto *vehicle{Train->controlled}; + if (Train->ggOilFuelPumpButton.type() == TGaugeType::push) + { + // impulse switch, as the separate ones: held to start both pumps + auto const pressed{Command.action == GLFW_PRESS}; + Train->ggOilFuelPumpButton.UpdateValue(pressed ? 1.0 : 0.0, Train->dsbSwitch); + vehicle->FuelPumpSwitch(pressed); + vehicle->OilPumpSwitch(pressed); + return; + } + // two-state switch, only cares about press events + if (Command.action != GLFW_PRESS) + { + return; + } + // both pumps go off if both were on, otherwise both go on; a pump started automatically doesn't take part + auto const enable{false == vehicle->OilFuelPumpsEnabled()}; + Train->ggOilFuelPumpButton.UpdateValue(enable ? 1.0 : 0.0, Train->dsbSwitch); + vehicle->FuelPumpSwitch(enable); + vehicle->FuelPumpSwitchOff(false == enable); + vehicle->OilPumpSwitch(enable); + vehicle->OilPumpSwitchOff(false == enable); +} + +// the traction selector of a dual-mode vehicle (eu07/maszyna#536), a two-state switch +void TTrain::OnCommand_tractionmodetoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (Train->controlled->GensetSelected()) + { + OnCommand_tractionmodecatenary(Train, Command); + } + else + { + OnCommand_tractionmodegenset(Train, Command); + } +} + +void TTrain::OnCommand_tractionmodecatenary(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed: then the switch doesn't move + Train->controlled->TractionModeSwitch(physics::Vehicle::traction_mode::catenary, range_t::consist); + if (false == Train->controlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_tractionmodegenset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // refused with the line breaker closed, or without a genset: then the switch doesn't move + Train->controlled->TractionModeSwitch(physics::Vehicle::traction_mode::genset, range_t::consist); + if (Train->controlled->GensetSelected()) + { + Train->ggTractionModeSwitch.UpdateValue(1.0, Train->dsbSwitch); + } +} + +// the start request of the genset of a dual-mode vehicle, a two-state switch +void TTrain::OnCommand_gensettoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->controlled->Genset.is_enabled) + { + OnCommand_gensetenable(Train, Command); + } + else + { + OnCommand_gensetdisable(Train, Command); + } +} + +void TTrain::OnCommand_gensetenable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + // ignored by a genset which starts on its own: then the switch doesn't move + Train->controlled->GensetSwitch(true, range_t::consist); + if (Train->controlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_gensetdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + Train->controlled->GensetSwitch(false, range_t::consist); + if (false == Train->controlled->Genset.is_enabled) + { + Train->ggGensetButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_waterheaterbreakertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->controlled->WaterHeater.breaker) + { + // turn on + OnCommand_waterheaterbreakerclose(Train, Command); + } + else + { + // turn off + OnCommand_waterheaterbreakeropen(Train, Command); + } + } +} + +void TTrain::OnCommand_waterheaterbreakerclose(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterBreakerButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->controlled->WaterHeater.breaker) + { + return; + } // already enabled + + Train->controlled->WaterHeaterBreakerSwitch(true); + } +} + +void TTrain::OnCommand_waterheaterbreakeropen(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterBreakerButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->controlled->WaterHeater.breaker) + { + return; + } // already enabled + + Train->controlled->WaterHeaterBreakerSwitch(false); + } +} + +void TTrain::OnCommand_waterheatertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->controlled->WaterHeater.is_enabled) + { + // turn on + OnCommand_waterheaterenable(Train, Command); + } + else + { + // turn off + OnCommand_waterheaterdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_waterheaterenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->controlled->WaterHeater.is_enabled) + { + return; + } // already enabled + + Train->controlled->WaterHeaterSwitch(true); + } +} + +void TTrain::OnCommand_waterheaterdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterHeaterButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->controlled->WaterHeater.is_enabled) + { + return; + } // already disabled + + Train->controlled->WaterHeaterSwitch(false); + } +} + +void TTrain::OnCommand_waterpumpbreakertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->controlled->WaterPump.breaker) + { + // turn on + OnCommand_waterpumpbreakerclose(Train, Command); + } + else + { + // turn off + OnCommand_waterpumpbreakeropen(Train, Command); + } + } +} + +void TTrain::OnCommand_waterpumpbreakerclose(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpBreakerButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->controlled->WaterPump.breaker) + { + return; + } // already enabled + + Train->controlled->WaterPumpBreakerSwitch(true); + } +} + +void TTrain::OnCommand_waterpumpbreakeropen(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpBreakerButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->controlled->WaterPump.breaker) + { + return; + } // already enabled + + Train->controlled->WaterPumpBreakerSwitch(false); + } +} + +void TTrain::OnCommand_waterpumptoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggWaterPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_waterpumpenable(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->controlled->WaterPump.is_enabled) + { + // turn on + OnCommand_waterpumpenable(Train, Command); + } + else + { + // turn off + OnCommand_waterpumpdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_waterpumpenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggWaterPumpButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->controlled->WaterPumpSwitch(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->controlled->WaterPumpSwitch(false); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(1.0, Train->dsbSwitch); + Train->controlled->WaterPumpSwitch(true); + Train->controlled->WaterPumpSwitchOff(false); + } + } +} + +void TTrain::OnCommand_waterpumpdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggWaterPumpButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterPumpButton.UpdateValue(0.0, Train->dsbSwitch); + Train->controlled->WaterPumpSwitch(false); + Train->controlled->WaterPumpSwitchOff(true); + } + } +} + +void TTrain::OnCommand_watercircuitslinktoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->controlled->WaterCircuitsLink()) + { + // turn on + OnCommand_watercircuitslinkenable(Train, Command); + } + else + { + // turn off + OnCommand_watercircuitslinkdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_watercircuitslinkenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterCircuitsLinkButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->controlled->WaterCircuitsLink()) + { + return; + } // already enabled + + Train->controlled->WaterCircuitsLinkSwitch(true); + } +} + +void TTrain::OnCommand_watercircuitslinkdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggWaterCircuitsLinkButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->controlled->WaterCircuitsLink()) + { + return; + } // already disabled + + Train->controlled->WaterCircuitsLinkSwitch(false); + } +} + +void TTrain::OnCommand_convertertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const overloadrelayisopen{(Train->Dynamic()->Mechanik != nullptr ? Train->Dynamic()->Mechanik->ConsistConverterOverloaded() : Train->occupied->converter.IsOverloaded())}; + + if (Train->occupied->converter.config.switchType != "impulse" ? Train->ggConverterButton.GetValue() < 0.5 : false == Train->occupied->lowVoltage.Is110vAvailable() && false == overloadrelayisopen) + { + // turn on + OnCommand_converterenable(Train, Command); + } + else + { + // turn off + OnCommand_converterdisable(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // on button release... + if (Train->occupied->converter.config.switchType == "impulse") + { + // ...return switches to start position if applicable + Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggConverterOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_converterenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggConverterButton.UpdateValue(1.0, Train->dsbSwitch); + + // impulse type switch has no effect if there's no power + // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway + if (Train->occupied->converter.config.switchType != "impulse" || Train->controlled->lineBreaker.IsClosed()) + { + // won't start if the line breaker button is still held + Train->occupied->ConverterSwitch(true); + } + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_convertertoggle(Train, Command); + } +} + +void TTrain::OnCommand_converterdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggConverterButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggConverterOffButton.SubModel != nullptr) + { + Train->ggConverterOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + + Train->occupied->ConverterSwitch(false); + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_convertertoggle(Train, Command); + } +} + +void TTrain::OnCommand_convertertogglelocal(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->converter.config.start == start_t::automatic) + { + // let the automatic thing do its automatic thing... + return; + } + if (Train->ggConverterLocalButton.SubModel == nullptr) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->occupied->converter.LocalSwitchOn() && Train->ggConverterLocalButton.GetValue() < 0.5) + { + // turn on + // visual feedback + Train->ggConverterLocalButton.UpdateValue(1.0, Train->dsbSwitch); + // effect + Train->occupied->converter.SetLocalSwitch(true); + /* + if( true == Train->controlled->ConverterSwitch( true, range::local ) ) { + // side effects + // control the compressor, if it's paired with the converter + if( Train->controlled->CompressorPower == 2 ) { + // hunter-091012: tak jest poprawnie + Train->controlled->CompressorSwitch( true, range::local ); + } + } + */ + } + else + { + // turn off + // visual feedback + Train->ggConverterLocalButton.UpdateValue(0.0, Train->dsbSwitch); + // effect + Train->occupied->converter.SetLocalSwitch(false); + /* + if( true == Train->controlled->ConverterSwitch( false, range::local ) ) { + // side effects + // control the compressor, if it's paired with the converter + if( Train->controlled->CompressorPower == 2 ) { + // hunter-091012: tak jest poprawnie + Train->controlled->CompressorSwitch( false, range::local ); + } + // if there's no (low voltage) power source left, drop pantographs + if( false == Train->controlled->Battery ) { + Train->controlled->PantFront( false, range::local ); + Train->controlled->PantRear( false, range::local ); + } + } + */ + } + } +} + +void TTrain::OnCommand_converteroverloadrelayreset(TTrain *Train, command_data const &Command) +{ + + if (Train->ggConverterFuseButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Converter Overload Relay Reset button is missing, or wasn't defined"); + } + // return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggConverterFuseButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->controlled->RelayReset(relay_t::primaryconverteroverload); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggConverterFuseButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_compressortoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const compressorisenabled{(Train->Dynamic()->Mechanik ? Train->Dynamic()->Mechanik->ConsistCompressorEnabled() : Train->occupied->air.compressor.IsAllowed())}; + + if (false == compressorisenabled) + { + // turn on + OnCommand_compressorenable(Train, Command); + } + else + { + // turn off + OnCommand_compressordisable(Train, Command); + } + } + /* + // disabled because we don't have yet support for compressor switch type definition + else if( Command.action == GLFW_RELEASE ) { + // on button release... + if( Train->occupied->CompSwitchType == "impulse" ) { + // ...return switches to start position if applicable + Train->ggCompressorButton.UpdateValue( 0.0, Train->dsbSwitch ); + Train->ggCompressorOffButton.UpdateValue( 0.0, Train->dsbSwitch ); + } + } + */ +} + +void TTrain::OnCommand_compressorenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggCompressorButton.UpdateValue(1.0, Train->dsbSwitch); + + // impulse type switch has no effect if there's no power + // NOTE: this is most likely setup wrong, but the whole thing is smoke and mirrors anyway + // if( ( Train->occupied->CompSwitchType != "impulse" ) + // || ( Train->controlled->Mains ) ) { + + Train->occupied->CompressorSwitch(true); + // } + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_compressortoggle(Train, Command); + } +} + +void TTrain::OnCommand_compressordisable(TTrain *Train, command_data const &Command) +{ + + if (Train->controlled->air.compressor.config.supply >= physics::CompressorSupply::converter) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggCompressorButton.UpdateValue(0.0, Train->dsbSwitch); + /* + if( Train->ggCompressorOffButton.SubModel != nullptr ) { + Train->ggCompressorOffButton.UpdateValue( 1.0, Train->dsbSwitch ); + } + */ + Train->occupied->CompressorSwitch(false); + } + else if (Command.action == GLFW_RELEASE) + { + // potentially reset impulse switch position, using shared code branch + OnCommand_compressortoggle(Train, Command); + } +} + +void TTrain::OnCommand_compressortogglelocal(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->air.compressor.config.supply >= physics::CompressorSupply::converter) + { + return; + } + if (Train->ggCompressorLocalButton.SubModel == nullptr) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->occupied->air.compressor.LocalSwitchOn()) + { + // turn on + // visual feedback + Train->ggCompressorLocalButton.UpdateValue(1.0, Train->dsbSwitch); + // effect + Train->occupied->air.compressor.SetLocalSwitch(true); + } + else + { + // turn off + // visual feedback + Train->ggCompressorLocalButton.UpdateValue(0.0, Train->dsbSwitch); + // effect + Train->occupied->air.compressor.SetLocalSwitch(false); + } + } +} + +void TTrain::OnCommand_compressorpresetactivatenext(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->air.compressor.config.listPositions == 0) + { + return; + } + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggCompressorListButton.type() == TGaugeType::push) + { + // impulse switch + if (Train->occupied->air.compressor.config.listPositions < Train->occupied->air.compressor.config.listDefaultPosition + 1) + { + return; + } + + Train->occupied->ChangeCompressorPreset(Command.action == GLFW_PRESS ? Train->occupied->air.compressor.config.listDefaultPosition + 1 : Train->occupied->air.compressor.config.listDefaultPosition); + // visual feedback + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); + } + else + { + // multi-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (Train->occupied->air.compressor.ListPosition() < Train->occupied->air.compressor.config.listPositions || true == Train->occupied->air.compressor.config.listWraps) + { + // active light preset is stored as value in range 1-LigthPosNo + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.ListPosition() < Train->occupied->air.compressor.config.listPositions ? Train->occupied->air.compressor.ListPosition() + 1 : 1); // wrap mode + // visual feedback + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_compressorpresetactivateprevious(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->air.compressor.config.listPositions == 0) + { + return; + } + if (Command.action != GLFW_PRESS) + { + return; + } // one change per key press + + if (Train->ggCompressorListButton.type() == TGaugeType::push) + { + // impulse switch toggles only between positions 'default' and 'default+1' + return; + } + + if (Train->occupied->air.compressor.ListPosition() > 1 || true == Train->occupied->air.compressor.config.listWraps) + { + // active light preset is stored as value in range 1-LigthPosNo + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.ListPosition() > 1 ? Train->occupied->air.compressor.ListPosition() - 1 : Train->occupied->air.compressor.config.listPositions); // wrap mode + + // visual feedback + if (Train->ggCompressorListButton.SubModel != nullptr) + { + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_compressorpresetactivatedefault(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->air.compressor.config.listPositions == 0) + { + return; + } + if (Command.action != GLFW_PRESS) + { + return; + } // one change per key press + + Train->occupied->ChangeCompressorPreset(Train->occupied->air.compressor.config.listDefaultPosition); + + // visual feedback + if (Train->ggCompressorListButton.SubModel != nullptr) + { + Train->ggCompressorListButton.UpdateValue(static_cast(Train->occupied->air.compressor.ListPosition() - 1), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_motorblowerstogglefront(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_motorblowersenablefront(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->controlled->MotorBlowers[VehicleEnd::front].is_enabled) + { + // turn on + OnCommand_motorblowersenablefront(Train, Command); + } + else + { + // turn off + OnCommand_motorblowersdisablefront(Train, Command); + } + } +} + +void TTrain::OnCommand_motorblowersenablefront(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::front); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::front); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(1.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + } + } +} + +void TTrain::OnCommand_motorblowersdisablefront(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersFrontButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersFrontButton.UpdateValue(0.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + } + } +} + +void TTrain::OnCommand_motorblowerstogglerear(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no off button so we always try to turn it on + OnCommand_motorblowersenablerear(Train, Command); + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->controlled->MotorBlowers[VehicleEnd::rear].is_enabled) + { + // turn on + OnCommand_motorblowersenablerear(Train, Command); + } + else + { + // turn off + OnCommand_motorblowersdisablerear(Train, Command); + } + } +} + +void TTrain::OnCommand_motorblowersenablerear(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::rear); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::rear); + } + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(true, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); + } + } +} + +void TTrain::OnCommand_motorblowersdisablerear(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersRearButton.type() == TGaugeType::push) + { + // impulse switch + // currently there's no disable return type switch + return; + } + else + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitch(false, VehicleEnd::rear); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); + } + } +} + +void TTrain::OnCommand_motorblowersdisableall(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggMotorBlowersAllOffButton.type() == TGaugeType::push) + { + // impulse switch + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggMotorBlowersAllOffButton.UpdateValue(1.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggMotorBlowersAllOffButton.UpdateValue(0.f, Train->dsbSwitch); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); + } + } + else + { + // two-state switch, only cares about press events + // NOTE: generally this switch doesn't come in two-state form + if (Command.action == GLFW_PRESS) + { + if (Train->ggMotorBlowersAllOffButton.GetDesiredValue() < 0.5f) + { + // switch is off, activate + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(true, VehicleEnd::rear); + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(1.f, Train->dsbSwitch); + } + else + { + // deactivate + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::front); + Train->controlled->MotorBlowersSwitchOff(false, VehicleEnd::rear); + // visual feedback + Train->ggMotorBlowersRearButton.UpdateValue(0.f, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_coolingfanstoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + Train->controlled->SetRVentForceOn(!Train->controlled->RVentForceOn()); +} diff --git a/vehicle/cab/brakecommands.cpp b/vehicle/cab/brakecommands.cpp new file mode 100644 index 000000000..afb3a6fd4 --- /dev/null +++ b/vehicle/cab/brakecommands.cpp @@ -0,0 +1,943 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the brakes: the independent, the train, the manual and the spring brake handles, the sand + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_independentbrakeincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + // when SplitEDPneumaticBrake is active the local brake key always operates + // the pneumatic local brake directly, never piggy-backing on the joint controller + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos() > 0) + { + OnCommand_mastercontrollerdecrease(Train, Command); + } + else + { + Train->occupied->IncLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); + if (useStepped) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakeincreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->MainCtrlPos() > 0) + { + OnCommand_mastercontrollerdecreasefast(Train, Command); + } + else + { + Train->occupied->IncLocalBrakeLevel(LocalBrakePosNo); + if (useJointAnim) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakedecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + auto const useStepped{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake + // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba + // TODO: sort AI out so it doesn't do things it doesn't have equipment for + || Train->occupied->brakes.IndependentPosition() > 0) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.IndependentPosition() == 0.0) + { + OnCommand_mastercontrollerincrease(Train, Command); + } + else + { + Train->occupied->DecLocalBrakeLevel(useStepped ? 1 : static_cast(Global.brake_speed * Command.time_delta * LocalBrakePosNo)); + if (useStepped) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakedecreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + auto const useJointAnim{Train->ggJointCtrl.SubModel != nullptr && !splitMode}; + if (Train->occupied->brakes.config.localKind != TLocalBrake::ManualBrake + // Ra 1014-06: AI potrafi zahamować pomocniczym mimo jego braku - odhamować jakoś trzeba + // TODO: sort AI out so it doesn't do things it doesn't have equipment for + || Train->occupied->brakes.IndependentPosition() > 0) + { + if (false == splitMode && Train->ggJointCtrl.SubModel != nullptr && Train->occupied->brakes.IndependentPosition() == 0.0) + { + OnCommand_mastercontrollerincreasefast(Train, Command); + } + else + { + Train->occupied->DecLocalBrakeLevel(LocalBrakePosNo); + if (useJointAnim) + { + Train->m_mastercontrollerinuse = true; + } + } + } + } +} + +void TTrain::OnCommand_independentbrakeset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + Train->occupied->brakes.SetIndependentPosition(std::clamp(Command.param1, 0.0, 1.0)); + } + /* + Train->controlled->LocalBrakePos = ( + std::round( + interpolate( + 0.0, + LocalBrakePosNo, + clamp( + Command.param1, + 0.0, 1.0 ) ) ) ); + */ +} + +void TTrain::OnCommand_independentbrakebailoff(TTrain *Train, command_data const &Command) +{ + + if (false == Command.freefly) + { + // TODO: check if this set of conditions can be simplified. + // it'd be more flexible to have an attribute indicating whether bail off position is supported + if (Train->controlled->TrainType() != train_type::emu && + (Train->controlled->EngineType == TEngineType::ElectricSeriesMotor || Train->controlled->EngineType == TEngineType::DieselElectric || + Train->controlled->EngineType == TEngineType::ElectricInductionMotor) && + Train->occupied->brakes.config.handlePositions > 0) + { + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggReleaserButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->occupied->BrakeReleaser(1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggReleaserButton.UpdateValue(0.0, Train->dsbSwitch); + + Train->occupied->BrakeReleaser(0); + } + } + } + else + { + // car brake handling, while in walk mode + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle != nullptr) + { + if (Command.action == GLFW_PRESS) + { + // press or hold + vehicle->physics->BrakeReleaser(1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + vehicle->physics->BrakeReleaser(0); + } + } + } +} + +void TTrain::OnCommand_universalbrakebutton1(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggUniveralBrakeButton1.UpdateValue(1.0, Train->dsbSwitch); + + Train->occupied->UniversalBrakeButton(0, 1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggUniveralBrakeButton1.UpdateValue(0.0, Train->dsbSwitch); + + Train->occupied->UniversalBrakeButton(0, 0); + } +} + +void TTrain::OnCommand_universalbrakebutton2(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggUniveralBrakeButton2.UpdateValue(1.0, Train->dsbSwitch); + + Train->occupied->UniversalBrakeButton(1, 1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggUniveralBrakeButton2.UpdateValue(0.0, Train->dsbSwitch); + + Train->occupied->UniversalBrakeButton(1, 0); + } +} + +void TTrain::OnCommand_universalbrakebutton3(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold + // visual feedback + Train->ggUniveralBrakeButton3.UpdateValue(1.0, Train->dsbSwitch); + + Train->occupied->UniversalBrakeButton(2, 1); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggUniveralBrakeButton3.UpdateValue(0.0, Train->dsbSwitch); + + Train->occupied->UniversalBrakeButton(2, 0); + } +} + +void TTrain::OnCommand_trainbrakeincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_REPEAT && Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(Global.brake_speed * Command.time_delta * Train->occupied->brakes.config.handlePositions); + else if (Command.action == GLFW_PRESS && Train->occupied->brakes.config.driverValveType != TBrakeHandle::FV4a) + Train->set_train_brake(Train->occupied->brakes.HandlePositionSmooth() + Global.fBrakeStep); +} + +void TTrain::OnCommand_trainbrakedecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_REPEAT && Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + Train->occupied->BrakeLevelAdd(-Global.brake_speed * Command.time_delta * Train->occupied->brakes.config.handlePositions); + else if (Command.action == GLFW_PRESS && Train->occupied->brakes.config.driverValveType != TBrakeHandle::FV4a) + Train->set_train_brake(Train->occupied->brakes.HandlePositionSmooth() - Global.fBrakeStep); + else if (Command.action == GLFW_RELEASE) + { + // release + Train->zero_charging_train_brake(); + } +} + +void TTrain::OnCommand_trainbrakeset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // press or hold + Train->occupied->BrakeLevelSet(std::lerp(Train->occupied->brakes.driverValve->GetPos(bh_MIN), Train->occupied->brakes.driverValve->GetPos(bh_MAX), std::clamp(Command.param1, 0.0, 1.0))); + } + else + { + // release + Train->zero_charging_train_brake(); + } +} + +void TTrain::OnCommand_trainbrakecharging(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // press or hold + Train->set_train_brake(-1); + } + else + { + // release + Train->zero_charging_train_brake(); + } +} + +void TTrain::OnCommand_trainbrakerelease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(0); + } +} + +void TTrain::OnCommand_trainbrakefirstservice(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(1); + } +} + +void TTrain::OnCommand_trainbrakeservice(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->occupied->brakes.config.handlePositions / 2 + (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a ? 1 : 0)); + } +} + +void TTrain::OnCommand_trainbrakefullservice(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->occupied->brakes.config.handlePositions - 1); + } +} + +void TTrain::OnCommand_trainbrakehandleoff(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->occupied->brakes.driverValve->GetPos(bh_NP)); + } +} + +void TTrain::OnCommand_trainbrakeemergency(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->set_train_brake(Train->occupied->brakes.driverValve->GetPos(bh_EB)); + /* + if( Train->occupied->BrakeCtrlPosNo <= 0.1 ) { + // hamulec bezpieczeństwa dla wagonów + Train->occupied->SetRadioStopFlag(true); + } + */ + } +} + +void TTrain::OnCommand_trainbrakebasepressureincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + { + Train->occupied->brakes.SetHandleCapPosition(std::clamp(Train->occupied->brakes.HandleCapPosition() - 0.01, -1.5, 2.0)); + } + else + { + Train->occupied->BrakeLevelAdd(0.01); + } + } +} + +void TTrain::OnCommand_trainbrakebasepressuredecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + { + Train->occupied->brakes.SetHandleCapPosition(std::clamp(Train->occupied->brakes.HandleCapPosition() + 0.01, -1.5, 2.0)); + } + else + { + Train->occupied->BrakeLevelAdd(-0.01); + } + } +} + +void TTrain::OnCommand_trainbrakebasepressurereset(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->occupied->brakes.SetHandleCapPosition(0); + } +} + +void TTrain::OnCommand_trainbrakeoperationtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + vehicle->physics->brakes.distributor->SetBrakeStatus(vehicle->physics->brakes.distributor->GetBrakeStatus() ^ b_dmg); + // the brake is the player's now, the wagon inspector won't put it back on its own + vehicle->physics->ClaimBrakeCutOut(); + } +} + +void TTrain::OnCommand_manualbrakeincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if (vehicle->physics->brakes.config.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.config.hasHandBrake == true) + { + + vehicle->physics->IncManualBrakeLevel(1); + } + } +} + +void TTrain::OnCommand_manualbrakedecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if (vehicle->physics->brakes.config.localKind == TLocalBrake::ManualBrake || vehicle->physics->brakes.config.hasHandBrake == true) + { + + vehicle->physics->DecManualBrakeLevel(1); + } + } +} + +void TTrain::OnCommand_alarmchaintoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + if (false == Train->occupied->brakes.alarmChain) + { + OnCommand_alarmchainenable(Train, Command); + } + else + { + OnCommand_alarmchaindisable(Train, Command); + } + } +} + +void TTrain::OnCommand_alarmchainenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + + // pull + Train->occupied->AlarmChainSwitch(true); + // visual feedback + Train->ggAlarmChain.UpdateValue(1.0); + } +} + +void TTrain::OnCommand_alarmchaindisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + + // release + Train->occupied->AlarmChainSwitch(false); + // visual feedback + Train->ggAlarmChain.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_wheelspinbrakeactivate(TTrain *Train, command_data const &Command) +{ + + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + if (Train->ggAntiSlipButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Wheelspin Brake button is missing, or wasn't defined"); + } + return; + } + + if (Train->occupied->brakes.config.kind != TBrakeSystem::ElectroPneumatic) + { + // standard behaviour + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbSwitch); + + // NOTE: system activation is (repeatedly) done in the train update routine + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(0.0); + } + } + else + { + // electro-pneumatic, custom case + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(1.0, Train->dsbPneumaticSwitch); + + // the EP fuse is the cab car's (Ctrl+Z switches occupied's), checked by SwitchEPBrake with the rest of + // the control's supply + if (Train->occupied->brakes.config.driverValveType == TBrakeHandle::St113) + { + Train->occupied->SwitchEPBrake(1); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggAntiSlipButton.UpdateValue(0.0); + + Train->occupied->SwitchEPBrake(0); + } + } +} + +void TTrain::OnCommand_sandboxactivate(TTrain *Train, command_data const &Command) +{ + + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + if (Train->ggSandButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Sandbox activation button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggSandButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->controlled->SandboxManual(true); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggSandButton.UpdateValue(0.0); + + Train->controlled->SandboxManual(false); + } +} + +void TTrain::OnCommand_autosandboxtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->occupied->SandDoseAutoAllow) + { + // turn on + OnCommand_autosandboxactivate(Train, Command); + } + else + { + // turn off + OnCommand_autosandboxdeactivate(Train, Command); + } + } +}; + +void TTrain::OnCommand_autosandboxactivate(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SandboxAutoAllow(true); + Train->ggAutoSandButton.UpdateValue(1.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_autosandboxdeactivate(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SandboxAutoAllow(false); + Train->ggAutoSandButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_epbrakecontrolenable(TTrain *Train, command_data const &Command) +{ + auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; + // command only works for bistable switch + if (Command.action == GLFW_PRESS && istoggle) + { + if (Train->occupied->EpFuseSwitch(true)) + { + // audio feedback + if (Train->dsbPneumaticSwitch) + { + Train->dsbPneumaticSwitch->play(); + } + Train->ggEPFuseButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_epbrakecontroldisable(TTrain *Train, command_data const &Command) +{ + auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; + // command only works for bistable switch + if (Command.action == GLFW_PRESS && istoggle) + { + if (Train->occupied->EpFuseSwitch(false)) + { + Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_epbrakecontroltoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + auto const ispush{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::push)) != 0}; + auto const istoggle{(static_cast(Train->ggEPFuseButton.type()) & static_cast(TGaugeType::toggle)) != 0}; + + if (Command.action == GLFW_PRESS) + { + if (istoggle) + { + // switch state + if (false == Train->occupied->EpFuse()) + { + // turn on + // audio feedback + if (Train->occupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) + { + Train->dsbPneumaticSwitch->play(); + } + } + else + { + // turn off + Train->occupied->EpFuseSwitch(false); + } + } + else if (ispush) + { + // potentially turn on + // audio feedback + if (Train->occupied->EpFuseSwitch(true) && Train->dsbPneumaticSwitch) + { + Train->dsbPneumaticSwitch->play(); + } + } + // visual feedback + Train->ggEPFuseButton.UpdateValue(ispush ? 1.0f : // push or pushtoggle + Train->occupied->EpFuse() ? 1.0f : + 0.0f, // toggle + Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE && ispush) + { + // return the switch to neutral position + Train->ggEPFuseButton.UpdateValue(0.0f, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_trainbrakeoperationmodeincrease(TTrain *Train, command_data const &Command) +{ + + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode << 1 & Train->occupied->brakes.config.availableOperatingModes) != 0) + { + // next mode + Train->occupied->brakes.operatingMode <<= 1; + // visual feedback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->brakes.operatingMode > 0 ? static_cast(std::log2(Train->occupied->brakes.operatingMode)) : 0); // audio fallback + } +} + +void TTrain::OnCommand_trainbrakeoperationmodedecrease(TTrain *Train, command_data const &Command) +{ + + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action == GLFW_PRESS && (Train->occupied->brakes.operatingMode >> 1 & Train->occupied->brakes.config.availableOperatingModes) != 0) + { + // previous mode + Train->occupied->brakes.operatingMode >>= 1; + // visual feedback + Train->ggBrakeOperationModeCtrl.UpdateValue(Train->occupied->brakes.operatingMode > 0 ? static_cast(std::log2(Train->occupied->brakes.operatingMode)) : 0); + } +} + +void TTrain::OnCommand_brakeactingspeedincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if ((vehicle->physics->brakes.delaySetting & bdelay_M) != 0) + { + // can't speed it up any more than this + return; + } + auto const fasterbrakesetting = vehicle->physics->brakes.delaySetting < bdelay_R ? vehicle->physics->brakes.delaySetting << 1 : vehicle->physics->brakes.delaySetting | bdelay_M; + + Train->set_train_brake_speed(vehicle, fasterbrakesetting); + } +} + +void TTrain::OnCommand_brakeactingspeeddecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + if (vehicle->physics->brakes.delaySetting == bdelay_G) + { + // can't slow it down any more than this + return; + } + auto const slowerbrakesetting = vehicle->physics->brakes.delaySetting < bdelay_M ? vehicle->physics->brakes.delaySetting >> 1 : vehicle->physics->brakes.delaySetting ^ bdelay_M; + + Train->set_train_brake_speed(vehicle, slowerbrakesetting); + } +} + +void TTrain::OnCommand_brakeactingspeedsetcargo(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + Train->set_train_brake_speed(vehicle, bdelay_G); + } +} + +void TTrain::OnCommand_brakeactingspeedsetpassenger(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + Train->set_train_brake_speed(vehicle, bdelay_P); + } +} + +void TTrain::OnCommand_brakeactingspeedsetrapid(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle == nullptr) + { + return; + } + + Train->set_train_brake_speed(vehicle, bdelay_R); + } +} + +void TTrain::OnCommand_brakeloadcompensationincrease(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle != nullptr) + { + vehicle->physics->IncBrakeMult(); + } + } +} + +void TTrain::OnCommand_brakeloadcompensationdecrease(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + auto *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; + if (vehicle != nullptr) + { + vehicle->physics->DecBrakeMult(); + } + } +} + +void TTrain::OnCommand_mubrakingindicatortoggle(TTrain *Train, command_data const &Command) +{ + + if (Train->ggSignallingButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Braking Indicator switch is missing, or wasn't defined"); + } + return; + } + if (Train->controlled->TrainType() != train_type::emu) + { + // + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->controlled->Signalling()) + { + // turn on + Train->controlled->SetSignalling(true); + // visual feedback + Train->ggSignallingButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // turn off + Train->controlled->SetSignalling(false); + // visual feedback + Train->ggSignallingButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} diff --git a/vehicle/cab/cab.cpp b/vehicle/cab/cab.cpp new file mode 100644 index 000000000..1d3192f30 --- /dev/null +++ b/vehicle/cab/cab.cpp @@ -0,0 +1,235 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the cab: its gauges, its buttons, the mapping of the controls, the screens it has + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + +void control_mapper::clear() +{ + + *this = control_mapper(); +} + +void control_mapper::insert(TGauge const &Gauge, std::string const &Label) +{ + + if (Gauge.SubModel != nullptr) + { + m_controlnames.try_emplace(Gauge.SubModel, Label); + } + if (Gauge.SubModelOn != nullptr) + { + m_controlnames.try_emplace(Gauge.SubModelOn, Label); + } + // the duplicate submodels of a control (duplicate: yes) work the control as well (eu07/maszyna#527) + for (auto const &mirror : Gauge.mirrors()) + { + insert(mirror, Label); + } + + m_names.emplace(Label); +} + +std::string control_mapper::find(TSubModel const *Control) const +{ + + auto const lookup = m_controlnames.find(Control); + if (lookup != m_controlnames.end()) + { + return lookup->second; + } + else + { + return ""; + } +} + +bool control_mapper::contains(std::string const &Control) const +{ + + return m_names.contains(Control); +} + +void TTrain::screen_entry::deserialize(cParser &Input) +{ + + while (true == deserialize_mapping(Input)) + { + // all work done by while() + } +} + +bool TTrain::screen_entry::deserialize_mapping(cParser &Input) +{ + // token can be a key or block end + auto const key{Input.getToken(true, "\n\r\t ,;[]")}; + + if (true == key.empty() || key == "}") + { + return false; + } + + if (key == "{") + { + script = Input.getToken(); + } + else if (key == "target:") + { + target = Input.getToken(); + } + else if (key == "updatetime:") + { + updatetime = Input.getToken(); + } + else if (key == "parameters:") + { + parameters = dictionary_source(Input.getToken()); + } + else + { + // HACK: we expect this to be true only if the screen entry doesn't start with a { which means legacy configuration format + target = key; + script = Input.getToken(); + return false; + } + + return true; +} + +void TCab::Load(cParser &Parser) +{ + // NOTE: clearing control tables here is bit of a crutch, imposed by current scheme of loading compartments anew on each cab change + ggList.clear(); + btList.clear(); + + std::string token; + Parser.getTokens(); + Parser >> token; + if (token == "cablight:") + { + Parser.getTokens(9, false); + /* + Parser + >> dimm.r + >> dimm.g + >> dimm.b + >> intlit.r + >> intlit.g + >> intlit.b + >> intlitlow.r + >> intlitlow.g + >> intlitlow.b; + */ + Parser.getTokens(); + Parser >> token; + } + CabPos1.x = static_cast(std::stod(token)); + Parser.getTokens(5, false); + Parser >> CabPos1.y >> CabPos1.z >> CabPos2.x >> CabPos2.y >> CabPos2.z; + + bEnabled = true; + bOccupied = true; +} + +TGauge &TCab::Gauge(int n) +{ // pobranie adresu obiektu aniomowanego ruchem + /* + if (n < 0) + { // rezerwacja wolnego + ggList[iGauges].Clear(); + return ggList + iGauges++; + } + else if (n < iGauges) + return ggList + n; + return NULL; + */ + if (n < 0) + { + ggList.emplace_back(); + return ggList.back(); + } + else + { + return ggList[n]; + } +}; + +TButton &TCab::Button(int n) +{ // pobranie adresu obiektu animowanego wyborem 1 z 2 + /* + if (n < 0) + { // rezerwacja wolnego + return btList + iButtons++; + } + else if (n < iButtons) + return btList + n; + return NULL; + */ + if (n < 0) + { + btList.emplace_back(); + return btList.back(); + } + else + { + return btList[n]; + } +}; + +void TCab::Update(bool const Power) +{ // odczyt parametrów i ustawienie animacji submodelom + for (auto &gauge : ggList) + { + // animacje izometryczne + gauge.UpdateValue(); // odczyt parametru i przeliczenie na kąt + gauge.Update(); // ustawienie animacji + } + + for (auto &button : btList) + { + // animacje dwustanowe + button.Update(Power); // odczyt parametru i wybór submodelu + } +}; diff --git a/vehicle/cab/cabcommands.cpp b/vehicle/cab/cabcommands.cpp new file mode 100644 index 000000000..b51c7a03d --- /dev/null +++ b/vehicle/cab/cabcommands.cpp @@ -0,0 +1,650 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the cab itself: the reverser, the battery, its activation, changing it + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_wiperswitchincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->occupied->SetWiperSwitchPos(Train->occupied->WiperSwitchPos() + 1); + if (Train->occupied->WiperSwitchPos() > Train->occupied->WiperListSize - 1) + Train->occupied->SetWiperSwitchPos(Train->occupied->WiperListSize - 1); + + // Visual feedback + Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->WiperSwitchPos()), Train->dsbSwitch); + } +} +void TTrain::OnCommand_wiperswitchdecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->occupied->SetWiperSwitchPos(Train->occupied->WiperSwitchPos() - 1); + if (Train->occupied->WiperSwitchPos() < 0) + Train->occupied->SetWiperSwitchPos(0); + + // visual feedback + Train->ggWiperSw.UpdateValue(static_cast(Train->occupied->WiperSwitchPos()), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_reverserincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->controlled->EIMDirectionChangeAllow()) + { + return; + } + + // aktualizacja skrajnych pojazdów w składzie + if (Train->occupied->DirectionForward() && Train->occupied->DirActive && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } +} + +void TTrain::OnCommand_reverserdecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->controlled->EIMDirectionChangeAllow()) + { + return; + } + + // aktualizacja skrajnych pojazdów w składzie + if (Train->occupied->DirectionBackward() && Train->occupied->DirActive && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } +} + +void TTrain::OnCommand_reverserforwardhigh(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->controlled->EIMDirectionChangeAllow()) + { + return; + } + + // HACK: try to move the reverser one position back, in case it's set to "high forward" + OnCommand_reverserdecrease(Train, Command); + + if (Train->occupied->DirActive < 1) + { + + while (Train->occupied->DirActive < 1 && true == Train->occupied->DirectionForward()) + { + // all work is done in the header + } + // aktualizacja skrajnych pojazdów w składzie + if (Train->occupied->DirActive == 1 && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } + OnCommand_reverserincrease(Train, Command); + } +} + +void TTrain::OnCommand_reverserforward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->controlled->EIMDirectionChangeAllow()) + { + return; + } + + // HACK: try to move the reverser one position back, in case it's set to "high forward" + // OnCommand_reverserdecrease( Train, Command ); + // visual feedback + Train->ggDirForwardButton.UpdateValue(1.0, Train->dsbSwitch); + + if (Train->occupied->DirActive == 0) + { + + while (Train->occupied->DirActive < 1 && true == Train->occupied->DirectionForward()) + { + // all work is done in the header + } + // aktualizacja skrajnych pojazdów w składzie + if (Train->occupied->DirActive == 1 && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggDirForwardButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_reverserneutral(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->controlled->EIMDirectionChangeAllow()) + { + return; + } + // visual feedback + Train->ggDirNeutralButton.UpdateValue(1.0, Train->dsbSwitch); + while (Train->occupied->DirActive < 0 && true == Train->occupied->DirectionForward()) + { + // all work is done in the header + } + while (Train->occupied->DirActive > 0 && true == Train->occupied->DirectionBackward()) + { + // all work is done in the header + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggDirNeutralButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_reverserbackward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + // HACK: master controller position isn't set in occupied vehicle in E(D)MUs + // so we do a manual check in relevant vehicle here + if (false == Train->controlled->EIMDirectionChangeAllow()) + { + return; + } + Train->ggDirBackwardButton.UpdateValue(1.0, Train->dsbSwitch); + if (Train->occupied->DirActive == 0) + { + + while (Train->occupied->DirActive > -1 && true == Train->occupied->DirectionBackward()) + { + // all work is done in the header + } + // aktualizacja skrajnych pojazdów w składzie + if (Train->occupied->DirActive == -1 && Train->DynamicObject->Mechanik) + { + + Train->DynamicObject->Mechanik->DirectionChange(); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggDirBackwardButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_alerteracknowledge(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggSecurityResetButton.UpdateValue(1.0, Train->dsbSwitch); + + if (Train->occupied->TrainType() == train_type::emu || Train->occupied->DirActive != 0) + Train->occupied->SecuritySystem.acknowledge_press(); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggSecurityResetButton.UpdateValue(0.0); + + if (Train->occupied->TrainType() == train_type::emu || Train->occupied->DirActive != 0) + Train->occupied->SecuritySystem.acknowledge_release(); + } +} + +void TTrain::OnCommand_cabsignalacknowledge(TTrain *Train, command_data const &Command) +{ + // TODO: visual feedback + if (Command.action == GLFW_PRESS) + { + if (Train->occupied->SecuritySystem.has_separate_acknowledge()) + { + Train->occupied->SecuritySystem.cabsignal_reset(); + Train->ggSHPResetButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + Train->ggSHPResetButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_batterytoggle(TTrain *Train, command_data const &Command) +{ + if (Train->allowBatteryToggle || Command.action != GLFW_REPEAT) + { + // keep the switch from flipping back and forth if key is held down + if (false == Train->occupied->lowVoltage.Is24vAvailable()) + { + // turn on + OnCommand_batteryenable(Train, Command); + } + else + { + // turn off + OnCommand_batterydisable(Train, Command); + } + } +} + +void TTrain::OnCommand_batteryenable(TTrain *Train, command_data const &Command) +{ + if (!Train->occupied->lowVoltage.config.batteryButtonImpulse) + { // regular button behavior + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); + + Train->occupied->BatterySwitch(true); + Train->allowBatteryToggle = false; + // side-effects + if (Train->occupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->ggBatteryButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggBatteryButton.UpdateValue(0.5f); + } + Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->allowBatteryToggle = true; + } + } + else // impulse button behavior + { + if (Command.action == GLFW_PRESS) + { + if (Train->occupied->lowVoltage.config.batteryButtonHeld) + { + // jesli przycisk trzeba przytrzymac + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->fBatteryTimer = Train->occupied->lowVoltage.config.batteryButtonHoldTime; // start timer + } + else + { + // jesli przycisk dziala od razu + Train->occupied->BatterySwitch(true); + Train->allowBatteryToggle = false; + // side-effects + if (Train->occupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + + // visual feedback + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->ggBatteryOnButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->fBatteryTimer = -1.f; // + Train->allowBatteryToggle = true; + Train->batteryButtonFired = false; + } + else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.config.batteryButtonHeld) + { + // trzymamy przycisk + if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.IsBatteryOn() == false && !Train->batteryButtonFired) + { + Train->occupied->BatterySwitch(true); + Train->batteryButtonFired = true; + + // side-effects + if (Train->occupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + Train->allowBatteryToggle = false; + } + } + } +} + +void TTrain::OnCommand_batterydisable(TTrain *Train, command_data const &Command) +{ + if (!Train->occupied->lowVoltage.config.batteryButtonImpulse) + { // regular button behavior + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); + + Train->occupied->BatterySwitch(false); + + // side-effects + if (Train->occupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->ggBatteryButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggBatteryButton.UpdateValue(0.5f); + } + Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } + else // impulse button behavior + { + if (Command.action == GLFW_PRESS) + { + if (Train->occupied->lowVoltage.config.batteryButtonHeld) + { + // jesli przycisk trzeba przytrzymac + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->fBatteryTimer = Train->occupied->lowVoltage.config.batteryButtonHoldTime; // start timer + } + else + { + // jesli przycisk dziala od razu + Train->occupied->BatterySwitch(false); + Train->allowBatteryToggle = false; + + // side-effects + if (Train->occupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + // visual feedback + Train->ggBatteryButton.UpdateValue(1.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggBatteryButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->ggBatteryOffButton.UpdateValue(0.0f, Train->dsbSwitch); + Train->allowBatteryToggle = true; + Train->batteryButtonFired = false; + } + else if (Command.action == GLFW_REPEAT && Train->occupied->lowVoltage.config.batteryButtonHeld) + { + // trzymamy przycisk + if (Train->fBatteryTimer <= 0.0 && Train->occupied->lowVoltage.IsBatteryOn() == true && !Train->batteryButtonFired) + { + Train->occupied->BatterySwitch(false); + Train->batteryButtonFired = true; + + // side-effects + if (Train->occupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + Train->allowBatteryToggle = false; + } + } + } +} + +void TTrain::OnCommand_cabactivationtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_REPEAT) + { + // keep the switch from flipping back and forth if key is held down + if (0 == Train->occupied->CabActive) + { + // turn on + OnCommand_cabactivationenable(Train, Command); + } + else + { + // turn off + OnCommand_cabactivationdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_cabactivationenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (Train->ggCabActivationButton.type() == TGaugeType::push) + { + Train->ggCabActivationButton.UpdateValue(1.0f, Train->dsbSwitch); + } + + Train->occupied->CabActivisation(); + + // side-effects + if (Train->occupied->LightsPosNo > 0) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggCabActivationButton.UpdateValue(0.5f); + } +} + +void TTrain::OnCommand_cabactivationdisable(TTrain *Train, command_data const &Command) +{ + // TBD, TODO: ewentualnie zablokować z FIZ, np. w samochodach się nie odłącza akumulatora + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (Train->ggCabActivationButton.type() == TGaugeType::push) + { + Train->ggCabActivationButton.UpdateValue(0.0f, Train->dsbSwitch); + } + + Train->occupied->CabDeactivisation(); + if (Train->occupied->LightsPosNo > 0 && Train->occupied->InactiveCabFlag & activation::redmarkers) + { + Train->Dynamic()->SetLights(); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggCabActivationButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->ggCabActivationButton.UpdateValue(0.5f); + } +} + +void TTrain::OnCommand_cabchangeforward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (auto const movedirection{1}; false == Train->CabChange(movedirection)) + { + auto const exitdirection{(movedirection > 0 ? VehicleEnd::front : VehicleEnd::rear)}; + if (Train->occupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) + { + // przejscie do nastepnego pojazdu + auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); + targetvehicle->physics->SetCabOccupied(Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1); + Train->MoveToVehicle(targetvehicle); + } + } + // HACK: match consist door permit state with the preset in the active cab + if (Train->ggDoorPermitPresetButton.SubModel != nullptr) + { + Train->occupied->ChangeDoorPermitPreset(0); + } + // HACK: update lights state + if (Train->occupied->LightsPosNo > 0) + { + Train->DynamicObject->SetLights(); + } + } +} + +void TTrain::OnCommand_cabchangebackward(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (auto const movedirection{-1}; false == Train->CabChange(movedirection)) + { + // current vehicle doesn't extend any farther in this direction, check if we there's one connected we can move to + auto const exitdirection{(movedirection > 0 ? VehicleEnd::front : VehicleEnd::rear)}; + if (Train->occupied->Couplers[exitdirection].CouplingFlag.HasAll(Coupling::gangway)) + { + // przejscie do nastepnego pojazdu + auto *targetvehicle = exitdirection == VehicleEnd::front ? Train->DynamicObject->PrevConnected() : Train->DynamicObject->NextConnected(); + targetvehicle->physics->SetCabOccupied(Train->occupied->Neighbours[exitdirection].vehicle_end ? -1 : 1); + Train->MoveToVehicle(targetvehicle); + } + } + // HACK: match consist door permit state with the preset in the active cab + if (Train->ggDoorPermitPresetButton.SubModel != nullptr) + { + Train->occupied->ChangeDoorPermitPreset(0); + } + // HACK: update lights state + if (Train->occupied->LightsPosNo > 0) + { + Train->DynamicObject->SetLights(); + } + } +} + +void TTrain::OnCommand_vehiclemoveforwards(TTrain *Train, const command_data &Command) +{ + if (Command.action == GLFW_RELEASE || !DebugModeFlag) + return; + + Train->DynamicObject->move_set(100.0); +} + +void TTrain::OnCommand_vehiclemovebackwards(TTrain *Train, const command_data &Command) +{ + if (Command.action == GLFW_RELEASE || !DebugModeFlag) + return; + + Train->DynamicObject->move_set(-100.0); +} + +void TTrain::OnCommand_vehicleboost(TTrain *Train, const command_data &Command) +{ + if (Command.action == GLFW_RELEASE || !DebugModeFlag) + return; + + double boost = Command.param1 != 0.0 ? Command.param1 : 2.78; + + if (Train->DynamicObject == nullptr) + { + return; + } + + auto *vehicle{Train->DynamicObject}; + while (vehicle) + { + vehicle->physics->SetV(vehicle->physics->V() + vehicle->DirectionGet() * boost); + vehicle = vehicle->Next(); // pozostałe też + } + vehicle = Train->DynamicObject->Prev(); + while (vehicle) + { + vehicle->physics->SetV(vehicle->physics->V() + vehicle->DirectionGet() * boost); + vehicle = vehicle->Prev(); // w drugą stronę też + } +} diff --git a/vehicle/cab/commandtable.cpp b/vehicle/cab/commandtable.cpp new file mode 100644 index 000000000..76908fcd5 --- /dev/null +++ b/vehicle/cab/commandtable.cpp @@ -0,0 +1,455 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the handlers of the commands of the cab + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// NOTE: we're currently using universal handlers and static handler map but it may be beneficial to have these implemented on individual class instance basis +// TBD, TODO: consider this approach if we ever want to have customized consist behaviour to received commands, based on the consist/vehicle type or whatever +TTrain::commandhandler_map const TTrain::m_commandhandlers = { + + {user_command::aidriverenable, &TTrain::OnCommand_aidriverenable}, + {user_command::aidriverdisable, &TTrain::OnCommand_aidriverdisable}, + {user_command::jointcontrollerset, &TTrain::OnCommand_jointcontrollerset}, + {user_command::mastercontrollerincrease, &TTrain::OnCommand_mastercontrollerincrease}, + {user_command::mastercontrollerincreasefast, &TTrain::OnCommand_mastercontrollerincreasefast}, + {user_command::mastercontrollerdecrease, &TTrain::OnCommand_mastercontrollerdecrease}, + {user_command::mastercontrollerdecreasefast, &TTrain::OnCommand_mastercontrollerdecreasefast}, + {user_command::mastercontrollerset, &TTrain::OnCommand_mastercontrollerset}, + {user_command::secondcontrollerincrease, &TTrain::OnCommand_secondcontrollerincrease}, + {user_command::secondcontrollerincreasefast, &TTrain::OnCommand_secondcontrollerincreasefast}, + {user_command::secondcontrollerdecrease, &TTrain::OnCommand_secondcontrollerdecrease}, + {user_command::secondcontrollerdecreasefast, &TTrain::OnCommand_secondcontrollerdecreasefast}, + {user_command::secondcontrollerset, &TTrain::OnCommand_secondcontrollerset}, + {user_command::dynamicbrakecontrollerincrease, &TTrain::OnCommand_DynamicBrakeControllerIncrease}, + {user_command::dynamicbrakecontrollerincreasefast, &TTrain::OnCommand_DynamicBrakeControllerIncreaseFast}, + {user_command::dynamicbrakecontrollerdecrease, &TTrain::OnCommand_DynamicBrakeControllerDecrease}, + {user_command::dynamicbrakecontrollerdecreasefast, &TTrain::OnCommand_DynamicBrakeControllerDecreaseFast}, + {user_command::dynamicbrakecontrollerset, &TTrain::OnCommand_DynamicBrakeControllerSet}, + {user_command::notchingrelaytoggle, &TTrain::OnCommand_notchingrelaytoggle}, + {user_command::tempomattoggle, &TTrain::OnCommand_tempomattoggle}, + {user_command::mucurrentindicatorothersourceactivate, &TTrain::OnCommand_mucurrentindicatorothersourceactivate}, + {user_command::independentbrakeincrease, &TTrain::OnCommand_independentbrakeincrease}, + {user_command::independentbrakeincreasefast, &TTrain::OnCommand_independentbrakeincreasefast}, + {user_command::independentbrakedecrease, &TTrain::OnCommand_independentbrakedecrease}, + {user_command::independentbrakedecreasefast, &TTrain::OnCommand_independentbrakedecreasefast}, + {user_command::independentbrakeset, &TTrain::OnCommand_independentbrakeset}, + {user_command::independentbrakebailoff, &TTrain::OnCommand_independentbrakebailoff}, + {user_command::universalbrakebutton1, &TTrain::OnCommand_universalbrakebutton1}, + {user_command::universalbrakebutton2, &TTrain::OnCommand_universalbrakebutton2}, + {user_command::universalbrakebutton3, &TTrain::OnCommand_universalbrakebutton3}, + {user_command::trainbrakeincrease, &TTrain::OnCommand_trainbrakeincrease}, + {user_command::trainbrakedecrease, &TTrain::OnCommand_trainbrakedecrease}, + {user_command::trainbrakeset, &TTrain::OnCommand_trainbrakeset}, + {user_command::trainbrakecharging, &TTrain::OnCommand_trainbrakecharging}, + {user_command::trainbrakerelease, &TTrain::OnCommand_trainbrakerelease}, + {user_command::trainbrakefirstservice, &TTrain::OnCommand_trainbrakefirstservice}, + {user_command::trainbrakeservice, &TTrain::OnCommand_trainbrakeservice}, + {user_command::trainbrakefullservice, &TTrain::OnCommand_trainbrakefullservice}, + {user_command::trainbrakehandleoff, &TTrain::OnCommand_trainbrakehandleoff}, + {user_command::trainbrakeemergency, &TTrain::OnCommand_trainbrakeemergency}, + {user_command::trainbrakebasepressureincrease, &TTrain::OnCommand_trainbrakebasepressureincrease}, + {user_command::trainbrakebasepressuredecrease, &TTrain::OnCommand_trainbrakebasepressuredecrease}, + {user_command::trainbrakebasepressurereset, &TTrain::OnCommand_trainbrakebasepressurereset}, + {user_command::trainbrakeoperationtoggle, &TTrain::OnCommand_trainbrakeoperationtoggle}, + {user_command::manualbrakeincrease, &TTrain::OnCommand_manualbrakeincrease}, + {user_command::manualbrakedecrease, &TTrain::OnCommand_manualbrakedecrease}, + {user_command::alarmchaintoggle, &TTrain::OnCommand_alarmchaintoggle}, + {user_command::alarmchainenable, &TTrain::OnCommand_alarmchainenable}, + {user_command::alarmchaindisable, &TTrain::OnCommand_alarmchaindisable}, + {user_command::wheelspinbrakeactivate, &TTrain::OnCommand_wheelspinbrakeactivate}, + {user_command::sandboxactivate, &TTrain::OnCommand_sandboxactivate}, + {user_command::autosandboxtoggle, &TTrain::OnCommand_autosandboxtoggle}, + {user_command::autosandboxactivate, &TTrain::OnCommand_autosandboxactivate}, + {user_command::autosandboxdeactivate, &TTrain::OnCommand_autosandboxdeactivate}, + {user_command::epbrakecontroltoggle, &TTrain::OnCommand_epbrakecontroltoggle}, + {user_command::epbrakecontrolenable, &TTrain::OnCommand_epbrakecontrolenable}, + {user_command::epbrakecontroldisable, &TTrain::OnCommand_epbrakecontroldisable}, + {user_command::trainbrakeoperationmodeincrease, &TTrain::OnCommand_trainbrakeoperationmodeincrease}, + {user_command::trainbrakeoperationmodedecrease, &TTrain::OnCommand_trainbrakeoperationmodedecrease}, + {user_command::brakeactingspeedincrease, &TTrain::OnCommand_brakeactingspeedincrease}, + {user_command::brakeactingspeeddecrease, &TTrain::OnCommand_brakeactingspeeddecrease}, + {user_command::brakeactingspeedsetcargo, &TTrain::OnCommand_brakeactingspeedsetcargo}, + {user_command::brakeactingspeedsetpassenger, &TTrain::OnCommand_brakeactingspeedsetpassenger}, + {user_command::brakeactingspeedsetrapid, &TTrain::OnCommand_brakeactingspeedsetrapid}, + {user_command::brakeloadcompensationincrease, &TTrain::OnCommand_brakeloadcompensationincrease}, + {user_command::brakeloadcompensationdecrease, &TTrain::OnCommand_brakeloadcompensationdecrease}, + {user_command::mubrakingindicatortoggle, &TTrain::OnCommand_mubrakingindicatortoggle}, + {user_command::reverserincrease, &TTrain::OnCommand_reverserincrease}, + {user_command::reverserdecrease, &TTrain::OnCommand_reverserdecrease}, + {user_command::reverserforwardhigh, &TTrain::OnCommand_reverserforwardhigh}, + {user_command::reverserforward, &TTrain::OnCommand_reverserforward}, + {user_command::reverserneutral, &TTrain::OnCommand_reverserneutral}, + {user_command::reverserbackward, &TTrain::OnCommand_reverserbackward}, + {user_command::alerteracknowledge, &TTrain::OnCommand_alerteracknowledge}, + {user_command::cabsignalacknowledge, &TTrain::OnCommand_cabsignalacknowledge}, + {user_command::batterytoggle, &TTrain::OnCommand_batterytoggle}, + {user_command::batteryenable, &TTrain::OnCommand_batteryenable}, + {user_command::batterydisable, &TTrain::OnCommand_batterydisable}, + {user_command::cabactivationtoggle, &TTrain::OnCommand_cabactivationtoggle}, + {user_command::cabactivationenable, &TTrain::OnCommand_cabactivationenable}, + {user_command::cabactivationdisable, &TTrain::OnCommand_cabactivationdisable}, + {user_command::pantographcompressorvalvetoggle, &TTrain::OnCommand_pantographcompressorvalvetoggle}, + {user_command::pantographcompressorvalveenable, &TTrain::OnCommand_pantographcompressorvalveenable}, + {user_command::pantographcompressorvalvedisable, &TTrain::OnCommand_pantographcompressorvalvedisable}, + {user_command::pantographcompressoractivate, &TTrain::OnCommand_pantographcompressoractivate}, + {user_command::pantographtogglefront, &TTrain::OnCommand_pantographtogglefront}, + {user_command::pantographtogglerear, &TTrain::OnCommand_pantographtogglerear}, + {user_command::pantographraisefront, &TTrain::OnCommand_pantographraisefront}, + {user_command::pantographraiserear, &TTrain::OnCommand_pantographraiserear}, + {user_command::pantographlowerfront, &TTrain::OnCommand_pantographlowerfront}, + {user_command::pantographlowerrear, &TTrain::OnCommand_pantographlowerrear}, + + {user_command::wiperswitchincrease, &TTrain::OnCommand_wiperswitchincrease}, + {user_command::wiperswitchdecrease, &TTrain::OnCommand_wiperswitchdecrease}, + + {user_command::lightsset, &TTrain::OnCommand_lightsset}, + + {user_command::pantographlowerall, &TTrain::OnCommand_pantographlowerall}, + {user_command::pantographselectnext, &TTrain::OnCommand_pantographselectnext}, + {user_command::pantographselectprevious, &TTrain::OnCommand_pantographselectprevious}, + {user_command::pantographtoggleselected, &TTrain::OnCommand_pantographtoggleselected}, + {user_command::pantographraiseselected, &TTrain::OnCommand_pantographraiseselected}, + {user_command::pantographlowerselected, &TTrain::OnCommand_pantographlowerselected}, + {user_command::pantographvalvesupdate, &TTrain::OnCommand_pantographvalvesupdate}, + {user_command::pantographvalvesoff, &TTrain::OnCommand_pantographvalvesoff}, + {user_command::linebreakertoggle, &TTrain::OnCommand_linebreakertoggle}, + {user_command::linebreakeropen, &TTrain::OnCommand_linebreakeropen}, + {user_command::linebreakerclose, &TTrain::OnCommand_linebreakerclose}, + {user_command::linebreakertoggleb, &TTrain::OnCommand_linebreakertoggleremote}, + {user_command::linebreakeropenb, &TTrain::OnCommand_linebreakeropenremote}, + {user_command::linebreakercloseb, &TTrain::OnCommand_linebreakercloseremote}, + {user_command::linebreakertogglec, &TTrain::OnCommand_linebreakertoggleremote}, + {user_command::linebreakeropenc, &TTrain::OnCommand_linebreakeropenremote}, + {user_command::linebreakerclosec, &TTrain::OnCommand_linebreakercloseremote}, + {user_command::fuelpumptoggle, &TTrain::OnCommand_fuelpumptoggle}, + {user_command::fuelpumpenable, &TTrain::OnCommand_fuelpumpenable}, + {user_command::fuelpumpdisable, &TTrain::OnCommand_fuelpumpdisable}, + {user_command::oilpumptoggle, &TTrain::OnCommand_oilpumptoggle}, + {user_command::oilfuelpumptoggle, &TTrain::OnCommand_oilfuelpumptoggle}, + {user_command::oilpumpenable, &TTrain::OnCommand_oilpumpenable}, + {user_command::oilpumpdisable, &TTrain::OnCommand_oilpumpdisable}, + {user_command::tractionmodetoggle, &TTrain::OnCommand_tractionmodetoggle}, + {user_command::tractionmodecatenary, &TTrain::OnCommand_tractionmodecatenary}, + {user_command::tractionmodegenset, &TTrain::OnCommand_tractionmodegenset}, + {user_command::gensettoggle, &TTrain::OnCommand_gensettoggle}, + {user_command::gensetenable, &TTrain::OnCommand_gensetenable}, + {user_command::gensetdisable, &TTrain::OnCommand_gensetdisable}, + {user_command::waterheaterbreakertoggle, &TTrain::OnCommand_waterheaterbreakertoggle}, + {user_command::waterheaterbreakerclose, &TTrain::OnCommand_waterheaterbreakerclose}, + {user_command::waterheaterbreakeropen, &TTrain::OnCommand_waterheaterbreakeropen}, + {user_command::waterheatertoggle, &TTrain::OnCommand_waterheatertoggle}, + {user_command::waterheaterenable, &TTrain::OnCommand_waterheaterenable}, + {user_command::waterheaterdisable, &TTrain::OnCommand_waterheaterdisable}, + {user_command::waterpumpbreakertoggle, &TTrain::OnCommand_waterpumpbreakertoggle}, + {user_command::waterpumpbreakerclose, &TTrain::OnCommand_waterpumpbreakerclose}, + {user_command::waterpumpbreakeropen, &TTrain::OnCommand_waterpumpbreakeropen}, + {user_command::waterpumptoggle, &TTrain::OnCommand_waterpumptoggle}, + {user_command::waterpumpenable, &TTrain::OnCommand_waterpumpenable}, + {user_command::waterpumpdisable, &TTrain::OnCommand_waterpumpdisable}, + {user_command::watercircuitslinktoggle, &TTrain::OnCommand_watercircuitslinktoggle}, + {user_command::watercircuitslinkenable, &TTrain::OnCommand_watercircuitslinkenable}, + {user_command::watercircuitslinkdisable, &TTrain::OnCommand_watercircuitslinkdisable}, + {user_command::convertertoggle, &TTrain::OnCommand_convertertoggle}, + {user_command::converterenable, &TTrain::OnCommand_converterenable}, + {user_command::converterdisable, &TTrain::OnCommand_converterdisable}, + {user_command::convertertogglelocal, &TTrain::OnCommand_convertertogglelocal}, + {user_command::converteroverloadrelayreset, &TTrain::OnCommand_converteroverloadrelayreset}, + {user_command::compressortoggle, &TTrain::OnCommand_compressortoggle}, + {user_command::compressorenable, &TTrain::OnCommand_compressorenable}, + {user_command::compressordisable, &TTrain::OnCommand_compressordisable}, + {user_command::compressortogglelocal, &TTrain::OnCommand_compressortogglelocal}, + {user_command::compressorpresetactivatenext, &TTrain::OnCommand_compressorpresetactivatenext}, + {user_command::compressorpresetactivateprevious, &TTrain::OnCommand_compressorpresetactivateprevious}, + {user_command::compressorpresetactivatedefault, &TTrain::OnCommand_compressorpresetactivatedefault}, + {user_command::motorblowerstogglefront, &TTrain::OnCommand_motorblowerstogglefront}, + {user_command::motorblowerstogglerear, &TTrain::OnCommand_motorblowerstogglerear}, + {user_command::motorblowersdisableall, &TTrain::OnCommand_motorblowersdisableall}, + {user_command::coolingfanstoggle, &TTrain::OnCommand_coolingfanstoggle}, + {user_command::motorconnectorsopen, &TTrain::OnCommand_motorconnectorsopen}, + {user_command::motorconnectorsclose, &TTrain::OnCommand_motorconnectorsclose}, + {user_command::motordisconnect, &TTrain::OnCommand_motordisconnect}, + {user_command::motoroverloadrelaythresholdtoggle, &TTrain::OnCommand_motoroverloadrelaythresholdtoggle}, + {user_command::motoroverloadrelaythresholdsetlow, &TTrain::OnCommand_motoroverloadrelaythresholdsetlow}, + {user_command::motoroverloadrelaythresholdsethigh, &TTrain::OnCommand_motoroverloadrelaythresholdsethigh}, + {user_command::motoroverloadrelayreset, &TTrain::OnCommand_motoroverloadrelayreset}, + {user_command::universalrelayreset1, &TTrain::OnCommand_universalrelayreset}, + {user_command::universalrelayreset2, &TTrain::OnCommand_universalrelayreset}, + {user_command::universalrelayreset3, &TTrain::OnCommand_universalrelayreset}, + {user_command::heatingtoggle, &TTrain::OnCommand_heatingtoggle}, + {user_command::heatingenable, &TTrain::OnCommand_heatingenable}, + {user_command::heatingdisable, &TTrain::OnCommand_heatingdisable}, + {user_command::lightspresetactivatenext, &TTrain::OnCommand_lightspresetactivatenext}, + {user_command::lightspresetactivateprevious, &TTrain::OnCommand_lightspresetactivateprevious}, + {user_command::headlighttoggleleft, &TTrain::OnCommand_headlighttoggleleft}, + {user_command::headlightenableleft, &TTrain::OnCommand_headlightenableleft}, + {user_command::headlightdisableleft, &TTrain::OnCommand_headlightdisableleft}, + {user_command::headlighttoggleright, &TTrain::OnCommand_headlighttoggleright}, + {user_command::headlightenableright, &TTrain::OnCommand_headlightenableright}, + {user_command::headlightdisableright, &TTrain::OnCommand_headlightdisableright}, + {user_command::headlighttoggleupper, &TTrain::OnCommand_headlighttoggleupper}, + {user_command::headlightenableupper, &TTrain::OnCommand_headlightenableupper}, + {user_command::headlightdisableupper, &TTrain::OnCommand_headlightdisableupper}, + {user_command::redmarkertoggleleft, &TTrain::OnCommand_redmarkertoggleleft}, + {user_command::redmarkerenableleft, &TTrain::OnCommand_redmarkerenableleft}, + {user_command::redmarkerdisableleft, &TTrain::OnCommand_redmarkerdisableleft}, + {user_command::redmarkertoggleright, &TTrain::OnCommand_redmarkertoggleright}, + {user_command::redmarkerenableright, &TTrain::OnCommand_redmarkerenableright}, + {user_command::redmarkerdisableright, &TTrain::OnCommand_redmarkerdisableright}, + {user_command::headlighttogglerearleft, &TTrain::OnCommand_headlighttogglerearleft}, + {user_command::headlightenablerearleft, &TTrain::OnCommand_headlightenablerearleft}, + {user_command::headlightdisablerearleft, &TTrain::OnCommand_headlightdisablerearleft}, + {user_command::headlighttogglerearright, &TTrain::OnCommand_headlighttogglerearright}, + {user_command::headlightenablerearright, &TTrain::OnCommand_headlightenablerearright}, + {user_command::headlightdisablerearright, &TTrain::OnCommand_headlightdisablerearright}, + {user_command::headlighttogglerearupper, &TTrain::OnCommand_headlighttogglerearupper}, + {user_command::headlightenablerearupper, &TTrain::OnCommand_headlightenablerearupper}, + {user_command::headlightdisablerearupper, &TTrain::OnCommand_headlightdisablerearupper}, + {user_command::modernlightdimmerdecrease, &TTrain::OnCommand_modernlightdimmerdecrease}, + {user_command::modernlightdimmerincrease, &TTrain::OnCommand_modernlightdimmerincrease}, + {user_command::redmarkertogglerearleft, &TTrain::OnCommand_redmarkertogglerearleft}, + {user_command::redmarkerenablerearleft, &TTrain::OnCommand_redmarkerenablerearleft}, + {user_command::redmarkerdisablerearleft, &TTrain::OnCommand_redmarkerdisablerearleft}, + {user_command::redmarkertogglerearright, &TTrain::OnCommand_redmarkertogglerearright}, + {user_command::redmarkerenablerearright, &TTrain::OnCommand_redmarkerenablerearright}, + {user_command::redmarkerdisablerearright, &TTrain::OnCommand_redmarkerdisablerearright}, + {user_command::redmarkerstoggle, &TTrain::OnCommand_redmarkerstoggle}, + {user_command::endsignalstoggle, &TTrain::OnCommand_endsignalstoggle}, + {user_command::headlightsdimtoggle, &TTrain::OnCommand_headlightsdimtoggle}, + {user_command::headlightsdimenable, &TTrain::OnCommand_headlightsdimenable}, + {user_command::headlightsdimdisable, &TTrain::OnCommand_headlightsdimdisable}, + {user_command::interiorlighttoggle, &TTrain::OnCommand_interiorlighttoggle}, + {user_command::interiorlightenable, &TTrain::OnCommand_interiorlightenable}, + {user_command::interiorlightdisable, &TTrain::OnCommand_interiorlightdisable}, + {user_command::interiorlightdimtoggle, &TTrain::OnCommand_interiorlightdimtoggle}, + {user_command::interiorlightdimenable, &TTrain::OnCommand_interiorlightdimenable}, + {user_command::interiorlightdimdisable, &TTrain::OnCommand_interiorlightdimdisable}, + {user_command::compartmentlightstoggle, &TTrain::OnCommand_compartmentlightstoggle}, + {user_command::compartmentlightsenable, &TTrain::OnCommand_compartmentlightsenable}, + {user_command::compartmentlightsdisable, &TTrain::OnCommand_compartmentlightsdisable}, + {user_command::instrumentlighttoggle, &TTrain::OnCommand_instrumentlighttoggle}, + {user_command::instrumentlightenable, &TTrain::OnCommand_instrumentlightenable}, + {user_command::instrumentlightdisable, &TTrain::OnCommand_instrumentlightdisable}, + {user_command::dashboardlighttoggle, &TTrain::OnCommand_dashboardlighttoggle}, + {user_command::dashboardlightenable, &TTrain::OnCommand_dashboardlightenable}, + {user_command::dashboardlightdisable, &TTrain::OnCommand_dashboardlightdisable}, + {user_command::timetablelighttoggle, &TTrain::OnCommand_timetablelighttoggle}, + {user_command::timetablelightenable, &TTrain::OnCommand_timetablelightenable}, + {user_command::timetablelightdisable, &TTrain::OnCommand_timetablelightdisable}, + {user_command::doorlocktoggle, &TTrain::OnCommand_doorlocktoggle}, + {user_command::doortoggleleft, &TTrain::OnCommand_doortoggleleft}, + {user_command::doortoggleright, &TTrain::OnCommand_doortoggleright}, + {user_command::doorpermitleft, &TTrain::OnCommand_doorpermitleft}, + {user_command::doorpermitright, &TTrain::OnCommand_doorpermitright}, + {user_command::doorpermitpresetactivatenext, &TTrain::OnCommand_doorpermitpresetactivatenext}, + {user_command::doorpermitpresetactivateprevious, &TTrain::OnCommand_doorpermitpresetactivateprevious}, + {user_command::dooropenleft, &TTrain::OnCommand_dooropenleft}, + {user_command::dooropenright, &TTrain::OnCommand_dooropenright}, + {user_command::doorcloseleft, &TTrain::OnCommand_doorcloseleft}, + {user_command::doorcloseright, &TTrain::OnCommand_doorcloseright}, + {user_command::dooropenall, &TTrain::OnCommand_dooropenall}, + {user_command::doorcloseall, &TTrain::OnCommand_doorcloseall}, + {user_command::doorsteptoggle, &TTrain::OnCommand_doorsteptoggle}, + {user_command::doormodetoggle, &TTrain::OnCommand_doormodetoggle}, + {user_command::mirrorstoggle, &TTrain::OnCommand_mirrorstoggle}, + {user_command::nearestcarcouplingincrease, &TTrain::OnCommand_nearestcarcouplingincrease}, + {user_command::nearestcarcouplingdisconnect, &TTrain::OnCommand_nearestcarcouplingdisconnect}, + {user_command::nearestcarcoupleradapterattach, &TTrain::OnCommand_nearestcarcoupleradapterattach}, + {user_command::nearestcarcoupleradapterremove, &TTrain::OnCommand_nearestcarcoupleradapterremove}, + {user_command::occupiedcarcouplingdisconnect, &TTrain::OnCommand_occupiedcarcouplingdisconnect}, + {user_command::departureannounce, &TTrain::OnCommand_departureannounce}, + {user_command::hornlowactivate, &TTrain::OnCommand_hornlowactivate}, + {user_command::hornhighactivate, &TTrain::OnCommand_hornhighactivate}, + {user_command::whistleactivate, &TTrain::OnCommand_whistleactivate}, + {user_command::radiotoggle, &TTrain::OnCommand_radiotoggle}, + {user_command::radioenable, &TTrain::OnCommand_radioenable}, + {user_command::radiodisable, &TTrain::OnCommand_radiodisable}, + {user_command::radiochannelincrease, &TTrain::OnCommand_radiochannelincrease}, + {user_command::radiochanneldecrease, &TTrain::OnCommand_radiochanneldecrease}, + {user_command::radiochannelset, &TTrain::OnCommand_radiochannelset}, + {user_command::radiostopsend, &TTrain::OnCommand_radiostopsend}, + {user_command::radiostopenable, &TTrain::OnCommand_radiostopenable}, + {user_command::radiostopdisable, &TTrain::OnCommand_radiostopdisable}, + {user_command::radiostoptest, &TTrain::OnCommand_radiostoptest}, + {user_command::radiocall1send, &TTrain::OnCommand_radiocall1send}, + {user_command::radiocall3send, &TTrain::OnCommand_radiocall3send}, + {user_command::radiovolumeincrease, &TTrain::OnCommand_radiovolumeincrease}, + {user_command::radiovolumedecrease, &TTrain::OnCommand_radiovolumedecrease}, + {user_command::radiovolumeset, &TTrain::OnCommand_radiovolumeset}, + {user_command::fmradiotoggle, &TTrain::OnCommand_fmradiotoggle}, + {user_command::fmradiovolumeincrease, &TTrain::OnCommand_fmradiovolumeincrease}, + {user_command::fmradiovolumedecrease, &TTrain::OnCommand_fmradiovolumedecrease}, + {user_command::fmradiovolumeset, &TTrain::OnCommand_fmradiovolumeset}, + {user_command::fmradiotuneincrease, &TTrain::OnCommand_fmradiotuneincrease}, + {user_command::fmradiotunedecrease, &TTrain::OnCommand_fmradiotunedecrease}, + {user_command::fmradiotuneset, &TTrain::OnCommand_fmradiotuneset}, + {user_command::radiofusetoggle, &TTrain::OnCommand_radiofusetoggle}, + {user_command::radiofuseenable, &TTrain::OnCommand_radiofuseenable}, + {user_command::radiofusedisable, &TTrain::OnCommand_radiofusedisable}, + {user_command::cabchangeforward, &TTrain::OnCommand_cabchangeforward}, + {user_command::cabchangebackward, &TTrain::OnCommand_cabchangebackward}, + {user_command::generictoggle0, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle1, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle2, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle3, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle4, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle5, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle6, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle7, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle8, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle9, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle10, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle11, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle12, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle13, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle14, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle15, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle16, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle17, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle18, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle19, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle20, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle21, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle22, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle23, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle24, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle25, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle26, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle27, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle28, &TTrain::OnCommand_generictoggle}, + {user_command::generictoggle29, &TTrain::OnCommand_generictoggle}, + {user_command::genericset0, &TTrain::OnCommand_genericset}, + {user_command::genericset1, &TTrain::OnCommand_genericset}, + {user_command::genericset2, &TTrain::OnCommand_genericset}, + {user_command::genericset3, &TTrain::OnCommand_genericset}, + {user_command::genericset4, &TTrain::OnCommand_genericset}, + {user_command::genericset5, &TTrain::OnCommand_genericset}, + {user_command::genericset6, &TTrain::OnCommand_genericset}, + {user_command::genericset7, &TTrain::OnCommand_genericset}, + {user_command::genericset8, &TTrain::OnCommand_genericset}, + {user_command::genericset9, &TTrain::OnCommand_genericset}, + {user_command::genericset10, &TTrain::OnCommand_genericset}, + {user_command::genericset11, &TTrain::OnCommand_genericset}, + {user_command::genericset12, &TTrain::OnCommand_genericset}, + {user_command::genericset13, &TTrain::OnCommand_genericset}, + {user_command::genericset14, &TTrain::OnCommand_genericset}, + {user_command::genericset15, &TTrain::OnCommand_genericset}, + {user_command::genericset16, &TTrain::OnCommand_genericset}, + {user_command::genericset17, &TTrain::OnCommand_genericset}, + {user_command::genericset18, &TTrain::OnCommand_genericset}, + {user_command::genericset19, &TTrain::OnCommand_genericset}, + {user_command::genericset20, &TTrain::OnCommand_genericset}, + {user_command::genericset21, &TTrain::OnCommand_genericset}, + {user_command::genericset22, &TTrain::OnCommand_genericset}, + {user_command::genericset23, &TTrain::OnCommand_genericset}, + {user_command::genericset24, &TTrain::OnCommand_genericset}, + {user_command::genericset25, &TTrain::OnCommand_genericset}, + {user_command::genericset26, &TTrain::OnCommand_genericset}, + {user_command::genericset27, &TTrain::OnCommand_genericset}, + {user_command::genericset28, &TTrain::OnCommand_genericset}, + {user_command::genericset29, &TTrain::OnCommand_genericset}, + {user_command::vehiclemoveforwards, &TTrain::OnCommand_vehiclemoveforwards}, + {user_command::vehiclemovebackwards, &TTrain::OnCommand_vehiclemovebackwards}, + {user_command::vehicleboost, &TTrain::OnCommand_vehicleboost}, + {user_command::springbraketoggle, &TTrain::OnCommand_springbraketoggle}, + {user_command::springbrakeenable, &TTrain::OnCommand_springbrakeenable}, + {user_command::springbrakedisable, &TTrain::OnCommand_springbrakedisable}, + {user_command::springbrakeshutofftoggle, &TTrain::OnCommand_springbrakeshutofftoggle}, + {user_command::springbrakeshutoffenable, &TTrain::OnCommand_springbrakeshutoffenable}, + {user_command::springbrakeshutoffdisable, &TTrain::OnCommand_springbrakeshutoffdisable}, + {user_command::springbrakerelease, &TTrain::OnCommand_springbrakerelease}, + {user_command::distancecounteractivate, &TTrain::OnCommand_distancecounteractivate}, + {user_command::speedcontrolincrease, &TTrain::OnCommand_speedcontrolincrease}, + {user_command::speedcontroldecrease, &TTrain::OnCommand_speedcontroldecrease}, + {user_command::speedcontrolpowerincrease, &TTrain::OnCommand_speedcontrolpowerincrease}, + {user_command::speedcontrolpowerdecrease, &TTrain::OnCommand_speedcontrolpowerdecrease}, + {user_command::speedcontrolbutton0, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton1, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton2, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton3, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton4, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton5, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton6, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton7, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton8, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::speedcontrolbutton9, &TTrain::OnCommand_speedcontrolbutton}, + {user_command::inverterenable1, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable2, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable3, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable4, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable5, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable6, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable7, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable8, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable9, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable10, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable11, &TTrain::OnCommand_inverterenable}, + {user_command::inverterenable12, &TTrain::OnCommand_inverterenable}, + {user_command::inverterdisable1, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable2, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable3, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable4, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable5, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable6, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable7, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable8, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable9, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable10, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable11, &TTrain::OnCommand_inverterdisable}, + {user_command::inverterdisable12, &TTrain::OnCommand_inverterdisable}, + {user_command::invertertoggle1, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle2, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle3, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle4, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle5, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle6, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle7, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle8, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle9, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle10, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle11, &TTrain::OnCommand_invertertoggle}, + {user_command::invertertoggle12, &TTrain::OnCommand_invertertoggle}, +}; diff --git a/vehicle/cab/controllercommands.cpp b/vehicle/cab/controllercommands.cpp new file mode 100644 index 000000000..2d9a402c3 --- /dev/null +++ b/vehicle/cab/controllercommands.cpp @@ -0,0 +1,667 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the controllers: the master, the secondary and the dynamic brake one, the speed regulator + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// command handlers +void TTrain::OnCommand_aidriverenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // on press + if (Train->DynamicObject->Mechanik == nullptr) + { + return; + } + + if (true == Train->DynamicObject->Mechanik->AIControllFlag()) + { + // żeby nie trzeba było rozłączać dla zresetowania + Train->DynamicObject->Mechanik->TakeControl(false); + } + Train->DynamicObject->Mechanik->TakeControl(true); + } +} + +void TTrain::OnCommand_aidriverdisable(TTrain *Train, command_data const &Command) +{ + + // on press + if (Command.action == GLFW_PRESS && Train->DynamicObject->Mechanik) + Train->DynamicObject->Mechanik->TakeControl(false); +} +auto const EU07_CONTROLLER_KEYBOARDETURNDELAY{1.5f}; + +void TTrain::OnCommand_jointcontrollerset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + // value controls brake in range 0-0.5, master controller in range 0.5-1.0 + if (Command.param1 >= 0.5) + { + Train->set_master_controller((Command.param1 * 2 - 1) * + (Train->controlled->CoupledCtrl ? Train->controlled->MainCtrlPosNo + Train->controlled->ScndCtrlPosNo() : Train->controlled->MainCtrlPosNo)); + Train->m_mastercontrollerinuse = true; + // when SplitEDPneumaticBrake is active the joint controller's negative range + // commands the dedicated dynamic-brake lever instead of the local pneumatic brake + if (Train->controlled->brakes.electrodynamic.splitFromPneumatic) + { + Train->controlled->DynamicBrakeLevelSet(0.0); + } + else + { + Train->occupied->brakes.SetIndependentPosition(0); + } + } + else + { + auto const negativeRange{std::clamp(1.0 - Command.param1 * 2, 0.0, 1.0)}; + if (Train->controlled->brakes.electrodynamic.splitFromPneumatic) + { + // negative range of jointctrl drives only ED braking, local pneumatic brake stays untouched. + // snap to DBPN discrete stops so the lever animates step-by-step + auto const stepCount{std::max(1, Train->controlled->brakes.electrodynamic.controllerPositions)}; + auto const snapped{std::round(negativeRange * stepCount) / stepCount}; + Train->controlled->DynamicBrakeLevelSet(snapped); + } + else + { + Train->occupied->brakes.SetIndependentPosition(negativeRange); + } + if (Train->controlled->MainCtrlPowerPos() > 0) + { + Train->set_master_controller(Train->controlled->MainCtrlNoPowerPos()); + } + } + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources + } +} + +void TTrain::OnCommand_mastercontrollerincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + // when SplitEDPneumaticBrake is true the joint controller's negative range maps + // to the dedicated dynamic-brake lever (DynamicBrakeCtrl) rather than to LocalBrake + auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.IndependentPosition() > 0.0}; + if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) + { + if (splitMode) + { + OnCommand_DynamicBrakeControllerDecrease(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakedecrease(Train, Command); + } + } + else + { + Train->controlled->IncMainCtrl(1); + Train->m_mastercontrollerinuse = true; + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerincreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + auto const negativeRangeActive{splitMode ? Train->controlled->brakes.electrodynamic.controllerPosition > 0.0 : Train->occupied->brakes.IndependentPosition() > 0.0}; + if (Train->ggJointCtrl.SubModel != nullptr && negativeRangeActive) + { + if (splitMode) + { + OnCommand_DynamicBrakeControllerDecreaseFast(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakedecreasefast(Train, Command); + } + } + else + { + Train->controlled->IncMainCtrl(Train->controlled->MainCtrlPosNo); + Train->m_mastercontrollerinuse = true; + } + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerdecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + if (Train->ggJointCtrl.SubModel != nullptr && Train->controlled->IsMainCtrlNoPowerPos()) + { + // negative range of jointctrl: ED brake when split, otherwise pneumatic local brake + if (splitMode) + { + OnCommand_DynamicBrakeControllerIncrease(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakeincrease(Train, Command); + } + } + else + { + Train->controlled->DecMainCtrl(1); + Train->m_mastercontrollerinuse = true; + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerdecreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + auto const splitMode{Train->controlled->brakes.electrodynamic.splitFromPneumatic}; + if (Train->ggJointCtrl.SubModel != nullptr && Train->controlled->IsMainCtrlNoPowerPos()) + { + if (splitMode) + { + OnCommand_DynamicBrakeControllerIncreaseFast(Train, Command); + Train->m_mastercontrollerinuse = true; + } + else + { + OnCommand_independentbrakeincreasefast(Train, Command); + } + } + else + { + Train->controlled->DecMainCtrl(Train->controlled->MainCtrlPowerPos()); + Train->m_mastercontrollerinuse = true; + } + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_KEYBOARDETURNDELAY + EU07_CONTROLLER_BASERETURNDELAY; + } +} + +void TTrain::OnCommand_mastercontrollerset(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + Train->set_master_controller(Command.param1); + Train->m_mastercontrollerinuse = true; + } + else + { + // release + Train->m_mastercontrollerinuse = false; + Train->m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; // NOTE: keyboard return delay is omitted for other input sources + } +} +void TTrain::OnCommand_DynamicBrakeControllerIncrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_RELEASE) + { + return; + } + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) + { + return; + } + + // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl + Train->controlled->IncDynamicBrakeLevel(1.0f); +} + +void TTrain::OnCommand_DynamicBrakeControllerIncreaseFast(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) + { + return; + } + + Train->controlled->IncDynamicBrakeLevel(static_cast(Train->controlled->brakes.electrodynamic.controllerPositions)); +} + +void TTrain::OnCommand_DynamicBrakeControllerDecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_RELEASE) + { + return; + } + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) + { + return; + } + + // step exactly one stop (1 / DBPN) per command, matching the discrete behaviour of jointctrl + Train->controlled->DecDynamicBrakeLevel(1.0f); +} + +void TTrain::OnCommand_DynamicBrakeControllerDecreaseFast(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) + { + return; + } + + Train->controlled->DecDynamicBrakeLevel(static_cast(Train->controlled->brakes.electrodynamic.controllerPositions)); +} + +void TTrain::OnCommand_DynamicBrakeControllerSet(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_RELEASE) + { + return; + } + if (false == Train->controlled->brakes.electrodynamic.splitFromPneumatic) + { + return; + } + + // when input source uses raw 0..1 value, snap to nearest DBPN step + auto const target{std::clamp(Command.param1, 0.0, 1.0)}; + auto const stepCount{std::max(1, Train->controlled->brakes.electrodynamic.controllerPositions)}; + auto const snapped{std::round(target * stepCount) / stepCount}; + Train->controlled->DynamicBrakeLevelSet(snapped); +} + +void TTrain::OnCommand_secondcontrollerincrease(TTrain *Train, command_data const &Command) +{ + + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntModeAllow && true == Train->controlled->ShuntMode) + { + if (Command.action != GLFW_RELEASE) + { + Train->controlled->SetAnPos(std::clamp(Train->controlled->AnPos() + 0.025, 0.0, 1.0)); + } + } + else + { + // regular mode + // push or pushtoggle control type + if (Train->ggScndCtrl.is_push()) + { + if (Command.action == GLFW_PRESS) + { + // activate on press + Train->controlled->IncScndCtrl(1); + } + } + // toggle control type + else + { + if (Command.action != GLFW_RELEASE) + { + Train->controlled->IncScndCtrl(1); + } + } + // HACK: potentially animate push or pushtoggle control + if (Train->ggScndCtrl.is_push()) + { + auto const activeposition{1.f}; + auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; + Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); + } + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos() <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) + { + Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_secondcontrollerincreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) + { + Train->controlled->SetAnPos(1.0); + } + else + { + Train->controlled->IncScndCtrl(2); + } + } +} + +void TTrain::OnCommand_notchingrelaytoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->occupied->AutoRelayFlag()) + { + // turn on + Train->occupied->AutoRelaySwitch(true); + } + else + { + // turn off + Train->occupied->AutoRelaySwitch(false); + } + // visual feedback + Train->ggAutoRelayButton.UpdateValue(Train->occupied->AutoRelayFlag() ? 1.f : 0.f, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_tempomattoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggScndCtrlButton.is_push()) + { + // impulse switch + if (Command.action == GLFW_RELEASE) + { + // just move the button(s) back to default position + // visual feedback + Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggScndCtrlOffButton.UpdateValue(0.0, Train->dsbSwitch); + return; + } + // glfw_press + if (false == Train->controlled->IsSpeedCtrlEngaged()) + { + // turn on if it's not active + Train->controlled->SpeedCtrlSwitch(true); + // visual feedback + Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // otherwise turn off + Train->controlled->SpeedCtrlSwitch(false); + // visual feedback + if (Train->m_controlmapper.contains("tempomatoff_sw:")) + { + Train->ggScndCtrlOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + } + else + { + // two-state switch + if (Command.action == GLFW_RELEASE) + { + return; + } + + if (false == Train->controlled->IsSpeedCtrlEngaged()) + { + // turn on + Train->controlled->SpeedCtrlSwitch(true); + // visual feedback + Train->ggScndCtrlButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // turn off + Train->controlled->SpeedCtrlSwitch(false); + // visual feedback + Train->ggScndCtrlButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_distancecounteractivate(TTrain *Train, command_data const &Command) +{ + // NOTE: distance meter activation button is presumed to be of impulse type + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggDistanceCounterButton.UpdateValue(1.0, Train->dsbSwitch); + // activate or start anew + if (Train->occupied->isDoubleClickForMeasureNeeded) + { + // handler tempomatu dla podwojnego kliku + if (Train->trainLenghtMeasureTimer >= 0.f) // jesli zdazylismy w czasie sekundy + Train->m_distancecounter = 0.f; // rozpoczynamy pomiar + else + Train->trainLenghtMeasureTimer = Train->occupied->DistanceCounterDoublePressPeriod; // odpalamy zegarek od nowa + } + else + { + // dla pojedynczego kliku + Train->m_distancecounter = 0.f; + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggDistanceCounterButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_mucurrentindicatorothersourceactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggNextCurrentButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Current Indicator Source switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // turn on + Train->ShowNextCurrent = true; + // visual feedback + Train->ggNextCurrentButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->ShowNextCurrent = false; + // visual feedback + Train->ggNextCurrentButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_secondcontrollerdecrease(TTrain *Train, command_data const &Command) +{ + + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) + { + if (Command.action != GLFW_RELEASE) + { + Train->controlled->SetAnPos(std::clamp(Train->controlled->AnPos() - 0.025, 0.0, 1.0)); + } + } + else + { + // regular mode + // push or pushtoggle control type + if (Train->ggScndCtrl.is_push()) + { + // basic push control can't decrease state, but pushtoggle can + if (true == Train->ggScndCtrl.is_toggle() && Command.action == GLFW_PRESS) + { + // activate on press + Train->controlled->DecScndCtrl(1); + } + } + // toggle control type + else + { + if (Command.action != GLFW_RELEASE) + { + Train->controlled->DecScndCtrl(1); + } + } + // HACK: potentially animate push or pushtoggle control + if (Train->ggScndCtrl.is_push()) + { + auto const activeposition{Train->ggScndCtrl.is_toggle() ? 0.f : 1.f}; + auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; + Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); + } + // potentially animate tempomat button, unless the cruise control has its own + if (Train->ggScndCtrlButton.is_push() && Train->controlled->ScndCtrlPos() <= 1 && false == Train->controlled->IsSpeedCtrlSeparate()) + { + if (Train->m_controlmapper.contains("tempomatoff_sw:")) + { + Train->ggScndCtrlOffButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); + } + else + { + Train->ggScndCtrlButton.UpdateValue(Command.action == GLFW_RELEASE ? 0.f : 1.f, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_secondcontrollerdecreasefast(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_RELEASE) + { + // on press or hold + if (Train->controlled->EngineType == TEngineType::DieselElectric && true == Train->controlled->ShuntMode) + { + Train->controlled->SetAnPos(0.0); + } + else + { + Train->controlled->DecScndCtrl(2); + } + } +} + +void TTrain::OnCommand_secondcontrollerset(TTrain *Train, command_data const &Command) +{ + + auto const targetposition{std::min(static_cast(Command.param1), Train->controlled->ScndCtrlPosNo())}; + // HACK: potentially animate push or pushtoggle control + if (Train->ggScndCtrl.is_push()) + { + auto const activeposition{Train->ggScndCtrl.is_toggle() ? + (targetposition < Train->controlled->ScndCtrlPos() ? 0.f : + targetposition > Train->controlled->ScndCtrlPos() ? 1.f : + Train->ggScndCtrl.GetDesiredValue()) : // leave the control in its current position if it hits the limit + targetposition == 0 ? 0.f : + 1.f}; + auto const neutralposition{Train->ggScndCtrl.is_toggle() ? 0.5f : 0.f}; + Train->ggScndCtrl.UpdateValue(Command.action == GLFW_RELEASE ? neutralposition : activeposition, Train->dsbSwitch); + } + // update control value + if (Command.action != GLFW_RELEASE) + { + // on press or hold + while (targetposition < Train->controlled->GetVirtualScndPos() && true == Train->controlled->DecScndCtrl(1)) + { + // all work is done in the header + } + while (targetposition > Train->controlled->GetVirtualScndPos() && true == Train->controlled->IncScndCtrl(1)) + { + // all work is done in the header + } + } +} diff --git a/vehicle/cab/couplingcommands.cpp b/vehicle/cab/couplingcommands.cpp new file mode 100644 index 000000000..d7a6822b1 --- /dev/null +++ b/vehicle/cab/couplingcommands.cpp @@ -0,0 +1,230 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the couplings and the departure + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_nearestcarcouplingincrease(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto couplerindex{-1}; + auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; + if (vehicle == nullptr) + vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); + + if (couplerindex != -1 && vehicle != nullptr) + { + + vehicle->couple(EndOf(couplerindex)); + } + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::connect); + } + } +} + +void TTrain::OnCommand_nearestcarcouplingdisconnect(TTrain *Train, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto couplerindex{-1}; + auto *vehicle{Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), 1, 1500, couplerindex)}; + if (vehicle == nullptr) + vehicle = Train->DynamicObject->ABuScanNearestObject(Command.location, Train->DynamicObject->GetTrack(), -1, 1500, couplerindex); + + if (couplerindex != -1 && vehicle != nullptr) + { + + vehicle->uncouple(EndOf(couplerindex)); + } + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); + } + } +} + +void TTrain::OnCommand_nearestcarcoupleradapterattach(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; + if (vehicle == nullptr) + { + return; + } + + auto const couplerindex = + glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::rear)} - Command.location) ? VehicleEnd::front : VehicleEnd::rear; + + vehicle->attach_coupler_adapter(couplerindex); + } +} + +void TTrain::OnCommand_nearestcarcoupleradapterremove(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + // tryb freefly, press only + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 50, false, true))}; + if (vehicle == nullptr) + { + return; + } + + auto const couplerindex = + glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::front)} - Command.location) < glm::length2(glm::vec3{vehicle->CouplerPosition(VehicleEnd::rear)} - Command.location) ? VehicleEnd::front : VehicleEnd::rear; + + vehicle->remove_coupler_adapter(couplerindex); + } +} + +void TTrain::OnCommand_occupiedcarcouplingdisconnect(TTrain *Train, command_data const &Command) +{ + + // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->m_couplingdisconnect = true; + + if (Train->iCabn == 0) + { + return; + } + + if (Train->DynamicObject) + { + Train->DynamicObject->uncouple(Train->cab_to_end()); + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->m_couplingdisconnect = false; + } +} + +void TTrain::OnCommand_occupiedcarcouplingdisconnectback(TTrain *Train, command_data const &Command) +{ + + // if( false == Train->m_controlmapper.contains( "couplingdisconnect_sw:" ) ) { return; } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->m_couplingdisconnectback = true; + + if (Train->iCabn == 0) + { + return; + } + + if (Train->DynamicObject) + { + Train->DynamicObject->uncouple(Opposite(Train->cab_to_end())); + if (Train->DynamicObject->Mechanik) + { + // aktualizacja flag kierunku w składzie + Train->DynamicObject->Mechanik->CheckVehicles(DriverOrder::disconnect); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->m_couplingdisconnectback = false; + } +} + +void TTrain::OnCommand_departureannounce(TTrain *Train, command_data const &Command) +{ + + if (Train->ggDepartureSignalButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Departure Signal button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the sound can loop uninterrupted + if (false == Train->occupied->DepartureSignal()) + { + // turn on + Train->occupied->signal_departure(true); + // visual feedback + Train->ggDepartureSignalButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->occupied->signal_departure(false); + // visual feedback + Train->ggDepartureSignalButton.UpdateValue(0.0, Train->dsbSwitch); + } +} diff --git a/vehicle/cab/doorcommands.cpp b/vehicle/cab/doorcommands.cpp new file mode 100644 index 000000000..53156786c --- /dev/null +++ b/vehicle/cab/doorcommands.cpp @@ -0,0 +1,694 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the doors and the mirrors + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_doorlocktoggle(TTrain *Train, command_data const &Command) +{ + + if (Train->ggDoorSignallingButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Door Lock switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the sound can loop uninterrupted + if (false == Train->occupied->Doors.lock_enabled) + { + // turn on + // TODO: door lock command to send through consist + Train->occupied->LockDoors(true); + // visual feedback + Train->ggDoorSignallingButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // turn off + // TODO: door lock command to send through consist + Train->occupied->LockDoors(false); + // visual feedback + Train->ggDoorSignallingButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_doortoggleleft(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors + if (false == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) + { + // open + OnCommand_dooropenleft(Train, Command); + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseleft(Train, Command); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (true == (Train->ggDoorLeftButton.GetDesiredValue() > 0.5 || Train->ggDoorLeftOnButton.GetDesiredValue() > 0.5)) + { + // open + if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal()) + { + // complete closing the doors + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseleft(Train, Command); + } + } + else + { + OnCommand_dooropenleft(Train, Command); + } + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorLeftOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseleft(Train, Command); + } + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + // NOTE: temporary arrangement, can be removed when LD system is in place + if (Train->ggDoorLeftOffButton.SubModel) + Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggDoorLeftOnButton.SubModel) + Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_doorpermitleft(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + if (false == Train->occupied->Doors.permit_presets.empty()) + { + return; + } + + auto const side{(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right)}; + + if (Command.action == GLFW_PRESS) + { + + if (Train->ggDoorLeftPermitButton.is_push()) + { + // impulse switch + Train->occupied->PermitDoors(side); + // visual feedback + Train->ggDoorLeftPermitButton.UpdateValue(1.0, Train->dsbSwitch); + // start potential timer for remote door control + Train->m_doorpermittimers[side] = Train->occupied->DoorsOpenWithPermitAfter; + } + else + { + // two-state switch + auto const newstate{!(Train->ggDoorLeftPermitButton.GetDesiredValue() > 0.5)}; + + Train->occupied->PermitDoors(side, newstate); + // visual feedback + Train->ggDoorLeftPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggDoorLeftPermitButton.is_push()) + { + // impulse switch + // visual feedback + Train->ggDoorLeftPermitButton.UpdateValue(0.0, Train->dsbSwitch); + // reset potential remote door control timer + Train->m_doorpermittimers[side] = -1.f; + } +} + +void TTrain::OnCommand_doorpermitright(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + if (false == Train->occupied->Doors.permit_presets.empty()) + { + return; + } + + auto const side{(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left)}; + + if (Command.action == GLFW_PRESS) + { + + if (Train->ggDoorRightPermitButton.type() == TGaugeType::push) + { + // impulse switch + Train->occupied->PermitDoors(side); + // visual feedback + Train->ggDoorRightPermitButton.UpdateValue(1.0, Train->dsbSwitch); + // start potential timer for remote door control + Train->m_doorpermittimers[side] = Train->occupied->DoorsOpenWithPermitAfter; + } + else + { + // two-state switch + auto const newstate{!(Train->ggDoorRightPermitButton.GetDesiredValue() > 0.5)}; + + Train->occupied->PermitDoors(side, newstate); + // visual feedback + Train->ggDoorRightPermitButton.UpdateValue(newstate ? 1.0 : 0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE && Train->ggDoorRightPermitButton.type() == TGaugeType::push) + { + // impulse switch + // visual feedback + Train->ggDoorRightPermitButton.UpdateValue(0.0, Train->dsbSwitch); + // reset potential remote door control timer + Train->m_doorpermittimers[side] = -1.f; + } +} + +void TTrain::OnCommand_doorpermitpresetactivatenext(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->occupied->ChangeDoorPermitPreset(1); + // visual feedback + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->occupied->Doors.permit_preset), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_doorpermitpresetactivateprevious(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->occupied->ChangeDoorPermitPreset(-1); + // visual feedback + Train->ggDoorPermitPresetButton.UpdateValue(static_cast(Train->occupied->Doors.permit_preset), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dooropenleft(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteopencontrol{Train->occupied->Doors.open_control == control_t::driver || Train->occupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + { + return; + } + + if (Train->ggDoorLeftOnButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, true); + // visual feedback + if (Train->ggDoorLeftOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorLeftOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorLeftButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + if (Train->ggDoorLeftOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorLeftOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_doorcloseleft(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteclosecontrol{Train->occupied->Doors.close_control == control_t::driver || Train->occupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + { + return; + } + + if (Train->ggDoorLeftOffButton.SubModel == nullptr && Train->ggDoorLeftButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + + if (Train->occupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->occupied->signal_departure(true); + } + else + { + // TODO: move door opening/closing to the update, so the switch animation doesn't hinge on door working + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); + } + // visual feedback + if (Train->ggDoorLeftOffButton.SubModel != nullptr) + { + // two separate switches to open and close the door + Train->ggDoorLeftOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (Train->occupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->occupied->signal_departure(false); + // now we can actually close the door + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right, false); + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + if (Train->ggDoorLeftOffButton.SubModel) + Train->ggDoorLeftOffButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_doortoggleright(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // NOTE: test how the door state check works with consists where the occupied vehicle doesn't have opening doors + if (false == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) + { + // open + OnCommand_dooropenright(Train, Command); + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseright(Train, Command); + } + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (true == (Train->ggDoorRightButton.GetDesiredValue() > 0.5 || Train->ggDoorRightOnButton.GetDesiredValue() > 0.5)) + { + // open + if (Train->occupied->Doors.has_autowarning && Train->occupied->DepartureSignal()) + { + // complete closing the doors + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseright(Train, Command); + } + } + else + { + OnCommand_dooropenright(Train, Command); + } + } + else + { + // close + if (Train->ggDoorAllOffButton.SubModel != nullptr && Train->ggDoorRightOffButton.SubModel == nullptr) + { + // OnCommand_doorcloseall( Train, Command ); + // if two-button setup lacks dedicated closing button require the user to press appropriate button manually + return; + } + else + { + OnCommand_doorcloseright(Train, Command); + } + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + // NOTE: temporary arrangement, can be removed when LD system is in place + if (Train->ggDoorRightOffButton.SubModel) + Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggDoorRightOnButton.SubModel) + Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dooropenright(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteopencontrol{Train->occupied->Doors.open_control == control_t::driver || Train->occupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + { + return; + } + + if (Train->ggDoorRightOnButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, true); + // visual feedback + if (Train->ggDoorRightOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorRightOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorRightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + if (Train->ggDoorRightOnButton.SubModel != nullptr) + { + // two separate impulse switches + Train->ggDoorRightOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_doorcloseright(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteclosecontrol{Train->occupied->Doors.close_control == control_t::driver || Train->occupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + { + return; + } + + if (Train->ggDoorRightOffButton.SubModel == nullptr && Train->ggDoorRightButton.SubModel == nullptr) + { + + return; + } + + if (Command.action == GLFW_PRESS) + { + + if (Train->occupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->occupied->signal_departure(true); + } + else + { + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); + } + // visual feedback + if (Train->ggDoorRightOffButton.SubModel != nullptr) + { + // two separate switches to open and close the door + Train->ggDoorRightOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single two-state switch + Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + + if (Train->occupied->Doors.has_autowarning) + { + // automatic departure signal delays actual door closing until the button is released + Train->occupied->signal_departure(false); + // now we can actually close the door + Train->occupied->OperateDoors(Train->cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left, false); + } + // visual feedback + // dedicated closing buttons are presumed to be impulse switches and return automatically to neutral position + if (Train->ggDoorRightOffButton.SubModel) + Train->ggDoorRightOffButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dooropenall(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteopencontrol{Train->occupied->Doors.open_control == control_t::driver || Train->occupied->Doors.open_control == control_t::mixed}; false == remoteopencontrol) + { + return; + } + + if (Train->ggDoorAllOnButton.SubModel == nullptr) + { + // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch + if (Command.action == GLFW_PRESS) + { + WriteLog("Open All Doors switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + + Train->occupied->OperateDoors(VehicleSide::right, true); + Train->occupied->OperateDoors(VehicleSide::left, true); + // visual feedback + Train->ggDoorAllOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggDoorAllOnButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_doorcloseall(TTrain *Train, command_data const &Command) +{ + + + if (auto const remoteclosecontrol{Train->occupied->Doors.close_control == control_t::driver || Train->occupied->Doors.close_control == control_t::mixed}; false == remoteclosecontrol) + { + return; + } + + if (Train->ggDoorAllOffButton.SubModel == nullptr) + { + // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch + if (Command.action == GLFW_PRESS) + { + WriteLog("Close All Doors switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + + if (Train->occupied->Doors.has_autowarning) + { + Train->occupied->signal_departure(true); + } + if (Train->ggDoorAllOffButton.type() != TGaugeType::push_delayed) + { + // delays the action until the button is released + Train->occupied->OperateDoors(VehicleSide::right, false); + Train->occupied->OperateDoors(VehicleSide::left, false); + } + // visual feedback + Train->ggDoorLeftButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggDoorRightButton.UpdateValue(0.0, Train->dsbSwitch); + if (Train->ggDoorAllOffButton.SubModel) + Train->ggDoorAllOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->occupied->Doors.has_autowarning) + { + Train->occupied->signal_departure(false); + } + if (Train->ggDoorAllOffButton.type() == TGaugeType::push_delayed) + { + // now we can actually close the door + Train->occupied->OperateDoors(VehicleSide::right, false); + Train->occupied->OperateDoors(VehicleSide::left, false); + } + // visual feedback + if (Train->ggDoorAllOffButton.SubModel) + Train->ggDoorAllOffButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_doorsteptoggle(TTrain *Train, command_data const &Command) +{ + // TODO: move logic/visualization code to the gauge, on_command() should return hint whether it should invoke a reaction + if (Command.action == GLFW_PRESS) + { + // effect + if (false == Train->ggDoorStepButton.is_delayed()) + { + Train->occupied->PermitDoorStep(false == Train->occupied->Doors.step_enabled); + } + // visual feedback + auto const isactive{(Train->ggDoorStepButton.is_push() // always press push button + || Train->occupied->Doors.step_enabled)}; // for toggle buttons indicate item state + Train->ggDoorStepButton.UpdateValue(isactive ? 1 : 0); + } + else if (Command.action == GLFW_RELEASE) + { + // effect + if (Train->ggDoorStepButton.is_delayed()) + { + Train->occupied->PermitDoorStep(false == Train->occupied->Doors.step_enabled); + } + // visual feedback + if (Train->ggDoorStepButton.is_push()) + { + Train->ggDoorStepButton.UpdateValue(0); + } + } +} + +void TTrain::OnCommand_doormodetoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + Train->occupied->ChangeDoorControlMode(false == Train->occupied->Doors.remote_only); + } +} + +void TTrain::OnCommand_mirrorstoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + // only reacting to press, so the sound can loop uninterrupted + if (false == Train->occupied->MirrorForbidden()) + { + // turn on + Train->occupied->SetMirrorForbidden(true); + } + else + { + // turn off + Train->occupied->SetMirrorForbidden(false); + } +} diff --git a/vehicle/cab/equipmentcommands.cpp b/vehicle/cab/equipmentcommands.cpp new file mode 100644 index 000000000..fb017f240 --- /dev/null +++ b/vehicle/cab/equipmentcommands.cpp @@ -0,0 +1,515 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the heating, the generic switches, the spring brake, the speed control and the inverters + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_heatingtoggle(TTrain *Train, command_data const &Command) +{ + + if (Train->ggTrainHeatingButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Train Heating switch is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // ignore repeats so the switch doesn't flip back and forth if key is held down + if (false == Train->controlled->trainHeating.IsAllowed()) + { + // turn on + OnCommand_heatingenable(Train, Command); + } + else + { + // turn off + OnCommand_heatingdisable(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE && (Train->ggTrainHeatingButton.type() == TGaugeType::push || Train->occupied->trainHeating.config.switchImpulse)) + { + // impulse switch + // visual feedback + Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_heatingenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->occupied->HeatingSwitch(true); + // visual feedback + Train->ggTrainHeatingButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.config.switchImpulse) + { + // the switch springs back to the middle + Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_heatingdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + + Train->occupied->HeatingSwitch(false); + // visual feedback: an impulse switch is pushed the other way, down + auto position{0.0}; + if (Train->occupied->trainHeating.config.switchImpulse) + { + position = -1.0; + } + else if (Train->ggTrainHeatingButton.type() == TGaugeType::push) + { + position = 1.0; + } + Train->ggTrainHeatingButton.UpdateValue(position, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE && Train->occupied->trainHeating.config.switchImpulse) + { + Train->ggTrainHeatingButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_generictoggle(TTrain *Train, command_data const &Command) +{ + + auto const itemindex = static_cast(Command.command) - static_cast(user_command::generictoggle0); + auto &item = Train->ggUniversals[itemindex]; + /* + if( item.SubModel == nullptr ) { + if( Command.action == GLFW_PRESS ) { + WriteLog( "Train generic item " + std::to_string( itemindex ) + " is missing, or wasn't defined" ); + } + return; + } + */ + + if (Command.action == GLFW_PRESS) + { + + if (item.type() == TGaugeType::push) + { + // impulse switch + // turn on + // visual feedback + item.UpdateValue(1.0); + } + else + { + // two-state switch, or one dragged in between its ends with the mouse: to the end farther from it + // visual feedback + item.UpdateValue(universal_drag::toggled(item.GetDesiredValue())); + } + } + else if (Command.action == GLFW_RELEASE && item.type() == TGaugeType::push) + { + // impulse switch + // turn off + // visual feedback + item.UpdateValue(0.0); + } +} + +// sets a universal control to the position given in param1, from 0 to 1 (MaSzyna-EU07/maszyna#62): the mouse drags +// the ones with drag: in their definition, and it can be bound to an axis of a gamepad. it stays where it is set +void TTrain::OnCommand_genericset(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_RELEASE) + { + return; + } + auto const itemindex = static_cast(Command.command) - static_cast(user_command::genericset0); + auto &item = Train->ggUniversals[itemindex]; + if (item.is_push()) + { + // an impulse switch springs back, it has no position to be left in + return; + } + // visual feedback + item.UpdateValue(universal_drag::clamp(Command.param1)); +} + +universal_drag::direction TTrain::universal_drag_direction(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size()) || ggUniversals[Index].SubModel == nullptr) + { + return universal_drag::direction::none; + } + return ggUniversals[Index].drag(); +} + +float TTrain::universal_position(int const Index) const +{ + + if (Index < 0 || Index >= static_cast(ggUniversals.size())) + { + return 0.f; + } + return ggUniversals[Index].GetDesiredValue(); +} + +void TTrain::OnCommand_springbraketoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->occupied->brakes.spring.activate) + { + // turn on + OnCommand_springbrakeenable(Train, Command); + } + else + { + // turn off + OnCommand_springbrakedisable(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); + Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_springbrakeenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpringBrakeActivate(true); + // visual feedback + Train->ggSpringBrakeOnButton.UpdateValue(1.0, Train->dsbSwitch); + Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_springbrakedisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpringBrakeActivate(false); + // visual feedback + Train->ggSpringBrakeOffButton.UpdateValue(1.0, Train->dsbSwitch); + Train->ggSpringBrakeOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpringBrakeOffButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; +void TTrain::OnCommand_springbrakeshutofftoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->occupied->brakes.spring.shutOff) + { + // turn on + OnCommand_springbrakeshutoffenable(Train, Command); + } + else + { + // turn off + OnCommand_springbrakeshutoffdisable(Train, Command); + } + } +}; + +void TTrain::OnCommand_springbrakeshutoffenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpringBrakeShutOff(true); + } +}; + +void TTrain::OnCommand_springbrakeshutoffdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpringBrakeShutOff(false); + } +}; + +void TTrain::OnCommand_springbrakerelease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + + if (auto const *vehicle{Train->find_nearest_consist_vehicle(Command.freefly, Command.location)}; vehicle == nullptr) + { + return; + } + Train->occupied->SpringBrakeRelease(); + } +}; + +void TTrain::OnCommand_speedcontrolincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpeedCtrlInc(); + // visual feedback + Train->ggSpeedControlIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontroldecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpeedCtrlDec(); + // visual feedback + Train->ggSpeedControlDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontrolpowerincrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpeedCtrlPowerInc(); + // visual feedback + Train->ggSpeedControlPowerIncreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlPowerIncreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontrolpowerdecrease(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpeedCtrlPowerDec(); + // visual feedback + Train->ggSpeedControlPowerDecreaseButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedControlPowerDecreaseButton.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_speedcontrolbutton(TTrain *Train, command_data const &Command) +{ + + auto const itemindex = static_cast(Command.command) - static_cast(user_command::speedcontrolbutton0); + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->occupied->SpeedCtrlButton(itemindex); + // visual feedback + Train->ggSpeedCtrlButtons[itemindex].UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + Train->ggSpeedCtrlButtons[itemindex].UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_inverterenable(TTrain *Train, command_data const &Command) +{ + + auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterenable1); + auto &item = Train->ggInverterEnableButtons[itemindex]; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied() > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + while (p) + { + if (p->physics->inductionMotor.traction.maxPower > 1) + { + if (itemindex < p->physics->inductionMotor.inverterCount) + { + p->physics->SwitchInverter(itemindex, true); + break; + } + else + { + itemindex -= p->physics->inductionMotor.inverterCount; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + // visual feedback + item.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + item.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_inverterdisable(TTrain *Train, command_data const &Command) +{ + + auto itemindex = static_cast(Command.command) - static_cast(user_command::inverterdisable1); + auto &item = Train->ggInverterDisableButtons[itemindex]; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied() > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + while (p) + { + if (p->physics->inductionMotor.traction.maxPower > 1) + { + if (itemindex < p->physics->inductionMotor.inverterCount) + { + p->physics->SwitchInverter(itemindex, false); + break; + } + else + { + itemindex -= p->physics->inductionMotor.inverterCount; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + // visual feedback + item.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // release + // visual feedback + item.UpdateValue(0.0, Train->dsbSwitch); + } +}; + +void TTrain::OnCommand_invertertoggle(TTrain *Train, command_data const &Command) +{ + + auto itemindex = static_cast(Command.command) - static_cast(user_command::invertertoggle1); + auto &item = Train->ggInverterToggleButtons[itemindex]; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + bool kier = Train->DynamicObject->DirectionGet() * Train->occupied->CabOccupied() > 0; + auto const flag{CouplingSet::FromBits(Train->DynamicObject->physics->inductionMotor.inverterControlCouplings)}; + TDynamicObject *p = Train->DynamicObject->GetFirstDynamic(Train->occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + while (p) + { + if (p->physics->inductionMotor.traction.maxPower > 1) + { + if (itemindex < p->physics->inductionMotor.inverterCount) + { + p->physics->SwitchInverter(itemindex, !p->physics->InverterActivated(itemindex)); + // visual feedback + item.UpdateValue(p->physics->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0, Train->dsbSwitch); + break; + } + else + { + itemindex -= p->physics->inductionMotor.inverterCount; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + } +}; diff --git a/vehicle/cab/internal.h b/vehicle/cab/internal.h new file mode 100644 index 000000000..cc4bc2f2c --- /dev/null +++ b/vehicle/cab/internal.h @@ -0,0 +1,67 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the constants and helpers the files of the cab share: only they include this header + +#pragma once + +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include + +/* +namespace input { + +extern user_command command; + +} +*/ + + +auto const EU07_CONTROLLER_BASERETURNDELAY{0.5f}; + +// what the split parts of TTrain share, kept out of the global namespace +namespace vehicle_cab +{ + +bool is_hold_coil_lever(TGauge const &Button); + +} // namespace vehicle_cab + diff --git a/vehicle/cab/lightcommands.cpp b/vehicle/cab/lightcommands.cpp new file mode 100644 index 000000000..6976f6595 --- /dev/null +++ b/vehicle/cab/lightcommands.cpp @@ -0,0 +1,1580 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the lights + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// the cab interior light set by the light preset just selected, if the preset sets one (eu07/maszyna#529). +// the cab light switch (cablight_sw:) is bound to the light state and follows it by itself +void TTrain::set_cab_light_from_lights_preset() +{ + auto const cablight{occupied->LightsPresetCabLight(occupied->LightsPos())}; + if (false == cablight.has_value()) + { + return; + } + auto const set{[&cablight](TCab &Cab) { + Cab.bLight = cablight->light; + Cab.bLightDim = cablight->dim; + }}; + if (false == DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + set(Cabine[iCabn]); + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Cabine) + { + set(cab); + } + } + // the dimmer switch is driven by commands only, move it along + if (ggCabLightDimButton.SubModel != nullptr) + { + ggCabLightDimButton.UpdateValue(cablight->dim ? 1.f : 0.f); + } +} + +void TTrain::OnCommand_lightspresetactivatenext(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo == 0) + { + // no preset selector + return; + } + if (Command.action != GLFW_PRESS) + { + // one change per key press + return; + } + + if (Train->occupied->LightsPos() < Train->occupied->LightsPosNo || true == Train->occupied->LightsWrap) + { + // active light preset is stored as value in range 1-LigthPosNo + auto const restartcycle{Train->occupied->LightsPos() >= Train->occupied->LightsPosNo}; + Train->occupied->SetLightsPos(false == restartcycle ? Train->occupied->LightsPos() + 1 : 1); // wrap mode + + Train->Dynamic()->SetLights(); + Train->set_cab_light_from_lights_preset(); + // visual feedback + if (Train->ggLightsButton.SubModel != nullptr) + { + if (false == restartcycle) + { + Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos() - 1), Train->dsbSwitch); + } + else + { + // past the last position to the first one: a knob turning all the way round turns on rather than + // back across all the positions, and the position reached sounds (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->occupied->LightsPos() - 1), true, Train->occupied->LightsPosNo, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_lightspresetactivateprevious(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo == 0) + { + // no preset selector + return; + } + if (Command.action != GLFW_PRESS) + { + // one change per key press + return; + } + + if (Train->occupied->LightsPos() > 1 || true == Train->occupied->LightsWrap) + { + // active light preset is stored as value in range 1-LigthPosNo + auto const restartcycle{Train->occupied->LightsPos() <= 1}; + Train->occupied->SetLightsPos(false == restartcycle ? Train->occupied->LightsPos() - 1 : Train->occupied->LightsPosNo); // wrap mode + + Train->Dynamic()->SetLights(); + Train->set_cab_light_from_lights_preset(); + // visual feedback + if (Train->ggLightsButton.SubModel != nullptr) + { + if (false == restartcycle) + { + Train->ggLightsButton.UpdateValue(static_cast(Train->occupied->LightsPos() - 1), Train->dsbSwitch); + } + else + { + // back past the first position to the last one, the same way (eu07/maszyna#464) + Train->ggLightsButton.UpdateValueWrapped(static_cast(Train->occupied->LightsPos() - 1), false, Train->occupied->LightsPosNo, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_headlighttoggleleft(TTrain *Train, command_data const &Command) +{ + + auto const vehicleend{Train->cab_to_end()}; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + + if (Train->ggLeftEndLightButton.SubModel != nullptr || Train->ggLeftLightButton.SubModel == nullptr) + { + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0) + { + // turn on + OnCommand_headlightenableleft(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableleft(Train, Command); + } + } else { + // if the light is controlled by 3-way switch, handle both headlight and redmarker + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0 && + (Train->occupied->LitLights()[vehicleend] & light::redmarker_left) == 0) + { + // turn on + OnCommand_headlightenableleft(Train, Command); + } + else if (Train->occupied->LitLights()[vehicleend] & light::headlight_left) + { + // switch to red + OnCommand_redmarkerenableleft(Train, Command); + } + else + { + // disable + OnCommand_redmarkerdisableleft(Train, Command); + } + } + } +} + +void TTrain::OnCommand_lightsset(TTrain *Train, command_data const &Command) +{ + // set custom item in Lights inventory + Train->occupied->Lights[VehicleEnd::front][17] = static_cast(Command.param1); + Train->occupied->Lights[VehicleEnd::rear][17] = static_cast(Command.param2); + Train->occupied->SetLightsPos(18); // nasza custom pozycja + Train->Dynamic()->SetLights(); +} + +void TTrain::OnCommand_headlightenableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); + // implementation + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0) + { + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_left)); + } + // if the light is controlled by 3-way switch, disable marker light + if (Train->ggLeftEndLightButton.SubModel == nullptr) + { + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::redmarker_left); + } + } +} + +void TTrain::OnCommand_headlightdisableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_left) == 0) + { + return; + } // already disabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_left)); + // visual feedback + Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttoggleright(TTrain *Train, command_data const &Command) +{ + + auto const vehicleend{Train->cab_to_end()}; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + + if (Train->ggRightEndLightButton.SubModel != nullptr || Train->ggRightLightButton.SubModel == nullptr) + { + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0) + { + // turn on + OnCommand_headlightenableright(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableright(Train, Command); + } + } else { + // if the light is controlled by 3-way switch, handle both headlight and redmarker + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0 && + (Train->occupied->LitLights()[vehicleend] & light::redmarker_right) == 0) + { + // turn on + OnCommand_headlightenableright(Train, Command); + } + else if (Train->occupied->LitLights()[vehicleend] & light::headlight_right) + { + // switch to red + OnCommand_redmarkerenableright(Train, Command); + } + else + { + // disable + OnCommand_redmarkerdisableright(Train, Command); + } + } + } +} + +void TTrain::OnCommand_headlightenableright(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggRightLightButton.UpdateValue(1.0, Train->dsbSwitch); + // implementation + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0) + { + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_right)); + } + // if the light is controlled by 3-way switch, disable marker light + if (Train->ggRightEndLightButton.SubModel == nullptr) + { + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::redmarker_right); + } + } +} + +void TTrain::OnCommand_headlightdisableright(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_right) == 0) + { + return; + } // already disabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_right)); + // visual feedback + Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttoggleupper(TTrain *Train, command_data const &Command) +{ + + auto const vehicleend{Train->cab_to_end()}; + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_upper) == 0) + { + // turn on + OnCommand_headlightenableupper(Train, Command); + } + else + { + // turn off + OnCommand_headlightdisableupper(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenableupper(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_upper) != 0) + { + return; + } // already enabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_upper)); + // visual feedback + Train->ggUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlightdisableupper(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::headlight_upper) == 0) + { + return; + } // already disabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::headlight_upper)); + // visual feedback + Train->ggUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkertoggleleft(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_left) == 0) + { + // turn on + OnCommand_redmarkerenableleft(Train, Command); + } + else + { + // turn off + OnCommand_redmarkerdisableleft(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_left) != 0) + { + return; + } // already enabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_left)); + // visual feedback + if (Train->ggLeftEndLightButton.SubModel != nullptr) + { + Train->ggLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggLeftLightButton.UpdateValue(-1.0, Train->dsbSwitch); + // if the light is controlled by 3-way switch, disable the headlight + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::headlight_left); + } + } +} + +void TTrain::OnCommand_redmarkerdisableleft(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_left) == 0) + { + return; + } // already disabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_left)); + // visual feedback + if (Train->ggLeftEndLightButton.SubModel != nullptr) + { + Train->ggLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_redmarkertoggleright(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_right) == 0) + { + // turn on + OnCommand_redmarkerenableright(Train, Command); + } + else + { + // turn off + OnCommand_redmarkerdisableright(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenableright(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_right) != 0) + { + return; + } // already enabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_right)); + // visual feedback + if (Train->ggRightEndLightButton.SubModel != nullptr) + { + Train->ggRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggRightLightButton.UpdateValue(-1.0, Train->dsbSwitch); + // if the light is controlled by 3-way switch, disable the headlight + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] & ~light::headlight_right); + } + } +} + +void TTrain::OnCommand_redmarkerdisableright(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleend{Train->cab_to_end()}; + + if ((Train->occupied->LitLights()[vehicleend] & light::redmarker_right) == 0) + { + return; + } // already disabled + + Train->occupied->SetLitLights(vehicleend, Train->occupied->LitLights()[vehicleend] ^ (light::redmarker_right)); + // visual feedback + if (Train->ggRightEndLightButton.SubModel != nullptr) + { + Train->ggRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + else + { + // we interpret lack of dedicated switch as a sign the light is controlled with 3-way switch + // this is crude, but for now will do + Train->ggRightLightButton.UpdateValue(0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlighttogglerearleft(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_right) == 0) + { + OnCommand_headlightenablerearleft(Train, Command); + } + else + { + OnCommand_headlightdisablerearleft(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenablerearleft(TTrain *Train, command_data const &Command) +{ + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // already enabled + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_right) == 0) + { + // turn on + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_right)); + // visual feedback + Train->ggRearLeftLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlightdisablerearleft(TTrain *Train, command_data const &Command) +{ + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + if (Command.action == GLFW_PRESS) + { + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // already disabled + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_right) == 0) + { + return; + } + + // turn off + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_right)); + // visual feedback + Train->ggRearLeftLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttogglerearright(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_left) == 0) + { + OnCommand_headlightenablerearright(Train, Command); + } + else + { + OnCommand_headlightdisablerearright(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenablerearright(TTrain *Train, command_data const &Command) +{ + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_left) == 0) + { + // turn on + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_left)); + // visual feedback + Train->ggRearRightLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlightdisablerearright(TTrain *Train, command_data const &Command) +{ + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // already disabled + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_left) == 0) + { + return; + } + + // turn off + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_left)); + // visual feedback + Train->ggRearRightLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_headlighttogglerearupper(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_upper) == 0) + { + OnCommand_headlightenablerearupper(Train, Command); + } + else + { + OnCommand_headlightdisablerearupper(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightenablerearupper(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_upper) == 0) + { + // turn on + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_upper)); + // visual feedback + Train->ggRearUpperLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_headlightdisablerearupper(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // already disabled? + if ((Train->occupied->LitLights()[vehicleotherend] & light::headlight_upper) == 0) + { + return; + } + + // turn off + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::headlight_upper)); + // visual feedback + Train->ggRearUpperLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_modernlightdimmerincrease(TTrain *Train, command_data const &Command) +{ + if (!Train->occupied->enableModernDimmer()) + return; // if modern dimmer is disabled, skip entire command + if (Command.action == GLFW_PRESS) + { + // update modern dimmer state + if (false == Train->occupied->stepDimmerPosition(1)) + return; // już na maksimum i nie można cyklicznie + auto const dimPos = Train->occupied->DimmerPosition(); + // update lightning + // Train->Dynamic()->SetLights(); + Train->Dynamic()->SetLightDimmings(); + + // visual feedback + if (Train->ggModernLightDimSw.SubModel != nullptr) + Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); + } +} +void TTrain::OnCommand_modernlightdimmerdecrease(TTrain *Train, command_data const &Command) +{ + if (!Train->occupied->enableModernDimmer()) + return; // jeśli dimmer jest wyłączony, olewamy + + if (Command.action == GLFW_PRESS) + { + if (false == Train->occupied->stepDimmerPosition(-1)) + return; // już na minimum i nie można cyklicznie + auto const dimPos = Train->occupied->DimmerPosition(); + + // Train->Dynamic()->SetLights(); + Train->Dynamic()->SetLightDimmings(); + + if (Train->ggModernLightDimSw.SubModel != nullptr) + Train->ggModernLightDimSw.UpdateValue(static_cast(dimPos), Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkertogglerearleft(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_right) == 0) + { + OnCommand_redmarkerenablerearleft(Train, Command); + } + else + { + OnCommand_redmarkerdisablerearleft(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenablerearleft(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_right) == 0) + { + // turn on + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_right)); + // visual feedback + Train->ggRearLeftEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_redmarkerdisablerearleft(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_right) == 0) + { + return; + } + // turn off + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_right)); + // visual feedback + Train->ggRearLeftEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkertogglerearright(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_left) == 0) + { + OnCommand_redmarkerenablerearright(Train, Command); + } + else + { + OnCommand_redmarkerdisablerearright(Train, Command); + } + } +} + +void TTrain::OnCommand_redmarkerenablerearright(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_left) == 0) + { + // turn on + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_left)); + // visual feedback + Train->ggRearRightEndLightButton.UpdateValue(1.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_redmarkerdisablerearright(TTrain *Train, command_data const &Command) +{ + + if (Train->occupied->LightsPosNo > 0) + { + // lights are controlled by preset selector + return; + } + + if (Command.action == GLFW_PRESS) + { + // NOTE: we toggle the light on opposite side, as 'rear right' is 'front left' on the rear end etc + auto const vehicleotherend{(Train->cab_to_end() == VehicleEnd::front ? VehicleEnd::rear : VehicleEnd::front)}; + if ((Train->occupied->LitLights()[vehicleotherend] & light::redmarker_left) == 0) + { + return; + } + // turn off + Train->occupied->SetLitLights(vehicleotherend, Train->occupied->LitLights()[vehicleotherend] ^ (light::redmarker_left)); + // visual feedback + Train->ggRearRightEndLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_redmarkerstoggle(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; + + if (vehicle == nullptr) + { + return; + } + + auto locationHead = vehicle->HeadPosition() - glm::dvec3(Command.location); // TODO: Maybe command_data should be dvec3? + auto locationRear = vehicle->RearPosition() - glm::dvec3(Command.location); + int const CouplNr{std::clamp(vehicle->DirectionGet() * (glm::dot(locationHead, locationHead) > glm::dot(locationRear, locationRear) ? 1 : -1), 0, 1)}; // z [-1,1] zrobić [0,1] + + auto const lightset{light::redmarker_left | light::redmarker_right}; + + auto const end{static_cast(CouplNr)}; + auto const lit{vehicle->physics->LitLights()[end]}; + vehicle->physics->SetLitLights(end, false == TestFlag(lit, lightset) ? lit | lightset : // turn signals on + lit ^ lightset); // turn signals off + } +} + +void TTrain::OnCommand_endsignalstoggle(TTrain * /*Train*/, command_data const &Command) +{ + + if (true == Command.freefly && Command.action == GLFW_PRESS) + { + + auto *vehicle{std::get(simulation::Region->find_vehicle(Command.location, 10, false, true))}; + + if (vehicle == nullptr) + { + return; + } + int const CouplNr{ + std::clamp(vehicle->DirectionGet() * (glm::length2(vehicle->HeadPosition() - glm::dvec3(Command.location)) > glm::length2(vehicle->RearPosition() - glm::dvec3(Command.location)) ? 1 : -1), 0, + 1)}; // z [-1,1] zrobić [0,1] + + auto const lightset{light::rearendsignals}; + + auto const end{static_cast(CouplNr)}; + auto const lit{vehicle->physics->LitLights()[end]}; + vehicle->physics->SetLitLights(end, false == TestFlag(lit, lightset) ? lit | lightset : // turn signals on + lit ^ lightset); // turn signals off + } +} + +void TTrain::OnCommand_headlightsdimtoggle(TTrain *Train, command_data const &Command) +{ + if (Train->DynamicObject->physics->enableModernDimmer()) + return; + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->DynamicObject->physics->DimmerPosition() == 0) + { + // turn on + OnCommand_headlightsdimenable(Train, Command); + } + else + { + // turn off + OnCommand_headlightsdimdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_headlightsdimenable(TTrain *Train, command_data const &Command) +{ + + if (Train->DynamicObject->physics->enableModernDimmer()) + return; + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggDimHeadlightsButton.SubModel != nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + // visual feedback + Train->ggDimHeadlightsButton.UpdateValue(1.0, Train->dsbSwitch); + } + + /* // to jest stara logika + if (true == Train->DynamicObject->DimHeadlights) + { + return; + } // already enabled + + Train->DynamicObject->DimHeadlights = true; + */ + Train->DynamicObject->physics->SetDimmerPosition(Train->DynamicObject->physics->clampDimmerPosition(1)); // ustawiamy modern dimmer na flage przyciemnienia + Train->DynamicObject->SetLightDimmings(); + } +} + +void TTrain::OnCommand_headlightsdimdisable(TTrain *Train, command_data const &Command) +{ + + if (Train->DynamicObject->physics->enableModernDimmer()) // nie wiem dlaczego to tak dziala ze jest odwrocona logika + return; + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggDimHeadlightsButton.SubModel != nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + // visual feedback + Train->ggDimHeadlightsButton.UpdateValue(0.0, Train->dsbSwitch); + } + + /* // stara logika przyciemniania + if( false == Train->DynamicObject->DimHeadlights ) { return; } // already enabled + + Train->DynamicObject->DimHeadlights = false; + + */ + Train->DynamicObject->physics->SetDimmerPosition(0); // ustawiamy modern dimmer na flage rozjasnienia + Train->DynamicObject->SetLightDimmings(); + } +} + +void TTrain::OnCommand_interiorlighttoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->Cabine[Train->iCabn].bLight) + { + // turn on + OnCommand_interiorlightenable(Train, Command); + } + else + { + // turn off + OnCommand_interiorlightdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_interiorlightenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->m_controlmapper.contains("cablight_sw:")) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Interior Light switch is missing, or wasn't defined"); + return; + } + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLight = true; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLight = true; + } + } + } +} + +void TTrain::OnCommand_interiorlightdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->m_controlmapper.contains("cablight_sw:")) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Interior Light switch is missing, or wasn't defined"); + return; + } + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLight = false; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLight = false; + } + } + } +} + +void TTrain::OnCommand_interiorlightdimtoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->Cabine[Train->iCabn].bLightDim) + { + // turn on + OnCommand_interiorlightdimenable(Train, Command); + } + else + { + // turn off + OnCommand_interiorlightdimdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_interiorlightdimenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggCabLightDimButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dim Interior Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggCabLightDimButton.UpdateValue(1.0, Train->dsbSwitch); + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLightDim = true; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLightDim = true; + } + } + } +} + +void TTrain::OnCommand_interiorlightdimdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggCabLightDimButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dim Interior Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggCabLightDimButton.UpdateValue(0.0, Train->dsbSwitch); + // store lighting switch states + if (false == Train->DynamicObject->JointCabs) + { + // vehicles with separate cabs get separate lighting switch states + Train->Cabine[Train->iCabn].bLightDim = false; + } + else + { + // joint virtual cabs share lighting switch states + for (auto &cab : Train->Cabine) + { + cab.bLightDim = false; + } + } + } +} + +void TTrain::OnCommand_compartmentlightstoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_RELEASE) + { + // the press changed the state the command is picked from below, so a release picked from it went to the other + // command and the push button that was pressed never withdrew its request. The release goes to both commands: + // each returns its own push type control to the neutral position and withdraws its request + OnCommand_compartmentlightsenable(Train, Command); + OnCommand_compartmentlightsdisable(Train, Command); + return; + } + + // keep the switch from flipping back and forth if key is held down + if (false == Train->occupied->CompartmentLights.is_active && false == Train->occupied->CompartmentLights.is_enabled) + { + // turn on + OnCommand_compartmentlightsenable(Train, Command); + } + else + { + // turn off + OnCommand_compartmentlightsdisable(Train, Command); + } +} + +void TTrain::OnCommand_compartmentlightsenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + Train->occupied->CompartmentLightsSwitch(true); + // withdraw the off request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightsoff_sw:"))) + { + Train->occupied->CompartmentLightsSwitchOff(false); + } + // visual feedback + if (Train->m_controlmapper.contains("compartmentlights_sw:")) + { + Train->ggCompartmentLightsButton.UpdateValue(1.0f, Train->dsbSwitch); + } + if (Train->m_controlmapper.contains("compartmentlightson_sw:")) + { + Train->ggCompartmentLightsOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->occupied->CompartmentLightsSwitch(false); + Train->occupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsButton.UpdateValue(0.5f); + } + if (Train->m_controlmapper.contains("compartmentlightson_sw:")) + { + Train->occupied->CompartmentLightsSwitch(false); + Train->ggCompartmentLightsOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_compartmentlightsdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + Train->occupied->CompartmentLightsSwitchOff(true); + // withdraw the on request, unless a push type control in the cab withdraws it when released + if (compartment_lights_switch::withdraws_other_request(Train->m_controlmapper.contains("compartmentlights_sw:"), Train->ggCompartmentLightsButton.is_toggle(), + Train->m_controlmapper.contains("compartmentlightson_sw:"))) + { + Train->occupied->CompartmentLightsSwitch(false); + } + // visual feedback + if (Train->m_controlmapper.contains("compartmentlights_sw:")) + { + Train->ggCompartmentLightsButton.UpdateValue(0.0f, Train->dsbSwitch); + } + if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) + { + Train->ggCompartmentLightsOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("compartmentlights_sw:") && Train->ggCompartmentLightsButton.type() == TGaugeType::push) + { + // return the switch to neutral position + Train->occupied->CompartmentLightsSwitch(false); + Train->occupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsButton.UpdateValue(0.5f); + } + if (Train->m_controlmapper.contains("compartmentlightsoff_sw:")) + { + Train->occupied->CompartmentLightsSwitchOff(false); + Train->ggCompartmentLightsOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_instrumentlighttoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (false == Train->InstrumentLightActive) + { + // turn on + OnCommand_instrumentlightenable(Train, Command); + } + else + { + // turn off + OnCommand_instrumentlightdisable(Train, Command); + } + } +} + +void TTrain::OnCommand_instrumentlightenable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggInstrumentLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Instrument Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggInstrumentLightButton.UpdateValue(1.0, Train->dsbSwitch); + + if (true == Train->InstrumentLightActive) + { + return; + } // already enabled + + Train->InstrumentLightActive = true; + } +} + +void TTrain::OnCommand_instrumentlightdisable(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Train->ggInstrumentLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Instrument Light switch is missing, or wasn't defined"); + return; + } + // visual feedback + Train->ggInstrumentLightButton.UpdateValue(0.0, Train->dsbSwitch); + + if (false == Train->InstrumentLightActive) + { + return; + } // already disabled + + Train->InstrumentLightActive = false; + } +} + +void TTrain::OnCommand_dashboardlighttoggle(TTrain *Train, command_data const &Command) +{ + if (false == Train->DashboardLightActive) + { + OnCommand_dashboardlightenable(Train, Command); + } + else + { + OnCommand_dashboardlightdisable(Train, Command); + } +} + +void TTrain::OnCommand_dashboardlightenable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggDashboardLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dashboard Light switch is missing, or wasn't defined"); + return; + } + + if (false == Train->DashboardLightActive) + { + // turn on + Train->DashboardLightActive = true; + // visual feedback + Train->ggDashboardLightButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_dashboardlightdisable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggDashboardLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Dashboard Light switch is missing, or wasn't defined"); + return; + } + + if (Train->DashboardLightActive) + { + // turn off + Train->DashboardLightActive = false; + // visual feedback + Train->ggDashboardLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_timetablelighttoggle(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (false == Train->TimetableLightActive) + { + OnCommand_timetablelightenable(Train, Command); + } + else + { + OnCommand_timetablelightdisable(Train, Command); + } +} + +void TTrain::OnCommand_timetablelightenable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggTimetableLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Timetable Light switch is missing, or wasn't defined"); + return; + } + + if (false == Train->TimetableLightActive) + { + // turn on + Train->TimetableLightActive = true; + // visual feedback + Train->ggTimetableLightButton.UpdateValue(1.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_timetablelightdisable(TTrain *Train, command_data const &Command) +{ + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (Command.action != GLFW_PRESS) + { + return; + } + + if (Train->ggTimetableLightButton.SubModel == nullptr) + { + // TODO: proper control deviced definition for the interiors, that doesn't hinge of presence of 3d submodels + WriteLog("Timetable Light switch is missing, or wasn't defined"); + return; + } + if (Train->TimetableLightActive) + { + // turn off + Train->TimetableLightActive = false; + // visual feedback + Train->ggTimetableLightButton.UpdateValue(0.0, Train->dsbSwitch); + } +} diff --git a/vehicle/cab/pantographcommands.cpp b/vehicle/cab/pantographcommands.cpp new file mode 100644 index 000000000..f41689591 --- /dev/null +++ b/vehicle/cab/pantographcommands.cpp @@ -0,0 +1,608 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the pantographs and their compressor + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_pantographtogglefront(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const &pantograph{Train->pantographUnit->pantographs[VehicleEnd::front]}; + auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches + if (state) + { + OnCommand_pantographlowerfront(Train, Command); + } + else + { + OnCommand_pantographraisefront(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // impulse switches return automatically to neutral position + if (Train->occupied->pantographCircuit.config.switchType == "impulse") + { + auto const ismanual{Train->iCabn == 0}; + Train->occupied->OperatePantographValve(VehicleEnd::front, operation_t::none, ismanual ? range_t::local : range_t::consist); + } + } +} + +void TTrain::OnCommand_pantographtogglerear(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const &pantograph{Train->pantographUnit->pantographs[VehicleEnd::rear]}; + auto const state{pantograph.valve.is_enabled || pantograph.is_active}; // fallback for impulse switches + if (state) + { + OnCommand_pantographlowerrear(Train, Command); + } + else + { + OnCommand_pantographraiserear(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // impulse switches return automatically to neutral position + if (Train->occupied->pantographCircuit.config.switchType == "impulse") + { + auto const ismanual{Train->iCabn == 0}; + Train->occupied->OperatePantographValve(VehicleEnd::rear, operation_t::none, ismanual ? range_t::local : range_t::consist); + } + } +} + +void TTrain::OnCommand_pantographraisefront(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + // prevent operation without submodel outside of engine compartment + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantfront_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglefront(Train, Command); + } +} + +void TTrain::OnCommand_pantographraiserear(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + // prevent operation without submodel outside of engine compartment + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains("pantrear_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::enable_on : operation_t::enable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglerear(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerfront(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + // prevent operation without submodel outside of engine compartment + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.config.switchType == "impulse" ? "pantfrontoff_sw:" : "pantfront_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->occupied->OperatePantographValve(VehicleEnd::front, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglefront(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerrear(TTrain *Train, command_data const &Command) +{ + + // HACK: presence of pantograph selector prevents manual operation of the individual valves + if (Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + if (Train->iCabn != 0 && false == Train->m_controlmapper.contains(Train->occupied->pantographCircuit.config.switchType == "impulse" ? "pantrearoff_sw:" : "pantrear_sw:")) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + // HACK: don't propagate pantograph commands issued from engine compartment, these are presumed to be manually moved levers + auto const ismanual{Train->iCabn == 0}; + Train->occupied->OperatePantographValve(VehicleEnd::rear, Train->occupied->pantographCircuit.config.switchType == "impulse" ? operation_t::disable_on : operation_t::disable, + ismanual ? range_t::local : range_t::consist); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtogglerear(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerall(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Train->ggPantAllDownButton.SubModel == nullptr) + { + // TODO: expand definition of cab controls so we can know if the control is present without testing for presence of 3d switch + if (Command.action == GLFW_PRESS) + { + WriteLog("Lower All Pantographs switch is missing, or wasn't defined"); + } + return; + } + + if (Train->ggPantAllDownButton.type() == TGaugeType::toggle) + { + // two-state switch, only cares about press events + if (Command.action == GLFW_PRESS) + { + Train->pantographUnit->DropAllPantographs(false == Train->pantographUnit->pantographCircuit.AllDown()); + // visual feedback + Train->ggPantAllDownButton.UpdateValue(Train->pantographUnit->pantographCircuit.AllDown() ? 1.0 : 0.0, Train->dsbSwitch); + } + } + else + { + // impulse switch + Train->controlled->DropAllPantographs(Command.action == GLFW_PRESS); + // visual feedback + Train->ggPantAllDownButton.UpdateValue(Command.action == GLFW_PRESS ? 1.0 : 0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_pantographselectnext(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + if (false == Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + Train->change_pantograph_selection(1); +} + +void TTrain::OnCommand_pantographselectprevious(TTrain *Train, command_data const &Command) +{ + + if (Command.action != GLFW_PRESS) + { + return; + } + + if (false == Train->m_controlmapper.contains("pantselect_sw:")) + { + return; + } + + Train->change_pantograph_selection(-1); +} + +void TTrain::OnCommand_pantographtoggleselected(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // recalculate pantograph state (hujhujhuj) + Train->change_pantograph_selection(1); + Train->change_pantograph_selection(-1); + + // only reacting to press, so the switch doesn't flip back and forth if key is held down + auto const state{Train->pantographUnit->pantographAir.valve.is_enabled || Train->pantographUnit->pantographAir.valve.is_active}; // fallback for impulse switches + if (state) + { + OnCommand_pantographlowerselected(Train, Command); + } + else + { + OnCommand_pantographraiseselected(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // impulse switches return automatically to neutral position + if (Train->m_controlmapper.contains("pantselectedoff_sw:")) + { + // two buttons setup + if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) + { + Train->occupied->OperatePantographsValve(operation_t::enable_off); + // visual feedback + Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); + } + if (Train->ggPantSelectedDownButton.type() != TGaugeType::toggle) + { + Train->occupied->OperatePantographsValve(operation_t::disable_off); + // visual feedback + Train->ggPantSelectedDownButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else + { + if (Train->ggPantSelectedButton.type() != TGaugeType::toggle) + { + // special case, just one impulse switch controlling both states + // with neutral position mid-way + Train->occupied->OperatePantographsValve(operation_t::none); + // visual feedback + Train->ggPantSelectedButton.UpdateValue(0.5, Train->dsbSwitch); + } + } + } +} + +void TTrain::OnCommand_pantographraiseselected(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // raise selected + Train->occupied->OperatePantographsValve(Train->ggPantSelectedButton.type() != TGaugeType::toggle ? operation_t::enable_on : operation_t::enable); + // visual feedback + Train->ggPantSelectedButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtoggleselected(Train, Command); + } +} + +void TTrain::OnCommand_pantographlowerselected(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // lower selected + Train->occupied->OperatePantographsValve(Train->ggPantSelectedDownButton.type() != TGaugeType::toggle ? operation_t::disable_on : operation_t::disable); + // visual feedback + if (Train->m_controlmapper.contains("pantselectedoff_sw:")) + { + // two button setup + Train->ggPantSelectedDownButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // single button + Train->ggPantSelectedButton.UpdateValue(0.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // NOTE: bit of a hax here, we're reusing button reset routine so we don't need a copy in every branch + OnCommand_pantographtoggleselected(Train, Command); + } +} + +void TTrain::update_pantograph_valves() +{ + using enum operation_t; + + auto const &presets{occupied->pantographCircuit.presets.first}; + auto const &selection{occupied->pantographCircuit.presets.second[cab_to_end()]}; + + auto const preset{presets[selection] - '0'}; + auto const swapends{cab_to_end() != VehicleEnd::front}; + // check desired states for both pantographs; value: whether the pantograph should be raised + auto const frontstate{preset & (swapends ? 2 : 1)}; + auto const rearstate{preset & (swapends ? 1 : 2)}; + occupied->OperatePantographValve(VehicleEnd::front, frontstate ? enable : disable); + occupied->OperatePantographValve(VehicleEnd::rear, rearstate ? enable : disable); +} + +void TTrain::change_pantograph_selection(int const Change) +{ + + auto const &presets{occupied->pantographCircuit.presets.first}; + auto &selection{occupied->pantographCircuit.presets.second[cab_to_end()]}; + auto const initialstate{selection}; + selection = std::clamp(selection + Change, 0, std::max(static_cast(presets.size() - 1), 0)); + + if (selection == initialstate) + { + return; + } // no change, nothing to do + + // potentially adjust pantograph valves to match the new state + if (false == m_controlmapper.contains("pantvalves_sw:")) + { + update_pantograph_valves(); + } +} + +void TTrain::OnCommand_pantographvalvesupdate(TTrain *Train, command_data const &Command) +{ + + bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + if (hasSeparateSwitches) + { + // implement action + Train->update_pantograph_valves(); + // visual feedback + Train->ggPantValvesUpdate.UpdateValue(1.0, Train->dsbSwitch); + } + + // Old logic to maintain compatibility + else + { + Train->update_pantograph_valves(); + Train->ggPantValvesButton.UpdateValue(1.0, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + // NOTE: pantvalves_sw: is a specialized button, with no toggle behavior support + if (hasSeparateSwitches) + Train->ggPantValvesUpdate.UpdateValue(0.5, Train->dsbSwitch); + + // Old logic to maintain compatibility + else + Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_pantographvalvesoff(TTrain *Train, command_data const &Command) +{ + + bool hasSeparateSwitches = Train->m_controlmapper.contains("pantvalvesupdate_bt:") && Train->m_controlmapper.contains("pantvalvesoff_bt:"); + + if (Command.action == GLFW_REPEAT) + { + return; + } + + if (Command.action == GLFW_PRESS) + { + // implement action + Train->occupied->OperatePantographValve(VehicleEnd::front, operation_t::disable); + Train->occupied->OperatePantographValve(VehicleEnd::rear, operation_t::disable); + // visual feedback + if (hasSeparateSwitches) + Train->ggPantValvesOff.UpdateValue(1.0, Train->dsbSwitch); + else + Train->ggPantValvesButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + // NOTE: pantvalves_sw: is a speciali zed button, with no toggle behavior support + if (hasSeparateSwitches) + Train->ggPantValvesOff.UpdateValue(0.f, Train->dsbSwitch); + else + Train->ggPantValvesButton.UpdateValue(0.5, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_pantographcompressorvalvetoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only react to press + if (Train->controlled->pantographAir.IsConnectedToMainReservoir() == false) + { + // connect pantographs with primary tank + OnCommand_pantographcompressorvalveenable(Train, Command); + } + else + { + // connect pantograps with pantograph compressor + OnCommand_pantographcompressorvalvedisable(Train, Command); + } + } +} + +void TTrain::OnCommand_pantographcompressorvalveenable(TTrain *Train, command_data const &Command) +{ + + + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->occupied == Train->pantographUnit && Train->iCabn == 0)}; false == valveispresent) + { + // tylko w maszynowym, unless actual device is present + return; + } + + if (Command.action == GLFW_PRESS) + { + // only react to press + // connect pantographs with primary tank + Train->controlled->pantographAir.ConnectToMainReservoir(true); + // visual feedback: + Train->ggPantCompressorValve.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_pantographcompressorvalvedisable(TTrain *Train, command_data const &Command) +{ + + + if (auto const valveispresent{Train->ggPantCompressorValve.SubModel != nullptr || (Train->occupied == Train->pantographUnit && Train->iCabn == 0)}; false == valveispresent) + { + // tylko w maszynowym, unless actual device is present + return; + } + + if (Command.action == GLFW_PRESS) + { + // only react to press + // connect pantograps with pantograph compressor + Train->controlled->pantographAir.ConnectToMainReservoir(false); + // visual feedback: + Train->ggPantCompressorValve.UpdateValue(1.0); + } +} + +void TTrain::OnCommand_pantographcompressoractivate(TTrain *Train, command_data const &Command) +{ + + // tylko w maszynowym, unless actual device is present + if (auto const switchispresent{Train->m_controlmapper.contains("pantcompressor_sw:") || (Train->occupied == Train->pantographUnit && Train->iCabn == 0)}; false == switchispresent) + { + return; + } + + if (Command.action != GLFW_RELEASE) + { + // press or hold to activate + if (Train->pantographUnit->pantographAir.Pressure() < 4.8 && true == Train->pantographUnit->lowVoltage.Is24vAvailable()) + { + // needs live power source and low enough pressure to work + Train->pantographUnit->pantographAir.SwitchCompressor(true); + } + // visual feedback + Train->ggPantCompressorButton.UpdateValue(1.0); + } + else + { + // release to disable + Train->pantographUnit->pantographAir.SwitchCompressor(false); + // visual feedback + Train->ggPantCompressorButton.UpdateValue(0.0); + } +} diff --git a/vehicle/cab/powercommands.cpp b/vehicle/cab/powercommands.cpp new file mode 100644 index 000000000..1aed10feb --- /dev/null +++ b/vehicle/cab/powercommands.cpp @@ -0,0 +1,569 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the line breaker, the traction motors and their relays + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// whether the cab's main_off_bt is the bistable lever of the line breaker's hold coil (eu07/maszyna#364) +bool vehicle_cab::is_hold_coil_lever(TGauge const &Button) +{ + return Button.SubModel != nullptr && hold_coil_lever::is_bistable(Button.type_declared(), Button.type() == TGaugeType::toggle); +} + +void TTrain::OnCommand_linebreakertoggle(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // press or hold... + // a single two-state lever stays where it was put, also when the line breaker gets knocked out + auto const latchinglever{Train->ggMainOnButton.SubModel == nullptr && Train->ggMainOffButton.SubModel == nullptr && Train->ggMainButton.SubModel != nullptr && + Train->ggMainButton.type() == TGaugeType::toggle}; + switch (linebreaker::pressed(Train->m_linebreakerstate, latchinglever, Train->ggMainButton.GetDesiredValue() > 0.5)) + { + case linebreaker::toggle::close: + // ...to close the circuit + if (vehicle_cab::is_hold_coil_lever(Train->ggMainOffButton) && hold_coil_lever::cuts_off(Train->ggMainOffButton.GetDesiredValue())) + { + // the one key works both controls: the hold coil lever goes back on first, or the line breaker couldn't close + Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + // NOTE: bit of a dirty shortcut here + OnCommand_linebreakerclose(Train, Command); + break; + case linebreaker::toggle::open: + // ...to open the circuit, or to put the lever off if the circuit was already opened + OnCommand_linebreakeropen(Train, Command); + break; + default: + break; + } + } + else if (Command.action == GLFW_RELEASE) + { + // release... + if (Train->ggMainOnButton.SubModel != nullptr || Train->ggMainButton.type() != TGaugeType::toggle) + { + // only impulse switches react to release events + // NOTE: we presume dedicated state switch is of impulse type + if (Train->m_linebreakerstate == linebreaker::state::open) + { + // ...after opening circuit, or holding for too short time to close it + OnCommand_linebreakeropen(Train, Command); + } + else + { + // ...after closing the circuit + // NOTE: bit of a dirty shortcut here + OnCommand_linebreakerclose(Train, Command); + } + } + // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls + Train->ggIgnitionKey.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_linebreakeropen(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (vehicle_cab::is_hold_coil_lever(Train->ggMainOffButton)) + { + // the bistable lever goes over to its other position and stays there + auto const position{hold_coil_lever::operated(Train->ggMainOffButton.GetDesiredValue())}; + Train->ggMainOffButton.UpdateValue(position, Train->dsbSwitch); + if (false == hold_coil_lever::cuts_off(position)) + { + // the hold coil is fed again, which by itself doesn't close the line breaker + return; + } + } + else if (Train->ggMainOffButton.SubModel != nullptr) + { + Train->ggMainOffButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Train->ggMainButton.SubModel != nullptr) + { + Train->ggMainButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Train->ggMainOnButton.SubModel != nullptr && false == Train->controlled->MainCircuitOpensWithStarterOnly()) + { + // NOTE: legacy behaviour, for vehicles equipped only with impulse close switch + // it doesn't make any real sense to animate this one, but some people can't get over how there's no visual reaction to their keypress + Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); + return; + } + // a diesel with only the starter button gets its engine stopped. the button stays put: held down, it would start the engine again + // play sound immediately when the switch is hit, not after release + Train->fMainRelayTimer = 0.0f; + + if (Train->m_linebreakerstate == linebreaker::state::open) + { + return; + } // already in the desired state + + if (true == Train->controlled->MainSwitch(false, Train->controlled->MainSwitchRange())) + { + Train->m_linebreakerstate = linebreaker::state::open; + if (Train->controlled->MainSwitchRange() != range_t::local) + { + // the engines of the vehicles in multiple stopped along: their two-state switches go off too, left on + // they'd start them again after the delay + for (auto &controls : Train->m_remotelinebreakers) + { + if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) + { + controls.main_switch.UpdateValue(0.0); + } + } + } + } + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + // we don't exactly know which of the two buttons was used, so reset both + // for setup with two separate swiches + if (Train->ggMainOnButton.SubModel != nullptr) + { + Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + if (Train->ggMainOffButton.SubModel != nullptr && false == vehicle_cab::is_hold_coil_lever(Train->ggMainOffButton)) + { + // (the bistable hold coil lever stays where it was put) + Train->ggMainOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + // and the two-state switch too, for good measure + if (Train->ggMainButton.SubModel != nullptr) + { + Train->ggMainButton.UpdateValue(Train->ggMainButton.type() != TGaugeType::toggle ? 0.5 : 0.0, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_linebreakerclose(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (Train->ggMainOnButton.SubModel != nullptr) + { + // two separate switches to close and break the circuit + Train->ggMainOnButton.UpdateValue(1.0, Train->dsbSwitch); + } + else if (Train->ggMainButton.SubModel != nullptr) + { + // single two-state switch + Train->ggMainButton.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // no switch capable of doing the job + // HACK: ignition key ignores lack of submodel, so we can start vehicles without any modeled controls + Train->ggIgnitionKey.UpdateValue(1.0); + return; + } + // the actual closing of the line breaker is handled in the train update routine + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + if (Train->ggMainOnButton.SubModel != nullptr) + { + // setup with two separate switches + Train->ggMainOnButton.UpdateValue(0.0, Train->dsbSwitch); + } + else if (Train->ggMainButton.SubModel != nullptr && Train->ggMainButton.type() != TGaugeType::toggle) + { + Train->ggMainButton.UpdateValue(0.5, Train->dsbSwitch); + } + + if (Train->m_linebreakerstate == linebreaker::state::closed) + { + return; + } // already in the desired state + + // we don't need to start the diesel twice, but the other types (with impulse switch setup) still need to be launched + // NOTE: this behaviour should depend on MainOnButton presence and type_delayed + // TODO: change it when/if vehicle definition files get their proper switch types + if (Train->m_linebreakerstate == linebreaker::state::closing && Train->controlled->EngineType == TEngineType::ElectricSeriesMotor) + { + // try to finalize state change of the line breaker, set the state based on the outcome + Train->m_linebreakerstate = Train->controlled->MainSwitch(true, Train->controlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; + } + // on button release reset the closing timer + Train->fMainRelayTimer = 0.0f; + } +} +namespace +{ + + +// which of the switches of the other vehicles in multiple a command works: 0 the second vehicle's, 1 the third one's +std::size_t remote_linebreaker_index(user_command const Command) +{ + using enum user_command; + return (Command == linebreakertogglec || Command == linebreakeropenc || Command == linebreakerclosec) ? 1 : 0; +} + +// the impulse switches of another vehicle's line breaker spring back when let go, whichever way they were pressed +void release_remote_linebreaker(TTrain::remote_linebreaker &Controls, std::optional &Sound) +{ + if (Controls.on_button.SubModel != nullptr) + { + Controls.on_button.UpdateValue(0.0, Sound); + } + if (Controls.off_button.SubModel != nullptr) + { + Controls.off_button.UpdateValue(0.0, Sound); + } + if (Controls.main_switch.SubModel != nullptr && Controls.main_switch.type() != TGaugeType::toggle) + { + Controls.main_switch.UpdateValue(0.5, Sound); + } + Controls.held_without_switch = false; +} + +} // namespace + +physics::Vehicle *TTrain::remote_engine(std::size_t const Index) const +{ + return engine_start::engine(*occupied, *controlled, static_cast(Index) + 2); +} + +void TTrain::OnCommand_linebreakertoggleremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // a two-state switch goes the other way than it stands, an impulse one the other way than the engine is + bool close{false}; + if (controls.main_switch.SubModel != nullptr && controls.main_switch.type() == TGaugeType::toggle) + { + close = controls.main_switch.GetDesiredValue() < 0.5; + } + else + { + auto const *engine{Train->remote_engine(index)}; + close = engine == nullptr || false == engine_start::remote_switch::is_running(*engine); + } + if (close) + { + OnCommand_linebreakercloseremote(Train, Command); + } + else + { + OnCommand_linebreakeropenremote(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (controls.on_button.SubModel != nullptr || controls.main_switch.type() != TGaugeType::toggle) + { + // only impulse switches react to release events + release_remote_linebreaker(controls, Train->dsbSwitch); + } + controls.held_without_switch = false; + } +} + +void TTrain::OnCommand_linebreakeropenremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // visual feedback + if (controls.off_button.SubModel != nullptr) + { + controls.off_button.UpdateValue(1.0, Train->dsbSwitch); + } + else if (controls.main_switch.SubModel != nullptr) + { + controls.main_switch.UpdateValue(0.0, Train->dsbSwitch); + } + controls.held_without_switch = false; + if (auto *engine{Train->remote_engine(index)}; engine != nullptr) + { + engine_start::remote_switch::open(*engine); + } + } + else if (Command.action == GLFW_RELEASE) + { + release_remote_linebreaker(controls, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_linebreakercloseremote(TTrain *Train, command_data const &Command) +{ + auto const index{remote_linebreaker_index(Command.command)}; + auto &controls{Train->m_remotelinebreakers[index]}; + + if (Command.action == GLFW_PRESS) + { + // visual feedback; the line breaker closes in the train update, once the switch was held long enough + if (controls.on_button.SubModel != nullptr) + { + controls.on_button.UpdateValue(1.0, Train->dsbSwitch); + } + else if (controls.main_switch.SubModel != nullptr) + { + controls.main_switch.UpdateValue(1.0, Train->dsbSwitch); + } + else + { + // no switch in the cab, the command alone holds it + controls.held_without_switch = true; + } + } + else if (Command.action == GLFW_RELEASE) + { + release_remote_linebreaker(controls, Train->dsbSwitch); + } +} + +void TTrain::update_remote_linebreakers(double const Deltatime) +{ + for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) + { + auto &controls{m_remotelinebreakers[index]}; + auto *engine{remote_engine(index)}; + auto const closeheld{controls.held_without_switch || (controls.main_switch.SubModel != nullptr && controls.main_switch.GetDesiredValue() > 0.95) || + (controls.on_button.SubModel != nullptr && controls.on_button.GetDesiredValue() > 0.95)}; + auto const openheld{controls.off_button.SubModel != nullptr && controls.off_button.GetDesiredValue() > 0.95}; + // as with the cab's own switch, an electric locomotive's impulse switch closes the line breaker when let go + auto const closesonrelease{engine != nullptr && controls.on_button.SubModel != nullptr && engine->EngineType == TEngineType::ElectricSeriesMotor}; + controls.state.update(engine, closeheld, openheld, Deltatime, closesonrelease); + } +} + +void TTrain::OnCommand_motorconnectorsopen(TTrain *Train, command_data const &Command) +{ + + // TODO: don't rely on presense of 3d model to determine presence of the switch + if (Train->ggStLinOffButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); + } + return; + } + // HACK: because we don't have modeled actual circuits this is a simplification of the real mechanics + // namely, pressing the button will flip it in the entire unit, which isn't exactly physically possible + if (Command.action == GLFW_PRESS) + { + // button works while it's held down but we can ignore repeats + if (false == Train->controlled->lineContactors.IsForcedOpen()) + { + // open the connectors + // visual feedback + Train->ggStLinOffButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->controlled->lineContactors.ForceOpen(true); + Train->set_paired_open_motor_connectors_button(true); + } + else + { + // potentially close the connectors + OnCommand_motorconnectorsclose(Train, Command); + } + } + else if (Command.action == GLFW_RELEASE) + { + // button released + if (Train->controlled->lineContactors.config.switchType != "toggle") + { + // default button type (impulse) ceases its work on button release + // visual feedback + Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); + + Train->controlled->lineContactors.ForceOpen(false); + Train->set_paired_open_motor_connectors_button(false); + } + } +} + +void TTrain::OnCommand_motorconnectorsclose(TTrain *Train, command_data const &Command) +{ + + // TODO: don't rely on presense of 3d model to determine presence of the switch + if (Train->ggStLinOffButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Open Motor Power Connectors button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + if (Train->controlled->lineContactors.config.switchType == "toggle") + { + // default type of button (impulse) has only one effect on press, but the toggle type can toggle the state + // visual feedback + Train->ggStLinOffButton.UpdateValue(0.0, Train->dsbSwitch); + } + + if (false == Train->controlled->lineContactors.IsForcedOpen()) + { + return; + } // already closed + + Train->controlled->lineContactors.ForceOpen(false); + Train->set_paired_open_motor_connectors_button(false); + } +} + +void TTrain::OnCommand_motordisconnect(TTrain *Train, command_data const &Command) +{ + + if (Train->controlled->TrainType() == train_type::emu ? Train->controlled != Train->occupied : Train->iCabn != 0) + { + // tylko w maszynowym + return; + } + + if (Command.action == GLFW_PRESS) + { + Train->controlled->CutOffEngine(); + } +} + +void TTrain::OnCommand_motoroverloadrelaythresholdtoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + if (true == Train->controlled->ShuntModeAllow ? false == Train->controlled->ShuntMode : false == Train->controlled->MotorOverloadRelayHighThreshold()) + { + // turn on + OnCommand_motoroverloadrelaythresholdsethigh(Train, Command); + } + else + { + // turn off + OnCommand_motoroverloadrelaythresholdsetlow(Train, Command); + } + } +} + +void TTrain::OnCommand_motoroverloadrelaythresholdsetlow(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->controlled->CurrentSwitch(false); + // visual feedback + Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold() ? 1 : 0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_motoroverloadrelaythresholdsethigh(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // only reacting to press, so the switch doesn't flip back and forth if key is held down + Train->controlled->CurrentSwitch(true); + // visual feedback + Train->ggMaxCurrentCtrl.UpdateValue(Train->controlled->MotorOverloadRelayHighThreshold() ? 1 : 0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_motoroverloadrelayreset(TTrain *Train, command_data const &Command) +{ + + if (Train->ggFuseButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Motor Overload Relay Reset button is missing, or wasn't defined"); + } + // return; + } + + if (Command.action == GLFW_PRESS) + { + // visual feedback + Train->ggFuseButton.UpdateValue(1.0, Train->dsbSwitch); + + Train->controlled->FuseOn(); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggFuseButton.UpdateValue(0.0, Train->dsbSwitch); + } +} + +void TTrain::OnCommand_universalrelayreset(TTrain *Train, command_data const &Command) +{ + + auto const itemindex = static_cast(Command.command) - static_cast(user_command::universalrelayreset1); + auto &item = Train->ggRelayResetButtons[itemindex]; + + // NOTE: relay reset switches are impulse-only + if (Command.action == GLFW_PRESS) + { + Train->occupied->UniversalResetButton(itemindex); + // visual feedback + item.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + item.UpdateValue(0.0); + } +} diff --git a/vehicle/cab/screens.cpp b/vehicle/cab/screens.cpp new file mode 100644 index 000000000..e5b2a37f3 --- /dev/null +++ b/vehicle/cab/screens.cpp @@ -0,0 +1,173 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the screens of the cab + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::update_screens(double dt) +{ + for (auto &screen : m_screens) + { + if (screen.updatetimecounter >= 0) + screen.updatetimecounter += dt; + + if (screen.updatetimecounter <= screen.updatetime) + continue; + + screen.updatetimecounter = screen.updatetime > 0 ? 0 : -1; + + auto state_dict = GetTrainState(screen.parameters); + + state_dict->insert("touches", *screen.touch_list); + screen.touch_list->clear(); + + Application.request({screen.script, state_dict, screen.rt}); + } +} + +void TTrain::update_script_screens() +{ + auto &queue{Application.screens()}; + for (auto &entry : m_scriptscreens) + { + if (false == queue.due(*entry.screen)) + { + continue; + } + auto input{GetTrainState(entry.parameters)}; + input->insert("touches", *entry.touch_list); + entry.touch_list->clear(); + queue.submit(entry.screen, std::move(input), id()); + } +} + +bool TTrain::find_screen_surface(std::string const &Target, std::string_view const Kind, TSubModel *&Submodel, ITexture *&Texture) const +{ + Submodel = DynamicObject->mdKabina ? DynamicObject->mdKabina->GetFromName(Target) : + DynamicObject->mdLowPolyInt ? DynamicObject->mdLowPolyInt->GetFromName(Target) : + nullptr; + if (Submodel == nullptr) + { + WriteLog(std::format("{}: submodel {} not found - Ignoring screen", Kind, Target)); + return false; + } + auto const material{Submodel->GetMaterial()}; + if (material <= 0) + { + // sub model nie posiada tekstury lub tekstura wymienna - nie obslugiwana + WriteLog(std::format("{}: invalid texture id {} - Ignoring screen", Kind, material)); + return false; + } + + Texture = &GfxRenderer->Texture(GfxRenderer->Material(material)->GetTexture(0)); + return true; +} + +void TTrain::load_script_screen(cParser &Parser, script_language const Language) +{ + script_screen_entry entry; + // the block is read whole even when the script screens are off + entry.config.deserialize(Parser); + if (entry.config.script.empty()) + { + return; + } + if (auto path{script_screens::screen_script_path(DynamicObject->asBaseDir, entry.config.script)}; path.has_value()) + { + entry.config.script = std::move(*path); + } + else + { + ErrorLog(std::format("Bad script screen: \"{}\" leads outside the game's folder", entry.config.script)); + return; + } + + TSubModel *submodel{nullptr}; + ITexture *texture{nullptr}; + auto &queue{Application.screens()}; + if (false == queue.runs(Language)) + { + // the screens of the language are off + return; + } + if (entry.config.target != "none" && + false == find_screen_surface(entry.config.target, Language == script_language::lua ? "Lua Screen" : "WASM Screen", submodel, texture)) + { + return; + } + + entry.screen = queue.acquire({.kind = script_screen_kind::cab, + .language = Language, + .script = entry.config.script, + .key = std::format("cab:{}:{}:{}", DynamicObject->name(), entry.config.target, entry.config.script), + .texture = texture, + .frames = entry.config.frames}); + if (entry.screen == nullptr) + { + return; + } + if (texture != nullptr) + { + // make the surface static so it doesn't get destroyed by garbage collector if the user spends long time outside cab + texture->create(true); + } + if (false == entry.config.parameters.empty()) + { + entry.parameters = dictionary_source(entry.config.parameters); + } + entry.touch_list = std::make_shared>(); + if (submodel != nullptr) + { + submodel->screen_touch_list = entry.touch_list; + } + m_scriptscreens.emplace_back(std::move(entry)); +} + +const TTrain::screenentry_sequence &TTrain::get_screens() +{ + update_screens(Timer::GetDeltaTime()); + return m_screens; +} diff --git a/vehicle/cab/setup.cpp b/vehicle/cab/setup.cpp new file mode 100644 index 000000000..2796e640c --- /dev/null +++ b/vehicle/cab/setup.cpp @@ -0,0 +1,2041 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// setting the cab up from its definition: its gauges and its buttons + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +// McZapkie-310302 +// wczytywanie pliku z danymi multimedialnymi (dzwieki, kontrolki, kabiny) +bool TTrain::LoadMMediaFile(std::string const &asFileName) +{ + using enum sound_placement; + using enum sound_type; + // initialize sounds so potential entries from previous vehicle don't stick around + std::unordered_map &, sound_placement, float, sound_type, int, double>> internalsounds = { + {"ctrl:", {dsbNastawnikJazdy, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"ctrlscnd:", {dsbNastawnikBocz, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"reverserkey:", {dsbReverserKey, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"buzzer:", {dsbBuzzer, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"buzzershp:", {dsbBuzzerShp, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"radiostop:", {m_radiostop, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"slipalarm:", {dsbSlipAlarm, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"distancecounter:", {m_distancecounterclear, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"tachoclock:", {dsbHasler, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"switch:", {dsbSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"pneumaticswitch:", {dsbPneumaticSwitch, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"airsound:", {rsHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound2:", {rsHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound3:", {rsHissE, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound4:", {rsHissX, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"airsound5:", {rsHissT, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"localbrakesound:", {rsSBHiss, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"localbrakesound2:", {rsSBHissU, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, sound_parameters::amplitude, 100.0}}, + {"brakesound:", {rsBrake, internal, -1, single, sound_parameters::amplitude | sound_parameters::frequency, 100.0}}, + {"fadesound:", {rsFadeSound, internal, EU07_SOUND_CABCONTROLSCUTOFFRANGE, single, 0, 100.0}}, + {"runningnoise:", {rsRunningNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, + {"resonancenoise:", {rsResonanceNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, + {"windsound:", {rsWindSound, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, + {"huntingnoise:", {rsHuntingNoise, internal, EU07_SOUND_GLOBALRANGE, single, sound_parameters::amplitude | sound_parameters::frequency, occupied->Vmax()}}, + {"rainsound:", {m_rainsound, internal, -1, single, 0, 100.0}}, + }; + for (auto &[soundname, soundsource] : internalsounds) + { + std::get &>(soundsource).reset(); + } + // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment + m_radiosound.owner(DynamicObject); + m_fmradiosound.owner(DynamicObject); + CabSoundLocations.clear(); + + cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); + // NOTE: yaml-style comments are disabled until conflict in use of # is resolved + // parser.addCommentStyle( "#", "\n" ); + std::string token; + do + { + token = ""; + parser.getTokens(); + parser >> token; + } while (token != "" && token != "internaldata:"); + + if (token == "internaldata:") + { + + do + { + token = ""; + parser.getTokens(); + parser >> token; + + auto lookup{internalsounds.find(token)}; + if (lookup == internalsounds.end()) + { + continue; + } + + auto const soundconfig{lookup->second}; + sound_source sound{std::get(soundconfig), std::get(soundconfig)}; + sound.deserialize(parser, std::get(soundconfig), std::get(soundconfig), static_cast(std::get(soundconfig))); + sound.owner(DynamicObject); + std::get &>(soundconfig) = sound; + } while (token != ""); + + // assign default samples to sound emitters which weren't included in the config file + if (!m_rainsound) + { + sound_source rainsound; + rainsound.deserialize("rainsound_default", single); + rainsound.owner(DynamicObject); + m_rainsound = rainsound; + } + if (!rsSBHiss) + { + // fallback for vehicles without defined local brake hiss sound + rsSBHiss = rsHiss; + } + if (!rsSBHissU) + { + // fallback for vehicles without defined local brake hiss sound + rsSBHissU = rsHissU; + } + if (rsBrake) + { + rsBrake->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); + } + if (rsResonanceNoise) + { + rsResonanceNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); + } + if (rsWindSound) + { + rsWindSound->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); + } + if (rsRunningNoise) + { + rsRunningNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); + } + if (rsHuntingNoise) + { + rsHuntingNoise->m_frequencyfactor /= static_cast(1 + occupied->Vmax()); + } + } + std::vector>> sounds = { + dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, + rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, + m_rainsound, m_radiostop}; + for (auto &sound : sounds) + { + if (sound.get()) + { + CabSoundLocations.emplace_back(sound, sound.get()->offset()); + } + } + + return true; +} + +bool TTrain::InitializeCab(int NewCabNo, std::string const &asFileName) +{ + m_controlmapper.clear(); + // clear python screens + m_screens.clear(); + m_scriptscreens.clear(); + // reset sound positions + auto const nullvector{glm::vec3()}; + std::vector>> sounds = { + dsbReverserKey, dsbNastawnikJazdy, dsbNastawnikBocz, dsbSwitch, dsbPneumaticSwitch, rsHiss, rsHissU, rsHissE, rsHissX, rsHissT, rsSBHiss, + rsSBHissU, rsFadeSound, rsRunningNoise, rsResonanceNoise, rsWindSound, rsHuntingNoise, dsbHasler, dsbBuzzer, dsbBuzzerShp, dsbSlipAlarm, m_distancecounterclear, + m_rainsound, m_radiostop}; + for (auto const &sound : sounds) + { + if (sound.get()) + { + sound.get()->offset(nullvector); + } + } + m_radiosound.offset(nullvector); + m_fmradiosound.offset(nullvector); + m_fmradiopresent = false; + for (auto const &[soundsource, soundoffset] : CabSoundLocations) + { + if (soundsource.get() && soundsource.get()->offset() == nullvector) + { + soundsource.get()->offset(soundoffset); + } + } + // reset view angles + pMechViewAngle = {0.0, 0.0}; + + is_cab_initialized = true; // the attempt may fail, but it's the attempt that counts + + bool parse = false; + int cabindex = 0; + DynamicObject->mdKabina = nullptr; // likwidacja wskaźnika na dotychczasową kabinę + switch (NewCabNo) + { // ustalenie numeru kabiny do wczytania + case -1: + cabindex = 2; + break; + case 1: + cabindex = 1; + break; + case 0: + cabindex = 0; + break; + default: + break; + } + iCabn = cabindex; + + std::string cabstr("cab" + std::to_string(cabindex) + "definition:"); + + cParser parser(asFileName, cParser::buffer_FILE, DynamicObject->asBaseDir, true, std::vector(), true); + // NOTE: yaml-style comments are disabled until conflict in use of # is resolved + // parser.addCommentStyle( "#", "\n" ); + std::string token; + do + { + // szukanie kabiny + token = ""; + parser.getTokens(); + parser >> token; + } while (token != "" && token != cabstr); + + if (token == cabstr) + { + // jeśli znaleziony wpis kabiny + Cabine[cabindex].Load(parser); + // NOTE: the position and angle definitions depend on strict entry order + // TODO: refactor into more flexible arrangement + parser.getTokens(); + parser >> token; + if (token == std::string("driver" + std::to_string(cabindex) + "angle:")) + { + // camera view angle + parser.getTokens(2, false); + // angle is specified in degrees but internally stored in radians + glm::vec2 viewangle; + parser >> viewangle.y // yaw first, then pitch + >> viewangle.x; + pMechViewAngle = glm::radians(viewangle); + + Global.pCamera.Angle.x = pMechViewAngle.x; + Global.pCamera.Angle.y = pMechViewAngle.y; + + parser.getTokens(); + parser >> token; + } + if (token == std::string("driver" + std::to_string(cabindex) + "pos:")) + { + // pozycja poczatkowa maszynisty + parser.getTokens(3, false); + parser >> pMechOffset.x >> pMechOffset.y >> pMechOffset.z; + pMechSittingPosition = pMechOffset; + + parser.getTokens(); + parser >> token; + } + // ABu: pozycja siedzaca mechanika + if (token == std::string("driver" + std::to_string(cabindex) + "sitpos:")) + { + // ABu 180404 pozycja siedzaca maszynisty + parser.getTokens(3, false); + parser >> pMechSittingPosition.x >> pMechSittingPosition.y >> pMechSittingPosition.z; + + parser.getTokens(); + parser >> token; + } + // else parse=false; + do + { + if (parse == true) + { + token = ""; + parser.getTokens(); + parser >> token; + } + else + { + parse = true; + } + // inicjacja kabiny + // Ra 2014-08: zmieniamy zasady - zamiast przypisywać submodel do + // istniejących obiektów animujących + // będziemy teraz uaktywniać obiekty animujące z tablicy i podawać im + // submodel oraz wskaźnik na parametr + if (token == std::string("cab" + std::to_string(cabindex) + "model:")) + { + // model kabiny + parser.getTokens(); + parser >> token; + std::ranges::replace(token, '\\', '/'); + if (token != "none") + { + // bieżąca sciezka do tekstur to dynamic/... + Global.asCurrentTexturePath = DynamicObject->asBaseDir; + // szukaj kabinę jako oddzielny model + // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory + replace_slashes(token); + erase_leading_slashes(token); + if (token[0] == '/') + { + token.erase(0, 1); + } + TModel3d *kabina = TModelsManager::GetModel(DynamicObject->asBaseDir + token, true, true, Global.network_servers.empty() && !Global.network_client ? 0 : id()); + // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = paths::textures; + // if (DynamicObject->mdKabina!=k) + if (kabina != nullptr) + { + DynamicObject->mdKabina = kabina; // nowa kabina + } + //(mdKabina) może zostać to samo po przejściu do innego członu bez + // zmiany kabiny, przy powrocie musi być wiązanie ponowne + // else + // break; //wyjście z pętli, bo model zostaje bez zmian + } + else if (cabindex == 1) + { + // model tylko, gdy nie ma kabiny 1 + // McZapkie-170103: szukaj elementy kabiny w glownym modelu + DynamicObject->mdKabina = DynamicObject->mdModel; + } + clear_cab_controls(); + } + /* + if (nullptr == DynamicObject->mdKabina) + { + // don't bother with other parts until the cab is initialised + continue; + } + */ + else if (true == initialize_gauge(parser, token, cabindex)) + { + // matched the token, grab the next one + continue; + } + else if (true == initialize_button(parser, token, cabindex)) + { + // matched the token, grab the next one + continue; + } + // TODO: add "pydestination:" + else if (token == "pyscreen:") + { + screen_entry screen; + screen.deserialize(parser); + if (false == screen.script.empty() && substr_path(screen.script).empty()) + { + screen.script = DynamicObject->asBaseDir + screen.script; + } + + ITexture *tex = nullptr; + TSubModel *submodel = nullptr; + if (screen.target != "none") + { + if (false == find_screen_surface(screen.target, "Python Screen", submodel, tex)) + { + continue; + } + } + else + { + // TODO: fix leak + tex = ITexture::null_texture(); + tex->make_stub(); + } + + tex->create(true); // make the surface static so it doesn't get destroyed by garbage + // collector if the user spends long time outside cab + // TBD, TODO: keep texture handles around, so we can undo the static switch when the + // user changes cabs? + auto rt = std::make_shared(); + rt->shared_tex = tex; + + // record renderer and material binding for future update requests + m_screens.emplace_back(screen); + m_screens.back().rt = rt; + + m_screens.back().touch_list = std::make_shared>(); + if (submodel) + submodel->screen_touch_list = m_screens.back().touch_list; + + if (Global.python_displaywindows) + m_screens.back().viewer = std::make_unique(rt, m_screens.back().touch_list, m_screens.back().script); + } + else if (token == "luascreen:") + { + load_script_screen(parser, script_language::lua); + } + else if (token == "wasmscreen:") + { + load_script_screen(parser, script_language::wasm); + } + else if (token == "pyscreenupdatetime:") + { + parser.getTokens(); + parser >> ScreenUpdateRate; + } + else if (token == "fmradio:") + { + // broadcast radio receiver, the parameter selects character of its sound + std::string fmradiotype; + parser.getTokens(); + parser >> fmradiotype; + m_fmradiotype = (fmradiotype == "wooden" ? audio::fmradio_type::wooden : audio::fmradio_type::cheap); + m_fmradiopresent = true; + } + else if (token == "fmradiospeaker:") + { + // submodel marking location of the receiver speaker, the sound is emitted from there + std::string speakername; + parser.getTokens(); + parser >> speakername; + TSubModel *speaker{nullptr}; + for (auto const *source : {DynamicObject->mdKabina, DynamicObject->mdLowPolyInt}) + { + if (source != nullptr && (speaker = source->GetFromName(speakername)) != nullptr) + { + break; + } + } + if (speaker != nullptr) + { + m_fmradiosound.offset(speaker->offset(1.f)); + } + else + { + ErrorLog("Bad config: failed to locate fm radio speaker submodel \"" + speakername + "\"", logtype::model); + } + m_fmradiopresent = true; + } + // btLampkaUnknown`"unknown",mdKabina,false); + } while (token != "" + // TODO: enable full per-cab deserialization when/if .mmd files get proper per-cab switch configuration + // && ( token != "cab1definition:" ) + // && ( token != "cab2definition:" ) + && token != "cab0definition:"); + for (auto &screen : m_screens) + { + if (screen.updatetime > 0) + { + screen.updatetime = std::max((int)screen.updatetime, Global.PythonScreenUpdateRate) * 0.001; + } + if (screen.updatetime == 0) + { + screen.updatetime = std::max(Global.PythonScreenUpdateRate, ScreenUpdateRate) * 0.001; + } + if (screen.updatetime < -1) + { + screen.updatetime = -screen.updatetime * 0.001; + } + } + } + else + { + return false; + } + /* + if (DynamicObject->mdKabina) + { + */ + // configure placement of sound emitters which aren't bound with any device model, and weren't placed manually + auto const caboffset{glm::dvec3{(Cabine[cabindex].CabPos1 + Cabine[cabindex].CabPos2) * 0.5f} + glm::dvec3{0, 1, 0}}; + // NOTE: since radiosound is an incomplete template not using std::optional it gets a special treatment + if (m_radiosound.offset() == nullvector) + { + m_radiosound.offset(btLampkaRadio.model_offset()); + } + if (m_radiosound.offset() == nullvector) + { + m_radiosound.offset(caboffset); + } + if (m_fmradiosound.offset() == nullvector) + { + m_fmradiosound.offset(caboffset); + } + if (m_fmradiopresent && false == m_fmradiopower && m_controlmapper.contains("fmradiovolume_sw:") && false == m_controlmapper.contains("fmradio_sw:")) + { + // receivers without dedicated switch are switched with the volume knob, so it has to start at the off position + m_fmradiovolume = 0.f; + } + std::vector>, glm::vec3>> soundlocations = { + {dsbReverserKey, ggDirKey.model_offset()}, + {dsbNastawnikJazdy, ggJointCtrl.model_offset()}, + {dsbNastawnikJazdy, ggMainCtrl.model_offset()}, // NOTE: fallback for vehicles without universal controller + {dsbNastawnikBocz, ggScndCtrl.model_offset()}, + {dsbSwitch, caboffset}, + {dsbPneumaticSwitch, caboffset}, + {rsHiss, ggBrakeCtrl.model_offset()}, + {rsHissU, ggBrakeCtrl.model_offset()}, + {rsHissE, ggBrakeCtrl.model_offset()}, + {rsHissX, ggBrakeCtrl.model_offset()}, + {rsHissT, ggBrakeCtrl.model_offset()}, + {rsSBHiss, ggLocalBrake.model_offset()}, + {rsSBHiss, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located + {rsSBHissU, ggLocalBrake.model_offset()}, + {rsSBHissU, ggBrakeCtrl.model_offset()}, // NOTE: fallback if the local brake model can't be located + {rsFadeSound, caboffset}, + {rsRunningNoise, caboffset}, + {rsResonanceNoise, caboffset}, + {rsWindSound, caboffset}, + {rsHuntingNoise, caboffset}, + {dsbHasler, caboffset}, + {dsbBuzzer, btLampkaCzuwaka.model_offset()}, + {dsbBuzzerShp, btLampkaCzuwaka.model_offset()}, + {dsbSlipAlarm, caboffset}, + {m_distancecounterclear, btLampkaCzuwaka.model_offset()}, + {m_rainsound, caboffset}, + {m_radiostop, m_radiosound.offset()}, + }; + for (auto const &[soundsource, soundoffset] : soundlocations) + { + if (soundsource.get() && soundsource.get()->offset() == nullvector) + { + soundsource.get()->offset(soundoffset); + } + } + // second pass, in case some items received no positioning due to missing submodels etc + for (auto const &[soundsource, soundoffset] : soundlocations) + { + if (soundsource.get() && soundsource.get()->offset() == nullvector) + { + soundsource.get()->offset(caboffset); + } + } + + if (DynamicObject->mdKabina) + { + DynamicObject->mdKabina->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego + // the vehicle has a cab, a player is in it: the odometer store keeps the vehicle also when its type has no + // driver's brake valve (eu07/maszyna#72) + DynamicObject->physics->ShowOdometer(); + } + + set_cab_controls(NewCabNo < 0 ? 2 : NewCabNo); + + // set pantograpths (hujhujhuj) + change_pantograph_selection(0); + + /* + return true; +} +return (token == "none"); +*/ + return true; +} + +glm::dvec3 TTrain::MirrorPosition(bool lewe) +{ // zwraca współrzędne widoku kamery z lusterka + auto const shiftdirection{(lewe ? -1 : 1) * (iCabn == 2 ? 1 : -1)}; + + return DynamicObject->mMatrix * + glm::dvec4(occupied->Dim.W * (0.5 * shiftdirection) + 0.2 * shiftdirection, 1.5 + Cabine[iCabn].CabPos1.y, std::lerp(Cabine[iCabn].CabPos1.z, Cabine[iCabn].CabPos2.z, 0.5), 1.0); +}; + +// clears state of all cabin controls +void TTrain::clear_cab_controls() +{ + // indicators exposed to custom control devices + btLampkaSHP.Clear(0); + btLampkaCzuwaka.Clear(1); + btLampkaOpory.Clear(2); + btLampkaWylSzybki.Clear(3); + btLampkaNadmSil.Clear(4); + btLampkaStyczn.Clear(5); + btLampkaPoslizg.Clear(6); + btLampkaNadmPrzetw.Clear(controlled->TrainType() == train_type::emu ? -1 : 7); // EN57 nie ma tej lampki + btLampkaPrzetwOff.Clear(controlled->TrainType() == train_type::emu ? 7 : -1); // za to ma tę + btLampkaNadmSpr.Clear(8); + btLampkaNadmWent.Clear(9); + btLampkaWysRozr.Clear(controlled->TrainType() == train_type::et22 ? -1 : 10); // ET22 nie ma tej lampki + btLampkaOgrzewanieSkladu.Clear(11); + // overheat indicator lamps + btLampkaOilOverheat.Clear(-1); + btLampkaWaterOverheat.Clear(-1); + btLampkaWaterAuxOverheat.Clear(-1); + btLampkaEngineOverheat.Clear(-1); + btHaslerBrakes.Clear(12); // ciśnienie w cylindrach do odbijania na haslerze + btHaslerCurrent.Clear(13); // prąd na silnikach do odbijania na haslerze + // Numer 14 jest używany dla buczka SHP w update_sounds() + // Jeśli ustawiamy nową wartość dla PoKeys wolna jest 15 + + // other cab controls + // TODO: arrange in more readable manner, and eventually refactor + ggJointCtrl.Clear(); + ggMainCtrl.Clear(); + ggMainCtrlAct.Clear(); + ggScndCtrl.Clear(); + ggScndCtrlButton.Clear(); + ggScndCtrlOffButton.Clear(); + ggDistanceCounterButton.Clear(); + ggDirKey.Clear(); + ggDirForwardButton.Clear(); + ggDirNeutralButton.Clear(); + ggDirBackwardButton.Clear(); + ggBrakeCtrl.Clear(); + ggLocalBrake.Clear(); + ggAlarmChain.Clear(); + ggBrakeProfileCtrl.Clear(); + ggBrakeProfileG.Clear(); + ggBrakeProfileR.Clear(); + ggBrakeOperationModeCtrl.Clear(); + ggWiperSw.Clear(); + ggMaxCurrentCtrl.Clear(); + ggAutoRelayButton.Clear(); + ggMainOffButton.Clear(); + ggMainOnButton.Clear(); + for (auto &remotelinebreaker : m_remotelinebreakers) + { + remotelinebreaker.main_switch.Clear(); + remotelinebreaker.on_button.Clear(); + remotelinebreaker.off_button.Clear(); + remotelinebreaker.held_without_switch = false; + } + ggSecurityResetButton.Clear(); + ggSHPResetButton.Clear(); + ggReleaserButton.Clear(); + ggSpringBrakeOnButton.Clear(); + ggSpringBrakeOffButton.Clear(); + ggUniveralBrakeButton1.Clear(); + ggUniveralBrakeButton2.Clear(); + ggUniveralBrakeButton3.Clear(); + ggEPFuseButton.Clear(); + ggSandButton.Clear(); + ggAutoSandButton.Clear(); + ggAntiSlipButton.Clear(); + ggHornButton.Clear(); + ggHornLowButton.Clear(); + ggHornHighButton.Clear(); + ggWhistleButton.Clear(); + ggHelperButton.Clear(); + ggNextCurrentButton.Clear(); + ggSpeedControlIncreaseButton.Clear(); + ggSpeedControlDecreaseButton.Clear(); + ggSpeedControlPowerIncreaseButton.Clear(); + ggSpeedControlPowerDecreaseButton.Clear(); + for (auto &speedctrlbutton : ggSpeedCtrlButtons) + { + speedctrlbutton.Clear(); + } + for (auto &universal : ggUniversals) + { + universal.Clear(); + } + for (auto &item : ggInverterEnableButtons) + { + item.Clear(); + } + for (auto &item : ggInverterDisableButtons) + { + item.Clear(); + } + for (auto &item : ggInverterToggleButtons) + { + item.Clear(); + } + for (auto &relayresetbutton : ggRelayResetButtons) + { + relayresetbutton.Clear(); + } + ggInstrumentLightButton.Clear(); + ggDashboardLightButton.Clear(); + ggTimetableLightButton.Clear(); + // hunter-091012 + ggCabLightDimButton.Clear(); + ggCompartmentLightsButton.Clear(); + ggCompartmentLightsOnButton.Clear(); + ggCompartmentLightsOffButton.Clear(); + ggBatteryButton.Clear(); + ggBatteryOnButton.Clear(); + ggBatteryOffButton.Clear(); + ggCabActivationButton.Clear(); + //------- + ggFuseButton.Clear(); + ggConverterFuseButton.Clear(); + ggStLinOffButton.Clear(); + ggRadioChannelSelector.Clear(); + ggRadioChannelPrevious.Clear(); + ggRadioChannelNext.Clear(); + ggRadioStop.Clear(); + ggRadioTest.Clear(); + ggRadioCall1.Clear(); + ggRadioCall3.Clear(); + ggRadioVolumeSelector.Clear(); + ggRadioVolumePrevious.Clear(); + ggRadioVolumeNext.Clear(); + ggRadioOnButton.Clear(); + ggRadioOffButton.Clear(); + ggRadioFuseOnButton.Clear(); + ggRadioFuseOffButton.Clear(); + ggDoorLeftPermitButton.Clear(); + ggDoorRightPermitButton.Clear(); + ggDoorPermitPresetButton.Clear(); + ggDoorLeftButton.Clear(); + ggDoorRightButton.Clear(); + ggDoorLeftOnButton.Clear(); + ggDoorRightOnButton.Clear(); + ggDoorLeftOffButton.Clear(); + ggDoorRightOffButton.Clear(); + ggDoorAllOnButton.Clear(); + ggDoorAllOffButton.Clear(); + ggTrainHeatingButton.Clear(); + ggSignallingButton.Clear(); + ggDoorSignallingButton.Clear(); + ggDoorStepButton.Clear(); + ggDepartureSignalButton.Clear(); + ggCompressorButton.Clear(); + ggCompressorLocalButton.Clear(); + ggConverterButton.Clear(); + ggConverterOffButton.Clear(); + ggConverterLocalButton.Clear(); + ggMainButton.Clear(); + /* + ggPantFrontButton.Clear(); + ggPantRearButton.Clear(); + ggPantFrontButtonOff.Clear(); + ggPantRearButtonOff.Clear(); + */ + ggPantAllDownButton.Clear(); + ggPantSelectedButton.Clear(); + ggPantSelectedDownButton.Clear(); + ggPantValvesButton.Clear(); + ggPantCompressorButton.Clear(); + ggPantCompressorValve.Clear(); + + ggPantValvesOff.Clear(); + ggPantValvesUpdate.Clear(); + + ggI1B.Clear(); + ggI2B.Clear(); + ggI3B.Clear(); + ggItotalB.Clear(); + ggOilPressB.Clear(); + ggWater1TempB.Clear(); + + ggClockSInd.Clear(); + ggClockMInd.Clear(); + ggClockHInd.Clear(); + ggEngineVoltage.Clear(); + ggLVoltage.Clear(); + ggMainGearStatus.Clear(); + ggIgnitionKey.Clear(); + + ggWaterPumpBreakerButton.Clear(); + ggWaterPumpButton.Clear(); + ggWaterHeaterBreakerButton.Clear(); + ggWaterHeaterButton.Clear(); + ggWaterCircuitsLinkButton.Clear(); + ggFuelPumpButton.Clear(); + ggOilPumpButton.Clear(); + ggOilFuelPumpButton.Clear(); + ggTractionModeSwitch.Clear(); + ggGensetButton.Clear(); + ggMotorBlowersFrontButton.Clear(); + ggMotorBlowersRearButton.Clear(); + ggMotorBlowersAllOffButton.Clear(); + + btLampkaPrzetw.Clear(); + btLampkaPrzetwB.Clear(); + btLampkaPrzetwBOff.Clear(); + btLampkaPrzetwAOff.Clear(); + btLampkaPrzekRozn.Clear(); + btLampkaPrzekRoznPom.Clear(); + btLampkaUkrotnienie.Clear(); + btLampkaHamPosp.Clear(); + btLampkaWylSzybkiOff.Clear(); + btLampkaWylSzybkiB.Clear(); + btLampkaWylSzybkiBOff.Clear(); + btLampkaMainBreakerReady.Clear(); + btLampkaMainBreakerBlinkingIfReady.Clear(); + btLampkaBezoporowa.Clear(); + btLampkaBezoporowaB.Clear(); + btLampkaMaxSila.Clear(); + btLampkaPrzekrMaxSila.Clear(); + btLampkaRadio.Clear(); + btLampkaRadioMessage.Clear(); + btLampkaRadioStop.Clear(); + btLampkaHamulecReczny.Clear(); + btLampkaBlokadaDrzwi.Clear(); + btLampkaDoorLockOff.Clear(); + for (auto &universal : btUniversals) + { + universal.Clear(); + } + btInstrumentLight.Clear(); + btDashboardLight.Clear(); + btTimetableLight.Clear(); + btLampkaWentZaluzje.Clear(); + btLampkaDoorLeft.Clear(); + btLampkaDoorRight.Clear(); + btLampkaDepartureSignal.Clear(); + btLampkaRezerwa.Clear(); + btLampkaBoczniki.Clear(); + btLampkaBocznik1.Clear(); + btLampkaBocznik2.Clear(); + btLampkaBocznik3.Clear(); + btLampkaBocznik4.Clear(); + btLampkaGear1.Clear(); + btLampkaGear2.Clear(); + btLampkaHydroLockup.Clear(); + btLampkaRadiotelefon.Clear(); + btLampkaHamienie.Clear(); + btLampkaBrakingOff.Clear(); + btLampkaED.Clear(); + btLampkaBrakeProfileG.Clear(); + btLampkaBrakeProfileP.Clear(); + btLampkaBrakeProfileR.Clear(); + btLampkaSpringBrakeActive.Clear(); + btLampkaSpringBrakeInactive.Clear(); + btLampkaSprezarka.Clear(); + btLampkaSprezarkaB.Clear(); + btLampkaSprezarkaOff.Clear(); + btLampkaSprezarkaBOff.Clear(); + btLampkaFuelPumpOff.Clear(); + btLampkaOilPump.Clear(); + btLampkaNapNastHam.Clear(); + btLampkaOporyB.Clear(); + btLampkaStycznB.Clear(); + btLampkaHamowanie1zes.Clear(); + btLampkaHamowanie2zes.Clear(); + btLampkaNadmPrzetwB.Clear(); + btLampkaHVoltageB.Clear(); + btLampkaForward.Clear(); + btLampkaBackward.Clear(); + btLampkaNeutral.Clear(); + // light indicators + btLampkaUpperLight.Clear(); + btLampkaLeftLight.Clear(); + btLampkaRightLight.Clear(); + btLampkaLeftEndLight.Clear(); + btLampkaRightEndLight.Clear(); + btLampkaRearUpperLight.Clear(); + btLampkaRearLeftLight.Clear(); + btLampkaRearRightLight.Clear(); + btLampkaRearLeftEndLight.Clear(); + btLampkaRearRightEndLight.Clear(); + // others + btLampkaMalfunction.Clear(); + btLampkaMalfunctionB.Clear(); + btLampkaMotorBlowers.Clear(); + btLampkaCoolingFans.Clear(); + btLampkaLouvresClosed.Clear(); + btLampkaTempomat.Clear(); + btLampkaDistanceCounter.Clear(); + + ggLeftLightButton.Clear(); + ggRightLightButton.Clear(); + ggUpperLightButton.Clear(); + ggDimHeadlightsButton.Clear(); + ggModernLightDimSw.Clear(); + ggLeftEndLightButton.Clear(); + ggRightEndLightButton.Clear(); + ggLightsButton.Clear(); + ggCompressorListButton.Clear(); + // hunter-230112 + ggRearLeftLightButton.Clear(); + ggRearRightLightButton.Clear(); + ggRearUpperLightButton.Clear(); + ggRearLeftEndLightButton.Clear(); + ggRearRightEndLightButton.Clear(); +} + +// NOTE: we can get rid of this function once we have per-cab persistent state +void TTrain::set_cab_controls(int const Cab) +{ + // switches + // battery + ggBatteryButton.PutValue(ggBatteryButton.type() == TGaugeType::push ? 0.5f : occupied->lowVoltage.Is24vAvailable() ? 1.f : 0.f); + // activation + ggCabActivationButton.PutValue(ggCabActivationButton.type() == TGaugeType::push ? 0.5f : occupied->IsCabMaster() ? 1.f : 0.f); + // line breaker + if (ggMainButton.SubModel != nullptr) + { // instead of single main button there can be on/off pair + ggMainButton.PutValue(ggMainButton.type() == TGaugeType::push ? 0.5f : m_linebreakerstate != linebreaker::state::open ? 1.f : 0.f); + } + // line breakers of the other vehicles in multiple + for (std::size_t index = 0; index < m_remotelinebreakers.size(); ++index) + { + auto &mainswitch{m_remotelinebreakers[index].main_switch}; + if (mainswitch.SubModel == nullptr) + { + continue; + } + if (mainswitch.type() == TGaugeType::push) + { + mainswitch.PutValue(0.5f); + continue; + } + auto const *engine{remote_engine(index)}; + mainswitch.PutValue(engine != nullptr && engine_start::remote_switch::is_running(*engine) ? 1.f : 0.f); + } + + if (ggModernLightDimSw.SubModel != nullptr) + { + occupied->SetDimmerPosition(occupied->modernDimmerDefaultPosition); + ggModernLightDimSw.PutValue(static_cast(occupied->modernDimmerDefaultPosition)); + } + + // Init separate buttons + if (ggPantValvesUpdate.SubModel != nullptr) + { + ggPantValvesUpdate.PutValue(0.f); + } + if (ggPantValvesOff.SubModel != nullptr) + { + ggPantValvesOff.PutValue(0.f); + } + + // motor connectors + ggStLinOffButton.PutValue(controlled->lineContactors.IsForcedOpen() ? 1.f : 0.f); + // radio + ggRadioChannelSelector.PutValue(static_cast((Dynamic()->Mechanik ? Dynamic()->Mechanik->RadioChannel() : 1) - 1)); + // pantographs + /* + if( occupied->PantSwitchType != "impulse" ) { + if( ggPantFrontButton.SubModel ) { + ggPantFrontButton.PutValue( + ( controlled->Pantographs[VehicleEnd::front].valve.is_enabled ? + 1.f : + 0.f ) ); + } + if( ggPantFrontButtonOff.SubModel ) { + ggPantFrontButtonOff.PutValue( + ( controlled->Pantographs[VehicleEnd::front].valve.is_disabled ? + 1.f : + 0.f ) ); + } + } + if( occupied->PantSwitchType != "impulse" ) { + if( ggPantRearButton.SubModel ) { + ggPantRearButton.PutValue( + ( controlled->Pantographs[VehicleEnd::rear].valve.is_enabled ? + 1.f : + 0.f ) ); + } + if( ggPantRearButtonOff.SubModel ) { + ggPantRearButtonOff.PutValue( + ( controlled->Pantographs[VehicleEnd::rear].valve.is_disabled ? + 1.f : + 0.f ) ); + } + } + */ + // front/end pantograph selection is relative to occupied cab + if (ggPantSelectedButton.type() == TGaugeType::toggle) + { + ggPantSelectedButton.PutValue(pantographUnit->pantographAir.valve.is_enabled ? 1.f : 0.f); + } + else + { + if (false == m_controlmapper.contains("pantselectedoff_sw:")) + { + // single impulse switch arrangement, with neutral position mid-way + ggPantSelectedButton.PutValue(0.5f); + } + } + if (ggPantSelectedDownButton.type() == TGaugeType::toggle) + { + ggPantSelectedDownButton.PutValue(pantographUnit->pantographAir.valve.is_disabled ? 1.f : 0.f); + } + + ggPantValvesButton.PutValue(0.5f); + + // auxiliary compressor + ggPantCompressorValve.PutValue(controlled->pantographAir.IsConnectedToMainReservoir() ? 0.f : // default setting is pantographs connected with primary tank + 1.f); + ggPantCompressorButton.PutValue(pantographUnit->pantographAir.IsCompressorRunning() ? 1.f : 0.f); + // converter + if (occupied->converter.config.switchType != "impulse") + { + ggConverterButton.PutValue(occupied->converter.IsAllowed() ? 1.f : 0.f); + } + ggConverterLocalButton.PutValue(occupied->converter.LocalSwitchOn() ? 1.f : 0.f); + // compressor + ggCompressorButton.PutValue(controlled->air.compressor.IsAllowed() ? 1.f : 0.f); + ggCompressorLocalButton.PutValue(controlled->air.compressor.LocalSwitchOn() ? 1.f : 0.f); + ggCompressorListButton.PutValue(static_cast(occupied->air.compressor.ListPosition() - 1)); + // motor overload relay threshold / shunt mode + ggMaxCurrentCtrl.PutValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold() ? 1.f : 0.f); + // automatic relays (AutoRelay) + ggAutoRelayButton.PutValue(occupied->AutoRelayFlag() ? 1.f : 0.f); + // lights + ggLightsButton.PutValue(static_cast(occupied->LightsPos() - 1)); + + auto const vehicleend{cab_to_end(Cab)}; + + if ((occupied->LitLights()[vehicleend] & light::headlight_left) != 0) + { + ggLeftLightButton.PutValue(1.f); + } + if ((occupied->LitLights()[vehicleend] & light::headlight_right) != 0) + { + ggRightLightButton.PutValue(1.f); + } + if ((occupied->LitLights()[vehicleend] & light::headlight_upper) != 0) + { + ggUpperLightButton.PutValue(1.f); + } + if ((occupied->LitLights()[vehicleend] & light::redmarker_left) != 0) + { + if (ggLeftEndLightButton.SubModel != nullptr) + { + ggLeftEndLightButton.PutValue(1.f); + } + else + { + ggLeftLightButton.PutValue(-1.f); + } + } + if ((occupied->LitLights()[vehicleend] & light::redmarker_right) != 0) + { + if (ggRightEndLightButton.SubModel != nullptr) + { + ggRightEndLightButton.PutValue(1.f); + } + else + { + ggRightLightButton.PutValue(-1.f); + } + } + if (1 == DynamicObject->physics->DimmerPosition()) + { + ggDimHeadlightsButton.PutValue(static_cast(DynamicObject->physics->DimmerPosition())); + } + // cab lights + if (true == Cabine[Cab].bLightDim) + { + ggCabLightDimButton.PutValue(1.f); + } + // compartment lights + ggCompartmentLightsButton.PutValue(ggCompartmentLightsButton.type() == TGaugeType::push ? 0.5f : occupied->CompartmentLights.is_enabled ? 1.f : 0.f); + // instrument lights + ggInstrumentLightButton.PutValue(InstrumentLightActive ? 1.f : 0.f); + ggDashboardLightButton.PutValue(DashboardLightActive ? 1.f : 0.f); + ggTimetableLightButton.PutValue(TimetableLightActive ? 1.f : 0.f); + // doors permits + if (false == ggDoorLeftPermitButton.is_push()) + { + ggDoorLeftPermitButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit ? 1.f : 0.f); + } + if (false == ggDoorRightPermitButton.is_push()) + { + ggDoorRightPermitButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit ? 1.f : 0.f); + } + ggDoorPermitPresetButton.PutValue(static_cast(occupied->Doors.permit_preset)); + // door controls + ggDoorLeftButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].is_closed ? 0.f : 1.f); + ggDoorRightButton.PutValue(occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].is_closed ? 0.f : 1.f); + // door lock + ggDoorSignallingButton.PutValue(occupied->Doors.lock_enabled ? 1.f : 0.f); + // door step + if (false == ggDoorStepButton.is_push()) + { + ggDoorStepButton.PutValue(occupied->Doors.step_enabled ? 1.f : 0.f); + } + // heating + if (false == ggTrainHeatingButton.is_push() && false == occupied->trainHeating.config.switchImpulse) + { + ggTrainHeatingButton.PutValue(controlled->trainHeating.IsOn() ? 1.f : 0.f); + } + // brake acting time + if (ggBrakeProfileCtrl.SubModel != nullptr) + { + ggBrakeProfileCtrl.PutValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 2.f : static_cast(occupied->brakes.delaySetting - 1)); + } + if (ggBrakeProfileG.SubModel != nullptr) + { + ggBrakeProfileG.PutValue(occupied->brakes.delaySetting == bdelay_G ? 1.f : 0.f); + } + if (ggBrakeProfileR.SubModel != nullptr) + { + ggBrakeProfileR.PutValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 1.f : 0.f); + } + + if (ggWiperSw.SubModel != nullptr) + { + ggWiperSw.PutValue(static_cast(occupied->WiperSwitchPos())); + } + + if (ggBrakeOperationModeCtrl.SubModel != nullptr) + { + ggBrakeOperationModeCtrl.PutValue(occupied->brakes.operatingMode > 0 ? static_cast(std::log2(occupied->brakes.operatingMode)) : 0); + } + // alarm chain + ggAlarmChain.PutValue(controlled->brakes.alarmChain ? 1.f : 0.f); + // brake signalling + ggSignallingButton.PutValue(controlled->Signalling() ? 1.f : 0.f); + // multiple-unit current indicator source + ggNextCurrentButton.PutValue(ShowNextCurrent ? 1.f : 0.f); + // water pump + ggWaterPumpBreakerButton.PutValue(controlled->WaterPump.breaker ? 1.f : 0.f); + if (ggWaterPumpButton.type() != TGaugeType::push) + { + ggWaterPumpButton.PutValue(controlled->WaterPump.is_enabled ? 1.f : 0.f); + } + // water heater + ggWaterHeaterBreakerButton.PutValue(controlled->WaterHeater.breaker ? 1.f : 0.f); + ggWaterHeaterButton.PutValue(controlled->WaterHeater.is_enabled ? 1.f : 0.f); + ggWaterCircuitsLinkButton.PutValue(controlled->WaterCircuitsLink() ? 1.f : 0.f); + // fuel pump + if (ggFuelPumpButton.type() != TGaugeType::push) + { + ggFuelPumpButton.PutValue(controlled->FuelPump.is_enabled ? 1.f : 0.f); + } + // oil pump + if (ggOilPumpButton.type() != TGaugeType::push) + { + ggOilPumpButton.PutValue(controlled->OilPump.is_enabled ? 1.f : 0.f); + } + // joint oil and fuel pump + if (ggOilFuelPumpButton.type() != TGaugeType::push) + { + ggOilFuelPumpButton.PutValue(controlled->OilFuelPumpsEnabled() ? 1.f : 0.f); + } + // traction selector and genset of a dual-mode vehicle + ggTractionModeSwitch.PutValue(controlled->GensetSelected() ? 1.f : 0.f); + if (ggGensetButton.type() != TGaugeType::push) + { + ggGensetButton.PutValue(controlled->Genset.is_enabled ? 1.f : 0.f); + } + // traction motor fans + if (ggMotorBlowersFrontButton.type() != TGaugeType::push) + { + ggMotorBlowersFrontButton.PutValue(controlled->MotorBlowers[VehicleEnd::front].is_enabled ? 1.f : 0.f); + } + if (ggMotorBlowersRearButton.type() != TGaugeType::push) + { + ggMotorBlowersRearButton.PutValue(controlled->MotorBlowers[VehicleEnd::rear].is_enabled ? 1.f : 0.f); + } + if (ggMotorBlowersAllOffButton.type() != TGaugeType::push) + { + ggMotorBlowersAllOffButton.PutValue(controlled->MotorBlowers[VehicleEnd::front].is_disabled || controlled->MotorBlowers[VehicleEnd::rear].is_disabled ? 1.f : 0.f); + } + // second controller + if (ggScndCtrl.is_push()) + { + ggScndCtrl.PutValue(ggScndCtrl.is_toggle() ? 0.5f : // pushtoggle is two-way control with neutral position in the middle + 0.f); // push is on/off control, active while held down, due to legacy use + } + // tempomat + if (false == ggScndCtrlButton.is_push()) + { + ggScndCtrlButton.PutValue(controlled->IsSpeedCtrlEngaged() ? 1.f : 0.f); + } + // sandbox + if (ggAutoSandButton.type() != TGaugeType::push) + { + ggAutoSandButton.PutValue(controlled->SandDoseAutoAllow ? 1.f : 0.f); + } + // radio + ggRadioVolumeSelector.PutValue(m_radiovolume); + + // finding each inverter - not so optimal, but action ins performed only during changing cabin + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied() > 0; + auto const flag{CouplingSet::FromBits(DynamicObject->physics->inductionMotor.inverterControlCouplings)}; + int itemstart = 0; + for ([[maybe_unused]] auto const &item : ggInverterToggleButtons) // for each button + { + int itemindex = itemstart; + itemstart++; + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, flag); + while (p) + { + if (p->physics->inductionMotor.traction.maxPower > 1) + { + if (itemindex < p->physics->inductionMotor.inverterCount) + { + // visual feedback + ggInverterToggleButtons[itemstart - 1].PutValue(p->physics->inductionMotor.inverters[itemindex].Activate ? 1.0 : 0.0); + break; + } + else + { + itemindex -= p->physics->inductionMotor.inverterCount; + } + } + p = kier ? p->Next(flag) : p->Prev(flag); + } + } + + // we reset all indicators, as they're set during the update pass + // TODO: when cleaning up break setting indicator state into a separate function, so we can reuse it +} + +// initializes a button matching provided label. returns: true if the label was found, false otherwise +// TODO: refactor the cabin controls into some sensible structure +bool TTrain::initialize_button(cParser &Parser, std::string const &Label, int const Cabindex) +{ + + std::unordered_map const lights = { + {"i-maxft:", btLampkaMaxSila}, + {"i-maxftt:", btLampkaPrzekrMaxSila}, + {"i-radio:", btLampkaRadio}, + {"i-radiomessage:", btLampkaRadioMessage}, + {"i-radiostop:", btLampkaRadioStop}, + {"i-manual_brake:", btLampkaHamulecReczny}, + {"i-door_blocked:", btLampkaBlokadaDrzwi}, + {"i-door_blockedoff:", btLampkaDoorLockOff}, + {"i-slippery:", btLampkaPoslizg}, + {"i-contactors:", btLampkaStyczn}, + {"i-conv_ovld:", btLampkaNadmPrzetw}, + {"i-converter:", btLampkaPrzetw}, + {"i-converteroff:", btLampkaPrzetwOff}, + {"i-converteraoff:", btLampkaPrzetwAOff}, + {"i-converterb:", btLampkaPrzetwB}, + {"i-converterboff:", btLampkaPrzetwBOff}, + {"i-diff_relay:", btLampkaPrzekRozn}, + {"i-diff_relay2:", btLampkaPrzekRoznPom}, + {"i-motor_ovld:", btLampkaNadmSil}, + {"i-train_controll:", btLampkaUkrotnienie}, + {"i-brake_delay_r:", btLampkaHamPosp}, + {"i-mainbreaker:", btLampkaWylSzybki}, + {"i-mainbreakerb:", btLampkaWylSzybkiB}, + {"i-mainbreakeroff:", btLampkaWylSzybkiOff}, + {"i-mainbreakerboff:", btLampkaWylSzybkiBOff}, + {"i-mainbreakerready:", btLampkaMainBreakerReady}, + {"i-mainbreakerblinking:", btLampkaMainBreakerBlinkingIfReady}, + {"i-vent_ovld:", btLampkaNadmWent}, + {"i-comp_ovld:", btLampkaNadmSpr}, + // overheat indicator lamps + {"i-oil_overheat:", btLampkaOilOverheat}, + {"i-water_overheat:", btLampkaWaterOverheat}, + {"i-wateraux_overheat:", btLampkaWaterAuxOverheat}, + {"i-engine_overheat:", btLampkaEngineOverheat}, + {"i-resistors:", btLampkaOpory}, + {"i-no_resistors:", btLampkaBezoporowa}, + {"i-no_resistors_b:", btLampkaBezoporowaB}, + {"i-highcurrent:", btLampkaWysRozr}, + {"i-vent_trim:", btLampkaWentZaluzje}, + {"i-motorblowers:", btLampkaMotorBlowers}, + {"i-coolingfans:", btLampkaCoolingFans}, + {"i-louvresclosed:", btLampkaLouvresClosed}, + {"i-tempomat:", btLampkaTempomat}, + {"i-distancecounter:", btLampkaDistanceCounter}, + {"i-trainheating:", btLampkaOgrzewanieSkladu}, + {"i-security_aware:", btLampkaCzuwaka}, + {"i-security_cabsignal:", btLampkaSHP}, + {"i-security_aware_cabsignal:", btLampkaCzuwakaSHP}, + {"i-door_left:", btLampkaDoorLeft}, + {"i-door_right:", btLampkaDoorRight}, + {"i-departure_signal:", btLampkaDepartureSignal}, + {"i-reserve:", btLampkaRezerwa}, + {"i-scnd:", btLampkaBoczniki}, + {"i-scnd1:", btLampkaBocznik1}, + {"i-scnd2:", btLampkaBocznik2}, + {"i-scnd3:", btLampkaBocznik3}, + {"i-scnd4:", btLampkaBocznik4}, + {"i-gear1:", btLampkaGear1}, + {"i-gear2:", btLampkaGear2}, + {"i-hydrolockup:", btLampkaHydroLockup}, + {"i-braking:", btLampkaHamienie}, + {"i-brakingoff:", btLampkaBrakingOff}, + {"i-dynamicbrake:", btLampkaED}, + {"i-brakeprofileg:", btLampkaBrakeProfileG}, + {"i-brakeprofilep:", btLampkaBrakeProfileP}, + {"i-brakeprofiler:", btLampkaBrakeProfileR}, + {"i-springbrakeactive:", btLampkaSpringBrakeActive}, + {"i-springbrakeinactive:", btLampkaSpringBrakeInactive}, + {"i-braking-ezt:", btLampkaHamowanie1zes}, + {"i-braking-ezt2:", btLampkaHamowanie2zes}, + {"i-compressor:", btLampkaSprezarka}, + {"i-compressorb:", btLampkaSprezarkaB}, + {"i-compressoroff:", btLampkaSprezarkaOff}, + {"i-compressorboff:", btLampkaSprezarkaBOff}, + {"i-fuelpumpoff:", btLampkaFuelPumpOff}, + {"i-oilpump:", btLampkaOilPump}, + {"i-voltbrake:", btLampkaNapNastHam}, + {"i-resistorsb:", btLampkaOporyB}, + {"i-contactorsb:", btLampkaStycznB}, + {"i-conv_ovldb:", btLampkaNadmPrzetwB}, + {"i-hvoltageb:", btLampkaHVoltageB}, + {"i-malfunction:", btLampkaMalfunction}, + {"i-malfunctionb:", btLampkaMalfunctionB}, + {"i-forward:", btLampkaForward}, + {"i-backward:", btLampkaBackward}, + {"i-neutral:", btLampkaNeutral}, + {"i-upperlight:", btLampkaUpperLight}, + {"i-leftlight:", btLampkaLeftLight}, + {"i-rightlight:", btLampkaRightLight}, + {"i-leftend:", btLampkaLeftEndLight}, + {"i-rightend:", btLampkaRightEndLight}, + {"i-rearupperlight:", btLampkaRearUpperLight}, + {"i-rearleftlight:", btLampkaRearLeftLight}, + {"i-rearrightlight:", btLampkaRearRightLight}, + {"i-rearleftend:", btLampkaRearLeftEndLight}, + {"i-rearrightend:", btLampkaRearRightEndLight}, + {"i-dashboardlight:", btDashboardLight}, + {"i-timetablelight:", btTimetableLight}, + {"i-universal0:", btUniversals[0]}, + {"i-universal1:", btUniversals[1]}, + {"i-universal2:", btUniversals[2]}, + {"i-universal3:", btUniversals[3]}, + {"i-universal4:", btUniversals[4]}, + {"i-universal5:", btUniversals[5]}, + {"i-universal6:", btUniversals[6]}, + {"i-universal7:", btUniversals[7]}, + {"i-universal8:", btUniversals[8]}, + {"i-universal9:", btUniversals[9]}, + {"i-cabactived:", btCabActived}, + {"i-aklvents:", btAKLVents}, + {"i-compressorany:", btCompressors}, + {"i-edenabled", btEDenabled}, + }; + { + auto lookup = lights.find(Label); + if (lookup != lights.end()) + { + lookup->second.Load(Parser, DynamicObject); + return true; + } + } + // TODO: move viable dedicated lights to the automatic light array + std::unordered_map const autolights = { + {"i-doors:", &m_doors}, + {"i-doorpermit_left:", &m_doorspermitleft}, + {"i-doorpermit_right:", &m_doorspermitright}, + {"i-doorpermit_any:", &m_doorpermits}, + {"i-doorstep:", &occupied->Doors.step_enabled}, + {"i-mainpipelock:", &occupied->brakes.pipeLock.locked}, + {"i-battery:", &occupied->lowVoltage.Is24vAvailable()}, + {"i-cablight:", &Cabine[iCabn].bLight}, + {"i-compartmentlights:", &occupied->CompartmentLights.is_active}, + }; + { + auto lookup = autolights.find(Label); + if (lookup != autolights.end()) + { + auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka + button.Load(Parser, DynamicObject); + button.AssignBool(lookup->second); + return true; + } + } + // custom lights + if (Label == "i-instrumentlight:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 0; + } + else if (Label == "i-instrumentlight_m:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 1; + } + else if (Label == "i-instrumentlight_c:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 2; + } + else if (Label == "i-instrumentlight_a:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 3; + } + else if (Label == "i-instrumentlight_l:") + { + btInstrumentLight.Load(Parser, DynamicObject); + InstrumentLightType = 4; + } + else if (Label == "i-doors:") + { + int i = Parser.getToken() - 1; + auto &button = Cabine[Cabindex].Button(-1); // pierwsza wolna lampka + button.Load(Parser, DynamicObject); + button.AssignBool(bDoors[0] + 3 * i); + } + else + { + // failed to match the label + return false; + } + + return true; +} + +// initializes a gauge matching provided label. returns: true if the label was found, false otherwise +// TODO: refactor the cabin controls into some sensible structure +bool TTrain::initialize_gauge(cParser &Parser, std::string const &Label, int const Cabindex) +{ + + std::unordered_map const gauges = {{"jointctrl:", ggJointCtrl}, + {"mainctrl:", ggMainCtrl}, + {"scndctrl:", ggScndCtrl}, + {"dirkey:", ggDirKey}, + {"brakectrl:", ggBrakeCtrl}, + {"localbrake:", ggLocalBrake}, + {"alarmchain:", ggAlarmChain}, + {"brakeprofile_sw:", ggBrakeProfileCtrl}, + {"brakeprofileg_sw:", ggBrakeProfileG}, + {"brakeprofiler_sw:", ggBrakeProfileR}, + {"brakeopmode_sw:", ggBrakeOperationModeCtrl}, + {"maxcurrent_sw:", ggMaxCurrentCtrl}, + {"autorelay_sw:", ggAutoRelayButton}, + {"main_off_bt:", ggMainOffButton}, + {"main_on_bt:", ggMainOnButton}, + {"mainb_sw:", m_remotelinebreakers[0].main_switch}, + {"mainb_off_bt:", m_remotelinebreakers[0].off_button}, + {"mainb_on_bt:", m_remotelinebreakers[0].on_button}, + {"mainc_sw:", m_remotelinebreakers[1].main_switch}, + {"mainc_off_bt:", m_remotelinebreakers[1].off_button}, + {"mainc_on_bt:", m_remotelinebreakers[1].on_button}, + {"security_reset_bt:", ggSecurityResetButton}, + {"shp_reset_bt:", ggSHPResetButton}, + {"releaser_bt:", ggReleaserButton}, + {"springbrakeon_bt:", ggSpringBrakeOnButton}, + {"springbrakeoff_bt:", ggSpringBrakeOffButton}, + {"universalbrake1_bt:", ggUniveralBrakeButton1}, + {"universalbrake2_bt:", ggUniveralBrakeButton2}, + {"universalbrake3_bt:", ggUniveralBrakeButton3}, + {"epbrake_bt:", ggEPFuseButton}, + {"sand_bt:", ggSandButton}, + {"autosandallow_sw:", ggAutoSandButton}, + {"antislip_bt:", ggAntiSlipButton}, + {"horn_bt:", ggHornButton}, + {"hornlow_bt:", ggHornLowButton}, + {"hornhigh_bt:", ggHornHighButton}, + {"whistle_bt:", ggWhistleButton}, + {"helper_bt:", ggHelperButton}, + {"fuse_bt:", ggFuseButton}, + {"converterfuse_bt:", ggConverterFuseButton}, + {"stlinoff_bt:", ggStLinOffButton}, + {"doorpermitpreset_sw:", ggDoorPermitPresetButton}, + {"door_left_sw:", ggDoorLeftButton}, + {"door_right_sw:", ggDoorRightButton}, + {"doorlefton_sw:", ggDoorLeftOnButton}, + {"doorrighton_sw:", ggDoorRightOnButton}, + {"doorleftoff_sw:", ggDoorLeftOffButton}, + {"doorrightoff_sw:", ggDoorRightOffButton}, + {"doorallon_sw:", ggDoorAllOnButton}, + {"departure_signal_bt:", ggDepartureSignalButton}, + {"upperlight_sw:", ggUpperLightButton}, + {"leftlight_sw:", ggLeftLightButton}, + {"rightlight_sw:", ggRightLightButton}, + {"dimheadlights_sw:", ggDimHeadlightsButton}, + {"leftend_sw:", ggLeftEndLightButton}, + {"rightend_sw:", ggRightEndLightButton}, + {"lights_sw:", ggLightsButton}, + {"moderndimmer_sw:", ggModernLightDimSw}, + {"rearupperlight_sw:", ggRearUpperLightButton}, + {"rearleftlight_sw:", ggRearLeftLightButton}, + {"rearrightlight_sw:", ggRearRightLightButton}, + {"rearleftend_sw:", ggRearLeftEndLightButton}, + {"rearrightend_sw:", ggRearRightEndLightButton}, + {"compressor_sw:", ggCompressorButton}, + {"compressorlocal_sw:", ggCompressorLocalButton}, + {"compressorlist_sw:", ggCompressorListButton}, + {"converter_sw:", ggConverterButton}, + {"converterlocal_sw:", ggConverterLocalButton}, + {"converteroff_sw:", ggConverterOffButton}, + {"main_sw:", ggMainButton}, + {"waterpumpbreaker_sw:", ggWaterPumpBreakerButton}, + {"waterpump_sw:", ggWaterPumpButton}, + {"waterheaterbreaker_sw:", ggWaterHeaterBreakerButton}, + {"waterheater_sw:", ggWaterHeaterButton}, + {"water1tempb:", ggWater1TempB}, + {"watercircuitslink_sw:", ggWaterCircuitsLinkButton}, + {"fuelpump_sw:", ggFuelPumpButton}, + {"oilpump_sw:", ggOilPumpButton}, + {"oilfuelpump_sw:", ggOilFuelPumpButton}, + {"tractionmode_sw:", ggTractionModeSwitch}, + {"genset_sw:", ggGensetButton}, + {"oilpressb:", ggOilPressB}, + {"motorblowersfront_sw:", ggMotorBlowersFrontButton}, + {"motorblowersrear_sw:", ggMotorBlowersRearButton}, + {"motorblowersalloff_sw:", ggMotorBlowersAllOffButton}, + {"radiochannel_sw:", ggRadioChannelSelector}, + {"radiochannelprev_sw:", ggRadioChannelPrevious}, + {"radiochannelnext_sw:", ggRadioChannelNext}, + {"radiostop_sw:", ggRadioStop}, + {"radiotest_sw:", ggRadioTest}, + {"radiocall1_sw:", ggRadioCall1}, + {"radiocall3_sw:", ggRadioCall3}, + {"radiovolume_sw:", ggRadioVolumeSelector}, + {"radiovolumeprev_sw:", ggRadioVolumePrevious}, + {"radiovolumenext_sw:", ggRadioVolumeNext}, + {"radioon_sw:", ggRadioOnButton}, + {"radiooff_sw:", ggRadioOffButton}, + {"radiofuseon_sw:", ggRadioFuseOnButton}, + {"radiofuseoff_sw:", ggRadioFuseOffButton}, + /* + { "pantfront_sw:", ggPantFrontButton }, + { "pantrear_sw:", ggPantRearButton }, + { "pantfrontoff_sw:", ggPantFrontButtonOff }, + { "pantrearoff_sw:", ggPantRearButtonOff }, + */ + {"pantalloff_sw:", ggPantAllDownButton}, + {"pantselected_sw:", ggPantSelectedButton}, + {"pantselectedoff_sw:", ggPantSelectedDownButton}, + {"pantvalves_sw:", ggPantValvesButton}, + {"pantcompressor_sw:", ggPantCompressorButton}, + {"pantcompressorvalve_sw:", ggPantCompressorValve}, + {"trainheating_sw:", ggTrainHeatingButton}, + {"signalling_sw:", ggSignallingButton}, + {"door_signalling_sw:", ggDoorSignallingButton}, + {"nextcurrent_sw:", ggNextCurrentButton}, + {"instrumentlight_sw:", ggInstrumentLightButton}, + {"dashboardlight_sw:", ggDashboardLightButton}, + {"timetablelight_sw:", ggTimetableLightButton}, + {"cablightdim_sw:", ggCabLightDimButton}, + {"compartmentlights_sw:", ggCompartmentLightsButton}, + {"compartmentlightson_sw:", ggCompartmentLightsOnButton}, + {"compartmentlightsoff_sw:", ggCompartmentLightsOffButton}, + {"battery_sw:", ggBatteryButton}, + {"batteryon_sw:", ggBatteryOnButton}, + {"batteryoff_sw:", ggBatteryOffButton}, + {"cabactivation_sw:", ggCabActivationButton}, + {"distancecounter_sw:", ggDistanceCounterButton}, + {"relayreset1_bt:", ggRelayResetButtons[0]}, + {"relayreset2_bt:", ggRelayResetButtons[1]}, + {"relayreset3_bt:", ggRelayResetButtons[2]}, + {"universal0:", ggUniversals[0]}, + {"universal1:", ggUniversals[1]}, + {"universal2:", ggUniversals[2]}, + {"universal3:", ggUniversals[3]}, + {"universal4:", ggUniversals[4]}, + {"universal5:", ggUniversals[5]}, + {"universal6:", ggUniversals[6]}, + {"universal7:", ggUniversals[7]}, + {"universal8:", ggUniversals[8]}, + {"universal9:", ggUniversals[9]}, + {"universal10:", ggUniversals[10]}, + {"universal11:", ggUniversals[11]}, + {"universal12:", ggUniversals[12]}, + {"universal13:", ggUniversals[13]}, + {"universal14:", ggUniversals[14]}, + {"universal15:", ggUniversals[15]}, + {"universal16:", ggUniversals[16]}, + {"universal17:", ggUniversals[17]}, + {"universal18:", ggUniversals[18]}, + {"universal19:", ggUniversals[19]}, + {"universal20:", ggUniversals[20]}, + {"universal21:", ggUniversals[21]}, + {"universal22:", ggUniversals[22]}, + {"universal23:", ggUniversals[23]}, + {"universal24:", ggUniversals[24]}, + {"universal25:", ggUniversals[25]}, + {"universal26:", ggUniversals[26]}, + {"universal27:", ggUniversals[27]}, + {"universal28:", ggUniversals[28]}, + {"universal29:", ggUniversals[29]}, + {"inverterenable1_bt:", ggInverterEnableButtons[0]}, + {"inverterenable2_bt:", ggInverterEnableButtons[1]}, + {"inverterenable3_bt:", ggInverterEnableButtons[2]}, + {"inverterenable4_bt:", ggInverterEnableButtons[3]}, + {"inverterenable5_bt:", ggInverterEnableButtons[4]}, + {"inverterenable6_bt:", ggInverterEnableButtons[5]}, + {"inverterenable7_bt:", ggInverterEnableButtons[6]}, + {"inverterenable8_bt:", ggInverterEnableButtons[7]}, + {"inverterenable9_bt:", ggInverterEnableButtons[8]}, + {"inverterenable10_bt:", ggInverterEnableButtons[9]}, + {"inverterenable11_bt:", ggInverterEnableButtons[10]}, + {"inverterenable12_bt:", ggInverterEnableButtons[11]}, + {"inverterdisable1_bt:", ggInverterDisableButtons[0]}, + {"inverterdisable2_bt:", ggInverterDisableButtons[1]}, + {"inverterdisable3_bt:", ggInverterDisableButtons[2]}, + {"inverterdisable4_bt:", ggInverterDisableButtons[3]}, + {"inverterdisable5_bt:", ggInverterDisableButtons[4]}, + {"inverterdisable6_bt:", ggInverterDisableButtons[5]}, + {"inverterdisable7_bt:", ggInverterDisableButtons[6]}, + {"inverterdisable8_bt:", ggInverterDisableButtons[7]}, + {"inverterdisable9_bt:", ggInverterDisableButtons[8]}, + {"inverterdisable10_bt:", ggInverterDisableButtons[9]}, + {"inverterdisable11_bt:", ggInverterDisableButtons[10]}, + {"inverterdisable12_bt:", ggInverterDisableButtons[11]}, + {"invertertoggle1_bt:", ggInverterToggleButtons[0]}, + {"invertertoggle2_bt:", ggInverterToggleButtons[1]}, + {"invertertoggle3_bt:", ggInverterToggleButtons[2]}, + {"invertertoggle4_bt:", ggInverterToggleButtons[3]}, + {"invertertoggle5_bt:", ggInverterToggleButtons[4]}, + {"invertertoggle6_bt:", ggInverterToggleButtons[5]}, + {"invertertoggle7_bt:", ggInverterToggleButtons[6]}, + {"invertertoggle8_bt:", ggInverterToggleButtons[7]}, + {"invertertoggle9_bt:", ggInverterToggleButtons[8]}, + {"invertertoggle10_bt:", ggInverterToggleButtons[9]}, + {"invertertoggle11_bt:", ggInverterToggleButtons[10]}, + {"invertertoggle12_bt:", ggInverterToggleButtons[11]}, + {"pantvalvesupdate_bt:", ggPantValvesUpdate}, + {"pantvalvesoff_bt:", ggPantValvesOff}, + {"wipers_sw:", ggWiperSw}}; + { + auto const lookup{gauges.find(Label)}; + if (lookup != gauges.end()) + { + lookup->second.Load(Parser, DynamicObject); + m_controlmapper.insert(lookup->second, lookup->first); + return true; + } + } + // dedicated gauges with state-driven optional submodel + // TODO: move viable gauges here + // TODO: convert dedicated gauges to auto-allocated ones, replace dedicated references in command handlers to mapper lookups + std::unordered_map> const stategauges = { + {"tempomat_sw:", {ggScndCtrlButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"tempomatoff_sw:", {ggScndCtrlOffButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedinc_bt:", {ggSpeedControlIncreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speeddec_bt:", {ggSpeedControlDecreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedctrlpowerinc_bt:", {ggSpeedControlPowerIncreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedctrlpowerdec_bt:", {ggSpeedControlPowerDecreaseButton, &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton0:", {ggSpeedCtrlButtons[0], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton1:", {ggSpeedCtrlButtons[1], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton2:", {ggSpeedCtrlButtons[2], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton3:", {ggSpeedCtrlButtons[3], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton4:", {ggSpeedCtrlButtons[4], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton5:", {ggSpeedCtrlButtons[5], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton6:", {ggSpeedCtrlButtons[6], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton7:", {ggSpeedCtrlButtons[7], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton8:", {ggSpeedCtrlButtons[8], &occupied->SpeedCtrlUnit.IsActive}}, + {"speedbutton9:", {ggSpeedCtrlButtons[9], &occupied->SpeedCtrlUnit.IsActive}}, + {"doorleftpermit_sw:", {ggDoorLeftPermitButton, &m_doorspermitleft}}, + {"doorrightpermit_sw:", {ggDoorRightPermitButton, &m_doorspermitright}}, + {"dooralloff_sw:", {ggDoorAllOffButton, &m_doors}}, + {"doorstep_sw:", {ggDoorStepButton, &occupied->Doors.step_enabled}}, + {"dirforward_bt:", {ggDirForwardButton, &m_dirforward}}, + {"dirneutral_bt:", {ggDirNeutralButton, &m_dirneutral}}, + {"dirbackward_bt:", {ggDirBackwardButton, &m_dirbackward}}, + }; + { + auto const lookup{stategauges.find(Label)}; + if (lookup != stategauges.end()) + { + auto &gauge{std::get(lookup->second)}; + gauge.Load(Parser, DynamicObject); + gauge.AssignState(std::get(lookup->second)); + m_controlmapper.insert(gauge, lookup->first); + return true; + } + } + // TODO: move viable dedicated gauges to the automatic array + std::unordered_map const autoboolgauges = { + {"doormode_sw:", &occupied->Doors.remote_only}, + {"coolingfans_sw:", &controlled->RVentForceOn()}, + {"pantfront_sw:", &pantographUnit->pantographs[VehicleEnd::front].valve.is_enabled}, + {"pantrear_sw:", &pantographUnit->pantographs[VehicleEnd::rear].valve.is_enabled}, + {"pantfrontoff_sw:", &pantographUnit->pantographs[VehicleEnd::front].valve.is_disabled}, + {"pantrearoff_sw:", &pantographUnit->pantographs[VehicleEnd::rear].valve.is_disabled}, + {"radio_sw:", &occupied->Radio()}, + {"radiofuse_sw:", &occupied->RadioFuse()}, + {"cablight_sw:", &Cabine[iCabn].bLight}, + {"springbraketoggle_bt:", &occupied->brakes.spring.activate}, + {"couplingdisconnect_sw:", &m_couplingdisconnect}, + {"couplingdisconnectback_sw:", &m_couplingdisconnectback}, + {"mirrors_sw:", &occupied->MirrorForbidden()}, + }; + { + auto lookup = autoboolgauges.find(Label); + if (lookup != autoboolgauges.end()) + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka + gauge.Load(Parser, DynamicObject); + gauge.AssignBool(lookup->second); + m_controlmapper.insert(gauge, lookup->first); + return true; + } + } + // TODO: move viable dedicated gauges to the automatic array + std::unordered_map const autointgauges = { + {"manualbrake:", &occupied->brakes.HandBrakePosition()}, + {"pantselect_sw:", &occupied->pantographCircuit.presets.second[cab_to_end()]}, + }; + { + auto lookup = autointgauges.find(Label); + if (lookup != autointgauges.end()) + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna lampka + gauge.Load(Parser, DynamicObject); + gauge.AssignInt(lookup->second); + m_controlmapper.insert(gauge, lookup->first); + return true; + } + } + + // broadcast radio receiver + if (Label == "fmradio_sw:" || Label == "fmradiovolume_sw:" || Label == "fmradiotune_sw:" || Label == "fmradioscale:") + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + if (Label == "fmradio_sw:") + { + gauge.AssignBool(&m_fmradiopower); + } + else + { + gauge.AssignFloat(Label == "fmradiovolume_sw:" ? &m_fmradiovolume : &m_fmradiodial); + } + if (Label != "fmradioscale:") + { + // the scale pointer is an indicator, the rest are controls + m_controlmapper.insert(gauge, Label); + } + m_fmradiopresent = true; + // unless the speaker location is defined explicitly, the sound comes from the first defined element of the receiver + if (m_fmradiosound.offset() == glm::vec3()) + { + m_fmradiosound.offset(gauge.model_offset()); + } + return true; + } + + // ABu 090305: uniwersalne przyciski lub inne rzeczy + if (Label == "mainctrlact:") + { + ggMainCtrlAct.Load(Parser, DynamicObject); + } + // SEKCJA WSKAZNIKOW + else if (Label == "tachometer:" || Label == "tachometerb:") + { + // predkosciomierz wskaźnikowy z szarpaniem + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fTachoVelocityJump); + // bind tachometer sound location to the meter + if (dsbHasler && dsbHasler->offset() == glm::vec3()) + { + dsbHasler->offset(gauge.model_offset()); + } + } + else if (Label == "tachometern:") + { + // predkosciomierz wskaźnikowy bez szarpania + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fTachoVelocity); + // bind tachometer sound location to the meter + if (dsbHasler && dsbHasler->offset() == glm::vec3()) + { + dsbHasler->offset(gauge.model_offset()); + } + } + else if (Label == "tachometerd:") + { + // predkosciomierz cyfrowy + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fTachoVelocity); + // bind tachometer sound location to the meter + if (dsbHasler && dsbHasler->offset() == glm::vec3()) + { + dsbHasler->offset(gauge.model_offset()); + } + } + else if (Label == "hvcurrent1:" || Label == "hvcurrent1b:") + { + // 1szy amperomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent + 1); + } + else if (Label == "hvcurrent2:" || Label == "hvcurrent2b:") + { + // 2gi amperomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent + 2); + } + else if (Label == "hvcurrent3:" || Label == "hvcurrent3b:") + { + // 3ci amperomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałska + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent + 3); + } + else if (Label == "hvcurrent:" || Label == "hvcurrentb:") + { + // amperomierz calkowitego pradu + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fHCurrent); + } + else if (Label == "eimscreen:") + { + // amperomierz calkowitego pradu + int i; + int j; + Parser.getTokens(2, false); + Parser >> i >> j; + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fEIMParams[i][j]); + } + else if (Label == "brakes:") + { + // specified pipe pressure of specified consist vehicle + int i; + int j; + Parser.getTokens(2, false); + Parser >> i >> j; + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignFloat(&fPress[std::clamp(i, 1, 20) - 1][std::clamp(j, 0, 3)]); + } + else if (Label == "brakepress:" || Label == "brakepressb:") + { + // manometr cylindrow hamulcowych + // Ra 2014-08: przeniesione do TCab + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&occupied->brakes.cylinderPressure); + } + else if (Label == "pipepress:" || Label == "pipepressb:") + { + // manometr przewodu hamulcowego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&occupied->brakePipe.Pressure()); + } + else if (Label == "scndpress:") + { + // manometr przewodu hamulcowego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&occupied->mainPipe.Pressure()); + } + else if (Label == "limpipepress:") + { + // manometr zbiornika sterujacego zaworu maszynisty + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&m_brakehandlecp); + } + else if (Label == "cntrlpress:") + { + // manometr zbiornika kontrolnego/rorzďż˝du + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&pantographUnit->pantographAir.Pressure()); + } + else if (Label == "springbrakepress:") + { + // manometr cylindra hamulca sprężynowego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&occupied->brakes.spring.pressure); + } + else if (Label == "epctrlvalue:") + { + // wskazowka sterowania sila hamulca ep + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&occupied->EpForce); + } + else if (Label == "compressor:" || Label == "compressorb:") + { + // manometr sprezarki/zbiornika glownego + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&occupied->air.MainReservoirPressure()); + } + else if (Label == "oilpress:") + { + // oil pressure + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&controlled->OilPump.pressure); + } + else if (Label == "oiltemp:") + { + // oil temperature + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&controlled->diesel.heat.To); + } + else if (Label == "water1temp:") + { + // main circuit water temperature + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&controlled->diesel.heat.temperatura1); + } + else if (Label == "water2temp:") + { + // auxiliary circuit water temperature + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&controlled->diesel.heat.temperatura2); + } + else if (Label == "pantpress:") + { + // pantograph tank pressure + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject, 0.1); + gauge.AssignDouble(&pantographUnit->pantographAir.Pressure()); + } + // yB - dla drugiej sekcji + else if (Label == "hvbcurrent1:") + { + // 1szy amperomierz + ggI1B.Load(Parser, DynamicObject); + } + else if (Label == "hvbcurrent2:") + { + // 2gi amperomierz + ggI2B.Load(Parser, DynamicObject); + } + else if (Label == "hvbcurrent3:") + { + // 3ci amperomierz + ggI3B.Load(Parser, DynamicObject); + } + else if (Label == "hvbcurrent:") + { + // amperomierz calkowitego pradu + ggItotalB.Load(Parser, DynamicObject); + } + //************************************************************* + else if (Label == "clock:") + { + // zegar analogowy + if (Parser.getToken() == "analog" && DynamicObject->mdKabina) + { + // McZapkie-300302: zegarek + ggClockSInd.Init(DynamicObject->mdKabina->GetFromName("ClockShand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); + ggClockMInd.Init(DynamicObject->mdKabina->GetFromName("ClockMhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 60.0)); + ggClockHInd.Init(DynamicObject->mdKabina->GetFromName("ClockHhand"), nullptr, TGaugeAnimation::gt_Rotate, static_cast(1.0 / 12.0)); + } + } + else if (Label == "clock_seconds:") + { + ggClockSInd.Load(Parser, DynamicObject); + } + else if (Label == "evoltage:") + { + // woltomierz napiecia silnikow + ggEngineVoltage.Load(Parser, DynamicObject); + } + else if (Label == "hvoltage:") + { + // woltomierz wysokiego napiecia + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(&fHVoltage); + } + else if (Label == "lvoltage:") + { + // woltomierz niskiego napiecia + ggLVoltage.Load(Parser, DynamicObject); + } + else if (Label == "enrot1m:") + { + // obrotomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fEngine + 1); + } // ggEnrot1m.Load(Parser,DynamicObject->mdKabina); + else if (Label == "enrot2m:") + { + // obrotomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fEngine + 2); + } // ggEnrot2m.Load(Parser,DynamicObject->mdKabina); + else if (Label == "enrot3m:") + { // obrotomierz + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignFloat(fEngine + 3); + } // ggEnrot3m.Load(Parser,DynamicObject->mdKabina); + else if (Label == "engageratio:") + { + // np. ciśnienie sterownika sprzęgła + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&controlled->diesel.clutchPressure); + } // ggEngageRatio.Load(Parser,DynamicObject->mdKabina); + else if (Label == "maingearstatus:") + { + // np. ciśnienie sterownika skrzyni biegów + ggMainGearStatus.Load(Parser, DynamicObject); + } + else if (Label == "ignitionkey:") + { + ggIgnitionKey.Load(Parser, DynamicObject); + } + else if (Label == "distcounter:") + { + // Ra 2014-07: licznik kilometrów + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + // the counter shows the odometer of the vehicle, kept between the sessions (eu07/maszyna#72). its offset + // was the state it started each session with, now it is that only for a vehicle with no known state + if (auto const seed{odometer::counter_seed(gauge.offset(), gauge.scale())}; seed.has_value()) + controlled->Odometer.seed(*seed); + gauge.offset(0.f); + gauge.AssignDouble(&controlled->Odometer.km); + // the vehicle the counter counts for is one the odometer store keeps, also in the sessions the counter seeds + // nothing (its state is a saved one by then) and when it's the motor car of the unit the cab is in + controlled->ShowOdometer(); + } + else if (Label == "shuntmodepower:") + { + // shunt mode power slider + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&controlled->AnPos()); + m_controlmapper.insert(gauge, "shuntmodepower:"); + } + else if (Label == "heatingvoltage:") + { + if (controlled->HeatingPowerSource.SourceType == TPowerSource::Generator) + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&controlled->HeatingPowerSource.EngineGenerator.voltage); + } + } + else if (Label == "heatingcurrent:") + { + auto &gauge = Cabine[Cabindex].Gauge(-1); // pierwsza wolna gałka + gauge.Load(Parser, DynamicObject); + gauge.AssignDouble(&controlled->TotalCurrent); + } + else + { + // failed to match the label + return false; + } + + return true; +} diff --git a/vehicle/cab/signalcommands.cpp b/vehicle/cab/signalcommands.cpp new file mode 100644 index 000000000..713aad7c7 --- /dev/null +++ b/vehicle/cab/signalcommands.cpp @@ -0,0 +1,517 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the commands of the horns and the radios + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::OnCommand_hornlowactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggHornButton.SubModel == nullptr && Train->ggHornLowButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Horn button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only need to react to press, sound will continue until stopped + if (false == TestFlag(Train->occupied->WarningSignal(), horn::low)) + { + // turn on + Train->occupied->SetWarningSignal(horn::pressed(Train->occupied->WarningSignal(), horn::low, Train->has_single_horn_lever())); + // visual feedback + Train->ggHornButton.UpdateValue(-1.0); + Train->ggHornLowButton.UpdateValue(1.0); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->occupied->SetWarningSignal(horn::released(Train->occupied->WarningSignal(), horn::low)); + // visual feedback + if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal(), horn::high))) + { + // leave the single lever alone if it was moved to the other tone in the meantime + Train->ggHornButton.UpdateValue(0.0); + } + Train->ggHornLowButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_hornhighactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggHornButton.SubModel == nullptr && Train->ggHornHighButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Horn button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only need to react to press, sound will continue until stopped + if (false == TestFlag(Train->occupied->WarningSignal(), horn::high)) + { + // turn on + Train->occupied->SetWarningSignal(horn::pressed(Train->occupied->WarningSignal(), horn::high, Train->has_single_horn_lever())); + // visual feedback + Train->ggHornButton.UpdateValue(1.0); + Train->ggHornHighButton.UpdateValue(1.0); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->occupied->SetWarningSignal(horn::released(Train->occupied->WarningSignal(), horn::high)); + // visual feedback + if (false == (Train->has_single_horn_lever() && TestFlag(Train->occupied->WarningSignal(), horn::low))) + { + // leave the single lever alone if it was moved to the other tone in the meantime + Train->ggHornButton.UpdateValue(0.0); + } + Train->ggHornHighButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_whistleactivate(TTrain *Train, command_data const &Command) +{ + + if (Train->ggWhistleButton.SubModel == nullptr) + { + if (Command.action == GLFW_PRESS) + { + WriteLog("Whistle button is missing, or wasn't defined"); + } + return; + } + + if (Command.action == GLFW_PRESS) + { + // only need to react to press, sound will continue until stopped + if (false == TestFlag(Train->occupied->WarningSignal(), 4)) + { + // turn on + Train->occupied->SetWarningSignal(Train->occupied->WarningSignal() | 4); + // visual feedback + Train->ggWhistleButton.UpdateValue(1.0); + } + } + else if (Command.action == GLFW_RELEASE) + { + // turn off + Train->occupied->SetWarningSignal(Train->occupied->WarningSignal() & ~4); + // visual feedback + Train->ggWhistleButton.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiotoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + + // NOTE: works without the switch in the 3d model too, to allow system reset after receiving radio-stop signal + // only reacting to press, so the sound can loop uninterrupted + // NOTE: flips the state directly rather than through radioenable/radiodisable, so it doesn't move the radioon_sw:/radiooff_sw: buttons + Train->occupied->SetRadio((false == Train->occupied->Radio())); +} + +void TTrain::OnCommand_radioenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->occupied->SetRadio(true); + // visual feedback + if (Train->m_controlmapper.contains("radioon_sw:")) + { + Train->ggRadioOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radioon_sw:")) + { + Train->ggRadioOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_radiodisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->occupied->SetRadio(false); + // visual feedback + if (Train->m_controlmapper.contains("radiooff_sw:")) + { + Train->ggRadioOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiooff_sw:")) + { + Train->ggRadioOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +// the cut-off in the radio's power supply (eu07/maszyna#438); opening it works like switching the radio off, the +// radio-stop flag included +void TTrain::OnCommand_radiofusetoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_PRESS) + { + return; + } + + // NOTE: flips the state directly rather than through radiofuseenable/radiofusedisable, so it doesn't move the + // radiofuseon_sw:/radiofuseoff_sw: buttons + Train->occupied->SetRadioFuse((false == Train->occupied->RadioFuse())); +} + +void TTrain::OnCommand_radiofuseenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->occupied->SetRadioFuse(true); + // visual feedback + if (Train->m_controlmapper.contains("radiofuseon_sw:")) + { + Train->ggRadioFuseOnButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiofuseon_sw:")) + { + Train->ggRadioFuseOnButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_radiofusedisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + Train->occupied->SetRadioFuse(false); + // visual feedback + if (Train->m_controlmapper.contains("radiofuseoff_sw:")) + { + Train->ggRadioFuseOffButton.UpdateValue(1.0f, Train->dsbSwitch); + } + } + else if (Command.action == GLFW_RELEASE) + { + if (Train->m_controlmapper.contains("radiofuseoff_sw:")) + { + Train->ggRadioFuseOffButton.UpdateValue(0.0f, Train->dsbSwitch); + } + } +} + +void TTrain::OnCommand_radiochannelincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // the channel buttons of a radio switched off or without power do nothing + if (Train->occupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->RadioChannel() + 1; + OnCommand_radiochannelset(Train, newCommand); + } + + Train->ggRadioChannelNext.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioChannelNext.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiochanneldecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->occupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->RadioChannel() - 1; + OnCommand_radiochannelset(Train, newCommand); + } + + Train->ggRadioChannelPrevious.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioChannelPrevious.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiochannelset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE) + { + // on press or hold + Train->SetRadioChannel(std::clamp((int)Command.param1, 1, 10)); + Train->ggRadioChannelSelector.UpdateValue(static_cast(Train->RadioChannel() - 1)); + } +} + +void TTrain::OnCommand_radiostopsend(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->occupied->RadioPowered()) + { + simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioStop.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioStop.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiostopenable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() == 0) + { + if (Train->occupied->RadioPowered()) + { + simulation::Region->RadioStop(Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioStop.UpdateValue(1.0); + } +} + +void TTrain::OnCommand_radiostopdisable(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS && Train->ggRadioStop.GetValue() > 0) + { + // visual feedback + Train->ggRadioStop.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiostoptest(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->RadioChannel() == 10 && Train->occupied->RadioPowered()) + { + Train->Dynamic()->RadioStop(); + } + // visual feedback + Train->ggRadioTest.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioTest.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiocall1send(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS) + { + if (Train->RadioChannel() != 10 && Train->occupied->RadioPowered()) + { + simulation::Events.queue_receivers(radio_message::call1, Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioCall1.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioCall1.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiocall3send(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->RadioChannel() != 10 && Train->occupied->RadioPowered()) + { + simulation::Events.queue_receivers(radio_message::call3, Train->Dynamic()->GetPosition()); + } + // visual feedback + Train->ggRadioCall3.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioCall3.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiovolumeincrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + // so do the volume buttons + if (Train->occupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->m_radiovolume + 0.125; + OnCommand_radiovolumeset(Train, newCommand); + } + Train->ggRadioVolumeNext.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioVolumeNext.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiovolumedecrease(TTrain *Train, command_data const &Command) +{ + + if (Command.action == GLFW_PRESS) + { + if (Train->occupied->RadioPowered()) + { + command_data newCommand = Command; + newCommand.param1 = Train->m_radiovolume - 0.125; + OnCommand_radiovolumeset(Train, newCommand); + } + Train->ggRadioVolumePrevious.UpdateValue(1.0); + } + else if (Command.action == GLFW_RELEASE) + { + // visual feedback + Train->ggRadioVolumePrevious.UpdateValue(0.0); + } +} + +void TTrain::OnCommand_radiovolumeset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE) + { + // on press or hold + Train->m_radiovolume = static_cast(std::clamp(Command.param1, 0.0, 1.0)); + Train->ggRadioVolumeSelector.UpdateValue(Train->m_radiovolume); + audio::event_volume_change = true; + } +} + +void TTrain::OnCommand_fmradiotoggle(TTrain *Train, command_data const &Command) +{ + if (Command.action == GLFW_PRESS && Train->m_fmradiopresent) + { + Train->m_fmradiopower = !Train->m_fmradiopower; + } +} + +void TTrain::OnCommand_fmradiovolumeincrease(TTrain *Train, command_data const &Command) +{ + // the knob keeps turning for as long as the control is held, the actual movement takes place in the update + Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); +} + +void TTrain::OnCommand_fmradiovolumedecrease(TTrain *Train, command_data const &Command) +{ + Train->m_fmradiovolumechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); +} + +void TTrain::OnCommand_fmradiovolumeset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) + { + Train->m_fmradiovolume = std::clamp(static_cast(Command.param1), 0.f, 1.f); + if (false == Train->m_controlmapper.contains("fmradio_sw:")) + { + // receivers without dedicated switch are switched with the volume knob + Train->m_fmradiopower = Train->m_fmradiovolume > 0.f; + } + } +} + +void TTrain::OnCommand_fmradiotuneincrease(TTrain *Train, command_data const &Command) +{ + Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? 1 : 0); +} + +void TTrain::OnCommand_fmradiotunedecrease(TTrain *Train, command_data const &Command) +{ + Train->m_fmradiotunechange = (Command.action != GLFW_RELEASE && Train->m_fmradiopresent ? -1 : 0); +} + +// sets the receiver to frequency specified in MHz +void TTrain::OnCommand_fmradiotuneset(TTrain *Train, command_data const &Command) +{ + if (Command.action != GLFW_RELEASE && Train->m_fmradiopresent) + { + Train->m_fmradiodial = std::clamp(100.f * (static_cast(Command.param1) - audio::EU07_FMRADIO_BANDSTART) / (audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART), 0.f, 100.f); + Train->m_fmradiotuned = true; + } +} diff --git a/vehicle/cab/sounds.cpp b/vehicle/cab/sounds.cpp new file mode 100644 index 000000000..2b7dac896 --- /dev/null +++ b/vehicle/cab/sounds.cpp @@ -0,0 +1,563 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the sounds of the cab + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +void TTrain::update_sounds(double const Deltatime) +{ + + double volume{0.0}; + double const brakevolumescale{0.5}; + + // Winger-160404 - syczenie pomocniczego (luzowanie) + if (m_lastlocalbrakepressure != -1.f) + { + // calculate rate of pressure drop in local brake cylinder, once it's been initialized + auto const brakepressuredifference{occupied->brakes.independentCylinderPressure - m_lastlocalbrakepressure}; + m_localbrakepressurechange = static_cast(std::lerp(m_localbrakepressurechange, 10 * (brakepressuredifference / Deltatime), 0.1f)); + } + m_lastlocalbrakepressure = static_cast(occupied->brakes.independentCylinderPressure); + // local brake, release + if (rsSBHiss) + { + if (m_localbrakepressurechange < -0.05f && occupied->brakes.independentCylinderPressure > occupied->brakes.cylinderPressure - 0.05) + { + rsSBHiss->gain(static_cast(std::clamp(rsSBHiss->m_amplitudeoffset + rsSBHiss->m_amplitudefactor * -m_localbrakepressurechange * 0.05, 0.0, 1.5))); + rsSBHiss->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + // don't stop the sound too abruptly + volume = std::max(0.0, rsSBHiss->gain() - 0.1 * Deltatime); + rsSBHiss->gain(static_cast(volume)); + if (volume < 0.05) + { + rsSBHiss->stop(); + } + } + } + // local brake, engage + if (rsSBHissU) + { + if (m_localbrakepressurechange > 0.05f) + { + rsSBHissU->gain(static_cast(std::clamp(rsSBHissU->m_amplitudeoffset + rsSBHissU->m_amplitudefactor * m_localbrakepressurechange * 0.05, 0.0, 1.5))); + rsSBHissU->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + // don't stop the sound too abruptly + volume = std::max(0.0, rsSBHissU->gain() - 0.1 * Deltatime); + rsSBHissU->gain(static_cast(volume)); + if (volume < 0.05) + { + rsSBHissU->stop(); + } + } + } + + // McZapkie-280302 - syczenie + // TODO: softer volume reduction than plain abrupt stop, perhaps as reusable wrapper? + if (occupied->brakes.config.driverValveType == TBrakeHandle::FV4a || occupied->brakes.config.driverValveType == TBrakeHandle::FVel6) + { + // upuszczanie z PG + if (rsHiss) + { + fPPress = std::lerp(fPPress, static_cast(occupied->brakes.driverValve->GetSound(s_fv4a_b)), 0.05f); + volume = fPPress > 0 ? rsHiss->m_amplitudefactor * fPPress * 0.25 + rsHiss->m_amplitudeoffset : 0; + if (volume * brakevolumescale > 0.05) + { + rsHiss->gain(static_cast(volume * brakevolumescale)); + rsHiss->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHiss->stop(); + } + } + // napelnianie PG + if (rsHissU) + { + fNPress = std::lerp(fNPress, static_cast(occupied->brakes.driverValve->GetSound(s_fv4a_u)), 0.25f); + volume = fNPress > 0 ? rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0; + if (volume * brakevolumescale > 0.05) + { + rsHissU->gain(static_cast(volume * brakevolumescale)); + rsHissU->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissU->stop(); + } + } + // upuszczanie przy naglym + if (rsHissE) + { + volume = occupied->brakes.driverValve->GetSound(s_fv4a_e) * rsHissE->m_amplitudefactor + rsHissE->m_amplitudeoffset; + if (volume * brakevolumescale > 0.05) + { + rsHissE->gain(static_cast(volume * brakevolumescale)); + rsHissE->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissE->stop(); + } + } + // upuszczanie sterujacego fala + if (rsHissX) + { + volume = occupied->brakes.driverValve->GetSound(s_fv4a_x) * rsHissX->m_amplitudefactor + rsHissX->m_amplitudeoffset; + if (volume * brakevolumescale > 0.05) + { + rsHissX->gain(static_cast(volume * brakevolumescale)); + rsHissX->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissX->stop(); + } + } + // upuszczanie z czasowego + if (rsHissT) + { + volume = occupied->brakes.driverValve->GetSound(s_fv4a_t) * rsHissT->m_amplitudefactor + +rsHissT->m_amplitudeoffset; + if (volume * brakevolumescale > 0.05) + { + rsHissT->gain(static_cast(volume * brakevolumescale)); + rsHissT->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissT->stop(); + } + } + } + else + { + // jesli nie FV4a + // upuszczanie z PG + if (rsHiss) + { + fPPress = static_cast((4.0f * fPPress + std::max(0.0, occupied->brakes.driverValveFlow)) / (4.0f + 1.0f)); + volume = fPPress > 0.0f ? 2.0 * rsHiss->m_amplitudefactor * fPPress + rsHiss->m_amplitudeoffset : 0.0; + if (volume > 0.05) + { + rsHiss->gain(static_cast(volume)); + rsHiss->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHiss->stop(); + } + } + // napelnianie PG + if (rsHissU) + { + fNPress = static_cast((4.0f * fNPress + std::min(0.0, occupied->brakes.driverValveFlow)) / (4.0f + 1.0f)); + volume = fNPress < 0.0f ? -1.0 * rsHissU->m_amplitudefactor * fNPress + rsHissU->m_amplitudeoffset : 0.0; + if (volume > 0.01) + { + rsHissU->gain(static_cast(volume)); + rsHissU->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsHissU->stop(); + } + } + } // koniec nie FV4a + + // brakes + if (rsBrake) + { + if (occupied->brakes.unitForce > 10.0 && occupied->Vel > 0.05) + { + + auto const brakeforceratio{ + std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles() * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0)}; + // HACK: in external view mute the sound rather than stop it, in case there's an opening bookend it'd (re)play on sound restart after returning inside + volume = FreeFlyModeFlag ? 0.0 : rsBrake->m_amplitudeoffset + std::sqrt(brakeforceratio * std::lerp(0.4, 1.0, occupied->Vel / (1 + occupied->Vmax()))) * rsBrake->m_amplitudefactor; + rsBrake->pitch(static_cast(rsBrake->m_frequencyoffset + occupied->Vel * rsBrake->m_frequencyfactor)); + rsBrake->gain(static_cast(volume)); + rsBrake->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + rsBrake->stop(); + } + } + + // ambient sound + // since it's typically ticking of the clock we can center it on tachometer or on middle of compartment bounding area + if (rsFadeSound) + { + rsFadeSound->play(sound_flags::exclusive | sound_flags::looping); + } + + if (dsbSlipAlarm) + { + // alarm przy poslizgu dla 181/182 - BOMBARDIER + if (controlled->SlippingWheels() && DynamicObject->GetVelocity() > 1.0) + { + dsbSlipAlarm->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + dsbSlipAlarm->stop(); + } + } + + // dzwiek wiatru rozbijajacego sie o szyby w kabinie + if (rsWindSound) + { + if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) + update_sounds_resonancenoise(*rsWindSound); + else + rsWindSound->stop(FreeFlyModeFlag); + } + + // dzwiek rezonansu (taki drugi runningnoise w sumie) + if (rsResonanceNoise) + { + if (!FreeFlyModeFlag && !Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) + { + + update_sounds_resonancenoise(*rsResonanceNoise); + } + else + rsResonanceNoise->stop(FreeFlyModeFlag); + } + + // szum w czasie jazdy + if (rsRunningNoise) + { + if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5) + { + + update_sounds_runningnoise(*rsRunningNoise); + } + else + { + // don't play the optional ending sound if the listener switches views + rsRunningNoise->stop(true == FreeFlyModeFlag); + } + } + // hunting oscillation noise + if (rsHuntingNoise) + { + if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && DynamicObject->GetVelocity() > 0.5 && DynamicObject->IsHunting) + { + + update_sounds_runningnoise(*rsHuntingNoise); + // modify calculated sound volume by hunting amount + auto const huntingamount = std::lerp( + 0.0, 1.0, std::clamp((occupied->Vel - DynamicObject->HuntingShake.fadein_begin) / (DynamicObject->HuntingShake.fadein_end - DynamicObject->HuntingShake.fadein_begin), 0.0, 1.0)); + + rsHuntingNoise->gain(static_cast(rsHuntingNoise->gain() * huntingamount)); + } + else + { + // don't play the optional ending sound if the listener switches views + rsHuntingNoise->stop(true == FreeFlyModeFlag); + } + } + // rain sound + if (m_rainsound) + { + if (false == FreeFlyModeFlag && false == Global.CabWindowOpen && Global.Weather == "rain:") + { + if (m_rainsound->is_combined()) + { + m_rainsound->pitch(static_cast(Global.Overcast - 1.0)); + } + m_rainsound->gain(m_rainsound->m_amplitudeoffset + m_rainsound->m_amplitudefactor * 1.f); + m_rainsound->play(sound_flags::exclusive | sound_flags::looping); + } + else + { + m_rainsound->stop(); + } + } + + if (dsbHasler) + { + if (fTachoCount >= 3.f) + { + auto const soundfrequency{(true == dsbHasler->is_combined() ? fTachoVelocity * 0.01 : dsbHasler->m_frequencyoffset + dsbHasler->m_frequencyfactor)}; + dsbHasler->pitch(static_cast(soundfrequency)); + dsbHasler->gain(dsbHasler->m_amplitudeoffset + dsbHasler->m_amplitudefactor); + dsbHasler->play(sound_flags::exclusive | sound_flags::looping); + } + else if (fTachoCount < 1.f) + { + dsbHasler->stop(); + } + } + + // power-reliant sounds + if (occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable()) + { + + // buzzer shp + if (occupied->SecuritySystem.is_cabsignal_beeping()) + { + if (dsbBuzzerShp && false == dsbBuzzerShp->is_playing()) + { + dsbBuzzerShp->pitch(dsbBuzzerShp->m_frequencyoffset + dsbBuzzerShp->m_frequencyfactor); + dsbBuzzerShp->gain(dsbBuzzerShp->m_amplitudeoffset + dsbBuzzerShp->m_amplitudefactor); + dsbBuzzerShp->play(sound_flags::looping); + } + } + else + { + if (dsbBuzzerShp && true == dsbBuzzerShp->is_playing()) + { + dsbBuzzerShp->stop(); + } + } + + // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa + // hunter-091012: rozdzielenie alarmow + if (occupied->SecuritySystem.is_beeping()) + { + if (dsbBuzzer && false == dsbBuzzer->is_playing()) + { + dsbBuzzer->pitch(dsbBuzzer->m_frequencyoffset + dsbBuzzer->m_frequencyfactor); + dsbBuzzer->gain(dsbBuzzer->m_amplitudeoffset + dsbBuzzer->m_amplitudefactor); + dsbBuzzer->play(sound_flags::looping); +#ifdef _WIN32 + Console::BitsSet(1 << 14); // ustawienie bitu 16 na PoKeys +#endif + } + } + else + { + if (dsbBuzzer && true == dsbBuzzer->is_playing()) + { + dsbBuzzer->stop(); +#ifdef _WIN32 + Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys +#endif + } + } + // distance meter alert + if (m_distancecounterclear) + { + auto const *owner{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; + if (m_distancecounter > owner->ConsistLength()) + { + // play assigned sound if the train travelled its full length since meter activation + // TBD: check all combinations of directions and active cab + m_distancecounter = -1.f; // turn off the meter after its task is done + m_distancecounterclear->pitch(m_distancecounterclear->m_frequencyoffset + m_distancecounterclear->m_frequencyfactor); + m_distancecounterclear->gain(m_distancecounterclear->m_amplitudeoffset + m_distancecounterclear->m_amplitudefactor); + m_distancecounterclear->play(sound_flags::exclusive); + } + } + } + else + { + // stop power-reliant sounds if power is cut + if (dsbBuzzer && true == dsbBuzzer->is_playing()) + { + dsbBuzzer->stop(); +#ifdef _WIN32 + Console::BitsClear(1 << 14); // ustawienie bitu 16 na PoKeys +#endif + } + + if (dsbBuzzerShp && dsbBuzzerShp->is_playing()) + { + dsbBuzzerShp->stop(); + } + + if (m_distancecounterclear) + { + m_distancecounterclear->stop(); + } + } + + update_sounds_radio(); + update_sounds_fmradio(Deltatime); +} + +void TTrain::update_sounds_resonancenoise(sound_source &Sound) const +{ + // frequency calculation + auto const normalizer{occupied->Vmax() * 0.01f}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * occupied->Vel * normalizer}; + + // volume calculation + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax()), 1.0, 0.5); // scale base volume between 0.5-1.0 + + if (volume > 0.05) + { + Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); + } + else + { + Sound.stop(); + } +} + +void TTrain::update_sounds_runningnoise(sound_source &Sound) +{ + // frequency calculation + auto const normalizer{(true == Sound.is_combined() ? occupied->Vmax() * 0.01f : 1.f)}; + auto const soundfrequency{Sound.m_frequencyoffset + Sound.m_frequencyfactor * occupied->Vel * normalizer}; + + // volume calculation + auto volume = Sound.m_amplitudeoffset + Sound.m_amplitudefactor * std::lerp(occupied->Vel / (1 + occupied->Vmax()), 1.0, + 0.5); // scale base volume between 0.5-1.0 + if (std::abs(occupied->nrot()) > 0.01) + { + // hamulce wzmagaja halas + auto const brakeforceratio{(std::clamp(occupied->brakes.unitForce / std::max(1.0, occupied->BrakeForceR(1.0, occupied->Vel) / (occupied->NAxles() * std::max(1, occupied->brakes.config.blocksPerAxle))), 0.0, 1.0))}; + + volume *= 1 + 0.125 * brakeforceratio; + } + // scale volume by track quality + // TODO: track quality and/or environment factors as separate subroutine + volume *= std::lerp(0.8, 1.2, std::clamp(DynamicObject->MyTrack->iQualityFlag / 20.0, 0.0, 1.0)); + // for single sample sounds muffle the playback at low speeds + if (false == Sound.is_combined()) + { + volume *= std::lerp(0.0, 1.0, std::clamp(occupied->Vel / 25.0, 0.0, 1.0)); + } + + if (volume > 0.05) + { + Sound.pitch(static_cast(soundfrequency)).gain(static_cast(volume)).play(sound_flags::exclusive | sound_flags::looping); + } + else + { + Sound.stop(); + } +} + +void TTrain::update_sounds_radio() +{ + + radio_message_played = false; + if (false == m_radiomessages.empty()) + { + // erase completed radio messages from the list + std::erase_if(m_radiomessages, [](auto const &source) { return false == source.second->is_playing(); }); + } + // adjust audibility of remaining messages based on current radio conditions + auto const radioenabled{occupied->RadioPowered()}; + for (auto const &[messagechannel, messagesound] : m_radiomessages) + { + auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel() ? m_radiovolume : 0.0}; + messagesound->gain(static_cast(volume)); + radio_message_played |= true == radioenabled && Dynamic()->Mechanik != nullptr && messagechannel == RadioChannel(); + } + // radiostop + if (m_radiostop) + { + if (true == radioenabled && true == occupied->RadioStopFlag()) + { + m_radiostop->play(sound_flags::exclusive | sound_flags::looping); + radio_message_played |= true; + } + else + { + m_radiostop->stop(); + } + } + if (radio_message_played) + { + btLampkaRadioMessage.gain(m_radiovolume); + } +} + +// operates the broadcast radio receiver +void TTrain::update_sounds_fmradio(double const Deltatime) +{ + // NOTE: there's a single receiver in the simulation, it plays in the cab occupied by the user + if (simulation::Train != this || false == m_fmradiopresent || false == Global.fmradio_enabled) + { + return; + } + auto &fmradio{audio::renderer.fmradio()}; + auto const bandwidth{audio::EU07_FMRADIO_BANDEND - audio::EU07_FMRADIO_BANDSTART}; + if (false == m_fmradiotuned) + { + // initially the receiver is tuned to the first station on the list + m_fmradiodial = 100.f * (fmradio.default_frequency() - audio::EU07_FMRADIO_BANDSTART) / bandwidth; + m_fmradiotuned = true; + } + // knobs + if (m_fmradiovolumechange != 0) + { + m_fmradiovolume = std::clamp(m_fmradiovolume + m_fmradiovolumechange * 0.5f * static_cast(Deltatime), 0.f, 1.f); + if (false == m_controlmapper.contains("fmradio_sw:")) + { + // receivers without dedicated switch are switched with the volume knob + m_fmradiopower = m_fmradiovolume > 0.f; + } + } + if (m_fmradiotunechange != 0) + { + // the knob moves slowly at first to allow fine tuning, then speeds up + m_fmradiotunetime += static_cast(Deltatime); + auto const tunerate{std::lerp(0.15f, 2.5f, std::clamp(m_fmradiotunetime * 0.5f, 0.f, 1.f))}; // MHz per second + m_fmradiodial = std::clamp(m_fmradiodial + 100.f * m_fmradiotunechange * tunerate * static_cast(Deltatime) / bandwidth, 0.f, 100.f); + } + else + { + m_fmradiotunetime = 0.f; + } + + fmradio.type(m_fmradiotype); + fmradio.tune(audio::EU07_FMRADIO_BANDSTART + m_fmradiodial * 0.01f * bandwidth); + fmradio.volume(m_fmradiovolume); + fmradio.placement(m_fmradiosound.location(), m_fmradiosound.soundproofing_factor(), m_fmradiosound.range()); + // NOTE: the receiver runs on batteries of its own, so it doesn't care about the state of the vehicle + fmradio.power(m_fmradiopower); +} diff --git a/vehicle/cab/train.cpp b/vehicle/cab/train.cpp new file mode 100644 index 000000000..5173a40b5 --- /dev/null +++ b/vehicle/cab/train.cpp @@ -0,0 +1,944 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the train the user drives: construction, its state, taking a vehicle, the trains of the scenery + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +std::vector const TTrain::fPress_labels = { + + "ch1: ", "ch2: ", "ch3: ", "ch4: ", "ch5: ", "ch6: ", "ch7: ", "ch8: ", "ch9: ", "ch0: "}; + +TTrain::TTrain() +{ + + // McZapkie-240302 - przyda sie do tachometru + + // asMessage=""; + DynamicSet(nullptr); // ustawia wszystkie mv* + //----- + + // + for (int i = 0; i < 8; i++) + { + bMains[i] = false; + fCntVol[i] = 0.0f; + bPants[i][0] = false; + bPants[i][1] = false; + bFuse[i] = false; + bBatt[i] = false; + bConv[i] = false; + bComp[i][0] = false; + bComp[i][1] = false; + // bComp[ i ][ 2 ] = false; + // bComp[ i ][ 3 ] = false; + bHeat[i] = false; + } + bCompressors.clear(); + for (int i = 0; i < 9; ++i) + for (int j = 0; j < 10; ++j) + { + fEIMParams[i][j] = 0.0; + fDieselParams[i][j] = 0.0; + } + + for (int i = 0; i < 20; ++i) + { + for (auto &press : fPress[i]) + press = 0.0; + bBrakes[i][0] = false; + bBrakes[i][1] = false; + } +} + +TTrain::~TTrain() = default; + +bool TTrain::Init(TDynamicObject *NewDynamicObject, bool e3d) +{ // powiązanie ręcznego sterowania kabiną z pojazdem + if (NewDynamicObject->Mechanik == nullptr) + { + /* + ErrorLog( "Bad config: can't take control of inactive vehicle \"" + NewDynamicObject->asName + "\"" ); + return false; + */ + auto const activecab{(NewDynamicObject->physics->CabOccupied() > 0 ? "1" : NewDynamicObject->physics->CabOccupied() < 0 ? "2" : "p")}; + NewDynamicObject->create_controller(activecab, NewDynamicObject->ctOwner != nullptr); + } + + DynamicSet(NewDynamicObject); + if (!e3d && DynamicObject->Mechanik == nullptr) + return false; + + DynamicObject->MechInside = true; + + fMainRelayTimer = 0; // Hunter, do k...y nędzy, ustawiaj wartości początkowe zmiennych! + + iCabn = occupied->CabOccupied() > 0 ? 1 : occupied->CabOccupied() < 0 ? 2 : 0; + + { + Global.CurrentMaxTextureSize = Global.iMaxCabTextureSize; + + auto const filename{occupied->TypeName + ".mmd"}; + LoadMMediaFile(filename); + InitializeCab(occupied->CabOccupied(), filename); + + Global.CurrentMaxTextureSize = Global.iMaxTextureSize; + + if (DynamicObject->Controller == Humandriver) + { + // McZapkie-030303: mozliwosc wyswietlania kabiny, w przyszlosci dac opcje w mmd + DynamicObject->bDisplayCab = true; + } + } + + // Ra: taka proteza - przesłanie kierunku do członów connected + /* + if (controlled->DirActive > 0) + { // było do przodu + controlled->DirectionBackward(); + controlled->DirectionForward(); + } + else if (controlled->DirActive < 0) + { + controlled->DirectionForward(); + controlled->DirectionBackward(); + } + */ + if (false == DynamicObject->Mechanik->AIControllFlag()) + { + DynamicObject->Mechanik->sync_consist_reversers(); + } + + return true; +} + +std::shared_ptr TTrain::GetTrainState(dictionary_source const &Extraparameters) +{ + + if (occupied == nullptr || controlled == nullptr) + { + return nullptr; + } + + auto dict = std::make_shared(Extraparameters); + if (dict == nullptr) + { + return nullptr; + } + + dict->insert("name", DynamicObject->asName); + dict->insert("cab", occupied->CabOccupied()); + dict->insert("cabactive", occupied->CabActive); + dict->insert("master", occupied->CabMaster()); + // basic systems state data + dict->insert("battery", occupied->lowVoltage.Is24vAvailable()); + dict->insert("linebreaker", controlled->lineBreaker.IsClosed()); + dict->insert("main_init", controlled->lineBreaker.RemainingInitTime() < controlled->lineBreaker.config.initTime && controlled->lineBreaker.RemainingInitTime() > 0.0); + dict->insert("main_ready", false == controlled->lineBreaker.IsClosed() && fHVoltage > 0.0 && controlled->lineBreaker.IsInitialised()); + dict->insert("converter", occupied->lowVoltage.Is110vAvailable()); + dict->insert("converter_overload", controlled->converter.IsOverloaded()); + dict->insert("compress", controlled->air.compressor.IsRunning()); + dict->insert("pant_compressor", pantographUnit->pantographAir.IsCompressorRunning()); + dict->insert("lights_front", occupied->LitLights()[VehicleEnd::front]); + dict->insert("lights_rear", occupied->LitLights()[VehicleEnd::rear]); + dict->insert("off_from_dimmer", occupied->currentDimPosition().isOff); + dict->insert("lights_compartments", occupied->CompartmentLights.is_active || occupied->CompartmentLights.is_disabled); + if (Dynamic()->Mechanik) + { + auto const *controller{Dynamic()->Mechanik}; + auto const cabmodifier{cab_to_end() == VehicleEnd::front ? 1 : -1}; + auto const traindirection{controller->Direction() * cabmodifier}; + auto const *frontvehicle{controller->Vehicle(traindirection >= 0 ? VehicleEnd::front : VehicleEnd::rear)}; + auto const *rearvehicle{controller->Vehicle(traindirection >= 0 ? VehicleEnd::rear : VehicleEnd::front)}; + auto const frontvehicledirection{(frontvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; + auto const rearvehicledirection{(rearvehicle->DirectionGet() == controller->Vehicle()->DirectionGet() ? 1 : -1)}; + auto const fronttrainlights{frontvehicle->physics->LitLights()[frontvehicledirection * cabmodifier >= 0 ? VehicleEnd::front : VehicleEnd::rear]}; + auto const reartrainlights{rearvehicle->physics->LitLights()[rearvehicledirection * cabmodifier >= 0 ? VehicleEnd::rear : VehicleEnd::front]}; + dict->insert("lights_train_front", fronttrainlights); + dict->insert("lights_train_rear", reartrainlights); + } + else + { + // fallback, in the unlikely case we lose the controller + dict->insert("lights_train_front", occupied->LitLights()[VehicleEnd::front]); + dict->insert("lights_train_rear", occupied->LitLights()[VehicleEnd::rear]); + } + // reverser + dict->insert("direction", occupied->DirActive); + // throttle + dict->insert("mainctrl_pos", controlled->MainCtrlPos()); + dict->insert("mainctrl_pos_count", controlled->MainCtrlPosNo); + dict->insert("main_ctrl_actual_pos", controlled->MainCtrlActualPos); + dict->insert("scndctrl_pos", controlled->ScndCtrlPos()); + dict->insert("dynamicbrake_pos", controlled->brakes.electrodynamic.controllerPosition); + dict->insert("scnd_ctrl_actual_pos", controlled->ScndCtrlActualPos); + dict->insert("brakectrl_pos", controlled->brakes.HandlePositionSmooth()); + dict->insert("localbrake_pos", controlled->brakes.IndependentPosition()); + dict->insert("new_speed", occupied->NewSpeed()); + dict->insert("speedctrl", occupied->SpeedCtrlValue); + dict->insert("speedctrlpower", occupied->SpeedCtrlUnit.DesiredPower); + dict->insert("speedctrlactive", occupied->SpeedCtrlUnit.IsActive); + dict->insert("speedctrlstandby", occupied->SpeedCtrlUnit.Standby); + // brakes + dict->insert("manual_brake", occupied->brakes.HandBrakePosition() > 0); + bool const bEP = controlled->brakes.independentValve->GetCP() > 0.2 || fEIMParams[0][5] > 0.01; + dict->insert("dir_brake", bEP); + bool bPN{false}; + auto const &brakevalve{*occupied->brakes.distributor}; + if (auto const &brakevalvetype{typeid(brakevalve)}; brakevalvetype == typeid(TLSt) || brakevalvetype == typeid(TEStED)) + { + + TBrake *temp_ham = occupied->brakes.distributor.get(); + bPN = static_cast(temp_ham)->GetEDBCP() > 0.2; + } + dict->insert("indir_brake", bPN); + dict->insert("emergency_brake", occupied->brakes.alarmChain); + dict->insert("brake_delay_flag", occupied->brakes.delaySetting); + dict->insert("brake_op_mode_flag", occupied->brakes.operatingMode); + dict->insert("pipelock", occupied->brakes.pipeLock.locked); + // other controls + dict->insert("ca", occupied->SecuritySystem.is_vigilance_blinking()); + dict->insert("shp", occupied->SecuritySystem.is_cabsignal_blinking()); + dict->insert("distance_counter", m_distancecounter); + dict->insert("pantpress", std::abs(pantographUnit->pantographAir.Pressure())); + dict->insert("universal3", InstrumentLightActive); + for (auto idx = 0; idx < ggUniversals.size(); idx++) + { + if (idx != 3) + { + dict->insert("universal" + std::to_string(idx), ggUniversals[idx].GetValue() > 0.5); + } + } + dict->insert("radio", occupied->Radio()); + dict->insert("radio_fuse", occupied->RadioFuse()); + dict->insert("radio_channel", RadioChannel()); + dict->insert("radio_volume", m_radiovolume); + dict->insert("door_lock", occupied->Doors.lock_enabled); + dict->insert("door_step", occupied->Doors.step_enabled); + dict->insert("door_permit_left", occupied->Doors.instances[VehicleSide::left].open_permit); + dict->insert("door_permit_right", occupied->Doors.instances[VehicleSide::right].open_permit); + // movement data + dict->insert("velocity", std::abs(occupied->Vel)); + dict->insert("tractionforce", std::abs(occupied->Ft())); + dict->insert("slipping_wheels", occupied->SlippingWheels()); + dict->insert("sanding", occupied->SandDose()); + dict->insert("odometer", occupied->DistCounter()); // distance run in the session, km + dict->insert("odometer_total", occupied->Odometer.km); // the vehicle's odometer, kept between the sessions + // electric current data + dict->insert("traction_voltage", std::abs(pantographUnit->pantographCircuit.SupplyVoltage())); + dict->insert("voltage", std::abs(controlled->EngineVoltage)); + dict->insert("im", std::abs(controlled->Im)); + dict->insert("fuse", controlled->FuseFlag); + dict->insert("epfuse", occupied->EpFuse()); + dict->insert("power_drawn", occupied->EnergyMeter.first); + dict->insert("power_returned", occupied->EnergyMeter.second); + + // induction motor state data + std::array const TXTT{"fd", "fdt", "fdb", "pd", "pdt", "pdb", "itothv", "1", "2", "3"}; + std::array const TXTC{"fr", "frt", "frb", "pr", "prt", "prb", "im", "vm", "ihv", "uhv"}; + std::array const TXTD{"enrot", "nrot", "fill_des", "fill_real", "clutch_des", "clutch_real", "water_temp", "oil_press", "engine_temp", "retarder_fill"}; + std::array const TXTP{"bc", "bp", "sp", "cp", "rp", "mass", "spring"}; + char const *TXTB[2] = {"spring_active", "spring_shutoff"}; + for (int j = 0; j < 10; ++j) + dict->insert("eimp_t_" + std::string(TXTT[j]), fEIMParams[0][j]); + for (int i = 0; i < 8; ++i) + { + auto const idx{std::to_string(i + 1)}; + for (int j = 0; j < 10; ++j) + dict->insert("eimp_c" + idx + "_" + std::string(TXTC[j]), fEIMParams[i + 1][j]); + + for (int j = 0; j < 10; ++j) + dict->insert("diesel_param_" + idx + "_" + std::string(TXTD[j]), fDieselParams[i + 1][j]); + + dict->insert("eimp_c" + idx + "_ms", bMains[i]); + dict->insert("eimp_c" + idx + "_cv", fCntVol[i]); + dict->insert("eimp_c" + idx + "_fuse", bFuse[i]); + dict->insert("eimp_c" + idx + "_batt", bBatt[i]); + dict->insert("eimp_c" + idx + "_conv", bConv[i]); + dict->insert("eimp_c" + idx + "_heat", bHeat[i]); + + dict->insert("eimp_u" + idx + "_pf", bPants[i][0]); + dict->insert("eimp_u" + idx + "_pr", bPants[i][1]); + dict->insert("eimp_u" + idx + "_comp_a", bComp[i][0]); + dict->insert("eimp_u" + idx + "_comp_w", bComp[i][1]); + } + + dict->insert("compressors_no", (int)bCompressors.size()); + for (int i = 0; i < bCompressors.size(); i++) + { + auto const idx{std::to_string(i + 1)}; + dict->insert("compressors_" + idx + "_allow", std::get<0>(bCompressors[i])); + dict->insert("compressors_" + idx + "_work", std::get<1>(bCompressors[i])); + dict->insert("compressors_" + idx + "_car_no", std::get<2>(bCompressors[i])); + } + + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied() > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); + int in = 0; + while (p && in < 8) + { + if (p->physics->inductionMotor.traction.maxPower > 1) + { + in++; + dict->insert("eimp_c" + std::to_string(in) + "_invno", p->physics->inductionMotor.inverterCount); + for (int j = 0; j < p->physics->inductionMotor.inverterCount; j++) + { + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_act", p->physics->inductionMotor.inverters[j].IsActive); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_error", p->physics->inductionMotor.inverters[j].Error); + dict->insert("eimp_c" + std::to_string(in) + "_inv" + std::to_string(j + 1) + "_allow", p->physics->inductionMotor.inverters[j].Activate); + } + } + p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); + } + for (int i = 0; i < 20; ++i) + { + for (int j = 0; j < 7; ++j) + { + dict->insert("eimp_pn" + std::to_string(i + 1) + "_" + TXTP[j], fPress[i][j]); + } + for (int j = 0; j < 2; ++j) + { + dict->insert("brakes_" + std::to_string(i + 1) + "_" + TXTB[j], bBrakes[i][j]); + } + } + // multi-unit state data + dict->insert("car_no", iCarNo); + dict->insert("power_no", iPowerNo); + dict->insert("unit_no", iUnitNo); + + for (int i = 0; i < 20; i++) + { + auto const caridx{std::to_string(i + 1)}; + dict->insert("doors_" + caridx, bDoors[i][0]); + dict->insert("doors_l_" + caridx, bDoors[i][1]); + dict->insert("doors_r_" + caridx, bDoors[i][2]); + dict->insert("doorstep_l_" + caridx, bDoors[i][3]); + dict->insert("doorstep_r_" + caridx, bDoors[i][4]); + dict->insert("doors_no_" + caridx, iDoorNo[i]); + dict->insert("code_" + caridx, std::to_string(iUnits[i]) + cCode[i]); + dict->insert("car_name" + caridx, asCarName[i]); + dict->insert("slip_" + caridx, bSlip[i]); + } + // ai state data + auto const *vehicledriver{(DynamicObject->ctOwner != nullptr ? DynamicObject->ctOwner : DynamicObject->Mechanik)}; + + dict->insert("velocity_desired", vehicledriver->DesiredVelocity()); + dict->insert("velroad", vehicledriver->RoadVelocity()); + dict->insert("vellimitlast", vehicledriver->LastLimitVelocity()); + dict->insert("velsignallast", vehicledriver->LastSignalVelocity()); + dict->insert("velsignalnext", vehicledriver->NextSignalVelocity()); + dict->insert("velnext", vehicledriver->NextVelocity()); + dict->insert("actualproximitydist", vehicledriver->ProximityDistance()); + // train data + vehicledriver->TrainTimetable().serialize(dict.get()); + dict->insert("train_atpassengerstop", vehicledriver->AtPassengerStop()); + dict->insert("train_length", vehicledriver->ConsistLength()); + // world state data + dict->insert("scenario", Global.SceneryFile); + dict->insert("hours", static_cast(simulation::Time.data().wHour)); + dict->insert("minutes", static_cast(simulation::Time.data().wMinute)); + dict->insert("seconds", static_cast(simulation::Time.second())); + dict->insert("air_temperature", Global.AirTemperature); + dict->insert("light_level", Global.fLuminance - std::max(0.f, Global.Overcast - 1.f)); + + return dict; +} + +TTrain::state_t TTrain::get_state() const +{ + + return { + btLampkaSHP.GetValue(), + btLampkaCzuwaka.GetValue(), + btLampkaRadioStop.GetValue(), + btLampkaOpory.GetValue(), + btLampkaWylSzybki.GetValue(), + btLampkaPrzekRozn.GetValue(), + btLampkaNadmSil.GetValue(), + btLampkaStyczn.GetValue(), + btLampkaPoslizg.GetValue(), + btLampkaNadmPrzetw.GetValue(), + btLampkaPrzetwOff.GetValue(), + btLampkaNadmSpr.GetValue(), + btLampkaNadmWent.GetValue(), + btLampkaWysRozr.GetValue(), + btLampkaOgrzewanieSkladu.GetValue(), + static_cast(iCabn), + btHaslerBrakes.GetValue(), + btHaslerCurrent.GetValue(), + occupied->SecuritySystem.is_beeping(), + btLampkaHVoltageB.GetValue(), + fTachoVelocity, + static_cast(occupied->air.MainReservoirPressure()), + static_cast(occupied->brakePipe.Pressure()), + static_cast(occupied->brakes.cylinderPressure), + static_cast(pantographUnit->pantographAir.Pressure()), + fHVoltage, + {fHCurrent[controlled->TrainType() == train_type::emu ? 0 : 1], fHCurrent[2], fHCurrent[3]}, + ggLVoltage.GetValue(), + occupied->DistCounter(), + static_cast(RadioChannel()), + btLampkaSpringBrakeActive.GetValue(), + btLampkaNapNastHam.GetValue(), + occupied->DirActive > 0, + occupied->DirActive < 0, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::right : VehicleSide::left].open_permit, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::right : VehicleSide::left].is_open, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::left : VehicleSide::right].open_permit, + occupied->Doors.instances[occupied->CabOccupied() < 0 ? VehicleSide::left : VehicleSide::right].is_open, + occupied->Doors.step_enabled, + occupied->lowVoltage.Is24vAvailable(), + 0, + occupied->brakes.pipeLock.locked, + btLampkaRadioMessage.GetValue(), + }; +} + +bool TTrain::is_eztoer() const +{ + + return controlled->TrainType() == train_type::emu && occupied->brakes.config.subsystem == TBrakeSubSystem::ss_ESt && controlled->lowVoltage.Is24vAvailable() == true && controlled->EpFuse() == true && + controlled->DirActive != 0; // od yB +} + +// move the master controller to specified position +void TTrain::set_master_controller(double const Position) +{ + + auto positionchange{std::min(static_cast(Position), controlled->CoupledCtrl ? controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo() : controlled->MainCtrlPosNo) - + (controlled->CoupledCtrl ? controlled->MainCtrlPos() + controlled->ScndCtrlPos() : controlled->MainCtrlPos())}; + while (positionchange < 0 && true == controlled->DecMainCtrl(1)) + { + ++positionchange; + } + while (positionchange > 0 && true == controlled->IncMainCtrl(1)) + { + --positionchange; + } +} + +// moves train brake lever to specified position, potentially emits switch sound if conditions are met +void TTrain::set_train_brake(double const Position) +{ + + auto const originalbrakeposition{static_cast(100.0 * occupied->brakes.HandlePositionSmooth())}; + occupied->BrakeLevelSet(Position); + + if (static_cast(100.0 * occupied->brakes.HandlePositionSmooth()) == originalbrakeposition) + { + return; + } + + // sound feedback if the lever movement activates one of the switches + if (true == is_eztoer() && false == ((originalbrakeposition / 100 == 0 || originalbrakeposition / 100 >= 5) && (occupied->brakes.HandlePosition() == 0 || occupied->brakes.HandlePosition() >= 5)) && dsbPneumaticSwitch) + { + dsbPneumaticSwitch->play(); + } +} + +void TTrain::zero_charging_train_brake() +{ + using enum TBrakeHandle; + + if (occupied->brakes.HandlePosition() == -1 && DynamicObject->Controller != AIdriver && Global.iFeedbackMode < 3 && + (occupied->brakes.config.driverValveType == FVel6 || occupied->brakes.config.driverValveType == MHZ_EN57 || occupied->brakes.config.driverValveType == MHZ_K8P)) + { + // Odskakiwanie hamulce EP + set_train_brake(0); + } +} + +void TTrain::set_train_brake_speed(TDynamicObject *Vehicle, int const Speed) +{ + + // visual feedback + // TODO: add setting indicator to vehicle class, for external lever/indicator + if (true == Vehicle->physics->BrakeDelaySwitch(Speed) && Vehicle == DynamicObject) + { + if (ggBrakeProfileCtrl.SubModel != nullptr) + { + ggBrakeProfileCtrl.UpdateValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 2.0 : static_cast(occupied->brakes.delaySetting - 1), dsbSwitch); + } + if (ggBrakeProfileG.SubModel != nullptr) + { + ggBrakeProfileG.UpdateValue(occupied->brakes.delaySetting == bdelay_G ? 1.0 : 0.0, dsbSwitch); + } + if (ggBrakeProfileR.SubModel != nullptr) + { + ggBrakeProfileR.UpdateValue((occupied->brakes.delaySetting & bdelay_R) != 0 ? 1.0 : 0.0, dsbSwitch); + } + } +} + +void TTrain::set_paired_open_motor_connectors_button(bool const State) +{ + + if (controlled->TrainType() == train_type::et41 || controlled->TrainType() == train_type::et42) + { + // crude implementation of the button affecting entire unit for multi-unit engines + // TODO: rework it into part of standard command propagation system + if (controlled->Couplers[VehicleEnd::front].Connected != nullptr && true == controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::permanent)) + { + controlled->Couplers[VehicleEnd::front].Connected->lineContactors.ForceOpen(State); + } + if (controlled->Couplers[VehicleEnd::rear].Connected != nullptr && true == controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::permanent)) + { + controlled->Couplers[VehicleEnd::rear].Connected->lineContactors.ForceOpen(State); + } + } +} + +// locates nearest vehicle belonging to the consist +TDynamicObject *TTrain::find_nearest_consist_vehicle(bool freefly, glm::vec3 pos) const +{ + if (!freefly) + return DynamicObject; + + auto couplerindex{-2}; // scan for vehicle, not any specific coupler + auto *vehicle{DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), 1, 1500, couplerindex)}; + if (vehicle == nullptr) + vehicle = DynamicObject->ABuScanNearestObject(pos, DynamicObject->GetTrack(), -1, 1500, couplerindex); + // TBD, TODO: perform owner test for the located vehicle + return vehicle; +} + +// cab movement update, fixed step part +void TTrain::UpdateCab() +{ + + // Ra: przesiadka, jeśli AI zmieniło kabinę (a człon?)... + if (DynamicObject->Mechanik // może nie być? + && DynamicObject->Mechanik->AIControllFlag() && iCabn != ( // numer kabiny (-1: kabina B) + occupied->CabOccupied() == -1 ? 2 : occupied->CabOccupied())) + { + + InitializeCab(occupied->CabOccupied(), occupied->TypeName + ".mmd"); + } + iCabn = occupied->CabOccupied() == -1 ? 2 : occupied->CabOccupied(); +} + +void TTrain::add_distance(double const Distance) +{ + + auto const meterenabled{m_distancecounter >= 0 && (occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable())}; + + if (true == meterenabled) + { + m_distancecounter += static_cast(Distance * Occupied()->CabOccupied()); + } + else + { + m_distancecounter = -1.f; + } +} + +bool TTrain::CabChange(int iDirection) +{ // McZapkie-090902: zmiana kabiny 1->0->2 i z powrotem + if (DynamicObject->Mechanik == nullptr || true == DynamicObject->Mechanik->AIControllFlag()) + { + // jeśli prowadzi AI albo jest w innym członie + // jak AI prowadzi, to nie można mu mieszać + if (std::abs(occupied->CabOccupied() + iDirection) > 1) + return false; // ewentualna zmiana pojazdu + occupied->SetCabOccupied(occupied->CabOccupied() + iDirection); + } + else + { // jeśli pojazd prowadzony ręcznie albo wcale (wagon) + occupied->CabDeactivisationAuto(); + if (occupied->ChangeCab(iDirection) && InitializeCab(occupied->CabOccupied(), occupied->TypeName + ".mmd")) + { + // zmiana kabiny w ramach tego samego pojazdu + occupied->CabActivisationAuto(); // załączenie rozrządu (wirtualne kabiny) + DynamicObject->Mechanik->DirectionChange(); + return true; // udało się zmienić kabinę + } + // aktywizacja poprzedniej, bo jeszcze nie wiadomo, czy jakiś pojazd jest + occupied->CabActivisationAuto(); + } + return false; // ewentualna zmiana pojazdu +} + +void TTrain::DynamicSet(TDynamicObject *d) +{ // taka proteza: chcę podłączyć + // kabinę EN57 bezpośrednio z + // silnikowym, aby nie robić tego + // przez ukrotnienie + // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka + // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą + // świecić się w rozrządczych + // dla EZT światła czołowe będą "zapalane w silnikowym", ale widziane z + // rozrządczych + // również wczytywanie MMD powinno dotyczyć aktualnego członu + // problematyczna może być kwestia wybranej kabiny (w silnikowym...) + // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno + // jeździć dobrze + // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... + DynamicObject = d; // jedyne miejsce zmiany + controlled = d ? DynamicObject->physics : nullptr; // albo silnikowy w EZT + occupied = controlled; + + if (DynamicObject == nullptr) + { + return; + } + + controlled = DynamicObject->FindPowered()->physics; + secondUnit = nullptr; // gdyby się nic nie znalazło + if (occupied->Power > 1.0) // dwuczłonowe lub ukrotnienia, żeby nie szukać każdorazowo + { + if (occupied->Couplers[1].Connected != nullptr && occupied->Couplers[1].AllowedFlag.HasAny(Coupling::control)) + { // gdy jest człon od sprzęgu 1, a sprzęg łączony + // warsztatowo (powiedzmy) + if (occupied->Couplers[1].Connected->Power > 1.0) // ten drugi ma moc + secondUnit = occupied->Couplers[1].Connected; // wskaźnik na drugiego + } + else if (occupied->Couplers[0].Connected != nullptr && occupied->Couplers[0].AllowedFlag.HasAny(Coupling::control)) + { // gdy jest człon od sprzęgu 0, a sprzęg łączony + // warsztatowo (powiedzmy) + if (occupied->Couplers[0].Connected->Power > 1.0) // ale ten drugi ma moc + secondUnit = occupied->Couplers[0].Connected; // wskaźnik na drugiego + } + } + // cache nearest unit equipped with pantographs + { + auto *lookup{DynamicObject->FindPantographCarrier()}; + // HACK: set pointer to existing vehicle to avoid error checking all over the place + pantographUnit = lookup != nullptr ? lookup->physics : controlled; + } +}; + +void TTrain::MoveToVehicle(TDynamicObject *target) +{ + // > Ra: to nie może być tak robione, to zbytnia proteza jest + // indeed, too much hacks... + // TODO: cleanup + TTrain *target_train = simulation::Trains.find(target->name()); + if (target_train) + { + // let's try to destroy this TTrain and move to already existing one + + if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag()) + { + // tylko jeśli ręcznie prowadzony + // jeśli prowadzi AI, to mu nie robimy dywersji! + Occupied()->CabDeactivisation(); + Occupied()->SetCabOccupied(0); + Occupied()->BrakeLevelSet(Occupied()->brakes.driverValve->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 + Occupied()->SetMainCtrlPos(Occupied()->MainCtrlNoPowerPos()); + Occupied()->SetScndCtrlPos(0); + Dynamic()->MechInside = false; + Dynamic()->Controller = AIdriver; + + Dynamic()->bDisplayCab = false; + Dynamic()->ABuSetModelShake({}); + + if (Dynamic()->Mechanik) + Dynamic()->Mechanik->MoveTo(target); + + target_train->Occupied()->brakes.pipeLimiterPressure = target_train->Occupied()->brakePipe.Pressure(); + target_train->Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) + target_train->Dynamic()->MechInside = true; + if (target_train->Dynamic()->Mechanik) + { + target_train->Dynamic()->Controller = target_train->Dynamic()->Mechanik->AIControllFlag(); + target_train->Dynamic()->Mechanik->DirectionChange(); + } + else + { + target_train->Dynamic()->Controller = Humandriver; + } + } + else + { + target_train->Dynamic()->bDisplayCab = false; + target_train->Dynamic()->ABuSetModelShake({}); + } + + target_train->Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? + + // potentially move player + if (simulation::Train == this) + { + simulation::Train = target_train; + // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization + target_train->Dynamic()->bDisplayCab |= !FreeFlyModeFlag; + } + + // delete this TTrain + pending_delete = true; + } + else + { + // move this TTrain to other dynamic + + // remove TTrain from global list, we're going to change dynamic anyway + simulation::Trains.detach(Dynamic()->name()); + + if (!Dynamic()->Mechanik || !Dynamic()->Mechanik->AIControllFlag()) + { + // tylko jeśli ręcznie prowadzony + // jeśli prowadzi AI, to mu nie robimy dywersji! + + Occupied()->CabDeactivisation(); + Occupied()->SetCabOccupied(0); + Occupied()->BrakeLevelSet(Occupied()->brakes.driverValve->GetPos(bh_NP)); // rozwala sterowanie hamulcem GF 04-2016 + Occupied()->SetMainCtrlPos(Occupied()->MainCtrlNoPowerPos()); + Occupied()->SetScndCtrlPos(0); + Dynamic()->MechInside = false; + Dynamic()->Controller = AIdriver; + + Dynamic()->bDisplayCab = false; + Dynamic()->ABuSetModelShake({}); + + if (Dynamic()->Mechanik) + Dynamic()->Mechanik->MoveTo(target); + + DynamicSet(target); + + Dynamic()->MechInside = true; + if (Dynamic()->Mechanik) + { + Dynamic()->Controller = Dynamic()->Mechanik->AIControllFlag(); + Dynamic()->Mechanik->DirectionChange(); + } + else + { + Dynamic()->Controller = Humandriver; + } + + Occupied()->brakes.pipeLimiterPressure = Occupied()->brakePipe.Pressure(); + Occupied()->CabActivisationAuto(true); // załączenie rozrządu (wirtualne kabiny) + } + else + { + Dynamic()->bDisplayCab = false; + Dynamic()->ABuSetModelShake({}); + + DynamicSet(target); + } + + { + auto const filename{Occupied()->TypeName + ".mmd"}; + LoadMMediaFile(filename); + InitializeCab(Occupied()->CabActive, filename); + } + + Dynamic()->ABuSetModelShake({}); // zerowanie przesunięcia przed powrotem? + + if (simulation::Train == this) + { + // our local driver may potentially be in external view mode, in which case we shouldn't activate cab visualization + Dynamic()->bDisplayCab |= !FreeFlyModeFlag; + } + + // add it back with updated dynamic name + simulation::Trains.insert(this); + } +} + +// checks whether specified point is within boundaries of the active cab +bool TTrain::point_inside(glm::dvec3 const Point) const +{ + + return Point.x >= Cabine[iCabn].CabPos1.x && Point.x <= Cabine[iCabn].CabPos2.x && Point.y >= Cabine[iCabn].CabPos1.y + 0.5 && Point.y <= Cabine[iCabn].CabPos2.y + 1.8 && + Point.z >= Cabine[iCabn].CabPos1.z && Point.z <= Cabine[iCabn].CabPos2.z; +} + +glm::dvec3 TTrain::clamp_inside(glm::dvec3 const &Point) const +{ + + if (DebugModeFlag) + { + return Point; + } + + // the bounds come from the .mmd as written, and some cabs have them reversed (the B cars of SA134 and 21xM, + // ET40, 754...); std::clamp is undefined for those and on MSVC makes the camera jump between the two bounds + // every frame, as its result is fed back here. safe_clamp keeps the camera on the upper bound, as 26.05 did + return {safe_clamp(Point.x, (double)Cabine[iCabn].CabPos1.x, (double)Cabine[iCabn].CabPos2.x), safe_clamp(Point.y, (double)Cabine[iCabn].CabPos1.y + 0.5, (double)Cabine[iCabn].CabPos2.y + 1.8), + safe_clamp(Point.z, (double)Cabine[iCabn].CabPos1.z, (double)Cabine[iCabn].CabPos2.z)}; +} + +void TTrain::radio_message(sound_source *Message, int const Channel) +{ + + if (auto const soundrange{Message->range()}; soundrange > 0 && glm::length2(Message->location() - glm::dvec3{DynamicObject->GetPosition()}) > sq(soundrange)) + { + // skip message playback if the receiver is outside of the emitter's range + return; + } + // NOTE: we initiate playback of all sounds in range, in case the user switches on the radio or tunes to the right channel mid-play + m_radiomessages.emplace_back(Channel, std::make_shared(m_radiosound)); + // assign sound to the template and play it + auto &message = *m_radiomessages.back().second.get(); + auto const radioenabled{occupied->RadioPowered()}; + auto const volume{true == radioenabled && Dynamic()->Mechanik != nullptr && Channel == RadioChannel() ? 1.0 : 0.0}; + message.copy_sounds(*Message).gain(static_cast(volume)).play(); +} + +uint16_t TTrain::id() +{ + if (vid == 0) + { + vid = ++simulation::prev_train_id; + WriteLog("net: assigning id " + std::to_string(vid) + " to vehicle " + Dynamic()->name(), logtype::net); + } + return vid; +} +namespace +{ + +// updates trains in range [Start, End) +void update_trains(std::deque const &Trains, std::size_t const Start, std::size_t const End, double const Dt) +{ + for (std::size_t j = Start; j < End; ++j) + { + if (Trains[j]) + Trains[j]->Update(Dt); + } +} + +} // namespace + +void train_table::updateAsync(double dt) +{ + const int threads = std::max(1, Global.trainThreads); + const size_t total = m_items.size(); + const size_t chunkSize = (total + threads - 1) / threads; + auto const instance{TSubModel::iInstance}; + + std::vector workers; + std::vector> results; // przekazują wyjątki z wątków do głównego wątku + workers.reserve(threads); + results.reserve(threads); + + for (int i = 0; i < threads; ++i) + { + const size_t start = i * chunkSize; + const size_t end = std::min(start + chunkSize, total); + + if (start >= end) + break; // brak więcej danych + + // the instance whose animations the gauges set (TSubModel::iInstance, per thread since the walks of the vulkan renderer went on + // several threads) is the one the main thread set for the driven vehicle + std::packaged_task task([this, start, end, dt, instance]() { + TSubModel::iInstance = instance; + update_trains(m_items, start, end, dt); + }); + results.emplace_back(task.get_future()); + workers.emplace_back(std::move(task)); + } + + // Poczekaj aż wszystkie wątki skończą + for (auto &worker : workers) + worker.join(); + + for (auto &result : results) + result.get(); + + // Teraz kasowanie (tylko w głównym wątku) + for (TTrain *train : m_items) + { + if (!train) + continue; + + if (train->pending_delete) + { + purge(train->Dynamic()->name()); + if (simulation::Train == train) + simulation::Train = nullptr; + } + else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) + { + purge(train->Dynamic()->name()); + } + } +} + +void train_table::update(double dt) +{ + for (TTrain *train : m_items) + { + if (!train) + continue; + + train->Update(dt); + + if (train->pending_delete) + { + purge(train->Dynamic()->name()); + if (simulation::Train == train) + simulation::Train = nullptr; + } + // for single-player destroy non-player trains + else if (simulation::Train != train && Global.network_servers.empty() && !Global.network_client) + { + purge(train->Dynamic()->name()); + } + } +} + +TTrain *train_table::find_id(std::uint16_t const Id) const +{ + + if (Id == 0) + { + return nullptr; + } + + for (TTrain *train : m_items) + { + if (!train) + { + continue; + } + if (train->id() == Id) + { + return train; + } + } + return nullptr; +} diff --git a/vehicle/cab/update.cpp b/vehicle/cab/update.cpp new file mode 100644 index 000000000..93e6f8758 --- /dev/null +++ b/vehicle/cab/update.cpp @@ -0,0 +1,1615 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the update of the cab in a step of the simulation + +#include "stdafx.h" +#include "vehicle/Train.h" +#include "vehicle/horn.h" +#include "vehicle/linebreaker.h" +#include "vehicle/holdcoillever.h" +#include "vehicle/compartmentlightsswitch.h" +#include "vehicle/odometer.h" +#include "vehicle/mainctrlact.h" +#include "utilities/Globals.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "world/Event.h" +#include "simulation/simulationtime.h" +#include "vehicle/Camera.h" +#include "utilities/Logs.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "utilities/Timer.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "world/mtable.h" +#include "Console.h" +#include "application/application.h" +#include "rendering/renderer.h" +#include "physics/vehicle.h" +#include +#include +#include +#include +#include +#include "vehicle/cab/internal.h" + + +bool TTrain::Update(double const Deltatime) +{ + // train state update + updateLineBreakerState(Deltatime); + // the switches of the other vehicles in multiple + update_remote_linebreakers(Deltatime); + updateTimers(Deltatime); + updateDoorAndDirectionStates(); + processReceivedCommands(); + + UpdateCab(); + + returnMasterController(Deltatime); + updateTachometer(Deltatime); + updateVoltagesAndCurrents(); + updateUnitStates(); + updateFeedbackGauges(); + updateConverterOverload(Deltatime); + auto const lowvoltagepower{occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable()}; + + updateSecondUnitGauges(); + updateClock(); + + Cabine[iCabn].Update(lowvoltagepower); // nowy sposób ustawienia animacji + /* + if (ggZbS.SubModel) + { + ggZbS.UpdateValue(occupied->Handle->GetCP()); + ggZbS.Update(); + } + */ + // replacement for the above. TODO: move it to a more suitable place + m_brakehandlecp = occupied->brakes.driverValve->GetCP(); + + updateEngineGauges(); + updateBasicLamps(); + + if (true == lowvoltagepower) + { + updateCircuitLamps(Deltatime); + updateTrainLamps(); + } + else + { + turnOffLamps(); + } + + updateSecondUnitLamps(lowvoltagepower); + updateMasterControllers(lowvoltagepower); + updateBrakeControllers(); + updateCabSwitches(lowvoltagepower); + updateHeatingAndInstrumentLights(); + updateButtons(); + updateAuxiliaryButtons(lowvoltagepower); + + // wyprowadzenie sygnałów dla haslera na PoKeys (zaznaczanie na taśmie) + btHaslerBrakes.Turn(occupied->brakes.cylinderPressure > 0.4); // ciśnienie w cylindrach + btHaslerCurrent.Turn(occupied->Im != 0.0); // prąd na silnikach + + updateCabLightLevels(); + + // anti slip system activation, maintained while the control button is down + if (occupied->brakes.config.kind != TBrakeSystem::ElectroPneumatic && ggAntiSlipButton.GetDesiredValue() > 0.95) + { + controlled->AntiSlippingBrake(); + } + // screens + + if (!FreeFlyModeFlag && simulation::Train == this) // don't bother if we're outside + { + update_screens(Deltatime); + update_script_screens(); + } + + // update direction relay + if (prevBatState != occupied->lowVoltage.Is24vAvailable()) + SetupDirectionRelays(); + if (prevDirection != occupied->DirActive) + UpdateDirectionRelays(); + + prevBatState = occupied->lowVoltage.Is24vAvailable(); + prevDirection = occupied->DirActive; + + // sounds + update_sounds(Deltatime); + + return true; //(DynamicObject->Update(dt)); +} // koniec update + +// keeps the state of the line breaker in step with the vehicle and with the buttons that close and open it +void TTrain::updateLineBreakerState(double const Deltatime) +{ + // line breaker: + if (m_linebreakerstate == linebreaker::state::open && true == controlled->lineBreaker.IsClosed()) + { + // crude way to sync state of the linebreaker with ai-issued commands + m_linebreakerstate = linebreaker::state::closed; + } + if (m_linebreakerstate == linebreaker::state::closed && false == (controlled->lineBreaker.IsClosed() || controlled->diesel.startupRequested)) + { + // crude way to catch cases where the main was knocked out + // because the state of the line breaker isn't changed to match, we need to do it here manually + m_linebreakerstate = linebreaker::state::open; + } + if (vehicle_cab::is_hold_coil_lever(ggMainOffButton) && hold_coil_lever::cuts_off(ggMainOffButton.GetDesiredValue())) + { + if (true == controlled->lineBreaker.IsClosed()) + { + // the line breaker was closed with the hold coil lever off, by the AI or through the control cable: + // put the lever back on to match, like the line breaker state above + ggMainOffButton.UpdateValue(0.0); + } + else if (m_linebreakerstate == linebreaker::state::closing) + { + // the hold coil was cut off while the closing button was held, the line breaker won't close on its release + m_linebreakerstate = linebreaker::state::open; + } + } + + if ((ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || + ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95 || + ggIgnitionKey.GetDesiredValue() > 0.95) + { // HACK: fallback + // keep track of period the line breaker button is held down, to determine when/if circuit closes + if (controlled->MainSwitchCheck()) + { + fMainRelayTimer += static_cast(Deltatime); + } + } + else + { + // button isn't down, reset the timer + fMainRelayTimer = 0.0f; + } + if (ggMainOffButton.GetDesiredValue() > 0.95) + { + // if the button disconnecting the line breaker is down prevent the timer from accumulating + fMainRelayTimer = 0.0f; + } + if (m_linebreakerstate == linebreaker::state::open && fMainRelayTimer > controlled->InitialCtrlDelay()) + { + // wlaczanie WSa z opoznieniem + // mark the line breaker as ready to close; for electric series vehicles with impulse switch the setup is completed on button release + m_linebreakerstate = linebreaker::state::closing; + } + // for diesels and/or vehicles with toggle switch setup we complete the engine start here + // TODO: make it a test for main_on_bt of type push_delayed instead + if (m_linebreakerstate == linebreaker::state::closing && (ggMainOnButton.SubModel == nullptr || controlled->EngineType != TEngineType::ElectricSeriesMotor)) + { + // try to finalize state change of the line breaker, set the state based on the outcome + m_linebreakerstate = controlled->MainSwitch(true, controlled->MainSwitchRange()) ? linebreaker::state::closed : linebreaker::state::open; + } +} + +// counts down the door permit, the train length measurement and the battery timers +void TTrain::updateTimers(double const Deltatime) +{ + // door permits + for (auto idx = 0; idx < 2; ++idx) + { + auto &doorpermittimer{m_doorpermittimers[idx]}; + if (doorpermittimer < 0.f) + { + continue; + } + doorpermittimer -= static_cast(Deltatime); + if (doorpermittimer < 0.f) + { + occupied->OperateDoors(static_cast(idx), true); + } + } + + // train measurement timer + if (trainLenghtMeasureTimer >= 0.f) + { + trainLenghtMeasureTimer -= static_cast(Deltatime); + if (trainLenghtMeasureTimer < 0.f) + trainLenghtMeasureTimer = -1.f; + } + + // battery timer + if (fBatteryTimer >= 0.f) + { + fBatteryTimer -= static_cast(Deltatime); + if (fBatteryTimer < 0.f) + fBatteryTimer = -1.f; + } +} + +// sets the helper flags of the open doors, the door permits and the direction of travel +void TTrain::updateDoorAndDirectionStates() +{ + // helper variables + if (DynamicObject->Mechanik != nullptr) + { + m_doors = DynamicObject->Mechanik->ConsistDoorsOpen()[VehicleSide::right] || DynamicObject->Mechanik->ConsistDoorsOpen()[VehicleSide::left]; + m_doorpermits = DynamicObject->Mechanik->ConsistDoorPermits()[VehicleSide::right] || DynamicObject->Mechanik->ConsistDoorPermits()[VehicleSide::left]; + m_doorspermitleft = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right].open_permit && + (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking() < 1 || + occupied->DoorsPermitLightBlinking() < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right] || + (occupied->DoorsPermitLightBlinking() < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right])); + m_doorspermitright = occupied->Doors.instances[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left].open_permit && + (simulation::Time.data().wSecond % 2 < 1 || occupied->DoorsPermitLightBlinking() < 1 || + occupied->DoorsPermitLightBlinking() < 2 && DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left] || + (occupied->DoorsPermitLightBlinking() < 3 && DynamicObject->Mechanik->ConsistDoorsOnlyOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left])); + } + m_dirforward = controlled->DirActive > 0; + m_dirneutral = controlled->DirActive == 0; + m_dirbackward = controlled->DirActive < 0; +} + +// passes the user commands received by the vehicle to their handlers +void TTrain::processReceivedCommands() +{ + // check for received user commands + // NOTE: this is a temporary arrangement, for the transition period from old command setup to the new one + // eventually commands are going to be retrieved directly by the vehicle, filtered through active control stand + // and ultimately executed, provided the stand allows it. + command_data commanddata; + while (simulation::Commands.pop(commanddata, static_cast(command_target::vehicle) | id())) + { + simulation::Blackbox.command(DynamicObject, commanddata.command, commanddata.action, commanddata.param1, commanddata.param2); + + auto lookup = m_commandhandlers.find(commanddata.command); + if (lookup != m_commandhandlers.end()) + { + // debug data + if (commanddata.action == GLFW_PRESS) + { + WriteLog(occupied->Name + " received command: [" + simulation::Commands_descriptions[static_cast(commanddata.command)].name + "]"); + } + // pass the command to the assigned handler + lookup->second(this, commanddata); + } + } +} + +// moves the master controller a step towards the actual position of the switch group when the driver leaves it (ET40, EP05, camshaft) +void TTrain::returnMasterController(double const Deltatime) +{ + // nie blokujemy AI + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() && (occupied->TrainType() == train_type::et40 || occupied->TrainType() == train_type::ep05 || occupied->HasCamshaft)) + { + // dla ET40 i EU05 automatyczne cofanie nastawnika - i tak nie będzie to działać dobrze... + // TODO: use deltatime to stabilize speed + /* + if( false == ( + ( input::command == user_command::mastercontrollerset ) + || ( input::command == user_command::mastercontrollerincrease ) + || ( input::command == user_command::mastercontrollerdecrease ) ) ) { + */ + if (false == (m_mastercontrollerinuse || Global.ctrlState)) + { + m_mastercontrollerreturndelay -= static_cast(Deltatime); + if (m_mastercontrollerreturndelay < 0.f) + { + m_mastercontrollerreturndelay = EU07_CONTROLLER_BASERETURNDELAY; + if (occupied->MainCtrlPos() > occupied->MainCtrlActualPos) + { + occupied->DecMainCtrl(1); + } + else if (occupied->MainCtrlPos() < occupied->MainCtrlActualPos) + { + // Ra 15-01: a to nie miało być tylko cofanie? + occupied->IncMainCtrl(1); + } + } + } + } +} + +// sets the speed shown by the tachometer, its jumps and the ticking of the speed recorder +void TTrain::updateTachometer(double const Deltatime) +{ + // McZapkie: predkosc wyswietlana na tachometrze brana jest z obrotow kol + auto const maxtacho{3.0}; + + double maxSpeed = controlled->Vmax() * 1.05; // zachowanie starej logiki jak nie ma definicji max tarczki + if (occupied->maxTachoSpeed != 0) + { + maxSpeed = occupied->maxTachoSpeed; + } + fTachoVelocity = static_cast(std::min(std::abs(11.31 * controlled->WheelDiameter() * controlled->nrot()), maxSpeed)); + { // skacze osobna zmienna + float ff = simulation::Time.data().wSecond; // skacze co sekunde - pol sekundy + // pomiar, pol sekundy ustawienie + if (ff != fTachoTimer) // jesli w tej sekundzie nie zmienial + { + if (fTachoVelocity >= 5) // jedzie + fTachoVelocityJump = static_cast(fTachoVelocity + (2.0 - LocalRandom(3) + LocalRandom(3)) * 0.5); + else if (fTachoVelocity < 5 && fTachoVelocity > 1) + fTachoVelocityJump = static_cast(Random(0, 4)); // tu ma sie bujac jak wariat i zatrzymac na jakiejs predkosci + // fTachoVelocityJump = 0; // stoi + fTachoTimer = ff; // juz zmienil + } + } + if (fTachoVelocity > 1) // McZapkie-270503: podkrecanie tachometru + { + // szybciej zacznij stukac + fTachoCount = static_cast(std::min(maxtacho, fTachoCount + Deltatime * 3)); + } + else if (fTachoCount > 0) + { + // schodz powoli - niektore haslery to ze 4 sekundy potrafia stukac + fTachoCount = static_cast(std::max(0.0, fTachoCount - Deltatime * 0.66)); + } +} + +// sets the high voltage and the currents shown in the cab, of the controlled vehicle or of the second unit +void TTrain::updateVoltagesAndCurrents() +{ + // Ra 2014-09: napięcia i prądy muszą być ustalone najpierw, bo wysyłane są ewentualnie na PoKeys + if (controlled->EngineType != TEngineType::DieselElectric && controlled->EngineType != TEngineType::ElectricInductionMotor) + { // Ra 2014-09: czy taki rozdzia? ma sens? + fHVoltage = static_cast(std::max(controlled->pantographCircuit.SupplyVoltage(), + controlled->GetTrainsetHighVoltage())); // Winger czy to nie jest zle? + } + // *controlled->Mains); + else + { + fHVoltage = static_cast(controlled->EngineVoltage); + } + if (ShowNextCurrent) + { // jeśli pokazywać drugi człon + if (secondUnit) + { // o ile jest ten drugi + fHCurrent[0] = static_cast(secondUnit->ShowCurrent(0) * 1.05); + fHCurrent[1] = static_cast(secondUnit->ShowCurrent(1) * 1.05); + fHCurrent[2] = static_cast(secondUnit->ShowCurrent(2) * 1.05); + fHCurrent[3] = static_cast(secondUnit->ShowCurrent(3) * 1.05); + } + else + { + fHCurrent[0] = 0.0; // gdy nie ma człona + fHCurrent[1] = 0.0; + fHCurrent[2] = 0.0; + fHCurrent[3] = 0.0; + } + } + else + { // normalne pokazywanie + fHCurrent[0] = static_cast(controlled->ShowCurrent(0)); + fHCurrent[1] = static_cast(controlled->ShowCurrent(1)); + fHCurrent[2] = static_cast(controlled->ShowCurrent(2)); + fHCurrent[3] = static_cast(controlled->ShowCurrent(3)); + } +} + +// clears the states of the units in multiple before they are read again +void TTrain::resetUnitStates() +{ + for (int i = 0; i < 8; i++) + { + bMains[i] = false; + fCntVol[i] = 0.0f; + bPants[i][0] = false; + bPants[i][1] = false; + bFuse[i] = false; + bBatt[i] = false; + bConv[i] = false; + bComp[i][0] = false; + bComp[i][1] = false; + // bComp[i][2] = false; + // bComp[i][3] = false; + bHeat[i] = false; + } + bCompressors.clear(); +} + +// reads the states of the vehicles and the units in multiple, from the cab along the control coupling +void TTrain::updateUnitStates() +{ + bool kier = DynamicObject->DirectionGet() * occupied->CabOccupied() > 0; + TDynamicObject *p = DynamicObject->GetFirstDynamic(occupied->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control); + int in = 0; + fEIMParams[0][6] = 0; + iCarNo = 0; + iPowerNo = 0; + iUnitNo = 1; + + resetUnitStates(); + for (int i = 0; i < 20; i++) + { + if (p) + { + fPress[i][0] = static_cast(p->physics->brakes.cylinderPressure); + fPress[i][1] = static_cast(p->physics->brakePipe.Pressure()); + fPress[i][2] = static_cast(p->physics->mainPipe.Pressure()); + fPress[i][3] = static_cast(p->physics->brakes.controlReservoirPressure); + fPress[i][4] = static_cast(p->physics->brakes.distributor->GetBRP()); + fPress[i][5] = static_cast((p->physics->TotalMass() - p->physics->Mred()) * 0.001); + fPress[i][6] = static_cast(p->physics->brakes.spring.pressure); + bBrakes[i][0] = p->physics->brakes.spring.isActive; + bBrakes[i][1] = p->physics->brakes.spring.shutOff; + bDoors[i][1] = p->physics->Doors.instances[VehicleSide::left].position > 0.f; + bDoors[i][2] = p->physics->Doors.instances[VehicleSide::right].position > 0.f; + bDoors[i][3] = p->physics->Doors.instances[VehicleSide::left].step_position > 0.f; + bDoors[i][4] = p->physics->Doors.instances[VehicleSide::right].step_position > 0.f; + bDoors[i][0] = bDoors[i][1] || bDoors[i][2]; + iDoorNo[i] = p->iAnimType[ANIM_DOORS]; + iUnits[i] = iUnitNo; + cCode[i] = p->physics->TypeName[p->physics->TypeName.length() - 1]; + asCarName[i] = p->name(); + if (p->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && iUnitNo <= 8) + { + bPants[iUnitNo - 1][VehicleEnd::front] = bPants[iUnitNo - 1][VehicleEnd::front] || p->physics->pantographs[VehicleEnd::front].is_active; + bPants[iUnitNo - 1][VehicleEnd::rear] = bPants[iUnitNo - 1][VehicleEnd::rear] || p->physics->pantographs[VehicleEnd::rear].is_active; + } + // TBD, TODO: clean up compressor data arrangement? + if (iUnitNo <= 8) + { + bComp[iUnitNo - 1][0] = bComp[iUnitNo - 1][0] || p->physics->air.compressor.IsAllowed() || p->physics->air.compressor.config.start == start_t::automatic; + } + if (p->physics->air.compressor.config.speed > 0.00001) + { + if (iUnitNo <= 8) + { + bComp[iUnitNo - 1][1] = bComp[iUnitNo - 1][1] || p->physics->air.compressor.IsRunning(); + } + bCompressors.emplace_back(p->physics->air.compressor.IsAllowed() || p->physics->air.compressor.config.start == start_t::automatic, p->physics->air.compressor.IsRunning(), i); + } + bSlip[i] = p->physics->SlippingWheels(); + if (in < 8 && p->physics->inductionMotor.traction.maxPower > 1) + { + fEIMParams[1 + in][0] = static_cast(p->physics->inductionMotor.state.maxForce); + fEIMParams[1 + in][1] = std::max(fEIMParams[1 + in][0], 0.f); + fEIMParams[1 + in][2] = -std::min(fEIMParams[1 + in][0], 0.f); + fEIMParams[1 + in][3] = static_cast(p->physics->inductionMotor.state.maxForce / std::max(p->physics->inductionMotor.state.fullForce, 1.)); + fEIMParams[1 + in][4] = std::max(fEIMParams[1 + in][3], 0.f); + fEIMParams[1 + in][5] = -std::min(fEIMParams[1 + in][3], 0.f); + fEIMParams[1 + in][6] = static_cast(p->physics->inductionMotor.state.fieldCurrent); + fEIMParams[1 + in][7] = static_cast(p->physics->inductionMotor.state.voltage); + fEIMParams[1 + in][8] = static_cast(p->physics->Itot); // p->physics->inductionMotor.state.lineCurrent; + fEIMParams[1 + in][9] = static_cast(p->physics->EngineVoltage); + fEIMParams[0][6] += fEIMParams[1 + in][8]; + bMains[in] = p->physics->lineBreaker.IsClosed(); + fCntVol[in] = static_cast(p->physics->lowVoltage.BatteryVoltage()); + bFuse[in] = p->physics->FuseFlag; + bBatt[in] = p->physics->lowVoltage.IsBatteryOn(); + bConv[in] = p->physics->converter.IsRunning(); + bHeat[in] = p->physics->trainHeating.IsOn(); + // bComp[in][2] = (p->physics->CompressorAllow || (p->physics->CompressorStart == start_t::automatic)); + // bComp[in][3] = (p->physics->CompressorFlag); + in++; + iPowerNo = in; + } + if (in < 8 && (p->physics->EngineType == TEngineType::DieselEngine || p->physics->EngineType == TEngineType::DieselElectric)) + { + fDieselParams[1 + in][0] = static_cast(p->physics->enrot * 60); + fDieselParams[1 + in][1] = static_cast(p->physics->nrot()); + fDieselParams[1 + in][2] = static_cast(p->physics->RList[p->physics->MainCtrlPos()].R); + fDieselParams[1 + in][3] = static_cast(p->physics->diesel.fill); + fDieselParams[1 + in][4] = static_cast(p->physics->RList[p->physics->MainCtrlPos()].Mn); + fDieselParams[1 + in][5] = static_cast(p->physics->diesel.clutchPressure); + fDieselParams[1 + in][6] = p->physics->diesel.heat.Twy; + fDieselParams[1 + in][7] = p->physics->OilPump.pressure; + fDieselParams[1 + in][8] = p->physics->diesel.heat.Ts; + fDieselParams[1 + in][9] = static_cast(p->physics->retarder.fill); + bMains[in] = p->physics->lineBreaker.IsClosed(); + fCntVol[in] = static_cast(p->physics->lowVoltage.BatteryVoltage()); + bFuse[in] = p->physics->FuseFlag; + bBatt[in] = p->physics->lowVoltage.IsBatteryOn(); + bConv[in] = p->physics->converter.IsRunning(); + bHeat[in] = p->physics->trainHeating.IsOn(); + in++; + iPowerNo = in; + } + if ((kier ? p->Next(Coupling::permanent) : p->Prev(Coupling::permanent)) != (kier ? p->Next(Coupling::control) : p->Prev(Coupling::control))) + iUnitNo++; + p = kier ? p->Next(Coupling::control) : p->Prev(Coupling::control); + iCarNo = i + 1; + } + else + { + fPress[i][0] = 0; + fPress[i][1] = 0; + fPress[i][2] = 0; + fPress[i][3] = 0; + fPress[i][4] = 0; + fPress[i][5] = 0; + fPress[i][6] = 0; + bDoors[i][0] = false; + bDoors[i][1] = false; + bDoors[i][2] = false; + bDoors[i][3] = false; + bDoors[i][4] = false; + bBrakes[i][0] = false; + bBrakes[i][1] = false; + bSlip[i] = false; + iUnits[i] = 0; + cCode[i] = 0; //'0'; + asCarName[i] = ""; + } + } + + completeUnitStates(in); +} + +// sets the induction motor values of the whole train and clears the slots of the units after the first in ones +void TTrain::completeUnitStates(int const in) +{ + // if (controlled == occupied) + // fEIMParams[0][3] = controlled->inductionMotor.state.forceDemand; // procent zadany + // else + // fEIMParams[0][3] = + // controlled->inductionMotor.state.forceDemand - occupied->LocalBrakeRatio(); // procent zadany + fEIMParams[0][3] = static_cast(occupied->EimicReal()); + fEIMParams[0][4] = std::max(fEIMParams[0][3], 0.f); + fEIMParams[0][5] = -std::min(fEIMParams[0][3], 0.f); + fEIMParams[0][1] = static_cast(fEIMParams[0][4] * controlled->inductionMotor.state.fullForce); + fEIMParams[0][2] = static_cast(fEIMParams[0][5] * controlled->inductionMotor.state.fullForce); + fEIMParams[0][0] = fEIMParams[0][1] - fEIMParams[0][2]; + fEIMParams[0][7] = 0; + fEIMParams[0][8] = 0; + fEIMParams[0][9] = 0; + + for (int i = in; i < 8; i++) + { + for (int j = 0; j <= 9; j++) + { + fEIMParams[1 + i][j] = 0; + fDieselParams[1 + i][j] = 0; + } + } +} + +// sets the gauges of the PoKeys desk from the state of the cab +void TTrain::updateFeedbackGauges() const +{ +#ifdef _WIN32 + if (Global.iFeedbackMode == 4) + { + // wykonywać tylko gdy wyprowadzone na pulpit + // Ra: sterowanie miernikiem: zbiornik główny + Console::ValueSet(0, occupied->air.MainReservoirPressure()); + // Ra: sterowanie miernikiem: przewód główny + Console::ValueSet(1, occupied->brakePipe.Pressure()); + // Ra: sterowanie miernikiem: cylinder hamulcowy + Console::ValueSet(2, occupied->brakes.cylinderPressure); + // woltomierz wysokiego napięcia + Console::ValueSet(3, fHVoltage); + // Ra: sterowanie miernikiem: drugi amperomierz + Console::ValueSet(4, fHCurrent[2]); + // pierwszy amperomierz; dla EZT prąd całkowity + Console::ValueSet(5, fHCurrent[controlled->TrainType() == train_type::emu ? 0 : 1]); + // Ra: prędkość na pin 43 - wyjście analogowe (to nie jest PWM); skakanie zapewnia mechanika napędu + Console::ValueSet(6, fTachoVelocity); + } +#endif +} + +// trips the converter overload relay when the compressor starts too soon after the converter, in the vehicles driven by hand +void TTrain::updateConverterOverload(double const Deltatime) +{ + //------------------ + // hunter-261211: nadmiarowy przetwornicy i ogrzewania + // Ra 15-01: to musi stąd wylecieć - zależności nie mogą być w kabinie + if (controlled->converter.IsRunning() == true) + { + fConverterTimer += static_cast(Deltatime); + if (controlled->air.compressor.IsRunning() == true && controlled->air.compressor.config.supply == physics::CompressorSupply::converterManual && (controlled->EngineType == TEngineType::ElectricSeriesMotor || controlled->TrainType() == train_type::emu) && + DynamicObject->Controller == Humandriver // hunter-110212: poprawka dla EZT + && DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag()) + { // hunter-091012: poprawka (zmiana warunku z CompressorPower /rozne od 0/ na /rowne 1/) + if (fConverterTimer < fConverterPrzekaznik) + { + controlled->converter.Overload(); + if (controlled->TrainType() != train_type::emu) + controlled->MainSwitch(false, controlled->TrainType() == train_type::emu ? range_t::unit : range_t::local); + } + else if (fConverterTimer >= fConverterPrzekaznik) + { + // changed switch from always true to take into account state of the compressor switch + controlled->CompressorSwitch(controlled->air.compressor.IsAllowed()); + } + } + } + else + fConverterTimer = 0; + //------------------ +} + +// sets the current, the water temperature and the oil pressure gauges of the second unit +void TTrain::updateSecondUnitGauges() +{ + // youBy - prad w drugim czlonie: galaz lub calosc + { + TDynamicObject const *tmp{nullptr}; + if (DynamicObject->NextConnected() && controlled->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() == 1) + tmp = DynamicObject->NextConnected(); + if (DynamicObject->PrevConnected() && controlled->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() == -1) + tmp = DynamicObject->PrevConnected(); + if (tmp && tmp->physics->Power > 0) + { + if (ggI1B.SubModel) + { + ggI1B.UpdateValue(static_cast(tmp->physics->ShowCurrent(1))); + ggI1B.Update(); + } + if (ggI2B.SubModel) + { + ggI2B.UpdateValue(static_cast(tmp->physics->ShowCurrent(2))); + ggI2B.Update(); + } + if (ggI3B.SubModel) + { + ggI3B.UpdateValue(static_cast(tmp->physics->ShowCurrent(3))); + ggI3B.Update(); + } + if (ggItotalB.SubModel) + { + ggItotalB.UpdateValue(static_cast(tmp->physics->ShowCurrent(0))); + ggItotalB.Update(); + } + if (ggWater1TempB.SubModel) + { + ggWater1TempB.UpdateValue(tmp->physics->diesel.heat.temperatura1); + ggWater1TempB.Update(); + } + if (ggOilPressB.SubModel) + { + ggOilPressB.UpdateValue(tmp->physics->OilPump.pressure); + ggOilPressB.Update(); + } + } + } +} + +// sets the hands of the cab clock +void TTrain::updateClock() +{ + // McZapkie-300302: zegarek + if (ggClockMInd.SubModel) + { + ggClockSInd.UpdateValue(simulation::Time.data().wSecond); + ggClockSInd.Update(); + ggClockMInd.UpdateValue(simulation::Time.data().wMinute); + ggClockMInd.Update(); + ggClockHInd.UpdateValue(static_cast(simulation::Time.data().wHour + simulation::Time.data().wMinute / 60.0)); + ggClockHInd.Update(); + } +} + +// sets the gauges of the motor and the low voltage, and the gauges and the ignition key of a diesel engine +void TTrain::updateEngineGauges() +{ + // youBy - napiecie na silnikach + if (ggEngineVoltage.SubModel) + { + if (controlled->brakes.electrodynamic.on) + { + ggEngineVoltage.UpdateValue(static_cast(std::abs(controlled->Im * 5))); + } + else + { + int x; + if (controlled->TrainType() == train_type::et42 && controlled->Imax == controlled->ImaxHi()) + x = 1; + else + x = 2; + if (controlled->RList[controlled->MainCtrlActualPos].Mn > 0 && std::abs(controlled->Im) > 0) + { + ggEngineVoltage.UpdateValue(static_cast(x * (std::abs(controlled->EngineVoltage) - controlled->RList[controlled->MainCtrlActualPos].R * std::abs(controlled->Im)) / + controlled->RList[controlled->MainCtrlActualPos].Mn)); + } + else + { + ggEngineVoltage.UpdateValue(0); + } + } + ggEngineVoltage.Update(); + } + + // Winger 140404 - woltomierz NN + if (ggLVoltage.SubModel) + { + // NOTE: since we don't have functional converter object, we're faking it here by simple check whether converter is on + // TODO: implement object-based circuits and power systems model so we can have this working more properly + ggLVoltage.UpdateValue(static_cast(std::max(occupied->lowVoltage.Is110vAvailable() ? occupied->lowVoltage.config.nominalBatteryVoltage : 0.0, occupied->lowVoltage.Is24vAvailable() ? occupied->lowVoltage.BatteryVoltage() : 0.0))); + ggLVoltage.Update(); + } + + if (controlled->EngineType == TEngineType::DieselElectric) + { // ustawienie zmiennych dla silnika spalinowego + fEngine[1] = static_cast(controlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(controlled->ShowEngineRotation(2)); + } + + else if (controlled->EngineType == TEngineType::DieselEngine) + { // albo dla innego spalinowego + fEngine[1] = static_cast(controlled->ShowEngineRotation(1)); + fEngine[2] = static_cast(controlled->ShowEngineRotation(2)); + fEngine[3] = static_cast(controlled->ShowEngineRotation(3)); + if (ggMainGearStatus.SubModel) + { + if (controlled->lineBreaker.IsClosed()) + ggMainGearStatus.UpdateValue(static_cast(1.1 - std::abs(controlled->diesel.automaticGearShift))); + else + ggMainGearStatus.UpdateValue(0.0); + ggMainGearStatus.Update(); + } + if (ggIgnitionKey.SubModel && ggIgnitionKey.GetDesiredValue() == 0.0) + { + ggIgnitionKey.UpdateValue(controlled->lineBreaker.IsClosed() || controlled->diesel.startupRequested || fMainRelayTimer > 0.f || + (ggMainButton.SubModel != nullptr && ggMainButton.GetDesiredValue() > 0.95) || + (ggMainOnButton.SubModel != nullptr && ggMainOnButton.GetDesiredValue() > 0.95)); + } + ggIgnitionKey.Update(); + } +} + +// sets the lamps of the wheel slip, the compressors, the dynamic brake permit and the active cab +void TTrain::updateBasicLamps() +{ + if (controlled->SlippingWheels()) + { + // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały + double veldiff = (DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax(); + // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza + if (veldiff < -0.01 && std::abs(controlled->Im) > 10.0) + { + btLampkaPoslizg.Turn(true); + } + } + else + { + btLampkaPoslizg.Turn(false); + } + + // Lampka pracujacej sprezacki + if (controlled->air.compressor.IsRunning() || occupied->air.compressor.IsRunning()) + btCompressors.Turn(true); + else + btCompressors.Turn(false); + + // Lampka zezwolenia na hamowanie ED + if (controlled->EpFuse()) + btEDenabled.Turn(true); + else + btEDenabled.Turn(false); + + // Lampka aktywowanej kabiny + if (controlled->CabActive != 0) + { + btCabActived.Turn(true); + } + else + { + btCabActived.Turn(false); + } + + if (controlled->lowVoltage.IsBatteryOn() && controlled->CabActive != 0) + btAKLVents.Turn(true); + else + btAKLVents.Turn(false); +} + +// sets the lamps of the vigilance, the line breaker, the converter, the circuits and the controllers, with the low voltage on +void TTrain::updateCircuitLamps(double const Deltatime) +{ + // McZapkie-141102: SHP i czuwak, TODO: sygnalizacja kabinowa + if (occupied->SecuritySystem.is_vigilance_blinking()) + { + if (fBlinkTimer > fCzuwakBlink) + fBlinkTimer = -fCzuwakBlink; + else + fBlinkTimer += Deltatime; + + btLampkaCzuwaka.Turn(fBlinkTimer > 0); + } + else + { + fBlinkTimer = 0.0; + btLampkaCzuwaka.Turn(false); + } + + btLampkaSHP.Turn(occupied->SecuritySystem.is_cabsignal_blinking()); + btLampkaCzuwakaSHP.Turn(btLampkaSHP.GetValue() || btLampkaCzuwaka.GetValue()); + + btLampkaWylSzybki.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.IsClosed()); + btLampkaWylSzybkiOff.Turn(m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.IsClosed()); + btLampkaMainBreakerReady.Turn(controlled->lineBreaker.IsInitialised() && m_linebreakerstate != linebreaker::state::closing && !controlled->lineBreaker.IsClosed()); + btLampkaMainBreakerBlinkingIfReady.Turn(m_linebreakerstate == linebreaker::state::closing || controlled->lineBreaker.IsClosed() || controlled->lineBreaker.RemainingInitTime() < 0.0 && simulation::Time.data().wMilliseconds > 500); + + btLampkaPrzetw.Turn(occupied->lowVoltage.Is110vAvailable()); + btLampkaPrzetwOff.Turn(!occupied->lowVoltage.Is110vAvailable()); + btLampkaPrzetwAOff.Turn(!controlled->converter.IsRunning()); + btLampkaNadmPrzetw.Turn(Dynamic()->Mechanik ? Dynamic()->Mechanik->ConsistConverterOverloaded() : controlled->converter.IsOverloaded()); + + btLampkaOpory.Turn(controlled->lineContactors.IsClosed() && controlled->ResistorsFlagCheck()); + btLampkaBezoporowa.Turn(controlled->ResistorsFlagCheck() || controlled->MainCtrlActualPos == 0); // do EU04 + btLampkaStyczn.Turn(controlled->LineContactorsLampLit()); // mozna prowadzic rozruch + btLampkaPrzekRozn.Turn(!controlled->protection.GroundHolds() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaNadmSil.Turn(controlled->FuseFlagCheck() && controlled->MainCircuitLampsEnabled()); // relay is off and needs a reset + btLampkaUkrotnienie.Turn(controlled->Couplers[controlled->CabOccupied() == 1 ? VehicleEnd::rear : VehicleEnd::front].CouplingFlag.HasAll(Coupling::control)); + btLampkaHamPosp.Turn(TestFlag(occupied->brakes.distributor->GetBrakeStatus(), 1)); // lampka drugiego stopnia hamowania + // TODO: youBy wyciągnąć flagę wysokiego stopnia + btLampkaNadmWent.Turn(controlled->RventRot < 5.0 && controlled->ResistorsFlagCheck()); // hunter-121211: lampka zanikowo-pradowego wentylatorow + btLampkaWysRozr.Turn(controlled->Imax >= controlled->ImaxHi()); + + btLampkaNapNastHam.Turn(controlled->DirActive != 0); // napiecie na nastawniku hamulcowym + btLampkaSprezarka.Turn(controlled->air.compressor.IsRunning()); // mutopsitka dziala + btLampkaSprezarkaOff.Turn(!controlled->air.compressor.IsRunning()); + btLampkaFuelPumpOff.Turn(!controlled->FuelPump.is_active); + btLampkaOilPump.Turn(controlled->OilPump.is_active); // pre-lubrication pump, goes off once the engine is started + + // boczniki + // Ra: w SU45 boczniki wchodzą na ScndCtrlPos, a nie na ScndCtrlActualPos + // - pokićkał ktoś? + int scp = controlled->RList[controlled->MainCtrlPos()].ScndAct; + scp = scp == 255 ? 0 : scp; // Ra: whatta hella is this? + btLampkaBoczniki.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik1.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 0 || controlled->ScndCtrlActualPos > 0 || scp > 0); + btLampkaBocznik2.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 1 || controlled->ScndCtrlActualPos > 1 || scp > 1); + btLampkaBocznik3.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 2 || controlled->ScndCtrlActualPos > 2 || scp > 2); + btLampkaBocznik4.Turn(!controlled->DelayCtrlFlag() && controlled->ScndCtrlPos() > 3 || controlled->ScndCtrlActualPos > 3 || scp > 3); + + // biegi dla motoraka + btLampkaGear1.Turn(controlled->ScndCtrlActualPos == 1 && controlled->diesel.clutchState > 0); // bieg 1 + btLampkaGear2.Turn(controlled->ScndCtrlActualPos == 2 && controlled->diesel.clutchState > 0); // bieg 2 + btLampkaHydroLockup.Turn(controlled->torqueConverter.lockedUp); // zblokowanie skrzyni z silnikiem + + if (controlled->Signalling() == true) + { + if (occupied->brakes.cylinderPressure >= 1.45f) + { + btLampkaHamowanie1zes.Turn(true); + } + if (controlled->brakes.cylinderPressure < 0.75f) + { + btLampkaHamowanie1zes.Turn(false); + } + } + else + { + btLampkaHamowanie1zes.Turn(false); + } +} + +// sets the lamps of the braking, the radio, the doors, the direction, the lights and the overheating, with the low voltage on +void TTrain::updateTrainLamps() +{ + switch (controlled->TrainType()) + { + // zależnie od typu lokomotywy + case train_type::emu: + { + btLampkaHamienie.Turn(controlled->brakes.cylinderPressure >= 0.2 && controlled->Signalling()); + break; + } + case train_type::et41: + { + // odhamowanie drugiego członu + if (secondUnit) + { + // bo może komuś przyjść do głowy jeżdżenie jednym członem + btLampkaHamienie.Turn(secondUnit->brakes.cylinderPressure < 0.4); + } + break; + } + default: + { + btLampkaHamienie.Turn(occupied->brakes.cylinderPressure >= 0.1 || controlled->brakes.electrodynamic.on); + btLampkaBrakingOff.Turn(occupied->brakes.cylinderPressure < 0.1 && !controlled->brakes.electrodynamic.on); + break; + } + } + // KURS90 + btLampkaMaxSila.Turn(abs(controlled->Im) >= 350); + btLampkaPrzekrMaxSila.Turn(abs(controlled->Im) >= 450); + btLampkaRadio.Turn(occupied->Radio() && occupied->RadioFuse()); + btLampkaRadioMessage.Turn(radio_message_played); + btLampkaRadioStop.Turn(occupied->Radio() && occupied->RadioFuse() && occupied->RadioStopFlag()); + btLampkaHamulecReczny.Turn(occupied->brakes.HandBrakePosition() > 0); + // NBMX wrzesien 2003 - drzwi oraz sygnał odjazdu + if (DynamicObject->Mechanik != nullptr) + { + btLampkaDoorLeft.Turn(DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::left : VehicleSide::right]); + btLampkaDoorRight.Turn(DynamicObject->Mechanik->ConsistDoorsOpen()[cab_to_end() == VehicleEnd::front ? VehicleSide::right : VehicleSide::left]); + } + if (DynamicObject->Mechanik != nullptr) + { + // with DoorClosureSignal in the definition of the cab's vehicle, the door closure signalling (SOD) of the whole + // consist: lit with all doors closed and locked, blinking with them closed but released, dark with a door open. + // without it, the lock of the vehicle's own doors, as before + btLampkaBlokadaDrzwi.Turn(occupied->door_closure_lamp_lit(DynamicObject->Mechanik->ConsistDoorClosure(), simulation::Time.data().wSecond % 2 < 1)); + } + else + { + btLampkaBlokadaDrzwi.Turn(occupied->Doors.is_locked); + } + btLampkaDoorLockOff.Turn(false == occupied->Doors.lock_enabled); + btLampkaDepartureSignal.Turn(controlled->DepartureSignal()); + btLampkaNapNastHam.Turn(controlled->DirActive != 0 && occupied->EpFuse()); // napiecie na nastawniku hamulcowym + + // Wylaczanie lampek kierunku gdy jedziemy + // Feature uruchamiany z fiz z sekcji Ctrl. wpisem HideDirStatusWhenMoving=Yes (domyslnie No) + if (occupied->HideDirStatusWhenMoving && // Czy ta funkcja jest w ogole wlaczona + occupied->Vel > occupied->HideDirStatusSpeed) // Uzaleznienie od predkosci + { + btLampkaForward.Turn(false); + btLampkaBackward.Turn(false); + btLampkaNeutral.Turn(false); + } + else + { + btLampkaForward.Turn(controlled->DirActive > 0); // jazda do przodu + btLampkaBackward.Turn(controlled->DirActive < 0); // jazda do tyłu + btLampkaNeutral.Turn(controlled->DirActive == 0); // kierunek neutral + } + + btLampkaED.Turn(controlled->brakes.electrodynamic.on); // hamulec ED + btLampkaBrakeProfileG.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_G)); + btLampkaBrakeProfileP.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_P)); + btLampkaBrakeProfileR.Turn(TestFlag(occupied->brakes.delaySetting, bdelay_R)); + btLampkaSpringBrakeActive.Turn(occupied->brakes.spring.isActive); + btLampkaSpringBrakeInactive.Turn(!occupied->brakes.spring.isActive); + // light indicators + // NOTE: sides are hardcoded to deal with setups where single cab is equipped with all indicators + btLampkaUpperLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::headlight_upper) != 0); + btLampkaLeftLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::headlight_left) != 0); + btLampkaRightLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::headlight_right) != 0); + btLampkaLeftEndLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::redmarker_left) != 0); + btLampkaRightEndLight.Turn((occupied->LitLights()[VehicleEnd::front] & light::redmarker_right) != 0); + btLampkaRearUpperLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::headlight_upper) != 0); + btLampkaRearLeftLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::headlight_left) != 0); + btLampkaRearRightLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::headlight_right) != 0); + btLampkaRearLeftEndLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::redmarker_left) != 0); + btLampkaRearRightEndLight.Turn((occupied->LitLights()[VehicleEnd::rear] & light::redmarker_right) != 0); + // others + btLampkaMalfunction.Turn(controlled->diesel.heat.PA); + // overheat indicator lamps + btLampkaOilOverheat.Turn(controlled->diesel.heat.oil.is_hot); + btLampkaWaterOverheat.Turn(controlled->diesel.heat.water.is_hot); + btLampkaWaterAuxOverheat.Turn(controlled->diesel.heat.water_aux.is_hot); + btLampkaEngineOverheat.Turn(controlled->diesel.heat.engine_is_hot); + btLampkaMotorBlowers.Turn(controlled->MotorBlowers[VehicleEnd::front].is_active && controlled->MotorBlowers[VehicleEnd::rear].is_active); + btLampkaCoolingFans.Turn(controlled->RventRot > 1.0); + btLampkaLouvresClosed.Turn(controlled->LouvresClosed()); + btLampkaTempomat.Turn(occupied->SpeedCtrlUnit.IsActive); + btLampkaDistanceCounter.Turn(m_distancecounter >= 0.f); + // universal devices state indicators + for (auto idx = 0; idx < btUniversals.size(); ++idx) + { + btUniversals[idx].Turn(ggUniversals[idx].GetValue() > 0.5); + } +} + +// turns off the lamps of the cab when there's no low voltage +void TTrain::turnOffLamps() +{ + // wylaczone + btLampkaCzuwaka.Turn(false); + btLampkaSHP.Turn(false); + btLampkaCzuwakaSHP.Turn(false); + btLampkaWylSzybki.Turn(false); + btLampkaWylSzybkiOff.Turn(false); + btLampkaMainBreakerReady.Turn(false); + btLampkaMainBreakerBlinkingIfReady.Turn(false); + btLampkaWysRozr.Turn(false); + btLampkaOpory.Turn(false); + btLampkaStyczn.Turn(false); + btLampkaPrzekRozn.Turn(false); + btLampkaNadmSil.Turn(false); + btLampkaUkrotnienie.Turn(false); + btLampkaHamPosp.Turn(false); + btLampkaBoczniki.Turn(false); + btLampkaBocznik1.Turn(false); + btLampkaBocznik2.Turn(false); + btLampkaBocznik3.Turn(false); + btLampkaBocznik4.Turn(false); + btLampkaGear1.Turn(false); + btLampkaGear2.Turn(false); + btLampkaHydroLockup.Turn(false); + btLampkaNapNastHam.Turn(false); + btLampkaPrzetw.Turn(false); + btLampkaPrzetwOff.Turn(false); + btLampkaPrzetwAOff.Turn(false); + btLampkaNadmPrzetw.Turn(false); + btLampkaSprezarka.Turn(false); + btLampkaSprezarkaOff.Turn(false); + btLampkaFuelPumpOff.Turn(false); + btLampkaOilPump.Turn(false); + btLampkaBezoporowa.Turn(false); + btLampkaHamowanie1zes.Turn(false); + btLampkaHamienie.Turn(false); + btLampkaBrakingOff.Turn(false); + btLampkaBrakeProfileG.Turn(false); + btLampkaBrakeProfileP.Turn(false); + btLampkaBrakeProfileR.Turn(false); + btLampkaSpringBrakeActive.Turn(false); + btLampkaSpringBrakeInactive.Turn(false); + // overheat indicator lamps off + btLampkaOilOverheat.Turn(false); + btLampkaWaterOverheat.Turn(false); + btLampkaWaterAuxOverheat.Turn(false); + btLampkaEngineOverheat.Turn(false); + btLampkaMaxSila.Turn(false); + btLampkaPrzekrMaxSila.Turn(false); + btLampkaRadio.Turn(false); + btLampkaRadioMessage.Turn(false); + btLampkaRadioStop.Turn(false); + btLampkaHamulecReczny.Turn(false); + btLampkaDoorLeft.Turn(false); + btLampkaDoorRight.Turn(false); + btLampkaBlokadaDrzwi.Turn(false); + btLampkaDoorLockOff.Turn(false); + btLampkaDepartureSignal.Turn(false); + btLampkaNapNastHam.Turn(false); + btLampkaForward.Turn(false); + btLampkaBackward.Turn(false); + btLampkaNeutral.Turn(false); + btLampkaED.Turn(false); + // light indicators + btLampkaUpperLight.Turn(false); + btLampkaLeftLight.Turn(false); + btLampkaRightLight.Turn(false); + btLampkaLeftEndLight.Turn(false); + btLampkaRightEndLight.Turn(false); + btLampkaRearUpperLight.Turn(false); + btLampkaRearLeftLight.Turn(false); + btLampkaRearRightLight.Turn(false); + btLampkaRearLeftEndLight.Turn(false); + btLampkaRearRightEndLight.Turn(false); + // others + btLampkaMalfunction.Turn(false); + btLampkaMotorBlowers.Turn(false); + btLampkaCoolingFans.Turn(false); + btLampkaLouvresClosed.Turn(false); + btLampkaTempomat.Turn(false); + btLampkaDistanceCounter.Turn(false); + // universal devices state indicators + for (auto &universal : btUniversals) + { + universal.Turn(false); + } +} + +// sets the lamps of the second unit, from the vehicle coupled behind the cab with the control coupling +void TTrain::updateSecondUnitLamps(bool const lowvoltagepower) +{ + { // yB - wskazniki drugiego czlonu + TDynamicObject const *tmp{nullptr}; //=controlled->secondUnit; //Ra 2014-07: trzeba to jeszcze wyjąć z kabiny... + // Ra 2014-07: no nie ma potrzeby szukać tego w każdej klatce + if (controlled->Couplers[1].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() > 0) + tmp = DynamicObject->NextConnected(); + if (controlled->Couplers[0].CouplingFlag.HasAll(Coupling::control) && occupied->CabOccupied() < 0) + tmp = DynamicObject->PrevConnected(); + + if (tmp) + { + if (lowvoltagepower) + { + + auto const *physics{tmp->physics}; + + btLampkaWylSzybkiB.Turn(physics->lineBreaker.IsClosed()); + btLampkaWylSzybkiBOff.Turn(false == physics->lineBreaker.IsClosed() + /*&& ( physics->MainsInitTimeCountdown <= 0.0 )*/ + /*&& ( fHVoltage != 0.0 )*/); + + btLampkaOporyB.Turn(physics->ResistorsFlagCheck()); + btLampkaBezoporowaB.Turn(true == physics->ResistorsFlagCheck() || physics->MainCtrlActualPos == 0); // do EU04 + + btLampkaStycznB.Turn(physics->LineContactorsLampLit()); // mozna prowadzic rozruch + // hunter-271211: sygnalizacja poslizgu w pierwszym pojezdzie, gdy wystapi w drugim + if (physics->SlippingWheels()) + { + // Ra 2014-12: lokomotywy 181/182 dostają SlippingWheels po zahamowaniu powyżej 2.85 bara i buczały + auto const veldiff{(DynamicObject->GetVelocity() - fTachoVelocity) / controlled->Vmax()}; + if (veldiff < -0.01) + { + // 1% Vmax rezerwy, żeby 181/182 nie buczały po zahamowaniu, ale to proteza + auto const lightstate{std::abs(physics->Im) > 10.0}; + btLampkaPoslizg.Turn(btLampkaPoslizg.GetValue() || lightstate); + } + } + + btLampkaSprezarkaB.Turn(physics->air.compressor.IsRunning()); // mutopsitka dziala + btLampkaSprezarkaBOff.Turn(false == physics->air.compressor.IsRunning()); + if (controlled->Signalling() == true) + { + if (physics->brakes.cylinderPressure >= 1.45f) + { + btLampkaHamowanie2zes.Turn(true); + } + if (physics->brakes.cylinderPressure < 0.75f) + { + btLampkaHamowanie2zes.Turn(false); + } + } + else + { + btLampkaHamowanie2zes.Turn(false); + } + btLampkaNadmPrzetwB.Turn(physics->converter.IsOverloaded()); // nadmiarowy przetwornicy? + btLampkaPrzetwB.Turn(physics->converter.IsRunning()); // zalaczenie przetwornicy + btLampkaPrzetwBOff.Turn(false == physics->converter.IsRunning()); + btLampkaHVoltageB.Turn(physics->protection.UndervoltageHolds() && physics->protection.OvervoltageHolds()); + btLampkaMalfunctionB.Turn(physics->diesel.heat.PA); + // motor fuse indicator turns on if the fuse was blown in any unit under control + if (physics->lineBreaker.IsClosed()) + { + btLampkaNadmSil.Turn(btLampkaNadmSil.GetValue() || physics->FuseFlagCheck()); + } + } + else // wylaczone + { + btLampkaWylSzybkiB.Turn(false); + btLampkaWylSzybkiBOff.Turn(false); + btLampkaOporyB.Turn(false); + btLampkaStycznB.Turn(false); + btLampkaSprezarkaB.Turn(false); + btLampkaSprezarkaBOff.Turn(false); + btLampkaBezoporowaB.Turn(false); + btLampkaHamowanie2zes.Turn(false); + btLampkaNadmPrzetwB.Turn(false); + btLampkaPrzetwB.Turn(false); + btLampkaPrzetwBOff.Turn(false); + btLampkaHVoltageB.Turn(false); + btLampkaMalfunctionB.Turn(false); + } + } + } +} + +// sets the master and the secondary controllers, the speed control buttons and the reverser +void TTrain::updateMasterControllers(bool const lowvoltagepower) +{ + // McZapkie-080602: obroty (albo translacje) regulatorow + if (ggJointCtrl.SubModel != nullptr) + { + // joint master controller moves forward to adjust power and backward to adjust brakes + auto const brakerangemultiplier{/* NOTE: scaling disabled as it was conflicting with associating sounds with control positions + ( controlled->CoupledCtrl ? + controlled->MainCtrlPosNo + controlled->ScndCtrlPosNo() : + controlled->MainCtrlPosNo ) + / static_cast(LocalBrakePosNo) + */ + 1}; + // when SplitEDPneumaticBrake is active the negative range of the joint controller + // represents the dedicated dynamic-brake lever (DBPN steps), not the pneumatic local brake + auto const negativePart{controlled->brakes.electrodynamic.splitFromPneumatic ? + (controlled->brakes.electrodynamic.controllerPosition > 0.0 ? controlled->brakes.electrodynamic.controllerPosition * controlled->brakes.electrodynamic.controllerPositions * -1 * brakerangemultiplier : 0.0) : + occupied->brakes.IndependentPosition() > 0.0 ? occupied->brakes.IndependentPosition() * LocalBrakePosNo * -1 * brakerangemultiplier : + 0.0}; + ggJointCtrl.UpdateValue(negativePart < 0.0 ? static_cast(negativePart) : + controlled->CoupledCtrl ? static_cast(double(controlled->MainCtrlPos() + controlled->ScndCtrlPos())) : + static_cast(double(controlled->MainCtrlPos())), + dsbNastawnikJazdy); + ggJointCtrl.Update(); + } + if (ggMainCtrl.SubModel != nullptr) + { + +#ifdef _WIN32 + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() // nie blokujemy AI + && Global.iFeedbackMode == 4 && Global.fCalibrateIn[2][1] != 0.0) + { + + set_master_controller(Console::AnalogCalibrateGet(2) * occupied->MainCtrlPosNo); + occupied->SetEimicAnalog(Console::AnalogCalibrateGet(2)); + } +#endif + + if (controlled->CoupledCtrl) + { + ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos() + controlled->ScndCtrlPos())), dsbNastawnikJazdy); + } + else + { + ggMainCtrl.UpdateValue(static_cast(double(controlled->MainCtrlPos())), dsbNastawnikJazdy); + } + ggMainCtrl.Update(); + } + if (ggMainCtrlAct.SubModel != nullptr) + { + ggMainCtrlAct.UpdateValue(main_ctrl_act::position(*controlled, ggMainCtrlAct.has_scaletable())); + ggMainCtrlAct.Update(); + } + if (ggScndCtrl.SubModel != nullptr) + { + // Ra: od byte odejmowane boolean i konwertowane potem na double? + if (false == ggScndCtrl.is_push()) + { + ggScndCtrl.UpdateValue(static_cast(double(controlled->ScndCtrlPos() - (controlled->TrainType() == train_type::et42 && controlled->brakes.electrodynamic.on))), dsbNastawnikBocz); + } + ggScndCtrl.Update(); + } + if (ggScndCtrlButton.SubModel != nullptr) + { + if (ggScndCtrlButton.is_toggle()) + { + ggScndCtrlButton.UpdateValue(controlled->IsSpeedCtrlEngaged() ? 1.f : 0.f, dsbSwitch); + } + ggScndCtrlButton.Update(lowvoltagepower); + } + if (ggScndCtrlOffButton.SubModel != nullptr) + { + ggScndCtrlOffButton.Update(lowvoltagepower); + } + if (ggDistanceCounterButton.SubModel != nullptr) + { + ggDistanceCounterButton.Update(); + } + if (ggDirKey.SubModel != nullptr) + { + if (controlled->TrainType() != train_type::emu) + { + ggDirKey.UpdateValue(static_cast(double(controlled->DirActive)), dsbReverserKey); + } + else + { + ggDirKey.UpdateValue(static_cast(double(controlled->DirActive) + double(controlled->Imin() == controlled->IminHi)), dsbReverserKey); + } + ggDirKey.Update(); + } +} + +// sets the train brake and the local brake handles, from the PoKeys desk when it drives them +void TTrain::updateBrakeControllers() +{ + if (ggBrakeCtrl.SubModel != nullptr) + { +#ifdef _WIN32 + if (DynamicObject->Mechanik ? (DynamicObject->Mechanik->AIControllFlag() ? false : Global.iFeedbackMode == 4 /*|| (Global.bMWDmasterEnable && Global.bMWDBreakEnable)*/) : + false && Global.fCalibrateIn[0][1] != 0.0) // nie blokujemy AI + { // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba + // Firleju: dlatego kasujemy i zastepujemy funkcją w Console + if (occupied->brakes.config.driverValveType == TBrakeHandle::FV4a) + { + double b = Console::AnalogCalibrateGet(0); + b = b * 8.0 - 2.0; + b = safe_clamp(b, -2.0, (double)occupied->brakes.config.handlePositions); // przycięcie zmiennej do granic + ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia + occupied->BrakeLevelSet(b); + } + else if (occupied->brakes.config.driverValveType == TBrakeHandle::FVel6) // może można usunąć ograniczenie do FV4a i FVel6? + { + double b = Console::AnalogCalibrateGet(0); + b = b * 7.0 - 1.0; + b = safe_clamp(b, -1.0, (double)occupied->brakes.config.handlePositions); // przycięcie zmiennej do granic + ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia + occupied->BrakeLevelSet(b); + } + else + { + double b = Console::AnalogCalibrateGet(0); + b = b * (occupied->brakes.driverValve->GetPos(bh_MAX) - occupied->brakes.driverValve->GetPos(bh_MIN)) + occupied->brakes.driverValve->GetPos(bh_MIN); + b = safe_clamp(b, occupied->brakes.driverValve->GetPos(bh_MIN), occupied->brakes.driverValve->GetPos(bh_MAX)); // przycięcie zmiennej do granic + ggBrakeCtrl.UpdateValue(b); // przesów bez zaokrąglenia + occupied->BrakeLevelSet(b); + } + } + else +#endif + { + // else //standardowa prodedura z kranem powiązanym z klawiaturą + // ggBrakeCtrl.UpdateValue(double(occupied->BrakeCtrlPos)); + ggBrakeCtrl.UpdateValue(static_cast(occupied->brakes.HandlePositionSmooth())); + ggBrakeCtrl.Update(); + } + } + + if (ggLocalBrake.SubModel != nullptr) + { +#ifdef _WIN32 + if (DynamicObject->Mechanik != nullptr && false == DynamicObject->Mechanik->AIControllFlag() // nie blokujemy AI + && occupied->brakes.config.independentValveType == TBrakeHandle::FD1 && Global.iFeedbackMode == 4 && Global.fCalibrateIn[0][1] != 0.0) + { + // Ra: nie najlepsze miejsce, ale na początek gdzieś to dać trzeba + // Firleju: dlatego kasujemy i zastepujemy funkcją w Console + auto const b = std::clamp(Console::AnalogCalibrateGet(1), 0.f, 1.f); + occupied->brakes.SetIndependentPosition(b); + ggLocalBrake.UpdateValue(b * LocalBrakePosNo); + } + else +#endif + { + // standardowa prodedura z kranem powiązanym z klawiaturą + ggLocalBrake.UpdateValue(static_cast(occupied->brakes.IndependentPosition() * LocalBrakePosNo)); + } + ggLocalBrake.Update(); + } +} + +// updates the direction, the brake setting, the door and the compressor switches and buttons +void TTrain::updateCabSwitches(bool const lowvoltagepower) +{ + ggDirForwardButton.Update(lowvoltagepower); + ggDirNeutralButton.Update(lowvoltagepower); + ggDirBackwardButton.Update(lowvoltagepower); + ggAlarmChain.Update(); + ggBrakeProfileCtrl.Update(); + ggBrakeProfileG.Update(); + ggBrakeProfileR.Update(); + ggBrakeOperationModeCtrl.Update(); + ggWiperSw.Update(); + ggMaxCurrentCtrl.UpdateValue(true == controlled->ShuntModeAllow ? (true == controlled->ShuntMode ? 1.f : 0.f) : controlled->MotorOverloadRelayHighThreshold() ? 1.f : 0.f); + ggMaxCurrentCtrl.Update(); + ggAutoRelayButton.UpdateValue(occupied->AutoRelayFlag() ? 1.f : 0.f); + ggAutoRelayButton.Update(); + // NBMX wrzesien 2003 - drzwi + ggDoorLeftPermitButton.Update(lowvoltagepower); + ggDoorRightPermitButton.Update(lowvoltagepower); + ggDoorPermitPresetButton.Update(lowvoltagepower); + ggDoorLeftButton.Update(lowvoltagepower); + ggDoorRightButton.Update(lowvoltagepower); + ggDoorLeftOnButton.Update(lowvoltagepower); + ggDoorRightOnButton.Update(lowvoltagepower); + ggDoorLeftOffButton.Update(lowvoltagepower); + ggDoorRightOffButton.Update(lowvoltagepower); + ggDoorAllOnButton.Update(lowvoltagepower); + ggDoorAllOffButton.Update(lowvoltagepower); + ggDoorSignallingButton.Update(lowvoltagepower); + ggDoorStepButton.Update(lowvoltagepower); + // NBMX dzwignia sprezarki + ggCompressorButton.Update(); + ggCompressorLocalButton.Update(); + ggCompressorListButton.Update(); +} + +// sets the train heating lamp and the instrument, the dashboard and the timetable lights +void TTrain::updateHeatingAndInstrumentLights() +{ + //--------- + // hunter-080812: poprawka na ogrzewanie w elektrykach - usuniete uzaleznienie od przetwornicy + if (controlled->trainHeating.IsOn() == true && controlled->converter.IsOverloaded() == false) + btLampkaOgrzewanieSkladu.Turn(true); + else + btLampkaOgrzewanieSkladu.Turn(false); + + //---------- + + // lights + auto const lightpower{(InstrumentLightType == 0 ? occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable() : + InstrumentLightType == 1 ? controlled->lineBreaker.IsClosed() : + InstrumentLightType == 2 ? occupied->lowVoltage.Is110vAvailable() : + InstrumentLightType == 3 ? occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable() : + InstrumentLightType == 4 ? occupied->lowVoltage.Is24vAvailable() || occupied->lowVoltage.Is110vAvailable() : + false)}; + InstrumentLightActive = InstrumentLightType == 3 ? true : // TODO: link the light state with the state of the master key + InstrumentLightType == 4 ? occupied->LitLights()[VehicleEnd::front] != 0 || occupied->LitLights()[VehicleEnd::rear] != 0 : + InstrumentLightActive; + btInstrumentLight.Turn(InstrumentLightActive && lightpower); + btDashboardLight.Turn(DashboardLightActive && lightpower); + btTimetableLight.Turn(TimetableLightActive && lightpower); +} + +// updates the buttons of the line breaker, the brakes, the radio, the pantographs and the lights +void TTrain::updateButtons() +{ + // guziki: + ggMainOffButton.Update(); + ggMainOnButton.Update(); + ggMainButton.Update(); + for (auto &remotelinebreaker : m_remotelinebreakers) + { + remotelinebreaker.main_switch.Update(); + remotelinebreaker.on_button.Update(); + remotelinebreaker.off_button.Update(); + } + ggSecurityResetButton.Update(); + ggSHPResetButton.Update(); + ggReleaserButton.Update(); + ggSpringBrakeOnButton.Update(); + ggSpringBrakeOffButton.Update(); + ggUniveralBrakeButton1.Update(); + ggUniveralBrakeButton2.Update(); + ggUniveralBrakeButton3.Update(); + ggEPFuseButton.Update(); + ggAntiSlipButton.Update(); + ggSandButton.Update(); + ggAutoSandButton.Update(); + ggFuseButton.Update(); + ggConverterFuseButton.Update(); + ggStLinOffButton.Update(); + ggRadioChannelSelector.Update(); + ggRadioChannelPrevious.Update(); + ggRadioChannelNext.Update(); + ggRadioStop.Update(); + ggRadioTest.Update(); + ggRadioCall1.Update(); + ggRadioCall3.Update(); + ggRadioVolumeSelector.Update(); + ggRadioVolumePrevious.Update(); + ggRadioVolumeNext.Update(); + ggRadioOnButton.Update(); + ggRadioOffButton.Update(); + ggRadioFuseOnButton.Update(); + ggRadioFuseOffButton.Update(); + ggDepartureSignalButton.Update(); + /* + ggPantFrontButton.Update(); + ggPantRearButton.Update(); + ggPantFrontButtonOff.Update(); + ggPantRearButtonOff.Update(); + */ + ggPantAllDownButton.Update(); + ggPantSelectedDownButton.Update(); + ggPantSelectedButton.Update(); + ggPantValvesButton.Update(); + ggPantCompressorButton.Update(); + ggPantCompressorValve.Update(); + + ggPantValvesOff.Update(); + ggPantValvesUpdate.Update(); + + ggLightsButton.Update(); + ggUpperLightButton.Update(); + ggLeftLightButton.Update(); + ggRightLightButton.Update(); + ggLeftEndLightButton.Update(); + ggRightEndLightButton.Update(); + ggModernLightDimSw.Update(); + // hunter-230112 + ggRearUpperLightButton.Update(); + ggRearLeftLightButton.Update(); + ggRearRightLightButton.Update(); + ggRearLeftEndLightButton.Update(); + ggRearRightEndLightButton.Update(); + ggDimHeadlightsButton.Update(); + ggDimHeadlightsButton.Update(); +} + +// updates the buttons of the converter, the horns, the speed control, the universal devices, the cab and the engine auxiliaries +void TTrain::updateAuxiliaryButtons(bool const lowvoltagepower) +{ + //------------ + // the converter switches follow the vehicle when something else flips them (the AI driver, the other cab, + // the pressure switch of an EMU), not only when the cab is entered (set_cab_controls()) + if (ggConverterButton.SubModel != nullptr && occupied->converter.config.switchType != "impulse" && occupied->converter.config.start == start_t::manual) + { + ggConverterButton.UpdateValue(occupied->converter.IsAllowed() ? 1.f : 0.f, dsbSwitch); + } + ggConverterButton.Update(); + if (ggConverterLocalButton.SubModel != nullptr) + { + ggConverterLocalButton.UpdateValue(occupied->converter.LocalSwitchOn() ? 1.f : 0.f, dsbSwitch); + } + ggConverterLocalButton.Update(); + ggConverterOffButton.Update(); + ggTrainHeatingButton.Update(); + ggSignallingButton.Update(); + ggNextCurrentButton.Update(); + ggHornButton.Update(); + ggHornLowButton.Update(); + ggHornHighButton.Update(); + ggWhistleButton.Update(); + if (DynamicObject->Mechanik != nullptr) + { + ggHelperButton.UpdateValue(static_cast(DynamicObject->Mechanik->Helper())); + } + ggHelperButton.Update(); + + ggSpeedControlIncreaseButton.Update(lowvoltagepower); + ggSpeedControlDecreaseButton.Update(lowvoltagepower); + ggSpeedControlPowerIncreaseButton.Update(lowvoltagepower); + ggSpeedControlPowerDecreaseButton.Update(lowvoltagepower); + for (auto &speedctrlbutton : ggSpeedCtrlButtons) + { + speedctrlbutton.Update(lowvoltagepower); + } + for (auto &universal : ggUniversals) + { + universal.Update(); + } + for (auto &item : ggInverterEnableButtons) + { + item.Update(); + } + for (auto &item : ggInverterDisableButtons) + { + item.Update(); + } + for (auto &item : ggInverterToggleButtons) + { + item.Update(); + } + for (auto &relayresetbutton : ggRelayResetButtons) + { + relayresetbutton.Update(); + } + // hunter-091012 + ggInstrumentLightButton.Update(); + ggDashboardLightButton.Update(); + ggTimetableLightButton.Update(); + ggCabLightDimButton.Update(); + ggCompartmentLightsButton.Update(); + ggCompartmentLightsOnButton.Update(); + ggCompartmentLightsOffButton.Update(); + ggBatteryButton.Update(); + ggBatteryOnButton.Update(); + ggBatteryOffButton.Update(); + if (ggCabActivationButton.SubModel != nullptr && ggCabActivationButton.type() != TGaugeType::push) + { + ggCabActivationButton.UpdateValue(occupied->IsCabMaster() ? 1.0 : 0.0); + } + ggCabActivationButton.Update(); + + ggWaterPumpBreakerButton.Update(); + ggWaterPumpButton.Update(); + ggWaterHeaterBreakerButton.Update(); + ggWaterHeaterButton.Update(); + ggWaterCircuitsLinkButton.Update(); + ggFuelPumpButton.Update(); + ggOilPumpButton.Update(); + ggOilFuelPumpButton.Update(); + ggTractionModeSwitch.Update(); + ggGensetButton.Update(); + ggMotorBlowersFrontButton.Update(); + ggMotorBlowersRearButton.Update(); + ggMotorBlowersAllOffButton.Update(); +} + +// sets the light level of each cab and of the interior of the vehicle +void TTrain::updateCabLightLevels() +{ + // calculate current level of interior illumination + { + // TODO: organize it along with rest of train update in a more sensible arrangement + // Ra: uzeleżnic od napięcia w obwodzie sterowania + // hunter-091012: uzaleznienie jasnosci od przetwornicy + int cabidx{0}; + for (auto &cab : Cabine) + { + + auto const cablightlevel = (cab.bLight == false ? 0.f : cab.bLightDim == true ? 0.4f : 1.f) * (occupied->lowVoltage.Is110vAvailable() ? 1.f : 0.5f); + + if (cab.LightLevel != cablightlevel) + { + cab.LightLevel = cablightlevel; + DynamicObject->set_cab_lights(cabidx, cab.LightLevel); + } + if (cabidx == iCabn) + { + DynamicObject->InteriorLightLevel = cablightlevel; + } + + ++cabidx; + } + } +} + +void TTrain::UpdateDirectionRelays() +{ + if (occupied->DirActive < 0 && occupied->lowVoltage.Is24vAvailable()) // wstecz + Dynamic()->sDirectionRelayR.play(); + if (occupied->DirActive == 0 && occupied->lowVoltage.Is24vAvailable()) // neutral + Dynamic()->sDirectionRelayN.play(); + if (occupied->DirActive > 0 && occupied->lowVoltage.Is24vAvailable()) // przod + Dynamic()->sDirectionRelayD.play(); +} + +void TTrain::SetupDirectionRelays() +{ + if (occupied->lowVoltage.Is24vAvailable()) + { + if (occupied->DirActive < 0 && occupied->lowVoltage.Is24vAvailable()) // wstecz + Dynamic()->sDirectionRelayR.play(); + if (occupied->DirActive > 0 && occupied->lowVoltage.Is24vAvailable()) // przod + Dynamic()->sDirectionRelayD.play(); + } + else if (occupied->DirActive != 0) // neutral + Dynamic()->sDirectionRelayN.play(); +} diff --git a/vehicle/cameraviews.cpp b/vehicle/cameraviews.cpp new file mode 100644 index 000000000..ef0975088 --- /dev/null +++ b/vehicle/cameraviews.cpp @@ -0,0 +1,281 @@ +/* +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/cameraviews.h" + +#include +#include +#include + +namespace cameraviews { + +namespace { + +glm::dvec3 const world_up{0.0, 1.0, 0.0}; + +// radians per second of the left and right keys, and of the page keys, for a key held +double constexpr orbit_turn_rate{1.2}; +double constexpr orbit_climb_rate{0.8}; +// the radius grows (or shrinks) e times in a second of a key held +double constexpr orbit_zoom_rate{1.0}; +// the height of the shunting view grows (or shrinks) e times in a second of a key held +double constexpr topdown_zoom_rate{0.8}; +// metres per second of the shunting view moved along and across, for each metre of its height +double constexpr topdown_pan_rate{0.6}; +// metres per second of the coupling view moved closer, further, up and down +double constexpr coupler_move_rate{3.0}; +// metres the coupling view stands back from the coupler, towards its vehicle +double constexpr coupler_step_back{2.0}; +// the share of the gap to the vehicle coming closer the coupling view keeps from the side of the train +double constexpr coupler_gap_share{0.7}; + +double flat_distance(glm::dvec3 const &A, glm::dvec3 const &B) { + return std::hypot(A.x - B.x, A.z - B.z); +} + +} // namespace + +glm::dvec3 flat_front(glm::dvec3 const &Front) { + glm::dvec3 const flat{Front.x, 0.0, Front.z}; + auto const length{glm::length(flat)}; + if (length < 1e-6) { + return {0.0, 0.0, -1.0}; + } + return flat / length; +} + +glm::dvec3 flat_left(glm::dvec3 const &Flatfront) { + return glm::cross(world_up, Flatfront); +} + +int step_index(int const Index, int const Count, int const Step) { + if (Count <= 0) { + return 0; + } + return std::clamp(Index + Step, 0, Count - 1); +} + +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction) { + if (Positions.empty()) { + return {-1, -1}; + } + auto const way{flat_front(Direction)}; + auto const along{[&way](glm::dvec3 const &Position) { return glm::dot(Position, way); }}; + auto const [tail, head]{std::ranges::minmax_element(Positions, {}, along)}; + return {static_cast(head - Positions.begin()), static_cast(tail - Positions.begin())}; +} + +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int const Cab) { + auto const cab{Cab < 0 ? -1 : 1}; + auto const aligned{glm::dot(flat_front(Front), flat_front(Drivenfront)) < 0.0 ? -1 : 1}; + return cab * aligned; +} + +// orbit + +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle) { + return Vehicle.position + world_up * (0.4 * Vehicle.height); +} + +double orbit_min_radius(vehicle_pose const &Vehicle) { + return 0.5 * std::hypot(Vehicle.length, Vehicle.width) + 1.0; +} + +orbit orbit_start(vehicle_pose const &Vehicle) { + orbit start; + start.azimuth = 0.6; + start.elevation = 0.25; + start.radius = std::max(orbit_min_radius(Vehicle), Vehicle.length + 5.0); + return orbit_clamped(start, Vehicle); +} + +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double const Radius) { + auto const centre{0.4 * Vehicle.height}; + auto const sine{std::clamp((rail_clearance - centre) / std::max(Radius, 1e-3), -1.0, 1.0)}; + return std::max(orbit_min_elevation, std::asin(sine)); +} + +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle) { + if (Orbit.radius <= 0.0) { + Orbit.radius = orbit_start(Vehicle).radius; + } + Orbit.radius = std::clamp(Orbit.radius, orbit_min_radius(Vehicle), std::max(orbit_min_radius(Vehicle), orbit_max_radius)); + Orbit.elevation = std::clamp(Orbit.elevation, orbit_lowest_elevation(Vehicle, Orbit.radius), orbit_max_elevation); + Orbit.azimuth = std::remainder(Orbit.azimuth, 2.0 * std::numbers::pi); + return Orbit; +} + +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double const Seconds, vehicle_pose const &Vehicle) { + Orbit = orbit_clamped(Orbit, Vehicle); + // the left key takes the camera to the left around the vehicle, as a step to the left would while looking at it: + // clockwise seen from above. so does the mouse moved to the right, which turns the view to the right + Orbit.azimuth += Keys.x * orbit_turn_rate * Seconds + Turn.y; + // the mouse moved down looks down at the vehicle, from higher up + Orbit.elevation += Keys.y * orbit_climb_rate * Seconds - Turn.x; + // the up arrow (a negative z) brings the camera closer + Orbit.radius *= std::exp(Keys.z * orbit_zoom_rate * Seconds); + return orbit_clamped(Orbit, Vehicle); +} + +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle) { + auto const front{flat_front(Vehicle.front)}; + auto const left{flat_left(front)}; + auto const around{std::cos(Orbit.azimuth) * front + std::sin(Orbit.azimuth) * left}; + auto const way{std::cos(Orbit.elevation) * around + std::sin(Orbit.elevation) * world_up}; + placement place; + place.target = orbit_centre(Vehicle); + place.eye = place.target + Orbit.radius * way; + place.up = world_up; + return place; +} + +// shunting view + +double topdown_min_height(vehicle_pose const &Vehicle) { + return Vehicle.height + 3.0; +} + +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double const Alonglimit) { + auto const lowest{topdown_min_height(Vehicle)}; + if (View.height <= 0.0) { + View.height = 1.5 * Vehicle.length; + } + View.height = std::clamp(View.height, lowest, std::max(lowest, topdown_max_height)); + auto const along{std::max(0.0, Alonglimit)}; + View.along = std::clamp(View.along, -along, along); + View.across = std::clamp(View.across, -topdown_max_across, topdown_max_across); + return View; +} + +topdown topdown_moved(topdown View, move_keys const &Keys, double const Seconds, vehicle_pose const &Vehicle, double const Alonglimit) { + View = topdown_clamped(View, Vehicle, Alonglimit); + auto const pan{View.height * topdown_pan_rate * Seconds}; + // the up arrow (a negative z) moves the view up the screen, the way the user drives + View.along -= Keys.z * pan; + View.across += Keys.x * pan; + View.height *= std::exp(Keys.y * topdown_zoom_rate * Seconds); + return topdown_clamped(View, Vehicle, Alonglimit); +} + +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int const Facing) { + auto const up{flat_front(Vehicle.front) * (Facing < 0 ? -1.0 : 1.0)}; + // looking down with the screen up the way the user drives, the right of the screen is the right of that way + auto const right{-flat_left(up)}; + placement place; + auto const ground{Vehicle.position + up * View.along + right * View.across}; + place.target = ground; + place.eye = ground + world_up * View.height; + place.up = up; + return place; +} + +// coupling view + +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double const Seconds) { + if (Keys.x < 0.0) { + View.side = 1.0; + } + else if (Keys.x > 0.0) { + View.side = -1.0; + } + View.distance = std::clamp(View.distance + Keys.z * coupler_move_rate * Seconds, coupler_min_distance, coupler_max_distance); + View.height = std::clamp(View.height + Keys.y * coupler_move_rate * Seconds, coupler_min_height, coupler_max_height); + return View; +} + +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other) { + auto const outward{flat_front(Coupler.outward)}; + auto const aside{flat_left(outward) * (View.side < 0.0 ? -1.0 : 1.0)}; + auto const buffers{Coupler.position + world_up * buffer_height}; + auto distance{View.distance}; + placement place; + if (Other != nullptr) { + auto const otherbuffers{*Other + world_up * buffer_height}; + distance = std::max(distance, coupler_gap_share * flat_distance(Coupler.position, *Other)); + place.target = 0.5 * (buffers + otherbuffers); + } + else { + place.target = buffers + outward; + } + distance = std::min(distance, coupler_max_distance); + place.eye = buffers - outward * coupler_step_back + aside * (0.5 * Coupler.width + distance) + world_up * View.height; + place.up = world_up; + return place; +} + +int first_coupling(double const Frontgap, double const Reargap, int const Count) { + auto const watched{[](double const Gap) { return Gap >= 0.0 && Gap <= coupler_watch_range; }}; + auto const front{watched(Frontgap)}; + auto const rear{watched(Reargap)}; + if (rear && (false == front || Reargap < Frontgap)) { + return std::max(Count, 0); + } + return 0; +} + +// trackside view + +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double const Curvature, double const Distance) { + auto const way{flat_front(Direction)}; + if (std::abs(Curvature) < 1e-6) { + return {Start + way * Distance, way}; + } + auto const left{flat_left(way)}; + auto const angle{Curvature * Distance}; + auto const point{Start + way * (std::sin(angle) / Curvature) + left * ((1.0 - std::cos(angle)) / Curvature)}; + auto const heading{way * std::cos(angle) + left * std::sin(angle)}; + return {point, heading}; +} + +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb) { + auto const distance{flat_distance(Positiona, Positionb)}; + if (distance < 1.0) { + return 0.0; + } + auto const ahead{flat_front(Directiona)}; + auto const behind{flat_front(Directionb)}; + // the vehicle ahead turned to the left of the one behind it: a turn about the up axis, anticlockwise from above + auto const angle{std::atan2(glm::cross(behind, ahead).y, glm::dot(behind, ahead))}; + return angle / distance; +} + +bool trackside_expired(trackside const &View, train_motion const &Train) { + if (false == View.placed) { + return true; + } + auto const way{flat_front(Train.direction)}; + auto const offset{View.spot - Train.tail}; + auto const passed{glm::dot(glm::dvec3{offset.x, 0.0, offset.z}, way) < -trackside_passed}; + return passed || flat_distance(View.spot, Train.head) > trackside_max_distance; +} + +trackside trackside_next(trackside const &View, train_motion const &Train) { + auto lead{std::clamp(Train.speed * trackside_lead_time, trackside_min_lead, trackside_max_lead)}; + // along a sharp curve the line comes round: the spot stays within a quarter of the circle + if (auto const quarter{0.5 * std::numbers::pi}; std::abs(Train.curvature) * lead > quarter) { + lead = quarter / std::abs(Train.curvature); + } + auto const [point, heading]{along_arc(Train.head, Train.direction, Train.curvature, lead)}; + trackside next; + next.side = View.placed ? -View.side : View.side; + next.spot = point + flat_left(heading) * (next.side * (0.5 * Train.width + trackside_distance)) + world_up * trackside_eye_height; + next.placed = true; + return next; +} + +placement trackside_placement(trackside const &View, glm::dvec3 const &Target) { + placement place; + place.eye = View.spot; + place.target = Target; + place.up = world_up; + return place; +} + +} // namespace cameraviews diff --git a/vehicle/cameraviews.h b/vehicle/cameraviews.h new file mode 100644 index 000000000..a23d09e55 --- /dev/null +++ b/vehicle/cameraviews.h @@ -0,0 +1,182 @@ +/* +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 + +#include +#include +#include + +// The outside views of the user's train that go with one of its vehicles (eu07/maszyna#551): the orbit around a +// vehicle, the shunting view from above, the view beside a coupling and the trackside view of a railfan. Each one +// is worked out here from the place of the vehicle and the keys of the user alone, so it can be tested without the +// game; application/consistviews.cpp hands over the vehicles of the train and turns the results into the camera. +// The world has y up; the rails are at the height of the place of a vehicle (TDynamicObject::GetPosition). +namespace cameraviews { + +// a vehicle of the train, as the views see it +struct vehicle_pose { + glm::dvec3 position{}; // its middle, at the height of the rails + glm::dvec3 front{0.0, 0.0, -1.0}; // unit, towards its front coupler + double length{20.0}; + double width{3.0}; + double height{4.0}; +}; + +// where the camera stands, the point it looks at and its up +struct placement { + glm::dvec3 eye{}; + glm::dvec3 target{}; + glm::dvec3 up{0.0, 1.0, 0.0}; +}; + +// the movement keys of the camera as TCamera::Velocity has them outside the cab: x to the right, y up, z backwards +// (the up arrow gives a negative z), 1 for a key held, 5 with ctrl +using move_keys = glm::dvec3; + +// the Front of a vehicle flattened on the ground, unit; a vehicle standing upright (no heading) faces -z +glm::dvec3 flat_front(glm::dvec3 const &Front); +// to the left of the flat Front, unit +glm::dvec3 flat_left(glm::dvec3 const &Flatfront); + +// the index after Step vehicles (or couplings) from Index, among Count of them, held at the first and the last +int step_index(int Index, int Count, int Step); + +// the two ends of a train whose vehicles stand at Positions, going in the Direction: the index of the vehicle +// at its head (furthest along the Direction) and at its tail +std::pair train_ends(std::vector const &Positions, glm::dvec3 const &Direction); + +// +1 when the front of the vehicle the view goes with points the way the user drives, -1 when it points back: +// the Front of that vehicle, the Front of the vehicle the user drives and its occupied cab (1 the front one, +// -1 the rear one, 0 none) +int driving_facing(glm::dvec3 const &Front, glm::dvec3 const &Drivenfront, int Cab); + +// orbit: around the middle of the vehicle, the left and right keys (and the mouse) turn the camera around it, +// the up and down arrows bring it closer and further away, the page keys (and the mouse) raise and lower it +struct orbit { + double azimuth{0.0}; // radians around the vehicle from its front, towards its left + double elevation{0.0}; // radians above the horizon of the middle of the vehicle + double radius{0.0}; // metres from the middle of the vehicle, 0 for the default one of the vehicle +}; + +inline constexpr double orbit_max_radius{250.0}; +inline constexpr double orbit_max_elevation{1.4}; // radians, about 80 degrees +inline constexpr double orbit_min_elevation{-0.5}; // radians, about -30 degrees, if the rails let it +inline constexpr double rail_clearance{0.5}; // metres the camera keeps above the rails + +// the first orbit around a vehicle: ahead of it on its left, a little above it, as far as the vehicle is long +orbit orbit_start(vehicle_pose const &Vehicle); +// the point the orbit goes around: the middle of the vehicle, a little lower than half of its height +glm::dvec3 orbit_centre(vehicle_pose const &Vehicle); +// the nearest the camera comes to the middle of the Vehicle: outside its body whichever way it looks +double orbit_min_radius(vehicle_pose const &Vehicle); +// the lowest elevation at the Radius which keeps the camera above the rails +double orbit_lowest_elevation(vehicle_pose const &Vehicle, double Radius); +// the Orbit held within its limits around the Vehicle (radius 0 becomes the default one) +orbit orbit_clamped(orbit Orbit, vehicle_pose const &Vehicle); +// the Orbit after Seconds of the Keys held and the mouse moved by Turn (radians: x up and down, y to the left and +// right, as TCamera::Angle takes them), within its limits around the Vehicle +orbit orbit_moved(orbit Orbit, move_keys const &Keys, glm::dvec2 const &Turn, double Seconds, vehicle_pose const &Vehicle); +// the camera of the Orbit around the Vehicle, looking at its middle +placement orbit_placement(orbit const &Orbit, vehicle_pose const &Vehicle); + +// shunting view: straight down from above the vehicle, the way the user drives up the screen; it goes with the +// vehicle, the up and down arrows move it along the train, left and right across, the page keys up and down +struct topdown { + double height{0.0}; // metres above the rails, 0 for the default one of the vehicle + double along{0.0}; // metres from the middle of the vehicle along it, the way the user drives + double across{0.0}; // metres from the middle of the vehicle across it, to the right of the screen +}; + +inline constexpr double topdown_max_height{300.0}; +inline constexpr double topdown_max_across{60.0}; + +// the lowest the camera comes: above the roof of the Vehicle +double topdown_min_height(vehicle_pose const &Vehicle); +// the View held within its limits: Alonglimit metres along the vehicle either way +topdown topdown_clamped(topdown View, vehicle_pose const &Vehicle, double Alonglimit); +// the View after Seconds of the Keys held; the further the camera, the faster it moves +topdown topdown_moved(topdown View, move_keys const &Keys, double Seconds, vehicle_pose const &Vehicle, double Alonglimit); +// the camera of the View over the Vehicle; Facing +1 puts the front of the vehicle up the screen, -1 its rear +placement topdown_placement(topdown const &View, vehicle_pose const &Vehicle, int Facing); + +// coupling view: beside a coupler, low, looking along the train at it; when another vehicle comes closer to it +// the camera steps back from the track to keep both couplers in sight, looking between them +inline constexpr double buffer_height{1.06}; // metres above the rails + +struct coupler { + glm::dvec3 position{}; // the coupler at the height of the rails (TDynamicObject::CouplerPosition) + glm::dvec3 outward{0.0, 0.0, -1.0}; // unit, from its vehicle out through the coupler + double width{3.0}; // of its vehicle +}; + +struct coupler_view { + double side{1.0}; // 1 on the left of the outward way, -1 on the right + double height{0.4}; // metres above the buffers + double distance{2.5}; // metres from the side of the vehicle, before the vehicle coming closer moves it further +}; + +inline constexpr double coupler_min_distance{1.0}; +inline constexpr double coupler_max_distance{40.0}; +inline constexpr double coupler_min_height{-0.8}; // metres above the buffers: a little above the rails +inline constexpr double coupler_max_height{10.0}; +inline constexpr double coupler_watch_range{150.0}; // metres to a vehicle that still counts as coming closer + +// the View after Seconds of the Keys held: left and right move it to that side of the track, the arrows closer +// and further, the page keys up and down +coupler_view coupler_moved(coupler_view View, move_keys const &Keys, double Seconds); +// the camera beside the Coupler; Other is the facing coupler of the vehicle coming closer, when there is one +placement coupler_placement(coupler_view const &View, coupler const &Coupler, glm::dvec3 const *Other); +// the coupling of a train of Count vehicles the view starts at, numbered from 0 (its front end) to Count (its rear +// end): the end with another vehicle, not coupled, closer than coupler_watch_range (the closer one of the two), +// otherwise the front. Frontgap and Reargap are the distances to such vehicles, negative for none +int first_coupling(double Frontgap, double Reargap, int Count); + +// trackside view: a railfan standing beside the line ahead of the train, looking at it as it comes and goes by; +// once the whole train has gone past (or gone far away) the railfan walks to a new spot ahead of it, on the other +// side of the line +struct trackside { + glm::dvec3 spot{}; // the eye of the railfan + double side{-1.0}; // 1 on the left of the line, -1 on the right + bool placed{false}; +}; + +// the train as the trackside view sees it +struct train_motion { + glm::dvec3 head{}; // the vehicle at its head, the way it goes, at the height of the rails + glm::dvec3 tail{}; // the vehicle at its tail + glm::dvec3 direction{0.0, 0.0, -1.0}; // unit, flat, the way it goes + double speed{0.0}; // m/s + double curvature{0.0}; // 1/m of the line at the head, positive turning left + double width{3.0}; // of the vehicles +}; + +inline constexpr double trackside_eye_height{1.7}; +inline constexpr double trackside_distance{8.0}; // metres from the side of the train +inline constexpr double trackside_passed{40.0}; // metres the tail goes past the spot before the railfan moves on +inline constexpr double trackside_max_distance{1000.0}; // metres to the head before the railfan moves on anyway +inline constexpr double trackside_lead_time{15.0}; // seconds the train needs to reach the new spot +inline constexpr double trackside_min_lead{80.0}; +inline constexpr double trackside_max_lead{500.0}; + +// whether the railfan at the View has seen the Train go by and moves on +bool trackside_expired(trackside const &View, train_motion const &Train); +// the next spot of the railfan, ahead of the Train along its line, on the other side than the View had +trackside trackside_next(trackside const &View, train_motion const &Train); +// the camera of the railfan at the View, looking at the Target +placement trackside_placement(trackside const &View, glm::dvec3 const &Target); + +// the point and the way Distance metres on from Start going in the (flat, unit) Direction along a line which +// turns by Curvature (1/m, positive to the left) +std::pair along_arc(glm::dvec3 const &Start, glm::dvec3 const &Direction, double Curvature, double Distance); +// the curvature of the line under two vehicles of a train going its way: A ahead of B, each at its Position with +// its front (or rear) towards the way of the train; 0 when they stand too close to tell +double line_curvature(glm::dvec3 const &Positiona, glm::dvec3 const &Directiona, glm::dvec3 const &Positionb, glm::dvec3 const &Directionb); + +} // namespace cameraviews diff --git a/vehicle/compartmentlightsswitch.h b/vehicle/compartmentlightsswitch.h new file mode 100644 index 000000000..0ef6684c0 --- /dev/null +++ b/vehicle/compartmentlightsswitch.h @@ -0,0 +1,27 @@ +/* +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 + +// the compartment lights get two requests: on (CompartmentLights.is_enabled) and off (is_disabled), and the off one +// wins. A two-state compartmentlights_sw: holds one of them, so turning it to one position withdraws the other request. +// A push type compartmentlights_sw: and the separate compartmentlightson_sw: / compartmentlightsoff_sw: push buttons +// withdraw their own request when they're released, so the other command leaves it alone. A cab with none of these +// controls (the keyboard toggle, ctrl+;, is all there is) acts as if it had the two-state switch, otherwise nothing +// would ever withdraw the off request and the lights couldn't be turned on again. +namespace compartment_lights_switch { + +// whether the command for one of the requests also withdraws the other one, from the cab's compartmentlights_sw: +// (whether it's there and whether it's a toggle type switch) and whether the cab has the push button of the other +// request (compartmentlightsoff_sw: for the on command, compartmentlightson_sw: for the off command) +inline bool withdraws_other_request(bool const Hasswitch, bool const Switchistoggle, bool const Hasotherbutton) { + return Hasswitch ? Switchistoggle : false == Hasotherbutton; +} + +} // namespace compartment_lights_switch diff --git a/vehicle/crew.cpp b/vehicle/crew.cpp new file mode 100644 index 000000000..0efda42fb --- /dev/null +++ b/vehicle/crew.cpp @@ -0,0 +1,134 @@ +/* +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/crew.h" + +#include "physics/vehicle.h" +#include "vehicle/handover.h" + +namespace crew { + +namespace { + +// the scenery parser folds the ASCII letters of the names only, and so does this +char lower_ascii(char const Character) { + return Character >= 'A' && Character <= 'Z' ? static_cast(Character - 'A' + 'a') : Character; +} + +// the controllers of the vehicle to the positions giving no power, and the vehicles it controls told so +void cut_power(physics::Vehicle &Vehicle) { + Vehicle.SetMainCtrlPos(Vehicle.MainCtrlNoPowerPos()); + Vehicle.SetScndCtrlPos(0); + // what the integrated handle and the cruise control asked for last stays in force until somebody drives + Vehicle.eimic = 0.0; + Vehicle.SetEimicReal(0.0); + Vehicle.SpeedCtrlValue = 0.0; + Vehicle.SpeedCtrlUnit.IsActive = false; + Vehicle.SendCtrlToNext(VehicleCommand::mainController, Vehicle.MainCtrlPosForCoupled(), Vehicle.CabActive); + Vehicle.SendCtrlToNext(VehicleCommand::secondaryController, Vehicle.ScndCtrlPos(), Vehicle.CabActive); + Vehicle.SendCtrlToNext(VehicleCommand::integratedController, 0.0, Vehicle.CabActive); +} + +} // namespace + +bool is_command(std::string_view const Text) { + return Text.starts_with(command_prefix); +} + +request parse(std::string_view const Text, double const Cab, double const Flags) { + request result; + if (false == is_command(Text)) { + return result; + } + result.vehicle = Text.substr(command_prefix.size()); + std::ranges::transform(result.vehicle, result.vehicle.begin(), lower_ascii); + result.cab_valid = Cab == 1.0 || Cab == -1.0 || Cab == 0.0; + if (result.cab_valid) { + result.cab = static_cast(Cab); + } + result.flags = static_cast(std::clamp(Flags, -65535.0, 65535.0)); + return result; +} + +action decide(request const &Request, vehicle_state const &State) { + using enum action; + if (false == Request.cab_valid) { + return refuse_cab; + } + if (State.occupied || (State.has_driver && false == State.driver_is_ai)) { + return refuse_user; + } + if (Request.cab == 0) { + return State.has_driver ? remove : nothing; + } + if (State.has_driver) { + return refuse_crewed; + } + if (false == State.has_cab) { + return refuse_no_cab; + } + if (State.consist_driven) { + return refuse_consist_driven; + } + return Request.cab > 0 ? add_front : add_rear; +} + +bool changes_crew(action const Action) { + return Action == action::add_front || Action == action::add_rear || Action == action::remove; +} + +std::string_view describe(action const Action) { + using enum action; + switch (Action) { + case add_front: + return "an AI driver takes cab A"; + case add_rear: + return "an AI driver takes cab B"; + case remove: + return "the AI driver leaves"; + case nothing: + return "no driver to take off"; + case refuse_cab: + return "refused, the cab has to be 1, -1 or 0"; + case refuse_user: + return "refused, a user is in the vehicle"; + case refuse_crewed: + return "refused, the vehicle has a driver already"; + case refuse_no_cab: + return "refused, the vehicle has no cab"; + case refuse_consist_driven: + return "refused, the consist has a driver in charge in another vehicle"; + default: + return ""; + } +} + +void secure(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { + handover::release_ai_controls(Occupied, Controlling); + cut_power(Controlling); + if (&Occupied != &Controlling) { + cut_power(Occupied); + } + // the emergency position vents the brake pipe whatever the brake mode, and with nobody in the cab too + Occupied.BrakeLevelSet(Occupied.brakes.driverValve->GetPos(bh_EB)); + // a vehicle with no train brake (a car, a draisine) gets the brake its driver stops it with, in full + if (Occupied.brakes.config.kind == TBrakeSystem::Individual) { + if (Occupied.brakes.config.localKind == TLocalBrake::ManualBrake) { + Occupied.IncManualBrakeLevel(ManualBrakePosNo); + } + else { + Occupied.IncLocalBrakeLevel(LocalBrakePosNo); + } + } + Occupied.CabDeactivisation(); + Occupied.SetCabOccupied(0); +} + +} // namespace crew diff --git a/vehicle/crew.h b/vehicle/crew.h new file mode 100644 index 000000000..d7c7fb325 --- /dev/null +++ b/vehicle/crew.h @@ -0,0 +1,82 @@ +/* +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 + +#include +#include + +namespace physics { class Vehicle; } + +// a driver put in a vehicle, or taken off it, while the scenario runs (eu07/maszyna#510): the command of a +// putvalues event +// event putvalues none 0 0 0 Crew: endevent +// with the name of the vehicle in the text, so the event works whatever sets it off (a key, an event +// launcher), the cab in the first value: 1 an AI driver in cab A, -1 in cab B, 0 nobody, and the second value +// reserved (0). "Crew:" with no name is for the vehicle which set the event off. +// here are the parts which need no vehicle of the game: reading the command, deciding what to do about it, +// and the state a train is left in when its driver goes. the game's side of it is in crewchange.h +namespace crew { + +// what the text of the command starts with, in this very case (the commands of the events are case sensitive) +inline constexpr std::string_view command_prefix{"Crew:"}; + +// whether the text of a putvalues event is the crew command +bool is_command(std::string_view Text); + +// the command as the event gives it +struct request { + std::string vehicle; // as the scenery keeps the names, in lower case; empty: the vehicle which set the event off + int cab{0}; // 1 a driver in cab A (the front one), -1 in cab B, 0 nobody + bool cab_valid{false}; // the value was one of the three + int flags{0}; // reserved, nothing reads it yet +}; + +// reads the command from the text of the event and its two values +request parse(std::string_view Text, double Cab, double Flags); + +// what the command finds in the vehicle +struct vehicle_state { + bool has_cab{false}; // the type of the vehicle has a driver's cab; a road vehicle or a boat counts as having one + bool has_driver{false}; + bool driver_is_ai{false}; // the driver it has is the AI, not a user + bool occupied{false}; // a user sits in the vehicle, whoever drives it + bool consist_driven{false}; // another vehicle of the consist has the driver in charge of it +}; + +enum class action { + add_front, // an AI driver goes into cab A + add_rear, // an AI driver goes into cab B + remove, // the AI driver is taken off + nothing, // asked to take the driver off a vehicle which has none + refuse_cab, // the cab asked for is none of 1, -1, 0 + refuse_user, // a user is in the vehicle, or drives it + refuse_crewed, // asked for a driver where there is one already + refuse_no_cab, // asked for a driver in a vehicle with no cab + refuse_consist_driven // asked for a driver in a consist which another vehicle's driver is in charge of +}; + +// what to do about the command. a user in the vehicle is never touched: neither replaced nor left without +// the driver the cab of the game works with +action decide(request const &Request, vehicle_state const &State); + +// whether the action changes anything +bool changes_crew(action Action); + +// the action in words, for the log +std::string_view describe(action Action); + +// the state a train is left in when the driver in charge of it goes: what the AI held is let go (as when it +// hands over to a user, see handover.h), the power is off, the driver's brake valve is in the emergency position, +// so a train on the move stops and stays braked, and the cab is neither active nor occupied. the engine, the +// pantographs and the lights stay as they were. Occupied is the vehicle of the driver, Controlling the one whose +// motors it drove (the AI's occupied and mvControlling; the same one in a locomotive) +void secure(physics::Vehicle &Occupied, physics::Vehicle &Controlling); + +} // namespace crew diff --git a/vehicle/crewchange.cpp b/vehicle/crewchange.cpp new file mode 100644 index 000000000..9202934f5 --- /dev/null +++ b/vehicle/crewchange.cpp @@ -0,0 +1,139 @@ +/* +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/crewchange.h" + +#include "simulation/simulation.h" +#include "utilities/Logs.h" +#include "vehicle/Driver.h" +#include "vehicle/DynObj.h" +#include "vehicle/Train.h" +#include "vehicle/handover.h" +#include "physics/vehicle.h" + +namespace crew { + +namespace { + +// physics::Vehicle::CategoryFlag of the rail vehicles +constexpr int rail_category{1}; +// more vehicles than a consist has, for a walk along one whose couplers form a loop +constexpr int consist_walk_limit{300}; + +// calls the function for each vehicle of the consist, from one end of it to the other. goes by the couplers +// alone, as the driver's own check of the consist does, so it works for a consist nobody has put in order +template +void for_each_in_consist(TDynamicObject &Vehicle, Function_ const Function) { + auto side{static_cast(VehicleEnd::front)}; + auto *vehicle{Vehicle.FirstFind(side)}; + side = 1 - side; + auto count{0}; + while (vehicle != nullptr && count < consist_walk_limit) { + Function(*vehicle); + vehicle = vehicle->Neighbour(side); + ++count; + } +} + +// whether another vehicle of the consist has the driver in charge of it +bool is_consist_driven(TDynamicObject &Vehicle) { + auto driven{false}; + for_each_in_consist(Vehicle, [&Vehicle, &driven](TDynamicObject const &Other) { + if (&Other != &Vehicle && Other.Mechanik != nullptr && Other.Mechanik->primary()) { + driven = true; + } + }); + return driven; +} + +vehicle_state state_of(TDynamicObject &Vehicle) { + vehicle_state state; + // a rail vehicle has a cab when it has the driver's brake valve. the others (cars, boats) have no such valve + // to tell by, and each of them is driven from its own seat + state.has_cab = Vehicle.physics->HasDriverCab() || Vehicle.physics->CategoryFlag != rail_category; + state.has_driver = Vehicle.Mechanik != nullptr; + state.driver_is_ai = state.has_driver && Vehicle.Mechanik->AIControllFlag(); + // a cab of the game is bound to the vehicle: the user's own, or another user's in a network game. the cab + // reads the driver of its vehicle all the time, so that driver stays + state.occupied = simulation::Trains.find(Vehicle.name()) != nullptr; + state.consist_driven = is_consist_driven(Vehicle); + return state; +} + +// an AI driver for the vehicle, as the scenery gives one to a vehicle of its own outside a trainset: in charge of +// the consist, with no timetable, waiting for orders when the vehicle stands and driving on when it rolls +void add_driver(TDynamicObject &Vehicle, int const Cab) { + Vehicle.physics->SetCabOccupied(Cab); + Vehicle.Controller = AIdriver; + Vehicle.create_controller(Cab > 0 ? "1" : "2", false); +} + +// takes the AI driver off. nothing but the vehicle and the vehicles the driver is in charge of points at a driver +// (the panels, the events, the network and the black box read it from a vehicle each time), so these are cleared +// and the driver deleted. the vehicles in its charge are looked for among all vehicles, not along the couplers: +// a coupler broken under force or in a collision (physics::Vehicle::damage_coupler()) parts the train and leaves +// the vehicles parted from it in the driver's charge, as uncoupling (TDynamicObject::Dettach()) doesn't +void remove_driver(TDynamicObject &Vehicle) { + auto *driver{Vehicle.Mechanik}; + auto &occupied{*Vehicle.physics}; + auto &controlling{*Vehicle.FindPowered()->physics}; + if (driver->primary()) { + // the train this driver was in charge of stops and stays braked + secure(occupied, controlling); + } + else { + // somebody else drives the train, so only what this one held is let go + handover::release_ai_controls(occupied, controlling); + occupied.SetCabOccupied(0); + } + Vehicle.Mechanik = nullptr; + auto released{0}; + for (auto *other : simulation::Vehicles.sequence()) { + if (other->ctOwner == driver) { + other->ctOwner = nullptr; + ++released; + } + } + WriteLog("Crew: [" + Vehicle.name() + "] the driver was in charge of " + std::to_string(released) + (released == 1 ? " vehicle" : " vehicles")); + delete driver; +} + +} // namespace + +void change(request const &Request, TDynamicObject const *Activator) { + std::string const name{Request.vehicle.empty() && Activator != nullptr ? Activator->name() : Request.vehicle}; + if (name.empty()) { + ErrorLog("Bad event: \"" + std::string{command_prefix} + "\" names no vehicle and no vehicle set the event off"); + return; + } + auto *vehicle{simulation::Vehicles.find(name)}; + if (vehicle == nullptr || false == vehicle->bEnabled) { + ErrorLog("Bad event: \"" + std::string{command_prefix} + name + "\" can't find the vehicle"); + return; + } + if (Request.flags != 0) { + WriteLog("Crew: [" + name + "] flags " + std::to_string(Request.flags) + " ignored, none is defined yet"); + } + auto const decision{decide(Request, state_of(*vehicle))}; + WriteLog("Crew: [" + name + "] " + std::string{describe(decision)}); + switch (decision) { + case action::add_front: + case action::add_rear: + add_driver(*vehicle, Request.cab); + break; + case action::remove: + remove_driver(*vehicle); + break; + default: + break; + } +} + +} // namespace crew diff --git a/vehicle/crewchange.h b/vehicle/crewchange.h new file mode 100644 index 000000000..3b348edaa --- /dev/null +++ b/vehicle/crewchange.h @@ -0,0 +1,24 @@ +/* +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 + +#include "vehicle/crew.h" + +class TDynamicObject; + +namespace crew { + +// carries out the crew command of an event (see crew.h) on the vehicle it names, or on Activator, the vehicle +// which set the event off, when it names none: puts an AI driver in, the way the scenery does for a vehicle of +// its own with a driver, or takes the AI driver off and leaves the train secured. whatever it does or refuses +// goes to the log. called from the event queue, between the updates of the vehicles +void change(request const &Request, TDynamicObject const *Activator); + +} // namespace crew diff --git a/vehicle/derailmotion.cpp b/vehicle/derailmotion.cpp new file mode 100644 index 000000000..252ba7f4d --- /dev/null +++ b/vehicle/derailmotion.cpp @@ -0,0 +1,907 @@ +/* +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/derailmotion.h" + +#include "physics/derailment.h" + +#include +#include +#include +#include + +namespace derail_motion { + +namespace { + +glm::dvec3 const world_up{0.0, 1.0, 0.0}; + +// the vector level, of unit length; the fallback for one standing up +glm::dvec3 level(glm::dvec3 const &Vector, glm::dvec3 const &Fallback = {0.0, 0.0, 1.0}) { + glm::dvec3 const flat{Vector.x, 0.0, Vector.z}; + auto const length{glm::length(flat)}; + return length > 1e-9 ? flat / length : Fallback; +} + +// to the left of a level heading, as TDynamicObject has it: up x front +glm::dvec3 left_of(glm::dvec3 const &Front) { + return glm::dvec3{Front.z, 0.0, -Front.x}; +} + +// the vector turned about the axis by the angle, right-handed +glm::dvec3 turned(glm::dvec3 const &Vector, glm::dvec3 const &Axis, double const Angle) { + auto const c{std::cos(Angle)}; + auto const s{std::sin(Angle)}; + return Vector * c + glm::cross(Axis, Vector) * s + Axis * (glm::dot(Axis, Vector) * (1.0 - c)); +} + +double sign_of(double const Value) { + if (Value > 0.0) { + return 1.0; + } + return Value < 0.0 ? -1.0 : 0.0; +} + +// the height of the triangle over the point, if it is over it (in the plan) +std::optional height_in(mesh_ground::triangle const &Triangle, double const X, double const Z) { + auto const &a{Triangle[0]}; + auto const &b{Triangle[1]}; + auto const &c{Triangle[2]}; + auto const determinant{(b.z - c.z) * (a.x - c.x) + (c.x - b.x) * (a.z - c.z)}; + if (std::abs(determinant) < 1e-12) { + // standing on its edge, a wall + return std::nullopt; + } + auto const u{((b.z - c.z) * (X - c.x) + (c.x - b.x) * (Z - c.z)) / determinant}; + auto const v{((c.z - a.z) * (X - c.x) + (a.x - c.x) * (Z - c.z)) / determinant}; + auto const w{1.0 - u - v}; + constexpr double edge{-1e-9}; + if (u < edge || v < edge || w < edge) { + return std::nullopt; + } + return u * a.y + v * b.y + w * c.y; +} + +} // namespace + +namespace { + +// the angle [rad] from the first level direction to the second, to the left positive +double angle_between(glm::dvec3 const &From, glm::dvec3 const &To) { + return std::atan2(glm::dot(To, left_of(From)), glm::dot(To, From)); +} + +// the beams of two ends further apart across than this have gone past each other [m] +constexpr double beam_reach{2.0}; +// nor do they meet pressed into each other deeper than this: the buffers and the ends behind them crushed [m] +constexpr double beam_depth{1.5}; +// the buffers of two ends this far apart along the line between them are apart, the coupling straight between [m] +constexpr double buffer_reach{0.1}; + +} // namespace + +double sliding_friction(double const Tipping, bool const Guided) { + if (Guided) { + return guided_friction; + } + auto const share{std::clamp(std::abs(Tipping) / body::half_turn, 0.0, 1.0)}; + return std::lerp(derailment::off_rails_friction, derailment::overturned_friction, share); +} + +double departure_angle(cause const Cause, double const Speed, double const Acceleration) { + if (Cause == cause::end_of_track || Cause == cause::collision) { + return 0.0; + } + auto const sideways{std::sqrt(2.0 * std::abs(Acceleration) * climb_width)}; + return std::min(most_departure, std::atan2(sideways, std::max(std::abs(Speed), 1.0))); +} + +scatter draw_scatter(std::uint32_t const Seed) { + // the raw numbers of the engine are the same with every library, the distributions of aren't + std::mt19937 engine{Seed}; // NOSONAR: seeded on purpose, so that a derailment can be repeated; nothing secret is drawn + auto const uniform = [&engine](double const Low, double const High) { return Low + (High - Low) * ((static_cast(engine()) + 0.5) / 4294967296.0); }; + scatter result; + result.departure = uniform(-0.01, 0.01); + result.yaw = uniform(-0.02, 0.02); + result.yaw_rate = uniform(-0.02, 0.02); + result.friction_front = uniform(0.85, 1.15); + result.friction_rear = uniform(0.85, 1.15); + auto const bites{uniform(0.0, 1.0) < 2.0 / 3.0}; + auto const when{uniform(0.2, 1.5)}; + auto const howlong{uniform(0.3, 0.8)}; + auto const how{uniform(2.0, 4.0)}; + auto const side{uniform(0.0, 1.0) < 0.5 ? -1 : 1}; + if (bites) { + result.dig_in = when; + result.dig_in_time = howlong; + result.dig_in_friction = how; + result.dig_in_side = side; + } + return result; +} + +std::uint32_t seed_of(std::uint32_t const Run, std::string_view const Name) { + // FNV-1a of the name, mixed with the seed of the run + std::uint32_t hash{2166136261u}; + for (auto const character : Name) { + hash = (hash ^ static_cast(character)) * 16777619u; + } + hash ^= Run + 0x9e3779b9u + (hash << 6) + (hash >> 2); + return hash; +} + +meeting meet(end_point const &First, end_point const &Second) { + meeting result; + auto const outward{level(First.outward)}; + auto const otherward{level(Second.outward, -outward)}; + result.point = First.point; + result.push = level(outward - otherward, outward); + result.bend = angle_between(outward, -otherward); + glm::dvec3 const apart{Second.point.x - First.point.x, 0.0, Second.point.z - First.point.z}; + auto const along{glm::dot(apart, result.push)}; + auto const across{glm::dot(apart, left_of(result.push))}; + auto const distance{glm::length(apart)}; + result.pull = distance > 0.05 ? apart / distance : result.push; + // the ends face each other (bent by less than a right angle) and meet within the depth of the buffers and the ends + // crushed behind them + auto const facing{glm::dot(outward, otherward) < 0.0}; + if (along <= 0.0 && facing && along > -beam_depth && std::abs(across) < beam_reach) { + // the buffers press into each other + result.gap = along; + } + else if (along <= 0.0) { + // the ends went past each other, or one body turned about: only the coupling holds them, stretched + result.gap = distance; + } + else { + // apart, the coupling between the middles of the beams; as they come together, the buffers in line + result.gap = std::hypot(along, across) - std::abs(across) * std::max(0.0, 1.0 - along / buffer_reach); + } + // the buffers of the outer side of a body rolled against the other one lift or drop by its roll + auto const apartinheight{std::abs(Second.point.y - First.point.y) + buffer_half_spacing * std::abs(std::sin(Second.roll - First.roll))}; + result.overlap = std::clamp(1.0 - apartinheight / buffer_head, 0.0, 1.0); + return result; +} + +end_force force_on(meeting const &Meeting, double const Compression) { + end_force result; + result.point = Meeting.point; + if (Compression > 0.0) { + // the inner buffer of the bend takes more of the push, all of it past the play of the buffers; as far as the + // buffers meet in height, and as much of it as a buffer takes, the rest at the middle of the beam + auto const holding{buffer_half_spacing * Meeting.overlap * std::min(1.0, buffer_limit / Compression)}; + result.point += left_of(Meeting.push) * (holding * std::clamp(Meeting.bend / buffer_lock, -1.0, 1.0)); + result.force = -Meeting.push * Compression; + } + else { + result.force = Meeting.pull * (-Compression); + } + return result; +} + +footprint footprint_of(pose const &Pose, double const Length, double const Width, double const Height) { + footprint result; + result.axis = level(Pose.front); + auto const left{left_of(result.axis)}; + result.half_length = std::max(0.5 * Length - buffer_length, 0.5) * std::max(std::hypot(Pose.front.x, Pose.front.z), 0.1); + // the corners of its cross section, from the rails to the roof, as it is rolled + auto low{std::numeric_limits::max()}; + auto high{std::numeric_limits::lowest()}; + auto mostleft{std::numeric_limits::lowest()}; + auto mostright{std::numeric_limits::max()}; + for (auto const across : {-0.5 * Width, 0.5 * Width}) { + for (auto const up : {0.0, Height}) { + auto const corner{Pose.position + Pose.left * across + Pose.up * up}; + auto const aside{glm::dot(corner - Pose.position, left)}; + mostleft = std::max(mostleft, aside); + mostright = std::min(mostright, aside); + low = std::min(low, corner.y); + high = std::max(high, corner.y); + } + } + result.half_width = 0.5 * (mostleft - mostright); + result.centre = glm::dvec3{Pose.position.x, 0.0, Pose.position.z} + left * (0.5 * (mostleft + mostright)); + // pitched, the ends rise and drop by the slope over half its length + auto const rise{std::abs(Pose.front.y) / std::max(std::hypot(Pose.front.x, Pose.front.z), 0.1) * result.half_length}; + result.low = low - rise; + result.high = high + rise; + return result; +} + +namespace { + +// the corners of the footprint, in turn round it +std::array corners_of(footprint const &Print) { + auto const along{Print.axis * Print.half_length}; + auto const across{left_of(Print.axis) * Print.half_width}; + return {Print.centre + along + across, Print.centre + along - across, Print.centre - along - across, Print.centre - along + across}; +} + +// whether the point is inside the footprint (in the plan) +bool inside(footprint const &Print, glm::dvec3 const &Point) { + glm::dvec3 const offset{Point.x - Print.centre.x, 0.0, Point.z - Print.centre.z}; + return std::abs(glm::dot(offset, Print.axis)) <= Print.half_length && std::abs(glm::dot(offset, left_of(Print.axis))) <= Print.half_width; +} + +double cross_up(glm::dvec3 const &Arm, glm::dvec3 const &Force) { + // about the vertical, to the left positive + return Arm.z * Force.x - Arm.x * Force.z; +} + +// the inverse of the mass the body moves with at the point the way of the direction +double inverse_mass(contact_body const &Body, glm::dvec3 const &Point, glm::dvec3 const &Direction) { + if (Body.mass <= 0.0) { + return 0.0; + } + if (Body.guided) { + auto const along{glm::dot(Direction, Body.guide)}; + return along * along / Body.mass; + } + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + auto const turning{cross_up(arm, Direction)}; + return (1.0 + turning * turning / std::max(Body.gyration, 1e-3)) / Body.mass; +} + +} // namespace + +std::optional collide(footprint const &First, footprint const &Second) { + if (std::min(First.high, Second.high) - std::max(First.low, Second.low) < height_overlap) { + // one goes over the other + return std::nullopt; + } + // the separating axes: the sides of both rectangles; the one they overlap least across is the way out + auto const first{corners_of(First)}; + auto const second{corners_of(Second)}; + glm::dvec3 const apart{Second.centre.x - First.centre.x, 0.0, Second.centre.z - First.centre.z}; + contact result; + result.depth = std::numeric_limits::max(); + for (auto const &axis : {First.axis, left_of(First.axis), Second.axis, left_of(Second.axis)}) { + auto spread = [&axis](std::array const &Corners) { + auto low{std::numeric_limits::max()}; + auto high{std::numeric_limits::lowest()}; + for (auto const &corner : Corners) { + auto const along{glm::dot(corner, axis)}; + low = std::min(low, along); + high = std::max(high, along); + } + return std::pair{low, high}; + }; + auto const [low1, high1]{spread(first)}; + auto const [low2, high2]{spread(second)}; + auto const overlap{std::min(high1, high2) - std::max(low1, low2)}; + if (overlap <= 0.0) { + return std::nullopt; + } + if (overlap < result.depth) { + result.depth = overlap; + result.normal = glm::dot(apart, axis) >= 0.0 ? axis : -axis; + } + } + // the point: the middle of the corners of each inside the other, or of where the overlap is + glm::dvec3 sum{0.0}; + auto count{0}; + for (auto const &corner : first) { + if (inside(Second, corner)) { + sum += corner; + ++count; + } + } + for (auto const &corner : second) { + if (inside(First, corner)) { + sum += corner; + ++count; + } + } + if (count > 0) { + result.point = sum / static_cast(count); + } + else { + // crossed without a corner inside the other (two long sides across each other): between the middles + result.point = 0.5 * (First.centre + Second.centre); + } + result.point.y = 0.0; + return result; +} + +glm::dvec3 velocity_at(contact_body const &Body, glm::dvec3 const &Point) { + if (Body.guided) { + return Body.velocity; + } + // turning about the vertical at the yaw rate: up x arm + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + return Body.velocity + Body.yaw_rate * glm::dvec3{arm.z, 0.0, -arm.x}; +} + +glm::dvec3 contact_impulse(contact const &Contact, contact_body const &First, contact_body const &Second) { + auto const &normal{Contact.normal}; + auto const relative{velocity_at(Second, Contact.point) - velocity_at(First, Contact.point)}; + auto const closing{glm::dot(relative, normal)}; + if (closing >= 0.0) { + // parting already + return glm::dvec3{0.0}; + } + auto const inverse{inverse_mass(First, Contact.point, normal) + inverse_mass(Second, Contact.point, normal)}; + if (inverse <= 0.0) { + return glm::dvec3{0.0}; + } + auto const push{-(1.0 + contact_restitution) * closing / inverse}; + glm::dvec3 result{normal * push}; + // the friction of the sides sliding along each other, no more than stops the sliding + auto const sliding{relative - normal * closing}; + auto const slide{glm::length(sliding)}; + if (slide > 1e-6) { + auto const along{sliding / slide}; + auto const alonginverse{inverse_mass(First, Contact.point, along) + inverse_mass(Second, Contact.point, along)}; + if (alonginverse > 0.0) { + result -= along * std::min(contact_friction * push, slide / alonginverse); + } + } + return result; +} + +std::pair impulse_change(contact_body const &Body, glm::dvec3 const &Impulse, glm::dvec3 const &Point) { + if (Body.mass <= 0.0) { + return {glm::dvec3{0.0}, 0.0}; + } + if (Body.guided) { + return {Body.guide * (glm::dot(Impulse, Body.guide) / Body.mass), 0.0}; + } + glm::dvec3 const arm{Point.x - Body.base.x, 0.0, Point.z - Body.base.z}; + return {glm::dvec3{Impulse.x, 0.0, Impulse.z} / Body.mass, cross_up(arm, Impulse) / (Body.mass * std::max(Body.gyration, 1e-3))}; +} + +std::optional stopping_distance(double const Speed, double const Friction, double const Grade) { + auto const angle{std::atan(Grade)}; + auto const deceleration{gravity * (Friction * std::cos(angle) + std::sin(angle))}; + if (deceleration <= 0.0) { + return std::nullopt; + } + return Speed * Speed / (2.0 * deceleration); +} + +double pull_ratio(double const Force, double const Angle, double const Mass, int const Axles) { + auto const axles{std::max(Axles, 2)}; + auto const load{Mass * gravity / (2.0 * axles)}; + if (load <= 0.0) { + return 0.0; + } + auto const across{std::abs(Force * std::sin(Angle))}; + return across / (0.5 * axles) / load; +} + +// ---- the ground + +std::optional flat_ground::height(double, double, double) const { + return m_level; +} + +mesh_ground::mesh_ground(std::vector const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double const Cell) : m_min{Min}, m_max{glm::max(Max, Min + glm::dvec2{1.0})}, m_cell{std::max(Cell, 1.0)} { + auto const size{m_max - m_min}; + // a million cells at most + m_cell = std::max(m_cell, std::sqrt(size.x * size.y / 1e6)); + m_columns = static_cast(std::ceil(size.x / m_cell)); + m_rows = static_cast(std::ceil(size.y / m_cell)); + m_cells.resize(m_columns * m_rows); + auto const column = [this](double const X) { return static_cast(std::clamp(std::floor((X - m_min.x) / m_cell), 0.0, static_cast(m_columns - 1))); }; + auto const row = [this](double const Z) { return static_cast(std::clamp(std::floor((Z - m_min.y) / m_cell), 0.0, static_cast(m_rows - 1))); }; + for (auto const &triangle : Triangles) { + auto const low{glm::min(glm::min(triangle[0], triangle[1]), triangle[2])}; + auto const high{glm::max(glm::max(triangle[0], triangle[1]), triangle[2])}; + if (high.x < m_min.x || low.x > m_max.x || high.z < m_min.y || low.z > m_max.y) { + continue; + } + auto const index{m_triangles.size()}; + m_triangles.push_back(triangle); + for (auto r = row(low.z); r <= row(high.z); ++r) { + for (auto c = column(low.x); c <= column(high.x); ++c) { + m_cells[r * m_columns + c].push_back(index); + } + } + } +} + +bool mesh_ground::covers(double const X, double const Z) const { + return X >= m_min.x && X <= m_max.x && Z >= m_min.y && Z <= m_max.y; +} + +bool mesh_ground::covers(glm::dvec2 const &Min, glm::dvec2 const &Max) const { + return Min.x >= m_min.x && Min.y >= m_min.y && Max.x <= m_max.x && Max.y <= m_max.y; +} + +mesh_ground mesh_ground::cropped(glm::dvec2 const &Min, glm::dvec2 const &Max) const { + return mesh_ground{m_triangles, Min, Max, m_cell}; +} + +std::optional mesh_ground::cell_of(double const X, double const Z) const { + if (false == covers(X, Z) || m_cells.empty()) { + return std::nullopt; + } + auto const column{std::min(static_cast((X - m_min.x) / m_cell), m_columns - 1)}; + auto const row{std::min(static_cast((Z - m_min.y) / m_cell), m_rows - 1)}; + return row * m_columns + column; +} + +std::optional mesh_ground::height(double const X, double const Z, double const Ceiling) const { + auto const cell{cell_of(X, Z)}; + if (false == cell.has_value()) { + return std::nullopt; + } + std::optional highest; + for (auto const index : m_cells[*cell]) { + auto const found{height_in(m_triangles[index], X, Z)}; + if (found.has_value() && *found <= Ceiling && (false == highest.has_value() || *found > *highest)) { + highest = found; + } + } + return highest; +} + +double formation::height(double const X, double const Z) const { + auto const across{std::abs(glm::dot(glm::dvec3{X, 0.0, Z} - glm::dvec3{point.x, 0.0, point.z}, left_of(level(direction))))}; + auto const top{point.y - depth}; + if (across <= half_width) { + return top; + } + return top - (across - half_width) / std::max(slope, 0.1); +} + +std::optional site::height(double const X, double const Z, double const Ceiling) const { + auto const bed{m_bed.height(X, Z)}; + std::optional result; + if (m_terrain == nullptr) { + // no terrain: level with the top of the ballast + result = m_bed.point.y - m_bed.depth; + } + else { + result = m_terrain->height(X, Z, Ceiling); + } + if (bed <= Ceiling && (false == result.has_value() || bed > *result)) { + result = bed; + } + return result; +} + +// ---- the vehicle + +void body::begin(start const &Start, vehicle_shape const &Shape, ground const &Ground, scatter const &Scatter) { + *this = body{}; + m_active = true; + m_reason = Start.reason; + m_shape = Shape; + m_scatter = Scatter; + // the body a box turning about its middle + m_yawgyration = std::max((Shape.length * Shape.length + Shape.width * Shape.width) / 12.0, 1.0); + + m_pivot = 0.5 * std::max(Shape.contact_spacing, 0.5); + auto const centre{std::max(Shape.centre_of_gravity, 0.3)}; + m_lever = centre + Shape.flexibility * std::max(0.0, centre - Shape.roll_centre); + m_tipangle = std::atan2(m_pivot, m_lever); + m_reach = std::hypot(m_pivot, m_lever); + // the body a box rolling about its middle, carried over to the wheels it tips about + m_gyration = m_reach * m_reach + (Shape.width * Shape.width + Shape.height * Shape.height) / 12.0; + + m_position = Start.position; + m_origin = Start.position; + m_front = level(Start.front); + m_line = level(Start.line, m_front); + m_speed = Start.speed; + // out of the curve, the way it travels + auto const direction{Start.speed < 0.0 ? -1.0 : 1.0}; + auto turn{Start.outward * direction * departure_angle(Start.reason, Start.speed, Start.acceleration)}; + if (Start.reason != cause::end_of_track && Start.reason != cause::collision) { + turn += Scatter.departure; + } + m_front = level(turned(m_front, world_up, turn), m_front); + m_axis = level(turned(m_front, world_up, Scatter.yaw), m_front); + + if (Start.reason == cause::overturned) { + m_guided = true; + m_outward = Start.outward != 0 ? Start.outward : 1; + m_guideacceleration = std::abs(Start.acceleration); + m_guidespeed = std::max(std::abs(Start.speed), 0.1); + } + else { + m_yawrate = Scatter.yaw_rate; + } + auto const foot{find_footing(Ground)}; + m_pitch = foot.grade; + m_grade = foot.grade; + m_cross = foot.cross; + place(); +} + +void body::step(double const Dt, double const Distance, double const Speed, ground const &Ground, std::array const &Ends) { + if (false == m_active || Dt <= 0.0) { + return; + } + // where the forces of the couplings act on the body, which turns under them through the step + for (std::size_t end = 0; end < Ends.size(); ++end) { + glm::dvec3 const arm{Ends[end].point.x - m_position.x, 0.0, Ends[end].point.z - m_position.z}; + m_ends[end].force = glm::dvec3{Ends[end].force.x, 0.0, Ends[end].force.z}; + m_ends[end].along = glm::dot(arm, m_axis); + m_ends[end].across = glm::dot(arm, left_of_heading()); + } + auto const steps{std::max(1, static_cast(std::ceil(Dt / substep - 1e-9)))}; + auto const dt{Dt / steps}; + auto const startspeed{m_speed}; + // the heading turned about within the step goes the other way along with the rest of the step + auto direction{1.0}; + for (int index = 1; index <= steps; ++index) { + auto const speed{std::lerp(startspeed, direction * Speed, static_cast(index) / steps)}; + auto const reversals{m_reversals}; + advance(dt, direction * Distance / steps, speed, Ground); + if (m_reversals != reversals) { + direction = -direction; + } + } + m_speed = direction * Speed; + place(); +} + +void body::advance(double const Dt, double const Distance, double const Speed, ground const &Ground) { + m_position += m_front * Distance + left_of_heading() * (m_lateral * Dt); + m_travelled += std::hypot(Distance, m_lateral * Dt); + m_time += Dt; + auto const foot{find_footing(Ground)}; + m_pitch = foot.grade; + // along the way it goes: of the slope along the body and across it + m_grade = foot.grade * glm::dot(m_front, m_axis) + foot.cross * glm::dot(m_front, left_of_heading()); + m_cross = foot.cross; + fall(Dt, foot.level, std::hypot(Distance, m_lateral * Dt)); + slide(Dt, foot.cross); + tip(Dt, foot.cross, Speed); + turn(Dt, Speed); + if (m_guided) { + m_guidetime += Dt; + if (m_tipping >= m_tipangle || std::abs(Speed) < 0.5 || m_guidetime > guidance_time) { + m_guided = false; + } + } +} + +body::footing body::find_footing(ground const &Ground) const { + auto const left{left_of_heading()}; + // a step up under the middle, and as much more under a support away from it as a slope of 2 in 1 rises: what is + // higher is over the vehicle, not under it (a bridge, a roof), and the ground under the slope of a bank isn't the + // ground the support stands on + constexpr double steepest{2.0}; + auto const sample = [&Ground, this](glm::dvec3 const &Point) { + auto const reach{std::hypot(Point.x - m_position.x, Point.z - m_position.z)}; + return Ground.height(Point.x, Point.z, m_position.y + step_up + steepest * reach).value_or(m_position.y); + }; + auto const ahead{m_axis * (0.5 * std::max(m_shape.base, 1.0))}; + // upright it stands on its wheels; tipping over, it comes to rest on the side of its body, which reaches out + // from the wheels it tips about as far as the body is high + auto const lean{std::sin(m_tipping)}; + auto const middle{left * (m_side * lean * 0.5 * m_shape.height)}; + auto const span{m_pivot + lean * std::max(0.0, 0.5 * m_shape.height - m_pivot)}; + auto const aside{left * span}; + auto const frontleft{sample(m_position + middle + ahead + aside)}; + auto const frontright{sample(m_position + middle + ahead - aside)}; + auto const rearleft{sample(m_position + middle - ahead + aside)}; + auto const rearright{sample(m_position + middle - ahead - aside)}; + footing result; + result.level = std::max(0.25 * (frontleft + frontright + rearleft + rearright), sample(m_position)); + // a step under one support is no slope steeper than 2 in 1 + result.grade = std::clamp((frontleft + frontright - rearleft - rearright) / (2.0 * std::max(m_shape.base, 1.0)), -steepest, steepest); + result.cross = std::clamp((frontleft + rearleft - frontright - rearright) / (4.0 * span), -steepest, steepest); + return result; +} + +void body::fall(double const Dt, double const Level, double const Travel) { + // on the ground it follows it down a slope as steep as 1:1.5; off a steeper drop it falls + constexpr double follows{1.0 / 1.5}; + if (m_grounded && m_position.y - Level <= std::max(0.02, follows * Travel)) { + m_position.y = Level; + return; + } + m_fallspeed -= gravity * Dt; + auto const height{m_position.y + m_fallspeed * Dt}; + m_grounded = (height <= Level); + if (m_grounded) { + m_position.y = Level; + m_fallspeed = 0.0; + } + else { + m_position.y = height; + } +} + +void body::slide(double const Dt, double const Cross) { + if (false == m_grounded) { + // in the air nothing holds it, nor pushes it + return; + } + auto const angle{std::atan(Cross)}; + // down the slope, to the left positive; held by the friction of its weight on the slope + m_lateral -= gravity * std::sin(angle) * Dt; + auto const held{lateral_friction * gravity * std::cos(angle) * Dt}; + if (std::abs(m_lateral) <= held) { + m_lateral = 0.0; + } + else { + m_lateral -= sign_of(m_lateral) * held; + } +} + +double body::lateral_load(double const Cross, double const Speed) const { + auto const angle{std::atan(Cross)}; + auto load{0.0}; + if (m_grounded) { + if (m_lateral != 0.0) { + // sliding across, the friction under its wheels or its side trips it the way it slides + load = sign_of(m_lateral) * lateral_friction * gravity * std::cos(angle); + } + else { + // standing on the slope, the weight pulls it down the slope, the friction holds its feet + load = -gravity * std::sin(angle); + } + // going askew, the friction across it trips it too + load += m_trip; + } + if (m_guided) { + auto const share{Speed / m_guidespeed}; + load += m_outward * m_guideacceleration * share * share; + } + return load; +} + +void body::tip(double const Dt, double const Cross, double const Speed) { + if (lying()) { + return; + } + auto const normal{gravity * std::cos(std::atan(Cross))}; + auto const load{lateral_load(Cross, Speed)}; + if (m_side == 0) { + // upright: it starts to tip once the load lifts the wheels of the other side + if (std::abs(load) * std::cos(m_tipangle) - normal * std::sin(m_tipangle) <= 0.0) { + return; + } + m_side = load > 0.0 ? 1 : -1; + } + auto const angle{m_tipping - m_tipangle}; + auto const acceleration{m_reach / m_gyration * (m_side * load * std::cos(angle) + normal * std::sin(angle))}; + m_tiprate += acceleration * Dt; + m_tipping += m_tiprate * Dt; + if (m_tipping <= 0.0) { + // back on its wheels + m_tipping = 0.0; + m_tiprate = 0.0; + m_side = 0; + } + else if (m_tipping >= half_turn) { + // on its side, where it stays + m_tipping = half_turn; + m_tiprate = 0.0; + } +} + +glm::dvec3 body::left_of_heading() const { + return left_of(m_axis); +} + +double body::friction_along() const { + return sliding_friction(m_tipping, m_guided); +} + +double body::friction_across() const { + return m_guided ? guided_friction : std::max(lateral_friction, friction_along()); +} + +double body::friction_share(bool const Front) const { + return Front ? m_scatter.friction_front : m_scatter.friction_rear; +} + +int body::biting() const { + if (m_scatter.dig_in < 0.0 || m_guided || false == m_grounded || m_time < m_scatter.dig_in || m_time >= m_scatter.dig_in + m_scatter.dig_in_time) { + return 0; + } + // the end it goes towards + auto const going{m_speed < 0.0 ? -m_front : m_front}; + return glm::dot(going, m_axis) >= 0.0 ? 1 : -1; +} + +double body::friction() const { + auto const along{glm::dot(m_front, m_axis)}; + auto const across{1.0 - along * along}; + auto result{0.5 * (friction_share(true) + friction_share(false)) * (friction_along() * along * along + friction_across() * across)}; + if (biting() != 0) { + // under half of its weight + result += 0.5 * (m_scatter.dig_in_friction - 1.0) * friction_along(); + } + return result; +} + +glm::dvec3 body::velocity() const { + return m_front * m_speed + left_of_heading() * m_lateral; +} + +void body::kick(glm::dvec3 const &Velocity, double const YawRate) { + if (false == m_active) { + return; + } + auto const moving{m_front * m_speed + glm::dvec3{Velocity.x, 0.0, Velocity.z}}; + auto const speed{glm::length(moving)}; + if (speed > 1e-6) { + m_front = moving / speed; + m_speed = speed; + if (glm::dot(m_front, m_axis) < 0.0) { + // it goes rear first + m_front = -m_front; + m_speed = -m_speed; + ++m_reversals; + } + } + else { + m_speed = 0.0; + } + m_yawrate = std::clamp(m_yawrate + YawRate, -most_yaw_rate, most_yaw_rate); +} + +void body::nudge(glm::dvec3 const &Offset) { + if (false == m_active) { + return; + } + m_position += glm::dvec3{Offset.x, 0.0, Offset.z}; + place(); +} + +double body::yaw() const { + return angle_between(m_line, m_axis); +} + +body::drag body::friction_under(double const Speed, double const Yawrate) const { + drag result; + if (false == m_grounded) { + // nothing holds it in the air + return result; + } + auto const left{left_of_heading()}; + auto const along{friction_along()}; + auto const across{friction_across()}; + // upright it stands on its bogies (the ends of its base), on its side it lies along all of its length + auto const share{std::clamp(m_tipping / half_turn, 0.0, 1.0)}; + auto const base{std::max(m_shape.base, 1.0)}; + auto const span{std::max(m_shape.length, base)}; + auto const velocity{m_front * Speed}; + auto const point = [&](double const Along, double const Across, double const Weight) { + // the friction under a point of the body: against the way it slides there, along the body and across it as each + // holds; slower than the creep, as much as it slides + auto const motion{velocity + left * (Yawrate * Along) - m_axis * (Yawrate * Across)}; + auto const speed{std::max(glm::length(motion), creep_speed)}; + auto const force{-(gravity * Weight) * (along * glm::dot(motion, m_axis) * m_axis + across * glm::dot(motion, left) * left) / speed}; + result.force += force; + // about the vertical, to the left positive + result.moment += Along * glm::dot(force, left) - Across * glm::dot(force, m_axis); + }; + if (share < 1.0) { + for (auto const end : {1.0, -1.0}) { + point(end * 0.5 * base, 0.0, (1.0 - share) * 0.5 * friction_share(end > 0.0)); + } + } + if (share > 0.0) { + for (int index = 0; index < friction_points; ++index) { + auto const along_body{span * ((index + 0.5) / friction_points - 0.5)}; + point(along_body, 0.0, share * friction_share(along_body > 0.0) / friction_points); + } + } + if (auto const end{biting()}; end != 0) { + // the leading end bites into the ballast at one of its wheels, under half of its weight; on its side, at a corner + // of its body + point(end * 0.5 * std::lerp(base, 0.5 * span, share), m_scatter.dig_in_side * std::lerp(m_pivot, 0.5 * m_shape.height, share), 0.5 * (m_scatter.dig_in_friction - 1.0)); + } + // the way it slides across, the friction trips it + result.trip = -glm::dot(result.force, left); + return result; +} + +void body::turn(double const Dt, double const Speed) { + // the forces of the couplings, per the mass + auto const left{left_of_heading()}; + auto moment{0.0}; + glm::dvec3 push{0.0}; + if (m_shape.mass > 0.0) { + for (auto const &end : m_ends) { + auto const arm{m_axis * end.along + left * end.across}; + moment += (arm.z * end.force.x - arm.x * end.force.z) / m_shape.mass; + push += end.force / m_shape.mass; + } + } + if (m_guided) { + // on its outer wheels on the rail it goes along the rail + m_yawrate = 0.0; + m_trip = 0.0; + return; + } + // the body: the couplings turn it, and the friction under it where it differs between the ends of a body going + // askew; the friction holds it against turning, never turning it back the other way + auto const driving{friction_under(Speed, 0.0).moment}; + auto rate{m_yawrate + (moment + driving) / m_yawgyration * Dt}; + auto const change{(friction_under(Speed, rate).moment - driving) / m_yawgyration * Dt}; + rate = ((rate + change) * rate <= 0.0 ? 0.0 : rate + change); + if (std::abs(Speed) < creep_speed && m_lateral == 0.0 && std::abs(rate) < 0.01 && m_grounded) { + // at a standstill it doesn't turn as long as the friction under it holds against the couplings + // on its bogies at half the base from the middle, lying along the length a quarter of it on average + auto const share{std::clamp(m_tipping / half_turn, 0.0, 1.0)}; + auto const arm{std::lerp(0.5 * std::max(m_shape.base, 1.0), 0.25 * std::max(m_shape.length, m_shape.base), share)}; + if (std::abs(moment) <= gravity * friction_across() * arm) { + rate = 0.0; + } + } + m_yawrate = std::clamp(rate, -most_yaw_rate, most_yaw_rate); + m_axis = level(turned(m_axis, world_up, m_yawrate * Dt), m_axis); + + // the way it travels: the friction of the body going askew turns it towards the body (no further), the couplings + // pushing across it turn it their way; the faster it goes, the less + auto const drag{friction_under(Speed, m_yawrate)}; + m_trip = drag.trip; + if (m_grounded && std::abs(Speed) >= turning_speed) { + auto const across{left_of(m_front)}; + auto const off{angle_between(m_front, glm::dot(m_front, m_axis) >= 0.0 ? m_axis : -m_axis)}; + auto byfriction{glm::dot(drag.force, across) * Dt / Speed}; + byfriction = (byfriction * off <= 0.0 ? 0.0 : sign_of(off) * std::min(std::abs(byfriction), std::abs(off))); + auto const bypush{glm::dot(push, across) * Dt / Speed}; + auto const turning{std::clamp(byfriction + bypush, -most_yaw_rate * Dt, most_yaw_rate * Dt)}; + m_front = level(turned(m_front, world_up, turning), m_front); + } + if (glm::dot(m_front, m_axis) < 0.0) { + // the body turned past a right angle off the way it goes: it goes rear first, the heading the other way + m_front = -m_front; + m_speed = -m_speed; + ++m_reversals; + } +} + +double body::roll() const { + // the ground rising to the left leans it to the right + return tipping() - std::atan(m_cross); +} + +double body::along() const { + return glm::dot(m_position - m_origin, m_line); +} + +double body::across() const { + return glm::dot(m_position - m_origin, left_of(m_line)); +} + +bool body::at_rest() const { + return m_active && m_grounded && std::abs(m_speed) < 0.01 && m_lateral == 0.0 && m_tiprate == 0.0 && m_yawrate == 0.0 && false == m_guided; +} + +void body::place() { + // the plane of the ground under the supports + auto const front{glm::normalize(m_axis + world_up * m_pitch)}; + auto const flatleft{glm::normalize(left_of_heading() + world_up * m_cross)}; + auto const up{glm::normalize(glm::cross(front, flatleft))}; + auto const left{glm::cross(up, front)}; + // tipped about the wheels of its side: turned about the front, the up going over to that side + auto const angle{-m_side * m_tipping}; + auto const pivot{m_position + left * (m_side * m_pivot)}; + auto origin{pivot + turned(m_position - pivot, front, angle)}; + auto const tippedleft{turned(left, front, angle)}; + auto const tippedup{turned(up, front, angle)}; + // the body doesn't go into the ground: the lowest of the edges of its box on it, from the rails to its roof + auto lowest{std::numeric_limits::max()}; + for (auto const across : {-0.5 * m_shape.width, 0.5 * m_shape.width}) { + for (auto const height : {0.0, m_shape.height}) { + lowest = std::min(lowest, glm::dot(origin + tippedleft * across + tippedup * height - m_position, up)); + } + } + if (lowest < 0.0) { + origin -= up * lowest; + } + m_pose.position = origin; + m_pose.front = front; + m_pose.left = tippedleft; + m_pose.up = tippedup; +} + +} // namespace derail_motion diff --git a/vehicle/derailmotion.h b/vehicle/derailmotion.h new file mode 100644 index 000000000..20c89747f --- /dev/null +++ b/vehicle/derailmotion.h @@ -0,0 +1,496 @@ +/* +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 + +#include +#include +#include +#include +#include +#include +#include + +#include + +// a rail vehicle off the rails (physics.derailment new, see physics/derailment.h for when it derails): from then on +// it doesn't follow the track any more, it moves on the ground by itself until the friction stops it. +// +// along: the longitudinal motion stays with the physics of the vehicle (physics::Vehicle), which brakes it with the +// friction() of this one, takes the grade() under it and passes the forces of the couplings on; each step gives +// the distance travelled along the heading of the vehicle +// the heading: the way it travels; the one the vehicle had when it derailed, turned out of the curve by the sideways +// speed it left the rail with: none off the end of the track, the speed of the flange climbing over the rail head +// (or of the wheels lifting over it) otherwise. so in a curve it leaves the track to its outside, on a buckle +// towards the bulge. from then on the friction of a body sliding askew (more across it than along it) and the +// sideways part of the forces of its couplings turn it, little at speed +// the yaw: the body turns about its vertical axis by itself, apart from the way it travels: the forces of the +// couplings at its ends (the push of the buffers of two bodies at an angle to each other, off the middle of the +// buffer beam) turn it, the friction of the ground under the length of it holds it. pushed from behind, a train +// of bodies off the track folds up into a zigzag once the bends between them are past what the buffers hold +// sideways: the vehicle slides across its heading only where the ground slopes across it more than the friction +// holds, down an embankment say +// the height and the attitude: the ground under the supports of the vehicle (the ends of its wheelbase, the wheels +// of both sides) gives its height, its pitch and its roll; it doesn't sink into the ground, it falls off a step +// tipping over: about the wheels of one side, the body as a rigid one with the lean of its suspension, so it tips at +// the very lateral acceleration the wheel unloading of physics/derailment.h reaches 1 at. what tips it: the +// overturning in the curve while its outer wheels still run on the rail (the curve keeps pushing it out as v^2/R, +// the excess over the limit the faster it tips), the slope of the ground across it, and the friction under it +// while it slides sideways. once over its tipping angle it falls on its side, at 90 degrees, and stays there +// +// the steps are cut to 0.01 s inside, so the result doesn't depend on the step of the simulation +namespace derail_motion { + +inline constexpr double gravity{9.81}; // [m/s2] +// the longest step of the motion [s] +inline constexpr double substep{0.01}; + +// what put the vehicle off the rails, for the way it leaves the track +enum class cause { + off_rails, // the flange climbed the rail + overturned, // the vehicle fell over out of the curve + end_of_track, // it ran off the end of the track: straight on + pulled_off, // the coupling of a vehicle off the track pulled it off sideways + collision // overriding, or pushed off the track in a collision: straight on +}; + +// ---- the friction [-] + +// of a vehicle tipping over on its outer wheels, which still roll on the outer rail +inline constexpr double guided_friction{0.1}; +// of the wheels, or of the body on its side, sliding across the heading +inline constexpr double lateral_friction{0.5}; +// the friction along the heading: upright on its wheels on the sleepers and the ballast, rising to the friction of a +// vehicle on its side (physics/derailment.h) as it tips over +double sliding_friction(double Tipping, bool Guided); + +// ---- the way the vehicle leaves the track + +// how far the flange or the wheel goes sideways over the head of the rail before it drops off it [m] +inline constexpr double climb_width{0.1}; +// the largest angle the vehicle turns off the track by [rad] +inline constexpr double most_departure{0.2}; +// the angle [rad] the heading turns out of the curve by: the sideways speed sqrt(2 a w) the lateral acceleration a +// [m/s2] gives the wheels over the climb width w, against the speed [m/s]. none off the end of the track or in a +// collision +double departure_angle(cause Cause, double Speed, double Acceleration); + +// ---- the scatter: what differs from one derailed vehicle to the next + +// the ground under it and the way it bites into the ballast: each vehicle draws its own from the seed of the run and its +// name, so a run with the same seed goes the same way and one with another seed another way +struct scatter { + double departure{0.0}; // added to the angle it leaves the track at [rad], not off the end of the track nor in a collision + double yaw{0.0}; // its body turned off the way it travels when it leaves the rails [rad], to the left positive + double yaw_rate{0.0}; // [rad/s] the kick of the leading wheels dropping off the rail head + double friction_front{1.0}; // the friction under the front half of its body, of the friction of the motion + double friction_rear{1.0}; // and under the rear half + double dig_in{-1.0}; // the time after leaving the rails its leading end digs into the ballast [s], -1 never + double dig_in_time{0.0}; // for how long [s] + double dig_in_friction{1.0}; // the friction under the leading half then, of the friction of the motion + int dig_in_side{1}; // the wheel that digs in: 1 the left one of the leading end, -1 the right one +}; +// the scatter of a vehicle: departure angle +-0.01 rad, yaw +-0.02 rad, yaw rate +-0.02 rad/s, the friction under each +// half 0.85..1.15 of the friction of the motion, and in two of three vehicles a bite of the leading end 0.2..1.5 s after +// it left the rails, for 0.3..0.8 s, the friction under that half 2..4 times the friction of the motion then +scatter draw_scatter(std::uint32_t Seed); +// the seed of a vehicle: of the seed of the run and its name +std::uint32_t seed_of(std::uint32_t Run, std::string_view Name); + +// ---- the buffers and the couplings of two vehicles, one of them off the track at least + +// the height of the middle of the buffer beam above the rails [m]: UIC, 940..1065 mm +inline constexpr double buffer_height{1.0}; +// half the spacing of the buffers [m]: UIC, 1750 mm +inline constexpr double buffer_half_spacing{0.875}; +// the height of a buffer head [m]: two buffers further apart in height than that miss each other +inline constexpr double buffer_head{0.34}; +// the bend between two bodies [rad] the push of the buffers goes all onto the inner buffer at: their play, 45 mm of +// difference over the spacing +inline constexpr double buffer_lock{0.05}; +// the most a buffer takes [N]: past it, it is pressed solid and gives way, the frames push against each other at +// the middle of the beams +inline constexpr double buffer_limit{1.0e6}; + +// an end of a vehicle, where it meets the vehicle coupled to it +struct end_point { + glm::dvec3 point{0.0}; // the middle of the buffer beam, at the height of the buffers + glm::dvec3 outward{0.0, 0.0, 1.0}; // the way the end faces, level + // how far the body is rolled [rad]: the buffers of two bodies rolled apart miss each other in height + double roll{0.0}; +}; +// a force on a body [N], at the point it acts at +struct end_force { + glm::dvec3 force{0.0}; + glm::dvec3 point{0.0}; +}; +// two ends meeting, as the first sees it +struct meeting { + // apart [m], negative where the buffers press into each other: along the bisector of the bend while they touch, + // the distance between the middles of the beams once they are apart + double gap{0.0}; + // the bend: the angle [rad] the second body turns off the axis of the first, to the left of its end positive + double bend{0.0}; + glm::dvec3 push{0.0, 0.0, 1.0}; // outwards from the first, the bisector of the bend: the buffers push the other way + glm::dvec3 pull{0.0, 0.0, 1.0}; // the way the coupling draws the first: to the beam of the second + glm::dvec3 point{0.0}; // the middle of the beam of the first + // how well the buffers meet in height: 0 they miss each other (one body lower than the other, or rolled against it), to 1 + double overlap{1.0}; +}; +meeting meet(end_point const &First, end_point const &Second); +// the force on the first end of the meeting, Compression [N] pushing it (negative: the coupling pulling it): through +// the inner buffer of the bend, off the middle of the beam as far as the buffers meet and hold +end_force force_on(meeting const &Meeting, double Compression); + +// ---- the bodies of two vehicles running into each other, one of them off the track at least + +// how far the buffers and the coupling stand out of the body at each end [m]: the body box is shorter by them, so two +// ends meeting through their buffers (meet(), force_on()) don't touch as bodies until the buffers are pressed in by that +inline constexpr double buffer_length{0.6}; +// the least overlap in height [m] two bodies run into each other with: lower, one goes over the other +inline constexpr double height_overlap{0.2}; +// the bodies part after a hit with this share of the speed they met at +inline constexpr double contact_restitution{0.2}; +// the friction of the side of one body sliding along the other +inline constexpr double contact_friction{0.3}; +// the overlap left after a hit, taken out of it by moving the bodies apart: what is over the slop [m], this share of it +// a step +inline constexpr double contact_slop{0.02}; +inline constexpr double contact_correction{0.8}; + +// where a body stands on the ground: the rectangle under its box (the box of the body, the buffers left out, rolled and +// pitched as it lies, seen from above along its level axis), and the height it reaches from and to +struct footprint { + glm::dvec3 centre{0.0}; // of the rectangle, level + glm::dvec3 axis{0.0, 0.0, 1.0}; // along the body, level + double half_length{10.0}; + double half_width{1.5}; + double low{0.0}; // [m] the lowest and the highest point of the box + double high{4.0}; +}; +struct pose; +// the footprint of the body of Length (over the buffers), Width and Height (above the rails) in the Pose +footprint footprint_of(pose const &Pose, double Length, double Width, double Height); +// two bodies in each other: how deep (the least the rectangles overlap across any of their sides), the way out of the +// first into the second (level), and the point they touch at +struct contact { + double depth{0.0}; + glm::dvec3 normal{1.0, 0.0, 0.0}; + glm::dvec3 point{0.0}; +}; +std::optional collide(footprint const &First, footprint const &Second); +// a body in a contact, for the impulse: its mass, the velocity of its middle (base) and how fast it turns; on the rails +// it moves only along the track (Guided: along the Guide), not turning +struct contact_body { + double mass{0.0}; // [kg], none: it doesn't move + glm::dvec3 base{0.0}; + glm::dvec3 velocity{0.0}; + double yaw_rate{0.0}; + double gyration{30.0}; // the square of its radius of gyration about the vertical [m2] + bool guided{false}; + glm::dvec3 guide{0.0, 0.0, 1.0}; +}; +// the velocity of the point of the body [m/s] +glm::dvec3 velocity_at(contact_body const &Body, glm::dvec3 const &Point); +// the impulse [N s] on the second body of the contact (the first gets the opposite one): it stops the two closing in on +// each other at the point, parting them with the restitution, and the friction holds them sliding along each other +glm::dvec3 contact_impulse(contact const &Contact, contact_body const &First, contact_body const &Second); +// the change of the velocity [m/s] and of the yaw rate [rad/s] of the body by the impulse at the point +std::pair impulse_change(contact_body const &Body, glm::dvec3 const &Impulse, glm::dvec3 const &Point); + +// the distance [m] a vehicle slides from the speed [m/s] with the friction, on the grade (rise per metre along the +// way); none when the grade doesn't let it stop +std::optional stopping_distance(double Speed, double Friction, double Grade = 0.0); + +// the Y/Q of the leading wheel of an end of a vehicle which the coupling pulls (or pushes) at the angle [rad] to its +// axis with the force [N]: the part across, taken by the axles of that end (half of them), against the static load of +// a wheel of the vehicle of the mass [kg] +double pull_ratio(double Force, double Angle, double Mass, int Axles); + +// ---- the ground + +// where the vehicle can find the ground +class ground { +public: + virtual ~ground() = default; + // the height of the ground at (X, Z): of the highest surface there at or under Ceiling; none where there is none + virtual std::optional height(double X, double Z, double Ceiling) const = 0; +}; + +// level everywhere +class flat_ground final : public ground { +public: + explicit flat_ground(double Level) : m_level{Level} {} + std::optional height(double X, double Z, double Ceiling) const override; + +private: + double m_level; +}; + +// the triangles of the terrain of the scenery, kept in square cells for the lookup +class mesh_ground final : public ground { +public: + using triangle = std::array; + // the triangles which reach into the rectangle from Min to Max (x, z), in cells of the size [m] + mesh_ground(std::vector const &Triangles, glm::dvec2 const &Min, glm::dvec2 const &Max, double Cell = 8.0); + std::optional height(double X, double Z, double Ceiling) const override; + // whether the point is inside the rectangle the triangles were taken for + bool covers(double X, double Z) const; + // whether the rectangle from Min to Max (x, z) is inside the one the triangles were taken for + bool covers(glm::dvec2 const &Min, glm::dvec2 const &Max) const; + // the ground of a smaller area: the triangles which reach into the rectangle from Min to Max (x, z) + mesh_ground cropped(glm::dvec2 const &Min, glm::dvec2 const &Max) const; + std::size_t size() const { return m_triangles.size(); } + glm::dvec2 const &minimum() const { return m_min; } + glm::dvec2 const &maximum() const { return m_max; } + +private: + std::optional cell_of(double X, double Z) const; + + std::vector m_triangles; + std::vector> m_cells; // the triangles reaching into each cell + glm::dvec2 m_min; + glm::dvec2 m_max; + double m_cell; + std::size_t m_columns{0}; + std::size_t m_rows{0}; +}; + +// the bed of the track at the place nearest to the vehicle: the top of the ballast under the rails, level out to the +// edge of the formation, then the slope of the embankment going down +struct formation { + glm::dvec3 point{0.0}; // on the axis of the track, at the height of the rails + glm::dvec3 direction{0.0, 0.0, 1.0}; // of the axis + double depth{0.2}; // of the top of the ballast under the rails [m] + double half_width{2.0}; // from the axis to the edge of the top [m] + double slope{1.5}; // run of the slope per metre of fall: 1:1.5, of an embankment + double height(double X, double Z) const; +}; + +// the ground as the vehicle finds it: the terrain of the scenery where it has any, level with the top of the ballast +// where it has none (a scenery without terrain), and the bed of the track over it +class site final : public ground { +public: + explicit site(ground const *Terrain = nullptr, formation const &Bed = {}) : m_terrain{Terrain}, m_bed{Bed} {} + void terrain(ground const *Terrain) { m_terrain = Terrain; } + // the bed moves along the track with the vehicle + void bed(formation const &Bed) { m_bed = Bed; } + formation const &bed() const { return m_bed; } + std::optional height(double X, double Z, double Ceiling) const override; + +private: + ground const *m_terrain; + formation m_bed; +}; + +// ---- the vehicle + +// what of the vehicle the motion takes +struct vehicle_shape { + double length{20.0}; // over the buffers [m] + double width{3.0}; // of the body [m] + double height{4.0}; // of the body above the rail [m] + double centre_of_gravity{1.5}; // its height above the rail [m] + double contact_spacing{1.5}; // of the wheels of a wheelset [m] + double base{10.0}; // between the bogie pivots or the outer axles, which it rests on lengthwise [m] + // the lean of the body on the suspension, as physics/derailment.h takes it: flexibility and roll centre + double flexibility{0.4}; + double roll_centre{0.5}; + // [kg] for the forces of the couplings on it; none: they don't move it + double mass{0.0}; +}; + +// how it left the rails +struct start { + glm::dvec3 position{0.0}; // of the vehicle, at the height of the rails + glm::dvec3 front{0.0, 0.0, 1.0}; // the way its front faces + glm::dvec3 line{0.0, 0.0, 1.0}; // the direction of the track there, to measure the offset across it by + double speed{0.0}; // along the front [m/s] + cause reason{cause::off_rails}; + // the outer side of the curve of the line under it: 1 to the left of its front, -1 to the right, 0 straight + int outward{0}; + double acceleration{0.0}; // the lateral acceleration of the body when it derailed, out of the curve [m/s2] +}; + +// where the body is and how it lies: the origin of its model, at the height of the rails between its wheels when +// upright, and its axes +struct pose { + glm::dvec3 position{0.0}; + glm::dvec3 front{0.0, 0.0, 1.0}; + glm::dvec3 left{1.0, 0.0, 0.0}; + glm::dvec3 up{0.0, 1.0, 0.0}; +}; + +class body { +public: + // the vehicle leaves the rails, set apart from the others by the Scatter + void begin(start const &Start, vehicle_shape const &Shape, ground const &Ground, scatter const &Scatter = {}); + // the step of Dt [s], in which the vehicle travelled Distance [m] along its heading (forwards along its front) and + // has the Speed [m/s] along it at its end; the couplings of its ends push or pull it with the Ends through the step + void step(double Dt, double Distance, double Speed, ground const &Ground, std::array const &Ends = {}); + // back on the rails, or never off them + void reset() { *this = body{}; } + + bool active() const { return m_active; } + pose const ¤t() const { return m_pose; } + // the middle of the vehicle on the ground, under it as it stands (not moved over to the side it tipped to) + glm::dvec3 const &base() const { return m_position; } + // the speed along the heading [m/s], and the velocity of the middle, level + double speed() const { return m_speed; } + glm::dvec3 velocity() const; + // the square of the radius of gyration about the vertical [m2] + double gyration() const { return m_yawgyration; } + // hit by another body: the velocity and the yaw rate change by these, the heading becomes the way it goes then + // (turned about where it goes rear first); the speed() after it is the one its vehicle goes on with + void kick(glm::dvec3 const &Velocity, double YawRate); + // moved over by the offset (level), out of another body it is in + void nudge(glm::dvec3 const &Offset); + // the friction along the heading now, of its weight: of the body sliding along itself, more the more askew it goes, + // up to the friction across it going sideways + double friction() const; + // the rise of the ground per metre along the heading, for the force of the gravity along it + double grade() const { return m_grade; } + // how far the body tipped over from its wheels [rad], to the left positive; 90 degrees: it lies on its side + double tipping() const { return m_side * m_tipping; } + // the roll of the body against the level [rad], to the left positive: the tipping and the slope across it + double roll() const; + bool lying() const { return m_tipping >= half_turn - 1e-9; } + // still on its outer wheels on the rail, tipping over out of the curve + bool guided() const { return m_guided; } + // the distance it went on the ground since it left the rails [m] + double travelled() const { return m_travelled; } + // from the place it left the rails at: along the line of the track there, and across it, to the left positive [m] + double along() const; + double across() const; + // the speed it slides with sideways, to the left of its front positive [m/s] + double sideways() const { return m_lateral; } + // at rest: not sliding, not tipping, on the ground + bool at_rest() const; + // the way it travels, level + glm::dvec3 const &heading() const { return m_front; } + // the way the front of its body faces, level + glm::dvec3 const &axis() const { return m_axis; } + // the angle [rad] its body is turned by off the line of the track where it left the rails, to the left positive + double yaw() const; + // how fast it turns [rad/s], to the left positive + double yaw_rate() const { return m_yawrate; } + // how many times the heading was turned about, the body having turned more than a right angle off the way it + // goes: the heading stays within a right angle of the front of the body, so the speed along the heading (of + // physics::Vehicle, of its couplers at its ends) goes with the body; the speed changes its sign with each + int reversals() const { return m_reversals; } + cause reason() const { return m_reason; } + // the vehicle the motion was begun with + vehicle_shape const &shape() const { return m_shape; } + + static constexpr double half_turn{1.5707963267948966}; + +private: + // the ground under the supports of the vehicle + struct footing { + double level{0.0}; // under the middle, not under any support + double grade{0.0}; // rise per metre forwards + double cross{0.0}; // rise per metre to the left + }; + + void advance(double Dt, double Distance, double Speed, ground const &Ground); + footing find_footing(ground const &Ground) const; + // down to the ground at the Level, or onto it, having travelled Travel [m] over the ground in the step + void fall(double Dt, double Level, double Travel); + void slide(double Dt, double Cross); + void tip(double Dt, double Cross, double Speed); + // the lateral acceleration [m/s2] on the centre of gravity, to the left positive, in the plane of the ground + double lateral_load(double Cross, double Speed) const; + void place(); + // to the left of the body + glm::dvec3 left_of_heading() const; + // the friction under the body going along its heading at the Speed and turning at the Yawrate, per its mass: the + // force [m/s2], the moment about its middle [m2/s2] and the sideways load that trips it over [m/s2] + struct drag { + glm::dvec3 force{0.0}; + double moment{0.0}; + double trip{0.0}; + }; + drag friction_under(double Speed, double Yawrate) const; + // the friction under the front (Front) or the rear half of the body, of the friction of the motion + double friction_share(bool Front) const; + // the leading end biting into the ballast now: 1 its front, -1 its rear, 0 none + int biting() const; + // the friction along the body and across it + double friction_along() const; + double friction_across() const; + // the body turns, and the way it travels turns, through the substep + void turn(double Dt, double Speed); + + bool m_active{false}; + cause m_reason{cause::off_rails}; + vehicle_shape m_shape; + // the geometry of the tipping: half the spacing of the wheels, the height the lateral force leans the body at, + // the distance of the centre of gravity from the wheels it tips about, the angle it tips over past, and the + // square of the radius of gyration about them + double m_pivot{0.75}; + double m_lever{1.8}; + double m_reach{1.9}; + double m_tipangle{0.4}; + double m_gyration{5.0}; + + glm::dvec3 m_position{0.0}; // of the middle of the vehicle on the ground (at its base) + glm::dvec3 m_front{0.0, 0.0, 1.0}; // the heading, level + glm::dvec3 m_axis{0.0, 0.0, 1.0}; // the front of the body, level + double m_yawrate{0.0}; // [rad/s] + double m_yawgyration{30.0}; // the square of the radius of gyration of the body about its vertical axis [m2] + scatter m_scatter; + double m_time{0.0}; // since it left the rails [s] + int m_reversals{0}; + double m_trip{0.0}; // the load across of the friction of the body going askew [m/s2], the way it slides + // the forces of the couplings through the step: the force, and where it acts, along the body and across it + struct end_load { + glm::dvec3 force{0.0}; + double along{0.0}; + double across{0.0}; + }; + std::array m_ends{}; + glm::dvec3 m_origin{0.0}; // where it left the rails + glm::dvec3 m_line{0.0, 0.0, 1.0}; // the direction of the track there, level + double m_fallspeed{0.0}; // [m/s], downwards negative + // on the ground, not falling. it leaves the rails above the top of the ballast, and drops onto it + bool m_grounded{false}; + double m_lateral{0.0}; // [m/s], to the left positive + double m_grade{0.0}; // along the heading + double m_pitch{0.0}; // along the body + double m_cross{0.0}; + int m_side{0}; // the side it tips to: 1 left, -1 right, 0 upright + double m_tipping{0.0}; // [rad] + double m_tiprate{0.0}; // [rad/s] + // overturning in the curve: the lateral acceleration of the curve at the speed it derailed at, which goes with the + // square of the speed, the side out of the curve, and how long it has been tipping + bool m_guided{false}; + double m_guideacceleration{0.0}; + double m_guidespeed{0.0}; + int m_outward{0}; + double m_guidetime{0.0}; + double m_speed{0.0}; + double m_travelled{0.0}; + pose m_pose; +}; + +// the slowest a point of the body slides at [m/s]: the friction under one going slower holds it as much as it goes +inline constexpr double creep_speed{0.05}; +// the fastest the body turns about its vertical axis [rad/s] +inline constexpr double most_yaw_rate{2.0}; +// the slowest the heading is turned at by the forces across it [m/s]: slower, the vehicle stops where it goes +inline constexpr double turning_speed{0.5}; +// the points the friction under the body is taken at, along it +inline constexpr int friction_points{8}; + +// how long the curve can keep tipping over a vehicle on its outer wheels [s] +inline constexpr double guidance_time{5.0}; +// how high a step up the vehicle can climb onto, for the ground under it [m] +inline constexpr double step_up{1.0}; + +} // namespace derail_motion diff --git a/vehicle/doorwings.h b/vehicle/doorwings.h index 07286aac8..259c85575 100644 --- a/vehicle/doorwings.h +++ b/vehicle/doorwings.h @@ -10,13 +10,26 @@ http://mozilla.org/MPL/2.0/. #pragma once #include +#include +#include +#include +#include +#include +#include +#include #include -// the poses of the animated door wings of a vehicle, for the door position of the mover. a wing is posed alike +// the poses of the animated door wings of a vehicle, for the door position of the physics. a wing is posed alike // in the main model and, when the low poly interior has a submodel of the same name, in the interior as well namespace door_wings { +// the kinds of wing animation, numbered as DoorOpenMethod of the .fiz (physics::door_data::type) +inline constexpr int shift_type{1}; +inline constexpr int rotate_type{2}; +inline constexpr int fold_type{3}; +inline constexpr int plug_type{4}; + // whether the animation with the given flags (TAnim::iFlags, the kind of animation in bits 4-7) moves a door wing inline bool is_wing(int const Flags) { return (Flags & 0xF0) == 0x10; @@ -49,4 +62,145 @@ inline fold_angles fold(float const Position) { return {Position, -Position - Position, Position}; } +// the animation of one wing given in the .mmd, in place of the one the .fiz sets for all door wings of the vehicle +// (eu07/maszyna#70). the wing still follows the door of its side, over its own range: +// animdoor: { type: range: rangeout: } +// every key is optional; a key left out keeps the value of the .fiz +struct wing_spec { + int number{0}; // of the wing, as in animdoorprefix: door1 is 1 + int type{rotate_type}; + float range{0.f}; // shift or angle of the wing when the door is fully open + float range_out{0.f}; // how far a plug wing is pushed out +}; + +// the kind of wing animation with the given name of DoorOpenMethod, in any letter case +inline std::optional type_from_name(std::string_view const Name) { + std::string name{Name}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (name == "shift") { + return shift_type; + } + if (name == "rotate") { + return rotate_type; + } + if (name == "fold") { + return fold_type; + } + if (name == "plug") { + return plug_type; + } + return std::nullopt; +} + +// the number written in the whole of the text, or nothing +inline std::optional number_from_text(std::string const &Text) { + if (Text.empty()) { + return std::nullopt; + } + char *end{nullptr}; + auto const value{std::strtof(Text.c_str(), &end)}; + if (end != Text.c_str() + Text.size() || false == std::isfinite(value)) { + return std::nullopt; + } + return value; +} + +// applies the keys and values of the block of an animdoor entry (the tokens between the braces) to the spec, which +// comes filled with the values of the .fiz. returns what is wrong with the block, or an empty text when nothing is; +// the keys before the fault are applied +inline std::string parse_spec(std::vector const &Tokens, wing_spec &Spec) { + for (std::size_t index = 0; index < Tokens.size(); index += 2) { + std::string key{Tokens[index]}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + if (index + 1 >= Tokens.size()) { + return "no value for \"" + key + "\""; + } + auto const &value{Tokens[index + 1]}; + if (key == "type:") { + auto const type{type_from_name(value)}; + if (false == type.has_value()) { + return "unknown door type \"" + value + "\""; + } + Spec.type = *type; + } + else if (key == "range:" || key == "rangeout:") { + auto const number{number_from_text(value)}; + if (false == number.has_value()) { + return "bad number \"" + value + "\" for \"" + key + "\""; + } + (key == "range:" ? Spec.range : Spec.range_out) = *number; + } + else { + return "unknown key \"" + key + "\""; + } + } + return {}; +} + +// whether the token is one of the keys of an animdoor block, in any letter case +inline bool is_spec_key(std::string const &Token) { + std::string key{Token}; + std::transform(key.begin(), key.end(), key.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return key == "type:" || key == "range:" || key == "rangeout:"; +} + +// reads an animdoor entry after its key: the wing number and the block in braces, into the spec filled with the values +// of the .fiz. returns what is wrong with the entry, or an empty text when nothing is. the parser is a cParser. a block +// without its } ends at the first token that is neither a key nor the value right after one (or at endmodels): that +// token is left for the caller, so the entries after a faulty one are read as ever +template +std::string read_spec(Parser_ &Parser, wing_spec &Spec) { + Parser.getTokens(1, false); + Parser >> Spec.number; + std::string token; + Parser.getTokens(1, false); + Parser >> token; + if (token != "{") { + return "no { after the wing number"; + } + std::vector block; + auto value{false}; // the token is the value of the key before it + while (true) { + token.clear(); + Parser.getTokens(1, false); + Parser >> token; + if (token.empty()) { + return "no } after the keys"; + } + if (token == "}") { + break; + } + if (token == "endmodels" || (false == value && false == is_spec_key(token))) { + Parser.injectString(token); + return "no } after the keys, \"" + token + "\" is none of them"; + } + value = false == value; + block.emplace_back(token); + } + return parse_spec(block, Spec); +} + +// the spec given for the wing with the given number, or null when the wing animates as the .fiz says +inline wing_spec const *find(std::vector const &Specs, int const Number) { + auto const lookup{std::find_if(Specs.begin(), Specs.end(), [Number](wing_spec const &Spec) { return Spec.number == Number; })}; + return lookup != Specs.end() ? &(*lookup) : nullptr; +} + +// keeps the spec of a wing; a later entry for the same wing replaces the earlier one +inline void store(std::vector &Specs, wing_spec const &Spec) { + auto lookup{std::find_if(Specs.begin(), Specs.end(), [&Spec](wing_spec const &Stored) { return Stored.number == Spec.number; })}; + if (lookup != Specs.end()) { + *lookup = Spec; + } + else { + Specs.emplace_back(Spec); + } +} + +// the shift or angle of a wing which opens over Wingrange, while the door of its side opens over Doorrange: the wing +// is as far along its range as the door is along the door range +inline float wing_position(float const Doorposition, float const Doorrange, float const Wingrange) { + return Doorrange != 0.f ? Doorposition / Doorrange * Wingrange : 0.f; +} + } // namespace door_wings diff --git a/vehicle/driverfigure.h b/vehicle/driverfigure.h new file mode 100644 index 000000000..5f25b39ae --- /dev/null +++ b/vehicle/driverfigure.h @@ -0,0 +1,70 @@ +/* +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 + +#include +#include +#include +#include + +// the driver figures of the lowpoly interior, mechanik1 and mechanik2, seen from outside the vehicle (eu07/maszyna#535). +// A vehicle with one desk for both directions (401Da, SM31, TEM2...) has two virtual cabs set up on the same spot, so +// the AI changes the cab to drive the other way and its figure turns round. The player usually stays in the cab and +// only moves the reverser, so in such a vehicle the player's figure follows the selected direction of travel instead. +namespace driver_figure { + +// what the .mmd says about one driver cab, as far as the figures go +struct cab_place { + std::string model; // cabNmodel:, empty when not given + std::optional position; // driverNpos: + std::optional sitting_position; // driverNsitpos: + + // where the driver sits: the sitting position, or the position when the cab gives no sitting position, the way + // the cab is loaded for the player + std::optional seat() const { + return sitting_position.has_value() ? sitting_position : position; + } +}; + +// how close the seats of the two cabs have to be to count as one seat, in metres +inline constexpr float seat_tolerance{0.01f}; + +// the cabs 1 and 2 of the vehicle are the same desk: the .mmd says they share the place and the model (jointcabs:), +// both name the same cab model and both seat the driver on the same spot. A vehicle with two desks in one cab (SM42, +// SP42) seats the driver on the other side of the cab for the other direction, and a vehicle with two cabs has them at +// its two ends, so neither of them is a single desk. +inline bool single_desk(bool const JointCabs, cab_place const &Cab1, cab_place const &Cab2) { + if (false == JointCabs || Cab1.model.empty() || Cab1.model == "none" || Cab1.model != Cab2.model) { + return false; + } + auto const seat1{Cab1.seat()}; + auto const seat2{Cab2.seat()}; + if (false == seat1.has_value() || false == seat2.has_value()) { + return false; + } + return glm::distance(*seat1, *seat2) <= seat_tolerance; +} + +// which of the figures shows: 1 for mechanik1, -1 for mechanik2, 0 for neither. +// Cab: the occupied cab (CabOccupied: 1, -1 or 0). +// Direction: the selected direction of travel against the couplers (DirAbsolute: 1, -1 or 0). +// FollowsDirection: the figure follows the direction rather than the cab, that is a player drives a single desk vehicle. +// Without a direction selected the figure of the occupied cab shows, as it always did. +inline int shown(int const Cab, int const Direction, bool const FollowsDirection) { + if (Cab == 0) { + return 0; + } + if (false == FollowsDirection || Direction == 0) { + return Cab > 0 ? 1 : -1; + } + return Direction > 0 ? 1 : -1; +} + +} // namespace driver_figure diff --git a/vehicle/driverorders.h b/vehicle/driverorders.h new file mode 100644 index 000000000..4dffb2229 --- /dev/null +++ b/vehicle/driverorders.h @@ -0,0 +1,49 @@ +/* +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 orders of the AI driver: a temporary operation (preparing the engine, changing the direction, coupling) and the +// way it drives (shunting, a train run), which an order can carry together (changeDirection on top of shunt) + +#pragma once + +#include "utilities/enumset.h" + +enum class DriverOrder : unsigned +{ + waitForOrders = 0, // czekanie na dostarczenie następnych rozkazów + // operacje tymczasowe + prepareEngine = 1 << 0, // włączenie silnika + releaseEngine = 1 << 1, // wyłączenie silnika + changeDirection = 1 << 2, // zmiana kierunku (bez skanowania sygnalizacji) + connect = 1 << 3, // podłączanie wagonów (z częściowym skanowaniem sygnalizacji) + disconnect = 1 << 4, // odłączanie wagonów (bez skanowania sygnalizacji) + // jazda + shunt = 1 << 5, // tryb manewrowy + looseShunt = 1 << 6, // coupling-free shunting mode + obeyTrain = 1 << 7, // tryb pociągowy + bank = 1 << 8, // assist mode + // others + jumpToFirstOrder = 1 << 9, // zapętlenie do pierwszej pozycji +}; +template <> struct IsEnumSetKind : std::true_type +{ +}; +using DriverOrders = EnumSet; + +// the orders the old numbers of which were from shunt up (32): they move the train, by a way of driving or the jump +inline constexpr DriverOrders movingOrders{DriverOrder::shunt | DriverOrder::looseShunt | DriverOrder::obeyTrain | DriverOrder::bank | + DriverOrder::jumpToFirstOrder}; +// the orders the old numbers of which were from obeyTrain up (128): the train runs, not shunting +inline constexpr DriverOrders trainOrders{DriverOrder::obeyTrain | DriverOrder::bank | DriverOrder::jumpToFirstOrder}; + +// the order as a single value, for a switch: a sum of several of them matches none of the cases +constexpr DriverOrder SingleOrder(DriverOrders const orders) +{ + return static_cast(orders.Bits()); +} diff --git a/vehicle/drivingaid.cpp b/vehicle/drivingaid.cpp new file mode 100644 index 000000000..7105edfda --- /dev/null +++ b/vehicle/drivingaid.cpp @@ -0,0 +1,79 @@ +/* +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/drivingaid.h" + +#include "physics/vehicle.h" +#include "physics/brakes.h" + +#include +#include + +namespace drivingaid { + +namespace { + +// the first throttle number: the drive demand in percent with an EIM controller, else the master controller. +// a separate ED lever off its zero shows as the negative step the cab's joint controller is at +int throttle_first(input const &Input) { + if (Input.splited && Input.dynamicbrakepos > 0.0) { + return -static_cast(std::lround(Input.dynamicbrakepos * Input.dynamicbrakeposno)); + } + if (Input.eimctrltype > 0) { + return std::max(0, static_cast(100.4 * Input.eimic_real)); + } + return Input.mainctrlpos; +} + +// the cab has a control of the local brake: its own lever, or the braking range of the joint controller +// unless that range is the separate ED lever +bool has_local_brake_control(input const &Input) { + return Input.cab.localbrake || (Input.cab.jointctrl && false == Input.splited); +} + +} // namespace + +readout compute(input const &Input) { + readout result; + result.throttle_first = throttle_first(Input); + result.throttle_second = Input.eimctrltype > 0 ? Input.mainctrlpos : Input.scndctrlpos; + + auto const edbraking{std::max(0.0, -100.0 * Input.eimic_real)}; + result.brake_first = Input.integratedbrake ? edbraking : Input.brakectrlpos; + result.local_brake = Input.localbrakepos * LocalBrakePosNo; + // without a control in the cab the local brake is left out, unless it is applied after all (the AI or a key) + result.show_local_brake = has_local_brake_control(Input) || Input.localbrakepos > 0.0; + // the integrated universal controller shows the ED demand as its brake number already + if (Input.eim && false == Input.integratedbrake) { + if (auto const percent{static_cast(std::lround(edbraking))}; percent > 0) { + result.ed_percent = percent; + } + } + return result; +} + +input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Controlling, cab_controls const &Cab) { + input result; + result.eim = Vehicle.EngineType == TEngineType::ElectricInductionMotor || Vehicle.EIMCtrlType > 0; + result.eimctrltype = Vehicle.EIMCtrlType; + result.splited = Controlling.brakes.electrodynamic.splitFromPneumatic; + result.integratedbrake = Vehicle.UniCtrlIntegratedBrakeCtrl; + result.eimic_real = Vehicle.EimicReal(); + result.dynamicbrakepos = Controlling.brakes.electrodynamic.controllerPosition; + result.dynamicbrakeposno = Controlling.brakes.electrodynamic.controllerPositions; + result.mainctrlpos = Controlling.MainCtrlPos(); + result.scndctrlpos = Controlling.ScndCtrlPos(); + result.brakectrlpos = Vehicle.brakes.HandlePositionSmooth(); + result.localbrakepos = Vehicle.brakes.IndependentPosition(); + result.cab = Cab; + return result; +} + +} // namespace drivingaid diff --git a/vehicle/drivingaid.h b/vehicle/drivingaid.h new file mode 100644 index 000000000..71b44f773 --- /dev/null +++ b/vehicle/drivingaid.h @@ -0,0 +1,68 @@ +/* +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 + +#include + +namespace physics { class Vehicle; } + +// what the driving aid panel shows of the controls and of the braking: the numbers of its throttle and +// brakes lines, worked out from the vehicle state (eu07/maszyna#558, eu07/maszyna#555) +namespace drivingaid { + +// the cab controls the panel needs to know of, which the cab definition (.mmd) has or lacks +struct cab_controls { + // a lever of the local (auxiliary) brake: localbrake: + bool localbrake{true}; + // a joint controller, jointctrl:, whose braking range is the local brake, or the ED lever with + // SplitEDPneumaticBrake + bool jointctrl{false}; +}; + +struct input { + // the vehicle works out the integrated drive and brake demand (eimic): an induction motor vehicle, + // or a diesel one with an EIM controller + bool eim{false}; + int eimctrltype{0}; + // the ED brake has a lever of its own (SplitEDPneumaticBrake), with dynamicbrakeposno steps + bool splited{false}; + // the universal controller brakes with the ED brake, so the brake handle number is the ED demand already + bool integratedbrake{false}; + // the demand in use, -1..1, negative braking + double eimic_real{0.0}; + double dynamicbrakepos{0.0}; // 0..1 + int dynamicbrakeposno{10}; + int mainctrlpos{0}; + int scndctrlpos{0}; + double brakectrlpos{0.0}; // the train brake handle + double localbrakepos{0.0}; // 0..1 + cab_controls cab; +}; + +struct readout { + // "Throttle: first+second" + int throttle_first{0}; + int throttle_second{0}; + // "Brakes: first+local" + double brake_first{0.0}; + double local_brake{0.0}; + bool show_local_brake{true}; + // the ED braking demand in percent, while there is some + std::optional ed_percent; +}; + +// the panel's numbers from the vehicle state +readout compute(input const &Input); + +// the state the panel reads: Vehicle is the one the driver sits in, Controlling the one whose controllers +// the driver moves (TController::Controlling()) +input from_vehicles(physics::Vehicle const &Vehicle, physics::Vehicle const &Controlling, cab_controls const &Cab); + +} // namespace drivingaid diff --git a/vehicle/dynamic/animations.cpp b/vehicle/dynamic/animations.cpp new file mode 100644 index 000000000..b994c2f02 --- /dev/null +++ b/vehicle/dynamic/animations.cpp @@ -0,0 +1,662 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the animated parts of a vehicle: pantographs, doors, platforms, mirrors, wipers, axles, levers, hoses, lights + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +//--------------------------------------------------------------------------- +void TAnimPant::common_pantograph_settings() +{ // wspólne ustawienia, liczone po przypisaniu wymiarów ramion + vPos = glm::dvec3(0, 0, 0); + fAngleL0 = glm::radians(2.8547285515689267247882521833308); + fAngleL = fAngleL0; // początkowy kąt dolnego ramienia + fAngleU0 = acos((fLenL1 * cos(fAngleL) + fHoriz) / fLenU1); // górne ramię + fAngleU = fAngleU0; // początkowy kąt + PantWys = fLenL1 * sin(fAngleL) + fLenU1 * sin(fAngleU) + fHeight; // wysokość początkowa + PantTraction = PantWys; + hvPowerWire = nullptr; + fWidthExtra = 0.381f; //(2.032m-1.027)/2 + // poza obszarem roboczym jest aproksymacja łamaną o 5 odcinkach + fHeightExtra[0] = 0.0f; //+0.0762 + fHeightExtra[1] = -0.01f; //+0.1524 + fHeightExtra[2] = -0.03f; //+0.2286 + fHeightExtra[3] = -0.07f; //+0.3048 + fHeightExtra[4] = -0.15f; //+0.3810 +} + +void TAnimPant::AKP_4E() +{ // ustawienie wymiarów dla pantografu AKP-4E + fLenL1 = 1.22; // 1.176289 w modelach + fLenU1 = 1.755; // 1.724482197 w modelach + fHoriz = 0.535; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego + // ramienia + fHeight = 0.07; // wysokość ślizgu ponad oś obrotu + fWidth = 0.635; // połowa szerokości ślizgu, 0.635 dla AKP-1 i AKP-4E + common_pantograph_settings(); +}; +void TAnimPant::WBL85() +{ // ustawienie wymiarów dla pantografu WBL88 + // mnozniki animacji ramion dla pantografu WBL88 + rd1rf = 1.f; + rd2rf = 1.2; + rg1rf = 0.875; + rg2rf = 1.0; + slizgrf = 1.f; + + fLenL1 = 1.98374; + fLenU1 = 2.14199; + fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego ramienia + fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu + fWidth = 0.4969; // połowa szerokości ślizgu + common_pantograph_settings(); +}; +void TAnimPant::EC160_200() +{ // ustawienie wymiarów dla pantografow EC160 lub EC200 + // mnozniki animacji ramion dla pantografow EC160 lub EC200 + rd1rf = 1.f; + rd2rf = 0.85; + rg1rf = 1.f; + rg2rf = 1.f; // 0.833 + slizgrf = 1.f; + + fLenL1 = 1.98374; + fLenU1 = 2.14199; + fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego ramienia + fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu + fWidth = 0.4969; // połowa szerokości ślizgu + common_pantograph_settings(); +}; +void TAnimPant::DSAx() +{ // ustawienie wymiarów dla pantografow z rodziny DSA + // mnozniki animacji ramion dla pantografow z rodziny DSA + rd1rf = 1.f; + rd2rf = 1.025; + rg1rf = 0.875; + rg2rf = 1.f; + slizgrf = 1.f; + + fLenL1 = 1.98374; + fLenU1 = 2.14199; + fHoriz = 0.142; // 0.54555075 przesunięcie ślizgu w długości pojazdu względem + // osi obrotu dolnego ramienia + fHeight = 0.09353; // wysokość ślizgu ponad oś obrotu + fWidth = 0.4969; // połowa szerokości ślizgu + common_pantograph_settings(); +}; +//--------------------------------------------------------------------------- +int TAnim::TypeSet(int i, physics::Vehicle currentPhysics, int fl) +{ // ustawienie typu animacji i zależnej od niego ilości animowanych submodeli + fMaxDist = -1.0; // normalnie nie pokazywać + switch (i) + { // maska 0x000F: ile używa wskaźników na submodele (0 gdy jeden, + // wtedy bez tablicy) + // maska 0x00F0: + // 0-osie,1-drzwi,2-obracane,3-zderzaki,4-wózki,5-pantografy,6-tłoki + // maska 0xFF00: ile używa liczb float dla współczynników i stanu + case 0: + iFlags = 0x000; + break; // 0-oś + case 1: + iFlags = 0x010; + break; // 1-drzwi + case 2: + iFlags = 0x020; + fParam = fl ? new float[fl] : nullptr; + iFlags += fl << 8; + break; // 2-wahacz, dźwignia itp. + case 3: + iFlags = 0x030; + break; // 3-zderzak + case 4: + iFlags = 0x040; + break; // 4-wózek + case 5: // 5-pantograf - 5 submodeli + iFlags = 0x055; + fParamPants = new TAnimPant(); + switch (currentPhysics.EnginePowerSource.CollectorParameters.PantographType) { + case TPantType::AKP_4E: + fParamPants->AKP_4E(); + break; + case TPantType::DSAx: + fParamPants->DSAx(); + break; + case TPantType::EC160_200: + fParamPants->EC160_200(); + break; + case TPantType::WBL85: + fParamPants->WBL85(); + break; + } + + break; + case 6: + iFlags = 0x068; + break; // 6-tłok i rozrząd - 8 submodeli + case 7: + iFlags = 0x070; + break; // doorstep + case 8: + iFlags = 0x080; + break; // mirror + case 9: + iFlags = 0x023; // 2: Rotating/Motion-based, 8: Uses 3 submodels + break; + default: + iFlags = 0; + } + yUpdate = nullptr; + return iFlags & 15; // ile wskaźników rezerwować dla danego typu animacji +}; + +TAnim::~TAnim() +{ // usuwanie animacji + switch (iFlags & 0xF0) + { // usuwanie struktur, zależnie ile zostało stworzonych + case 0x20: // 2-wahacz, dźwignia itp. + delete fParam; + break; + case 0x50: // 5-pantograf + delete fParamPants; + break; + default: + break; + } +}; + +int TDynamicObject::GetPneumatic(bool front, bool red) +{ + int x, y, z; // 1=prosty, 2=skośny + if (red) + { + if (front) + { + x = btCPneumatic1.GetStatus(); + y = btCPneumatic1r.GetStatus(); + } + else + { + x = btCPneumatic2.GetStatus(); + y = btCPneumatic2r.GetStatus(); + } + } + else if (front) + { + x = btPneumatic1.GetStatus(); + y = btPneumatic1r.GetStatus(); + } + else + { + x = btPneumatic2.GetStatus(); + y = btPneumatic2r.GetStatus(); + } + z = 0; // brak węży? + if (x > 0 && y > 0) + z = 3; // dwa + if (x > 0 && y == 0) + z = 1; // lewy, brak prawego + if (x == 0 && y > 0) + z = 2; // brak lewego, prawy + + return z; +} + +void TDynamicObject::SetPneumatic(bool front, bool red) +{ + int x = 0, + ten = 0, + tamten = 0; + ten = GetPneumatic(front, red); // 1=lewy skos,2=prawy skos,3=dwa proste + if (front) + if (PrevConnected()) // pojazd od strony sprzęgu 0 + tamten = PrevConnected()->GetPneumatic(EndOf(PrevConnectedNo()) == VehicleEnd::front ? true : false, red); + if (!front) + if (NextConnected()) // pojazd od strony sprzęgu 1 + tamten = NextConnected()->GetPneumatic(EndOf(NextConnectedNo()) == VehicleEnd::front ? true : false, red); + if (ten == tamten) // jeśli układ jest symetryczny + switch (ten) + { + case 1: + x = 2; + break; // mamy lewy skos, dać lewe skosy + case 2: + x = 3; + break; // mamy prawy skos, dać prawe skosy + case 3: // wszystkie cztery na prosto + if (physics->Couplers[front ? VehicleEnd::front : VehicleEnd::rear].Render) + x = 1; + else + x = 4; + break; + } + else + { + if (ten == 2) + x = 4; + if (ten == 1) + x = 1; + if (ten == 3) + if (tamten == 1) + x = 4; + else + x = 1; + } + if (front) + { + if (red) + cp1 = x; + else + sp1 = x; + } // który pokazywać z przodu + else + { + if (red) + cp2 = x; + else + sp2 = x; + } // który pokazywać z tyłu +} + +void TDynamicObject::UpdateAxle(TAnim *pAnim) +{ // animacja osi + size_t wheel_id = pAnim->dWheelAngle; + pAnim->smAnimated->SetRotate(float3(1, 0, 0), dWheelAngle[wheel_id]); + pAnim->smAnimated->future_transform = glm::rotate((float)glm::radians(m_future_wheels_angle[wheel_id]), glm::vec3(1.0f, 0.0f, 0.0f)); +}; + +// angle of a slotted lever for given angle of the wheel, which drives the coupling rod with the pin +// all points of the coupling rod move along circles of crank radius, the lever follows the pin sliding in its slot +double TDynamicObject::slottedlever_angle( slottedlever_data const &Lever, double const Wheelangle ) { + // crank turned around X axis, the same way as the wheel + auto const wheelangle { glm::radians( Wheelangle ) }; + auto const crank { glm::dvec2( + Lever.crank.x * std::cos( wheelangle ) - Lever.crank.y * std::sin( wheelangle ), + Lever.crank.x * std::sin( wheelangle ) + Lever.crank.y * std::cos( wheelangle ) ) }; + auto const pin { Lever.pin - Lever.crank + crank }; + // angle relative to the pose of the lever in the model, which matches wheel angle 0 + return glm::degrees( std::atan2( pin.y, pin.x ) - std::atan2( Lever.pin.y, Lever.pin.x ) ); +} + +void TDynamicObject::update_slottedlevers() { + + for( auto const &lever : m_slottedlevers ) { + auto const wheelid { ( + ( lever.axle < iAnimType[ ANIM_WHEELS ] ) && ( lever.axle < static_cast( pAnimations.size() ) ) ? + pAnimations[ lever.axle ].dWheelAngle : + 1 ) }; // driving wheels and coupling rods by default + auto const angle { slottedlever_angle( lever, dWheelAngle[ wheelid ] ) }; + auto const futureangle { slottedlever_angle( lever, dWheelAngle[ wheelid ] + m_future_wheels_angle[ wheelid ] ) }; + lever.submodel->SetRotate( float3( 1, 0, 0 ), angle ); + lever.submodel->future_transform = glm::rotate( (float)glm::radians( std::remainder( futureangle - angle, 360.0 ) ), glm::vec3( 1.0f, 0.0f, 0.0f ) ); + } +} +namespace +{ + + +// the position of the door the animated wing belongs to: its shift or angle from closed +float door_position( physics::Vehicle const &Physics, TAnim const *Animation ) { + + return Physics.Doors.instances[ ( + door_wings::on_right_side( Animation->iNumber ) ? + VehicleSide::right : + VehicleSide::left ) ].position; +} + +// the wing in the main model, and its namesake in the low poly interior; either can be missing +std::array wing_parts( TAnim const *Animation ) { + + return { Animation->smAnimated, Animation->smInterior }; +} + +// folding door: the smaller wing turns, the larger wing (its child) the other way, the step (child of that) under it +void fold_wing( TSubModel *Wing, door_wings::fold_angles const &Angles ) { + + if( Wing == nullptr ) { return; } + // skrzydło mniejsze + Wing->SetRotate( float3( 0, 0, 1 ), Angles.smaller ); + // skrzydło większe + auto *larger { Wing->ChildGet() }; + if( larger == nullptr ) { return; } + larger->SetRotate( float3( 0, 0, 1 ), Angles.larger ); + // podnóżek? + auto *step { larger->ChildGet() }; + if( step == nullptr ) { return; } + step->SetRotate( float3( 0, 1, 0 ), Angles.step ); +} + +} // namespace + +// animacja drzwi - przesuw +void TDynamicObject::UpdateDoorTranslate(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const shift { door_wings::slide( door_position( *physics, pAnim ) ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetTranslate( shift ); + } + } +}; + +// animacja drzwi - obrót +void TDynamicObject::UpdateDoorRotate(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const angle { door_position( *physics, pAnim ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetRotate( float3( 1, 0, 0 ), angle ); + } + } +}; + +// animacja drzwi - obrót +void TDynamicObject::UpdateDoorFold(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const angles { door_wings::fold( door_position( *physics, pAnim ) ) }; + for( auto *wing : wing_parts( pAnim ) ) { + fold_wing( wing, angles ); + } +}; + +// animacja drzwi - odskokprzesuw +void TDynamicObject::UpdateDoorPlug(TAnim *pAnim) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const shift { door_wings::plug( door_position( *physics, pAnim ), physics->Doors.range_out ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing != nullptr ) { + wing->SetTranslate( shift ); + } + } +} + +// a wing animated in its own way (animdoor: of the .mmd): as far along its own range as the door of its side is +void TDynamicObject::UpdateDoorWing( TAnim *pAnim, door_wings::wing_spec const &Spec ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const position { door_wings::wing_position( door_position( *physics, pAnim ), physics->Doors.range, Spec.range ) }; + for( auto *wing : wing_parts( pAnim ) ) { + if( wing == nullptr ) { continue; } + switch( Spec.type ) { + case door_wings::shift_type: { + wing->SetTranslate( door_wings::slide( position ) ); + break; + } + case door_wings::rotate_type: { + wing->SetRotate( float3( 1, 0, 0 ), position ); + break; + } + case door_wings::fold_type: { + fold_wing( wing, door_wings::fold( position ) ); + break; + } + case door_wings::plug_type: { + wing->SetTranslate( door_wings::plug( position, Spec.range_out ) ); + break; + } + default: { + break; + } + } + } +} + +void TDynamicObject::bind_door_animation( TAnim &Animation ) { + + if( auto const *spec { door_wings::find( m_doorwings, Animation.iNumber ) } ) { + Animation.yUpdate = [ this, spec = *spec ]( TAnim *pAnim ) { UpdateDoorWing( pAnim, spec ); }; + return; + } + switch( physics->Doors.type ) { // od razu zapinamy potrzebny typ animacji + case 1: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorTranslate, this, std::placeholders::_1 ); + break; + case 2: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorRotate, this, std::placeholders::_1 ); + break; + case 3: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorFold, this, std::placeholders::_1 ); + break; // obrót 3 kolejnych submodeli + case 4: + Animation.yUpdate = std::bind( &TDynamicObject::UpdateDoorPlug, this, std::placeholders::_1 ); + break; + default: + break; + } +} + +void TDynamicObject::UpdatePant(TAnim *pAnim) +{ // animacja pantografu - 4 obracane ramiona, ślizg piąty + float a, b, c; + a = glm::degrees(pAnim->fParamPants->fAngleL - pAnim->fParamPants->fAngleL0); + b = glm::degrees(pAnim->fParamPants->fAngleU - pAnim->fParamPants->fAngleU0); + c = a + b; + if (pAnim->smElement[0]) + pAnim->smElement[0]->SetRotate(float3(-1, 0, 0), a); // dolne ramie 1 + if (pAnim->smElement[1]) + pAnim->smElement[1]->SetRotate(float3(1, 0, 0), a * pAnim->fParamPants->rd2rf); // dolne ramie 2 + if (pAnim->smElement[2]) + pAnim->smElement[2]->SetRotate(float3(1, 0, 0), c); // górne ramie 1 + if (pAnim->smElement[3]) + pAnim->smElement[3]->SetRotate(float3(-1, 0, 0), c * pAnim->fParamPants->rg2rf); // gorne ramie 2 + if (pAnim->smElement[4]) + pAnim->smElement[4]->SetRotate(float3(-1, 0, 0), b * pAnim->fParamPants->slizgrf); // ślizg +} + +// doorstep animation, shift +void TDynamicObject::UpdatePlatformTranslate( TAnim *pAnim ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const &door { physics->Doors.instances[ ( + ( pAnim->iNumber & 1 ) == 0 ? + VehicleSide::right : + VehicleSide::left ) ] }; + + pAnim->smAnimated->SetTranslate( + glm::vec3{ + std::lerp( 0.f, physics->Doors.step_range, door.step_position ), + 0.0, + 0.0 } ); +} + +// doorstep animation, rotate +void TDynamicObject::UpdatePlatformRotate( TAnim *pAnim ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + auto const &door { physics->Doors.instances[ ( + ( pAnim->iNumber & 1 ) == 0 ? + VehicleSide::right : + VehicleSide::left ) ] }; + + pAnim->smAnimated->SetRotate( + float3( 0, 1, 0 ), + std::lerp( 0.f, physics->Doors.step_range, door.step_position ) ); +} + +// mirror animation, rotate +void TDynamicObject::UpdateMirror( TAnim *pAnim ) { + + if( pAnim->smAnimated == nullptr ) { return; } + + // only animate the mirror if it's located on the same end of the vehicle as the active cab + auto const isactive { ( + physics->CabOccupied() > 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::front ? 1.0 : 0.0 ) : + physics->CabOccupied() < 0 ? ( EndOf( pAnim->iNumber >> 4 ) == VehicleEnd::rear ? 1.0 : 0.0 ) : + 0.0 ) }; + + if( pAnim->iNumber & 1 ) + pAnim->smAnimated->SetRotate( + float3( 0, 1, 0 ), + std::lerp( 0.0, physics->MirrorMaxShift, dMirrorMoveR * isactive ) ); + else + pAnim->smAnimated->SetRotate( + float3( 0, 1, 0 ), + std::lerp( 0.0, physics->MirrorMaxShift, dMirrorMoveL * isactive ) ); +} + +// wipers +void TDynamicObject::UpdateWiper(TAnim* pAnim) +{ + if (!pAnim || !pAnim->smElement) + return; + + int i = pAnim->iNumber; + // odwaramy animacje dla parzystych indexow + const double rotateAngle = (i + 1) % 2 == 0 ? -physics->WiperAngle : physics->WiperAngle; + + if (pAnim->smElement[0]) // ramie 1 + pAnim->smElement[0]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); + if (pAnim->smElement[1]) // ramie 2 + pAnim->smElement[1]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, rotateAngle, dWiperPos[i])); + if (pAnim->smElement[2]) // pioro + pAnim->smElement[2]->SetRotate(float3(0, 1, 0), smoothInterpolate(0.0, -rotateAngle, dWiperPos[i])); +} + +/* +void TDynamicObject::UpdateLeverDouble(TAnim *pAnim) +{ // animacja gałki zależna od double + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fDoubleBase); +}; +void TDynamicObject::UpdateLeverFloat(TAnim *pAnim) +{ // animacja gałki zależna od float + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->fFloatBase); +}; +void TDynamicObject::UpdateLeverInt(TAnim *pAnim) +{ // animacja gałki zależna od int + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fSpeed * *pAnim->iIntBase); +}; +void TDynamicObject::UpdateLeverEnum(TAnim *pAnim) +{ // ustawienie kąta na + // wartość wskazaną przez + // int z tablicy fParam + // pAnim->fParam[0]; - dodać lepkość + pAnim->smAnimated->SetRotate(float3(1, 0, 0), pAnim->fParam[*pAnim->iIntBase]); +}; +*/ +// sets light levels for registered interior sections +void +TDynamicObject::toggle_lights() { + + if( true == SectionLightsActive ) { + // switch all lights off... + for( auto §ion : Sections ) { + auto const sectionname { section.compartment->pName }; + if( sectionname.rfind( "cab", 0 ) != 0 ) { + section.light_level = 0.0; + } + } + SectionLightsActive = false; + } + else { + // set lights with probability depending on the compartment type. TODO: expose this in .mmd file + for( auto §ion : Sections ) { + + auto const sectionname { section.compartment->pName }; + if( sectionname.find("corridor") == 0 + || sectionname.find("korytarz") == 0 ) { + // corridors are lit 100% of time + section.light_level = 0.75f; + } + else if( + sectionname.find("compartment") == 0 + || sectionname.find("przedzial") == 0 ) { + // compartments are lit with 75% probability + section.light_level = Random() < 0.75 ? 0.75f : 0.10f; + } + } + SectionLightsActive = true; + } +} + +void +TDynamicObject::set_cab_lights( int const Cab, float const Level ) { + + for( auto §ion : Sections ) { + // cab compartments are placed at the beginning of the list, so we can bail out as soon as we find different compartment type + auto const sectionname { section.compartment->pName }; + if( sectionname.size() < 4 ) { return; } + if( sectionname.find( "cab" ) != 0 ) { return; } + if( sectionname[ 3 ] != Cab + '0' ) { continue; } // match the cab with correct index + + section.light_level = Level; + } +} + +// aktualizujemy submodele w zaleznosci od aktualnej pory roku +void TDynamicObject::on_season_update() +{ + if (sm_winter_variant != nullptr) // pokazujemy wariant zimowy + sm_winter_variant->SetVisibilityLevel(Global.Season == "winter:" ? 1 : 0, true, false); + if (sm_spring_variant != nullptr) // pokazujemy wariant wiosenny + sm_spring_variant->SetVisibilityLevel(Global.Season == "spring:" ? 1 : 0, true, false); + if (sm_summer_variant != nullptr) // pokazujemy wariant letni + sm_summer_variant->SetVisibilityLevel(Global.Season == "summer:" ? 1 : 0, true, false); + if (sm_autumn_variant != nullptr) // pokazujemy wariant jesienny + sm_autumn_variant->SetVisibilityLevel(Global.Season == "autumn:" ? 1 : 0, true, false); +} diff --git a/vehicle/dynamic/consist.cpp b/vehicle/dynamic/consist.cpp new file mode 100644 index 000000000..c94fd4aed --- /dev/null +++ b/vehicle/dynamic/consist.cpp @@ -0,0 +1,529 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a vehicle among the others of its train: the neighbours, the ends, the vehicles found along the couplings + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + + +//--------------------------------------------------------------------------- +TDynamicObject * TDynamicObject::FirstFind(int &coupler_nr, CouplingSet const cf) +{ // szukanie skrajnego połączonego pojazdu w pociagu + // od strony sprzegu (coupler_nr) obiektu (start) + TDynamicObject *temp = this; + for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu + { + if (!temp) + return nullptr; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów + if (false == temp->physics->Couplers[coupler_nr].CouplingFlag.HasAll(cf)) + return temp; // nic nie ma już dalej podłączone sprzęgiem cf + if (EndOf(coupler_nr) == VehicleEnd::front) + { // jeżeli szukamy od sprzęgu 0 + if (temp->PrevConnected()) // jeśli mamy coś z przodu + { + if (EndOf(temp->PrevConnectedNo()) == VehicleEnd::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->PrevConnected(); // ten jest od strony 0 + } + else + return temp; // jeśli jednak z przodu nic nie ma + } + else + { + if (temp->NextConnected()) + { + if (EndOf(temp->NextConnectedNo()) == VehicleEnd::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->NextConnected(); // ten pojazd jest od strony 1 + } + else + return temp; // jeśli jednak z tyłu nic nie ma + } + } + return nullptr; // to tylko po wyczerpaniu pętli +}; + +//--------------------------------------------------------------------------- +float TDynamicObject::GetEPP() +{ // szukanie skrajnego połączonego pojazdu w pociagu + // od strony sprzegu (coupler_nr) obiektu (start) + TDynamicObject *temp = this; + int coupler_nr = 0; + double eq = 0.0; + double am = 0.0; + + for (int i = 0; i < 300; ++i) // ograniczenie do 300 na wypadek zapętlenia składu + { + if (!temp) + break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów + eq += temp->physics->brakePipe.Pressure() * temp->physics->Dim.L; + am += temp->physics->Dim.L; + if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) + break; // nic nie ma już dalej podłączone + if (coupler_nr == 0) + { // jeżeli szukamy od sprzęgu 0 + if (temp->PrevConnected()) // jeśli mamy coś z przodu + { + if (EndOf(temp->PrevConnectedNo()) == VehicleEnd::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->PrevConnected(); // ten jest od strony 0 + } + else + break; // jeśli jednak z przodu nic nie ma + } + else + { + if (temp->NextConnected()) + { + if (EndOf(temp->NextConnectedNo()) == VehicleEnd::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->NextConnected(); // ten pojazd jest od strony 1 + } + else + break; // jeśli jednak z tyłu nic nie ma + } + } + + temp = this; + coupler_nr = 1; + for (int i = 0; i < 300; i++) // ograniczenie do 300 na wypadek zapętlenia składu + { + if (!temp) + break; // Ra: zabezpieczenie przed ewentaulnymi błędami sprzęgów + eq += temp->physics->brakePipe.Pressure() * temp->physics->Dim.L; + am += temp->physics->Dim.L; + if ((temp->physics->Couplers[coupler_nr].CouplingFlag & Coupling::brakeHose) != Coupling::brakeHose) + break; // nic nie ma już dalej podłączone + if (coupler_nr == 0) + { // jeżeli szukamy od sprzęgu 0 + if (temp->PrevConnected()) // jeśli mamy coś z przodu + { + if (EndOf(temp->PrevConnectedNo()) == VehicleEnd::front) // jeśli pojazd od strony sprzęgu 0 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->PrevConnected(); // ten jest od strony 0 + } + else + break; // jeśli jednak z przodu nic nie ma + } + else + { + if (temp->NextConnected()) + { + if (EndOf(temp->NextConnectedNo()) == VehicleEnd::rear) // jeśli pojazd od strony sprzęgu 1 jest odwrócony + coupler_nr = 1 - coupler_nr; // to zmieniamy kierunek sprzęgu + temp = temp->NextConnected(); // ten pojazd jest od strony 1 + } + else + break; // jeśli jednak z tyłu nic nie ma + } + } + eq -= physics->brakePipe.Pressure() * physics->Dim.L; + am -= physics->Dim.L; + return eq / am; +}; + +//--------------------------------------------------------------------------- +TDynamicObject * TDynamicObject::GetFirstDynamic(VehicleEnd const cpl_type, CouplingSet const cf) +{ // Szukanie skrajnego połączonego pojazdu w pociagu + // od strony sprzegu (cpl_type) obiektu szukajacego + // Ra: wystarczy jedna funkcja do szukania w obu kierunkach + int coupler { NumberOf( cpl_type ) }; + return FirstFind(coupler, cf); // używa referencji +}; + +int TDynamicObject::DirectionSet(int d) +{ // ustawienie kierunku w składzie (wykonuje AI) + auto const lastdirection { iDirection }; + iDirection = d > 0 ? 1 : 0; // d:1=zgodny,-1=przeciwny; iDirection:1=zgodny,0=przeciwny; + + if( iDirection != lastdirection ) { + // direction was flipped, switch recorded servicable platform sides for potentially ongoing load exchange + auto const left { lastdirection > 0 ? 1 : 2 }; + auto const right { 3 - left }; + m_exchange.platforms = + ( ( m_exchange.platforms & left ) != 0 ? right : 0 ) + + ( ( m_exchange.platforms & right ) != 0 ? left : 0 ); + } + + if (MyTrack) + { // podczas wczytywania wstawiane jest AI, ale może jeszcze nie być toru + // AI ustawi kierunek ponownie po uruchomieniu silnika + update_neighbours(); + } + // informacja o położeniu następnego + return 1 - ( iDirection > 0 ? NextConnectedNo() : PrevConnectedNo() ); +}; + +// wskaźnik na poprzedni, nawet wirtualny +TDynamicObject * TDynamicObject::PrevAny() const { + return physics->Neighbours[ iDirection ^ 1 ].vehicle; +} +TDynamicObject * TDynamicObject::Prev(CouplingSet const couplings) const { + return physics->Couplers[iDirection ^ 1].CouplingFlag.HasAny(couplings) ? physics->Neighbours[iDirection ^ 1].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było +} +TDynamicObject * TDynamicObject::Next(CouplingSet const couplings) const { + return physics->Couplers[iDirection].CouplingFlag.HasAny(couplings) ? physics->Neighbours[iDirection].vehicle : nullptr;// gdy sprzęg wirtualny, to jakby nic nie było +} + +// checks whether there's unbroken connection of specified type to specified vehicle +bool +TDynamicObject::is_connected( TDynamicObject const *Vehicle, CouplingSet const couplings ) const { + + auto *vehicle { this }; + if( vehicle == Vehicle ) { + // edge case, vehicle is always "connected" with itself + return true; + } + // check ahead, it's more likely the "owner" using this method is located there + while( ( vehicle = vehicle->Prev( couplings ) ) != nullptr ) { + if( vehicle == Vehicle ) { + return true; + } + if( vehicle == this ) { + // edge case, looping consist + return false; + } + } + // start anew in the other direction + vehicle = this; + while( ( vehicle = vehicle->Next( couplings ) ) != nullptr ) { + if( vehicle == Vehicle ) { + return true; + } + } + // no luck in either direction, give up + return false; +} + +// ustalenie następnego (1) albo poprzedniego (0) w składzie bez względu na prawidłowość iDirection +TDynamicObject * +TDynamicObject::Neighbour(int &dir) { + + auto *neighbour { ( + physics->Couplers[ dir ].CouplingFlag != Coupling::none ? + physics->Neighbours[ dir ].vehicle : + nullptr ) }; + // nowa wartość + dir = 1 - physics->Neighbours[ dir ].vehicle_end; + + return neighbour; +}; + +// updates potential collision sources +void +TDynamicObject::update_neighbours() { + + for (auto const end : VehicleEnds) { + + auto &neighbour { physics->Neighbours[ end ] }; + auto const &coupler { physics->Couplers[ end ] }; + + if( coupler.Connected != nullptr + && neighbour.vehicle != nullptr ) { + // physical connection with another vehicle locks down collision source on this end +// neighbour.vehicle = coupler.Connected; +// neighbour.vehicle_end = coupler.ConnectedNr; + neighbour.distance = physics::Vehicle::CouplerDist( physics, coupler.Connected ); + neighbour.off_track = false; + if( physics->OffTrack.active() || neighbour.vehicle->physics->OffTrack.active() ) { + // physics.derailment new: off the track the bodies turn against each other, the ends meet where they are + // (the distance between the middles less the half lengths would press the buffers of a bent pair) + vehicle_dynamic::measure_off_track( neighbour, *this, end ); + } + // take into account potential adapters attached to the couplers + auto const &othercoupler { neighbour.vehicle->physics->Couplers[ neighbour.vehicle_end ] }; + neighbour.distance -= coupler.adapter_length; + neighbour.distance -= othercoupler.adapter_length; + } + else { + // if there's no connected vehicle check for potential collision sources in the vicinity + // NOTE: we perform a new scan on each update to ensure we always locate the nearest potential source + neighbour = neighbour_data(); + // 10m ~= 140 km/h at 4 fps + safety margin, potential distance between outer axles of involved vehicles + auto const scanrange { std::max( 10.0, std::abs( physics->V() ) ) + 40.0 }; + // physics.derailment new: a vehicle off the track beside the other one doesn't run into it, the scan goes on + // past it to the vehicles beyond + auto const lookup { find_vehicle( NumberOf( end ), scanrange, true ) }; + + if( false == std::get( lookup ) ) { continue; } + + neighbour.vehicle = std::get( lookup ); + neighbour.vehicle_end = std::get( lookup ); + neighbour.distance = std::get( lookup ); + + if( neighbour.vehicle + && neighbour.distance < (neighbour.vehicle->physics->CategoryFlag == 2 ? 50 : 100) ) { + // at short distances (re)calculate range between couplers directly + neighbour.distance = physics::Vehicle::CouplerDist( physics, neighbour.vehicle->physics ); + if( physics->OffTrack.active() || neighbour.vehicle->physics->OffTrack.active() ) { + // physics.derailment new: the ends where they are, as for a coupled pair + vehicle_dynamic::measure_off_track( neighbour, *this, end ); + } + // take into account potential adapters attached to the couplers + auto const &othercoupler { neighbour.vehicle->physics->Couplers[ neighbour.vehicle_end ] }; + neighbour.distance -= coupler.adapter_length; + neighbour.distance -= othercoupler.adapter_length; + } + } + } +} + +bool +TDynamicObject::in_line_with( TDynamicObject const &Other ) const { + + // the middle of the other one off the axis of this one, and this one off the axis of the other one, by less than + // the half widths of both: their ends can meet + auto const reach { 0.5 * ( physics->Dim.W + Other.physics->Dim.W ) }; + auto const apart { Other.vPosition - vPosition }; + return std::abs( glm::dot( apart, vLeft ) ) < reach && std::abs( glm::dot( apart, Other.vLeft ) ) < reach; +} + +// locates potential collision source within specified range, scanning track in specified direction. returns: true if neighbour was located, false otherwise +// NOTE: reuses legacy code. TBD, TODO: review, refactor? +std::tuple +TDynamicObject::find_vehicle( int const Direction, double const Distance, bool const InLine ) const { + + auto direction { ( EndOf( Direction ) == VehicleEnd::front ? 1 : -1 ) }; + auto const initialdirection { direction }; // zapamiętanie kierunku poszukiwań na torze początkowym, względem sprzęgów + + auto const *track { RaTrackGet() }; + if( RaDirectionGet() < 0 ) { + // czy oś jest ustawiona w stronę Point1? + direction = -direction; + } + + // (teraz względem toru) + auto const mycoupler { NumberOf( initialdirection < 0 ? VehicleEnd::rear : VehicleEnd::front ) }; // numer sprzęgu do podłączenia w obiekcie szukajacym + auto foundcoupler { -1 }; // numer sprzęgu w znalezionym obiekcie (znaleziony wypełni) + auto distance { 0.0 }; // przeskanowana odleglość; odległość do zawalidrogi + auto *foundobject { ABuFindObject( foundcoupler, distance, track, direction, mycoupler, InLine ) }; // zaczynamy szukać na tym samym torze + + if( foundobject == nullptr ) { + // jeśli nie ma na tym samym, szukamy po okolicy szukanie najblizszego toru z jakims obiektem + // praktycznie przeklejone z TraceRoute()... + if (direction >= 0) // uwzględniamy kawalek przeanalizowanego wcześniej toru + distance = track->Length() - RaTranslationGet(); // odległość osi od Point2 toru + else + distance = RaTranslationGet(); // odległość osi od Point1 toru + + while (distance < Distance) { + if (direction > 0) { + // w kierunku Point2 toru + if( track ? + track->iNextDirection : + false ) { + // jeśli następny tor jest podpięty od Point2 + direction = -direction; // to zmieniamy kierunek szukania na tym torze + } + if( track ) { + track = track->CurrentNext(); // potem dopiero zmieniamy wskaźnik + } + } + else { + // w kierunku Point1 + if( track ? + !track->iPrevDirection : + true ) { + // jeśli poprzedni tor nie jest podpięty od Point2 + direction = -direction; // to zmieniamy kierunek szukania na tym torze + } + if( track ) { + track = track->CurrentPrev(); // potem dopiero zmieniamy wskaźnik + } + } + if (track) { + // jesli jest kolejny odcinek toru + foundobject = ABuFindObject(foundcoupler, distance, track, direction, mycoupler, InLine); // przejrzenie pojazdów tego toru + if (foundobject) { + break; + } + } + else { + // jeśli toru nie ma, to wychodzimy + distance = Distance + 1.0; // koniec przeglądania torów + break; + } + } + } // Koniec szukania najbliższego toru z jakimś obiektem. + + if( foundobject == nullptr ) { return {}; } +/* + auto const *vehicle { physics }; + auto const *foundvehicle { foundobject->physics }; + if( ( false == TestFlag( track->iCategoryFlag, 1 ) ) + && ( distance > 50.0 ) ) { + // Ra: jeśli dwa samochody się mijają na odcinku przed zawrotką, to odległość między nimi nie może być liczona w linii prostej! + // NOTE: the distance is approximated, and additionally less accurate for cars heading in opposite direction + distance -= ( 0.5 * ( vehicle->Dim.L + foundvehicle->Dim.L ) ); + } + else if( distance < 100.0 ) { + // at short distances start to calculate range between couplers directly + // odległość do najbliższego pojazdu w linii prostej + distance = physics::Vehicle::CouplerDist( vehicle, foundvehicle ); + } +*/ + return { foundobject, foundcoupler, distance, true }; +} + +TDynamicObject * TDynamicObject::FindPowered() +{ // taka proteza: + // chcę podłączyć kabinę EN57 bezpośrednio z silnikowym, aby nie robić tego przez ukrotnienie + // drugi silnikowy i tak musi być ukrotniony, podobnie jak kolejna jednostka + // lepiej by było przesyłać komendy sterowania, co jednak wymaga przebudowy transmisji komend (LD) + // problem się robi ze światłami, które będą zapalane w silnikowym, ale muszą świecić się w rozrządczych + // dla EZT światłą czołowe będą "zapalane w silnikowym", ale widziane z rozrządczych + // również wczytywanie MMD powinno dotyczyć aktualnego członu + // problematyczna może być kwestia wybranej kabiny (w silnikowym...) + // jeśli silnikowy będzie zapięty odwrotnie (tzn. -1), to i tak powinno jeździć dobrze + // również hamowanie wykonuje się zaworem w członie, a nie w silnikowym... + auto const coupling { physics->is_multiple_unit() ? + Coupling::permanent : + Coupling::control }; + + auto *lookup { + find_vehicle( + coupling, + []( TDynamicObject * vehicle ) { + return vehicle->physics->Power > 1.0; } ) }; + + return lookup != nullptr ? lookup : this; // always return valid vehicle for backward compatibility +} + +TDynamicObject * +TDynamicObject::FindPantographCarrier() { + + // try first within a single unit, broaden to all vehicles under our control if first attempt fails + std::array const couplings = { Coupling::permanent, Coupling::control }; + + for( auto const coupling : couplings ) { + auto *result = + find_vehicle( + coupling, + []( TDynamicObject * vehicle ) { + return vehicle->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector && vehicle->physics->EnginePowerSource.CollectorParameters.CollectorsNo > 0; } ); + if( result != nullptr ) { + return result; + } + } + // if we're still here, admit failure + return nullptr; +} + +//--------------------------------------------------------------------------- + +void TDynamicObject::ParamSet(int what, int into) +{ // ustawienie lokalnego parametru (what) na stan (into) + switch (what & 0xFF00) + { + case 0x0100: // to np. są drzwi, bity 0..7 określają numer 1..254 albo maskę + // dla 8 różnych + if (what & 1) // na razie mamy lewe oraz prawe, czyli używamy maskę 1=lewe, + // 2=prawe, 3=wszystkie + if( physics->Doors.instances[VehicleSide::left].is_open ) + { // są otwarte + if (!into) // jeśli zamykanie + { + // dźwięk zamykania + } + } + else + { // są zamknięte + if (into) // jeśli otwieranie + { + // dźwięk otwierania + } + } + if (what & 2) // prawe działają niezależnie od lewych + if( physics->Doors.instances[VehicleSide::right].is_open ) + { // są otwarte + if (!into) // jeśli zamykanie + { + // dźwięk zamykania + } + } + else + { // są zamknięte + if (into) // jeśli otwieranie + { + // dźwięk otwierania + } + } + break; + } +}; + +int TDynamicObject::RouteWish(TTrack *tr) +{ // zapytanie do AI, po którym + // segmencie (-6..6) jechać na + // skrzyżowaniu (tr) + return Mechanik ? Mechanik->CrossRoute(tr) : 0; // wg AI albo prosto +}; + +// the vehicles coupled at the ends, and the ends of theirs facing this one +TDynamicObject *TDynamicObject::NextConnected() { return physics->Neighbours[ VehicleEnd::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() { return physics->Neighbours[ VehicleEnd::front ].vehicle; } +TDynamicObject *TDynamicObject::NextConnected() const { return physics->Neighbours[ VehicleEnd::rear ].vehicle; } +TDynamicObject *TDynamicObject::PrevConnected() const { return physics->Neighbours[ VehicleEnd::front ].vehicle; } +int TDynamicObject::NextConnectedNo() const { return physics->Neighbours[ VehicleEnd::rear ].vehicle_end; } +int TDynamicObject::PrevConnectedNo() const { return physics->Neighbours[ VehicleEnd::front ].vehicle_end; } + +void TDynamicObject::SetdMoveLen( double dMoveLen ) { physics->SetMoveLength(dMoveLen); } +void TDynamicObject::ResetdMoveLen() { physics->SetMoveLength(0); } +double TDynamicObject::GetdMoveLen() { return physics->MoveLength(); } + +double TDynamicObject::GetVelocity() const { return physics->Vel; } +double TDynamicObject::GetLength() const { return physics->Dim.L; } +double TDynamicObject::GetWidth() const { return physics->Dim.W; } diff --git a/vehicle/dynamic/couplers.cpp b/vehicle/dynamic/couplers.cpp new file mode 100644 index 000000000..43de745b6 --- /dev/null +++ b/vehicle/dynamic/couplers.cpp @@ -0,0 +1,331 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// coupling and uncoupling a vehicle, the adapters of its couplers + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +int TDynamicObject::DettachStatus(int dir) +{ // sprawdzenie odległości sprzęgów + // rzeczywistych od strony (dir): + // 0=przód,1=tył + // Ra: dziwne, że ta funkcja nie jest używana + if( physics->Couplers[ dir ].CouplingFlag == Coupling::none ) { + return 0; // jeśli nic nie podłączone, to jest OK + } + return physics->DettachStatus(dir); // czy jest w odpowiedniej odległości? +} + +int TDynamicObject::Dettach(int dir) +{ // rozłączenie sprzęgów rzeczywistych od + // strony (dir): 0=przód,1=tył + // zwraca maskę bitową aktualnych sprzegów (0 jeśli rozłączony) + if (ctOwner) + { // jeśli pojazd ma przypisany obiekt nadzorujący skład, to póki + // są wskaźniki + TDynamicObject *d = this; + while (d) + { + d->ctOwner = nullptr; // usuwanie właściciela + d = d->Prev(); + } + d = Next(); + while (d) + { + d->ctOwner = nullptr; // usuwanie właściciela + d = d->Next(); // i w drugą stronę + } + } + if( physics->Couplers[ dir ].CouplingFlag ) { + // odczepianie, o ile coś podłączone + physics->Dettach( dir ); +/* + if( true == physics->Dettach( dir ) ) { + auto *othervehicle { dir ? NextConnected : PrevConnected }; + auto const othercoupler { dir ? NextConnectedNo() : PrevConnectedNo() }; + ( othercoupler ? othervehicle->NextConnected : othervehicle->PrevConnected ) = nullptr; + ( dir ? NextConnected : PrevConnected ) = nullptr; + }; +*/ + } + // sprzęg po rozłączaniu (czego się nie da odpiąć + return physics->Couplers[dir].CouplingFlag.Bits(); +} + +void +TDynamicObject::couple( VehicleEnd const Side ) { + + auto const &neighbour { physics->Neighbours[ Side ] }; + + if( neighbour.vehicle == nullptr ) { return; } + + auto const &coupler { physics->Couplers[ Side ] }; + auto *othervehicle { neighbour.vehicle }; + auto *othervehicleparams{ othervehicle->physics }; + auto const &othercoupler { othervehicleparams->Couplers[ neighbour.vehicle_end ] }; + + if( coupler.CouplingFlag == Coupling::none ) { + // najpierw hak + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::coupler ) == Coupling::coupler ) { + if( physics->Attach( + Side, neighbour.FacingEnd(), + othervehicleparams, + Coupling::coupler ) ) { + // one coupling type per key press + return; + } + else { + WriteLog( "Mechanical coupling failed." ); + } + } + } + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::brakeHose) ) { + // pneumatyka + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::brakeHose ) == Coupling::brakeHose ) { + if( physics->Attach( + Side, neighbour.FacingEnd(), + othervehicleparams, + coupler.CouplingFlag | Coupling::brakeHose ) ) { + SetPneumatic( Side != VehicleEnd::front, true ); + othervehicle->SetPneumatic( Side != VehicleEnd::front, true ); + // one coupling type per key press + return; + } + } + } + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::mainHose) ) { + // zasilajacy + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::mainHose ) == Coupling::mainHose ) { + if( physics->Attach( + Side, neighbour.FacingEnd(), + othervehicleparams, + coupler.CouplingFlag | Coupling::mainHose ) ) { + SetPneumatic( Side != VehicleEnd::front, false ); + othervehicle->SetPneumatic( Side != VehicleEnd::front, false ); + // one coupling type per key press + return; + } + } + } + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::control) ) { + // ukrotnionko + if( (coupler.AllowedFlag & othercoupler.AllowedFlag & Coupling::control) == Coupling::control + && coupler.control_type == othercoupler.control_type + && physics->CompatibleCoupling( Side, *othervehicleparams, neighbour.FacingEnd(), coupler.CouplingFlag | Coupling::control ).HasAny( Coupling::control ) ) { + if( physics->Attach( + Side, neighbour.FacingEnd(), + othervehicleparams, + coupler.CouplingFlag | Coupling::control ) ) { + // one coupling type per key press + return; + } + } + } + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::gangway) ) { + // mostek + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::gangway ) == Coupling::gangway ) { + if( physics->Attach( + Side, neighbour.FacingEnd(), + othervehicleparams, + coupler.CouplingFlag | Coupling::gangway ) ) { + // one coupling type per key press + return; + } + } + } + if( false == physics->Couplers[ Side ].CouplingFlag.HasAll(Coupling::heating) ) { + // heating + if( ( coupler.AllowedFlag + & othercoupler.AllowedFlag + & Coupling::heating ) == Coupling::heating ) { + if( physics->Attach( + Side, neighbour.FacingEnd(), + othervehicleparams, + coupler.CouplingFlag | Coupling::heating ) ) { + // one coupling type per key press + return; + } + } + } + +} + +int +TDynamicObject::uncouple( VehicleEnd const Side ) { + + if( DettachStatus( NumberOf( Side ) ) >= 0 + || true == physics->Couplers[Side].CouplingFlag.HasAll(Coupling::permanent) ) { + // can't uncouple, return existing coupling state + return physics->Couplers[ Side ].CouplingFlag.Bits(); + } + // jeżeli sprzęg niezablokowany, jest co odczepić i się da + auto const couplingflag { Dettach( NumberOf( Side ) ) }; + return couplingflag; +} + +bool +TDynamicObject::attach_coupler_adapter( VehicleEnd const Side, bool const Enforce ) { + + auto &coupler { physics->Couplers[ Side ] }; + // sanity check(s) + if( coupler.type() == TCouplerType::Automatic ) { return false; } + auto const *neighbour { physics->Neighbours[ Side ].vehicle }; + if( neighbour == nullptr + || physics->Neighbours[Side].distance > 25.0 ) { + // can only acquire the adapter from a nearby enough vehicle + return false; + } + // TBD: empty struct instead of fallback defaults, to allow vehicles without adapter? + auto adapterdata { + coupleradapter_data { + { 0.085f, 0.95f }, + "tabor/polsprzeg" } }; + if( false == neighbour->m_coupleradapter.model.empty() ) { + // explicit coupler adapter definition overrides default parameters + adapterdata = neighbour->m_coupleradapter; + } + if( physics->Neighbours[Side].distance - adapterdata.position.x < 0.5 + && false == Enforce ) { + // arbitrary amount of free room required to install the adapter + // NOTE: this also covers cases with established physical connection + return false; + } + + coupler.adapter_type = TCouplerType::Automatic; + coupler.adapter_length = adapterdata.position.x; + coupler.adapter_height = adapterdata.position.y; + // audio flag, visuals update + coupler.sounds |= sound::attachadapter; + m_coupleradapters[ Side ] = TModelsManager::GetModel( adapterdata.model ); + + return true; +} + +bool +TDynamicObject::remove_coupler_adapter( VehicleEnd const Side ) { + + auto &coupler{ physics->Couplers[ Side ] }; + + if( coupler.adapter_type == TCouplerType::NoCoupler ) { return false; } + // TODO: sanity check(s) + if( coupler.Connected != nullptr ) { + // TBD: disallow instead adapter removal if it's coupled with another vehicle? + uncouple( Side ); + } + coupler.adapter_type = TCouplerType::NoCoupler; + coupler.adapter_length = 0.0; + coupler.adapter_height = 0.0; + // audio flag, visuals update + coupler.sounds |= sound::removeadapter; + m_coupleradapters[ Side ] = nullptr; + + return true; +} + +void TDynamicObject::AttachNext(TDynamicObject *Object, int iType) +{ // Ra: doczepia Object na końcu składu (nazwa funkcji może być myląca) + // Ra: używane tylko przy wczytywaniu scenerii + auto const vehicleend { iDirection }; + auto const othervehicleend { Object->iDirection ^ 1 }; + + physics->Attach( vehicleend, othervehicleend, Object->physics, CouplingSet::FromBits( iType ), true, false ); + // update neighbour data for both affected vehicles + update_neighbours(); + Object->update_neighbours(); + + // potentially attach automatic coupler adapter to allow the connection + // HACK: we're doing it after establishin actual connection, as the method needs valid neighbour data + auto &coupler { physics->Couplers[ vehicleend ] }; + auto &othercoupler { Object->physics->Couplers[ ( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ) ] }; + + if( coupler.type() != othercoupler.type() ) { + if( othercoupler.type() == TCouplerType::Automatic ) { + // try to attach adapter to the vehicle + attach_coupler_adapter( + EndOf( vehicleend ), + true ); + } + else if( coupler.type() == TCouplerType::Automatic ) { + // try to attach adapter to the other vehicle + Object->attach_coupler_adapter( + EndOf( othervehicleend != 2 ? othervehicleend : coupler.ConnectedNr ), + true ); + } + // update distance to neighbours on account of potentially attached adapter + update_neighbours(); + Object->update_neighbours(); + } + // potentially adjust vehicle position to avoid collision at the simulation start + if( physics->Neighbours[ vehicleend ].distance > -0.001 ) { return; } + + Object->Move( physics->Neighbours[ vehicleend ].distance * Object->DirectionGet() ); + // HACK: manually update vehicle position as it's used by neighbour distance update we do next + Object->physics->SetLoc({ + -Object->vPosition.x, + Object->vPosition.z, + Object->vPosition.y }); + // update neighbour distance data after moving our vehicle + update_neighbours(); + Object->update_neighbours(); +} diff --git a/vehicle/dynamic/destinations.cpp b/vehicle/dynamic/destinations.cpp new file mode 100644 index 000000000..556629ed2 --- /dev/null +++ b/vehicle/dynamic/destinations.cpp @@ -0,0 +1,379 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the destination boards and the announcements of a vehicle + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::destination_data::deserialize( cParser &Input ) { + + while( true == deserialize_mapping( Input ) ) { + ; // all work done by while() + } +} + +bool TDynamicObject::destination_data::deserialize_mapping( cParser &Input ) { + // token can be a key or block end + auto const key { Input.getToken( true, "\n\r\t ,;[]" ) }; + + if( true == key.empty() || key == "}" ) { return false; } + + if( key == "{" ) { + script = Input.getToken(); + } + else if( key == "update:" ) { + auto const value { Input.getToken() }; + // TODO: implement + } + else if( key == "instance:" ) { + instancing = Input.getToken(); + } + else if( key == "parameters:" ) { + parameters = Input.getToken(); + } + else if( key == "background:" ) { + background = Input.getToken(); + } + + return true; +} + +/* +Ra: + Powinny być dwie funkcje wykonujące aktualizację fizyki. Jedna wykonująca +krok obliczeń, powtarzana odpowiednią liczbę razy, a druga wykonująca zbiorczą +aktualzację mniej istotnych elementów. + Ponadto należało by ustalić odległość składów od kamery i jeśli przekracza +ona np. 10km, to traktować składy jako uproszczone, np. bez wnikania w siły +na sprzęgach, opóźnienie działania hamulca itp. Oczywiście musi mieć to pewną +histerezę czasową, aby te tryby pracy nie przełączały się zbyt szybko. +*/ + +void TDynamicObject::update_destinations() { + + if( DestinationSign.sign == nullptr ) { return; } + + auto const lowvoltagepower { ( physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() ) }; + + DestinationSign.sign->fLight = DestinationSign.has_light && lowvoltagepower ? 2.0 : -1.0; + + // jak są 4 tekstury wymienne, to nie zmieniać rozkładem + if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } + // TODO: dedicated setting to discern electronic signs, instead of fallback on light presence + m_materialdata.replacable_skins[ 4 ] = DestinationSign.destination != null_handle && (false == DestinationSign.has_light // physical destination signs remain up until manually changed + || (lowvoltagepower // lcd signs are off without power + && ctOwner != nullptr)) ? // lcd signs are off for carriages without engine, potentially left on a siding + DestinationSign.destination : + DestinationSign.destination_off; + + update_script_destination(); +} + +void TDynamicObject::update_script_destination() { + + if( DestinationSign.script_sign == nullptr ) { return; } + // only while the sign shows the destination it draws + if( m_materialdata.replacable_skins[ 4 ] != DestinationSign.destination ) { return; } + + auto &queue { Application.screens() }; + if( false == queue.due( *DestinationSign.script_sign ) ) { return; } + // read anew on every refresh, so the sign follows the timetable + queue.submit( DestinationSign.script_sign, std::make_shared( DestinationSign.script_request ), 0 ); +} + +void TDynamicObject::DestinationClear() { + + if( false == DestinationSign.has_light ) { return; } // physical destination signs remain up until manually changed + // update_destinations() shows the blank sign in place of the missing destination + DestinationSign.destination = null_handle; + DestinationSign.script_sign.reset(); +} + +void TDynamicObject::DestinationSet(std::string const &to, std::string const &numer) { + // ustawienie stacji docelowej oraz wymiennej tekstury 4, jeśli istnieje plik + // w zasadzie, to każdy wagon mógłby mieć inną stację docelową + // zwłaszcza w towarowych, pod kątem zautomatyzowania maewrów albo pracy górki + // ale to jeszcze potrwa, zanim będzie możliwe, na razie można wpisać stację z + // rozkładu + + asDestination = to; + + if( std::abs( m_materialdata.multi_textures ) >= 4 ) { return; } // jak są 4 tekstury wymienne, to nie zmieniać rozkładem + if( DestinationSign.sign == nullptr ) { return; } // no sign submodel, no problem + // a sign drawn for the previous destination + DestinationSign.script_sign.reset(); + + // now see if we can find any version of the destination texture + std::vector const destinations = { + numer, // try dedicated timetable sign first... + to }; // ...then generic destination sign + + for( auto const &destination : destinations ) { + + DestinationSign.destination = DestinationFind( destination ); + if( DestinationSign.destination != null_handle ) { + // got what we wanted, we're done here + return; + } + } + // if we didn't get static texture we might be able to make one + if( true == destination_set_script( numer ) ) { return; } + if( DestinationSign.script.empty() ) { return; } // no script so no way to make the texture + if( numer == "none" ) { return; } // blank or incomplete/malformed timetable, don't bother + + DestinationSign.destination = GfxRenderer->Fetch_Material( destination_request( DestinationSign.script, DestinationSign.instancing, DestinationSign.parameters ) ); +} + +std::string TDynamicObject::destination_request( std::string const &Script, std::string const &Instancing, std::string const &Parameters ) const { + + auto const trainname { [this]() -> std::string { + if( ctOwner != nullptr ) { return ctOwner->TrainName(); } + if( Mechanik != nullptr ) { return Mechanik->TrainName(); } + return "none"; } }; // shouldn't get here but, eh + auto const instance { [this, &Instancing]() -> std::string { + if( Instancing == "name" ) { return physics->Name; } + if( Instancing == "type" ) { return physics->TypeName; } + return "none"; } }; + + std::string signrequest { + "make:" + + Script + + "?" + // timetable include + + "$timetable=" + ( + ctOwner == nullptr ? + physics->Name : // leading vehicle, can point to it directly + ctOwner->Vehicle()->physics->Name ) // owned vehicle, safer to point to owner as carriages can have identical names + // basic instancing string + // NOTE: underscore doesn't have any magic meaning for the time being, it's just less likely to conflict with regular dictionary keys + + "&_id1=" + trainname() }; + // TBD, TODO: replace instancing with support for variables in extra parameters string? + if( false == Instancing.empty() ) { + signrequest += "&_id2=" + instance(); + } + // optionl extra parameters + if( false == Parameters.empty() ) { + signrequest += "&" + Parameters; + } + return signrequest; +} + +script_screens::screen_config const *TDynamicObject::script_destination( script_language &Language ) const { + + auto const &screens { Application.screens() }; + if( false == DestinationSign.lua.script.empty() && screens.runs( script_language::lua ) ) { + Language = script_language::lua; + return &DestinationSign.lua; + } + if( false == DestinationSign.wasm.script.empty() && screens.runs( script_language::wasm ) ) { + Language = script_language::wasm; + return &DestinationSign.wasm; + } + return nullptr; // no script sign, maybe a python one +} + +bool TDynamicObject::destination_set_script( std::string const &Numer ) { + + if( Numer == "none" ) { return false; } // blank or incomplete/malformed timetable, don't bother + auto language { script_language::lua }; + auto const *scriptsign { script_destination( language ) }; + if( scriptsign == nullptr ) { return false; } + + auto const signrequest { destination_request( scriptsign->script, scriptsign->instancing, scriptsign->parameters ) }; + auto const signmaterial { GfxRenderer->Fetch_Material( signrequest ) }; + if( signmaterial == null_handle ) { return false; } + auto &signtexture { GfxRenderer->Texture( GfxRenderer->Material( signmaterial )->GetTexture( 0 ) ) }; + + // vehicles showing the same request (one train, one instance) share the screen, as they share the texture + auto sign { Application.screens().acquire( { + .kind = script_screen_kind::external, + .language = language, + .script = scriptsign->script, + .key = signrequest, + .texture = &signtexture, + .frames = scriptsign->frames } ) }; + if( sign == nullptr ) { return false; } + + DestinationSign.destination = signmaterial; + DestinationSign.script_sign = std::move( sign ); + DestinationSign.script_request = signrequest.substr( signrequest.find( '?' ) + 1 ); + return true; +} + +std::shared_ptr TDynamicObject::draw_script_texture( std::string const &Name, material_handle const Material ) { + + if( false == Name.starts_with( "make:" ) || Material == null_handle ) { return nullptr; } + auto const query { Name.find( '?' ) }; + auto const script { Name.substr( 5, query == std::string::npos ? std::string::npos : query - 5 ) }; + auto const language { script_language_of( script ) }; + if( false == language.has_value() ) { return nullptr; } // a python texture, made by the texture itself + if( false == script_screens::screen_script_path( "", script ).has_value() ) { + ErrorLog( "Bad script texture: \"" + script + "\" leads outside the game's folder" ); + return nullptr; + } + + auto &queue { Application.screens() }; + auto &texture { GfxRenderer->Texture( GfxRenderer->Material( Material )->GetTexture( 0 ) ) }; + auto screen { queue.acquire( { + .kind = script_screen_kind::external, + .language = *language, + .script = script, + .key = Name, + .texture = &texture, + .frames = 0 } ) }; + if( screen == nullptr ) { return nullptr; } + queue.submit( + screen, + query == std::string::npos ? + std::make_shared() : + std::make_shared( Name.substr( query + 1 ) ), + 0 ); + return screen; +} + +material_handle TDynamicObject::DestinationFind( std::string Destination ) { + + if( Destination.empty() ) { return null_handle; } + + // destination textures are kept in the vehicle's directory so we point the current texture path there + auto const currenttexturepath { Global.asCurrentTexturePath }; + Global.asCurrentTexturePath = asBaseDir; + + auto destinationhandle { null_handle }; + + if( Destination.starts_with("make:") ) { + // autogenerated texture + destinationhandle = GfxRenderer->Fetch_Material( Destination ); + } + else { + // regular texture + Destination = Bezogonkow( Destination ); // do szukania pliku obcinamy ogonki + // now see if we can find any version of the texture + std::vector const destinations { + Destination + '@' + physics->TypeName, + Destination }; + + for( auto const &destination : destinations ) { + auto material = TextureTest( ToLower( destination ) ); + if( false == material.empty() ) { + destinationhandle = GfxRenderer->Fetch_Material( material ); + break; + } + } + } + // whether we got anything, restore previous texture path + Global.asCurrentTexturePath = currenttexturepath; + + return destinationhandle; +} + +void TDynamicObject::announce( announcement_t const Announcement, bool const Chime ) { + + if( m_doorspeakers.empty() ) { return; } + + auto const *driver { ( + ctOwner != nullptr ? + ctOwner : + Mechanik ) }; + if( driver == nullptr ) { return; } + + auto const &timetable { driver->TrainTimetable() }; + auto const &announcements { m_pasystem.announcements }; + auto playchime { Chime }; + + if( announcements[ static_cast( Announcement ) ].empty() ) { + goto followup; + } + // if the announcement sound was defined queue playback + { + sound_source stopnamesound; + switch( Announcement ) { + case announcement_t::approaching: + case announcement_t::next: { + stopnamesound = timetable.next_stop_sound(); + break; + } + case announcement_t::current: { + stopnamesound = timetable.current_stop_sound(); + break; + } + case announcement_t::destination: { + stopnamesound = timetable.last_stop_sound(); + break; + } + default: { + break; + } + } + if( stopnamesound.empty() ) { + goto followup; + } + // potentially precede the announcement with a chime... + if( true == playchime + && false == announcements[static_cast(announcement_t::chime)].empty() ) { + m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( announcement_t::chime ) ] ); + playchime = false; + } + // ...then play the announcement itself + m_pasystem.announcement_queue.emplace_back( announcements[ static_cast( Announcement ) ] ); + m_pasystem.announcement_queue.emplace_back( stopnamesound ); + } +followup: + // potentially follow up with another announcement + if( Announcement == announcement_t::next ) { + announce( announcement_t::destination, playchime ); + } +} diff --git a/vehicle/dynamic/internal.h b/vehicle/dynamic/internal.h new file mode 100644 index 000000000..40c6f734d --- /dev/null +++ b/vehicle/dynamic/internal.h @@ -0,0 +1,87 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the constants and helpers the files of the vehicles of the scenery share: only they include this header + +#pragma once + +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" + +// Ra: taki zapis funkcjonuje lepiej, ale może nie jest optymalny +#define vWorldFront glm::vec3(0, 0, 1) +#define vWorldUp glm::vec3(0, 1, 0) +#define vWorldLeft glm::cross(vWorldUp, vWorldFront) + +#define M_2PI 6.283185307179586476925286766559; + +TSubModel * +GetSubmodelFromName( TModel3d * const Model, std::string const Name ); + + +// the time spent off the track in a frame which makes it worth a warning [s] +constexpr double off_track_slow { 0.02 }; + + +using off_track_clock = std::chrono::steady_clock; + +// what the split parts of TDynamicObject share, kept out of the global namespace +namespace vehicle_dynamic { + +double seconds_since( off_track_clock::time_point const Start ); +// physics.derailment new, either vehicle of the pair off the track: the distance between their ends where they are, and +// the shares the moves of both vehicles along their own axes have in it (physics::Vehicle::coupler_gap_change()): along +// the direction they are apart in, which for ends gone past each other is the other way than along the track +void measure_off_track( neighbour_data &Neighbour, TDynamicObject const &Self, VehicleEnd End ); + +} // namespace vehicle_dynamic + diff --git a/vehicle/dynamic/lifecycle.cpp b/vehicle/dynamic/lifecycle.cpp new file mode 100644 index 000000000..d1dc4653c --- /dev/null +++ b/vehicle/dynamic/lifecycle.cpp @@ -0,0 +1,881 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a vehicle of the scenery made, set up from its definition and removed + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +const float maxrot = (float)(M_PI / 3.0); // 60° + +bool TDynamicObject::bDynamicRemove { false }; + +// helper, locates submodel with specified name in specified 3d model; returns: pointer to the submodel, or null +TSubModel * +GetSubmodelFromName( TModel3d * const Model, std::string const Name ) { + + return Model ? Model->GetFromName(Name) : nullptr; +} + +TDynamicObject::TDynamicObject() { + modelShake = glm::dvec3(0, 0, 0); +// fTrackBlock = 10000.0; // brak przeszkody na drodze + btnOn = false; + vUp = vWorldUp; + vFront = vWorldFront; + vLeft = vWorldLeft; + iNumAxles = 0; + physics = nullptr; + Mechanik = nullptr; + MechInside = false; + // McZapkie-270202 + Controller = AIdriver; + bDisplayCab = false; // 030303 +// NextConnected = PrevConnected = NULL; +// NextConnectedNo = PrevConnectedNo = 2; // ABu: Numery sprzegow. 2=nie podłączony + bEnabled = true; + MyTrack = nullptr; + // McZapkie-260202 + dWheelAngle[0] = 0.0; + dWheelAngle[1] = 0.0; + dWheelAngle[2] = 0.0; + // Winger 160204 - pantografy + // PantVolume = 3.5; + NoVoltTime = 0; + mdModel = nullptr; + mdKabina = nullptr; + // smWiazary[0]=smWiazary[1]=NULL; + smWahacze[0] = smWahacze[1] = smWahacze[2] = smWahacze[3] = nullptr; + fWahaczeAmp = 0; + smBrakeMode = nullptr; + smLoadMode = nullptr; + mdLoad = nullptr; + mdLowPolyInt = nullptr; + //smMechanik0 = smMechanik1 = NULL; + smBuforLewy[0] = smBuforLewy[1] = nullptr; + smBuforPrawy[0] = smBuforPrawy[1] = nullptr; + smBogie[0] = smBogie[1] = nullptr; + bogieRot[0] = bogieRot[1] = glm::dvec3(0, 0, 0); + modelRot = glm::dvec3(0, 0, 0); + cp1 = cp2 = sp1 = sp2 = 0; + iDirection = 1; // stoi w kierunku tradycyjnym (0, gdy jest odwrócony) + iAxleFirst = 0; // numer pierwszej osi w kierunku ruchu (przełączenie + // następuje, gdy osie sa na + // tym samym torze) + RaLightsSet(0, 0); // początkowe zerowanie stanu świateł + // Ra: domyślne ilości animacji dla zgodności wstecz (gdy brak ilości podanych + // w MMD) + // ustawienie liczby modeli animowanych podczas konstruowania obiektu a nie na 0 + // prowadzi prosto do wysypów jeśli źle zdefiniowane mmd + iAnimations = 0; // na razie nie ma żadnego + pAnimated = nullptr; + fShade = 0.0; // standardowe oświetlenie na starcie + iHornWarning = 1; // numer syreny do użycia po otrzymaniu sygnału do jazdy + asDestination = "none"; // stojący nigdzie nie jedzie + pValveGear = nullptr; // Ra: tymczasowo + iCabs = 0; // maski bitowe modeli kabin + smBrakeSet = nullptr; // nastawa hamulca (wajcha) + smLoadSet = nullptr; // nastawa ładunku (wajcha) + smWiper = nullptr; // wycieraczka (poniekąd też wajcha) + ctOwner = nullptr; // na początek niczyj + iOverheadMask = 0; // maska przydzielana przez AI pojazdom posiadającym + // pantograf, aby wymuszały + // jazdę bezprądową + tmpTraction.TractionVoltage = 0; // Ra 2F1H: prowizorka, trzeba przechować + // napięcie, żeby nie wywalało WS pod + // izolatorem + fAdjustment = 0.0; // korekcja odległości pomiędzy wózkami (np. na łukach) +} + +TDynamicObject::~TDynamicObject() { + SafeDelete( Mechanik ); + SafeDelete( physics ); + SafeDeleteArray( pAnimated ); // lista animowanych submodeli +} + +void TDynamicObject::place_on_track(TTrack *Track, double fDist, bool Reversed) +{ + for( auto &axle : m_axlesounds ) { + // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) + axle.distance = ( + Reversed ? + -axle.offset : + axle.offset + physics->Dim.L ) + fDist; + } + double fAxleDistHalf = fAxleDist * 0.5; + // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu + fDist -= 0.5 * physics->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) + switch (iNumAxles) { + // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane + case 2: // ustawianie osi na torze + Axle0.Reset(); + Axle0.Init(Track, this, iDirection ? 1 : -1); + Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); + Axle1.Reset(); + Axle1.Init(Track, this, iDirection ? 1 : -1); + Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów + break; + } + // the stretches the criteria of derailment held over were on the track the vehicle left (consistteleport) + physics->derailment_monitor.reset(); + physics->SetDerailmentDistance(0.0); + // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji + // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie + // zrobiło tego + Move( 0.0001 ); + ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) +} + +double +TDynamicObject::Init(std::string Name, // nazwa pojazdu, np. "EU07-424" + std::string BaseDir, // z którego katalogu wczytany, np. "PKP/EU07" + std::string asReplacableSkin, // nazwa wymiennej tekstury + std::string Type_Name, // nazwa CHK/MMD, np. "303E" + TTrack *Track, // tor początkowy wstwawienia (początek składu) + double fDist, // dystans względem punktu 1 + std::string DriverType, // typ obsady + double fVel, // prędkość początkowa + std::string TrainName, // nazwa składu, np. "PE2307" albo Vmax, jeśli pliku nie ma a są cyfry + float Load, // ilość ładunku + std::string LoadType, // nazwa ładunku + bool Reversed, // true, jeśli ma stać odwrotnie w składzie + std::string MoreParams // dodatkowe parametry wczytywane w postaci tekstowej + ) +{ // Ustawienie początkowe pojazdu + iDirection = Reversed ? 0 : 1; // Ra: 0, jeśli ma być wstawiony jako obrócony tyłem + asBaseDir = paths::dynamic + BaseDir + "/"; // McZapkie-310302 + asName = Name; + // derived from the name and the seed of the simulation rather than drawn at random, so that the vehicle + // keeps the same look for the whole session and looks the same for everyone in a multiplayer game, while + // another run of the same scenario, with another seed, dresses it differently + m_variantseed = hash_string( asName, Global.random_seed ); + std::string asAnimName; // zmienna robocza do wyszukiwania osi i wózków + // a vehicle prepared for being hauled dead (parameter H after its coupling, MaSzyna-EU07/maszyna#64) has nobody + // driving it, whatever its crew entry says: its cab can't be activated, and a driver in it would either take + // the train or be one more for the train's driver to put to sleep + auto const hauled { pullee_mode::requested( MoreParams ) }; + if( hauled && ( DriverType == "headdriver" || DriverType == "reardriver" ) ) { + WriteLog( "Vehicle " + asName + " is prepared for hauling (parameter H), the driver it was given is left out" ); + DriverType = "nobody"; + } + // Ra: zmieniamy znaczenie obsady na jednoliterowe, żeby dosadzić kierownika + if (DriverType == "headdriver") + DriverType = "1"; // sterujący kabiną +1 + else if (DriverType == "reardriver") + DriverType = "2"; // sterujący kabiną -1 + else if (DriverType == "passenger") + DriverType = ""; // legacy type, no longer needed + else if (DriverType == "nobody") + DriverType = ""; // nikt nie siedzi + + int Cab = 0; // numer kabiny z obsadą (nie można zająć obu) + if (DriverType == "1") // od przodu składu + Cab = 1; // iDirection?1:-1; //iDirection=1 gdy normalnie, =0 odwrotnie + else if (DriverType == "2") // od tyłu składu + Cab = -1; // iDirection?-1:1; +/* + // NOTE: leave passenger in the middle section, this is most likely to be 'passenger' section in MU trains + else if (DriverType == "p") + { + if (Random(6) < 3) + Cab = 1; + else + Cab = -1; // losowy przydział kabiny + } +*/ + // utworzenie parametrów fizyki + physics = new physics::Vehicle(iDirection ? fVel : -fVel, Type_Name, asName, Cab); + // the vehicle carries on with the odometer state of its earlier sessions (eu07/maszyna#72) + physics->SetOdometer( odometer::starting_state( odometer::states(), asName, asBaseDir ) ); + // McZapkie: TypeName musi byc nazwą CHK/MMD pojazdu + if (!physics->LoadFIZ(asBaseDir)) + { // jak wczytanie CHK się nie uda, to błąd + if (ConversionError == 666) + ErrorLog( "Bad vehicle: failed to locate definition file \"" + BaseDir + "/" + Type_Name + ".fiz" + "\"" ); + else { + ErrorLog( "Bad vehicle: failed to load definition from file \"" + BaseDir + "/" + Type_Name + ".fiz\" (error " + std::to_string( ConversionError ) + ")" ); + } + return 0.0; // zerowa długość to brak pojazdu + } + // load the cargo now that we know whether the vehicle will allow it + physics->AssignLoad( LoadType, Load ); + physics->ComputeMass(); + + bool driveractive = fVel != 0.0; // jeśli prędkość niezerowa, to aktywujemy ruch + if (!physics->CheckLocomotiveParameters( + driveractive, + (fVel > 0 ? 1 : -1) * Cab * + (iDirection ? 1 : -1))) // jak jedzie lub obsadzony to gotowy do drogi + { + Error("Parameters mismatch: dynamic object " + asName + " from \"" + BaseDir + "/" + Type_Name + "\"" ); + return 0.0; // zerowa długość to brak pojazdu + } + // controller position + physics->SetMainCtrlPos(physics->MainCtrlNoPowerPos()); + // ustawienie pozycji hamulca + physics->brakes.SetIndependentPosition(0.0); + if (driveractive) + { + if (Cab == 0) + physics->brakes.SetHandlePosition(static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) )); + else + physics->brakes.SetHandlePosition(static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_RP)) )); + + // engage independent brake if applicable, if the vehicle is to be on standby + // NOTE: with more than one driver in the consist this is likely to go awery, since all but one will be sent to sleep + // TBD, TODO: have the virtual helper release independent brakes during consist check? + if( DriverType != "" ) { + if( physics->brakes.config.localKind != TLocalBrake::ManualBrake ) { + if( fVel < 1.0 ) { + physics->IncLocalBrakeLevel( LocalBrakePosNo ); + if ( physics->EIMCtrlEmergency() ) { + physics->DecLocalBrakeLevel(1); + } + } + } + } + } + else + physics->brakes.SetHandlePosition(static_cast( std::floor(physics->brakes.driverValve->GetPos(bh_NP)) )); + + // poprawienie hamulca po ewentualnym przestawieniu przez Pascal + // TODO: check if needed, we're not in Pascal anymore, Toto + physics->BrakeLevelSet(physics->brakes.HandlePosition()); + + // dodatkowe parametry yB + MoreParams += "."; // wykonuje o jedną iterację za mało, więc trzeba mu dodać + // kropkę na koniec + size_t kropka = MoreParams.find("."); // znajdź kropke + std::string ActPar; // na parametry + while (kropka != std::string::npos) // jesli sa kropki jeszcze + { + size_t dlugosc = MoreParams.length(); + ActPar = ToUpper(MoreParams.substr(0, kropka)); // pierwszy parametr; + MoreParams = MoreParams.substr(kropka + 1, dlugosc - kropka); // reszta do dalszej obrobki + kropka = MoreParams.find("."); + + if (ActPar.substr(0, 1) == "B") // jesli hamulce + { // sprawdzanie kolejno nastaw + WriteLog("Wpis hamulca: " + ActPar); + if ( contains( ActPar, 'G') ) + { + physics->BrakeDelaySwitch(bdelay_G); + } + if( contains( ActPar, 'P' ) ) + { + physics->BrakeDelaySwitch(bdelay_P); + } + if( contains( ActPar, 'R' ) ) + { + physics->BrakeDelaySwitch(bdelay_R); + } + if( contains( ActPar, 'M' ) ) + { + physics->BrakeDelaySwitch(bdelay_R); + physics->BrakeDelaySwitch(bdelay_R + bdelay_M); + } + // wylaczanie hamulca + if ( contains( ActPar, "<>") ) // wylaczanie na probe hamowania naglego + { + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz + } + if ( contains( ActPar, '0' ) ) // wylaczanie na sztywno + { + physics->brakes.distributor->ForceEmptiness(); + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz + } + if ( contains( ActPar, 'E' ) ) // oprozniony + { + physics->brakes.distributor->ForceEmptiness(); + physics->brakePipe.reservoir->CreatePress(0); + physics->mainPipe.reservoir->CreatePress(0); + } + if ( contains( ActPar, 'Q' ) ) // oprozniony + { + physics->brakes.distributor->ForceEmptiness(); + physics->brakePipe.reservoir->CreatePress(0.0); + physics->brakePipe.SetPressure(0.0); + physics->mainPipe.reservoir->CreatePress(0.0); + physics->mainPipe.SetPressure(0.0); + physics->pantographAir.Empty(); + physics->air.Fill(0.0); + } + + if ( contains( ActPar, '1' ) ) // wylaczanie 10% + { + if (Random(10) < 1) // losowanie 1/10 + { + physics->brakes.distributor->ForceEmptiness(); + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz + } + } + if ( contains( ActPar, 'X') ) // agonalny wylaczanie 20%, usrednienie przekladni + { + if (Random(100) < 20) // losowanie 20/100 + { + physics->brakes.distributor->ForceEmptiness(); + physics->brakes.distributor->SetBrakeStatus( physics->brakes.distributor->GetBrakeStatus() | b_dmg ); // wylacz + } + if (physics->brakes.config.cylinders.leverRatio[2] * physics->brakes.config.cylinders.leverRatio[1] > + 0.01) // jesli jest nastawiacz mechaniczny PL + { + float rnd = Random(100); + if (rnd < 20) // losowanie 20/100 usrednienie + { + physics->brakes.config.cylinders.leverRatio[2] = physics->brakes.config.cylinders.leverRatio[1] = + (physics->brakes.config.cylinders.leverRatio[2] + physics->brakes.config.cylinders.leverRatio[1]) / + 2; + } + else if (rnd < 70) // losowanie 70/100-20/100 oslabienie + { + physics->brakes.config.cylinders.leverRatio[1] = physics->brakes.config.cylinders.leverRatio[1] * 0.50; + physics->brakes.config.cylinders.leverRatio[2] = physics->brakes.config.cylinders.leverRatio[2] * 0.75; + } + else if (rnd < 80) // losowanie 80/100-70/100 tylko prozny + { + physics->brakes.config.cylinders.leverRatio[2] = physics->brakes.config.cylinders.leverRatio[1]; + } + else // tylko ladowny + { + physics->brakes.config.cylinders.leverRatio[1] = physics->brakes.config.cylinders.leverRatio[2]; + } + } + } + // nastawianie ladunku + if ( contains( ActPar, 'T' ) ) // prozny + { + physics->DecBrakeMult(); + physics->DecBrakeMult(); + } // dwa razy w dol + if ( contains( ActPar, 'H' ) ) // ladowny I (dla P-Ł dalej prozny) + { + physics->IncBrakeMult(); + physics->IncBrakeMult(); + physics->DecBrakeMult(); + } // dwa razy w gore i obniz + if ( contains( ActPar, 'F' ) ) // ladowny II + { + physics->IncBrakeMult(); + physics->IncBrakeMult(); + } // dwa razy w gore + if ( contains( ActPar, 'N' ) ) // parametr neutralny + { + } + } // koniec hamulce + else if( ActPar.size() >= 3 + && ActPar.front() == 'W' ) { + // wheel + ActPar.erase( 0, 1 ); + + auto fixedflatsize { 0 }; + auto randomflatsize { 0 }; + auto flatchance { 100 }; + + while( false == ActPar.empty() ) { + // TODO: convert this whole copy and paste mess to something more elegant one day + switch( ActPar.front() ) { + case 'F': { + // fixed flat size + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + fixedflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + ActPar.erase( 0, indexend ); + break; + } + case 'R': { + // random flat size + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + randomflatsize = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + ActPar.erase( 0, indexend ); + break; + } + case 'P': { + // random flat probability + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + flatchance = std::atoi( ActPar.substr( indexstart, indexend ).c_str() ); + ActPar.erase( 0, indexend ); + break; + } + case 'H': { + // truck hunting + auto const indexstart { 1 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + auto const huntingchance { std::atoi( ActPar.substr( indexstart, indexend ).c_str() ) }; + physics->SetTruckHunting(Random(0, 100) < huntingchance); + ActPar.erase( 0, indexend ); + break; + } + default: { + // unrecognized key + ActPar.erase( 0, 1 ); + break; + } + } + } + if( Random( 0, 100 ) <= flatchance ) { + physics->SetWheelFlat( physics->WheelFlat() + ( fixedflatsize + Random( 0, randomflatsize ) ) ); + } + } // wheel + else if( ActPar.size() >= 2 + && ActPar.front() == 'T' ) { + // temperature + ActPar.erase( 0, 1 ); + + auto setambient { false }; + + while( false == ActPar.empty() ) { + switch( ActPar.front() ) { + case 'A': { + // cold start, set all temperatures to ambient level + setambient = true; + ActPar.erase( 0, 1 ); + break; + } + default: { + // unrecognized key + ActPar.erase( 0, 1 ); + break; + } + } + } + if( true == setambient ) { + // TODO: pull ambient temperature from environment data + physics->dizel_HeatSet( Global.AirTemperature ); + } + } // temperature + else if( ActPar.size() >= 2 + && ActPar.front() == 'L' ) { + // load + ActPar.erase( 0, 1 ); + // immediately followed by max load override + // TBD: make it instead an optional sub-parameter? + { + auto const indexstart { 0 }; + auto const indexend { ActPar.find_first_not_of( "1234567890", indexstart ) }; + physics->SetMaxLoad(std::atoi( ActPar.substr( indexstart, indexend ).c_str() )); + ActPar.erase( 0, indexend ); + } + while( false == ActPar.empty() ) { + switch( ActPar.front() ) { + default: { + // unrecognized key + ActPar.erase( 0, 1 ); + break; + } + } + } + } // load +/* else if (ActPar.substr(0, 1) == "") // tu mozna wpisac inny prefiks i inne rzeczy + { + // jakies inne prefiksy + } +*/ + } // koniec while kropka + + if( hauled ) { + // once the vehicle has its starting state: the hand brake and the spring brake of a standing one let go, battery off + physics->PulleeModeSwitch( true ); + } + + if (physics->CategoryFlag & 2) // jeśli samochód + { // ustawianie samochodow na poboczu albo na środku drogi + if( Track->fTrackWidth < 3.5 // jeśli droga wąska + || Track->m_road != nullptr ) // a lane of a road node is one-way, the vehicle keeps to its middle + physics->SetOffsetTrackH(0.0); // to stawiamy na środku, niezależnie od stanu + // ruchu + else if( driveractive ) {// od 3.5m do 8.0m jedzie po środku pasa, dla + // szerszych w odległości + // 1.5m + auto const lanefreespace = 0.5 * Track->fTrackWidth - physics->Dim.W; + physics->SetOffsetTrackH(lanefreespace > 1.5 ? + -0.5 * physics->Dim.W - 0.75 : // wide road, keep near centre with safe margin + lanefreespace > 0.1 ? + -0.25 * Track->fTrackWidth : // narrow fit, stay on the middle + -0.5 * physics->Dim.W - 0.075); // too narrow, just keep some minimal clearance + } + else // jak stoi, to kołem na poboczu i pobieramy szerokość razem z + // poboczem, ale nie z + // chodnikiem + physics->SetOffsetTrackH(-0.5 * (Track->WidthTotal() - physics->Dim.W) + 0.05); + iHornWarning = 0; // nie będzie trąbienia po podaniu zezwolenia na jazdę + if (fDist < 0.0) //-0.5*physics->Dim.L) //jeśli jest przesunięcie do tyłu + if (!Track->CurrentPrev()) // a nie ma tam odcinka i trzeba by coś + // wygenerować + fDist = -fDist; // to traktujemy, jakby przesunięcie było w drugą stronę + } + + create_controller( DriverType, !TrainName.empty() ); + + ShakeSpring.Init( 125.0 ); + BaseShake = baseshake_config {}; + ShakeState = shake_state {}; + ShakeStateBefore = shake_state {}; + + // McZapkie-250202 +/* + iAxles = std::min( physics->NAxles(), MaxAxles ); // ilość osi +*/ + // wczytywanie z pliku nazwatypu.mmd, w tym model + erase_extension( asReplacableSkin ); + LoadMMediaFile(Type_Name, asReplacableSkin); + // McZapkie-100402: wyszukiwanie submodeli sprzegów + btCoupler1.Init( "coupler1", mdModel ); // false - ma być wyłączony + btCoupler2.Init( "coupler2", mdModel ); + // brake hoses + btCPneumatic1.Init("cpneumatic1", mdModel); + btCPneumatic2.Init("cpneumatic2", mdModel); + btCPneumatic1r.Init("cpneumatic1r", mdModel); + btCPneumatic2r.Init("cpneumatic2r", mdModel); + // main hoses + btPneumatic1.Init("pneumatic1", mdModel); + btPneumatic2.Init("pneumatic2", mdModel); + btPneumatic1r.Init("pneumatic1r", mdModel); + btPneumatic2r.Init("pneumatic2r", mdModel); + // control cables + btCCtrl1.Init( "cctrl1", mdModel, false); + btCCtrl2.Init( "cctrl2", mdModel, false); + // gangways + btCPass1.Init( "cpass1", mdModel, false); + btCPass2.Init( "cpass2", mdModel, false); + // sygnaly + m_endsignal12.Init( "endsignal12", mdModel, false ); + m_endsignal13.Init( "endsignal13", mdModel, false ); + m_endsignal22.Init( "endsignal22", mdModel, false ); + m_endsignal23.Init( "endsignal23", mdModel, false ); + m_endsignals1.Init( "endsignals1", mdModel, false ); + m_endsignals2.Init( "endsignals2", mdModel, false ); + m_endtab1.Init( "endtab1", mdModel, false ); + m_endtab2.Init( "endtab2", mdModel, false ); + m_headlamp11.Init( "headlamp11", mdModel ); // górne + m_headlamp12.Init( "headlamp12", mdModel ); // prawe + m_headlamp13.Init( "headlamp13", mdModel ); // lewe + m_highbeam12.Init("highbeam12", mdModel); // prawe dlugie + m_highbeam13.Init("highbeam13", mdModel); // lewe dlugie + m_headlamp21.Init( "headlamp21", mdModel ); + m_headlamp22.Init( "headlamp22", mdModel ); + m_headlamp23.Init( "headlamp23", mdModel ); + m_highbeam22.Init("highbeam22", mdModel); + m_highbeam23.Init("highbeam23", mdModel); + m_headsignal12.Init( "headsignal12", mdModel ); + m_headsignal13.Init( "headsignal13", mdModel ); + m_headsignal22.Init( "headsignal22", mdModel ); + m_headsignal23.Init( "headsignal23", mdModel ); + // informacja, czy ma poszczególne światła + iInventory[ VehicleEnd::front ] |= m_endsignal12.Active() ? light::redmarker_right : 0; + iInventory[ VehicleEnd::front ] |= m_endsignal13.Active() ? light::redmarker_left : 0; + iInventory[ VehicleEnd::rear ] |= m_endsignal22.Active() ? light::redmarker_right : 0; + iInventory[ VehicleEnd::rear ] |= m_endsignal23.Active() ? light::redmarker_left : 0; + iInventory[ VehicleEnd::front ] |= m_endsignals1.Active() ? light::redmarker_left | light::redmarker_right : 0; + iInventory[ VehicleEnd::rear ] |= m_endsignals2.Active() ? light::redmarker_left | light::redmarker_right : 0; + iInventory[ VehicleEnd::front ] |= m_endtab1.Active() ? light::rearendsignals : 0; // tabliczki blaszane + iInventory[ VehicleEnd::rear ] |= m_endtab2.Active() ? light::rearendsignals : 0; + iInventory[ VehicleEnd::front ] |= m_headlamp11.Active() ? light::headlight_upper : 0; + iInventory[ VehicleEnd::front ] |= m_headlamp12.Active() ? light::headlight_right : 0; + iInventory[ VehicleEnd::front ] |= m_headlamp13.Active() ? light::headlight_left : 0; + + iInventory[VehicleEnd::front] |= m_highbeam12.Active() ? light::highbeamlight_right : 0; + iInventory[VehicleEnd::front] |= m_highbeam13.Active() ? light::highbeamlight_left : 0; + + iInventory[ VehicleEnd::rear ] |= m_headlamp21.Active() ? light::headlight_upper : 0; + iInventory[ VehicleEnd::rear ] |= m_headlamp22.Active() ? light::headlight_right : 0; + iInventory[ VehicleEnd::rear ] |= m_headlamp23.Active() ? light::headlight_left : 0; + iInventory[ VehicleEnd::front ] |= m_headsignal12.Active() ? light::auxiliary_right : 0; + iInventory[ VehicleEnd::front ] |= m_headsignal13.Active() ? light::auxiliary_left : 0; + iInventory[ VehicleEnd::rear ] |= m_headsignal22.Active() ? light::auxiliary_right : 0; + iInventory[ VehicleEnd::rear ] |= m_headsignal23.Active() ? light::auxiliary_left : 0; + + iInventory[VehicleEnd::rear] |= m_highbeam22.Active() ? light::highbeamlight_right : 0; + iInventory[VehicleEnd::rear] |= m_highbeam23.Active() ? light::highbeamlight_left : 0; + + btExteriorOnly.Init("external_only", mdModel, false); + + btMechanik1.Init( "mechanik1", mdLowPolyInt, false); + btMechanik2.Init( "mechanik2", mdLowPolyInt, false); + + if( physics->diesel.heat.water.config.shutters ) { + btShutters1.Init( "shutters1", mdModel, false ); + } + if( physics->diesel.heat.water_aux.config.shutters ) { + btShutters2.Init( "shutters2", mdModel, false ); + } + TurnOff(); // resetowanie zmiennych submodeli + + if( mdLowPolyInt != nullptr ) { + // check the low poly interior for potential compartments of interest, ie ones which can be individually lit + // TODO: definition of relevant compartments in the .mmd file + TSubModel *submodel { nullptr }; + if( ( submodel = mdLowPolyInt->GetFromName( "cab0" ) ) != nullptr ) { + Sections.push_back( { submodel, nullptr, 0, 0.0f } ); + LowPolyIntCabs[ 0 ] = submodel; + } + if( ( submodel = mdLowPolyInt->GetFromName( "cab1" ) ) != nullptr ) { + Sections.push_back( { submodel, nullptr, 0, 0.0f } ); + LowPolyIntCabs[ 1 ] = submodel; + } + if( ( submodel = mdLowPolyInt->GetFromName( "cab2" ) ) != nullptr ) { + Sections.push_back( { submodel, nullptr, 0, 0.0f } ); + LowPolyIntCabs[ 2 ] = submodel; + } + // passenger car compartments + std::vector nameprefixes = { "corridor", "korytarz", "compartment", "przedzial" }; + for( auto const &nameprefix : nameprefixes ) { + init_sections( mdLowPolyInt, nameprefix, physics->CompartmentLights.start_type == start_t::manual ); + } + // the inside of the door wings, if the interior has them + init_interior_doors(); + } + // destination sign + if( mdModel ) { + init_destination( mdModel ); + } + // 'external_load' is an optional special section in the main model, pointing to submodel of external load + if( mdModel ) { + init_sections( mdModel, "external_load", false ); + } + update_load_sections(); + update_load_visibility(); + // wyszukiwanie zderzakow + if( mdModel ) { + // jeśli ma w czym szukać + for( int i = 0; i < 2; i++ ) { + asAnimName = std::string( "buffer_left0" ) + std::to_string( i + 1 ); + smBuforLewy[ i ] = mdModel->GetFromName( asAnimName ); + if( smBuforLewy[ i ] ) + smBuforLewy[ i ]->WillBeAnimated(); // ustawienie flagi animacji + asAnimName = std::string( "buffer_right0" ) + std::to_string( i + 1 ); + smBuforPrawy[ i ] = mdModel->GetFromName( asAnimName ); + if( smBuforPrawy[ i ] ) + smBuforPrawy[ i ]->WillBeAnimated(); + } + } + if( Track->fSoundDistance > 0.f ) { + for( auto &axle : m_axlesounds ) { + // wyszukiwanie osi (0 jest na końcu, dlatego dodajemy długość?) + axle.distance = + clamp_circular( + ( Reversed ? + -axle.offset : + axle.offset ) + - 0.5 * physics->Dim.L + + fDist, + Track->fSoundDistance ); + } + } + // McZapkie-250202 end. + Track->AddDynamicObject(this); // wstawiamy do toru na pozycję 0, a potem przesuniemy + // McZapkie: zmieniono na ilosc osi brane z chk + // iNumAxles=(physics->NAxles()>3 ? 4 : 2 ); + initial_track = MyTrack; + iNumAxles = 2; + // McZapkie-090402: odleglosc miedzy czopami skretu lub osiami + fAxleDist = safe_clamp( + std::max( physics->BDist(), physics->ADist() ), + 0.2, //żeby się dało wektory policzyć + physics->Dim.L - 0.2 ); // nie mogą być za daleko bo będzie "walenie w mur" + double fAxleDistHalf = fAxleDist * 0.5; + // przesuwanie pojazdu tak, aby jego początek był we wskazanym miejcu + fDist -= 0.5 * physics->Dim.L; // dodajemy pół długości pojazdu, bo ustawiamy jego środek (zliczanie na minus) + switch (iNumAxles) { + // Ra: pojazdy wstawiane są na tor początkowy, a potem przesuwane + case 2: // ustawianie osi na torze + Axle0.Init(Track, this, iDirection ? 1 : -1); + Axle0.Move((iDirection ? fDist : -fDist) + fAxleDistHalf, false); + Axle1.Init(Track, this, iDirection ? 1 : -1); + Axle1.Move((iDirection ? fDist : -fDist) - fAxleDistHalf, false); // false, żeby nie generować eventów + break; + case 4: + Axle0.Init(Track, this, iDirection ? 1 : -1); + Axle0.Move((iDirection ? fDist : -fDist) + (fAxleDistHalf + physics->ADist() * 0.5), false); + Axle1.Init(Track, this, iDirection ? 1 : -1); + Axle1.Move((iDirection ? fDist : -fDist) - (fAxleDistHalf + physics->ADist() * 0.5), false); + // Axle2.Init(Track,this,iDirection?1:-1); + // Axle2.Move((iDirection?fDist:-fDist)-(fAxleDistHalf-physics->ADist()*0.5),false); + // Axle3.Init(Track,this,iDirection?1:-1); + // Axle3.Move((iDirection?fDist:-fDist)+(fAxleDistHalf-physics->ADist()*0.5),false); + break; + } + // potrzebne do wyliczenia aktualnej pozycji; nie może być zero, bo nie przeliczy pozycji + // teraz jeszcze trzeba przypisać pojazdy do nowego toru, bo przesuwanie początkowe osi nie + // zrobiło tego + Move( 0.0001 ); + ABuCheckMyTrack(); // zmiana toru na ten, co oś Axle0 (oś z przodu) + // Ra: ustawienie pozycji do obliczania sprzęgów + physics->SetLoc({ + -vPosition.x, + vPosition.z, + vPosition.y }); // normalnie przesuwa ComputeMovement() w Update() + // ABuWozki 060504 + if (mdModel) // jeśli ma w czym szukać + { + smBogie[0] = mdModel->GetFromName("bogie1"); // Ra: bo nazwy są małymi + smBogie[1] = mdModel->GetFromName("bogie2"); + if (!smBogie[0]) + smBogie[0] = mdModel->GetFromName("boogie01"); // Ra: alternatywna nazwa + if (!smBogie[1]) + smBogie[1] = mdModel->GetFromName("boogie02"); // Ra: alternatywna nazwa + if (smBogie[0]) + smBogie[0]->WillBeAnimated(); + if (smBogie[1]) + smBogie[1]->WillBeAnimated(); + sm_winter_variant = mdModel->GetFromName("winter_variant"); + sm_spring_variant = mdModel->GetFromName("spring_variant"); + sm_summer_variant = mdModel->GetFromName("summer_variant"); + sm_autumn_variant = mdModel->GetFromName("autumn_variant"); + } + // ABu: zainicjowanie zmiennej, zeby nic sie nie ruszylo w pierwszej klatce, + // potem juz liczona prawidlowa wartosc masy + physics->ComputeConstans(); + // wektor podłogi dla wagonów, przesuwa ładunek + vFloor = glm::dvec3(0, 0, physics->Floor); + + // długość większa od zera oznacza OK; 2mm docisku? + return physics->Dim.L; +} + +int +TDynamicObject::init_sections( TModel3d const *Model, std::string const &Nameprefix, bool const Overrideselfillum ) { + + auto sectioncount = 0; + auto sectionindex = 0; + TSubModel *sectionsubmodel { nullptr }; + + do { + // section names for index < 10 match either prefix0X or prefixX + // section names above 10 match prefixX + auto const sectionindexname { std::to_string( sectionindex ) }; + sectionsubmodel = Model->GetFromName( Nameprefix + sectionindexname ); + if( sectionsubmodel == nullptr + && sectionindex < 10 ) { + sectionsubmodel = Model->GetFromName( Nameprefix + "0" + sectionindexname ); + } + if( sectionsubmodel != nullptr ) { + // HACK: disable automatic self-illumination threshold, at least until 3d model update + if( Overrideselfillum ) { + sectionsubmodel->SetSelfIllum( 2.0f, true, false ); + } + Sections.push_back( { + sectionsubmodel, + nullptr, // pointers to load sections are generated afterwards + 0, + 0.0f } ); + ++sectioncount; + } + ++sectionindex; + } while( sectionsubmodel != nullptr + || sectionindex < 2 ); // chain can start from prefix00 or prefix01 + + return sectioncount; +} + +// a door wing of the main model is seen from the outside, lit as the exterior. its namesake in the low poly interior, +// if the model has one, follows its moves and is lit with the interior, by its compartment section if it's in one +void +TDynamicObject::init_interior_doors() { + + if( mdLowPolyInt == nullptr ) { return; } + + for( auto &animation : pAnimations ) { + // the door animation is only set up for a wing found in the main model + if( false == door_wings::is_wing( animation.iFlags ) ) { continue; } + if( ( animation.yUpdate == nullptr ) || ( animation.smAnimated == nullptr ) ) { continue; } + + auto *interiorwing { mdLowPolyInt->GetFromName( animation.smAnimated->pName ) }; + if( ( interiorwing == nullptr ) || ( interiorwing == animation.smAnimated ) ) { continue; } + + interiorwing->WillBeAnimated(); + animation.smInterior = interiorwing; + } +} + +bool +TDynamicObject::init_destination( TModel3d *Model ) { + + if( Model->GetSMRoot() == nullptr ) { return false; } + + std::tie( DestinationSign.sign, DestinationSign.has_light ) = Model->GetSMRoot()->find_replacable4(); + + return DestinationSign.sign != nullptr; +} + +void +TDynamicObject::create_controller( std::string const Type, bool const Trainset ) { + + if( Type == "" ) { return; } + + // McZapkie-151102: rozkład jazdy czytany z pliku *.txt z katalogu w którym jest sceneria + if( Type == "1" + || Type == "2" ) { + // McZapkie-110303: mechanik i rozklad tylko gdy jest obsada + Mechanik = new TController( Controller, this, Aggressive ); + + if( false == Trainset ) { + // jeśli nie w składzie + // załączenie rozrządu (wirtualne kabiny) itd. + Mechanik->DirectionInitial(); + // tryb pociągowy z ustaloną prędkością (względem sprzęgów) + Mechanik->PutCommand( + "Timetable:", + physics->V() * 3.6 * ( iDirection ? -1.0 : 1.0 ), + 0, + nullptr ); + } + } + else if( Type == "p" ) { + // obserwator w charakterze pasażera + // Ra: to jest niebezpieczne, bo w razie co będzie pomagał hamulcem bezpieczeństwa + Mechanik = new TController( Controller, this, Easyman, false ); + } +} diff --git a/vehicle/dynamic/lights.cpp b/vehicle/dynamic/lights.cpp new file mode 100644 index 000000000..0549ff63f --- /dev/null +++ b/vehicle/dynamic/lights.cpp @@ -0,0 +1,313 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the lights of a vehicle and the signals they make + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::SetLights() { + auto const isfrontcaboccupied { physics->CabOccupied() * DirectionGet() >= 0 }; + int const automaticmarkers { physics->CabActive == 0 && physics->InactiveCabFlag & activation::redmarkers + ? light::redmarker_left + light::redmarker_right : 0 }; + auto const lightpos { physics->LightsPos() - 1 }; + ByEnd const cablights { + automaticmarkers > 0 ? automaticmarkers : physics->Lights[ VehicleEnd::front ][ lightpos ], + automaticmarkers > 0 ? automaticmarkers : physics->Lights[ VehicleEnd::rear ][ lightpos ] }; + // the custom position keeps the lights lit at coupled ends as well + auto const ignorecouplings { physics->LightsPos() == 18 }; + auto *vehicle { GetFirstDynamic( physics->CabOccupied() >= 0 ? VehicleEnd::front : VehicleEnd::rear, Coupling::control ) }; + while( vehicle != nullptr ) { + // set lights on given side if there's no coupling with another vehicle, turn them off otherwise + auto const iscoupled { [ vehicle, ignorecouplings ]( VehicleEnd const Side ) { + return false == ignorecouplings + && vehicle->physics->Couplers[ Side ].CouplingFlag.HasAny(Coupling::coupler) + && vehicle->physics->Neighbours[ Side ].vehicle != nullptr; } }; + auto const lights { lights_programmer::vehicle_lights( + cablights, isfrontcaboccupied, vehicle->iDirection, { iscoupled( VehicleEnd::front ), iscoupled( VehicleEnd::rear ) } ) }; + vehicle->RaLightsSet( lights.head, lights.rear ); + vehicle = isfrontcaboccupied ? vehicle->Next(Coupling::control) : vehicle->Prev(Coupling::control); + } +}; + +void TDynamicObject::RaLightsSet(int head, int rear) +{ // zapalenie świateł z przodu i z + // tyłu, zależne od kierunku + // pojazdu + if (!physics) + return; // może tego nie być na początku + if (rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) + { // jeśli koniec pociągu, to trzeba ustalić, czy + // jest tam czynna lokomotywa + // EN57 może nie mieć końcówek od środka członu + if (physics->Power > 1.0) // jeśli ma moc napędową + if (!physics->DirActive) // jeśli nie ma ustawionego kierunku + { // jeśli ma zarówno światła jak i końcówki, ustalić, czy jest w stanie aktywnym + // np. lokomotywa na zimno będzie mieć końcówki a nie światła + rear = light::rearendsignals; // tablice blaszane + // trzeba to uzależnić od "załączenia baterii" w pojeździe + } + if( rear == ( light::redmarker_left | light::redmarker_right | light::rearendsignals ) ) // jeśli nadal obydwie możliwości + if( iInventory[ + ( iDirection ? + VehicleEnd::rear : + VehicleEnd::front ) ] & ( light::redmarker_left | light::redmarker_right ) ) { + // czy ma jakieś światła czerowone od danej strony + rear = light::redmarker_left | light::redmarker_right; // dwa światła czerwone + } + else { + rear = light::rearendsignals; // tablice blaszane + } + } + // w zależności od kierunku pojazdu w składzie + if( head >= 0 ) { + auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; + physics->SetLitLights( vehicleend, head & iInventory[vehicleend] ); + bool tLeft = physics->LitLights()[vehicleend] & (light::auxiliary_left | light::headlight_left); // roboczo czy jakiekolwiek swiatlo z lewej jest zapalone + bool tRight = physics->LitLights()[vehicleend] & (light::auxiliary_right | light::headlight_right); // a tu z prawej + if (Controller == Humandriver) { + + auto const dps{physics->currentDimPosition()}; + + // domyślnie + HighBeamLights = false; + DimHeadlights = false; + + // obsługa OFF + if (dps.isOff) + { + //physics->SetLitLights(vehicleend, physics->LitLights()[vehicleend] & (0 | light::rearendsignals)); // zostawiamy tylko tabliczki jesli sa + HighBeamLights = false; + DimHeadlights = false; + // the headlights at the end of the active cab: A at the front, B at the rear + if( auto const cabend { CabEnd( physics->CabActive ) }; cabend.has_value() ) { + ( *cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff ) = true; + } + } + else + { + if( auto const cabend { CabEnd( physics->CabActive ) }; cabend.has_value() ) { + ( *cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff ) = false; + } + } + + // obsługa przyciemnionych + DimHeadlights = dps.isDimmed; + + // obsługa długich + if (dps.isHighBeam) + { + HighBeamLights = true; + } + } + + } + if( rear >= 0 ) { + auto const vehicleend{ iDirection > 0 ? VehicleEnd::rear : VehicleEnd::front }; + physics->SetLitLights( vehicleend, rear & iInventory[vehicleend] ); + } +}; + +void TDynamicObject::SetLightDimmings() +{ + if (Controller == Humandriver) + { + + auto const dps{physics->currentDimPosition()}; + + // domyślnie + HighBeamLights = false; + DimHeadlights = false; + + // obsługa OFF: the headlights at the end of the active cab, as RaLightsSet() picks them: A at the front, B at the + // rear, none without an active cab + if (dps.isOff) + { + HighBeamLights = false; + DimHeadlights = false; + if (auto const cabend{CabEnd(physics->CabActive)}; cabend.has_value()) + { + (*cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff) = true; + } + } + else + { + if (auto const cabend{CabEnd(physics->CabActive)}; cabend.has_value()) + { + (*cabend == VehicleEnd::front ? HeadlightsAoff : HeadlightsBoff) = false; + } + } + + // obsługa przyciemnionych + DimHeadlights = dps.isDimmed; + + // obsługa długich + if (dps.isHighBeam) + { + // obsługa długich + if (dps.isHighBeam) + { + HighBeamLights = true; + } + } + } +} + +bool TDynamicObject::has_signal_pc1_on() const { + + auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const equippedlights { iInventory[ vehicleend ] }; + auto const pattern { equippedlights & ( light::headlight_left | light::headlight_right | light::headlight_upper ) }; + auto const patternfallback { equippedlights & ( light::auxiliary_left | light::auxiliary_right | light::headlight_upper ) }; + auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; + auto const activelights { physics->LitLights()[ vehicleend ] }; + + return (pattern != 0 && activelights == pattern) || (hasauxiliarylights && activelights == patternfallback) || + (pattern == 0 && patternfallback == 0 && activelights == light::rearendsignals); // pc4 +} + +bool TDynamicObject::has_signal_pc2_on() const { + + auto const vehicleend { iDirection > 0 ? VehicleEnd::front : VehicleEnd::rear }; + auto const equippedlights { iInventory[ vehicleend ] }; + auto const pattern { equippedlights & ( light::redmarker_left | light::headlight_right | light::headlight_upper ) }; + auto const patternfallback { equippedlights & ( light::redmarker_left | light::auxiliary_right | light::headlight_upper ) }; + auto const hasauxiliarylights { ( equippedlights & ( light::auxiliary_left | light::auxiliary_right ) ) != 0 }; + auto const activelights { physics->LitLights()[ vehicleend ] }; + + return activelights == pattern || (hasauxiliarylights && activelights == patternfallback); +} + +bool TDynamicObject::has_signal_pc5_on() const { + + auto const vehicleend { iDirection > 0 ? VehicleEnd::rear : VehicleEnd::front }; + auto const equippedlights { iInventory[ vehicleend ] }; + auto const pattern { equippedlights & ( light::redmarker_left | light::redmarker_right ) }; + auto const patternfallback { equippedlights & light::rearendsignals }; + auto const activelights { physics->LitLights()[ vehicleend ] }; + + return (pattern != 0 && activelights == pattern) || (patternfallback != 0 && activelights == patternfallback); +} + +bool TDynamicObject::has_signal_on( VehicleEnd const Side, int const Pattern ) const { +/* + auto const vehicleend { iDirection > 0 ? Side : 1 - Side }; + auto const pattern { iInventory[ vehicleend ] & Pattern }; + + return ( physics->LitLights()[ vehicleend ] == pattern ); +*/ + return physics->LitLights()[Side] == (Pattern & iInventory[Side]); +} + +TDimension const &TDynamicObject::Dimensions() const { + return physics->Dim; +} + +double TDynamicObject::Speed() const { + return physics->V(); +} + +int TDynamicObject::ActiveCab() const { + return physics->CabActive; +} + +float TDynamicObject::CompartmentLightIntensity() const { + return physics->CompartmentLights.intensity; +} + +double TDynamicObject::CouplerAdapterHeight( VehicleEnd const End ) const { + return physics->Couplers[ End ].adapter_height; +} + +double TDynamicObject::CouplerAdapterLength( VehicleEnd const End ) const { + return physics->Couplers[ End ].adapter_length; +} + +void TDynamicObject::ExhaustScales( float &Velocity, float &Opacity ) const { + Opacity = static_cast(physics->diesel.fill); + if (physics->EngineType == TEngineType::DieselElectric) + { + if (physics->diesel.spinningUp == true) + { + Velocity = static_cast(0.38*(((physics->enrot)/2)*0.5)); + } + else + { + Velocity = static_cast((((physics->enrot)/60)*0.6) * (physics->EnginePower *0.03)); + } + } +} + +bool TDynamicObject::LowVoltagePowered() const { + return ( true == physics->lowVoltage.Is24vAvailable() ) || ( true == physics->lowVoltage.Is110vAvailable() ); +} + +int TDynamicObject::LightsSwitchedOn( VehicleEnd const End ) const { + return physics->LitLights()[ End ]; +} + +double TDynamicObject::HeadlightsMultiplier() const { + if( DimHeadlights && !HighBeamLights ) { return physics->dimMultiplier; } // tylko przyciemnione + if( !DimHeadlights && !HighBeamLights ) { return physics->normMultiplier; } // normalne + if( DimHeadlights && HighBeamLights ) { return physics->highDimMultiplier; } // przyciemnione dlugie + return physics->highMultiplier; // dlugie zwykle +} + +glm::vec3 TDynamicObject::HeadlightsColor() const { + return { + static_cast(physics->refR) / 255.0f, + static_cast(physics->refG) / 255.0f, + static_cast(physics->refB) / 255.0f }; +} diff --git a/vehicle/dynamic/load.cpp b/vehicle/dynamic/load.cpp new file mode 100644 index 000000000..309fe4033 --- /dev/null +++ b/vehicle/dynamic/load.cpp @@ -0,0 +1,301 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the load of a vehicle, its exchange at the stops, how it shows + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +// initiates load change by specified amounts, with a platform on specified side +void TDynamicObject::LoadExchange( int const Disembark, int const Embark, int const Platforms ) { +/* + if( ( physics->Doors.open_control == control_t::passenger ) + || ( physics->Doors.open_control == control_t::mixed ) ) { + // jeśli jedzie do tyłu, to drzwi otwiera odwrotnie + auto const lewe = ( DirectionGet() > 0 ) ? 1 : 2; + auto const prawe = 3 - lewe; + if( Platform & lewe ) { + physics->OperateDoors( VehicleSide::left, true, range_t::local ); + } + if( Platform & prawe ) { + physics->OperateDoors( VehicleSide::right, true, range_t::local ); + } + } +*/ + if( Platforms == 0 ) { return; } // edge case, if there's no accessible platforms discard the request + + m_exchange.unload_count += Disembark; + m_exchange.load_count += Embark; + m_exchange.platforms = Platforms; + m_exchange.time = 0.0; +} + +// calculates time needed to complete current load change +float TDynamicObject::LoadExchangeTime( int const Platforms ) { + + m_exchange.platforms = Platforms; + return LoadExchangeTime(); +} + +float TDynamicObject::LoadExchangeTime() const { + + if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return 0.f; } + + auto const baseexchangetime { m_exchange.unload_count / physics->UnLoadSpeed + m_exchange.load_count / physics->LoadSpeed }; + auto const nominalexchangespeedfactor { ( m_exchange.platforms == 3 ? 2.f : 1.f ) }; + auto const actualexchangespeedfactor { LoadExchangeSpeed() }; + + return baseexchangetime / ( actualexchangespeedfactor > 0.f ? actualexchangespeedfactor : nominalexchangespeedfactor ); +} + +// calculates current load exchange rate +float TDynamicObject::LoadExchangeSpeed() const { + // platforms (1:left, 2:right, 3:both) + // with exchange performed on both sides waiting times are halved + auto exchangespeedfactor { 0.f }; + auto const lewe { DirectionGet() > 0 ? 1 : 2 }; + auto const prawe { 3 - lewe }; + if( m_exchange.platforms & lewe ) { + exchangespeedfactor += physics->Doors.instances[VehicleSide::left].is_open ? 1.f : 0.f; + } + if( m_exchange.platforms & prawe ) { + exchangespeedfactor += physics->Doors.instances[VehicleSide::right].is_open ? 1.f : 0.f; + } + + return exchangespeedfactor; +} + +// update state of load exchange operation +void TDynamicObject::update_exchange( double const Deltatime ) { + + // TODO: move offset calculation after initial check, when the loading system is all unified + update_load_offset(); + + if( m_exchange.unload_count < 0.01 && m_exchange.load_count < 0.01 ) { return; } + + if( physics->Vel < 2.0 ) { + + auto const exchangespeed { LoadExchangeSpeed() }; + + if( exchangespeed < ( m_exchange.platforms == 3 ? 2.f : 1.f ) ) { + // the exchange isn't performed at optimal rate, or at all. try to open viable vehicle doors to speed it up + auto const lewe { DirectionGet() > 0 ? 1 : 2 }; + auto const prawe { 3 - lewe }; + if( m_exchange.platforms & lewe + && false == (physics->Doors.instances[VehicleSide::left].is_open || physics->Doors.instances[VehicleSide::left].is_opening) ) { + // try to open left door + physics->OperateDoors( VehicleSide::left, true, range_t::local ); + } + if( m_exchange.platforms & prawe + && false == (physics->Doors.instances[VehicleSide::right].is_open || physics->Doors.instances[VehicleSide::right].is_opening) ) { + // try to open right door + physics->OperateDoors( VehicleSide::right, true, range_t::local ); + } + } + + if( exchangespeed > 0.f ) { + + m_exchange.time += Deltatime; + while( m_exchange.unload_count > 0.01 + && m_exchange.time >= 1.0 ) { + + m_exchange.time -= 1.0; + auto const exchangesize = std::min( m_exchange.unload_count, physics->UnLoadSpeed * exchangespeed ); + m_exchange.unload_count -= exchangesize; + physics->UnloadStep( exchangesize ); + update_load_visibility(); + } + if( m_exchange.unload_count < 0.01 ) { + // finish any potential unloading operation before adding new load + // don't load more than can fit + m_exchange.load_count = std::min( m_exchange.load_count, physics->MaxLoad() - physics->LoadAmount() ); + while( m_exchange.load_count > 0.01 + && m_exchange.time >= 1.0 ) { + + m_exchange.time -= 1.0; + auto const exchangesize = std::min( m_exchange.load_count, physics->LoadSpeed * exchangespeed ); + m_exchange.load_count -= exchangesize; + physics->LoadStep( exchangesize ); + update_load_visibility(); + } + } + } + } + + if( physics->Vel > 2.0 ) { + // if the vehicle moves too fast cancel the exchange + m_exchange.unload_count = 0; + m_exchange.load_count = 0; + } + + if( m_exchange.unload_count < 0.01 + && m_exchange.load_count < 0.01 ) { + + physics->FinishLoadExchange(); + // if the exchange is completed (or canceled) close the door, if applicable + if( physics->Doors.close_control == control_t::passenger + || physics->Doors.close_control == control_t::mixed ) { + + if( physics->Vel > 2.0 + || Random() < ( + // remotely controlled door are more likely to be left open + physics->Doors.close_control == control_t::passenger ? 0.75 : 0.50) ) { + + physics->OperateDoors( VehicleSide::left, false, range_t::local ); + physics->OperateDoors( VehicleSide::right, false, range_t::local ); + } + } + // if the vehicle was emptied potentially switch load visualization model + if( physics->LoadAmount() == 0 ) { + physics->AssignLoad( "" ); + } + } +} + +void TDynamicObject::LoadUpdate() { + + physics->AcknowledgeLoadExchange(); // po zakończeniu będzie równe zero + // przeładowanie modelu ładunku + // whether we succeed or not don't try more than once + if( physics->TakeLoadTypeChange() ) { + // bieżąca ścieżka do tekstur to dynamic/... + Global.asCurrentTexturePath = asBaseDir; + mdLoad = LoadMMediaFile_mdload( physics->LoadType.name ); + // TODO: discern from vehicle component which merely uses vehicle directory and has no animations, so it can be initialized outright + // and actual vehicles which get their initialization after their animations are set up + if( mdLoad != nullptr ) { + mdLoad->Init(); + } + // update bindings between lowpoly sections and potential load chunks placed inside them + update_load_sections(); + // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = std::string( paths::textures ); + } +} + +void +TDynamicObject::update_load_sections() { + + SectionLoadOrder.clear(); + + for( auto §ion : Sections ) { + + section.load = GetSubmodelFromName( mdLoad, section.compartment->pName ); + + if( section.load != nullptr ) { + // create entry for each load model chunk assigned to the section + // TBD, TODO: store also pointer to chunk submodel and control its visibility more directly, instead of per-section visibility flag? + auto loadchunkcount { section.load->count_children() }; + while( loadchunkcount-- ) { + SectionLoadOrder.push_back( §ion ); + } + // HACK: disable automatic self-illumination threshold, at least until 3d model update + if( physics->CompartmentLights.start_type == start_t::manual ) { + section.load->SetSelfIllum( 2.0f, true, false ); + } + } + } + shuffle_load_order(); +} + +void +TDynamicObject::update_load_visibility() { + // start with clean load chunk visibility slate + for( auto §ion : Sections ) { + section.load_chunks_visible = 0; + } + // each entry in load order sequence matches a single chunk of the section it points to + // the length of load order sequence matches total number of load chunks + auto const loadpercentage { ( + physics->MaxLoad() == 0.f ? + 0.0 : + physics->LoadAmount() / physics->MaxLoad() ) }; + auto visiblechunkcount { ( + SectionLoadOrder.empty() ? + 0 : + static_cast( std::ceil( loadpercentage * SectionLoadOrder.size() - 0.001f ) ) ) }; + for( auto *section : SectionLoadOrder ) { + if( visiblechunkcount == 0 ) { break; } + section->load_chunks_visible++; + --visiblechunkcount; + } +} + +void +TDynamicObject::update_load_offset() { + + if( physics->LoadType.offset_min == 0.f ) { return; } + + auto const loadpercentage { ( + physics->MaxLoad() == 0.f ? + 0.0 : + 100.0 * physics->LoadAmount() / physics->MaxLoad() ) }; + + LoadOffset = std::lerp( physics->LoadType.offset_min, 0.f, safe_clamp( 0.0, 1.0, loadpercentage * 0.01 ) ); +} + +void +TDynamicObject::shuffle_load_order() { + + // order of visible load chunks, nothing security related -- see the engines in Globals.h + std::shuffle( std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), Global.random_engine ); // NOSONAR + // shift chunks assigned to corridors to the end of the list, so they show up last + std::stable_partition( + std::begin( SectionLoadOrder ), std::end( SectionLoadOrder ), + []( vehicle_section const *section ) { + return section->compartment->pName.find("compartment") == 0 || section->compartment->pName.find("przedzial") == 0; } ); + // NOTE: potentially we're left with a mix of corridor and external section loads + // but that's not necessarily a wrong outcome, so we leave it this way for the time being +} diff --git a/vehicle/dynamic/mmd.cpp b/vehicle/dynamic/mmd.cpp new file mode 100644 index 000000000..e77dacde2 --- /dev/null +++ b/vehicle/dynamic/mmd.cpp @@ -0,0 +1,2392 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// reading the definition of the model and the sounds of a vehicle (.mmd) + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "vehicle/driverfigure.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +namespace +{ + + +// a luadestinationsign: or wasmdestinationsign: block, its script in the vehicle folder when it has no path of its own +void deserialize_script_sign( cParser &Parser, script_screens::screen_config &Sign, std::string const &Folder ) { + + Sign.deserialize( Parser ); + if( Sign.script.empty() ) { return; } + if( auto path { script_screens::screen_script_path( Folder, Sign.script ) }; path.has_value() ) { + Sign.script = std::move( *path ); + } + else { + ErrorLog( "Bad script sign: \"" + Sign.script + "\" leads outside the game's folder" ); + Sign.script.clear(); + } +} + +struct driver_position_key { + std::string_view token; + std::size_t cab; // 0 for the cab 1, 1 for the cab 2 + bool sitting; +}; + +constexpr std::array driver_position_keys{{ + {"driver1pos:", 0, false}, {"driver1sitpos:", 0, true}, {"driver2pos:", 1, false}, {"driver2sitpos:", 1, true}}}; + +// driverNpos: and driverNsitpos: of the cabs 1 and 2 of the internaldata: section, kept for the driver figures; any +// other token is left alone +void read_driver_position(cParser &Parser, std::string_view const Token, std::array &Cabs) { + auto const key{std::ranges::find(driver_position_keys, Token, &driver_position_key::token)}; + if (key == driver_position_keys.end()) { + return; + } + Parser.getTokens(3, false); + glm::vec3 position{0.f}; + Parser >> position.x >> position.y >> position.z; + auto &cab{Cabs[key->cab]}; + if (key->sitting) { + cab.sitting_position = position; + } + else { + cab.position = position; + } +} + +} // namespace + +// McZapkie-250202 +// wczytywanie pliku z danymi multimedialnymi (dzwieki) +void TDynamicObject::LoadMMediaFile( std::string const &TypeName, std::string const &ReplacableSkin ) { + rTypeName = TypeName; + rReplacableSkin = ReplacableSkin; + Global.asCurrentDynamicPath = asBaseDir; + std::string asFileName = asBaseDir + TypeName + ".mmd"; + std::string asAnimName; + bool Stop_InternalData = false; + pants = nullptr; // wskaźnik pierwszego obiektu animującego dla pantografów + wipers = nullptr; // wskaznik pierwszego obiektu animujacego dla wycieraczek + { + // preliminary check whether the file exists + cParser parser( TypeName + ".mmd", cParser::buffer_FILE, asBaseDir ); + if( false == parser.ok() ) { + ErrorLog( "Failed to load appearance data for vehicle " + physics->Name ); + return; + } + } + // use #include wrapper to access the appearance data file + // this allows us to provide the file content with user-defined parameters + cParser parser( + "include " + TypeName + ".mmd" + + " " + asName // (p1) + + " " + TypeName // (p2) + + " " + ReplacableSkin // (p3) + + " end", + cParser::buffer_TEXT, + asBaseDir, true, std::vector(), true ); + std::string token; + do { + token = ""; + parser.getTokens(); parser >> token; + + if( token == "models:" ) { + loadModelsSection( parser, token, asAnimName, asFileName, ReplacableSkin ); + } // models + + else if( token == "sounds:" ) { + loadSoundsSection( parser, token ); + } // sounds: + + else if( token == "locations:" ) { + loadLocationsSection( parser, token ); + } // locations: + + else if( token == "internaldata:" ) { + loadInternalDataSection( parser, token ); + } // internaldata: + + } while( token != "" ); + + finishLoadingMMediaFile( asFileName, ReplacableSkin ); +} + +// the models: section of the .mmd file: the 3d models of the vehicle and the submodels of its animations +void TDynamicObject::loadModelsSection( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName, std::string const &ReplacableSkin ) { + // modele i podmodele + m_materialdata.multi_textures = 0; // czy jest wiele tekstur wymiennych? + parser.getTokens(); + parser >> asModel; + replace_slashes( asModel ); + if( asModel.back() == '#' ) // Ra 2015-01: nie podoba mi siê to + { // model wymaga wielu tekstur wymiennych + m_materialdata.multi_textures = 1; + asModel.erase( asModel.length() - 1 ); + } + // name can contain leading slash, erase it to avoid creation of double slashes when the name is combined with current directory + erase_leading_slashes( asModel ); + /* + // never really used, may as well get rid of it + std::size_t i = asModel.find( ',' ); + if ( i != std::string::npos ) + { // Ra 2015-01: może szukać przecinka w nazwie modelu, a po przecinku była by liczba tekstur? + if( i < asModel.length() ) { + m_materialdata.multi_textures = asModel[ i + 1 ] - '0'; + } + m_materialdata.multi_textures = std::clamp( m_materialdata.multi_textures, 0, 1 ); // na razie ustawiamy na 1 + } + */ + asModel = asBaseDir + asModel; // McZapkie 2002-07-20: dynamics maja swoje modele w dynamics/basedir + Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... + mdModel = TModelsManager::GetModel(asModel, true); + if (ReplacableSkin != "none") { + m_materialdata.assign( ReplacableSkin ); + } + Global.asCurrentTexturePath = paths::textures; // z powrotem defaultowa sciezka do tekstur + do { + token = ""; + parser.getTokens(); parser >> token; + + loadModelsKeyword( parser, token, asAnimName, asFileName ); + + } while( token != "" + && token != "endmodels" ); + + if( false == physics->LoadAttributes.empty() ) { + // Ra: tu wczytywanie modelu ładunku jest w porządku + + // bieżąca ścieżka do tekstur to dynamic/... + Global.asCurrentTexturePath = asBaseDir; + + mdLoad = LoadMMediaFile_mdload( physics->LoadType.name ); + + // z powrotem defaultowa sciezka do tekstur + Global.asCurrentTexturePath = std::string( paths::textures ); + } +} + +// a keyword of the models: section, read by the first group of keywords that knows it +void TDynamicObject::loadModelsKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( loadModelsGeneralKeyword( parser, token, asAnimName ) ) { return; } + if( loadModelsWheelKeyword( parser, token, asAnimName ) ) { return; } + if( loadModelsPantographLowerKeyword( parser, token, asAnimName, asFileName ) ) { return; } + if( loadModelsPantographUpperKeyword( parser, token, asAnimName, asFileName ) ) { return; } + if( loadModelsLinkageKeyword( parser, token, asAnimName, asFileName ) ) { return; } + if( loadModelsDoorKeyword( parser, token, asAnimName, asFileName ) ) { return; } + loadModelsMirrorWiperKeyword( parser, token, asAnimName ); +} + +// the animation counts, the other models, the loads and the knobs in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsGeneralKeyword( cParser &parser, std::string &token, std::string &asAnimName ) { + if( token == "animations:" ) { + // Ra: ustawienie ilości poszczególnych animacji - musi być jako pierwsze, inaczej ilości będą domyślne +/* + if( nullptr == pAnimations ) +*/ + if( true == pAnimations.empty() ) + { // jeśli nie ma jeszcze tabeli animacji, można odczytać nowe ilości + int co = 0; + iAnimations = 0; + int ile; + do + { // kolejne liczby to ilość animacj, -1 to znacznik końca + ile = -1; + parser.getTokens( 1, false ); + parser >> ile; // ilość danego typu animacji + if (ile >= 0) + { + iAnimType[co] = ile; // zapamiętanie + iAnimations += ile; // ogólna ilość animacji + } + else { + iAnimType[co] = 0; + } + ++co; + } while ( ile >= 0 && co < ANIM_TYPES ); //-1 to znacznik końca + + pAnimations.resize( iAnimations ); + int i, j, k = 0, sm = 0; + for (j = 0; j < ANIM_TYPES; ++j) // petla po wszystkich wpisach w animations + for (i = 0; i < iAnimType[j]; ++i) // petla iteruje sie tyle razy ile mamy wpisane w animations + { + if (j == ANIM_PANTS) // zliczamy poprzednie animacje + if (!pants) + if (iAnimType[ANIM_PANTS]) // o ile jakieś pantografy są (a domyślnie są) + pants = &pAnimations[k]; // zapamiętanie na potrzeby wyszukania submodeli + if (j == ANIM_WIPERS) + if (!wipers) + if (iAnimType[ANIM_WIPERS]) + wipers = &pAnimations[k]; + pAnimations[k].iShift = sm; // przesunięcie do przydzielenia wskaźnika + sm += pAnimations[k++].TypeSet(j, *physics); // ustawienie typu animacji i zliczanie tablicowanych submodeli + } + if (sm) // o ile są bardziej złożone animacje + { + pAnimated = new TSubModel *[sm]; // tabela na animowane submodele + for (k = 0; k < iAnimations; ++k) + pAnimations[k].smElement = pAnimated + pAnimations[k].iShift; // przydzielenie wskaźnika do tabelki + } + } + } + + else if(token == "lowpolyinterior:") { + // ABu: wnetrze lowpoly + parser.getTokens(); + parser >> asModel; + + replace_slashes( asModel ); + erase_leading_slashes( asModel ); + asModel = asBaseDir + asModel; // McZapkie-200702 - dynamics maja swoje modele w dynamic/basedir + Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... + mdLowPolyInt = TModelsManager::GetModel(asModel, true); + } + + else if(token == "coupleradapter:") { + // coupling adapter data + parser.getTokens( 3 ); + parser + >> m_coupleradapter.model + >> m_coupleradapter.position.x + >> m_coupleradapter.position.y; + replace_slashes( m_coupleradapter.model ); + erase_leading_slashes( m_coupleradapter.model ); + } + + else if(token == "attachments:") { + // additional 3d models attached to main body + // content provided as a series of values together enclosed in "{}" + // each value is a name of additional 3d model + // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly + // TBD: reconsider something more yaml-compliant and/or ability to define offset and rotation + while( (token = deserialize_random_set(parser)) != "" + && token != "}" ) { + if( token == "{" ) { continue; } + replace_slashes( token ); + Global.asCurrentTexturePath = asBaseDir; // biezaca sciezka do tekstur to dynamic/... + auto *attachmentmodel { TModelsManager::GetModel( asBaseDir + token, true ) }; + if( attachmentmodel != nullptr ) { + mdAttachments.emplace_back( attachmentmodel ); + } + } + } + + else if(token == "loads:") { + // default load visualization models overrides + // content provided as "key: value" pairs together enclosed in "{}" + // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly + while( (token = parser.getToken()) != "" + && token != "}" ) { + if( token.back() == ':' ) { + auto loadmodel { deserialize_random_set( parser ) }; + replace_slashes( loadmodel ); + LoadModelOverrides.emplace( token.erase( token.size() - 1 ), loadmodel ); + } + } + } + + else if( token == "brakemode:" ) { + // Ra 15-01: gałka nastawy hamulca + parser.getTokens(); + parser >> asAnimName; + smBrakeMode = GetSubmodelFromName( mdModel, asAnimName ); + // jeszcze wczytać kąty obrotu dla poszczególnych ustawień + } + + else if( token == "loadmode:" ) { + // Ra 15-01: gałka nastawy hamulca + parser.getTokens(); + parser >> asAnimName; + smLoadMode = GetSubmodelFromName( mdModel, asAnimName ); + // jeszcze wczytać kąty obrotu dla poszczególnych ustawień + } + else { + return false; + } + return true; +} + +// the wheels in the models: section; false when the token is another one +bool TDynamicObject::loadModelsWheelKeyword( cParser &parser, std::string &token, std::string &asAnimName ) { + if (token == "animwheelprefix:") { + // prefiks kręcących się kół + int i, k, m; + unsigned int j; + parser.getTokens( 1, false ); parser >> token; + for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // liczba osi + { // McZapkie-050402: wyszukiwanie kol o nazwie str* + asAnimName = token + std::to_string(i + 1); + pAnimations[i].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if (pAnimations[i].smAnimated) + { //++iAnimatedAxles; + pAnimations[i].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + pAnimations[i].yUpdate = std::bind( &TDynamicObject::UpdateAxle, this, std::placeholders::_1 ); + pAnimations[i].fMaxDist = Global.fDistanceFactor * physics->WheelDiameter() * 200; + pAnimations[i].fMaxDist *= pAnimations[i].fMaxDist; + } + } + // Ra: ustawianie indeksów osi + for (i = 0; i < iAnimType[ANIM_WHEELS]; ++i) // ilość osi (zabezpieczenie przed błędami w CHK) + pAnimations[i].dWheelAngle = 1; // domyślnie wskaźnik na napędzające + i = 0; + j = 1; + k = 0; + m = 0; // numer osi; kolejny znak; ile osi danego typu; która średnica + if (physics->WheelDiameterL != physics->WheelDiameter() || + physics->WheelDiameterT != physics->WheelDiameter()) + { // obsługa różnych średnic, o ile występują + while (i < iAnimType[ANIM_WHEELS] && + j <= physics->AxleArangement.length()) + { // wersja ze wskaźnikami jest bardziej elastyczna na nietypowe układy + if (k >= 'A' && k <= 'J') // 10 chyba maksimum? + { + pAnimations[i++].dWheelAngle = 1; // obrót osi napędzających + --k; // następna będzie albo taka sama, albo bierzemy kolejny znak + m = 2; // następujące toczne będą miały inną średnicę + } + else if (k >= '1' && k <= '9') + { + pAnimations[i++].dWheelAngle = m; // obrót osi tocznych + --k; // następna będzie albo taka sama, albo bierzemy kolejny znak + } + else + k = physics->AxleArangement[j++]; // pobranie kolejnego znaku + } + } + } + // else if (str==AnsiString("animrodprefix:")) //prefiks wiazarow dwoch + // { + // str= Parser->GetNextSymbol(); + // for (int i=1; i<=2; i++) + // {//McZapkie-050402: wyszukiwanie max 2 wiazarow o nazwie str* + // asAnimName=str+i; + // smWiazary[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smWiazary[i-1]->WillBeAnimated(); + // } + // } + + else { + return false; + } + return true; +} + +// the lower arms of the pantographs in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsPantographLowerKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( token == "animpantprefix:" ) { + // Ra: pantografy po nowemu mają literki i numerki + } + // Pantografy - Winger 160204 + else if( token == "animpantrd1prefix:" ) { + // prefiks ramion dolnych 1 + parser.getTokens(); parser >> token; + float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu + TSubModel *sm; + if (pants) + for (int i = 0; i < iAnimType[ANIM_PANTS]; i++) + { // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string(i + 1); + sm = GetSubmodelFromName( mdModel, asAnimName ); + pants[i].smElement[0] = sm; // jak NULL, to nie będzie animowany + if (sm) + { // w EP09 wywalało się tu z powodu NULL + sm->WillBeAnimated(); + sm->ParentMatrix(&m); // pobranie macierzy transformacji + // m(3)[1]=m[3][1]+0.054; //w górę o wysokość ślizgu (na razie tak) + pants[i].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) + pants[i].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu + if ((sm = pants[i].smElement[0]->ChildGet()) != nullptr) + { // jeśli ma potomny, można policzyć długość (odległość potomnego od osi obrotu) + m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, nie trzeba kopiować + // może trzeba: pobrać macierz dolnego ramienia, wyzerować przesunięcie, przemnożyć przez macierz górnego + pants[i].fParamPants->fHoriz = -fabs(m[3][1]); + pants[i].fParamPants->fLenL1 = hypot(m[3][1], m[3][2]); // po osi OX nie potrzeba + pants[i].fParamPants->fAngleL0 = atan2(fabs(m[3][2]), fabs(m[3][1])); + // if (pants[i].fParamPants->fAngleL0fAngleL0+=M_PI; //gdyby w odwrotną stronę wyszło + // if + // ((pants[i].fParamPants->fAngleL0<0.03)||(pants[i].fParamPants->fAngleL0>0.09)) + // //normalnie ok. 0.05 + // pants[i].fParamPants->fAngleL0=pants[i].fParamPants->fAngleL; + pants[i].fParamPants->fAngleL = pants[i].fParamPants->fAngleL0; // początkowy kąt dolnego ramienia + if ((sm = sm->ChildGet()) != nullptr) + { // jeśli dalej jest ślizg, można policzyć długość górnego ramienia + m = float4x4(*sm->GetMatrix()); // wystarczyłby wskaźnik, + // nie trzeba kopiować trzeba by uwzględnić macierz dolnego ramienia, żeby uzyskać kąt do poziomu... + pants[i].fParamPants->fHoriz += fabs(m(3)[1]); // różnica długości rzutów ramion na + // płaszczyznę podstawy (jedna dodatnia, druga ujemna) + pants[i].fParamPants->fLenU1 = hypot( m[3][1], m[3][2] ); // po osi OX nie potrzeba + // pants[i].fParamPants->pantu=acos((1.22*cos(pants[i].fParamPants->fAngleL)+0.535)/1.755); //górne ramię + // pants[i].fParamPants->fAngleU0=acos((1.176289*cos(pants[i].fParamPants->fAngleL)+0.54555075)/1.724482197); //górne ramię + pants[i].fParamPants->fAngleU0 = atan2( fabs(m[3][2]), fabs(m[3][1]) ); // początkowy kąt górnego ramienia, odczytany z modelu + // if (pants[i].fParamPants->fAngleU0fAngleU0+=M_PI; //gdyby w odwrotną stronę wyszło + // if (pants[i].fParamPants->fAngleU0<0) + // pants[i].fParamPants->fAngleU0=-pants[i].fParamPants->fAngleU0; + // if + // ((pants[i].fParamPants->fAngleU0<0.00)||(pants[i].fParamPants->fAngleU0>0.09)) //normalnie ok. 0.07 + // pants[i].fParamPants->fAngleU0=acos((pants[i].fParamPants->fLenL1*cos(pants[i].fParamPants->fAngleL)+pants[i].fParamPants->fHoriz)/pants[i].fParamPants->fLenU1); + pants[i].fParamPants->fAngleU = pants[i].fParamPants->fAngleU0; // początkowy kąt + // Ra: ze względu na to, że niektóre modele pantografów są zrąbane, ich mierzenie ma obecnie ograniczony sens + sm->ParentMatrix(&m); // pobranie macierzy transformacji pivota ślizgu względem wstawienia pojazdu + float det = Det(m); + if (std::fabs(det - 1.0) < 0.001) // dopuszczamy 1 promil błędu na skalowaniu ślizgu + { // skalowanie jest w normie, można pobrać wymiary z modelu + pants[i].fParamPants->fHeight = sm->MaxY(m); // przeliczenie maksimum wysokości wierzchołków względem macierzy + pants[i].fParamPants->fHeight -= m[3][1]; // odjęcie wysokości pivota ślizgu + pants[i].fParamPants->vPos.x = m[3][2]; // przy okazji odczytać z modelu pozycję w długości + // ErrorLog("Model OK: "+asModel+", + // height="+pants[i].fParamPants->fHeight); + // ErrorLog("Model OK: "+asModel+", + // pos.x="+pants[i].fParamPants->vPos.x); + } + else + { // gdy ktoś przesadził ze skalowaniem + pants[i].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: + ErrorLog( + "Bad model: " + asModel + ", scale of " + sm->pName + " is " + std::to_string(100.0 * det) + "%", + logtype::model ); + } + } + } + } + else { + // brak ramienia + pants[ i ].fParamPants->fHeight = 0.0; // niech będzie odczyt z pantfactors: + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); + } + } + } + + else if( token == "animpantrd2prefix:" ) { + // prefiks ramion dolnych 2 + parser.getTokens(); parser >> token; + float4x4 m; // macierz do wyliczenia pozycji i wektora ruchu pantografu + TSubModel *sm; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + sm = GetSubmodelFromName( mdModel, asAnimName ); + pants[ i ].smElement[ 1 ] = sm; // jak NULL, to nie będzie animowany + if( sm ) { // w EP09 wywalało się tu z powodu NULL + sm->WillBeAnimated(); + if( pants[ i ].fParamPants->vPos.y == 0.0 ) { + // jeśli pierwsze ramię nie ustawiło tej wartości, próbować drugim + //!!!! docelowo zrobić niezależną animację ramion z każdej strony + m = float4x4( + *sm->GetMatrix()); // skopiowanie, bo będziemy mnożyć + m( 3 )[ 1 ] = + m[ 3 ][ 1 ] + 0.054; // w górę o wysokość ślizgu (na razie tak) + while( sm->Parent ) { + if( sm->Parent->GetMatrix() ) + m = *sm->Parent->GetMatrix() * m; + sm = sm->Parent; + } + pants[ i ].fParamPants->vPos.z = m[3][0]; // przesunięcie w bok (asymetria) + pants[ i ].fParamPants->vPos.y = m[3][1]; // przesunięcie w górę odczytane z modelu + } + } + else + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + + else { + return false; + } + return true; +} + +// the upper arms and the shoes of the pantographs and their factors in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsPantographUpperKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( token == "animpantrg1prefix:" ) { + // prefiks ramion górnych 1 + parser.getTokens(); parser >> token; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + pants[ i ].smElement[ 2 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( pants[ i ].smElement[ 2 ] ) { + pants[ i ].smElement[ 2 ]->WillBeAnimated(); + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + } + + else if( token == "animpantrg2prefix:" ) { + // prefiks ramion górnych 2 + parser.getTokens(); parser >> token; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + pants[ i ].smElement[ 3 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( pants[ i ].smElement[ 3 ] ) { + pants[ i ].smElement[ 3 ]->WillBeAnimated(); + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + } + + else if( token == "animpantslprefix:" ) { + // prefiks ślizgaczy + parser.getTokens(); parser >> token; + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; i++ ) { + // Winger 160204: wyszukiwanie max 2 patykow o nazwie str* + asAnimName = token + std::to_string( i + 1 ); + pants[ i ].smElement[ 4 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( pants[ i ].smElement[ 4 ] ) { + pants[ i ].smElement[ 4 ]->WillBeAnimated(); + pants[ i ].yUpdate = std::bind( &TDynamicObject::UpdatePant, this, std::placeholders::_1 ); + pants[ i ].fMaxDist = 300 * 300; // nie podnosić w większej odległości + pants[ i ].iNumber = i; + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); // brak ramienia + } + } + } + } + + else if( token == "pantfactors:" ) { + // Winger 010304: + // parametry pantografow + double pant1x, pant2x, pant1h, pant2h; + parser.getTokens( 4, false ); + parser + >> pant1x + >> pant2x + >> pant1h // wysokość pierwszego ślizgu + >> pant2h;// wysokość drugiego ślizgu + if( pant1h > 0.5 ) { + pant1h = pant2h; // tu może być zbyt duża wartość + } + if (pant1x < 0 && + pant2x > 0) // pierwsza powinna być dodatnia, a druga ujemna + { + pant1x = -pant1x; + pant2x = -pant2x; + } + if( pants ) { + for( int i = 0; i < iAnimType[ ANIM_PANTS ]; ++i ) { + // przepisanie współczynników do pantografów (na razie nie będzie lepiej) + auto &pantograph { *pants[i].fParamPants }; + + pantograph.fAngleL = pantograph.fAngleL0; // początkowy kąt dolnego ramienia + pantograph.fAngleU = pantograph.fAngleU0; // początkowy kąt + // pants[i].fParamPants->PantWys=1.22*sin(pants[i].fParamPants->fAngleL)+1.755*sin(pants[i].fParamPants->fAngleU); + // //wysokość początkowa + // pants[i].fParamPants->PantWys=1.176289*sin(pants[i].fParamPants->fAngleL)+1.724482197*sin(pants[i].fParamPants->fAngleU); + // //wysokość początkowa + if( pantograph.fHeight == 0.0 ) // gdy jest nieprawdopodobna wartość (np. nie znaleziony ślizg) + { // gdy pomiary modelu nie udały się, odczyt podanych parametrów z MMD + pantograph.vPos.x = + i & 1 ? + pant2x : + pant1x; + pantograph.fHeight = + i & 1 ? + pant2h : + pant1h; // wysokość ślizgu jest zapisana w MMD + } + pantograph.PantWys = + pantograph.fLenL1 * sin( pantograph.fAngleL ) + + pantograph.fLenU1 * sin( pantograph.fAngleU ) + + pantograph.fHeight; // wysokość początkowa + // pants[i].fParamPants->vPos.y=panty-panth-pants[i].fParamPants->PantWys; //np. 4.429-0.097=4.332=~4.335 + if( pantograph.vPos.y == 0.0 ) { + // crude fallback, place the pantograph(s) atop of the vehicle-sized box + pantograph.vPos.y = physics->Dim.H - pantograph.fHeight - pantograph.PantWys; + } + // pants[i].fParamPants->vPos.z=0; //niezerowe dla pantografów asymetrycznych + pantograph.PantTraction = pantograph.PantWys; + // połowa szerokości ślizgu; jest w "Power: CSW=" + pantograph.fWidth = 0.5 * physics->EnginePowerSource.CollectorParameters.CSW; + + // create sound emitters for the pantograph + m_pantographsounds.emplace_back(); + } + } + } + + else { + return false; + } + return true; +} + +// the pistons, the rods, the pendulums and the slotted levers in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsLinkageKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if (token == "animpistonprefix:") { + // prefiks tłoczysk - na razie uzywamy modeli pantografów + parser.getTokens(1, false); parser >> token; + for( int i = 1; i <= 2; ++i ) + { + // asAnimName=str+i; + // smPatykird1[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykird1[i-1]->WillBeAnimated(); + } + } + + else if( token == "animconrodprefix:" ) { + // prefiks korbowodów - na razie używamy modeli pantografów + parser.getTokens(); parser >> token; + for( int i = 1; i <= 2; i++ ) + { + // asAnimName=str+i; + // smPatykirg1[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykirg1[i-1]->WillBeAnimated(); + } + } + + else if( token == "pistonfactors:" ) { + // Ra: parametry + // silnika parowego + // (tłoka) + /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji + pantografów + pant1x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia + dla + pierwszego tłoka + pant2x=Parser->GetNextSymbol().ToDouble(); //kąt przesunięcia + dla + drugiego tłoka + panty=Parser->GetNextSymbol().ToDouble(); //długość korby (r) + panth=Parser->GetNextSymbol().ToDouble(); //długoś korbowodu + (k) + */ + physics->EnginePowerSource.PowerType = + TPowerType::SteamPower; // Ra: po chamsku, ale z CHK nie działa + } + + else if( token == "animreturnprefix:" ) { + // prefiks drążka mimośrodowego - na razie używamy modeli pantografów + parser.getTokens(1, false); parser >> token; + for( int i = 1; i <= 2; i++ ) + { + // asAnimName=str+i; + // smPatykird2[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykird2[i-1]->WillBeAnimated(); + } + } + + else if (token == "animexplinkprefix:"){ // animreturnprefix: + // prefiks jarzma - na razie używamy modeli pantografów + parser.getTokens(1, false); parser >> token; + for( int i = 1; i <= 2; i++ ) + { + // asAnimName=str+i; + // smPatykirg2[i-1]=mdModel->GetFromName(asAnimName.c_str()); + // smPatykirg2[i-1]->WillBeAnimated(); + } + } + + else if( token == "animpendulumprefix:" ) { + // prefiks wahaczy + parser.getTokens(); parser >> token; + asAnimName = ""; + for( int i = 1; i <= 4; ++i ) { + // McZapkie-050402: wyszukiwanie max 4 wahaczy o nazwie str* + asAnimName = token + std::to_string( i ); + smWahacze[ i - 1 ] = GetSubmodelFromName( mdModel, asAnimName ); + if( smWahacze[ i - 1 ] ) { + smWahacze[ i - 1 ]->WillBeAnimated(); + } + } + parser.getTokens(); parser >> token; + if( token == "pendulumamplitude:" ) { + parser.getTokens( 1, false ); + parser >> fWahaczeAmp; + } + } + + else if( token == "animslottedlever:" ) { + // lever with a slot, turned by a pin on the coupling rod (e.g. speedometer drive) + // parameters: submodel name, number of axle (from animwheelprefix) driving the coupling rod, crank radius [m], + // pin position relative to the lever axis [m] and crank angle [deg] for wheel angle 0, in local (Y, Z) plane of the lever + // angle is measured from Y axis towards Z axis, i.e. in the direction of rotation around X axis + slottedlever_data lever; + int axle { 1 }; + double crankradius { 0.0 }; + double crankangle { 0.0 }; + parser.getTokens( 6, false ); + parser + >> asAnimName + >> axle + >> crankradius + >> lever.pin.x + >> lever.pin.y + >> crankangle; + lever.submodel = GetSubmodelFromName( mdModel, asAnimName ); + if( lever.submodel != nullptr ) { + lever.submodel->WillBeAnimated(); + lever.axle = std::max( 0, axle - 1 ); + lever.crank = crankradius * glm::dvec2( std::cos( glm::radians( crankangle ) ), std::sin( glm::radians( crankangle ) ) ); + m_slottedlevers.emplace_back( lever ); + } + else { + ErrorLog( "Bad model: " + asFileName + " - missed submodel " + asAnimName, logtype::model ); + } + } + + else { + return false; + } + return true; +} + +// the doors and the door steps in the models: section; false when the token is none of them +bool TDynamicObject::loadModelsDoorKeyword( cParser &parser, std::string &token, std::string &asAnimName, std::string const &asFileName ) { + if( token == "animdoorprefix:" ) { + // nazwa animowanych drzwi + int i, j; + parser.getTokens(1, false); parser >> token; + for (i = 0, j = 0; i < ANIM_DOORS; ++i) + j += iAnimType[i]; // zliczanie wcześniejszych animacji + for (i = 0; i < iAnimType[ANIM_DOORS]; ++i) // liczba drzwi + { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* + // ustalenie submodelu + asAnimName = token + std::to_string(i + 1); + pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if (pAnimations[i + j].smAnimated) + { //++iAnimatedDoors; + pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste + bind_door_animation( pAnimations[ i + j ] ); // od razu zapinamy potrzebny typ animacji + pAnimations[i + j].fMaxDist = 300 * 300; // drzwi to z daleka widać +/* + // NOTE: no longer used + pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor + pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; +*/ + } + } + } + + else if( token == "animdoor:" ) { + // own kind of animation of one door wing, in place of the one of the .fiz (eu07/maszyna#70): + // animdoor: { type: range: rangeout: } + // the keys left out keep the values of the .fiz. the wing still follows the door of its side + door_wings::wing_spec spec { + 0, + physics->Doors.type, + physics->Doors.range, + physics->Doors.range_out }; + auto error { door_wings::read_spec( parser, spec ) }; + if( error.empty() + && ( spec.number < 1 || spec.number > iAnimType[ ANIM_DOORS ] ) ) { + error = "no door wing " + std::to_string( spec.number ) + " among the door animations"; + } + if( false == error.empty() ) { + ErrorLog( "Bad model: " + asFileName + " - animdoor: " + error, logtype::model ); + } + else { + door_wings::store( m_doorwings, spec ); + // a wing animdoorprefix has found already gets the new kind of animation now; the ones it + // finds later get it then + auto const index { static_cast( std::accumulate( std::begin( iAnimType ), std::begin( iAnimType ) + ANIM_DOORS, 0 ) + spec.number - 1 ) }; + if( index < pAnimations.size() && pAnimations[ index ].yUpdate ) { + bind_door_animation( pAnimations[ index ] ); + } + } + } + + else if( token == "animstepprefix:" ) { + // animated doorstep submodel name prefix + int i, j; + parser.getTokens(1, false); parser >> token; + for (i = 0, j = 0; i < ANIM_DOORSTEPS; ++i) + j += iAnimType[i]; // zliczanie wcześniejszych animacji + for (i = 0; i < iAnimType[ANIM_DOORSTEPS]; ++i) // liczba drzwi + { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* + // ustalenie submodelu + asAnimName = token + std::to_string(i + 1); + pAnimations[i + j].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if (pAnimations[i + j].smAnimated) + { //++iAnimatedDoors; + pAnimations[i + j].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + switch( physics->Doors.step_type ) + { // od razu zapinamy potrzebny typ animacji + case 1: // shift + pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformTranslate, this, std::placeholders::_1 ); + break; + case 2: // rotate + pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdatePlatformRotate, this, std::placeholders::_1 ); + break; + default: + break; + } + pAnimations[i + j].iNumber = i + 1; // parzyste działają inaczej niż nieparzyste + pAnimations[i + j].fMaxDist = 150 * 150; // drzwi to z daleka widać +/* + // NOTE: no longer used + pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor + pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; +*/ + } + } + } + + else { + return false; + } + return true; +} + +// the mirrors and the wipers in the models: section +void TDynamicObject::loadModelsMirrorWiperKeyword( cParser &parser, std::string &token, std::string &asAnimName ) { + if( token == "animmirrorprefix:" ) { + // animated mirror submodel name prefix + int i, j; + parser.getTokens( 1, false ); parser >> token; + for( i = 0, j = 0; i < ANIM_MIRRORS; ++i ) + j += iAnimType[ i ]; // zliczanie wcześniejszych animacji + for( i = 0; i < iAnimType[ ANIM_MIRRORS ]; ++i ) // liczba drzwi + { // NBMX wrzesien 2003: wyszukiwanie drzwi o nazwie str* + // ustalenie submodelu + asAnimName = token + std::to_string( i + 1 ); + pAnimations[ i + j ].smAnimated = GetSubmodelFromName( mdModel, asAnimName ); + if( pAnimations[ i + j ].smAnimated ) { + pAnimations[ i + j ].smAnimated->WillBeAnimated(); // wyłączenie optymalizacji transformu + // od razu zapinamy potrzebny typ animacji + auto const offset { pAnimations[ i + j ].smAnimated->offset() }; + pAnimations[ i + j ].yUpdate = std::bind( &TDynamicObject::UpdateMirror, this, std::placeholders::_1 ); + // we don't expect more than 2-4 mirrors, so it should be safe to store submodel location (front/rear) in the higher bits + // parzyste działają inaczej niż nieparzyste + pAnimations[ i + j ].iNumber = + ( NumberOf( pAnimations[ i + j ].smAnimated->offset().z > 0 ? + VehicleEnd::front : + VehicleEnd::rear ) << 4 ) + + i; + pAnimations[ i + j ].fMaxDist = 150 * 150; // drzwi to z daleka widać +/* + // NOTE: no longer used + pAnimations[i + j].fSpeed = Random(150); // oryginalny koncept z DoorSpeedFactor + pAnimations[i + j].fSpeed = (pAnimations[i + j].fSpeed + 100) / 100; +*/ + } + } + } + + else if (token == "animwiperprefix:") + { + parser.getTokens(1, false); + parser >> token; + TSubModel *sm; + if (wipers) + { + + for (int i = 0; i < iAnimType[ANIM_WIPERS]; i++) // zebranie wszystkich submodeli wycieraczek + { + dWiperPos.emplace_back(0.0); // dodajemy na koniec zeby sie miejsce tam zrobilo i nie bylo invalid addressow potem + if (wiperOutTimer.size() < dWiperPos.size()) + { + // more wipers than the state of the wipers has room for at the start + wiperOutTimer.resize(dWiperPos.size(), 0.0); + wiperParkTimer.resize(dWiperPos.size(), 0.0); + workingSwitchPos.resize(dWiperPos.size(), 0); + wiperDirection.resize(dWiperPos.size(), false); + } + + asAnimName = token + std::to_string(i + 1); + // element wycieraczki nr 1 + sm = GetSubmodelFromName(mdModel, asAnimName + "_p1"); + wipers[i].smElement[0] = sm; + if (sm) + { + wipers[i].smElement[0]->WillBeAnimated(); + // auto const offset{wipers[i].smElement[0]->offset()}; + } + + // element wycieraczki nr 2 + sm = GetSubmodelFromName(mdModel, asAnimName + "_p2"); + wipers[i].smElement[1] = sm; + if (sm) + { + wipers[i].smElement[1]->WillBeAnimated(); + // auto const offset{wipers[i].smElement[0]->offset()}; + } + + // element wycieraczki nr 3 + sm = GetSubmodelFromName(mdModel, asAnimName + "_p3"); + wipers[i].smElement[2] = sm; + if (sm) + { + wipers[i].smElement[2]->WillBeAnimated(); + // auto const offset{wipers[i].smElement[0]->offset()}; + } + wipers[i].yUpdate = std::bind(&TDynamicObject::UpdateWiper, this, std::placeholders::_1); + wipers[i].fMaxDist = 150 * 150; + wipers[i].iNumber = i; + } + } + } +} + +// the sounds: section of the .mmd file: the sounds of the vehicle +void TDynamicObject::loadSoundsSection( cParser &parser, std::string &token ) { + // dzwieki + do { + token = ""; + parser.getTokens(); parser >> token; + loadSoundsKeyword( parser, token ); + } while( token != "" + && token != "endsounds" ); +} + +// a keyword of the sounds: section, read by the first group of keywords that knows it +void TDynamicObject::loadSoundsKeyword( cParser &parser, std::string &token ) { + if( loadSoundsEngineKeyword( parser, token ) ) { return; } + if( loadSoundsMotorKeyword( parser, token ) ) { return; } + if( loadSoundsBrakeKeyword( parser, token ) ) { return; } + if( loadSoundsDeviceKeyword( parser, token ) ) { return; } + if( loadSoundsDoorKeyword( parser, token ) ) { return; } + if( loadSoundsOtherKeyword( parser, token ) ) { return; } + loadSoundsAnnouncementKeyword( parser, token ); +} + +// the clatter of the wheels and the sounds of the engine and its pumps in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsEngineKeyword( cParser &parser, std::string &token ) { + if( token == "wheel_clatter:" ){ + // polozenia osi w/m srodka pojazdu + double dSDist; + parser.getTokens( 1, false ); + parser >> dSDist; + while( (token = parser.getToken()) != "" + && token != "end" ) { + // add another axle entry to the list + axle_sounds axle { + 0, + std::atof( token.c_str() ) * -1.0, // for axle locations negative value means ahead of centre but vehicle faces +Z in 'its' space + { sound_placement::external, static_cast( dSDist ) } }; + axle.clatter.deserialize( parser, sound_type::single ); + axle.clatter.owner( this ); + axle.clatter.offset( { 0, 0, axle.offset } ); + m_axlesounds.emplace_back( axle ); + } + // arrange the axles in case they're listed out of order + std::sort( + std::begin( m_axlesounds ), std::end( m_axlesounds ), + []( axle_sounds const &Left, axle_sounds const &Right ) { + return Left.offset > Right.offset; } ); + } + + else if( token == "engine:" + && physics->Power > 0 ) { + // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. + m_powertrainsounds.engine.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.engine.owner( this ); + + auto const amplitudedivisor = static_cast( physics->EngineType == TEngineType::DieselEngine ? 1 : + physics->EngineType == TEngineType::DieselElectric ? 1 : + physics->nmax * 60 + physics->Power * 3 ); + m_powertrainsounds.engine.m_amplitudefactor /= amplitudedivisor; + + } else if (token == "fakeengine:") { + m_powertrainsounds.fake_engine.deserialize(parser, sound_type::single); + m_powertrainsounds.fake_engine.owner(this); + } + + else if( token == "dieselinc:" ) { + // dzwiek przy wlazeniu na obroty woodwarda + m_powertrainsounds.engine_revving.deserialize( parser, sound_type::single, sound_parameters::range ); + m_powertrainsounds.engine_revving.owner( this ); + } + + else if( token == "oilpump:" ) { + m_powertrainsounds.oil_pump.deserialize( parser, sound_type::single ); + m_powertrainsounds.oil_pump.owner( this ); + } + + else if( token == "fuelpump:" ) { + m_powertrainsounds.fuel_pump.deserialize( parser, sound_type::single ); + m_powertrainsounds.fuel_pump.owner( this ); + } + + else if( token == "waterpump:" ) { + m_powertrainsounds.water_pump.deserialize( parser, sound_type::single ); + m_powertrainsounds.water_pump.owner( this ); + } + + else if( token == "waterheater:" ) { + m_powertrainsounds.water_heater.deserialize( parser, sound_type::single ); + m_powertrainsounds.water_heater.owner( this ); + } + + else { + return false; + } + return true; +} + +// the sounds of the traction motors, their blowers, the inverter, the fans and the transmission in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsMotorKeyword( cParser &parser, std::string_view token ) { + if( token == "tractionmotor:" && physics->Power > 0 ) { + // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. + sound_source motortemplate { sound_placement::external }; + motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + auto const amplitudedivisor { static_cast( physics->nmax * 60 + physics->Power * 3 ) }; + motortemplate.m_amplitudefactor /= amplitudedivisor; + motortemplate.owner( this ); + + auto &motors { m_powertrainsounds.motors }; + + if( true == motors.empty() ) { + // fallback for cases without specified motor locations, convert sound template to a single sound source + motors.emplace_back( motortemplate ); + } + else { + // apply configuration to all defined motors + for( auto &motor : motors ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors + auto motoroffset { motortemplate.offset() }; + motoroffset.z = motor.offset().z; + motor = motortemplate; + motor.offset( motoroffset ); + // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources + motor.start( LocalRandom( 0.0, 1.0 ) ); + } + } + } + + else if( token == "tractionacmotor:" && physics->Power > 0 ) { + // plik z dzwiekiem silnika, mnozniki i ofsety amp. i czest. + sound_source motortemplate { sound_placement::external }; + motortemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + motortemplate.owner( this ); + + auto &motors { m_powertrainsounds.acmotors }; + + if( true == motors.empty() ) { + // fallback for cases without specified motor locations, convert sound template to a single sound source + motors.emplace_back( motortemplate ); + } + else { + // apply configuration to all defined motors + for( auto &motor : motors ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors + auto motoroffset { motortemplate.offset() }; + motoroffset.z = motor.offset().z; + motor = motortemplate; + motor.offset( motoroffset ); + // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources + motor.start( LocalRandom( 0.0, 1.0 ) ); + } + } + } + + else if( token == "motorblower:" ) { + + sound_source blowertemplate { sound_placement::engine }; + blowertemplate.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + blowertemplate.owner( this ); + + auto const amplitudedivisor { static_cast( + physics->MotorBlowers[ VehicleEnd::front ].speed > 0 ? physics->MotorBlowers[ VehicleEnd::front ].speed * physics->nmax * 60 + physics->Power * 3 : + blowertemplate.has_bookends() ? 1 : // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments + physics->MotorBlowers[ VehicleEnd::front ].speed * -1 ) }; + blowertemplate.m_amplitudefactor /= amplitudedivisor; + blowertemplate.m_frequencyfactor /= amplitudedivisor; + + if( true == m_powertrainsounds.motors.empty() ) { + // fallback for cases without specified motor locations, convert sound template to a single sound source + m_powertrainsounds.motorblowers.emplace_back( blowertemplate ); + } + else { + // apply configuration to all defined motor blowers + for( auto &blower : m_powertrainsounds.motorblowers ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual blowers + auto bloweroffset { blowertemplate.offset() }; + bloweroffset.z = blower.offset().z; + blower = blowertemplate; + blower.offset( bloweroffset ); + // apply randomized playback start offset for each instance, to reduce potential reverb with identical nearby sources + blower.start( LocalRandom( 0.0, 1.0 ) ); + } + } + } + + else if( token == "inverter:" ) { + // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. + m_powertrainsounds.inverter.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.inverter.owner( this ); + } + + else if( token == "ventilator:" ) { + // plik z dzwiekiem wentylatora, mnozniki i ofsety amp. i czest. + m_powertrainsounds.rsWentylator.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.rsWentylator.owner( this ); + + m_powertrainsounds.rsWentylator.m_amplitudefactor /= physics->RVentnmax; + m_powertrainsounds.rsWentylator.m_frequencyfactor /= physics->RVentnmax; + } + + else if( token == "radiatorfan1:" ) { + // primary circuit radiator fan + m_powertrainsounds.radiator_fan.deserialize( parser, sound_type::single ); + m_powertrainsounds.radiator_fan.owner( this ); + } + + else if( token == "radiatorfan2:" || token == "radiatorfan2" ) { + // auxiliary circuit radiator fan + m_powertrainsounds.radiator_fan_aux.deserialize( parser, sound_type::single ); + m_powertrainsounds.radiator_fan_aux.owner( this ); + } + + else if( token == "transmission:" ) { + // plik z dzwiekiem, mnozniki i ofsety amp. i czest. + // NOTE, fixed default parameters, legacy system leftover + auto &sound { m_powertrainsounds.transmission }; + sound.m_amplitudefactor = 0.029; + sound.m_amplitudeoffset = 0.1; + sound.m_frequencyfactor = 0.005; + sound.m_frequencyoffset = 1.0; + + sound.deserialize( parser, sound_type::single, sound_parameters::range ); + sound.owner( this ); + } + + else { + return false; + } + return true; +} + +// the sounds of the brakes in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsBrakeKeyword( cParser &parser, std::string_view token ) { + if( token == "brakesound:" ) { + // hamowanie zwykle: + rsBrake.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); + rsBrake.owner( this ); + // NOTE: can't pre-calculate amplitude normalization based on max brake force, as this varies depending on vehicle speed + rsBrake.m_frequencyfactor /= 1 + physics->Vmax(); + } + + else if( token == "brake:" ) { + // plik z piskiem hamulca, mnozniki i ofsety amplitudy. + rsPisk.deserialize( parser, sound_type::single, sound_parameters::range | sound_parameters::amplitude ); + rsPisk.owner( this ); + + if( rsPisk.m_amplitudefactor > 10.f ) { + // HACK: convert old style activation point threshold to the new, regular amplitude adjustment system + rsPisk.m_amplitudefactor = 1.f; + rsPisk.m_amplitudeoffset = 0.f; + } + rsPisk.m_amplitudeoffset *= ( 105.f - Random( 10.f ) ) / 100.f; + } + + else if( token == "brakecylinderinc:" ) { + // brake cylinder pressure increase sounds + m_brakecylinderpistonadvance.deserialize( parser, sound_type::single ); + m_brakecylinderpistonadvance.owner( this ); + } + + else if( token == "brakecylinderdec:" ) { + // brake cylinder pressure decrease sounds + m_brakecylinderpistonrecede.deserialize( parser, sound_type::single ); + m_brakecylinderpistonrecede.owner( this ); + } + + else if (token == "epbrakeinc:") { + // brake cylinder pressure increase sounds + m_epbrakepressureincrease.deserialize(parser, sound_type::single); + m_epbrakepressureincrease.owner(this); + } + + else if (token == "epbrakedec:") { + // brake cylinder pressure decrease sounds + m_epbrakepressuredecrease.deserialize(parser, sound_type::single); + m_epbrakepressuredecrease.owner(this); + } + + else if( token == "emergencybrake:" ) { + // emergency brake sound + m_emergencybrake.deserialize( parser, sound_type::single ); + m_emergencybrake.owner( this ); + } + + else if( token == "brakeacc:" ) { + // plik z przyspieszaczem (upust po zlapaniu hamowania) + sBrakeAcc.deserialize( parser, sound_type::single ); + sBrakeAcc.owner( this ); + + bBrakeAcc = true; + } + + else if( token == "unbrake:" ) { + // plik z piskiem hamulca, mnozniki i ofsety amplitudy. + rsUnbrake.m_amplitudefactor = 20.0f; + rsUnbrake.deserialize( parser, sound_type::single, sound_parameters::range ); + rsUnbrake.owner( this ); + } + // spring brake sounds + else if( token == "springbrake:" ) { + m_springbrakesounds.activate.deserialize( parser, sound_type::single ); + m_springbrakesounds.activate.owner( this ); + } + else if( token == "springbrakeoff:" ) { + m_springbrakesounds.release.deserialize( parser, sound_type::single ); + m_springbrakesounds.release.owner( this ); + } + + else { + return false; + } + return true; +} + +// the sounds of the derailment, the curves, the horns, the pantographs, the compressors and other devices in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsDeviceKeyword( cParser &parser, std::string_view token ) { + if( token == "derail:" ) { + // dzwiek przy wykolejeniu + rsDerailment.deserialize( parser, sound_type::single, sound_parameters::range ); + rsDerailment.owner( this ); + } + + else if( token == "curve:" ) { + rscurve.deserialize( parser, sound_type::single, sound_parameters::range ); + rscurve.owner( this ); + } + + else if( token == "horn1:" ) { + // pliki z trabieniem + sHorn1.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sHorn1.owner( this ); + } + + else if( token == "horn2:" ) { + // pliki z trabieniem wysokoton. + sHorn2.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sHorn2.owner( this ); + // TBD, TODO: move horn selection to ai config file + if( iHornWarning ) { + iHornWarning = 2; // numer syreny do użycia po otrzymaniu sygnału do jazdy + } + } + + else if( token == "horn3:" ) { + sHorn3.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sHorn3.owner( this ); + } + + else if( token == "pantographup:" ) { + // pliki dzwiekow pantografow + sound_source pantographup { sound_placement::external }; + pantographup.deserialize( parser, sound_type::single ); + pantographup.owner( this ); + for( auto &pantograph : m_pantographsounds ) { + pantograph.sPantUp = pantographup; + } + } + + else if( token == "pantographdown:" ) { + // pliki dzwiekow pantografow + sound_source pantographdown { sound_placement::external }; + pantographdown.deserialize( parser, sound_type::single ); + pantographdown.owner( this ); + for( auto &pantograph : m_pantographsounds ) { + pantograph.sPantDown = pantographdown; + } + } + + else if( token == "compressor:" ) { + // pliki ze sprezarka + sCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sCompressor.owner( this ); + } + + else if( token == "compressoridle:" ) { + // pliki ze sprezarka + sCompressorIdle.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sCompressorIdle.owner( this ); + } + + else if( token == "converter:" ) { + // pliki z przetwornica + sConverter.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sConverter.owner( this ); + } + + // Dzwiek wentylatora rezystora hamowania + else if (token == "brakingresistorventilator:") + { + sBRVent.deserialize(parser, sound_type::multipart, sound_parameters::range); + sBRVent.owner(this); + } + + else if( token == "heater:" ) { + // train heating device + sHeater.deserialize( parser, sound_type::single ); + sHeater.owner( this ); + } + + else if( token == "battery:" ) { + // train heating device + m_batterysound.deserialize( parser, sound_type::single ); + m_batterysound.owner( this ); + } + + else if( token == "turbo:" ) { + // pliki z turbogeneratorem + m_powertrainsounds.engine_turbo.deserialize( parser, sound_type::multipart, sound_parameters::range ); + m_powertrainsounds.engine_turbo.owner( this ); + m_powertrainsounds.engine_turbo.gain( 0 ); + } + + else if( token == "small-compressor:" ) { + // pliki z przetwornica + sSmallCompressor.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sSmallCompressor.owner( this ); + } + + else { + return false; + } + return true; +} + +// the sounds of the doors, the door steps and the mirrors in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsDoorKeyword( cParser &parser, std::string_view token ) { + if( token == "departuresignal:" ) { + // pliki z sygnalem odjazdu + sound_source soundtemplate { sound_placement::general, 25.f }; + soundtemplate.deserialize( parser, sound_type::multipart, sound_parameters::range ); + soundtemplate.owner( this ); + for( auto &speaker : m_doorspeakers ) { + speaker.departure_signal = soundtemplate; + speaker.departure_signal.offset( speaker.offset ); + } + } + + else if( token == "dooropen:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.rsDoorOpen.offset() }; + door.rsDoorOpen = soundtemplate; + door.rsDoorOpen.offset( dooroffset ); + } + } + + else if( token == "doorclose:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.rsDoorClose.offset() }; + door.rsDoorClose = soundtemplate; + door.rsDoorClose.offset( dooroffset ); + } + } + + else if( token == "doorlock:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.lock.offset() }; + door.lock = soundtemplate; + door.lock.offset( dooroffset ); + } + } + + else if( token == "doorunlock:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.unlock.offset() }; + door.unlock = soundtemplate; + door.unlock.offset( dooroffset ); + } + } + + else if( token == "doorstepopen:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.step_open.offset() }; + door.step_open = soundtemplate; + door.step_open.offset( dooroffset ); + } + } + + else if( token == "mirroropen:" || token == "mirrorclose:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &mirror : m_mirrorsounds ) { + // apply configuration to all defined mirrors, but preserve their individual offsets + auto &sound { token == "mirroropen:" ? mirror.unfold : mirror.fold }; + auto const mirroroffset { sound.offset() }; + sound = soundtemplate; + sound.offset( mirroroffset ); + } + } + + else if( token == "doorstepclose:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.step_close.offset() }; + door.step_close = soundtemplate; + door.step_close.offset( dooroffset ); + } + } + + else if( token == "doorpermit:" ) { + sound_source soundtemplate { sound_placement::general }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &door : m_doorsounds ) { + // apply configuration to all defined doors, but preserve their individual offsets + auto const dooroffset { door.permit_granted.offset() }; + door.permit_granted = soundtemplate; + door.permit_granted.offset( dooroffset ); + } + } + + else { + return false; + } + return true; +} + +// the sounds of the load exchange, the sanders, the releaser and the running noise in the sounds: section; false when the token is none of them +bool TDynamicObject::loadSoundsOtherKeyword( cParser &parser, std::string_view token ) { + if( token == "unloading:" ) { + m_exchangesounds.unloading.range( physics->Dim.L * 0.5f * -1 ); + m_exchangesounds.unloading.deserialize( parser, sound_type::single ); + m_exchangesounds.unloading.owner( this ); + } + + else if( token == "loading:" ) { + m_exchangesounds.loading.range( physics->Dim.L * 0.5f * -1 ); + m_exchangesounds.loading.deserialize( parser, sound_type::single ); + m_exchangesounds.loading.owner( this ); + } + + else if( token == "sand:" ) { + sSand.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sSand.owner( this ); + } + + else if( token == "releaser:" ) { + // pliki z odluzniaczem + sReleaser.deserialize( parser, sound_type::multipart, sound_parameters::range ); + sReleaser.owner( this ); + } + + else if( token == "outernoise:" ) { + // szum podczas jazdy: + sound_source noisetemplate{ sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; + noisetemplate.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency, physics->Vmax() ); + noisetemplate.owner( this ); + + noisetemplate.m_amplitudefactor /= 1 + physics->Vmax(); + noisetemplate.m_frequencyfactor /= 1 + physics->Vmax(); +#ifdef EU07_SOUND_BOGIESOUNDS + if( true == m_bogiesounds.empty() ) { + // fallback for cases without specified noise locations, convert sound template to a single sound source + m_bogiesounds.emplace_back( noisetemplate ); + } + else { + // apply configuration to all defined bogies + for( auto &bogie : m_bogiesounds ) { + // combine potential x- and y-axis offsets of the sound template with z-axis offsets of individual motors + auto bogieoffset{ noisetemplate.offset() }; + bogieoffset.z = bogie.offset().z; + bogie = noisetemplate; + bogie.offset( bogieoffset ); + } + } + // apply randomized playback start offset for each bogie, to reduce potential reverb with identical nearby sources + auto bogieidx( 0 ); + for( auto &bogie : m_bogiesounds ) { + bogie.start( ( + bogieidx % 2 ? + LocalRandom( 0.0, 30.0 ) : + LocalRandom( 50.0, 80.0 ) ) + * 0.01 ); + ++bogieidx; + } +#else + m_outernoise = noisetemplate; + // apply randomized playback start offset, to reduce potential reverb with identical nearby sources + m_outernoise.start( Random( 0.0, 80.0 ) * 0.01 ); +#endif + } + + else if( token == "wheelflat:" ) { + // szum podczas jazdy: + m_wheelflat.deserialize( parser, sound_type::single, sound_parameters::frequency ); + m_wheelflat.owner( this ); + } + + else { + return false; + } + return true; +} + +// the announcements of the passenger information system in the sounds: section +void TDynamicObject::loadSoundsAnnouncementKeyword( cParser &parser, std::string &token ) { + if(token == "announcements:") { + // announcement sounds + // content provided as "key: value" pairs together enclosed in "{}" + // value can be optionally set of values enclosed in "[]" in which case one value will be picked randomly + std::unordered_map const announcements = { + { "near_stop:", announcement_t::approaching }, + { "stop:", announcement_t::current }, + { "next_stop:", announcement_t::next }, + { "destination:", announcement_t::destination }, + { "chime:", announcement_t::chime } }; + while( (token = parser.getToken()) != "" + && token != "}" ) { + if( token.back() == ':' ) { + + if( token == "soundproofing:" ) { + // custom soundproofing in format [ p1, p2, p3, p4, p5, p6 ] + parser.getTokens( 6, false, "\n\r\t ,;[]" ); + std::array soundproofing; + parser + >> soundproofing[ 0 ] + >> soundproofing[ 1 ] + >> soundproofing[ 2 ] + >> soundproofing[ 3 ] + >> soundproofing[ 4 ] + >> soundproofing[ 5 ]; + for( auto & soundproofingelement : soundproofing ) { + if( soundproofingelement != -1.f ) { + soundproofingelement = std::sqrt( std::clamp( soundproofingelement, 0.f, 1.f ) ); + } + } + m_pasystem.soundproofing = soundproofing; + continue; + } + + auto const lookup { announcements.find( token ) }; + auto const announcementtype { ( + lookup != announcements.end() ? + lookup->second : + announcement_t::idle ) }; + // NOTE: we retrieve key value for all keys, not just recognized ones + if( announcementtype == announcement_t::idle ) { + token = parser.getToken(); + continue; + } +/* + auto announcementsound { deserialize_random_set( parser ) }; + replace_slashes( announcementsound ); +*/ + sound_source soundtemplate { sound_placement::engine }; // NOTE: sound range gets filled by pa system + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + m_pasystem.announcements[ static_cast( announcementtype ) ] = soundtemplate; + } + } + // set provided custom soundproofing to assigned sounds (for sounds without their own custom soundproofing) + if( m_pasystem.soundproofing ) { + for( auto &announcement : m_pasystem.announcements ) { + if( !announcement.soundproofing() ) { + announcement.soundproofing() = m_pasystem.soundproofing; + } + } + } + } +} + +// the locations: section of the .mmd file: the places of the doors, the mirrors, the motors and the bogies for their sounds +void TDynamicObject::loadLocationsSection( cParser &parser, std::string &token ) { + do { + token = ""; + parser.getTokens(); parser >> token; + + if( token == "doors:" ) { + // a list of pairs: offset along vehicle's z-axis and sides on which the door is present; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, for door locations negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + // recognized side specifications are "right", "left" and "both" + auto const sides { parser.getToken() }; + // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization + door_sounds door; + // add entries to the list: + if( sides == "both" + || sides == "left" ) { + // left... + auto const location { glm::vec3 { physics->Dim.W * 0.5f, physics->Dim.H * 0.5f, offset } }; + door.placement = VehicleSide::left; + door.rsDoorClose.offset( location ); + door.rsDoorOpen.offset( location ); + door.lock.offset( location ); + door.unlock.offset( location ); + door.step_close.offset( location ); + door.step_open.offset( location ); + door.permit_granted.offset( location ); + m_doorsounds.emplace_back( door ); + } + if( sides == "both" + || sides == "right" ) { + // ...and right + auto const location { glm::vec3 { physics->Dim.W * -0.5f, 2.f, offset } }; + door.placement = VehicleSide::right; + door.rsDoorClose.offset( location ); + door.rsDoorOpen.offset( location ); + door.lock.offset( location ); + door.unlock.offset( location ); + door.step_close.offset( location ); + door.step_open.offset( location ); + door.permit_granted.offset( location ); + m_doorsounds.emplace_back( door ); + } + m_doorspeakers.emplace_back( + doorspeaker_sounds { + { 0.f, 3.f, offset }, + {} } ); + } + } + + else if( token == "mirrors:" ) { + // a list of offsets along vehicle's z-axis of the mirror pairs, one at each cab; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, as for the doors negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + mirror_sounds mirror; + mirror.end = offset >= 0.f ? VehicleEnd::front : VehicleEnd::rear; + for( auto const mirrorside : { VehicleSide::left, VehicleSide::right } ) { + auto const location { glm::vec3 { + physics->Dim.W * ( mirrorside == VehicleSide::left ? 0.5f : -0.5f ), + physics->Dim.H * 0.5f, + offset } }; + mirror.placement = mirrorside; + mirror.unfold.offset( location ); + mirror.fold.offset( location ); + m_mirrorsounds.emplace_back( mirror ); + } + } + } + + else if( token == "tractionmotors:" ) { + // a list of offsets along vehicle's z-axis; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, for motor locations negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization + sound_source motor { sound_placement::external }; // generic traction motor sounds + sound_source acmotor { sound_placement::external }; // inverter-specific traction motor sounds + sound_source motorblower { sound_placement::engine }; // associated motor blowers + // add entry to the list + auto const location { glm::vec3 { 0.f, 0.f, offset } }; + motor.offset( location ); + m_powertrainsounds.motors.emplace_back( motor ); + acmotor.offset( location ); + m_powertrainsounds.acmotors.emplace_back( acmotor ); + motorblower.offset( location ); + m_powertrainsounds.motorblowers.emplace_back( motorblower ); + } + } + + else if( token == "bogies:" ) { + // a list of offsets along vehicle's z-axis; followed with "end" + while( (token = parser.getToken()) != "" + && token != "end" ) { + // vehicle faces +Z in 'its' space, for bogie locations negative value means ahead of centre + auto const offset { std::atof( token.c_str() ) * -1.f }; + // NOTE: we skip setting owner of the sounds, it'll be done during individual sound deserialization + sound_source bogienoise { sound_placement::external, EU07_SOUND_RUNNINGNOISECUTOFFRANGE }; + // add entry to the list + auto const location { glm::vec3 { 0.f, 0.f, offset } }; + bogienoise.offset( location ); +#ifdef EU07_SOUND_BOGIESOUNDS + m_bogiesounds.emplace_back( bogienoise ); +#endif + } + } + + } while( token != "" + && token != "endlocations" ); +} + +// the internaldata: section of the .mmd file: the cabs, the sounds of the devices, the couplers and the cab +void TDynamicObject::loadInternalDataSection( cParser &parser, std::string &token ) { + std::array cabplaces; // the cabs 1 and 2, for the driver figures + // dalej nie czytaj + do { + // zbieranie informacji o kabinach + token = ""; + parser.getTokens(); parser >> token; + loadInternalDataKeyword( parser, token, cabplaces ); + } while( token != "" ); + + SingleDesk = driver_figure::single_desk( JointCabs, cabplaces[ 0 ], cabplaces[ 1 ] ); +} + +// a keyword of the internaldata: section, read by the first group of keywords that knows it +void TDynamicObject::loadInternalDataKeyword( cParser &parser, std::string &token, std::array &cabplaces ) { + if( loadInternalDataDeviceKeyword( parser, token, cabplaces ) ) { return; } + if( loadInternalDataCouplerKeyword( parser, token ) ) { return; } + if( loadInternalDataBufferKeyword( parser, token ) ) { return; } + loadInternalDataCabKeyword( parser, token, cabplaces ); +} + +// the cab models and the sounds of the engine and its devices in the internaldata: section; false when the token is none of them +bool TDynamicObject::loadInternalDataDeviceKeyword( cParser &parser, std::string &token, std::array &cabplaces ) { + if( token == "cab0model:" ) { + parser.getTokens(); parser >> token; + if( token != "none" ) { iCabs |= 0x2; } + } + else if( token == "cab1model:" ) { + parser.getTokens(); parser >> token; + if( token != "none" ) { iCabs |= 0x1; } + cabplaces[ 0 ].model = token; + } + else if( token == "cab2model:" ) { + parser.getTokens(); parser >> token; + if( token != "none" ) { iCabs |= 0x4; } + cabplaces[ 1 ].model = token; + } + // engine sounds + else if( token == "ignition:" ) { + // odpalanie silnika + m_powertrainsounds.engine_ignition.deserialize( parser, sound_type::single ); + m_powertrainsounds.engine_ignition.owner( this ); + } else if (token == "shutdown:") { + m_powertrainsounds.engine_shutdown.deserialize(parser, sound_type::single); + m_powertrainsounds.engine_shutdown.owner(this); + } else if( token == "engageslippery:" ) { + // tarcie tarcz sprzegla: + m_powertrainsounds.rsEngageSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency ); + m_powertrainsounds.rsEngageSlippery.owner( this ); + + m_powertrainsounds.rsEngageSlippery.m_frequencyfactor /= 1 + physics->nmax; + } + + // dzwieki wycieraczkuf + else if (token == "wiperfrompark:") + { + sWiperFromPark.deserialize(parser, sound_type::single); + sWiperFromPark.owner(this); + } + else if (token == "wipertopark:") + { + sWiperToPark.deserialize(parser, sound_type::single); + sWiperToPark.owner(this); + } + + else if (token == "retarder:") { + m_powertrainsounds.retarder.deserialize(parser, sound_type::single, sound_parameters::amplitude | sound_parameters::frequency); + m_powertrainsounds.retarder.owner(this); + } + else if( token == "linebreakerclose:" ) { + m_powertrainsounds.linebreaker_close.deserialize( parser, sound_type::single ); + m_powertrainsounds.linebreaker_close.owner( this ); + } + else if( token == "linebreakeropen:" ) { + m_powertrainsounds.linebreaker_open.deserialize( parser, sound_type::single ); + m_powertrainsounds.linebreaker_open.owner( this ); + } + else if( token == "relay:" ) { + // styczniki itp: + m_powertrainsounds.motor_relay.deserialize( parser, sound_type::single ); + m_powertrainsounds.motor_relay.owner( this ); + } + else if( token == "shuntfield:" ) { + // styczniki itp: + m_powertrainsounds.motor_shuntfield.deserialize( parser, sound_type::single ); + m_powertrainsounds.motor_shuntfield.owner( this ); + } + else if( token == "wejscie_na_bezoporow:" ) { + // hunter-111211: wydzielenie wejscia na bezoporowa i na drugi uklad do pliku + m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( parser, sound_type::single ); + m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); + } + // przekazniki od kierunku jazdy + else if (token == "directionrelay_d:") { + // przekaznik od kierunku jazdy do przodu + sDirectionRelayD.deserialize(parser, sound_type::single); + sDirectionRelayD.owner(this); + } + else if (token == "directionrelay_r:") { + // przekaznik od kierunku jazdy do tylu + sDirectionRelayR.deserialize(parser, sound_type::single); + sDirectionRelayR.owner(this); + } + else if (token == "directionrelay_n:") + { + // przekaznik od kierunku jazdy do tylu + sDirectionRelayN.deserialize(parser, sound_type::single); + sDirectionRelayN.owner(this); + } + else if( token == "wejscie_na_drugi_uklad:" ) { + m_powertrainsounds.motor_parallel.deserialize( parser, sound_type::single ); + m_powertrainsounds.motor_parallel.owner( this ); + } + else if( token == "pneumaticrelay:" ) { + // wylaczniki pneumatyczne: + dsbPneumaticRelay.deserialize( parser, sound_type::single ); + dsbPneumaticRelay.owner( this ); + } + else if( token == "slipperysound:" ) { + // sanie: + rsSlippery.deserialize( parser, sound_type::single, sound_parameters::amplitude ); + rsSlippery.owner( this ); + + rsSlippery.m_amplitudefactor /= 1 + physics->Vmax(); + } + else { + return false; + } + return true; +} + +// the sounds of attaching and detaching the couplers and the connections in the internaldata: section; false when the token is none of them +bool TDynamicObject::loadInternalDataCouplerKeyword( cParser &parser, std::string_view token ) { + // coupler sounds + if( token == "couplerattach:" ) { + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_coupler = soundtemplate; + } + } + else if( token == "brakehoseattach:" ) { + // laczenie: + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_brakehose = soundtemplate; + } + } + else if( token == "mainhoseattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_mainhose = soundtemplate; + } + } + else if( token == "controlattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_control = soundtemplate; + } + } + else if( token == "gangwayattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_gangway = soundtemplate; + } + } + else if( token == "heatingattach:" ) { + // laczenie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.attach_heating = soundtemplate; + } + } + else if( token == "couplerdetach:" ) { + // rozlaczanie: + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_coupler = soundtemplate; + } + } + else if( token == "brakehosedetach:" ) { + // rozlaczanie: + sound_source soundtemplate { sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_brakehose = soundtemplate; + } + } + else if( token == "mainhosedetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_mainhose = soundtemplate; + } + } + else if( token == "controldetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_control = soundtemplate; + } + } + else if( token == "gangwaydetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_gangway = soundtemplate; + } + } + else if( token == "heatingdetach:" ) { + // rozlaczanie: + sound_source soundtemplate{ sound_placement::external }; + soundtemplate.deserialize( parser, sound_type::single ); + soundtemplate.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.detach_heating = soundtemplate; + } + } + else { + return false; + } + return true; +} + +// the sounds of the stretched couplers, the buffers and the coupler adapters in the internaldata: section; false when the token is none of them +bool TDynamicObject::loadInternalDataBufferKeyword( cParser &parser, std::string_view token ) { + if( token == "couplerstretch:" ) { + // coupler stretching + sound_source couplerstretch { sound_placement::external }; + couplerstretch.deserialize( parser, sound_type::single ); + couplerstretch.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbCouplerStretch = couplerstretch; + } + } + else if( token == "couplerstretch_loud:" ) { + // coupler stretching + sound_source couplerstretch { sound_placement::external }; + couplerstretch.deserialize( parser, sound_type::single ); + couplerstretch.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbCouplerStretch_loud = couplerstretch; + } + } + else if( token == "bufferclamp:" ) { + // buffers hitting one another + sound_source bufferclash { sound_placement::external }; + bufferclash.deserialize( parser, sound_type::single ); + bufferclash.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbBufferClamp = bufferclash; + } + } + else if( token == "bufferclamp_loud:" ) { + // buffers hitting one another + sound_source bufferclash { sound_placement::external }; + bufferclash.deserialize( parser, sound_type::single ); + bufferclash.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbBufferClamp_loud = bufferclash; + } + } + else if( token == "coupleradapterattach:" ) { + // laczenie: + sound_source adapterattach { sound_placement::external }; + adapterattach.deserialize( parser, sound_type::single ); + adapterattach.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbAdapterAttach = adapterattach; + } + } + else if( token == "coupleradapterremove:" ) { + // rozlaczanie: + sound_source adapterremove { sound_placement::external }; + adapterremove.deserialize( parser, sound_type::single ); + adapterremove.owner( this ); + for( auto &couplersounds : m_couplersounds ) { + couplersounds.dsbAdapterRemove = adapterremove; + } + } + else { + return false; + } + return true; +} + +// the start jolt, the shaking, the soundproofing, the light and the destination sign of the cab in the internaldata: section +void TDynamicObject::loadInternalDataCabKeyword( cParser &parser, std::string_view token, std::array &cabplaces ) { + if( token == "startjolt:" ) { + // movement start jolt + m_startjolt.deserialize( parser, sound_type::single ); + m_startjolt.owner( this ); + } + + else if (token == "mechspring:") + { + // parametry bujania kamery: + double ks, kd; + parser.getTokens(2, false); + parser + >> ks + >> kd; + ShakeSpring.Init(ks, kd); + parser.getTokens(6, false); + parser + >> BaseShake.jolt_scale.x + >> BaseShake.jolt_scale.y + >> BaseShake.jolt_scale.z + >> BaseShake.jolt_limit + >> BaseShake.angle_scale.x + >> BaseShake.angle_scale.z; + } + else if( token == "enginespring:" ) { + parser.getTokens( 5, false ); + parser + >> EngineShake.scale + >> EngineShake.fadein_offset + >> EngineShake.fadein_factor + >> EngineShake.fadeout_offset + >> EngineShake.fadeout_factor; + // offsets values are provided as rpm for convenience + EngineShake.fadein_offset /= 60.f; + EngineShake.fadeout_offset /= 60.f; + } + else if( token == "huntingspring:" ) { + parser.getTokens( 4, false ); + parser + >> HuntingShake.scale + >> HuntingShake.frequency + >> HuntingShake.fadein_begin + >> HuntingShake.fadein_end; + } + + else if( token == "soundproofing:" ) { + for( auto &soundproofingtable : m_soundproofing ) { + for( auto &soundproofingelement : soundproofingtable ) { + auto const value { parser.getToken( false ) }; + if( value != -1.f ) { + soundproofingelement = std::sqrt( std::clamp( value, 0.f, 1.f ) ); + } + } + } + } + + else if( token == "jointcabs:" ) { + parser.getTokens(); + parser >> JointCabs; + } + + else if( token == "cablight:" ) { + parser.getTokens( 3, false ); // low power light, ignore + parser.getTokens( 3, false ); // base light + parser + >> InteriorLight.r + >> InteriorLight.g + >> InteriorLight.b; + InteriorLight = glm::clamp( InteriorLight / 255.f, glm::vec3( 0.f ), glm::vec3( 1.f ) ); + parser.getTokens( 3, false ); // dimmed light, ignore + } + + else if( token == "pydestinationsign:" ) { + DestinationSign.deserialize( parser ); + // supply vehicle folder as script path if none is provided + if( false == DestinationSign.script.empty() + && substr_path(DestinationSign.script).empty() ) { + DestinationSign.script = asBaseDir + DestinationSign.script; + } + } + else if( token == "luadestinationsign:" ) { + deserialize_script_sign( parser, DestinationSign.lua, asBaseDir ); + } + else if( token == "wasmdestinationsign:" ) { + deserialize_script_sign( parser, DestinationSign.wasm, asBaseDir ); + } + // NOTE: legacy key, now expected as optional "background:" parameter in pydestinationsign: { parameter block } + else if( token == "destinationsignbackground:" ) { + parser.getTokens(); + parser >> DestinationSign.background; + } + else { + read_driver_position( parser, token, cabplaces ); + } +} + +// the end of loading the .mmd file: the checks, the destination sign and what the file left out +void TDynamicObject::finishLoadingMMediaFile( std::string const &asFileName, std::string const &ReplacableSkin ) { + if( !iAnimations ) { + // if the animations weren't defined the model is likely to be non-functional. warrants a warning. + ErrorLog( "Animations tag is missing from the .mmd file \"" + asFileName + "\"" ); + } + + if( ReplacableSkin != "none" ) { + // potentially set blank destination texture + auto language { script_language::lua }; + auto const *scriptsign { script_destination( language ) }; + auto const &background { ( scriptsign != nullptr && false == scriptsign->background.empty() ) ? scriptsign->background : DestinationSign.background }; + DestinationSign.destination_off = DestinationFind( background.empty() ? "nowhere" : background ); + // a blank sign a script draws, drawn once + DestinationSign.background_sign = draw_script_texture( background, DestinationSign.destination_off ); + } + + assignDefaultMMediaSounds(); + initMMediaModels(); + positionMMediaSoundEmitters(); +} + +// assigns the default samples to the sound emitters the .mmd file left out +void TDynamicObject::assignDefaultMMediaSounds() { + // assign default samples to sound emitters which weren't included in the config file + if( TestFlag( physics->CategoryFlag, 1 ) ) { + // rail vehicles: + // engine + if( physics->Power > 0 ) { + if( true == m_powertrainsounds.dsbWejscie_na_bezoporow.empty() ) { + // hunter-111211: domyslne, gdy brak + m_powertrainsounds.dsbWejscie_na_bezoporow.deserialize( "wejscie_na_bezoporow", sound_type::single ); + m_powertrainsounds.dsbWejscie_na_bezoporow.owner( this ); + } + if( true == m_powertrainsounds.motor_parallel.empty() ) { + m_powertrainsounds.motor_parallel.deserialize( "wescie_na_drugi_uklad", sound_type::single ); + m_powertrainsounds.motor_parallel.owner( this ); + } + } + // braking sounds + if( true == rsUnbrake.empty() ) { + rsUnbrake.deserialize( "[1007]estluz", sound_type::single ); + rsUnbrake.owner( this ); + } + // couplers + for( auto &couplersounds : m_couplersounds ) { + if( true == couplersounds.attach_coupler.empty() ) { + couplersounds.attach_coupler.deserialize( "couplerattach_default", sound_type::single ); + couplersounds.attach_coupler.owner( this ); + } + if( true == couplersounds.detach_coupler.empty() ) { + couplersounds.detach_coupler.deserialize( "couplerdetach_default", sound_type::single ); + couplersounds.detach_coupler.owner( this ); + } + if( true == couplersounds.dsbCouplerStretch.empty() ) { + couplersounds.dsbCouplerStretch.deserialize( "couplerstretch_default", sound_type::single ); + couplersounds.dsbCouplerStretch.owner( this ); + } + if( true == couplersounds.dsbBufferClamp.empty() ) { + couplersounds.dsbBufferClamp.deserialize( "bufferclamp_default", sound_type::single ); + couplersounds.dsbBufferClamp.owner( this ); + } + } + // other sounds + if( true == m_wheelflat.empty() ) { + m_wheelflat.deserialize( "lomotpodkucia 0.23 0.0", sound_type::single, sound_parameters::frequency ); + m_wheelflat.owner( this ); + } + if( true == rscurve.empty() ) { + // hunter-111211: domyslne, gdy brak + rscurve.deserialize( "curve", sound_type::single ); + rscurve.owner( this ); + } + } +} + +// initialises the loaded 3d models and restores the default paths +void TDynamicObject::initMMediaModels() { + if (mdModel) + mdModel->Init(); // obrócenie modelu oraz optymalizacja, również zapisanie binarnego + if (mdLoad) + mdLoad->Init(); + if (mdLowPolyInt) + mdLowPolyInt->Init(); + for( auto *attachment : mdAttachments ) { + attachment->Init(); + } + + Global.asCurrentTexturePath = paths::textures; // kiedyś uproszczone wnętrze mieszało tekstury nieba + Global.asCurrentDynamicPath = ""; +} + +// places the sound emitters the .mmd file left without a location +void TDynamicObject::positionMMediaSoundEmitters() { + // position sound emitters which weren't defined in the config file + // engine sounds, centre of the vehicle + auto const enginelocation { glm::vec3 {0.f, physics->Dim.H * 0.5f, 0.f } }; + m_powertrainsounds.position( enginelocation ); + // other engine compartment sounds + auto const nullvector { glm::vec3() }; + std::vector enginesounds = { + &sConverter, &sBRVent, &sCompressor, &sCompressorIdle, &sSmallCompressor, &sHeater, &m_batterysound + }; + for( auto sound : enginesounds ) { + if( sound->offset() == nullvector ) { + sound->offset( enginelocation ); + } + } + + // pantographs + if( pants != nullptr ) { + std::size_t pantographindex { 0 }; + for( auto &pantographsounds : m_pantographsounds ) { + auto const pantographoffset { + glm::vec3( + 0.f, + pants[ pantographindex ].fParamPants->vPos.y, + -pants[ pantographindex ].fParamPants->vPos.x ) }; + pantographsounds.sPantUp.offset( pantographoffset ); + pantographsounds.sPantDown.offset( pantographoffset ); + ++pantographindex; + } + } + // doors + std::size_t dooranimationfirstindex { 0 }; + for( std::size_t i = 0; i < ANIM_DOORS; ++i ) { + // zliczanie wcześniejszych animacji + dooranimationfirstindex += iAnimType[ i ]; + } + // couplers + auto const frontcoupleroffset { glm::vec3{ 0.f, 1.f, physics->Dim.L * 0.5f } }; + m_couplersounds[ VehicleEnd::front ].attach_coupler.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_brakehose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_mainhose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_control.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_gangway.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].attach_heating.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_coupler.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_brakehose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_mainhose.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_control.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_gangway.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].detach_heating.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbCouplerStretch.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbCouplerStretch_loud.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbBufferClamp.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbBufferClamp_loud.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbAdapterAttach.offset( frontcoupleroffset ); + m_couplersounds[ VehicleEnd::front ].dsbAdapterRemove.offset( frontcoupleroffset ); + auto const rearcoupleroffset { glm::vec3{ 0.f, 1.f, physics->Dim.L * -0.5f } }; + m_couplersounds[ VehicleEnd::rear ].attach_coupler.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_brakehose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_mainhose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_control.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_gangway.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].attach_heating.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_coupler.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_brakehose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_mainhose.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_control.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_gangway.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].detach_heating.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbCouplerStretch.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbCouplerStretch_loud.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbBufferClamp.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbBufferClamp_loud.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbAdapterAttach.offset( rearcoupleroffset ); + m_couplersounds[ VehicleEnd::rear ].dsbAdapterRemove.offset( rearcoupleroffset ); +} + +TModel3d * +TDynamicObject::LoadMMediaFile_mdload( std::string const &Name ) const { + + auto const loadname { ( Name.empty() ? "none" : Name ) }; + TModel3d *loadmodel { nullptr }; + + // check if we don't have model override for this load type + if ( loadmodel == nullptr ) + { + auto const lookup { LoadModelOverrides.find( loadname ) }; + if( lookup != LoadModelOverrides.end() ) { + loadmodel = TModelsManager::GetModel( asBaseDir + lookup->second, true ); + } + } + // regular routine if there's no override or it couldn't be loaded + // try first specialized version of the load model, vehiclename_loadname + if ( loadmodel == nullptr ) + { + auto const specializedloadfilename { asBaseDir + physics->TypeName + "_" + loadname }; + loadmodel = TModelsManager::GetModel( specializedloadfilename, true, false ); + } + // try generic version of the load model next, loadname + if ( loadmodel == nullptr ) + { + auto const genericloadfilename { asBaseDir + loadname }; + loadmodel = TModelsManager::GetModel( genericloadfilename, true, false ); + } + + if ( loadmodel != nullptr ) + loadmodel->GetSMRoot()->WillBeAnimated(); + + return loadmodel; +} diff --git a/vehicle/dynamic/movement.cpp b/vehicle/dynamic/movement.cpp new file mode 100644 index 000000000..d26cb101b --- /dev/null +++ b/vehicle/dynamic/movement.cpp @@ -0,0 +1,321 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// moving a vehicle along its track, its axles and its bogies + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::FastMove(double fDistance) +{ + physics->SetMoveLength(physics->MoveLength() + fDistance); +} + +void TDynamicObject::Move(double fDistance) +{ + if( physics->OffTrack.active() ) { + // physics.derailment new: off the track it goes on the ground + move_off_track( fDistance ); + return; + } + move_axles( fDistance ); + if( fDistance != 0.0 || m_offtrackplaced ) // nie liczyć ponownie, jeśli stoi + { // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach + // (also once the vehicle off the track is back on the rails) + m_offtrackplaced = false; + place_by_axles(); + } +} + +void TDynamicObject::move_axles(double fDistance) +{ // przesuwanie pojazdu po + // trajektorii polega na + // przesuwaniu poszczególnych osi + // Ra: wartość prędkości 2km/h ma ograniczyć aktywację eventów w przypadku + // drgań + if (Axle0.GetTrack() == Axle1.GetTrack()) // przed przesunięciem + { // powiązanie pojazdu z osią można zmienić tylko wtedy, gdy skrajne osie są + // na tym samym torze + if (physics->Vel > + 2) //|[km/h]| nie ma sensu zmiana osi, jesli pojazd drga na postoju + iAxleFirst = physics->V() >= 0.0 ? + 1 : + 0; //[m/s] ?1:0 - aktywna druga oś w kierunku jazdy + // aktualnie eventy aktywuje druga oś, żeby AI nie wyłączało sobie semafora + // za szybko + } + if (fDistance > 0.0) + { // gdy ruch w stronę sprzęgu 0, doliczyć korektę do osi 1 + bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu + bEnabled &= Axle1.Move(fDistance /*-fAdjustment*/, iAxleFirst != 0); // oś z tyłu pojazdu + } + else if (fDistance < 0.0) + { // gdy ruch w stronę sprzęgu 1, doliczyć korektę do osi 0 + bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza + bEnabled &= Axle0.Move(fDistance /*-fAdjustment*/, iAxleFirst == 0); // oś z przodu pojazdu + } + else // gf: bez wywolania Move na postoju nie ma event0 + { + bEnabled &= Axle1.Move(fDistance, iAxleFirst != 0); // oś z tyłu pojazdu prusza się pierwsza + bEnabled &= Axle0.Move(fDistance, iAxleFirst == 0); // oś z przodu pojazdu + } +} + +void TDynamicObject::place_by_axles() +{ // liczenie pozycji pojazdu tutaj, bo jest używane w wielu miejscach + vPosition = 0.5 * (Axle1.pPosition + Axle0.pPosition); //środek między skrajnymi osiami + vFront = Axle0.pPosition - Axle1.pPosition; // wektor pomiędzy skrajnymi osiami + // Ra 2F1J: to nie jest stabilne (powoduje rzucanie taborem) i wymaga + // dopracowania + fAdjustment = glm::length(vFront) - fAxleDist; // na łuku będzie ujemny + // if (fabs(fAdjustment)>0.02) //jeśli jest zbyt dużo, to rozłożyć na kilka przeliczeń (wygasza drgania?) + //{//parę centymetrów trzeba by już skorygować; te błędy mogą się też + // generować na ostrych łukach + // fAdjustment*=0.5; //w jednym kroku korygowany jest ułamek błędu + //} + // else + // fAdjustment=0.0; + vFront = glm::normalize(vFront); // kierunek ustawienia pojazdu (wektor jednostkowy) + vLeft = glm::normalize(glm::cross(glm::dvec3(vWorldUp), vFront)); // wektor poziomy w lewo, + // normalizacja potrzebna z powodu pochylenia (vFront) + vUp = glm::cross(vFront, vLeft); // wektor w górę, będzie jednostkowy + modelRot.z = atan2(-vFront.x, vFront.z); // kąt obrotu pojazdu [rad]; z ABuBogies() + auto const roll { Roll() }; // suma przechyłek + if (roll != 0.0) + { // wyznaczanie przechylenia tylko jeśli jest przechyłka + // można by pobrać wektory normalne z toru... + mMatrix = glm::rotate(glm::dmat4(1.0), roll * 0.5, vFront); // ta macierz jest potrzebna głównie do wyświetlania // obrót wzdłuż osi o przechyłkę + vUp = glm::dvec3(mMatrix * glm::dvec4(vUp, 0.0)); // wektor w górę pojazdu (przekręcenie na przechyłce) + // vLeft=mMatrix*DynamicObject->vLeft; + // vUp=CrossProduct(vFront,vLeft); //wektor w górę + // vLeft=Normalize(CrossProduct(vWorldUp,vFront)); //wektor w lewo + vLeft = glm::normalize(glm::cross(vUp, vFront)); // wektor w lewo + // vUp=CrossProduct(vFront,vLeft); //wektor w górę + } + mMatrix = BasisChange(vLeft, vUp, vFront); // to też można by od razu policzyć, ale potrzebne jest do wyświetlania // przesuwanie jest jednak rzadziej niż renderowanie + mMatrix = glm::inverse(mMatrix); // wyliczenie macierzy dla pojazdu (potrzebna tylko do wyświetlania?) + // if (physics->CategoryFlag&2) + { // przesunięcia są używane po wyrzuceniu pociągu z toru + vPosition.x += physics->OffsetTrackH() * vLeft.x; // dodanie przesunięcia w bok + vPosition.z += physics->OffsetTrackH() * vLeft.z; // vLeft jest wektorem poprzecznym + // if () na przechyłce będzie dodatkowo zmiana wysokości samochodu + vPosition.y += physics->OffsetTrackV(); // te offsety są liczone przez the physics + } + // obliczanie pozycji sprzęgów do liczenia zderzeń + auto dir = 0.5 * physics->Dim.L * vFront; // wektor sprzęgu + vCoulpler[VehicleEnd::front] = vPosition + dir; // współrzędne sprzęgu na początku + vCoulpler[VehicleEnd::rear] = vPosition - dir; // współrzędne sprzęgu na końcu + // bCameraNear= + // if (bCameraNear) //jeśli istotne są szczegóły (blisko kamery) + { // przeliczenie cienia + TTrack *t0 = Axle0.GetTrack(); // już po przesunięciu + TTrack *t1 = Axle1.GetTrack(); + if (t0->eEnvironment == e_flat && t1->eEnvironment == e_flat) // może być e_bridge... + fShade = 0.0; // standardowe oświetlenie + else + { // jeżeli te tory mają niestandardowy stopień zacienienia + // (e_canyon, e_tunnel) + if (t0->eEnvironment == t1->eEnvironment) + { + switch (t0->eEnvironment) + { // typ zmiany oświetlenia + case e_canyon: + fShade = 0.65f; + break; // zacienienie w kanionie + case e_tunnel: + fShade = 0.20f; + break; // zacienienie w tunelu + } + } + else // dwa różne + { // liczymy proporcję + double d = Axle0.GetTranslation(); // aktualne położenie na torze + if (Axle0.GetDirection() < 0) + d = t0->Length() - d; // od drugiej strony liczona długość + d /= fAxleDist; // rozsataw osi procentowe znajdowanie się na torze + + float shadefrom = 1.0f, shadeto = 1.0f; + // NOTE, TODO: calculating brightness level is used enough times to warrant encapsulation into a function + switch( t0->eEnvironment ) { + case e_canyon: { shadeto = 0.65f; break; } + case e_tunnel: { shadeto = 0.2f; break; } + default: {break; } + } + switch( t1->eEnvironment ) { + case e_canyon: { shadefrom = 0.65f; break; } + case e_tunnel: { shadefrom = 0.2f; break; } + default: {break; } + } + fShade = std::lerp( shadefrom, shadeto, static_cast( d ) ); +/* + switch (t0->eEnvironment) + { // typ zmiany oświetlenia - zakładam, że + // drugi tor ma e_flat + case e_canyon: + fShade = (d * 0.65) + (1.0 - d); + break; // zacienienie w kanionie + case e_tunnel: + fShade = (d * 0.20) + (1.0 - d); + break; // zacienienie w tunelu + } + switch (t1->eEnvironment) + { // typ zmiany oświetlenia - zakładam, że + // pierwszy tor ma e_flat + case e_canyon: + fShade = d + (1.0 - d) * 0.65; + break; // zacienienie w kanionie + case e_tunnel: + fShade = d + (1.0 - d) * 0.20; + break; // zacienienie w tunelu + } +*/ + } + } + } +} + +bool TDynamicObject::UpdateForce(double dt) +{ + if (!bEnabled) + return false; + if( dt > 0 ) { + // wywalenie WS zależy od ustawienia kierunku + physics->ComputeTotalForce( dt ); + } + return true; +} + +glm::dvec3 TDynamicObject::get_future_movement() const +{ + return m_future_movement; +} + +void TDynamicObject::move_set(double distance) +{ + TDynamicObject *d = this; + while( d ) { + d->Move( distance * d->DirectionGet() ); + d = d->Next(); // pozostałe też + } + d = Prev(); + while( d ) { + d->Move( distance * d->DirectionGet() ); + d = d->Prev(); // w drugą stronę też + } +} + +bool TDynamicObject::FastUpdate(double dt) +{ + if (dt == 0.0) + return true; // Ra: pauza + double dDOMoveLen; + if (!physics->PhysicActivation()) + return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba + + if (!bEnabled) + return false; + + // NOTE: coordinate system swap + // TODO: replace with regular glm vectors + TLocation const l { + -vPosition.x, + vPosition.z, + vPosition.y }; + TRotation const r { + 0.0, + 0.0, + modelRot.z }; + // McZapkie: parametry powinny byc pobierane z toru + // ts.R=MyTrack->fRadius; + // ts.Len= std::max(physics->BDist(),physics->ADist()); + // ts.dHtrack=Axle1.pPosition.y-Axle0.pPosition.y; + // ts.dHrail=((Axle1.GetRoll())+(Axle0.GetRoll()))*0.5f; + // tp.Width=MyTrack->fTrackWidth; + // McZapkie-250202 + // tp.friction= MyTrack->fFriction; + // tp.CategoryFlag= MyTrack->iCategoryFlag&15; + // tp.DamageFlag=MyTrack->iDamageFlag; + // tp.QualityFlag=MyTrack->iQualityFlag; + dDOMoveLen = physics->FastComputeMovement(dt, ts, tp, l, r); // ,ts,tp,tmpTraction); + // Move(dDOMoveLen); + // ResetdMoveLen(); + FastMove(dDOMoveLen); + + if( physics->LoadStatus() ) { + LoadUpdate(); // zmiana modelu ładunku + } + update_exchange( dt ); + + return true; // Ra: chyba tak? +} + +// calculates distance between event-starting axle and front of the vehicle +double +TDynamicObject::tracing_offset() const { + + auto const axletoend{ ( GetLength() - fAxleDist ) * 0.5 }; + return iAxleFirst ? axletoend : axletoend + iDirection * fAxleDist; +} + +// TODO: compute and cache radius during vehicle initialization +double +TDynamicObject::radius() const { + + glm::vec3 diagonal( + static_cast( physics->Dim.L ), + static_cast( physics->Dim.H ), + static_cast( physics->Dim.W ) ); + return glm::length( diagonal ) * 0.5f; +} diff --git a/vehicle/dynamic/neighbours.cpp b/vehicle/dynamic/neighbours.cpp new file mode 100644 index 000000000..9d9d97945 --- /dev/null +++ b/vehicle/dynamic/neighbours.cpp @@ -0,0 +1,313 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the vehicles near a vehicle on its track, found for the couplings and the collisions + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +// ABu 29.01.05 koniec przeklejenia ************************************* + +TDynamicObject * TDynamicObject::ABuFindNearestObject(glm::vec3 pos, TTrack *Track, TDynamicObject *MyPointer, int &CouplNr) +{ + // zwraca wskaznik do obiektu znajdujacego sie na torze (Track), którego sprzęg jest najblizszy punktowi + // służy np. do łączenia i rozpinania sprzęgów + // WE: Track - tor, na ktorym odbywa sie poszukiwanie + // MyPointer - wskaznik do obiektu szukajacego + // WY: CouplNr - który sprzęg znalezionego obiektu jest bliższy kamerze + + // Uwaga! Jesli CouplNr==-2 to szukamy njblizszego obiektu, a nie sprzegu!!! + for( auto dynamic : Track->Dynamics ) { + + if( CouplNr == -2 ) { + // wektor [kamera-obiekt] - poszukiwanie obiektu + // length2 is better than length for comparing because it does not require sqrt function + if (glm::length2(glm::dvec3(pos) - dynamic->vPosition) < sq(10.0)) + { + // 10 metrów + return dynamic; + } + } + else { + // jeśli (CouplNr) inne niz -2, szukamy sprzęgu + // length2 is better than length for comparing because it does not require sqrt function + if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[0]) < sq(5.0)) { + // 5 metrów + CouplNr = 0; + return dynamic; + } + // length2 is better than length for comparing because it does not require sqrt function + if (glm::length2(glm::dvec3(pos) - dynamic->vCoulpler[1]) < sq(5.0)) { + // 5 metrów + CouplNr = 1; + return dynamic; + } + } + } + // empty track or nothing found + return nullptr; +} + +TDynamicObject * TDynamicObject::ABuScanNearestObject(glm::vec3 pos, TTrack *Track, double ScanDir, double ScanDist, int &CouplNr) +{ // skanowanie toru w poszukiwaniu obiektu najblizszego punktowi + if (ABuGetDirection() < 0) + ScanDir = -ScanDir; + TDynamicObject *FoundedObj; + FoundedObj = + ABuFindNearestObject(pos, Track, this, CouplNr); // zwraca numer sprzęgu znalezionego pojazdu + if (FoundedObj == nullptr && Track != nullptr) + { + double ActDist; // Przeskanowana odleglosc. + double CurrDist = 0; // Aktualna dlugosc toru. + if (ScanDir >= 0) + ActDist = + Track->Length() - RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru + else + ActDist = RaTranslationGet(); // przesunięcie wózka względem Point1 toru + while (ActDist < ScanDist) + { + ActDist += CurrDist; + if (ScanDir > 0) // do przodu + { + if (Track->iNextDirection) // NOSONAR + { + Track = Track->CurrentNext(); + ScanDir = -ScanDir; + } + else + Track = Track->CurrentNext(); + } + else // do tyłu + { + if (Track->iPrevDirection) // NOSONAR + Track = Track->CurrentPrev(); + else + { + Track = Track->CurrentPrev(); + ScanDir = -ScanDir; + } + } + if (Track != nullptr) + { // jesli jest kolejny odcinek toru + CurrDist = Track->Length(); + FoundedObj = ABuFindNearestObject(pos, Track, this, CouplNr); + if (FoundedObj != nullptr) + ActDist = ScanDist; + } + else // Jesli nie ma, to wychodzimy. + break; + } + } // Koniec szukania najblizszego toru z jakims obiektem. + return FoundedObj; +} + +// ABu 01.11.04 poczatek wyliczania przechylow pudla ********************** +void TDynamicObject::ABuModelRoll() +{ // ustawienie przechyłki pojazdu i jego + // zawartości + // Ra: przechyłkę załatwiamy na etapie przesuwania modelu +} + +// ABu 06.05.04 poczatek wyliczania obrotow wozkow ********************** + +void TDynamicObject::ABuBogies() +{ // Obracanie wozkow na zakretach. Na razie + // uwzględnia tylko zakręty, + // bez zadnych gorek i innych przeszkod. + if( smBogie[ 0 ] != nullptr && smBogie[ 1 ] != nullptr && physics->OffTrack.active() ) { + // off the track the bogies stay straight under the body, they don't follow the track any more + bogieRot[ 0 ] = glm::vec3 { 0.f }; + bogieRot[ 1 ] = glm::vec3 { 0.f }; + smBogie[ 0 ]->SetRotateXYZ( bogieRot[ 0 ] ); + smBogie[ 1 ]->SetRotateXYZ( bogieRot[ 1 ] ); + return; + } + if (smBogie[0] != nullptr && smBogie[1] != nullptr) + { + // modelRot.z=ABuAcos(Axle0.pPosition-Axle1.pPosition); //kąt obrotu pojazdu + // [rad] + // bogieRot[0].z=ABuAcos(Axle0.pPosition-Axle3.pPosition); + bogieRot[0].z = Axle0.vAngles.z; + bogieRot[0] = glm::degrees(modelRot - bogieRot[0]); // mnożenie wektora przez stałą + smBogie[0]->SetRotateXYZ(bogieRot[0]); + // bogieRot[1].z=ABuAcos(Axle2.pPosition-Axle1.pPosition); + bogieRot[1].z = Axle1.vAngles.z; + bogieRot[1] = glm::degrees(modelRot - bogieRot[1]); + smBogie[1]->SetRotateXYZ(bogieRot[1]); + } +}; +// ABu 06.05.04 koniec wyliczania obrotow wozkow ************************ + +// ABu 16.03.03 sledzenie toru przed obiektem: ************************** +void TDynamicObject::ABuCheckMyTrack() +{ // Funkcja przypisujaca obiekt + // prawidlowej tablicy Dynamics, + // bo gdzies jest jakis blad i wszystkie obiekty z danego + // pociagu na poczatku stawiane sa na jednym torze i wpisywane + // do jednej tablicy. Wykonuje sie tylko raz - po to 'ABuChecked' + TTrack *OldTrack = MyTrack; + TTrack *NewTrack = Axle0.GetTrack(); + if( NewTrack != OldTrack ) { + if( OldTrack ) { + OldTrack->RemoveDynamicObject( this ); + } + NewTrack->AddDynamicObject(this); + } + iAxleFirst = 0; // pojazd powiązany z przednią osią - Axle0 +} + +// Ra: w poniższej funkcji jest problem ze sprzęgami +TDynamicObject * +TDynamicObject::ABuFindObject( int &Foundcoupler, double &Distance, TTrack const *Track, int const Direction, int const Mycoupler, bool const InLine ) const +{ // Zwraca wskaźnik najbliższego obiektu znajdującego się + // na torze w określonym kierunku, ale tylko wtedy, kiedy + // obiekty mogą się zderzyć, tzn. nie mijają się. + // WE: + // Track - tor, na ktorym odbywa sie poszukiwanie, + // Direction - kierunek szukania na torze (+1:w stronę Point2, -1:w stronę Point1) + // Mycoupler - nr sprzegu obiektu szukajacego; + // WY: + // wskaznik do znalezionego obiektu. + // Foundcoupler - nr sprzegu znalezionego obiektu + // Distance - distance to found object + + if( true == Track->Dynamics.empty() ) { + // sens szukania na tym torze jest tylko, gdy są na nim pojazdy + Distance += Track->Length(); // doliczenie długości odcinka do przeskanowanej odległości + return nullptr; // nie ma pojazdów na torze, to jest NULL + } + + double distance = Track->Length(); // najmniejsza znaleziona odleglość (zaczynamy od długości toru) + double myposition; // pozycja szukającego na torze + TDynamicObject *foundobject = nullptr; + if( MyTrack == Track ) { + // gdy szukanie na tym samym torze + myposition = RaTranslationGet(); // położenie wózka względem Point1 toru + } + else { + // gdy szukanie na innym torze + if( Direction > 0 ) { + // szukanie w kierunku Point2 (od zera) - jesteśmy w Point1 + myposition = 0; + } + else { + // szukanie w kierunku Point1 (do zera) - jesteśmy w Point2 + myposition = distance; + } + } + + double objectposition; // robocza odległość od kolejnych pojazdów na danym odcinku + for( auto dynamic : Track->Dynamics ) { + + if( dynamic == this ) { continue; } // szukający się nie liczy + // physics.derailment new: one of the two off the track beside the other one, they don't meet + if( InLine && ( physics->OffTrack.active() || dynamic->physics->OffTrack.active() ) && false == in_line_with( *dynamic ) ) { + continue; + } +/* + if( ( ( dynamic == PrevConnected ) && ( physics->Couplers[ physics::Vehicle::side::front ].CouplingFlag != Coupling::none ) ) + || ( ( dynamic == NextConnected ) && ( physics->Couplers[ physics::Vehicle::side::rear ].CouplingFlag != Coupling::none ) ) ){ + // stop-gap check to prevent 'detection' of attached vehicles + // which seems to be a side-effect of inaccurate location calculation in 'simple' mode? + // TODO: investigate actual cause + continue; + } +*/ + if( Direction > 0 ) { + // jeśli szukanie w kierunku Point2 + objectposition = dynamic->RaTranslationGet() - myposition; // odległogłość tamtego od szukającego + if( objectposition > 0 + && objectposition < distance ) { + // gdy jest po właściwej stronie i bliżej niż jakiś wcześniejszy + Foundcoupler = dynamic->RaDirectionGet() > 0 ? 1 : 0; // to, bo (ScanDir>=0) + } + else { continue; } + } + else { + objectposition = myposition - dynamic->RaTranslationGet(); //???-przesunięcie wózka względem Point1 toru + if( objectposition > 0 + && objectposition < distance ) { + Foundcoupler = dynamic->RaDirectionGet() > 0 ? 0 : 1; // odwrotnie, bo (ScanDir<0) + } + else { continue; } + } + + if( Track->iCategoryFlag & 254 ) { + // trajektoria innego typu niż tor kolejowy + // dla torów nie ma sensu tego sprawdzać, rzadko co jedzie po jednej szynie i się mija + // Ra: mijanie samochodów wcale nie jest proste + // Przesuniecie wzgledne pojazdow. Wyznaczane, zeby sprawdzic, + // czy pojazdy faktycznie sie zderzaja (moga byc przesuniete + // w/m siebie tak, ze nie zachodza na siebie i wtedy sie mijaja). + double relativeoffset; // wzajemna odległość poprzeczna + if( Foundcoupler != Mycoupler ) { + // facing the same direction + relativeoffset = std::abs( physics->OffsetTrackH() - dynamic->physics->OffsetTrackH() ); + } + else { + relativeoffset = std::abs( physics->OffsetTrackH() + dynamic->physics->OffsetTrackH() ); + } + if( relativeoffset + relativeoffset > physics->Dim.W + dynamic->physics->Dim.W ) { + // odległość większa od połowy sumy szerokości - kolizji nie będzie + continue; + } + // jeśli zahaczenie jest niewielkie, a jest miejsce na poboczu, to zjechać na pobocze + } + foundobject = dynamic; // potencjalna kolizja + distance = objectposition; // odleglość pomiędzy aktywnymi osiami pojazdów + } + + Distance += distance; // doliczenie odległości przeszkody albo długości odcinka do przeskanowanej odległości + return foundobject; +} diff --git a/vehicle/dynamic/offtrack.cpp b/vehicle/dynamic/offtrack.cpp new file mode 100644 index 000000000..a1cb6bffc --- /dev/null +++ b/vehicle/dynamic/offtrack.cpp @@ -0,0 +1,523 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// a derailed vehicle off the track, on the ground + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +namespace +{ + + +using ground_triangles = std::vector; + +bool outside( glm::dvec3 const &Centre, double const Radius, glm::dvec2 const &Min, glm::dvec2 const &Max ) { + return Centre.x + Radius < Min.x || Centre.x - Radius > Max.x || Centre.z + Radius < Min.y || Centre.z - Radius > Max.y; +} + +} // namespace +namespace +{ + +void add_triangle( glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + if( std::max( { A.x, B.x, C.x } ) < Min.x || std::min( { A.x, B.x, C.x } ) > Max.x + || std::max( { A.z, B.z, C.z } ) < Min.y || std::min( { A.z, B.z, C.z } ) > Max.y ) { + return; + } + Out.push_back( { A, B, C } ); +} + +// the triangles of a piece of the scenery's geometry within the rectangle (x, z), as the editor gathers the ground +void add_shape( scene::shape_node const &Shape, glm::dvec2 const &Min, glm::dvec2 const &Max, ground_triangles &Out ) { + auto const &data { Shape.data() }; + if( data.area.radius >= 0.f && outside( data.area.center, data.area.radius, Min, Max ) ) { + return; + } + if( false == data.vertices.empty() ) { + for( std::size_t i = 0; i + 2 < data.vertices.size(); i += 3 ) { + add_triangle( data.vertices[ i ].position, data.vertices[ i + 1 ].position, data.vertices[ i + 2 ].position, Min, Max, Out ); + } + return; + } + // once the shape is uploaded its world-space source is released; the renderer keeps an origin-relative copy + if( data.geometry.bank == 0 && data.geometry.chunk == 0 ) { + return; + } + auto const &vertices { GfxRenderer->Vertices( data.geometry ) }; + auto const &indices { GfxRenderer->Indices( data.geometry ) }; + auto const point = [ &data, &vertices ]( std::size_t const Index ) { return data.origin + glm::dvec3 { vertices[ Index ].position }; }; + if( indices.empty() ) { + for( std::size_t i = 0; i + 2 < vertices.size(); i += 3 ) { + add_triangle( point( i ), point( i + 1 ), point( i + 2 ), Min, Max, Out ); + } + return; + } + for( std::size_t i = 0; i + 2 < indices.size(); i += 3 ) { + if( std::max( { indices[ i ], indices[ i + 1 ], indices[ i + 2 ] } ) >= vertices.size() ) { + continue; + } + add_triangle( point( indices[ i ] ), point( indices[ i + 1 ] ), point( indices[ i + 2 ] ), Min, Max, Out ); + } +} + +// the ground of the scenery within the rectangle (x, z): its terrain and the other opaque geometry of its sections, +// and the heightmap terrain where it is loaded. the models aren't ground +ground_triangles scenery_ground( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + ground_triangles triangles; + if( simulation::Region == nullptr ) { + return triangles; + } + auto const centre { 0.5 * ( Min + Max ) }; + std::vector sections; + simulation::Region->sections( glm::dvec3 { centre.x, 0.0, centre.y }, static_cast( 0.5 * glm::length( Max - Min ) ), sections ); + for( auto const *section : sections ) { + for( auto const &shape : section->m_shapes ) { + add_shape( shape, Min, Max, triangles ); + } + for( auto const &cell : section->m_cells ) { + if( outside( cell.m_area.center, cell.m_area.radius, Min, Max ) ) { + continue; + } + for( auto const &shape : cell.m_shapesopaque ) { + add_shape( shape, Min, Max, triangles ); + } + } + } + if( EditorTerrain.active() ) { + EditorTerrain.gather_triangles( Min, Max, triangles ); + } + return triangles; +} + +glm::dvec3 level_left_of( glm::dvec3 const &Front ) { + return glm::dvec3 { Front.z, 0.0, -Front.x }; +} + +// the end of the vehicle where it meets the one coupled to it: the middle of its buffer beam, the way it faces. off the +// track, over its base on the ground as it stands: rolled over, its ends go with it as far as the coupling holds them, +// and the buffers of the side it rolled to miss those of an upright one +derail_motion::end_point end_point_of( TDynamicObject const &Vehicle, VehicleEnd const End ) { + auto const facing { End == VehicleEnd::front ? 1.0 : -1.0 }; + auto const &motion { Vehicle.physics->OffTrack }; + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + auto const axis { length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 } }; + auto const middle { motion.active() ? motion.base() : Vehicle.GetPosition() }; + return derail_motion::end_point { + middle + glm::dvec3 { 0.0, derail_motion::buffer_height, 0.0 } + axis * ( facing * 0.5 * Vehicle.physics->Dim.L ), + axis * facing, + motion.active() ? motion.tipping() : 0.0 }; +} + +// the push of the buffers on the end of the vehicle [N], negative the pull of its coupling +double compression_of( physics::Vehicle const &Vehicle, VehicleEnd const End ) { + return ( End == VehicleEnd::front ? -1.0 : 1.0 ) * Vehicle.Couplers[ End ].CForce; +} + +} // namespace + +double vehicle_dynamic::seconds_since( off_track_clock::time_point const Start ) { + return std::chrono::duration( off_track_clock::now() - Start ).count(); +} +namespace +{ + +std::string_view side_name( int const Side ) { + if( Side > 0 ) { + return "left"; + } + return Side < 0 ? "right" : "none"; +} + +// the level unit vector the vehicle moves along with a positive V, its front +glm::dvec3 level_front_of( TDynamicObject const &Vehicle ) { + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + return length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; +} + +} // namespace + +void vehicle_dynamic::measure_off_track( neighbour_data &Neighbour, TDynamicObject const &Self, VehicleEnd const End ) { + auto const &other { *Neighbour.vehicle }; + auto const meeting { derail_motion::meet( end_point_of( Self, End ), end_point_of( other, Neighbour.FacingEnd() ) ) }; + // pressed into each other the buffers give along the bisector of the bend, apart the coupling between the beams + auto const direction { meeting.gap < 0.0 ? meeting.push : meeting.pull }; + Neighbour.distance = static_cast( meeting.gap ); + Neighbour.off_track = true; + Neighbour.own_share = -glm::dot( direction, level_front_of( Self ) ); + Neighbour.other_share = glm::dot( direction, level_front_of( other ) ); +} + +double TDynamicObject::off_track_gap( VehicleEnd const End ) const { + + auto const *neighbour { physics->Neighbours[ End ].vehicle }; + if( neighbour == nullptr ) { + return 0.0; + } + return derail_motion::meet( end_point_of( *this, End ), end_point_of( *neighbour, physics->Neighbours[ End ].FacingEnd() ) ).gap; +} + +double TDynamicObject::off_track_offset() const { + + if( false == physics->OffTrack.active() ) { + return 0.0; + } + auto const middle { 0.5 * ( Axle0.pPosition + Axle1.pPosition ) }; + auto const offset { vPosition - middle }; + return glm::dot( glm::dvec3 { offset.x, 0.0, offset.z }, level_left_of( track_front() ) ); +} + +glm::dvec3 TDynamicObject::track_front() const { + + auto const along { Axle0.pPosition - Axle1.pPosition }; + glm::dvec3 const flat { along.x, 0.0, along.z }; + auto const length { glm::length( flat ) }; + return length > 1e-6 ? flat / length : glm::dvec3 { 0.0, 0.0, 1.0 }; +} + +derail_motion::formation TDynamicObject::track_bed() const { + + derail_motion::formation bed; + bed.point = 0.5 * ( Axle0.pPosition + Axle1.pPosition ); + bed.direction = track_front(); + if( auto const *track { RaTrackGet() }; track != nullptr ) { + // the ballast out of the rails, as wide as the track draws it + bed.half_width = std::clamp( 0.5 * std::abs( track->fTrackWidth ) + std::abs( track->fTexWidth ), 1.2, 3.5 ); + } + return bed; +} + +int TDynamicObject::outward_side() const { + + // the track as designed turns from the rear axle to the front one: the outside of its curve, or its inside where a + // buckle bends the line the other way more than the curve does (the criteria of derailment, physics/derailment.h) + if( auto const design { std::sin( Axle1.vAngles.z - Axle0.vAngles.z ) }; std::abs( design ) >= 1e-4 ) { + auto const outside { design > 0.0 ? -1 : 1 }; + return physics->DerailAcceleration() < 0.0 ? -outside : outside; + } + // a straight track: the path under the vehicle as it is, a buckle on it, turns from the rear axle to the front one + auto const front { Axle0.PathDirection() }; + auto const rear { Axle1.PathDirection() }; + auto const turn { glm::dot( front, level_left_of( rear ) ) }; + // a turn under a tenth of a milliradian is a straight track + if( std::abs( turn ) < 1e-4 ) { + return 0; + } + // turning left, the outside of the curve is on the right + return turn > 0.0 ? -1 : 1; +} + +void TDynamicObject::gather_off_track_terrain() { + + auto const &position { physics->OffTrack.active() ? physics->OffTrack.current().position : vPosition }; + // as far as it may slide, and some + auto const slide { derail_motion::stopping_distance( physics->V(), derailment::off_rails_friction ).value_or( 0.0 ) }; + auto const reach { std::min( slide + physics->Dim.L + 50.0, 600.0 ) }; + m_offtrackgathered = m_offtracktotal; + m_offtrackcropped = false; + // the terrain of another vehicle, where it covers the way this one goes: around it and around where it stops going + // straight on, by its length and the margin the terrain is gathered again at + glm::dvec3 heading { vFront.x, 0.0, vFront.z }; + if( physics->OffTrack.active() ) { + heading = physics->OffTrack.heading(); + } + auto const length { glm::length( heading ) }; + auto const stop { length > 1e-6 ? position + heading * ( std::copysign( std::max( reach - physics->Dim.L - 50.0, 0.0 ), physics->V() ) / length ) : position }; + auto const margin { physics->Dim.L + 30.0 }; + if( auto shared { simulation::Vehicles.off_track_terrain( + glm::dvec2 { std::min( position.x, stop.x ) - margin, std::min( position.z, stop.z ) - margin }, + glm::dvec2 { std::max( position.x, stop.x ) + margin, std::max( position.z, stop.z ) + margin } ) }; + shared != nullptr ) { + m_offtrackterrain = std::move( shared ); + m_offtrackmin = m_offtrackterrain->minimum(); + m_offtrackmax = m_offtrackterrain->maximum(); + m_offtracksite.terrain( m_offtrackterrain.get() ); + return; + } + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + auto const started { off_track_clock::now() }; + auto triangles { scenery_ground( m_offtrackmin, m_offtrackmax ) }; + auto const trimmed { triangles.size() > off_track_triangles }; + if( trimmed ) { + // a scenery dense enough to make it slow: the triangles nearest to it are enough + std::nth_element( triangles.begin(), triangles.begin() + off_track_triangles, triangles.end(), + [ &position ]( auto const &Left, auto const &Right ) { + auto const distance = [ &position ]( auto const &Triangle ) { + auto const middle { ( Triangle[ 0 ] + Triangle[ 1 ] + Triangle[ 2 ] ) / 3.0 }; + return std::max( std::abs( middle.x - position.x ), std::abs( middle.z - position.z ) ); }; + return distance( Left ) < distance( Right ); } ); + triangles.resize( off_track_triangles ); + ErrorLog( std::format( "derailment: warning: {} found more than {} triangles of terrain around it, took the nearest", physics->Name, off_track_triangles ) ); + } + if( triangles.empty() ) { + // a scenery without terrain: level with the top of the ballast + m_offtrackterrain.reset(); + } + else { + m_offtrackterrain = std::make_shared( triangles, m_offtrackmin, m_offtrackmax ); + // the vehicles sliding over it take it as it is; the nearest triangles of a dense scenery are its own + if( false == trimmed ) { + simulation::Vehicles.share_off_track_terrain( m_offtrackterrain ); + } + } + m_offtracksite.terrain( m_offtrackterrain.get() ); + auto const took { vehicle_dynamic::seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: gathering the terrain of {:.0f} m around {} took {:.0f} ms ({} triangles)", reach, physics->Name, took * 1000.0, triangles.size() ) ); + } +} + +void TDynamicObject::crop_off_track_terrain() { + + if( m_offtrackcropped || m_offtrackterrain == nullptr ) { + return; + } + m_offtrackcropped = true; + // the ground under it, and as far around as it gathers the terrain anew once it moves again + auto const &position { physics->OffTrack.current().position }; + auto const reach { 0.5 * physics->Dim.L + 40.0 }; + m_offtrackmin = glm::dvec2 { position.x - reach, position.z - reach }; + m_offtrackmax = glm::dvec2 { position.x + reach, position.z + reach }; + m_offtrackterrain = std::make_shared( m_offtrackterrain->cropped( m_offtrackmin, m_offtrackmax ) ); + m_offtracksite.terrain( m_offtrackterrain.get() ); +} + +void TDynamicObject::begin_off_track() { + + derail_motion::vehicle_shape shape; + shape.length = physics->Dim.L; + shape.width = physics->Dim.W > 0.5 ? physics->Dim.W : 3.0; + // a height up to 2 m in the definition is the height of the floor, the older meaning of the key + shape.height = physics->Dim.H > 2.0 ? physics->Dim.H : 4.0; + shape.centre_of_gravity = physics->centre_of_gravity(); + shape.contact_spacing = derailment::contact_spacing( physics->TrackW ); + shape.base = std::max( static_cast( fAxleDist ), 1.0 ); + shape.mass = physics->TotalMass(); + + derail_motion::start start; + start.position = vPosition; + start.front = vFront; + start.line = track_front(); + start.speed = physics->V(); + start.reason = physics->DerailCause(); + start.outward = ( physics->DerailSide() != 0 ? physics->DerailSide() : outward_side() ); + start.acceleration = physics->DerailAcceleration(); + + // the terrain as far as it may slide, and some + m_offtracktotal = 0.0; + gather_off_track_terrain(); + m_offtracksite = derail_motion::site { m_offtrackterrain.get(), track_bed() }; + // each vehicle its own way of going off, from the seed of the run (the same seed, the same way) + auto const scatter { derail_motion::draw_scatter( derail_motion::seed_of( Global.random_seed, physics->Name ) ) }; + physics->OffTrack.begin( start, shape, m_offtracksite, scatter ); + m_pulledoff = {}; + m_offtracklogdue = 0.0; + m_offtrackslowdue = 0.0; + m_offtrackaxles = 0.0; + m_offtrackfrom = physics->OffTrack.current().position; + + auto const heading { physics->OffTrack.heading() }; + auto const front { glm::dvec3 { vFront.x, 0.0, vFront.z } }; + auto const turn { std::asin( std::clamp( glm::dot( heading, level_left_of( glm::normalize( front ) ) ), -1.0, 1.0 ) ) }; + std::string terrain { "no terrain, level ground" }; + if( m_offtrackterrain != nullptr ) { + terrain = std::format( "{} triangles of terrain", m_offtrackterrain->size() ); + } + WriteLog( std::format( + "derailment: {} leaves the track at {:.0f} km/h on track {}, heading turned {:.1f} deg to the {}, the outside of the curve to the {}; {} around it", + physics->Name, std::abs( physics->V() ) * 3.6, MyTrack != nullptr ? MyTrack->name() : std::string { "(none)" }, + std::abs( glm::degrees( turn ) ), side_name( turn >= 0.0 ? 1 : -1 ), side_name( start.outward ), terrain ) ); + WriteLog( std::format( + "derailment: {} scattered by {:+.2f} deg of departure, {:+.2f} deg of yaw at {:+.3f} rad/s, the friction under its ends x{:.2f} / x{:.2f}{}", + physics->Name, glm::degrees( scatter.departure ), glm::degrees( scatter.yaw ), scatter.yaw_rate, scatter.friction_front, scatter.friction_rear, + scatter.dig_in >= 0.0 ? std::format( ", its leading end digs in after {:.2f} s, x{:.2f} for {:.2f} s", scatter.dig_in, scatter.dig_in_friction, scatter.dig_in_time ) : std::string {} ) ); +} + +void TDynamicObject::move_off_track( double const Distance ) { + + auto const started { off_track_clock::now() }; + auto &motion { physics->OffTrack }; + auto const time { std::exchange( m_offtracktime, 0.0 ) }; + m_offtracktotal += time; + // near the edge of the terrain gathered, the terrain further on; not more than once a second, whatever happens + if( m_offtrackterrain != nullptr && Distance != 0.0 && m_offtracktotal - m_offtrackgathered >= 1.0 ) { + auto const &position { motion.current().position }; + constexpr double margin { 30.0 }; + if( position.x - margin < m_offtrackmin.x || position.x + margin > m_offtrackmax.x + || position.z - margin < m_offtrackmin.y || position.z + margin > m_offtrackmax.y ) { + gather_off_track_terrain(); + } + } + m_offtracksite.bed( track_bed() ); + // the buffers and the couplings of its ends push and pull it, at an angle to it where the vehicle coupled there is + std::array ends {}; + for (auto const end : VehicleEnds) { + auto const *neighbour { physics->Neighbours[ end ].vehicle }; + auto const compression { compression_of( *physics, end ) }; + if( neighbour == nullptr || compression == 0.0 ) { + continue; + } + ends[ NumberOf( end ) ] = derail_motion::force_on( + derail_motion::meet( end_point_of( *this, end ), end_point_of( *neighbour, physics->Neighbours[ end ].FacingEnd() ) ), compression ); + } + auto const reversals { motion.reversals() }; + motion.step( time, Distance, physics->V(), m_offtracksite, ends ); + if( ( motion.reversals() - reversals ) % 2 != 0 ) { + // the body turned about against the way it goes: the vehicle goes rear first, its speed the other way along it + physics->SetV(-physics->V()); + } + auto const &pose { motion.current() }; + // the axles go along the track as far as the vehicle went along it, for the track nearest to it: the vehicles on it + // find it there, the events of the track are passed. by 10 cm at least: a body turning or rocking in place moves + // the axles back and forth by millimetres, which over the end of a track would fire its events every frame. from + // where it was the last time, so the moves out of the other bodies between the frames go into the axles too + m_offtrackaxles += glm::dot( pose.position - std::exchange( m_offtrackfrom, pose.position ), track_front() ); + if( std::abs( m_offtrackaxles ) >= 0.1 ) { + move_axles( std::exchange( m_offtrackaxles, 0.0 ) ); + } + + place_off_track(); + if( motion.at_rest() ) { + crop_off_track_terrain(); + } + + pull_neighbours( time ); + + // what it cost: a frame of the vehicle off the track should take well under a millisecond + auto const took { vehicle_dynamic::seconds_since( started ) }; + m_offtrackslowdue -= time; + if( took > off_track_slow && m_offtrackslowdue <= 0.0 ) { + m_offtrackslowdue = 1.0; + ErrorLog( std::format( "derailment: warning: moving {} off the track took {:.0f} ms in a frame of {:.3f} s", physics->Name, took * 1000.0, time ) ); + } +} + +void TDynamicObject::place_off_track() { + + auto const &pose { physics->OffTrack.current() }; + vPosition = pose.position; + vFront = pose.front; + vLeft = pose.left; + vUp = pose.up; + modelRot.z = std::atan2( -vFront.x, vFront.z ); + mMatrix = glm::inverse( BasisChange( vLeft, vUp, vFront ) ); + auto const half { 0.5 * physics->Dim.L * vFront }; + vCoulpler[ VehicleEnd::front ] = vPosition + half; + vCoulpler[ VehicleEnd::rear ] = vPosition - half; + m_offtrackplaced = true; +} + +void TDynamicObject::pull_neighbours( double const Time ) { + + for (auto const end : VehicleEnds) { + auto const &coupler { physics->Couplers[ end ] }; + auto *neighbour { physics->Neighbours[ end ].vehicle }; + if( coupler.CouplingFlag == Coupling::none || neighbour == nullptr || neighbour->physics->OffTrack.active() + || neighbour->physics->DamageFlag.HasAll(VehicleDamage::derailed) ) { + m_pulledoff[ end ].reset(); + continue; + } + auto &other { *neighbour->physics }; + auto const otherend { physics->Neighbours[ end ].FacingEnd() }; + glm::dvec3 const otherfront { neighbour->vFront.x, 0.0, neighbour->vFront.z }; + if( glm::length( otherfront ) < 1e-6 ) { + continue; + } + // the coupling pulls the end of the other vehicle towards the beam of this one, the buffers push it along the + // bisector of the bend between them: at an angle to its axis, the part across it on its leading wheels + auto const compression { compression_of( other, otherend ) }; + auto const force { derail_motion::force_on( derail_motion::meet( end_point_of( *neighbour, otherend ), end_point_of( *this, end ) ), compression ).force }; + auto const axis { glm::normalize( otherfront ) }; + auto const across { glm::dot( force, level_left_of( axis ) ) }; + auto const angle { std::atan2( std::abs( across ), std::abs( glm::dot( force, axis ) ) ) }; + auto const magnitude { glm::length( glm::dvec3 { force.x, 0.0, force.z } ) }; + auto const mass { other.TotalMass() - other.Mred() }; + auto const ratio { derail_motion::pull_ratio( magnitude, angle, mass, other.NAxles() ) }; + // the flange climbs the rail over the distance the wheels of the vehicle pulled run along it, whatever this one + // does: lying at rest beside the track, it went on pulling the vehicle running past it, which then never got + // the distance the climb takes + if( false == m_pulledoff[ end ].update( ratio >= derailment::climbing_limit, std::abs( other.V() ) * Time ) ) { + continue; + } + // the way the force across it goes: towards this one pulled, away from it pushed + auto const side { across >= 0.0 ? 1 : -1 }; + other.pull_off( + side, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from the {} of {} at {:.0f} deg, {:.0f} kN", ratio, compression > 0.0 ? "buffers" : "coupling", physics->Name, glm::degrees( angle ), magnitude / 1000.0 ) ); + m_pulledoff[ end ].reset(); + } +} + +void TDynamicObject::update_off_track( double const Deltatime ) { + + auto const &motion { physics->OffTrack }; + if( false == motion.active() || m_offtracklogdue < 0.0 ) { + // on the track, or came to rest and told so + return; + } + m_offtracklogdue -= Deltatime; + auto const resting { motion.at_rest() }; + if( m_offtracklogdue > 0.0 && false == resting ) { + return; + } + m_offtracklogdue = ( resting ? -1.0 : 1.0 ); + WriteLog( std::format( + "derailment: {} {} {:.1f} m from where it left the rails, {:.1f} m from the axis of the track, at {:.1f} km/h, sliding sideways at {:.1f} m/s, tipped {:.0f} deg, roll {:.0f} deg, yaw {:+.1f} deg turning at {:+.1f} deg/s{}", + physics->Name, resting ? "came to rest" : "off the track", motion.travelled(), off_track_offset(), std::abs( physics->V() ) * 3.6, motion.sideways(), + glm::degrees( motion.tipping() ), glm::degrees( motion.roll() ), glm::degrees( motion.yaw() ), glm::degrees( motion.yaw_rate() ), motion.lying() ? ", lying on its side" : "" ) ); +} diff --git a/vehicle/dynamic/sounds.cpp b/vehicle/dynamic/sounds.cpp new file mode 100644 index 000000000..94786d822 --- /dev/null +++ b/vehicle/dynamic/sounds.cpp @@ -0,0 +1,1622 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the sounds of a vehicle + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +// przeliczanie dźwięków, bo będzie słychać bez wyświetlania sektora z pojazdem +void TDynamicObject::RenderSounds() { + + if( false == simulation::is_ready ) { return; } + if( Global.iPause != 0 ) { return; } + + if( m_startjoltplayed + && ( std::abs(physics->AccSVBased()) < 0.01 + || GetVelocity() < 0.01 ) ) { + // if the vehicle comes to a stop set the movement jolt to play when it starts moving again + m_startjoltplayed = false; + } + + auto const dt{ Timer::GetDeltaRenderTime() }; + m_powertrainsounds.render( *physics, dt ); + + renderAuxiliarySounds(); + + // brake system and braking sounds: + + // brake cylinder piston + auto const brakepressureratio { std::max( 0.0, physics->brakes.cylinderPressure ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[ 3 ] ) }; + renderBrakeCylinderSounds( brakepressureratio ); + renderEpBrakeSounds( dt ); + renderEmergencyBrakeSound(); + renderAirReleaseSounds( dt, brakepressureratio ); + renderSlipAndSandSounds(); + auto const brakeforceratio { renderBrakeFrictionSounds( dt ) }; + renderSpringBrakeSounds(); + + // other sounds + renderLoadExchangeSounds(); + renderDepartureSignalSounds(); + renderAnnouncementSounds(); + renderDoorSounds(); + renderHornSounds(); + renderRunningNoise( brakeforceratio ); + renderWheelFlatSound(); + renderCurveSound(); + renderStartJoltSound(); + + // McZapkie! - to wazne - SoundFlag wystawiane jest przez moje moduly gdy zachodza pewne wydarzenia komentowane dzwiekiem. + renderPhysicsEventSounds(); + renderCouplerSounds(); + + physics->ClearSoundFlags(); + // McZapkie! - koniec obslugi dzwiekow z physics.pas + + renderDerailmentSounds(); +} + +// the sounds of the converter, the braking resistor fans, the compressors, the heater and the battery +void TDynamicObject::renderAuxiliarySounds() { + + auto frequency{ 1.0 }; + + // NBMX dzwiek przetwornicy + if( physics->converter.IsRunning() ) { + if( physics->EngineType == TEngineType::ElectricSeriesMotor ) { + auto const voltage { std::max( physics->GetTrainsetHighVoltage(), physics->pantographCircuit.SupplyVoltage() ) }; + if( voltage > 0.0 ) { + // NOTE: we do sound modulation here to avoid sudden jump on voltage loss + frequency = voltage / (physics->NominalVoltage * physics->RList[physics->RlistSize].Mn); + frequency *= sConverter.m_frequencyfactor + sConverter.m_frequencyoffset; + sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) + } + } + else { + frequency = sConverter.m_frequencyoffset + sConverter.m_frequencyfactor * frequency; + sConverter.pitch( std::clamp( frequency, 0.75, 1.25 ) ); // arbitrary limits ) + } + sConverter.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sConverter.stop(); + } + + // Odtworzenie dzwieku wentylatora rezystora hamowania + + if (physics->brakes.electrodynamic.resistorFansRunning) + { + sBRVent.play(sound_flags::exclusive | sound_flags::looping); + } + else + { + sBRVent.stop(); + } + + + + + + if( physics->air.compressor.config.speed > 0.0 ) { + // McZapkie! - dzwiek compressor.wav tylko gdy dziala sprezarka + if( physics->air.compressor.IsRunning() ) { + // for compressor coupled with the diesel engine sound pitch is driven by engine revolutions + if( physics->air.compressor.config.supply == physics::CompressorSupply::engine ) { + // presume the compressor sound is recorded for idle revolutions + // increase the pitch according to increase of engine revolutions + auto const enginefactor { + std::clamp( // try to keep the sound pitch in semi-reasonable range + physics->EngineMaxRPM() / physics->EngineIdleRPM() * physics->EngineRPMRatio(), + 0.5, 2.5 ) }; + sCompressor.pitch( enginefactor ); + sCompressorIdle.pitch( enginefactor ); + } + if( sCompressorIdle.empty() ) { + // legacy sound path, if there's no dedicated idle sound + sCompressor.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // enhanced sound path, with dedicated sound for idling compressor + if( physics->air.compressor.IsGovernorLocked() ) { + sCompressor.stop(); + sCompressorIdle.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sCompressor.play( sound_flags::exclusive | sound_flags::looping ); + sCompressorIdle.stop(); + } + } + } + else { + sCompressor.stop(); + sCompressorIdle.stop(); + } + } + + // Winger 160404 - dzwiek malej sprezarki + if( physics->pantographAir.IsCompressorRunning() ) { + sSmallCompressor.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sSmallCompressor.stop(); + } + + // heater sound + { + auto const isdieselenginepowered { physics->EngineType == TEngineType::DieselElectric || physics->EngineType == TEngineType::DieselEngine }; + if( true == physics->trainHeating.IsOn() + && ( false == isdieselenginepowered + || std::abs(physics->enrot) > 0.01 ) ) { + sHeater + .pitch( true == sHeater.is_combined() ? + std::abs( physics->enrot ) * 60.f * 0.01f : + 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHeater.stop(); + } + } + + // battery sound + if( physics->lowVoltage.IsBatteryOn() ) { + m_batterysound.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + m_batterysound.stop(); + } +} + +// the sounds of the brake cylinder piston as the pressure in the cylinder rises or falls +void TDynamicObject::renderBrakeCylinderSounds( double const brakepressureratio ) { + + if( m_lastbrakepressure != -1.f ) { + // HACK: potentially reset playback of opening bookend sounds + if( false == m_brakecylinderpistonadvance.is_playing() ) { + m_brakecylinderpistonadvance.stop(); + } + if( false == m_brakecylinderpistonrecede.is_playing() ) { + m_brakecylinderpistonrecede.stop(); + } + // actual sound playback + auto const quantizedratio { static_cast( 15 * brakepressureratio ) }; + auto const lastbrakepressureratio { std::max( 0.f, m_lastbrakepressure ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[ 3 ] ) }; + auto const quantizedratiochange { quantizedratio - static_cast( 15 * lastbrakepressureratio ) }; + if( quantizedratiochange > 0 ) { + m_brakecylinderpistonadvance + .pitch( + true == m_brakecylinderpistonadvance.is_combined() ? + quantizedratio * 0.01f : + m_brakecylinderpistonadvance.m_frequencyoffset + m_brakecylinderpistonadvance.m_frequencyfactor * 1.f ) + .play(); + } + else if( quantizedratiochange < 0 ) { + m_brakecylinderpistonrecede + .pitch( true == m_brakecylinderpistonrecede.is_combined() ? + quantizedratio * 0.01f : + m_brakecylinderpistonrecede.m_frequencyoffset + m_brakecylinderpistonrecede.m_frequencyfactor * 1.f ) + .play(); + } + } +} + +// the sounds of the electro-pneumatic brake as its pressure rises or falls +void TDynamicObject::renderEpBrakeSounds( double const dt ) { + + // epbrake - epcompact + if (physics->brakes.config.kind == TBrakeSystem::ElectroPneumatic && physics->brakes.independentValve) { + auto const epbrakepressureratio{ std::min( std::max( 0.0, physics->brakes.independentValve->GetCP() ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ), + m_epbrakepressurechangedectimer > -1.0f ? + std::max( physics->brakes.IndependentPositionEim(), physics->brakes.distributor->GetEDBCP() / physics->brakes.config.maxCylinderPressure[3]) : + 1.0 ) }; + if ( m_lastepbrakepressure != -1.f ) { + // HACK: potentially reset playback of opening bookend sounds + if ( false == m_epbrakepressureincrease.is_playing() ) { + m_epbrakepressureincrease.stop(); + } + if ( false == m_epbrakepressuredecrease.is_playing() ) { + m_epbrakepressuredecrease.stop(); + } + m_epbrakepressurechangeinctimer += dt; + m_epbrakepressurechangedectimer += dt; + // actual sound playback + auto const epquantizedratio{ static_cast( 50 * epbrakepressureratio) }; + auto const lastepbrakepressureratio { std::max( 0.f, m_lastepbrakepressure ) / std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ) }; + auto const epquantizedratiochange { epquantizedratio - static_cast( 50 * lastepbrakepressureratio ) }; + if ( epquantizedratiochange > 0 && m_epbrakepressurechangeinctimer > 0.05f) { + m_epbrakepressureincrease + .pitch( + true == m_epbrakepressureincrease.is_combined() ? + epquantizedratio * 0.01f : + m_epbrakepressureincrease.m_frequencyoffset + m_epbrakepressureincrease.m_frequencyfactor * 1.f ) + .play(); + m_epbrakepressurechangeinctimer = 0; + } + else if ( epquantizedratiochange < 0 && m_epbrakepressurechangedectimer > 0.3f) { + m_epbrakepressuredecrease + .pitch(true == m_epbrakepressuredecrease.is_combined() ? + -epquantizedratiochange * 0.01f : + m_epbrakepressuredecrease.m_frequencyoffset + m_epbrakepressuredecrease.m_frequencyfactor * 1.f ) + .play(); + m_epbrakepressurechangedectimer = 0; + } + } + if ( m_epbrakepressurechangeinctimer == 0 || m_epbrakepressurechangedectimer == 0 ) + m_lastepbrakepressure = std::min( physics->brakes.independentValve->GetCP(), + physics->brakes.IndependentPositionEim() * std::max( 1.0, physics->brakes.config.maxCylinderPressure[0] ) ); + } +} + +// the sound of the air flowing out through the emergency brake valve +void TDynamicObject::renderEmergencyBrakeSound() { + + // emergency brake + if( physics->brakes.emergencyValve.flow > 0.025 ) { + // smooth out air flow rate + m_emergencybrakeflow = m_emergencybrakeflow == 0.0 ? physics->brakes.emergencyValve.flow : std::lerp(m_emergencybrakeflow, physics->brakes.emergencyValve.flow, 0.1); + // scale volume based on the flow rate and on the pressure in the main pipe + auto const flowpressure { std::clamp( m_emergencybrakeflow, 0.0, 1.0 ) + std::clamp( 0.1 * physics->brakePipe.Pressure(), 0.0, 0.5 ) }; + m_emergencybrake + .pitch( m_emergencybrake.m_frequencyoffset + 1.0 * m_emergencybrake.m_frequencyfactor ) + .gain( m_emergencybrake.m_amplitudeoffset + std::clamp( flowpressure, 0.0, 1.0 ) * m_emergencybrake.m_amplitudefactor ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else if( physics->brakes.emergencyValve.flow < 0.015 ) { + m_emergencybrakeflow = 0.0; + m_emergencybrake.stop(); + } +} + +// the sounds of the air released from the brake cylinder and of the releaser +void TDynamicObject::renderAirReleaseSounds( double const dt, double const brakepressureratio ) { + + auto volume{ 0.0 }; + + // air release + if( m_lastbrakepressure != -1.f ) { + // calculate rate of pressure drop in brake cylinder, once it's been initialized + auto const brakepressuredifference{ m_lastbrakepressure - physics->brakes.cylinderPressure }; + m_brakepressurechange = std::lerp( m_brakepressurechange, brakepressuredifference / dt, 0.05f ); + } + m_lastbrakepressure = physics->brakes.cylinderPressure; + // ensure some basic level of volume and scale it up depending on pressure in the cylinder; scale this by the air release rate + volume = rsUnbrake.m_amplitudefactor * m_brakepressurechange * ( 0.25 + 0.75 * brakepressureratio ); + if( m_brakepressurechange > 0.05 && brakepressureratio > 0.05 ) { + rsUnbrake + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // don't stop the sound too abruptly + volume = std::max( 0.0, rsUnbrake.gain() - 0.5 * dt ); + rsUnbrake.gain( volume ); + if( volume < 0.05 ) { + rsUnbrake.stop(); + } + } + + // Dzwiek odluzniacza + if( physics->brakes.distributor->Releaser() ) { + sReleaser + .gain( + std::clamp( + physics->brakes.cylinderPressure * 1.25, // arbitrary multiplier + 0., 1. ) ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sReleaser.stop(); + } +} + +// the sounds of the slipping wheels and of the sander +void TDynamicObject::renderSlipAndSandSounds() { + + // slipping wheels + if( physics->SlippingWheels() ) { + + if( physics->brakes.unitForce > 100.0 + && GetVelocity() > 1.0 ) { + + auto const velocitydifference{ GetVelocity() / physics->Vmax() }; + rsSlippery + .gain( rsSlippery.m_amplitudeoffset + rsSlippery.m_amplitudefactor * velocitydifference ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + rsSlippery.stop(); + } + + // Dzwiek piasecznicy + if( physics->SandDose() ) { + sSand.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sSand.stop(); + } +} + +// the sounds of the brake shoes, of the brake accelerator and the squeal of tight brakes; returns the brake force ratio +double TDynamicObject::renderBrakeFrictionSounds( double const dt ) { + + auto volume{ 0.0 }; + + // brakes + auto brakeforceratio{ 0.0 }; + if( //( false == occupied->SlippingWheels() ) && + physics->brakes.unitForce > 10.0 + && physics->Vel > 0.05 ) { + + brakeforceratio = + std::clamp( + physics->brakes.unitForce / std::max( 1.0, physics->BrakeForceR( 1.0, physics->Vel ) / ( physics->NAxles() * std::max( 1, physics->brakes.config.blocksPerAxle ) ) ), + 0.0, 1.0 ); + rsBrake + .pitch( rsBrake.m_frequencyoffset + physics->Vel * rsBrake.m_frequencyfactor ) + .gain( rsBrake.m_amplitudeoffset + std::sqrt( brakeforceratio * std::lerp( 0.4, 1.0, physics->Vel / (1 + physics->Vmax()) ) ) * rsBrake.m_amplitudefactor ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + rsBrake.stop(); + } + + // yB: przyspieszacz (moze zadziala, ale dzwiek juz jest) + if( true == bBrakeAcc ) { + if( true == TestFlag( physics->brakes.distributor->GetSoundFlag(), sf_Acc ) ) { + sBrakeAcc.play( sound_flags::exclusive ); + } + } + + // McZapkie-280302 - pisk mocno zacisnietych hamulcow + if( physics->Vel > 2.5 ) { + + volume = rsPisk.m_amplitudeoffset + std::lerp( -1.0, 1.0, brakeforceratio ) * rsPisk.m_amplitudefactor; + if( volume > 0.075 ) { + rsPisk + .pitch( + true == rsPisk.is_combined() ? + physics->Vel * 0.01f : + rsPisk.m_frequencyoffset + rsPisk.m_frequencyfactor * 1.f ) + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + // don't stop the sound too abruptly + volume = std::max( 0.0, rsPisk.gain() - rsPisk.gain() * 2.5 * dt ); + rsPisk.gain( volume ); + } + if( volume < 0.05 ) { + rsPisk.stop(); + } + + return brakeforceratio; +} + +// the sounds of the spring brake being activated or released +void TDynamicObject::renderSpringBrakeSounds() { + + // spring brake + if( m_springbrakesounds.state != physics->brakes.spring.activate ) { + m_springbrakesounds.state = physics->brakes.spring.activate; + if( m_springbrakesounds.state ) { + m_springbrakesounds.activate.play( sound_flags::exclusive ); + m_springbrakesounds.release.stop(); + } + else { + m_springbrakesounds.activate.stop(); + m_springbrakesounds.release.play( sound_flags::exclusive ); + } + } +} + +// the sounds of the load being loaded or unloaded +void TDynamicObject::renderLoadExchangeSounds() { + + // load exchange + if( physics->LoadStatus() & 1 ) { + m_exchangesounds.unloading.play( sound_flags::exclusive ); + } + else { + m_exchangesounds.unloading.stop(); + } + if( physics->LoadStatus() & 2 ) { + m_exchangesounds.loading.play( sound_flags::exclusive ); + } + else { + m_exchangesounds.loading.stop(); + } +} + +// the departure signal of the door speakers +void TDynamicObject::renderDepartureSignalSounds() { + + // NBMX sygnal odjazdu + if( physics->Doors.has_warning ) { + auto const lowvoltagepower { physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() }; + for( auto &doorspeaker : m_doorspeakers ) { + // TBD, TODO: per-location door state triggers? + if( physics->DepartureSignal() + && lowvoltagepower +/* + || ( ( physics->DoorCloseCtrl = control::autonomous ) + && ( ( ( false == physics->DoorLeftOpened ) && ( dDoorMoveL > 0.0 ) ) + || ( ( false == physics->DoorRightOpened ) && ( dDoorMoveR > 0.0 ) ) ) ) +*/ + ) { + // for the autonomous doors play the warning automatically whenever a door is closing + // MC: pod warunkiem ze jest zdefiniowane w chk + doorspeaker.departure_signal.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + doorspeaker.departure_signal.stop(); + } + } + } +} + +// the queued announcements of the passenger information system +void TDynamicObject::renderAnnouncementSounds() { + + // announcements + { + auto const lowvoltagepower { physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() }; + if( lowvoltagepower ) { + // system is powered up, can play queued announcements + if( false == m_pasystem.announcement_queue.empty() + && false == m_pasystem.announcement.is_playing() ) { + // pull first sound from the queue + m_pasystem.announcement = m_pasystem.announcement_queue.front(); + m_pasystem.announcement.owner( this ); + m_pasystem.announcement.range( 0.5 * physics->Dim.L * -1 ); + if( m_pasystem.soundproofing ) { + if( !m_pasystem.announcement.soundproofing() ) { + m_pasystem.announcement.soundproofing() = m_pasystem.soundproofing; + } + } + m_pasystem.announcement.play(); + m_pasystem.announcement_queue.pop_front(); + } + } + else { + m_pasystem.announcement.stop(); + m_pasystem.announcement_queue.clear(); + } + } +} + +// the sounds of the doors, the doorsteps and the door locks +void TDynamicObject::renderDoorSounds() { + + // NBMX Obsluga drzwi, MC: zuniwersalnione + auto const &sides { VehicleSides }; + for( auto const side : sides ) { + + auto const &door { physics->Doors.instances[ side ] }; + + if( true == door.is_opening ) { + // door sounds + if( false == door.step_unfolding // no wait if no doorstep + || physics->Doors.step_type == 2 ) { // no wait for rotating doorstep + if( door.position < 0.5f ) { // safety measure, to keep slightly too short sounds from repeating + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + // determine left side doors from their offset + doorsounds.rsDoorOpen.play( sound_flags::exclusive ); + doorsounds.rsDoorClose.stop(); + } + } + } + } + } + if( true == door.is_closing ) { + // door sounds can start playing before the door begins moving but shouldn't cease once the door closes + if( door.position > 0.f ) { + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + // determine left side doors from their offset + doorsounds.rsDoorClose.play( sound_flags::exclusive ); + doorsounds.rsDoorOpen.stop(); + } + } + } + } + // doorstep sounds + if( door.step_unfolding ) { + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + doorsounds.step_open.play( sound_flags::exclusive ); + doorsounds.step_close.stop(); + } + } + } + if( door.step_folding ) { + if( door.step_position < 1.0f ) { // sanity check, the vehicles may keep the doorstep unfolded until the door close + for( auto &doorsounds : m_doorsounds ) { + if( doorsounds.placement == side ) { + // determine left side doors from their offset + doorsounds.step_close.play( sound_flags::exclusive ); + doorsounds.step_open.stop(); + } + } + } + } + } + // door locks + if( physics->Doors.is_locked != m_doorlocks ) { + // toggle state of the locks... + m_doorlocks = !m_doorlocks; + // ...and play relevant sounds + for( auto &door : m_doorsounds ) { + if( m_doorlocks ) { + door.lock.play( sound_flags::exclusive ); + } + else { + door.unlock.play( sound_flags::exclusive ); + } + } + } +} + +// the sounds of the horns +void TDynamicObject::renderHornSounds() { + + // horns + { + // for moving vehicle combine regular horn activation flag with emergency brake horn activation flag, if the brake is active; + // the horns without the air or the voltage they need stay silent + auto const warningsignal { physics->SoundingHorns( + ( physics->Vel > 0.5 && physics->brakes.alarmChain ? + physics->EmergencyBrakeWarningSignal : + 0 ) + | physics->WarningSignal() ) }; + + if( TestFlag( warningsignal, 1 ) ) { + sHorn1.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHorn1.stop(); + } + if( TestFlag( warningsignal, 2 ) ) { + sHorn2.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHorn2.stop(); + } + if( TestFlag( warningsignal, 4 ) ) { + sHorn3.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + sHorn3.stop(); + } + } +} + +// the outer noise of the running vehicle, louder with the brakes applied by brakeforceratio +void TDynamicObject::renderRunningNoise( double const brakeforceratio ) { + + auto volume{ 0.0 }; + auto frequency{ 1.0 }; + + // szum w czasie jazdy + if( GetVelocity() > 0.5 +#ifdef EU07_SOUND_BOGIESOUNDS + && false == m_bogiesounds.empty() +#endif + && ( // compound test whether the vehicle belongs to user-driven consist (as these don't emit outer noise in cab view) + FreeFlyModeFlag ? true : // in external view all vehicles emit outer noise + simulation::Train == nullptr ? true : // no player train, e.g. it went through a portal and the view isn't switched yet + ctOwner == nullptr ? true : // standalone vehicle, can't be part of user-driven train + ctOwner != simulation::Train->Dynamic()->ctOwner ? true : // confirmed isn't a part of the user-driven train + Global.CabWindowOpen ? true : // sticking head out we get to hear outer noise + false ) ) { +#ifdef EU07_SOUND_BOGIESOUNDS + auto const &bogiesound { m_bogiesounds.front() }; +#else + auto const &bogiesound { m_outernoise }; +#endif + // frequency calculation + auto const normalizer { ( + true == bogiesound.is_combined() ? + physics->Vmax() * 0.01f : + 1.f ) }; + frequency = + bogiesound.m_frequencyoffset + + bogiesound.m_frequencyfactor * physics->Vel * normalizer; + + // volume calculation + volume = + bogiesound.m_amplitudeoffset + + bogiesound.m_amplitudefactor * physics->Vel; + if( brakeforceratio > 0.0 ) { + // hamulce wzmagaja halas + volume *= 1 + 0.125 * brakeforceratio; + } + // scale volume by track quality + // TODO: track quality and/or environment factors as separate subroutine + volume *= + std::lerp( + 0.8, 1.2, + std::clamp( + MyTrack->iQualityFlag / 20.0, + 0.0, 1.0 ) ); + // for single sample sounds muffle the playback at low speeds + if( false == bogiesound.is_combined() ) { + volume *= + std::lerp( + 0.0, 1.0, + std::clamp( + physics->Vel / 40.0, + 0.0, 1.0 ) ); + } + switch( MyTrack->eEnvironment ) { + case e_tunnel: { + volume *= 1.3; + break; + } + case e_bridge: { + volume *= 1.5; + break; + } + default: { + break; + } + } + + if( volume > 0.05 ) { + // apply calculated parameters to all motor instances +#ifdef EU07_SOUND_BOGIESOUNDS + for( auto &bogiesound : m_bogiesounds ) { + bogiesound + .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } +#else + m_outernoise + .pitch( frequency ) // arbitrary limits to prevent the pitch going out of whack + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); +#endif + } + else { + // stop all noise instances +#ifdef EU07_SOUND_BOGIESOUNDS + for( auto &bogiesound : m_bogiesounds ) { + bogiesound.stop(); + } +#else + m_outernoise.stop(); +#endif + } + } + else { + // don't play the optional ending sound if the listener switches views +#ifdef EU07_SOUND_BOGIESOUNDS + for( auto &bogiesound : m_bogiesounds ) { + bogiesound.stop( false == FreeFlyModeFlag ); + } +#else + m_outernoise.stop( false == FreeFlyModeFlag ); +#endif + } +} + +// the sound of the flat spots on the wheels +void TDynamicObject::renderWheelFlatSound() { + + // flat spot sound + if( physics->CategoryFlag == 1 ) { + // trains only + if( GetVelocity() > 1.0 + && physics->WheelFlat() > 5.0 ) { + m_wheelflat + .pitch( m_wheelflat.m_frequencyoffset + std::abs( physics->nrot() ) * m_wheelflat.m_frequencyfactor ) + .gain( m_wheelflat.m_amplitudeoffset + m_wheelflat.m_amplitudefactor * ( ( 1.0 + physics->Vel / physics->Vmax() + std::clamp( physics->WheelFlat() / 60.0, 0.0, 1.0 ) ) / 3.0 ) ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + m_wheelflat.stop(); + } + } +} + +// the squeal of the wheels in sharp curves and on switches +void TDynamicObject::renderCurveSound() { + + auto volume{ 0.0 }; + + // youBy: dzwiek ostrych lukow i ciasnych zwrotek + if( physics->Vel > 5.0 + && ts.R * ts.R > 1.0 + && std::abs(ts.R) < 15000.0 ) { + // scale volume with curve radius and vehicle speed + volume = + std::abs( physics->AccN() ) // * physics->AccN() + * std::lerp( + 0.5, 1.0, + std::clamp( + physics->Vel / 40.0, + 0.0, 1.0 ) ) + * ( MyTrack->eType == tt_Switch && std::abs(ts.R) < 1500.0 ? 100.0 : 1.0 ); + } + else { + volume = 0; + } + if( volume > 0.05 ) { + rscurve + .pitch( + true == rscurve.is_combined() ? + physics->Vel * 0.01f : + rscurve.m_frequencyoffset + rscurve.m_frequencyfactor * 1.f ) + .gain( 2.5 * volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + rscurve.stop(); + } +} + +// the jolt of the vehicle starting to move +void TDynamicObject::renderStartJoltSound() { + + // movement start jolt + if( false == m_startjoltplayed ) { + auto const velocity { GetVelocity() }; + if( ( physics->V() > 0.0 ? physics->AccSVBased() > 0.1 : physics->AccSVBased() < 0.1 ) + && velocity > 1.0 + && velocity < 15.0 ) { + m_startjolt.play( sound_flags::exclusive ); + m_startjoltplayed = true; + } + } +} + +// the sounds of the pneumatic relay and of the door permit, set in the sound flags of the physics +void TDynamicObject::renderPhysicsEventSounds() { + + // pneumatic relay + if( TestFlag( physics->SoundFlag(), sound::pneumatic ) ) { + dsbPneumaticRelay + .gain( + true == TestFlag( physics->SoundFlag(), sound::loud ) ? + 1.0f : + 0.8f ) + .play(); + } + // door permit + if( TestFlag( physics->SoundFlag(), sound::doorpermit ) ) { + // NOTE: current implementation doesn't discern between permit for left/right side, + // which may be undesired in weird setups with doors only on one side + // TBD, TODO: rework into dedicated sound event flag for each door location instance? + for( auto &door : m_doorsounds ) { + door.permit_granted.play( sound_flags::exclusive ); + } + } +} + +// the sounds of the buffers, of the couplers stretching and of the couplings attached or detached, and clears their sound flags +void TDynamicObject::renderCouplerSounds() { + + // couplers + int couplerindex { 0 }; + for( auto &couplersounds : m_couplersounds ) { + + auto &coupler { physics->Couplers[ couplerindex ] }; + + if( coupler.sounds == sound::none ) { + ++couplerindex; + continue; + } + + if( true == TestFlag( coupler.sounds, sound::bufferclash ) ) { + // zderzaki uderzaja o siebie + if( true == TestFlag( coupler.sounds, sound::loud ) ) { + // loud clash + if( false == couplersounds.dsbBufferClamp_loud.empty() ) { + // dedicated sound for loud clash + couplersounds.dsbBufferClamp_loud + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + else { + // fallback on the standard sound + couplersounds.dsbBufferClamp + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + else { + // basic clash + couplersounds.dsbBufferClamp + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + + if( true == TestFlag( coupler.sounds, sound::couplerstretch ) ) { + // sprzegi sie rozciagaja + if( true == TestFlag( coupler.sounds, sound::loud ) ) { + // loud stretch + if( false == couplersounds.dsbCouplerStretch_loud.empty() ) { + // dedicated sound for loud stretch + couplersounds.dsbCouplerStretch_loud + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + else { + // fallback on the standard sound + couplersounds.dsbCouplerStretch + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + else { + // basic clash + couplersounds.dsbCouplerStretch + .gain( 1.f ) + .play( sound_flags::exclusive ); + } + } + // attach/detach sounds + if( ( coupler.sounds & sound::detach ) == 0 ) { + // potentially added some couplings + if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { + couplersounds.attach_coupler.play(); + } + if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { + couplersounds.attach_brakehose.play(); + } + if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { + couplersounds.attach_mainhose.play(); + } + if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { + couplersounds.attach_control.play(); + } + if( ( coupler.sounds & sound::attachgangway ) != 0 ) { + couplersounds.attach_gangway.play(); + } + if( ( coupler.sounds & sound::attachheating ) != 0 ) { + couplersounds.attach_heating.play(); + } + } + else { + // potentially removed some couplings + if( ( coupler.sounds & sound::attachcoupler ) != 0 ) { + couplersounds.detach_coupler.play(); + } + if( ( coupler.sounds & sound::attachbrakehose ) != 0 ) { + couplersounds.detach_brakehose.play(); + } + if( ( coupler.sounds & sound::attachmainhose ) != 0 ) { + couplersounds.detach_mainhose.play(); + } + if( ( coupler.sounds & sound::attachcontrol ) != 0 ) { + couplersounds.detach_control.play(); + } + if( ( coupler.sounds & sound::attachgangway ) != 0 ) { + couplersounds.detach_gangway.play(); + } + if( ( coupler.sounds & sound::attachheating ) != 0 ) { + couplersounds.detach_heating.play(); + } + } + if( true == TestFlag( coupler.sounds, sound::attachadapter ) ) { + couplersounds.dsbAdapterAttach.play(); + } + if( true == TestFlag( coupler.sounds, sound::removeadapter ) ) { + couplersounds.dsbAdapterRemove.play(); + } + + ++couplerindex; + coupler.sounds = 0; + } +} + +// the scraping of the vehicle off the track and the sounds of the special events (derailment), and clears the event flag +void TDynamicObject::renderDerailmentSounds() { + + // physics.derailment new: off the track the vehicle scrapes along the ground until it stops, or until it is put back + // on the rails (rerail()) while still sliding + if( physics->OffTrack.active() && false == physics->OffTrack.at_rest() ) { + if( false == rsDerailment.is_playing() ) { + rsDerailment.play( sound_flags::exclusive | sound_flags::looping ); + } + m_offtrackscraping = true; + } + else if( std::exchange( m_offtrackscraping, false ) && rsDerailment.is_playing() ) { + rsDerailment.stop(); + } + +// special events + if( physics->EventFlag() ) { + // McZapkie: w razie wykolejenia + if( true == physics->DamageFlag.HasAll(VehicleDamage::derailed) ) { + rsDerailment.play( sound_flags::exclusive ); + } + + physics->ClearEventFlag(); + } +} + +void TDynamicObject::play_mirror_sounds( VehicleSide const Side, mirror_moves::event const Event ) { + + if( Event == mirror_moves::event::none ) { return; } + // as UpdateMirror(), only the mirrors of the occupied cab move + if( physics->CabOccupied() == 0 ) { return; } + auto const cabend { physics->CabOccupied() > 0 ? VehicleEnd::front : VehicleEnd::rear }; + for( auto &mirror : m_mirrorsounds ) { + if( mirror.placement != Side || mirror.end != cabend ) { continue; } + auto &sound { Event == mirror_moves::event::unfolding ? mirror.unfold : mirror.fold }; + auto &other { Event == mirror_moves::event::unfolding ? mirror.fold : mirror.unfold }; + other.stop(); + sound.play( sound_flags::exclusive ); + } +} + +void +TDynamicObject::powertrain_sounds::position( glm::vec3 const Location ) { + + auto const nullvector { glm::vec3() }; + std::vector enginesounds = { + &inverter, + &motor_relay, &dsbWejscie_na_bezoporow, &motor_parallel, &motor_shuntfield, &rsWentylator, + &engine, &engine_ignition, &engine_shutdown, &engine_revving, &engine_turbo, &oil_pump, &fuel_pump, &water_pump, &water_heater, &radiator_fan, &radiator_fan_aux, + &transmission, &rsEngageSlippery, &retarder + }; + for( auto sound : enginesounds ) { + if( sound->offset() == nullvector ) { + sound->offset( Location ); + } + } +} + +void +TDynamicObject::powertrain_sounds::render( physics::Vehicle const &Vehicle, double const Deltatime ) { + + if( Vehicle.Power == 0 ) { return; } + + renderPumpSounds( Vehicle ); + renderIgnitionSounds( Vehicle ); + renderEngineSounds( Vehicle, Deltatime ); + renderTurboSound( Vehicle, Deltatime ); + renderClutchSound( Vehicle ); + renderRetarderSound( Vehicle ); + renderTractionMotorSounds( Vehicle, Deltatime ); + renderMotorBlowerSounds( Vehicle ); + renderInverterSound( Vehicle ); + renderFanSounds( Vehicle ); + renderRelaySounds( Vehicle ); + renderTransmissionSound( Vehicle ); +} + +// the sounds of the oil, fuel and water pumps and of the water heater +void +TDynamicObject::powertrain_sounds::renderPumpSounds( physics::Vehicle const &Vehicle ) { + + // oil pump + if( true == Vehicle.OilPump.is_active ) { + oil_pump + .pitch( oil_pump.m_frequencyoffset + oil_pump.m_frequencyfactor * 1.f ) + .gain( oil_pump.m_amplitudeoffset + oil_pump.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + oil_pump.stop(); + } + // fuel pump + if( true == Vehicle.FuelPump.is_active ) { + fuel_pump + .pitch( fuel_pump.m_frequencyoffset + fuel_pump.m_frequencyfactor * 1.f ) + .gain( fuel_pump.m_amplitudeoffset + fuel_pump.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + fuel_pump.stop(); + } + // water pump + if( true == Vehicle.WaterPump.is_active ) { + water_pump + .pitch( water_pump.m_frequencyoffset + water_pump.m_frequencyfactor * 1.f ) + .gain( water_pump.m_amplitudeoffset + water_pump.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + water_pump.stop(); + } + // water heater + if( true == Vehicle.WaterHeater.is_active ) { + water_heater + .pitch( water_heater.m_frequencyoffset + water_heater.m_frequencyfactor * 1.f ) + .gain( water_heater.m_amplitudeoffset + water_heater.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + water_heater.stop(); + } +} + +// the sounds of the engine and the main circuit being switched on or off +void +TDynamicObject::powertrain_sounds::renderIgnitionSounds( physics::Vehicle const &Vehicle ) { + + // engine sounds + // ignition + if( engine_state_last != Vehicle.lineBreaker.IsClosed() ) { + + if( true == Vehicle.lineBreaker.IsClosed() ) { + // TODO: separate engine and main circuit + // engine activation + engine_shutdown.stop(); + engine_ignition + .pitch( engine_ignition.m_frequencyoffset + engine_ignition.m_frequencyfactor * 1.f ) + .gain( engine_ignition.m_amplitudeoffset + engine_ignition.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive ); + // main circuit activation + linebreaker_close + .pitch( linebreaker_close.m_frequencyoffset + linebreaker_close.m_frequencyfactor * 1.f ) + .gain( linebreaker_close.m_amplitudeoffset + linebreaker_close.m_amplitudefactor * 1.f ) + .play(); + } + else { + // engine deactivation + engine_ignition.stop(); + engine_shutdown.pitch( engine_shutdown.m_frequencyoffset + engine_shutdown.m_frequencyfactor * 1.f ) + .gain( engine_shutdown.m_amplitudeoffset + engine_shutdown.m_amplitudefactor * 1.f ) + .play( sound_flags::exclusive ); + // main circuit deactivation + linebreaker_open + .pitch( linebreaker_open.m_frequencyoffset + linebreaker_open.m_frequencyfactor * 1.f ) + .gain( linebreaker_open.m_amplitudeoffset + linebreaker_open.m_amplitudefactor * 1.f ) + .play(); + } + engine_state_last = Vehicle.lineBreaker.IsClosed(); + } +} + +// the sounds of the running engine, of its revving and of the fake engine, and the smoothed engine volume +void +TDynamicObject::powertrain_sounds::renderEngineSounds( physics::Vehicle const &Vehicle, double const Deltatime ) { + + double frequency { 1.0 }; + double volume { 0.0 }; + + // main engine sound + if( true == Vehicle.lineBreaker.IsClosed() ) { + + if( std::abs(Vehicle.enrot) > 0.01 + // McZapkie-280503: zeby dla dumb dzialal silnik na jalowych obrotach + || Vehicle.EngineType == TEngineType::Dumb ) { + + // frequency calculation + auto const normalizer { ( + true == engine.is_combined() ? + // for combined engine sound we calculate sound point in rpm, to make .mmd files setup easier + // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range + 60.f * 0.01f : + // for legacy single-piece sounds the standard frequency calculation is left untouched + 1.f ) }; + frequency = + engine.m_frequencyoffset + + engine.m_frequencyfactor * std::abs( Vehicle.enrot ) * normalizer; + + if( Vehicle.EngineType == TEngineType::Dumb ) { + frequency -= 0.2 * Vehicle.EnginePower / ( 1 + Vehicle.Power * 1000 ); + } + + // base volume calculation + switch( Vehicle.EngineType ) { + // TODO: check calculated values + case TEngineType::DieselElectric: { + + volume = + engine.m_amplitudeoffset + + engine.m_amplitudefactor * ( + 0.25 * ( Vehicle.EnginePower / Vehicle.Power ) + + 0.75 * Vehicle.EngineRPMRatio() ); + break; + } + case TEngineType::DieselEngine: { + if( Vehicle.enrot > 0.0 ) { + volume = Vehicle.EnginePower > 0 ? engine.m_amplitudeoffset + engine.m_amplitudefactor * Vehicle.diesel.fill : + engine.m_amplitudeoffset + engine.m_amplitudefactor * std::fabs(Vehicle.enrot / Vehicle.diesel.maxRevolutions); + } + break; + } + default: { + volume = + engine.m_amplitudeoffset + + engine.m_amplitudefactor * ( Vehicle.EnginePower + std::fabs( Vehicle.enrot ) * 60.0 ); + break; + } + } + + if( engine_volume >= 0.05 ) { + + auto enginerevvolume { 0.f }; + if( Vehicle.EngineType == TEngineType::DieselElectric + || Vehicle.EngineType == TEngineType::DieselEngine ) { + // diesel engine revolutions increase; it can potentially decrease volume of base engine sound + if( engine_revs_last != -1.f ) { + // calculate potential recent increase of engine revolutions + auto const revolutionsperminute { Vehicle.enrot * 60 }; + auto const revolutionsdifference { revolutionsperminute - engine_revs_last }; + auto const idlerevolutionsthreshold { 1.01 * Vehicle.EngineIdleRPM() }; + engine_revs_change = std::max( 0.0, engine_revs_change - 2.5 * Deltatime ); + if( revolutionsperminute > idlerevolutionsthreshold + && revolutionsdifference > 1.0 * Deltatime ) { + engine_revs_change = std::clamp( engine_revs_change + 5.0 * Deltatime, 0.0, 1.25 ); + } + enginerevvolume = 0.8 * engine_revs_change; + } + engine_revs_last = Vehicle.enrot * 60; + + auto const enginerevfrequency { ( + true == engine_revving.is_combined() ? + // if the sound contains multiple samples we reuse rpm-based calculation from the engine + frequency : + engine_revving.m_frequencyoffset + 1.f * engine_revving.m_frequencyfactor ) }; + + if( enginerevvolume > 0.02 ) { + engine_revving + .pitch( enginerevfrequency ) + .gain( enginerevvolume ) + .play( sound_flags::exclusive ); + } + else { + engine_revving.stop(); + } + } // diesel engines + + // multi-part revving sound pieces replace base engine sound, single revving simply gets mixed with the base + auto const enginevolume { ( + enginerevvolume > 0.02 && true == engine_revving.is_combined() ? + std::max( 0.0, engine_volume - enginerevvolume ) : + engine_volume ) }; + engine + .pitch( frequency ) + .gain( enginevolume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } // enginevolume > 0.05 + } + else { + engine.stop(); + } + } + + if (Vehicle.lineBreaker.IsClosed()) { + float power = std::clamp(Vehicle.inductionMotor.forceShare, 0.0, 1.0); + + fake_engine + .pitch(fake_engine.m_frequencyoffset + power * fake_engine.m_frequencyfactor) + .gain(fake_engine.m_amplitudeoffset + power * fake_engine.m_amplitudefactor) + .play(sound_flags::exclusive | sound_flags::looping); + } + else { + fake_engine.stop(); + } + + engine_volume = std::lerp( engine_volume, volume, 0.25 ); + if( engine_volume < 0.05 ) { + engine.stop(); + } +} + +// the sound of the turbocharger +void +TDynamicObject::powertrain_sounds::renderTurboSound( physics::Vehicle const &Vehicle, double const Deltatime ) { + + double volume { 0.0 }; + + // youBy - przenioslem, bo diesel tez moze miec turbo + if( Vehicle.TurboTest > 0 ) { + // udawanie turbo: + auto const pitch_diesel{Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric ? Vehicle.enrot / Vehicle.diesel.maxRevolutions * Vehicle.diesel.fill : 1}; + auto const goalpitch { std::max( 0.025, ( /*engine_volume **/ pitch_diesel + engine_turbo.m_frequencyoffset ) * engine_turbo.m_frequencyfactor ) }; + auto const goalvolume { ( + Vehicle.MainCtrlPos() >= Vehicle.TurboTest && Vehicle.enrot > 0.1 ? + std::max( 0.0, ( engine_turbo_pitch + engine_turbo.m_amplitudeoffset ) * engine_turbo.m_amplitudefactor ) : + 0.0 ) }; + auto const currentvolume { engine_turbo.gain() }; + auto const changerate { 0.4 * Deltatime }; + + engine_turbo_pitch = engine_turbo_pitch > goalpitch ? std::max(goalpitch, engine_turbo_pitch - changerate * 0.5) : std::min(goalpitch, engine_turbo_pitch + changerate); + + volume = currentvolume > goalvolume ? std::max(goalvolume, currentvolume - changerate) : std::min(goalvolume, currentvolume + changerate); + + engine_turbo + .pitch( 0.4 + engine_turbo_pitch * 0.4 ) + .gain( volume ); + + if( volume > 0.05 ) { + engine_turbo.play( sound_flags::exclusive | sound_flags::looping ); + } + else { + engine_turbo.stop(); + } + } +} + +// the sound of the slipping clutch +void +TDynamicObject::powertrain_sounds::renderClutchSound( physics::Vehicle const &Vehicle ) { + + double frequency { 1.0 }; + double volume { 0.0 }; + + if( Vehicle.diesel.clutchPressure > 0.1 ) { + if( std::abs( Vehicle.diesel.clutchSlip ) > 0.2 ) { + frequency = rsEngageSlippery.m_frequencyoffset + rsEngageSlippery.m_frequencyfactor * std::fabs( Vehicle.diesel.clutchSlip ); + volume = rsEngageSlippery.m_amplitudeoffset + rsEngageSlippery.m_amplitudefactor * Vehicle.diesel.clutchPressure; + } + else { + frequency = 1.f; // rsEngageSlippery.FA+0.7*rsEngageSlippery.FM*(fabs(controlled->enrot)+controlled->nmax); + volume = Vehicle.diesel.clutchPressure > 0.2 ? rsEngageSlippery.m_amplitudeoffset + 0.2 * rsEngageSlippery.m_amplitudefactor * (Vehicle.enrot / Vehicle.nmax) : 0.f; + } + + rsEngageSlippery + .pitch( frequency ) + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + rsEngageSlippery.stop(); + } +} + +// the sound of the retarder +void +TDynamicObject::powertrain_sounds::renderRetarderSound( physics::Vehicle const &Vehicle ) { + + if (Vehicle.retarder.present) { + float speed = std::abs(Vehicle.retarder.revolutions); + + retarder + .pitch(retarder.m_frequencyoffset + speed * retarder.m_frequencyfactor) + .gain(retarder.m_amplitudeoffset + Vehicle.retarder.fill * retarder.m_amplitudefactor); + + if (retarder.gain() > 0.01 && speed > 1 && Vehicle.retarder.clutchActive) { + retarder.play(sound_flags::exclusive | sound_flags::looping); + } + else { + retarder.stop(); + } + } +} + +// the sounds of the traction motors, the generic ones and the inverter-specific ones +void +TDynamicObject::powertrain_sounds::renderTractionMotorSounds( physics::Vehicle const &Vehicle, double const Deltatime ) { + + double frequency { 1.0 }; + double volume { 0.0 }; + + // motor sounds + volume = 0.0; + // generic traction motor sounds + if( false == motors.empty() ) { + + if( std::abs( Vehicle.nrot() ) > 0.01 ) { + + auto const &motor { motors.front() }; + // frequency calculation + auto normalizer { 1.f }; + if( true == motor.is_combined() ) { + // for combined motor sound we calculate sound point in rpm, to make .mmd files setup easier + // NOTE: we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range + normalizer = 60.f * 0.01f; + } + auto const motorrevolutions { std::abs( Vehicle.nrot() ) * Vehicle.Transmision.Ratio }; + frequency = + motor.m_frequencyoffset + + motor.m_frequencyfactor * motorrevolutions * normalizer; + + // base volume calculation + switch( Vehicle.EngineType ) { + case TEngineType::ElectricInductionMotor: { + volume = + motor.m_amplitudeoffset + + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 2 ); + break; + } + case TEngineType::ElectricSeriesMotor: { + volume = + motor.m_amplitudeoffset + + motor.m_amplitudefactor * ( Vehicle.EnginePower + motorrevolutions * 60.0 ); + break; + } + default: { + volume = + motor.m_amplitudeoffset + + motor.m_amplitudefactor * motorrevolutions * 60.0; + break; + } + } + + if( Vehicle.EngineType == TEngineType::ElectricSeriesMotor ) { + // volume variation + if( volume < 1.0 + && Vehicle.EnginePower < 100 ) { + + auto const volumevariation { LocalRandom( 100 ) * Vehicle.enrot / ( 1 + Vehicle.nmax ) }; + if( volumevariation < 2 ) { + volume += volumevariation / 200; + } + } + + if( Vehicle.brakes.electrodynamic.on + && Vehicle.EnginePower > 0.1 ) { + // Szociu - 29012012 - jeżeli uruchomiony jest hamulec elektrodynamiczny, odtwarzany jest dźwięk silnika + volume += 0.8; + } + } + // scale motor volume based on whether they're active + motor_momentum = + std::clamp( + motor_momentum + - 1.0 * Deltatime // smooth out decay + + std::abs( Vehicle.Mm() ) / 60.0 * Deltatime, + 0.0, 1.25 ); + volume *= std::max( 0.25f, motor_momentum ); + motor_volume = std::lerp( motor_volume, volume, 0.25 ); + if( motor_volume >= 0.05 ) { + // apply calculated parameters to all motor instances + for( auto &motor : motors ) { + motor + .pitch( frequency ) + .gain( motor_volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + // stop all motor instances + for( auto &motor : motors ) { + motor.stop(); + } + } + } + else { + // stop all motor instances + motor_volume = 0.0; + for( auto &motor : motors ) { + motor.stop(); + } + } + } + // inverter-specific traction motor sounds + if( false == acmotors.empty() ) { + + if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { + if( Vehicle.inductionMotor.inverterFrequency > 0.001 ) { + + for( auto &motor : acmotors ) { + motor + .pitch( motor.m_frequencyoffset + motor.m_frequencyfactor * Vehicle.inductionMotor.inverterFrequency ) + .gain( motor.m_amplitudeoffset + motor.m_amplitudefactor * std::sqrt( std::abs( Vehicle.inductionMotor.forceShare ) ) ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + } + else { + for( auto &motor : acmotors ) { + motor.stop(); + } + } + } + } +} + +// the sounds of the motor blowers, each matched with the blower at its end of the vehicle +void +TDynamicObject::powertrain_sounds::renderMotorBlowerSounds( physics::Vehicle const &Vehicle ) { + + // motor blowers + if( false == motorblowers.empty() ) { + for( auto &blowersound : motorblowers ) { + // match the motor blower and the sound source based on whether they're located in the front or the back of the vehicle + auto const &blower { Vehicle.MotorBlowers[ ( blowersound.offset().z > 0 ? VehicleEnd::front : VehicleEnd::rear ) ] }; + // TODO: for the sounds with provided bookends invoke stop() when the stop is triggered and revolutions start dropping, instead of after full stop + if( blower.revolutions > 1 ) { + // NOTE: for motorblowers with fixed speed if the sound has defined bookends we skip revolutions-based part of frequency/volume adjustments + auto const revolutionmodifier { blower.speed < 0.f && blowersound.has_bookends() ? 1.f : blower.revolutions }; + blowersound + .pitch( + true == blowersound.is_combined() ? + blower.revolutions * 0.01f : + blowersound.m_frequencyoffset + blowersound.m_frequencyfactor * revolutionmodifier ) + .gain( blowersound.m_amplitudeoffset + blowersound.m_amplitudefactor * revolutionmodifier ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + blowersound.stop(); + } + } + } +} + +// the sound of the inverter +void +TDynamicObject::powertrain_sounds::renderInverterSound( physics::Vehicle const &Vehicle ) { + + double volume { 0.0 }; + + // inverter sounds + if( Vehicle.EngineType == TEngineType::ElectricInductionMotor ) { + if( Vehicle.inductionMotor.inverterFrequency > 0.001 ) { + + volume = inverter.m_amplitudeoffset + inverter.m_amplitudefactor * std::sqrt( std::abs( Vehicle.inductionMotor.forceShare) ); + + inverter + .pitch( inverter.m_frequencyoffset + inverter.m_frequencyfactor * Vehicle.inductionMotor.inverterFrequency ) + .gain( volume ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + inverter.stop(); + } + } +} + +// the sounds of the ventilator and of the radiator fans +void +TDynamicObject::powertrain_sounds::renderFanSounds( physics::Vehicle const &Vehicle ) { + + // ventillator sounds + if( Vehicle.RventRot > 0.1 ) { + + rsWentylator + .pitch( rsWentylator.m_frequencyoffset + rsWentylator.m_frequencyfactor * Vehicle.RventRot ) + .gain( rsWentylator.m_amplitudeoffset + rsWentylator.m_amplitudefactor * Vehicle.RventRot ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // ...otherwise shut down the sound + rsWentylator.stop(); + } + // radiator fan sounds + if( Vehicle.EngineType == TEngineType::DieselEngine + || Vehicle.EngineType == TEngineType::DieselElectric ) { + + if( Vehicle.diesel.heat.rpmw > 0.1 ) { + // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 + radiator_fan + .pitch( 0.5 + radiator_fan.m_frequencyoffset + radiator_fan.m_frequencyfactor * Vehicle.diesel.heat.rpmw * 0.01 ) + .gain( 0.5 + radiator_fan.m_amplitudeoffset + 0.5 * radiator_fan.m_amplitudefactor * Vehicle.diesel.heat.rpmw * 0.01 ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // ...otherwise shut down the sound + radiator_fan.stop(); + } + + if( Vehicle.diesel.heat.rpmw2 > 0.1 ) { + // NOTE: fan speed tends to max out at ~100 rpm; by default we try to get pitch range of 0.5-1.5 and volume range of 0.5-1.0 + radiator_fan_aux + .pitch( 0.5 + radiator_fan_aux.m_frequencyoffset + radiator_fan_aux.m_frequencyfactor * Vehicle.diesel.heat.rpmw2 * 0.01 ) + .gain( 0.5 + radiator_fan_aux.m_amplitudeoffset + 0.5 * radiator_fan_aux.m_amplitudefactor * Vehicle.diesel.heat.rpmw2 * 0.01 ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + // ...otherwise shut down the sound + radiator_fan_aux.stop(); + } + } +} + +// the sounds of the relays, set in the sound flags of the vehicle +void +TDynamicObject::powertrain_sounds::renderRelaySounds( physics::Vehicle const &Vehicle ) { + + // relay sounds + auto const soundflags { Vehicle.SoundFlag() }; + if( TestFlag( soundflags, sound::relay ) ) { + // przekaznik - gdy bezpiecznik, automatyczny rozruch itp + if( true == TestFlag( soundflags, sound::shuntfield ) ) { + // shunt field + motor_shuntfield + .pitch( + true == motor_shuntfield.is_combined() ? + Vehicle.ScndCtrlActualPos * 0.01f : + motor_shuntfield.m_frequencyoffset + motor_shuntfield.m_frequencyfactor * 1.f ) + .gain( + motor_shuntfield.m_amplitudeoffset + ( + true == TestFlag( soundflags, sound::loud ) ? + 1.0f : + 0.8f ) + * motor_shuntfield.m_amplitudefactor ) + .play(); + } + else if( true == TestFlag( soundflags, sound::parallel ) ) { + // parallel mode + if( TestFlag( soundflags, sound::loud ) ) { + dsbWejscie_na_bezoporow.play(); + } + else { + motor_parallel.play(); + } + } + else { + // series mode + motor_relay + .pitch( + true == motor_relay.is_combined() ? + Vehicle.MainCtrlActualPos * 0.01f : + motor_relay.m_frequencyoffset + motor_relay.m_frequencyfactor * 1.f ) + .gain( + motor_relay.m_amplitudeoffset + ( + true == TestFlag( soundflags, sound::loud ) ? + 1.0f : + 0.8f ) + * motor_relay.m_amplitudefactor ) + .play(); + } + } +} + +// the sound of the transmission +void +TDynamicObject::powertrain_sounds::renderTransmissionSound( physics::Vehicle const &Vehicle ) { + + if( Vehicle.Vel > 0.1 ) { + transmission + .pitch( transmission.m_frequencyoffset + transmission.m_frequencyfactor * Vehicle.Vel ) + .gain( transmission.m_amplitudeoffset + transmission.m_amplitudefactor * Vehicle.Vel ) + .play( sound_flags::exclusive | sound_flags::looping ); + } + else { + transmission.stop(); + } +} diff --git a/vehicle/dynamic/update.cpp b/vehicle/dynamic/update.cpp new file mode 100644 index 000000000..398fe1241 --- /dev/null +++ b/vehicle/dynamic/update.cpp @@ -0,0 +1,1124 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// the update of a vehicle in a step of the simulation + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +bool TDynamicObject::Update(double dt, double dt1) +{ + if (dt1 == 0.0) + return true; // Ra: pauza + // physics.derailment new: all of the update of a vehicle off the track, timed; a warning once a second at most when it + // takes long, to find what makes a derailment slow + // (no vehicle when it is on the track: nothing is timed then) + class off_track_watch { + public: + off_track_watch( TDynamicObject *Vehicle, double const Frame ) : + vehicle { Vehicle }, frame { Frame } { + if( vehicle != nullptr ) { + started = off_track_clock::now(); + } + } + off_track_watch( off_track_watch const & ) = delete; + off_track_watch &operator=( off_track_watch const & ) = delete; + ~off_track_watch() { + if( vehicle == nullptr ) { + return; + } + auto const took { vehicle_dynamic::seconds_since( started ) }; + vehicle->m_offtrackupdatedue -= frame; + if( took > off_track_slow && vehicle->m_offtrackupdatedue <= 0.0 ) { + vehicle->m_offtrackupdatedue = 1.0; + ErrorLog( std::format( "derailment: warning: the update of {} off the track took {:.0f} ms in a frame of {:.3f} s", vehicle->physics->Name, took * 1000.0, frame ) ); + } + } + private: + TDynamicObject *vehicle; + double frame; + off_track_clock::time_point started {}; + }; + off_track_watch const watch { physics->OffTrack.active() ? this : nullptr, dt1 }; + if( m_offtrackterrain != nullptr && false == physics->OffTrack.active() ) { + // physics.derailment new: back on the rails (rerail()), the terrain it slid over is let go + m_offtrackterrain.reset(); + m_offtracksite.terrain( nullptr ); + } + if (!physics->PhysicActivation() && + !MechInside) { // to drugie, bo będąc w maszynowym blokuje się fizyka + // physics.derailment new: a vehicle off the track stopped along its heading still settles: it slides down a + // slope, falls over, or comes to rest after the step its physics stopped in + if( physics->OffTrack.active() && false == physics->OffTrack.at_rest() && bEnabled ) { + m_offtracktime = dt1; + Move( 0.0 ); + update_off_track( dt1 ); + } + return true; // McZapkie: wylaczanie fizyki gdy nie potrzeba + } + if (!MyTrack) + return false; // pojazdy postawione na torach portalowych mają MyTrack==NULL + if (!bEnabled) + return false; // a normalnie powinny mieć bEnabled==false + + updateTrackParameters(); + updateCouplingState(); + updateTractionVoltage( dt1 ); + // McZapkie: predkosc w torze przekazac do TrackParam + // McZapkie: Vel ma wymiar [km/h] (absolutny), V ma wymiar [m/s], taka przyjalem notacje + tp.Velmax = MyTrack->VelocityGet(); + + if (Mechanik) + { // Ra 2F3F: do Driver.cpp to przenieść? + updateDriver( dt1 ); + } + + switchOffMainsWithoutBattery(); + + double const dDOMoveLen { moveByPhysics( dt, dt1 ) }; + + if (!bEnabled) // usuwane pojazdy nie mają toru + { // pojazd do usunięcia + bDynamicRemove = true; // sprawdzić + return false; + } + ResetdMoveLen(); + + updateAxleClatter( dDOMoveLen ); + + // fragment z EXE Kursa + /* if (physics->TrainType()==train_type::et42) + { + if ((physics->DynamicBrakeType=dbrake_switch) && + ((physics->BrakePress > + 0.2) || ( physics->PipePress < 0.36 ))) + { + physics->StLinFlag=true; + } + else + if ((physics->DynamicBrakeType=dbrake_switch) && + (physics->BrakePress < + 0.1)) + { + physics->StLinFlag=false; + + } + } */ + + updateWheelAngles( dt1 ); + updateCurrentCollectors( dt1 ); + updateWipers( dt1 ); + updateMirrors( dt1 ); + + // compartment lights + // if the vehicle has a controller, we base the light state on state of the controller otherwise we check the vehicle itself + if( ctOwner != nullptr ? SectionLightsActive != physics->CompartmentLights.is_active : + Mechanik != nullptr ? SectionLightsActive != physics->CompartmentLights.is_active : + SectionLightsActive ) { // without controller switch the lights off + toggle_lights(); + } + + if (physics->InactiveCabPantsCheck()) + { + pants_up(); + physics->SetInactiveCabPantsCheck(false); + } + + if( physics->LoadStatus() ) { + LoadUpdate(); // zmiana modelu ładunku + } + update_exchange( dt ); + + return true; // Ra: chyba tak? +} + +// the shape and the parameters of the track under the vehicle, for its physics +void TDynamicObject::updateTrackParameters() +{ + // McZapkie: parametry powinny byc pobierane z toru + if (Axle0.vAngles.z != Axle1.vAngles.z) + { // wyliczenie promienia z obrotów osi - modyfikację zgłosił youBy + ts.R = Axle0.vAngles.z - Axle1.vAngles.z; // różnica może dawać stałą ±M_2PI + if( ts.R > 15000.0 || ts.R < -15000.0 ) { + // szkoda czasu na zbyt duże promienie, 4km to promień nie wymagający przechyłki + ts.R = 0.0; + } + else { + // normalizacja + if( ts.R > M_PI ) { ts.R -= M_2PI; } + else if( ts.R < -M_PI ) { ts.R += M_2PI; } + + if( ts.R != 0.0 ) { + // sin(0) results in division by zero + ts.R = -0.5 * physics->BDist() / sin( ts.R * 0.5 ); + } + } + } + else + ts.R = 0.0; + // ts.R=ComputeRadius(Axle1.pPosition,Axle2.pPosition,Axle3.pPosition,Axle0.pPosition); + // Ra: składową pochylenia wzdłużnego mamy policzoną w jednostkowym wektorze + // vFront + ts.Len = 1.0; // std::max(physics->BDist(),physics->ADist()); + ts.dHtrack = -vFront.y; // Axle1.pPosition.y-Axle0.pPosition.y; //wektor + // między skrajnymi osiami + // (!!!odwrotny) + ts.dHrail = (Axle1.GetRoll() + Axle0.GetRoll()) * 0.5; //średnia przechyłka pudła + // the uneven track under the outer axles, for the criteria of derailment: its lateral curvature, and its cross level + ts.uneven_curvature = glm::dot( 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ), vLeft ); + ts.uneven_cross = MyTrack->uneven_underway().cross; + // a buckle of the track under the body: the mean of the curvatures at the outer axles, each over the wheelbase of its bogie + ts.buckle_curvature = 0.5 * ( Axle0.BuckleCurvature( physics->ADist() ) + Axle1.BuckleCurvature( physics->ADist() ) ); + // TTrackParam tp; + tp.Width = MyTrack->fTrackWidth; + // McZapkie-250202 + tp.friction = MyTrack->Friction() * Global.fFriction * Global.FrictionWeatherFactor; + tp.CategoryFlag = MyTrack->iCategoryFlag & 15; + tp.DamageFlag = MyTrack->iDamageFlag; + tp.QualityFlag = MyTrack->iQualityFlag; + tp.Name = &MyTrack->name(); +} + +// the vehicle inside the consist or at its end, and the consist checked once a coupler was attached +void TDynamicObject::updateCouplingState() +{ + // couplers + if( physics->Couplers[0].CouplingFlag != Coupling::none + && physics->Couplers[1].CouplingFlag != Coupling::none ) { + physics->SetInsideConsist(true); + } + else { + physics->SetInsideConsist(false); + } + if( TestFlag( physics->AIFlag(), sound::attachcoupler ) ) { + auto *driver{ ctOwner ? ctOwner : Mechanik }; + if( driver != nullptr ) { + driver->CheckVehicles( DriverOrder::connect ); + } + physics->ClearAIFlag( sound::attachcoupler ); + } +} + +// the voltage of the supply of the vehicle, kept over a short loss of contact, passed to its physics +void TDynamicObject::updateTractionVoltage( double const dt1 ) +{ + // napiecie sieci trakcyjnej + if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { // dla EZT tylko silnikowy + + tmpTraction.TractionVoltage = std::max( std::abs( physics->pantographCircuit.RearVoltage() ), std::abs( physics->pantographCircuit.FrontVoltage() ) ); + // jeśli brak zasilania dłużej niż 0.2 sekundy (25km/h pod izolatorem daje 0.15s) + // Ra 2F1H: prowizorka, trzeba przechować napięcie, żeby nie wywalało WS pod izolatorem + if( tmpTraction.TractionVoltage > 0.0) { + NoVoltTime = 0; + } + else { + NoVoltTime += dt1; + if( NoVoltTime <= 0.2 ) { + tmpTraction.TractionVoltage = physics->pantographCircuit.SupplyVoltage(); + } + else { + // jeśli jedzie + if( physics->Vel > 0.5 ) { + // Ra 2014-07: doraźna blokada logowania zimnych lokomotyw - zrobić to trzeba inaczej + if( physics->pantographs[VehicleEnd::front].is_active + || physics->pantographs[VehicleEnd::rear].is_active ) { + if( physics->lineBreaker.IsClosed() // Ra 15-01: logować tylko, jeśli WS załączony + && physics->GetTrainsetHighVoltage() < 0.1f // yB 16-03: i nie jest to asynchron zasilany z daleka + && false == physics->GensetSelected() ) { // nor a dual-mode vehicle running on its genset + // Ra 15-01: bezwzględne współrzędne pantografu nie są dostępne więc lepiej się tego nie zaloguje + ErrorLog( + "Bad traction: " + physics->Name + + " lost power for " + to_string( NoVoltTime, 2 ) + " sec. at " + + to_string(vPosition) ); + } + } + } + } + } + } + else { + tmpTraction.TractionVoltage = 0.95 * physics->EnginePowerSource.MaxVoltage; + } + tmpTraction.TractionFreq = 0; + tmpTraction.TractionMaxCurrent = 7500; // Ra: chyba za dużo? powinno wywalać przy 1500 + tmpTraction.TractionResistivity = 0.3; + + physics->pantographCircuit.SetSupplyVoltage(tmpTraction.TractionVoltage); +} + +// the driver of the vehicle: the integrated controller, the brakes blended over a consist with induction motors, the AI +void TDynamicObject::updateDriver( double const dt1 ) +{ + if( Mechanik->primary() ) { + physics->SetEquivalentPipePressure( GetEPP() ); // srednie cisnienie w PG + } + if (Mechanik->primary() && + (physics->EngineType == TEngineType::DieselEngine || + physics->EngineType == TEngineType::DieselElectric) + && physics->EIMCtrlType > 0) { + physics->CheckEIMIC(dt1); + if (physics->SpeedCtrl()) + physics->CheckSpeedCtrl(dt1); + physics->SetEimicReal(std::min(physics->eimic,physics->eimicSpeedCtrl())); + physics->SendCtrlToNext(VehicleCommand::integratedController, physics->EimicReal(), physics->CabActive); + } + if( Mechanik->primary() + && physics->EngineType == TEngineType::ElectricInductionMotor ) { + // jesli glowny i z asynchronami, to niech steruje hamulcem i napedem lacznie dla calego pociagu/ezt + distributeInductionBraking( dt1 ); + } + + Timer::subsystem.vehicles_ai.start(); + Mechanik->Update(dt1); // przebłyski świadomości AI + Timer::subsystem.vehicles_ai.stop(); +} + +// the consist with induction motors driven and braked as a whole: its braking blended between the ED and the EP brakes +// (physics::ConsistBrakeBlending), over the vehicles in their order from the occupied cab +void TDynamicObject::distributeInductionBraking( double const dt1 ) +{ + auto const forward { DirectionGet() * physics->CabOccupied() > 0 }; + std::vector consist; + for( TDynamicObject *vehicle = GetFirstDynamic( physics->CabOccupied() < 0 ? VehicleEnd::rear : VehicleEnd::front, Coupling::control ); vehicle != nullptr; + vehicle = forward ? vehicle->Next( Coupling::control ) : vehicle->Prev( Coupling::control ) ) { + consist.emplace_back( vehicle->physics ); + } + physics::ConsistBrakeBlending::Inputs inputs; + inputs.owner = ctOwner != nullptr ? ctOwner->Controlling() : nullptr; + inputs.aiDriving = Mechanik->AIControllFlag(); + Mechanik->SetMedAmax(brakeBlending.Update( *physics, consist, inputs, dt1 )); +} + +// the main switch off, with the supply of the vehicle's circuits off, but for diesel engines and hand cars +void TDynamicObject::switchOffMainsWithoutBattery() +{ + // fragment "z EXE Kursa" + if( physics->lineBreaker.IsClosed() ) { // nie wchodzić w funkcję bez potrzeby + if( false == (physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable()) +/* + // NOTE: disabled on account of multi-unit setups, where the unmanned unit wouldn't be affected + && ( Controller == Humandriver ) +*/ + && physics->EngineType != TEngineType::DieselEngine + && physics->EngineType != TEngineType::WheelsDriven ) { // jeśli bateria wyłączona, a nie diesel ani drezyna reczna + if( physics->MainSwitch( false, physics->TrainType() == train_type::emu ? range_t::unit : range_t::local ) ) { + // wyłączyć zasilanie + // NOTE: we turn off entire EMU, but only the affected unit for other multi-unit consists + physics->RaiseEventFlag(); + // drop pantographs + // NOTE: this isn't universal behaviour + // TODO: have this dependant on .fiz-driven flag + // NOTE: moved to pantspeed calculation part a little later in the function. all remarks and todo still apply +/* + physics->PantFront( false, ( physics->TrainType() == train_type::emu ? range::unit : range::local ) ); + physics->PantRear( false, ( physics->TrainType() == train_type::emu ? range::unit : range::local ) ); +*/ + } + } + } +} + +// the vehicle moved by its physics in the step; the distance it went returned +double TDynamicObject::moveByPhysics( double const dt, double const dt1 ) +{ + // przekazanie pozycji do fizyki + // NOTE: coordinate system swap + // TODO: replace with regular glm vectors + TLocation const l { + -vPosition.x, + vPosition.z, + vPosition.y }; + TRotation const r { + 0.0, + 0.0, + modelRot.z }; + // McZapkie-260202 - dMoveLen przyda sie przy stukocie kol + double const dDOMoveLen = GetdMoveLen() + physics->ComputeMovement(dt, dt1, ts, tp, tmpTraction, l, r); + if( Mechanik ) { + // dodanie aktualnego przemieszczenia + Mechanik->MoveDistanceAdd( dDOMoveLen ); + } + if( simulation::Train != nullptr + && simulation::Train->Dynamic() == this ) { + // update distance meter in user-controlled cab + // TBD: place the meter on physics logic level? + simulation::Train->add_distance( dDOMoveLen ); + } + // physics.derailment new: derailed, the vehicle leaves the track and goes on the ground + if( physics->leaves_track() ) { + begin_off_track(); + } + m_offtracktime = dt1; + glm::dvec3 old_pos = vPosition; + Move(dDOMoveLen); + update_off_track( dt1 ); + + m_future_movement = (vPosition - old_pos) / dt1 * Timer::GetDeltaRenderTime(); + return dDOMoveLen; +} + +// the clatter of the wheels over the rail joints, and the jolts they give +void TDynamicObject::updateAxleClatter( double const dDOMoveLen ) +{ + // McZapkie-260202 + // tupot mew, tfu, stukot kol: + if( MyTrack->fSoundDistance != -1 ) { + + if( MyTrack->fSoundDistance != dRailLength ) { + if( dRailLength > 0.0 ) { + for( auto &axle : m_axlesounds ) { + axle.distance = axle.offset; + axle.atjoints = false; + } + } + dRailLength = MyTrack->fSoundDistance; + } + if( dRailLength > 0.0 ) { + if( physics->Vel > 0 ) { + // TODO: track quality and/or environment factors as separate subroutine + auto volume = + std::lerp( + 0.8, 1.2, + std::clamp( + MyTrack->iQualityFlag / 10.0, + 0.0, 1.5 ) ); + switch( MyTrack->eEnvironment ) { + case e_tunnel: { + volume *= 1.3; + break; + } + case e_bridge: { + volume *= 1.5; + break; + } + default: { + break; + } + } + if( dRailLength > 0.0 ) { + auto axleindex { 0 }; + auto const directioninconsist { ( + ctOwner == nullptr ? + 1 : + ctOwner->Vehicle()->DirectionGet() == DirectionGet() ? 1 : -1 ) }; + for( auto &axle : m_axlesounds ) { + if( axle_passed_joint( axle, dDOMoveLen, directioninconsist ) + && physics->Vel > 0.1 ) { + // NOTE: for combined clatter sound we supply 1/100th of actual value, as the sound module converts does the opposite, converting received (typically) 0-1 values to 0-100 range + auto const frequency = true == axle.clatter.is_combined() ? physics->Vel * 0.01 : 1.0; + axle.clatter + .pitch( frequency ) + .gain( volume ) + .play(); + applyJointJolt( axleindex ); + } + ++axleindex; + } + } + } + } + } + // McZapkie-260202 end +} + +// the jolt of an axle over a rail joint: vertical on a plain track, vertical and sideways on a switch +void TDynamicObject::applyJointJolt( int const axleindex ) +{ + // crude bump simulation, drop down on even axles, move back up on + // the odd ones + // physics->AccVert() += (physics->Vel*0.1f) * + // the arguments keep the order they had up to 26.05.1, 0 in place of the value and the figure in place of the + // upper limit, so they work out as the old clamp worked them out up to 26.05.1: the headroom is + // Vmax - (Vel + 0.32 Vmax) whatever its sign, and the bump is capped from above only + double const headroom = safe_clamp( 0.0, physics->Vmax(), physics->Vmax() - ( physics->Vel + physics->Vmax() * 0.32f ) ); + double const jolt = headroom * .05f * ( MyTrack->iDamageFlag * 0.25f ); + if (MyTrack->eType == tt_Normal) + { + physics->ShakeVertically( safe_clamp( 0.0, 4.0, jolt ) ); + } + else if (MyTrack->eType == tt_Switch) + { + double const accHorizontal = safe_clamp( 0.0, 1.0, jolt ) * ((axleindex % 2) != 0 ? 1 : -1); + physics->ShakeHorizontally( accHorizontal ); + physics->ShakeVertically( safe_clamp( 0.0, 2.0, jolt ) ); + } +} + +// the wheels turned by the distance the vehicle went +void TDynamicObject::updateWheelAngles( double const dt1 ) +{ + if (physics->Vel != 0) + { // McZapkie-050402: krecenie kolami: + glm::dvec3 old_wheels = glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]); + + dWheelAngle[0] += 114.59155902616464175359630962821 * physics->V() * dt1 / + physics->WheelDiameterL; // przednie toczne + dWheelAngle[1] += physics->nrot() * dt1 * 360.0; // napędne + dWheelAngle[2] += 114.59155902616464175359630962821 * physics->V() * dt1 / + physics->WheelDiameterT; // tylne toczne + + + m_future_wheels_angle = (glm::dvec3(dWheelAngle[0], dWheelAngle[1], dWheelAngle[2]) - old_wheels) / dt1 * Timer::GetDeltaRenderTime(); + + dWheelAngle[0] = clamp_circular( dWheelAngle[0] ); + dWheelAngle[1] = clamp_circular( dWheelAngle[1] ); + dWheelAngle[2] = clamp_circular( dWheelAngle[2] ); + } +} + +// the pantographs, or the valve gear of a steam engine, and the supply of a vehicle that fakes it +void TDynamicObject::updateCurrentCollectors( double const dt1 ) +{ + if (pants) // pantograf może być w wagonie kuchennym albo pojeździe rewizyjnym (np. SR61) + { // przeliczanie kątów dla pantografów + // prąd pobierany przez pojazd z sieci: trakcyjny (on the genset of a dual-mode vehicle none) i TotalCurrent + // TotalCurrent to bedzie prad nietrakcyjny (niezwiazany z napedem) + double fCurrent = physics->CatenaryCurrent(); + // fCurrent+=fabs(physics->Voltage)*1e-6; //prąd płynący przez woltomierz, rozładowuje kondensator orgromowy 4µF +/* + double fPantCurrent = fCurrent; // normalnie cały prąd przez jeden pantograf + if (iAnimType[ANIM_PANTS] > 1) { // a jeśli są dwa pantografy //Ra 1014-11: proteza, trzeba zrobić sensowniej + if (pants[0].fParamPants->hvPowerWire && pants[1].fParamPants->hvPowerWire) { // i oba podłączone do drutów + fPantCurrent = fCurrent * 0.5; // to dzielimy prąd równo na oba (trochę bez sensu, ale lepiej tak niż podwoić prąd) + } + } +*/ + // test whether more than one pantograph touches the wire + // NOTE: we're duplicating lot of code from below + // TODO: clean this up + auto activepantographs { 0 }; + for( int idx = 0; idx < iAnimType[ ANIM_PANTS ]; ++idx ) { + auto const *pantograph { pants[ idx ].fParamPants }; + if( Global.bLiveTraction == false ) { + if( pantograph->PantWys >= 1.2 ) { + ++activepantographs; + } + } + else { + if( pantograph->hvPowerWire != nullptr + && true == physics->pantographs[PantographEnd( idx )].is_active + && pantograph->PantTraction - pantograph->PantWys < 0.01 ) { // tolerancja niedolegania + ++activepantographs; + } + } + } + auto const fPantCurrent { fCurrent / std::max( 1, activepantographs ) }; + + for (int i = 0; i < iAnimType[ANIM_PANTS]; ++i) + { // pętla po wszystkich pantografach + updatePantograph( i, fPantCurrent, fCurrent, dt1 ); + } // koniec pętli po pantografach + playPantographDropSounds(); + } + else if (physics->EnginePowerSource.SourceType == TPowerSource::InternalSource) + if (physics->EnginePowerSource.PowerType == TPowerType::SteamPower) + // if (smPatykird1[0]) + { // Ra: animacja rozrządu parowozu, na razie nieoptymalizowane + /* //Ra: tymczasowo wyłączone ze względu na porządkowanie animacji + pantografów + double fi,dx,c2,ka,kc; + double sin_fi,cos_fi; + double L1=1.6688888888888889; + double L2=5.6666666666666667; //2550/450 + double Lc=0.4; + double L=5.686422222; //2558.89/450 + double G1,G2,G3,ksi,sin_ksi,gam; + double G1_2,G2_2,G3_2; //kwadraty + //ruch tłoków oraz korbowodów + for (int i=0;i<=1;++i) + {//obie strony w ten sam sposób + fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)); //kąt obrotu koła dla + tłoka 1 + sin_fi=sin(fi); + cos_fi=cos(fi); + dx=panty*cos_fi+sqrt(panth*panth-panty*panty*sin_fi*sin_fi)-panth; + //nieoptymalne + if (smPatykird1[i]) //na razie zabezpieczenie + smPatykird1[i]->SetTranslate(float3(dx,0,0)); + ka=-asin(panty/panth)*sin_fi; + if (smPatykirg1[i]) //na razie zabezpieczenie + smPatykirg1[i]->SetRotateXYZ(vector3(RadToDeg(ka),0,0)); + //smPatykirg1[0]->SetRotate(float3(0,1,0),RadToDeg(fi)); //obracamy + //ruch drążka mimośrodkowego oraz jarzma + //korzystałem z pliku PDF "mm.pdf" (opis czworoboku + korbowo-wahaczowego): + //"MECHANIKA MASZYN. Szkic wykładu i laboratorium komputerowego." + //Prof. dr hab. inż. Jerzy Zajączkowski, 2007, Politechnika Łódzka + //L1 - wysokość (w pionie) osi jarzma ponad osią koła + //L2 - odległość w poziomie osi jarzma od osi koła + //Lc - długość korby mimośrodu na kole + //Lr - promień jarzma =1.0 (pozostałe przeliczone proporcjonalnie) + //L - długość drążka mimośrodowego + //fi - kąt obrotu koła + //ksi - kąt obrotu jarzma (od pionu) + //gam - odchylenie drążka mimośrodowego od poziomu + //G1=(Lr*Lr+L1*L1+L2*L2+Kc*Lc-L*L-2.0*Lc*L2*cos(fi)+2.0*Lc*L1*sin(fi))/(Lr*Lr); + //G2=2.0*(L2-Lc*cos(fi))/Lr; + //G3=2.0*(L1-Lc*sin(fi))/Lr; + fi=DegToRad(dWheelAngle[1]+(i?pant2x:pant1x)-96.77416667); //kąt + obrotu koła dla + tłoka 1 + //1) dla dWheelAngle[1]=0° korba jest w dół, a mimośród w stronę + jarzma, czyli + fi=-7° + //2) dla dWheelAngle[1]=90° korba jest do tyłu, a mimośród w dół, + czyli fi=83° + sin_fi=sin(fi); + cos_fi=cos(fi); + G1=(1.0+L1*L1+L2*L2+Lc*Lc-L*L-2.0*Lc*L2*cos_fi+2.0*Lc*L1*sin_fi); + G1_2=G1*G1; + G2=2.0*(L2-Lc*cos_fi); + G2_2=G2*G2; + G3=2.0*(L1-Lc*sin_fi); + G3_2=G3*G3; + sin_ksi=(G1*G2-G3*_fm_sqrt(G2_2+G3_2-G1_2))/(G2_2+G3_2); //x1 (minus + delta) + ksi=asin(sin_ksi); //kąt jarzma + if (smPatykirg2[i]) + smPatykirg2[i]->SetRotateXYZ(vector3(RadToDeg(ksi),0,0)); //obrócenie + jarzma + //1) ksi=-23°, gam= + //2) ksi=10°, gam= + //gam=acos((L2-sin_ksi-Lc*cos_fi)/L); //kąt od poziomu, liczony + względem poziomu + //gam=asin((L1-cos_ksi-Lc*sin_fi)/L); //kąt od poziomu, liczony + względem pionu + gam=atan2((L1-cos(ksi)+Lc*sin_fi),(L2-sin_ksi+Lc*cos_fi)); //kąt od + poziomu + if (smPatykird2[i]) //na razie zabezpieczenie + smPatykird2[i]->SetRotateXYZ(vector3(RadToDeg(-gam-ksi),0,0)); + //obrócenie drążka + mimośrodowego + } + */ + } + + if (physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector + && physics->EnginePowerSource.CollectorParameters.FakePower) { + physics->pantographCircuit.SetRearVoltage(0.95 * physics->EnginePowerSource.MaxVoltage); + physics->pantographCircuit.SetFrontVoltage(0.95 * physics->EnginePowerSource.MaxVoltage); + } +} + +// one pantograph: broken, it only folds down; otherwise the voltage at it, and its arms moved +void TDynamicObject::updatePantograph( int const i, double const fPantCurrent, double &fCurrent, double const dt1 ) +{ + double PantDiff; + TAnimPant *p; // wskaźnik do obiektu danych pantografu + p = pants[i].fParamPants; + if (p->PantWys < 0) + { // patograf został połamany, liczony nie będzie + if (p->fAngleL > p->fAngleL0) + p->fAngleL -= 0.2 * dt1; // nieco szybciej niż jak dla opuszczania + if (p->fAngleL < p->fAngleL0) + p->fAngleL = p->fAngleL0; // kąt graniczny + if (p->fAngleU < M_PI) + p->fAngleU += 0.5 * dt1; // górne się musi ruszać szybciej. + if (p->fAngleU > M_PI) + p->fAngleU = M_PI; + if (i & 1) // zgłoszono, że po połamaniu potrafi zostać zasilanie + physics->pantographCircuit.SetRearVoltage(0.0); + else + physics->pantographCircuit.SetFrontVoltage(0.0); + return; // reszta wtedy nie jest wykonywana + } + PantDiff = p->PantTraction - p->PantWys; // docelowy-aktualny + updatePantographVoltage( i, p, PantDiff, fPantCurrent, fCurrent, dt1 ); + updatePantographMotion( i, p, PantDiff, dt1 ); +} + +// the voltage at one pantograph, from the wire it touches, and the energy drawn through it metered +void TDynamicObject::updatePantographVoltage( int const i, TAnimPant const *p, double const PantDiff, double const fPantCurrent, double &fCurrent, double const dt1 ) +{ + switch (i) // numer pantografu + { // trzeba usunąć to rozróżnienie + case 0: + if (Global.bLiveTraction == false + && p->hvPowerWire == nullptr ) { + // jeśli nie ma drutu, może pooszukiwać + physics->pantographCircuit.SetFrontVoltage(p->PantWys >= 1.2 ? + 0.95 * physics->EnginePowerSource.MaxVoltage : + 0.0); + } + else if( true == physics->pantographs[VehicleEnd::front].is_active + && PantDiff < 0.01 ) // tolerancja niedolegania + { + if (p->hvPowerWire) { + auto const lastvoltage { physics->pantographCircuit.FrontVoltage() }; + // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() + if( lastvoltage == 0.0 ) { + // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply + physics->pantographCircuit.SetFrontVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), 0.0 )); + } + else { + physics->pantographCircuit.SetFrontVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), fPantCurrent )); + if( physics->pantographCircuit.FrontVoltage() > 0.0 ) { + fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) + } + } + // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph + if( lastvoltage == 0.0 + && physics->pantographCircuit.FrontVoltage() > 0.0 ) { + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantUp.offset().z > 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantUp.play( sound_flags::exclusive ); + } + } + } + } + else + physics->pantographCircuit.SetFrontVoltage(0.0); + } + else + physics->pantographCircuit.SetFrontVoltage(0.0); + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.FrontVoltage() * fPantCurrent * dt1 / 3600000.0; + break; + case 1: + if( false == Global.bLiveTraction + && nullptr == p->hvPowerWire ) { + // jeśli nie ma drutu, może pooszukiwać + physics->pantographCircuit.SetRearVoltage(p->PantWys >= 1.2 ? + 0.95 * physics->EnginePowerSource.MaxVoltage : + 0.0); + } + else if ( true == physics->pantographs[VehicleEnd::rear].is_active + && PantDiff < 0.01 ) + { + if (p->hvPowerWire) { + auto const lastvoltage { physics->pantographCircuit.RearVoltage() }; + // TODO: wyliczyć trzeba prąd przypadający na pantograf i wstawić do GetVoltage() + if( lastvoltage == 0.0 ) { + // HACK: retrieve the wire voltage for calculations down the road without blowing up the supply + physics->pantographCircuit.SetRearVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), 0.0 )); + } + else { + physics->pantographCircuit.SetRearVoltage(p->hvPowerWire->VoltageGet( physics->pantographCircuit.SupplyVoltage(), fPantCurrent )); + if( physics->pantographCircuit.RearVoltage() > 0.0 ) { + fCurrent -= fPantCurrent; // taki prąd płynie przez powyższy pantograf (unless it doesn't) + } + } + // TODO: refactor reaction to voltage change to physics as sound event for specific pantograph + if( lastvoltage == 0.0 + && physics->pantographCircuit.RearVoltage() > 0.0 ) { + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantUp.offset().z < 0 ) { + // limit to pantographs located in the rear half of the vehicle + pantograph.sPantUp.play( sound_flags::exclusive ); + } + } + } + } + else + physics->pantographCircuit.SetRearVoltage(0.0); + } + else { +// Global.iPause ^= 2; + physics->pantographCircuit.SetRearVoltage(0.0); + } + ( fPantCurrent > 0.0 ? physics->EnergyMeter.first : physics->EnergyMeter.second ) += physics->pantographCircuit.RearVoltage() * fPantCurrent * dt1 / 3600000.0; + break; + } // pozostałe na razie nie obsługiwane +} + +// the arms of one pantograph raised by the pressure towards the wire, or lowered +void TDynamicObject::updatePantographMotion( int const i, TAnimPant *p, double const PantDiff, double const dt1 ) +{ + double k; // tymczasowy kąt + if( physics->pantographAir.Pressure() > ( + physics->TrainType() == train_type::emu ? + 2.45 : // Ra 2013-12: Niebugocław mówi, że w EZT podnoszą się przy 2.5 + 3.45 ) ) { + // z EXE Kursa + // Ra: wysokość zależy od ciśnienia !!! + pantspeedfactor = 0.015 * physics->pantographAir.Pressure() * dt1; + } + else { + pantspeedfactor = 0.0; + } + if( false == ( physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() ) ) { + pantspeedfactor = 0.0; + } + pantspeedfactor = std::max( 0.0, pantspeedfactor ); + k = p->fAngleL; + if( pantspeedfactor > 0.0 + && physics->pantographs[PantographEnd( i )].is_active )// jeśli ma być podniesiony + { + if (PantDiff > 0.001) // jeśli nie dolega do drutu + { // jeśli poprzednia wysokość jest mniejsza niż pożądana, zwiększyć kąt dolnego + // ramienia zgodnie z ciśnieniem + if (pantspeedfactor > + 0.55 * PantDiff) // 0.55 to około pochodna kąta po wysokości + k += 0.55 * PantDiff; // ograniczenie "skoku" w danej klatce + else + k += pantspeedfactor; // dolne ramię + // jeśli przekroczono kąt graniczny, zablokować pantograf + // (wymaga interwencji pociągu sieciowego) + } + else if (PantDiff < -0.001) { + // drut się obniżył albo pantograf podniesiony za wysoko + // jeśli wysokość jest zbyt duża, wyznaczyć zmniejszenie kąta + // jeśli zmniejszenie kąta jest zbyt duże, przejść do trybu łamania pantografu + // if (PantFrontDiff<-0.05) //skok w dół o 5cm daje złąmanie pantografu + k += 0.4 * PantDiff; // mniej niż pochodna kąta po wysokości + } // jeśli wysokość jest dobra, nic więcej nie liczyć + } + else + { // jeśli ma być na dole + if (k > p->fAngleL0) // jeśli wyżej niż położenie wyjściowe + k -= 0.15 * dt1; // ruch w dół + if (k < p->fAngleL0) + k = p->fAngleL0; // położenie minimalne + } + if (k != p->fAngleL) + { //żeby nie liczyć w kilku miejscach ani gdy nie potrzeba + if (k + p->fAngleU < M_PI) + { // o ile nie został osiągnięty kąt maksymalny + p->fAngleL = k; // zmieniony kąt + // wyliczyć kąt górnego ramienia z wzoru (a)cosinusowego + //=acos((b*cos()+c)/a) + // p->dPantAngleT=acos((1.22*cos(k)+0.535)/1.755); //górne ramię + p->fAngleU = acos((p->fLenL1 * cos(k) + p->fHoriz) / p->fLenU1); // górne ramię + // wyliczyć aktualną wysokość z wzoru sinusowego + // h=a*sin()+b*sin() + // wysokość całości + p->PantWys = p->fLenL1 * sin(k) + p->fLenU1 * sin(p->fAngleU) + p->fHeight; + } + } +} + +// the sound of the pantographs dropping, at the end whose pantograph went down +void TDynamicObject::playPantographDropSounds() +{ + // TBD, TODO: generate sound event during physics update instead? + if( m_pantographsoundstate[ VehicleEnd::front ] != physics->pantographs[ VehicleEnd::front ].is_active ) { + if( physics->pantographs[ VehicleEnd::front ].is_active ) { + // pantograph moving up + // TBD: add a sound? + } + else { + // pantograph dropping + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantDown.offset().z > 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantDown.play( sound_flags::exclusive ); + } + } + } + m_pantographsoundstate[ VehicleEnd::front ] = physics->pantographs[ VehicleEnd::front ].is_active; + } + if( m_pantographsoundstate[ VehicleEnd::rear ] != physics->pantographs[ VehicleEnd::rear ].is_active ) { + if( physics->pantographs[ VehicleEnd::rear ].is_active ) { + // pantograph moving up + // TBD: add a sound? + } + else { + // pantograph dropping + for( auto &pantograph : m_pantographsounds ) { + if( pantograph.sPantDown.offset().z < 0 ) { + // limit to pantographs located in the front half of the vehicle + pantograph.sPantDown.play( sound_flags::exclusive ); + } + } + } + m_pantographsoundstate[ VehicleEnd::rear ] = physics->pantographs[ VehicleEnd::rear ].is_active; + } +} + +// the wipers moved, each on its own timing, out and back to the park position +void TDynamicObject::updateWipers( double const dt1 ) +{ + // wipers + if (dWiperPos.size() > 0) // tylko dla wozow ze zdefiniowanymi wycierakami + { + for (int i = 0; i < dWiperPos.size(); i++) // iteracja po kazdej wycieraczce + { + bool wipersActive; + auto const bytesum = physics->WiperList[physics->WiperSwitchPos()].byteSum; + // rozroznienie kabinowe + if (physics->CabActive == 1) + { + wipersActive = (bytesum & 1 << i) != 0 && physics->lowVoltage.IsBatteryOn(); + } + else if (physics->CabActive == -1) + { + // odwroconie indexow wycieraczek + wipersActive = (bytesum & 1 << dWiperPos.size() - 1 - i) != 0 && physics->lowVoltage.IsBatteryOn(); + } + else { + wipersActive = false; + } + + auto const currentWiperParams = physics->WiperList[workingSwitchPos[i]]; + + wiperOutTimer[i] += dt1; // aktualizujemy zegarek + wiperParkTimer[i] += dt1; // aktualizujemy zegarek + + if (wipersActive || dWiperPos[i] > 0.0) // zeby wrocily do trybu park + { + if (dWiperPos[i] > 0.0 && !wipersActive) // bezwzgledny powrot do zera + { + dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); + } + else { + + if (dWiperPos[i] < 1.0 && !wiperDirection[i] && wiperParkTimer[i] > currentWiperParams.interval) + // go out + { + if (!sWiperFromParkPlayed) + { + sWiperFromPark.play(sound_flags::exclusive); + sWiperFromParkPlayed = true; + } + dWiperPos[i] = std::min(1.0, dWiperPos[i] + 1.f / currentWiperParams.WiperSpeed * dt1); + } + if (dWiperPos[i] > 0.0 && wiperDirection[i] && wiperOutTimer[i] > currentWiperParams.outBackDelay) + // return back + { + if (!sWiperToParkPlayed) + { + sWiperToPark.play(sound_flags::exclusive); + sWiperToParkPlayed = true; + } + dWiperPos[i] = std::max(0.0, dWiperPos[i] - 1.f / currentWiperParams.WiperSpeed * dt1); + } + if (dWiperPos[i] >= 1.0) // we reached end + { + sWiperFromPark.stop(); + sWiperFromParkPlayed = false; + wiperParkTimer[i] = 0.0; + wiperDirection[i] = true; // switch direction + } + if (dWiperPos[i] <= 0.0) + { + // when in park position + sWiperToPark.stop(); + sWiperToParkPlayed = false; + wiperOutTimer[i] = 0.0; + wiperDirection[i] = false; + workingSwitchPos[i] = physics->WiperSwitchPos(); // update configuration + } + + } + } + } + } +} + +// the mirrors folded above their speed or when they may not be out, otherwise unfolded on the side of open doors +void TDynamicObject::updateMirrors( double const dt1 ) +{ + // mirrors + auto const mirrorleft { dMirrorMoveL }; + auto const mirrorright { dMirrorMoveR }; + if( physics->Vel > physics->MirrorVelClose + || physics->CabActive == 0 && activation::mirrors + || physics->MirrorForbidden() ) { + // automatically fold mirrors when above velocity threshold + if( dMirrorMoveL > 0.0 ) { + dMirrorMoveL = std::max( + 0.0, + dMirrorMoveL - 1.0 * dt1 ); + } + if( dMirrorMoveR > 0.0 ) { + dMirrorMoveR = std::max( + 0.0, + dMirrorMoveR - 1.0 * dt1 ); + } + } + else { + // unfold mirror on the side with open doors, if not moving too fast + if( dMirrorMoveL < 1.0 + && true == physics->Doors.instances[VehicleSide::left].open_permit ) { + dMirrorMoveL = std::min( + 1.0, + dMirrorMoveL + 1.0 * dt1 ); + } + if( dMirrorMoveR < 1.0 + && true == physics->Doors.instances[VehicleSide::right].open_permit ) { + dMirrorMoveR = std::min( + 1.0, + dMirrorMoveR + 1.0 * dt1 ); + } + } + play_mirror_sounds( VehicleSide::left, m_mirrormotion[ VehicleSide::left ].update( dMirrorMoveL - mirrorleft ) ); + play_mirror_sounds( VehicleSide::right, m_mirrormotion[ VehicleSide::right ].update( dMirrorMoveR - mirrorright ) ); +} + +void TDynamicObject::pants_up() +{ + TDynamicObject *d = this; + bool isAnyPantUp = false; + while (d) { + for (auto &item : d->physics->pantographs) + { + isAnyPantUp |= item.is_active; + } + d = d->Next(Coupling::control); // pozostałe też + } + d = Prev(Coupling::control); + while (d) { + for (auto &item : d->physics->pantographs) + { + isAnyPantUp |= item.is_active; + } + d = d->Prev(Coupling::control); // w drugą stronę też + } + if (isAnyPantUp) + { + d = this; + while (d) { + d->physics->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + d->physics->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); + d = d->Next(Coupling::control); // pozostałe też + } + d = Prev(Coupling::control); + while (d) { + d->physics->OperatePantographValve(VehicleEnd::front, operation_t::enable, range_t::local); + d->physics->OperatePantographValve(VehicleEnd::rear, operation_t::enable, range_t::local); + d = d->Prev(Coupling::control); // w drugą stronę też + } + } +} + +// McZapkie-040402: liczenie pozycji uwzgledniajac wysokosc szyn itp. +// vector3 TDynamicObject::GetPosition() +//{//Ra: pozycja pojazdu jest liczona zaraz po przesunięciu +// return vPosition; +//}; + +void TDynamicObject::TurnOff() +{ // wyłączenie rysowania submodeli zmiennych dla + // egemplarza pojazdu + btnOn = false; + btCoupler1.TurnOff(); + btCoupler2.TurnOff(); + btCPneumatic1.TurnOff(); + btCPneumatic1r.TurnOff(); + btCPneumatic2.TurnOff(); + btCPneumatic2r.TurnOff(); + btPneumatic1.TurnOff(); + btPneumatic1r.TurnOff(); + btPneumatic2.TurnOff(); + btPneumatic2r.TurnOff(); + btCCtrl1.Turn( false ); + btCCtrl2.Turn( false ); + btCPass1.Turn( false ); + btCPass2.Turn( false ); + m_endsignal12.Turn( false ); + m_endsignal13.Turn( false ); + m_endsignal22.Turn( false ); + m_endsignal23.Turn( false ); + m_endsignals1.Turn( false ); + m_endsignals2.Turn( false ); + m_endtab1.Turn( false ); + m_endtab2.Turn( false ); + m_headlamp11.TurnOff(); + m_headlamp12.TurnOff(); + m_headlamp13.TurnOff(); + m_headlamp21.TurnOff(); + m_headlamp22.TurnOff(); + m_headlamp23.TurnOff(); + m_highbeam12.TurnOff(); + m_highbeam13.TurnOff(); + m_highbeam22.TurnOff(); + m_highbeam23.TurnOff(); + m_headsignal12.TurnOff(); + m_headsignal13.TurnOff(); + m_headsignal22.TurnOff(); + m_headsignal23.TurnOff(); + btMechanik1.Turn( false ); + btMechanik2.Turn( false ); + btShutters1.Turn( false ); + btShutters2.Turn( false ); +}; + +//--------------------------------------------------------------------------- +void TDynamicObject::RadioStop() +{ // zatrzymanie pojazdu + if( Mechanik ) { + // o ile ktoś go prowadzi + if( physics->SecuritySystem.radiostop_available() + && physics->Radio() + && physics->RadioFuse() ) { + // jeśli pojazd ma RadioStop i jest on aktywny + // HACK cast until math types unification + glm::dvec3 pos = static_cast(vPosition); + Mechanik->PutCommand( "Emergency_brake", 1.0, 1.0, &pos, stopRadio ); + // add onscreen notification for human driver + // TODO: do it selectively for the 'local' driver once the multiplayer is in + if( false == Mechanik->AIControllFlag() ) { + ui::Transcripts.AddLine( "!! RADIO-STOP !!", 0.0, 10.0, false ); + } + } + } +}; + +//--------------------------------------------------------------------------- +void TDynamicObject::Damage(char flag) +{ + // the number of the message, as a char (sign extended as the number was) + physics->SetEquipmentFaults(EquipmentFaultSet::FromBits(flag)); +} + +void TDynamicObject::OverheadTrack(float o) +{ // ewentualne wymuszanie jazdy + // bezprądowej z powodu informacji + // w torze + if (ctOwner) // jeśli ma obiekt nadzorujący + { // trzeba zaktualizować mapę flag bitowych jazdy bezprądowej + ctOwner->MarkOverhead( iOverheadMask, o ); + } +}; diff --git a/vehicle/dynamic/vehicletable.cpp b/vehicle/dynamic/vehicletable.cpp new file mode 100644 index 000000000..9d0e42a22 --- /dev/null +++ b/vehicle/dynamic/vehicletable.cpp @@ -0,0 +1,893 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// all the vehicles of the scenery and their update + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + +namespace +{ + + +// a train on the same track this close to the end of the player's train is taken into the physical coupler model [m] +constexpr double coupler_physics_reach { 200.0 }; +// and let go of once none of its vehicles is this close to the player's train [m]; farther than the reach, so that +// the trains don't switch to and fro between the models +constexpr double coupler_physics_release { 500.0 }; + +// the vehicle and those coupled with it, one after the other +std::vector +coupled_train( TDynamicObject *Vehicle ) { + + std::vector train { Vehicle }; + for (auto const direction : VehicleEnds) { + auto *vehicle { Vehicle }; + auto side { direction }; + // a train of more vehicles than are on the tracks would be one coupled into a ring + while( train.size() < 10000 ) { + auto const &physics { *vehicle->physics }; + auto *next { physics.Neighbours[ side ].vehicle }; + if( next == nullptr + || false == physics.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) + || std::ranges::find( train, next ) != train.end() ) { + break; + } + train.emplace_back( next ); + // onwards from the end of the next vehicle away from this one + side = EndOf( 1 - physics.Neighbours[ side ].vehicle_end ); + vehicle = next; + } + } + return train; +} + +// the trains on the same track the player's train is closing in on: those found at its free ends, near enough +std::vector +trains_closing_in( std::vector const &Train ) { + + std::vector trains; + for( auto *vehicle : Train ) { + for (auto const side : VehicleEnds) { + auto const &physics { *vehicle->physics }; + auto const &neighbour { physics.Neighbours[ side ] }; + if( neighbour.vehicle == nullptr + || physics.Couplers[ side ].CouplingFlag.HasAny(Coupling::coupler) + || neighbour.distance > coupler_physics_reach + || std::ranges::find( Train, neighbour.vehicle ) != Train.end() ) { + continue; + } + std::ranges::copy( coupled_train( neighbour.vehicle ), std::back_inserter( trains ) ); + } + } + return trains; +} + +// whether any vehicle of the train is within the distance of any vehicle of the other one +bool +trains_within( std::vector const &Train, std::vector const &Other, double const Distance ) { + + return std::ranges::any_of( Train, [&]( TDynamicObject const *Vehicle ) { + return std::ranges::any_of( Other, [&]( TDynamicObject const *Othervehicle ) { + return glm::distance( Vehicle->GetPosition(), Othervehicle->GetPosition() ) <= Distance; } ); } ); +} + +} // namespace + +// the physical coupler model covers the player's train and the trains it closes in on, on the same track; the others +// keep the legacy model, as the AI drives them in it +void +vehicle_table::update_coupler_physics() const { + + if( false == Global.coupler_physics + || true == Global.coupler_physics_all ) { + return; + } + auto *player { simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr }; + std::vector train; + if( player != nullptr ) { + train = coupled_train( player ); + } + std::unordered_set covered { train.begin(), train.end() }; + for( auto *vehicle : trains_closing_in( train ) ) { + covered.insert( vehicle ); + } + + std::unordered_set checked; + for( auto *vehicle : m_items ) { + if( covered.contains( vehicle ) ) { + vehicle->physics->SetCouplerPhysics(true); + continue; + } + if( false == vehicle->physics->CouplerPhysics() + || checked.contains( vehicle ) ) { + continue; + } + // a train taken in before stays in the model until it's far from the player's one, all of it alike + auto const other { coupled_train( vehicle ) }; + checked.insert( other.begin(), other.end() ); + if( false == trains_within( other, train, coupler_physics_release ) ) { + for( auto *othervehicle : other ) { + othervehicle->physics->SetCouplerPhysics(false); + } + } + } +} + +// legacy method, calculates changes in simulation state over specified time +void +vehicle_table::update( double Deltatime, int Iterationcount ) { + // Ra: w zasadzie to trzeba by utworzyć oddzielną listę taboru do liczenia fizyki + // na którą by się zapisywały wszystkie pojazdy będące w ruchu + // pojazdy stojące nie potrzebują aktualizacji, chyba że np. ktoś im zmieni nastawę hamulca + // oddzielną listę można by zrobić na pojazdy z napędem, najlepiej posortowaną wg typu napędu + // what the update goes through, for the debug panel. the counts are of the last call in the frame + auto &counts { Timer::subsystem.vehicles }; + counts.all = static_cast( m_items.size() ); + counts.enabled = counts.road = counts.ai = counts.active = 0; + counts.kind = {}; + counts.standing = {}; + counts.awake = {}; + counts.steps += static_cast( std::max( Iterationcount, 1 ) ); + // the kind of each vehicle: rail or road, near the camera or farther. the time of each vehicle in the loops below goes to its + // kind, measured from the end of the one before it + static std::vector kinds; + kinds.resize( m_items.size() ); + // road vehicles far from the camera with nobody inside go by one step of the physics in the frame, as long as all the steps + // together (Global.physics_roadlod): their movement goes on, in coarser steps nobody is close enough to tell + // not in a network session: which vehicles go coarse depends on the camera of each machine, so their movement and the draws of + // Random() they make would part ways between the machines. nor with physics.fullphysics off, whose steps are long already: one + // step for all of them would be the time of the whole frame, with the collisions looked at once in it + static std::vector coarse; + coarse.assign( m_items.size(), 0 ); + auto const roadlod { + Global.physics_roadlod + && Global.FullPhysics + && Global.network_servers.empty() + && ( false == Global.network_client.has_value() ) }; + auto const camera { Global.pCamera.Pos }; + for( std::size_t index = 0; index < m_items.size(); ++index ) { + auto const *vehicle { m_items[ index ] }; + auto const road { ( vehicle->physics->CategoryFlag & 2 ) != 0 }; + auto const distant { glm::length2( vehicle->GetPosition() - camera ) > Timer::subsystem.VEHICLE_NEAR * Timer::subsystem.VEHICLE_NEAR }; + kinds[ index ] = static_cast( ( road ? 2 : 0 ) + ( distant ? 1 : 0 ) ); + coarse[ index ] = static_cast( roadlod && road && distant && ( false == vehicle->MechInside ) && ( Iterationcount > 1 ) ); + if( false == vehicle->bEnabled ) { continue; } + ++counts.kind[ kinds[ index ] ]; + auto const *physics { vehicle->physics }; + if( physics->Vel < 0.01 ) { + ++counts.standing[ kinds[ index ] ]; + if( ( false == road ) && physics->PhysicActivation() ) { + // the test of physics::Vehicle::ComputeTotalForce(), part by part + auto const moving = []( neighbour_data const &Neighbour ) { + return ( Neighbour.vehicle != nullptr ) + && ( ( Neighbour.vehicle->physics->Vel > 0.0001 ) || Neighbour.vehicle->physics->accelerating() ); }; + auto &awake { counts.awake }; + ++awake.vehicles; + if( physics->CabActive != 0 ) { ++awake.cab; } + if( physics->Vel > 0.0001 ) { ++awake.speed; } + if( physics->accelerating() ) { ++awake.acceleration; } + if( physics->LastSwitchingTime < 5 ) { ++awake.switching; } + if( physics->is_multiple_unit() ) { ++awake.multipleunit; } + if( moving( physics->Neighbours[ VehicleEnd::front ] ) || moving( physics->Neighbours[ VehicleEnd::rear ] ) ) { ++awake.neighbour; } + } + } + } + auto const lap = [ & ]( std::size_t const Index, std::array &Times, std::chrono::steady_clock::time_point &Mark ) { + auto const now { std::chrono::steady_clock::now() }; + if( Index < kinds.size() ) { + Times[ kinds[ Index ] ].add( std::chrono::duration( now - Mark ).count() ); + } + Mark = now; + }; + for( auto const *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { continue; } + ++counts.enabled; + if( vehicle->physics->CategoryFlag & 2 ) { ++counts.road; } + if( ( vehicle->Mechanik != nullptr ) && vehicle->Mechanik->AIControllFlag() ) { ++counts.ai; } + if( vehicle->physics->PhysicActivation() || vehicle->MechInside ) { ++counts.active; } + } + + Timer::subsystem.vehicles_prepare.start(); + for( auto *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { continue; } + // Ra: zmienić warunek na sprawdzanie pantografów w jednej zmiennej: czy pantografy i czy podniesione + if( vehicle->physics->EnginePowerSource.SourceType == TPowerSource::CurrentCollector ) { + update_traction( vehicle ); + } + vehicle->physics->ComputeConstans(); + vehicle->update_neighbours(); + } + update_coupler_physics(); + Timer::subsystem.vehicles_prepare.stop(); + Timer::subsystem.vehicles_forces.start(); + auto const totaltime { Deltatime * Iterationcount }; // całkowity czas + // the steps of the physics on many threads (Global.performance_multithreading), as many as the work is worth: a thread for each + // STEPS_PER_THREAD steps of vehicles with the physics on, up to all the cores. not in a network session (network.server, + // .client), which keeps the draws of Random() in step across the machines: the threads have engines of their own. the messages + // to external programs (Global.iMultiplayer) don't mind + auto constexpr STEPS_PER_THREAD { 128 }; + std::size_t work { 0 }; + for( std::size_t index = 0; index < m_items.size(); ++index ) { + auto const *vehicle { m_items[ index ] }; + if( vehicle->physics->PhysicActivation() || vehicle->MechInside ) { + work += ( coarse[ index ] != 0 ? 1 : static_cast( std::max( Iterationcount, 1 ) ) ); + } + } + auto const network { ( false == Global.network_servers.empty() ) || Global.network_client.has_value() }; + auto const threads { ( + network ? + 1 : + std::min( worker_pool::capacity(), std::max( 1, ( work + STEPS_PER_THREAD / 2 ) / STEPS_PER_THREAD ) ) ) }; + // what keeps them in one thread, for the debug panel + counts.capacity = static_cast( worker_pool::capacity() ); + counts.singlethread = ( + false == Global.performance_multithreading ? std::string{ "performance.multithreading off" } : + network ? std::string{ "network session" } : + threads <= 1 ? std::string{ "too little work" } : + std::string{} ); + counts.threads = 1; + auto const parallel { ( threads > 1 ) && update_steps_parallel( Deltatime, Iterationcount, coarse, threads ) }; + if( parallel ) { + counts.threads = static_cast( threads ); + } + else { + if( threads > 1 ) { + counts.singlethread = "a vehicle coupled with one it doesn't see"; + } + auto mark { std::chrono::steady_clock::now() }; + if( Iterationcount > 1 ) { + // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja + for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { + std::size_t index { 0 }; + for( auto *vehicle : m_items ) { + if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { + vehicle->UpdateForce( Deltatime ); + } + lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); + } + index = 0; + for( auto *vehicle : m_items ) { + if( ( index >= coarse.size() ) || ( coarse[ index ] == 0 ) ) { + vehicle->FastUpdate( Deltatime ); + } + lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); + } + update_brake_pipes( Deltatime ); + } + } + { + std::size_t index { 0 }; + for( auto *vehicle : m_items ) { + // the vehicles going by one step take it with the time of all of them + auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; + vehicle->UpdateForce( coarsestep ? totaltime : Deltatime ); + lap( index++, Timer::subsystem.vehicles_forces_kind, mark ); + } + } + } + Timer::subsystem.vehicles_forces.stop(); + + update_off_track_contacts( totaltime ); + + Timer::subsystem.vehicles_update.start(); + { + std::size_t index { 0 }; + auto mark { std::chrono::steady_clock::now() }; + for( auto *vehicle : m_items ) { + auto const coarsestep { ( index < coarse.size() ) && ( coarse[ index ] != 0 ) }; + // Ra 2015-01: tylko tu przelicza sieć trakcyjną + vehicle->Update( coarsestep ? totaltime : Deltatime, totaltime ); + lap( index++, Timer::subsystem.vehicles_update_kind, mark ); + } + } + update_brake_pipes( Deltatime ); + Timer::subsystem.vehicles_update.stop(); + + // jeśli jest coś do usunięcia z listy, to trzeba na końcu + erase_disabled(); + + // the odometers are saved now and then, a crash doesn't lose more than the last minute + m_odometersavetimer += totaltime; + if( m_odometersavetimer >= 60.0 ) { + save_odometers(); + } +} +namespace +{ + + +// the body of the vehicle as it stands, for the contacts: off the track by its motion, on the track upright on it +derail_motion::footprint footprint_of( TDynamicObject const &Vehicle ) { + + auto const &physics { *Vehicle.physics }; + derail_motion::pose pose; + if( physics.OffTrack.active() ) { + pose = physics.OffTrack.current(); + } + else { + pose.position = Vehicle.GetPosition(); + pose.front = Vehicle.VectorFront(); + pose.left = Vehicle.VectorLeft(); + pose.up = Vehicle.VectorUp(); + } + auto const &shape { physics.OffTrack.shape() }; + return derail_motion::footprint_of( + pose, physics.Dim.L, + physics.OffTrack.active() ? shape.width : ( physics.Dim.W > 0.5 ? physics.Dim.W : 3.0 ), + physics.OffTrack.active() ? shape.height : ( physics.Dim.H > 2.0 ? physics.Dim.H : 4.0 ) ); +} + +// the vehicle as a body in a contact +derail_motion::contact_body contact_body_of( TDynamicObject const &Vehicle ) { + + auto const &physics { *Vehicle.physics }; + derail_motion::contact_body body; + body.mass = physics.TotalMass(); + if( physics.OffTrack.active() ) { + body.base = physics.OffTrack.base(); + body.velocity = physics.OffTrack.velocity(); + body.yaw_rate = physics.OffTrack.yaw_rate(); + body.gyration = physics.OffTrack.gyration(); + } + else { + // on the rails it goes along them only + glm::dvec3 const front { Vehicle.VectorFront().x, 0.0, Vehicle.VectorFront().z }; + auto const length { glm::length( front ) }; + body.guided = true; + body.guide = length > 1e-6 ? front / length : glm::dvec3 { 0.0, 0.0, 1.0 }; + body.base = Vehicle.GetPosition(); + body.velocity = body.guide * physics.V(); + } + return body; +} + +// how the two came to overlap, for the log +std::string_view overlap_kind( TDynamicObject const &First, TDynamicObject const &Second ) { + + auto const offtrack { First.physics->OffTrack.active() && Second.physics->OffTrack.active() }; + for (auto const end : VehicleEnds) { + if( First.physics->Couplers[ end ].Connected == Second.physics + && First.physics->Couplers[ end ].CouplingFlag != Coupling::none ) { + return offtrack ? "coupled, both off the track" : "coupled, one on the rails"; + } + if( First.physics->Neighbours[ end ].vehicle == &Second ) { + return offtrack ? "neighbours, both off the track" : "neighbours, one on the rails"; + } + } + return offtrack ? "not neighbours, both off the track" : "not neighbours, one on the rails"; +} + +} // namespace + +void +vehicle_table::update_off_track_contacts( double const Deltatime ) { + + if( Global.derailment != global_settings::derailment_model::physical || Deltatime <= 0.0 ) { + return; + } + // by their places in the table: the order the pairs are taken in is the same in every run + std::vector offtrack; + for( std::size_t index = 0; index < m_items.size(); ++index ) { + if( m_items[ index ]->bEnabled && m_items[ index ]->physics->OffTrack.active() ) { + offtrack.push_back( index ); + } + } + if( offtrack.empty() ) { + return; + } + auto const started { off_track_clock::now() }; + auto deepest { 0.0 }; + std::string deepestpair; + auto resting { true }; + for( auto const place : offtrack ) { + auto *vehicle { m_items[ place ] }; + resting = resting && vehicle->physics->OffTrack.at_rest(); + auto const print { footprint_of( *vehicle ) }; + auto const reach { std::hypot( print.half_length, print.half_width ) }; + for( std::size_t otherplace = 0; otherplace < m_items.size(); ++otherplace ) { + auto *other { m_items[ otherplace ] }; + if( otherplace == place || false == other->bEnabled ) { + continue; + } + // each pair of two off the track once + auto const otheroff { other->physics->OffTrack.active() }; + if( otheroff && otherplace < place ) { + continue; + } + // the bounding circles first + auto const apart { other->GetPosition() - vehicle->GetPosition() }; + auto const otherreach { 0.5 * other->physics->Dim.L + std::max( other->physics->Dim.W, other->physics->Dim.H ) }; + if( glm::length( glm::dvec3 { apart.x, 0.0, apart.z } ) > reach + otherreach + 1.0 ) { + continue; + } + auto const otherprint { footprint_of( *other ) }; + auto const hit { derail_motion::collide( print, otherprint ) }; + if( false == hit.has_value() ) { + continue; + } + if( hit->depth > deepest ) { + deepest = hit->depth; + deepestpair = std::format( "{} and {}, {}", vehicle->physics->Name, other->physics->Name, overlap_kind( *vehicle, *other ) ); + } + auto const body { contact_body_of( *vehicle ) }; + auto const otherbody { contact_body_of( *other ) }; + auto const impulse { derail_motion::contact_impulse( *hit, body, otherbody ) }; + // the one off the track: kicked, and moved out of the other one (half of the way when both are off it) + auto const [ velocity, yawrate ] { derail_motion::impulse_change( body, -impulse, hit->point ) }; + auto &motion { vehicle->physics->OffTrack }; + auto const share { otheroff ? 0.5 : 1.0 }; + auto const correction { derail_motion::contact_correction * std::max( 0.0, hit->depth - derail_motion::contact_slop ) }; + if( glm::length( impulse ) > 0.0 ) { + motion.kick( velocity, yawrate ); + vehicle->physics->SetV(motion.speed()); + } + if( correction > 0.0 ) { + motion.nudge( -hit->normal * ( share * correction ) ); + vehicle->place_off_track(); + } + if( otheroff ) { + auto const [ othervelocity, otheryawrate ] { derail_motion::impulse_change( otherbody, impulse, hit->point ) }; + auto &othermotion { other->physics->OffTrack }; + if( glm::length( impulse ) > 0.0 ) { + othermotion.kick( othervelocity, otheryawrate ); + other->physics->SetV(othermotion.speed()); + } + if( correction > 0.0 ) { + othermotion.nudge( hit->normal * ( share * correction ) ); + other->place_off_track(); + } + continue; + } + // one on the rails: along them into its speed, across them on its wheels, as a coupling pulls them off + auto &otherPhysics { *other->physics }; + otherPhysics.SetV( otherPhysics.V() + glm::dot( impulse, otherbody.guide ) / std::max( otherPhysics.TotalMass(), 1.0 ) ); + if( otherPhysics.DamageFlag.HasAll(VehicleDamage::derailed) ) { + continue; + } + glm::dvec3 const otherleft { otherbody.guide.z, 0.0, -otherbody.guide.x }; + auto const across { glm::dot( impulse, otherleft ) / Deltatime }; + auto const mass { otherPhysics.TotalMass() - otherPhysics.Mred() }; + auto const ratio { derail_motion::pull_ratio( std::abs( across ), 0.5 * std::numbers::pi, mass, otherPhysics.NAxles() ) }; + // held over the window of the climbing as the bodies slide along each other, or a hit three times as hard + // at once: the wheels jump the rail + auto const sliding { glm::length( derail_motion::velocity_at( body, hit->point ) - otherbody.velocity ) * Deltatime }; + if( other->m_struck.update( ratio >= derailment::climbing_limit, sliding ) || ratio >= 3.0 * derailment::climbing_limit ) { + otherPhysics.pull_off( + across >= 0.0 ? 1 : -1, + mass > 0.0 ? std::abs( across ) / mass : 0.0, + std::format( "Y/Q {:.2f} from {} running into it, {:.0f} kN across", ratio, vehicle->physics->Name, std::abs( across ) / 1000.0 ) ); + other->m_struck.reset(); + } + } + } + // the log: every second the most the bodies overlapped by, once more when all of them are at rest + if( deepest > m_overlapmost ) { + m_overlapmost = deepest; + m_overlappair = deepestpair; + } + m_overlapdue -= Deltatime; + if( ( m_overlapdue <= 0.0 && false == resting ) || ( resting && false == m_overlaplogged ) ) { + WriteLog( std::format( + "derailment: the bodies overlap by up to {:.2f} m{} over the last second, {:.2f} m now{}", + m_overlapmost, m_overlapmost > 0.0 ? " (" + m_overlappair + ")" : std::string {}, deepest, resting ? ", all at rest" : "" ) ); + m_overlapmost = 0.0; + m_overlappair.clear(); + m_overlapdue = 1.0; + m_overlaplogged = resting; + } + if( false == resting ) { + m_overlaplogged = false; + } + auto const took { vehicle_dynamic::seconds_since( started ) }; + if( took > off_track_slow ) { + ErrorLog( std::format( "derailment: warning: the contacts of {} vehicles off the track took {:.0f} ms", offtrack.size(), took * 1000.0 ) ); + } +} + +std::shared_ptr +vehicle_table::off_track_terrain( glm::dvec2 const &Min, glm::dvec2 const &Max ) { + + std::erase_if( m_offtrackterrains, []( auto const &Terrain ) { return Terrain.expired(); } ); + for( auto const &terrain : m_offtrackterrains ) { + if( auto shared { terrain.lock() }; shared != nullptr && shared->covers( Min, Max ) ) { + return shared; + } + } + return {}; +} + +void +vehicle_table::share_off_track_terrain( std::shared_ptr const &Terrain ) { + + if( Terrain != nullptr ) { + m_offtrackterrains.emplace_back( Terrain ); + } +} + +// the air exchange through the brake and main reservoir hoses of the vehicles which stepped their physics, after all of them did +void +vehicle_table::update_brake_pipes( double const Deltatime ) { + + m_brakepipes.clear(); + for( auto *vehicle : m_items ) { + if( ( true == vehicle->physics->brakePipe.CouplersPending() ) + || ( true == vehicle->physics->mainPipe.CouplersPending() ) ) { + m_brakepipes.push_back( vehicle->physics ); + } + } + physics::Vehicle::UpdatePipeCouplers( m_brakepipes, Deltatime ); +} + +// records the odometer states of the vehicles and saves them for the next sessions (eu07/maszyna#72) +void +vehicle_table::save_odometers() { + + m_odometersavetimer = 0.0; + auto &odometers { odometer::states() }; + for( auto const *vehicle : m_items ) { + if( vehicle->physics != nullptr ) { + odometer::record( odometers, vehicle->name(), vehicle->physics->HasDriverCab(), vehicle->physics->Odometer ); + } + } + odometer::save(); +} + +// the steps of the physics of vehicle_table::update() (UpdateForce() and FastUpdate() of each vehicle, Iterationcount times) on up +// to Threads threads of worker_pool. a step acts on the vehicle itself, on the ones coupled with it, and on the ones seen ahead or +// behind it (CollisionDetect() changes the speed of the other one); the movement along the tracks, the events and the sounds wait +// for Update(). so the vehicles are put in groups which act on nothing outside them, and each group goes through all its steps in +// one thread, its vehicles in their order, the groups at once: what doing them one by one gives. the groups of vehicles exchanging +// their load, which can load the models of it, are done in the main thread. Coarse: as in update(). returns false, having done +// nothing, when a vehicle is coupled with one it doesn't see next to it, which the groups don't account for +bool +vehicle_table::update_steps_parallel( double const Deltatime, int const Iterationcount, std::vector const &Coarse, std::size_t const Threads ) { + + auto const itemcount { m_items.size() }; + for( std::size_t index = 0; index < itemcount; ++index ) { + m_items[ index ]->m_tableindex = static_cast( index ); + } + // the groups, by joining the vehicles with the ones they act on. the coupled ones are those next to them + m_groupparent.resize( itemcount ); + std::iota( std::begin( m_groupparent ), std::end( m_groupparent ), 0u ); + auto const root = [ this ]( std::uint32_t Index ) { + while( m_groupparent[ Index ] != Index ) { + m_groupparent[ Index ] = m_groupparent[ m_groupparent[ Index ] ]; + Index = m_groupparent[ Index ]; + } + return Index; }; + for( std::size_t index = 0; index < itemcount; ++index ) { + auto const *physics { m_items[ index ]->physics }; + for (auto const end : VehicleEnds) { + auto const *neighbour { physics->Neighbours[ end ].vehicle }; + if( ( physics->Couplers[ end ].Connected != nullptr ) + && ( ( neighbour == nullptr ) || ( neighbour->physics != physics->Couplers[ end ].Connected ) ) ) { + return false; + } + if( neighbour == nullptr ) { continue; } + auto const other { neighbour->m_tableindex }; + if( ( other >= itemcount ) || ( m_items[ other ] != neighbour ) ) { + // not in the table, shouldn't happen + return false; + } + auto const left { root( static_cast( index ) ) }; + auto const right { root( other ) }; + if( left != right ) { + m_groupparent[ std::max( left, right ) ] = std::min( left, right ); + } + } + } + auto constexpr none { std::numeric_limits::max() }; + m_groupof.assign( itemcount, none ); + std::size_t groupcount { 0 }; + for( std::size_t index = 0; index < itemcount; ++index ) { + auto &group { m_groupof[ root( static_cast( index ) ) ] }; + if( group == none ) { + group = static_cast( groupcount++ ); + if( m_groups.size() < groupcount ) { m_groups.emplace_back(); } + m_groups[ group ].clear(); + } + m_groups[ group ].push_back( static_cast( index ) ); + } + // the groups done in the main thread, and the others largest first, for the threads to end close to one another + m_threadgroups.clear(); + m_maingroups.clear(); + std::size_t largest { 0 }; + for( std::size_t group = 0; group < groupcount; ++group ) { + largest = std::max( largest, m_groups[ group ].size() ); + auto const loading { std::any_of( + std::begin( m_groups[ group ] ), std::end( m_groups[ group ] ), + [ this ]( std::uint32_t const Index ) { + auto const *vehicle { m_items[ Index ] }; + return ( vehicle->physics->LoadStatus() != 0 ) || ( vehicle->LoadExchangeTime() > 0.f ); } ) }; + ( loading ? m_maingroups : m_threadgroups ).push_back( static_cast( group ) ); + } + std::sort( + std::begin( m_threadgroups ), std::end( m_threadgroups ), + [ this ]( std::uint32_t const Left, std::uint32_t const Right ) { + return m_groups[ Left ].size() > m_groups[ Right ].size(); } ); + auto &counts { Timer::subsystem.vehicles }; + counts.groups = static_cast( groupcount ); + counts.largestgroup = static_cast( largest ); + counts.maingroups = static_cast( m_maingroups.size() ); + + // all the steps of a group, in the order update() makes them + auto const totaltime { Deltatime * Iterationcount }; + auto const coarse = [ & ]( std::uint32_t const Index ) { + return ( Index < Coarse.size() ) && ( Coarse[ Index ] != 0 ); }; + // the draws of Random() a group makes come from an engine of its own, seeded from the run's engine and the group: the same in + // every run of a seed, whichever thread takes the group (the engines of the threads are seeded at random) + auto const seed { static_cast( Global.random_engine() ) }; + auto const steps = [ & ]( std::uint32_t const Group ) { + auto const &members { m_groups[ Group ] }; + std::seed_seq groupseed { seed, members.front() }; + std::mt19937 engine { groupseed }; // NOSONAR: randomness of the simulation, not of anything security-relevant + auto *const threadengine { thread_random_engine() }; + set_thread_random_engine( &engine ); + // the hoses join only vehicles coupled with each other, which are in one group: the air they carry is exchanged + // within the group after each step, as update_brake_pipes() does for all the vehicles in one thread + std::vector pipes; + if( Iterationcount > 1 ) { + // ABu: ponizsze wykonujemy tylko jesli wiecej niz jedna iteracja + for( int iteration = 0; iteration < Iterationcount - 1; ++iteration ) { + for( auto const index : members ) { + if( false == coarse( index ) ) { m_items[ index ]->UpdateForce( Deltatime ); } + } + for( auto const index : members ) { + if( false == coarse( index ) ) { m_items[ index ]->FastUpdate( Deltatime ); } + } + pipes.clear(); + for( auto const index : members ) { + auto *physics { m_items[ index ]->physics }; + if( physics->brakePipe.CouplersPending() || physics->mainPipe.CouplersPending() ) { + pipes.push_back( physics ); + } + } + physics::Vehicle::UpdatePipeCouplers( pipes, Deltatime ); + } + } + for( auto const index : members ) { + // the vehicles going by one step take it with the time of all of them + m_items[ index ]->UpdateForce( coarse( index ) ? totaltime : Deltatime ); + } + set_thread_random_engine( threadengine ); }; + + Workers().run( + m_threadgroups.size(), Threads, + [ & ]( std::size_t const Group ) { + steps( m_threadgroups[ Group ] ); } ); + for( auto const group : m_maingroups ) { + steps( group ); + } + return true; +} + +// legacy method, checks for presence and height of traction wire for specified vehicle +void +vehicle_table::update_traction( TDynamicObject *Vehicle ) { + auto const vFront = Vehicle->VectorFront(); // wektor normalny dla płaszczyzny ruchu pantografu + auto const vUp = Vehicle->VectorUp(); // wektor pionu pudła (pochylony od pionu na przechyłce) + auto const vLeft = Vehicle->VectorLeft(); // wektor odległości w bok (odchylony od poziomu na przechyłce) + auto const position = Vehicle->GetPosition(); // współrzędne środka pojazdu + + for( int pantographindex = 0; pantographindex < Vehicle->iAnimType[ ANIM_PANTS ]; ++pantographindex ) { + // pętla po pantografach + auto *pantograph { Vehicle->pants[ pantographindex ].fParamPants }; + if( true == Vehicle->physics->pantographs[ pantographindex ].is_active ) { + // jeśli pantograf podniesiony + auto const pant0 { position + vLeft * pantograph->vPos.z + vUp * pantograph->vPos.y + vFront * pantograph->vPos.x }; + if( pantograph->hvPowerWire != nullptr ) { + // jeżeli znamy drut z poprzedniego przebiegu + for( int attempts = 0; attempts < 30; ++attempts ) { + // sanity check. shouldn't happen in theory, but did happen in practice + if( pantograph->hvPowerWire == nullptr ) { break; } + + // powtarzane aż do znalezienia odpowiedniego odcinka na liście dwukierunkowej + if( pantograph->hvPowerWire->iLast & 0x3 ) { + // dla ostatniego i przedostatniego przęsła wymuszamy szukanie innego + // nie to, że nie ma, ale trzeba sprawdzić inne + pantograph->hvPowerWire = nullptr; + break; + } + if( pantograph->hvPowerWire->hvParallel ) { + // jeśli przęsło tworzy bieżnię wspólną, to trzeba sprawdzić pozostałe + // nie to, że nie ma, ale trzeba sprawdzić inne + pantograph->hvPowerWire = nullptr; + break; + } + // obliczamy wyraz wolny równania płaszczyzny (to miejsce nie jest odpowienie) + // podstawiamy równanie parametryczne drutu do równania płaszczyzny pantografu + // TODO: investigate this routine with reardriver/negative speed, does it picks the right wire? + auto const fRaParam = + -( glm::dot( pantograph->hvPowerWire->pPoint1, vFront ) - glm::dot( pant0, vFront ) ) + / glm::dot( pantograph->hvPowerWire->vParametric, vFront ); + + if( fRaParam < -0.001 ) { + // histereza rzędu 7cm na 70m typowego przęsła daje 1 promil + pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 0 ]; + continue; + } + if( fRaParam > 1.001 ) { + pantograph->hvPowerWire = pantograph->hvPowerWire->hvNext[ 1 ]; + continue; + } + // jeśli t jest w przedziale, wyznaczyć odległość wzdłuż wektorów vUp i vLeft + // punkt styku płaszczyzny z drutem (dla generatora łuku el.) + auto const vStyk { pantograph->hvPowerWire->pPoint1 + fRaParam * pantograph->hvPowerWire->vParametric }; + auto const vGdzie { vStyk - pant0 }; // wektor + // odległość w pionie musi być w zasięgu ruchu "pionowego" pantografu + // musi się mieścić w przedziale ruchu pantografu + auto const fVertical { glm::dot( vGdzie, vUp ) }; + // odległość w bok powinna być mniejsza niż pół szerokości pantografu + // to się musi mieścić w przedziale zależnym od szerokości pantografu + auto const fHorizontal { std::abs( glm::dot( vGdzie, vLeft ) ) - pantograph->fWidth }; + // jeśli w pionie albo w bok jest za daleko, to dany drut jest nieużyteczny + if( fHorizontal <= 0.0 ) { + // koniec pętli, aktualny drut pasuje + pantograph->PantTraction = fVertical; + break; + } + else { + // the wire is outside contact area and as of now we don't have good detection of parallel sections + // as such there's no guaratee there isn't parallel section present. + // therefore we don't bother checking if the wire is still within range of guide horns + // but simply force area search for potential better option + pantograph->hvPowerWire = nullptr; + break; + } + } + } + + if( pantograph->hvPowerWire == nullptr ) { + // look in the region for a suitable traction piece if we don't already have any + simulation::Region->update_traction( Vehicle, pantographindex ); + } + + if( pantograph->hvPowerWire == nullptr + && false == Global.bLiveTraction ) { + // jeśli drut nie znaleziony ale można oszukiwać to dajemy coś tam dla picu + Vehicle->pants[ pantographindex ].fParamPants->PantTraction = 1.4; + } + } + else { + // pantograph is down + pantograph->hvPowerWire = nullptr; + } + } +} + +// legacy method, sends list of vehicles over network +void +vehicle_table::DynamicList( bool const Onlycontrolled ) const { + // odesłanie nazw pojazdów dostępnych na scenerii (nazwy, szczególnie wagonów, mogą się powtarzać!) + for( auto const *vehicle : m_items ) { + if( false == Onlycontrolled + || vehicle->Mechanik != nullptr ) { + // same nazwy pojazdów + multiplayer::WyslijString( vehicle->asName, 6 ); + } + } + // informacja o końcu listy + multiplayer::WyslijString( "none", 6 ); +} + +// maintenance; removes from tracks consists with vehicles marked as disabled +bool +vehicle_table::erase_disabled() { + + if( false == TDynamicObject::bDynamicRemove ) { return false; } + + // go through the list and retrieve vehicles scheduled for removal... + type_sequence disabledvehicles; + for( auto *vehicle : m_items ) { + if( false == vehicle->bEnabled ) { + disabledvehicles.emplace_back( vehicle ); + } + } + // ...now propagate removal flag through affected consists... + for( auto *vehicle : disabledvehicles ) { + TDynamicObject *coupledvehicle { vehicle }; + while( ( coupledvehicle = coupledvehicle->Next() ) != nullptr ) { + coupledvehicle->bEnabled = false; + } + // (try to) run propagation in both directions, it's simpler than branching based on direction etc + coupledvehicle = vehicle; + while( ( coupledvehicle = coupledvehicle->Prev() ) != nullptr ) { + coupledvehicle->bEnabled = false; + } + } + // ...then actually remove all disabled vehicles... + auto vehicleiter = std::begin( m_items ); + while( vehicleiter != std::end( m_items ) ) { + + auto *vehicle { *vehicleiter }; + + if( true == vehicle->bEnabled ) { + ++vehicleiter; + } + else { + // the distance the vehicle ran goes in the odometer store now, it doesn't depend on the vehicle being + // kept on the list until the next save (eu07/maszyna#72) + if( vehicle->physics != nullptr ) { + odometer::record( odometer::states(), vehicle->name(), vehicle->physics->HasDriverCab(), vehicle->physics->Odometer ); + } + if( vehicle->MyTrack != nullptr + && true == vehicle->MyTrack->RemoveDynamicObject(vehicle) ) { + vehicle->MyTrack = nullptr; + } + if( simulation::Train != nullptr + && simulation::Train->Dynamic() == vehicle ) { + // clear potential train binding + // TBD, TODO: kill vehicle sounds + simulation::Train = nullptr; + } + simulation::Trains.purge(vehicle->name()); + // remove potential entries in the light array + simulation::Lights.remove( vehicle ); + simulation::Blackbox.vehicle_removed( vehicle ); +/* + // finally get rid of the vehicle and its record themselves + // BUG: deleting the vehicle leaves dangling pointers in event->Activator and potentially elsewhere + // TBD, TODO: either mark 'dead' vehicles with additional flag, or delete the references as well + SafeDelete( vehicle ); + vehicleiter = m_items.erase( vehicleiter ); +*/ + ++vehicleiter; // NOTE: instead of the erase in the disabled section + } + } + // ...and call it a day + TDynamicObject::bDynamicRemove = false; + + return true; +} diff --git a/vehicle/dynamic/visual.cpp b/vehicle/dynamic/visual.cpp new file mode 100644 index 000000000..7beef31e2 --- /dev/null +++ b/vehicle/dynamic/visual.cpp @@ -0,0 +1,788 @@ +/* +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/. +*/ +/* + MaSzyna EU07 locomotive simulator + Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others + +*/ + +// how a vehicle shows: its model, its sway and its shake + +#include "stdafx.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "vehicle/lightsprogrammer.h" +#include "simulation/simulation.h" +#include "simulation/blackboxrecorder.h" +#include "rendering/lightarray.h" +#include "vehicle/Camera.h" +#include "vehicle/Train.h" +#include "vehicle/odometer.h" +#include "vehicle/pulleemode.h" +#include "vehicle/Driver.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/Timer.h" +#include "utilities/workerpool.h" +#include "utilities/Logs.h" +#include "utilities/glmHelpers.h" +#include "Console.h" +#include "world/Traction.h" +#include "audio/sound.h" +#include "model/MdlMngr.h" +#include "model/Model3d.h" +#include "vehicle/doorwings.h" +#include "vehicle/driverfigure.h" +#include "rendering/renderer.h" +#include "editor/editorTerrainStreamer.hpp" +#include "application/uitranscripts.h" +#include "input/messaging.h" +#include "application/application.h" +#include "vehicle/Driver.h" +#include "vehicle/dynamic/internal.h" + + +void TDynamicObject::ABuSetModelShake(glm::dvec3 mShake) +{ + modelShake = mShake; +}; + +// ABu 29.01.05 przeklejone z render i renderalpha: ********************* +void TDynamicObject::ABuLittleUpdate(double ObjSqrDist) +{ // ABu290105: pozbierane i uporzadkowane powtarzajace + // sie rzeczy z Render i RenderAlpha + // dodatkowy warunek, if (ObjSqrDist<...) zeby niepotrzebnie nie zmianiec w + // obiektach, + // ktorych i tak nie widac + // NBMX wrzesien, MC listopad: zuniwersalnione + btnOn = false; // czy przywrócić stan domyślny po renderowaniu + + // the submodels set below are shared with whatever else is drawn with the same models + for( auto *model : { mdModel, mdLoad, mdLowPolyInt, mdKabina } ) { + if( model != nullptr ) { + model->state_changed(); + } + } + for( auto *model : mdAttachments ) { + if( model != nullptr ) { + model->state_changed(); + } + } + + if (mdLoad) // tymczasowo ładunek na poziom podłogi + if (vFloor.z > 0.0) + mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); + + // model jest współdzielony przez pojazdy, a pora roku może się zmienić w trakcie symulacji + if (Global.UpdateMaterials) + on_season_update(); + + if (ObjSqrDist < 400 * 400 ) // gdy bliżej niż 400m + { + for( auto &animation : pAnimations ) { + // wykonanie kolejnych animacji + if( ObjSqrDist < animation.fMaxDist + && animation.yUpdate ) { + // jeśli zdefiniowana funkcja aktualizacja animacji (położenia submodeli + animation.yUpdate( &animation ); + } + } + update_slottedlevers(); + + if( mdModel != nullptr + && ObjSqrDist < 50 * 50 ) { + // gdy bliżej niż 50m + // ABu290105: rzucanie pudlem + // te animacje wymagają bananów w modelach! + mdModel->GetSMRoot()->SetTranslate(modelShake); + if (mdKabina) + mdKabina->GetSMRoot()->SetTranslate(modelShake); + if (mdLoad) + mdLoad->GetSMRoot()->SetTranslate(modelShake + vFloor); + if (mdLowPolyInt) + mdLowPolyInt->GetSMRoot()->SetTranslate(modelShake); + // ABu: koniec rzucania + // ABu011104: liczenie obrotow wozkow + ABuBogies(); + // Mczapkie-100402: rysowanie lub nie - sprzegow + // ABu-240105: Dodatkowy warunek: if (...).Render, zeby rysowal tylko jeden z polaczonych sprzegow + // display _on if connected with another vehicle and the coupling owner (render flag) + // display _xon if connected with another vehicle and not the coupling owner + // display _xon if not connected, but equipped with coupling adapter + // display _off if not connected, not equipped with coupling adapter or if _xon model is missing + if( physics->Couplers[ VehicleEnd::front ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( physics->Couplers[ VehicleEnd::front ].Render ) { + btCoupler1.TurnOn(); + } + else { + btCoupler1.TurnxOnWithOffAsFallback(); + } + btnOn = true; + } + else { + if( true == physics->Couplers[ VehicleEnd::front ].has_adapter() ) { + btCoupler1.TurnxOnWithOffAsFallback(); + btnOn = true; + } + } + if( physics->Couplers[ VehicleEnd::rear ].CouplingFlag.HasAll(Coupling::coupler) ) { + if( physics->Couplers[ VehicleEnd::rear ].Render ) { + btCoupler2.TurnOn(); + } + else { + btCoupler2.TurnxOnWithOffAsFallback(); + } + btnOn = true; + } + else { + if( true == physics->Couplers[ VehicleEnd::rear ].has_adapter() ) { + btCoupler2.TurnxOnWithOffAsFallback(); + btnOn = true; + } + } + //******************************************************************************** + // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie + // 'render' - juz + // nie + // przewody powietrzne, yB: decyzja na podstawie polaczen w t3d + if (Global.bnewAirCouplers) + { + SetPneumatic(false, false); // wczytywanie z t3d ulozenia wezykow + SetPneumatic(true, false); // i zapisywanie do zmiennej + SetPneumatic(true, true); // ktore z nich nalezy + SetPneumatic(false, true); // wyswietlic w tej klatce + + if (physics->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) + { + switch (cp1) + { + case 1: + btCPneumatic1.TurnOn(); + break; + case 2: + btCPneumatic1.TurnxOn(); + break; + case 3: + btCPneumatic1r.TurnxOn(); + break; + case 4: + btCPneumatic1r.TurnOn(); + break; + } + btnOn = true; + } + + if (physics->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + { + switch (cp2) + { + case 1: + btCPneumatic2.TurnOn(); + break; + case 2: + btCPneumatic2.TurnxOn(); + break; + case 3: + btCPneumatic2r.TurnxOn(); + break; + case 4: + btCPneumatic2r.TurnOn(); + break; + } + btnOn = true; + } + + // przewody zasilajace, j.w. (yB) + if (physics->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::mainHose)) + { + switch (sp1) + { + case 1: + btPneumatic1.TurnOn(); + break; + case 2: + btPneumatic1.TurnxOn(); + break; + case 3: + btPneumatic1r.TurnxOn(); + break; + case 4: + btPneumatic1r.TurnOn(); + break; + } + btnOn = true; + } + + if (physics->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::mainHose)) + { + switch (sp2) + { + case 1: + btPneumatic2.TurnOn(); + break; + case 2: + btPneumatic2.TurnxOn(); + break; + case 3: + btPneumatic2r.TurnxOn(); + break; + case 4: + btPneumatic2r.TurnOn(); + break; + } + btnOn = true; + } + } + //*********************************************************************************/ + else // po staremu ABu'oewmu + { + // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie + // 'render' + if (physics->Couplers[VehicleEnd::front].CouplingFlag.HasAll(Coupling::brakeHose)) + { + if (physics->Couplers[VehicleEnd::front].Render) + btCPneumatic1.TurnOn(); + else + btCPneumatic1r.TurnOn(); + btnOn = true; + } + + if (physics->Couplers[VehicleEnd::rear].CouplingFlag.HasAll(Coupling::brakeHose)) + { + if (physics->Couplers[VehicleEnd::rear].Render) + btCPneumatic2.TurnOn(); + else + btCPneumatic2r.TurnOn(); + btnOn = true; + } + + // przewody powietrzne j.w., ABu: decyzja czy rysowac tylko na podstawie + // 'render' + // //yB - zasilajace + if (physics->Couplers[0].CouplingFlag.HasAll(Coupling::mainHose)) + { + if (physics->Couplers[0].Render) + btPneumatic1.TurnOn(); + else + btPneumatic1r.TurnOn(); + btnOn = true; + } + + if (physics->Couplers[1].CouplingFlag.HasAll(Coupling::mainHose)) + { + if (physics->Couplers[1].Render) + btPneumatic2.TurnOn(); + else + btPneumatic2r.TurnOn(); + btnOn = true; + } + } + //*************************************************************/// koniec + // wezykow + // uginanie zderzakow + for (int i = 0; i < 2; ++i) { + + if( physics->Couplers[ i ].has_adapter() ) { + // HACK: if there's coupler adapter on this side, we presume there's additional distance put between vehicles + // which prevents buffers from clashing against each other (or the other vehicle doesn't have buffers to begin with) + continue; + } + + auto const dist { safe_clamp( physics->Couplers[ i ].Dist / 2.0, -physics->Couplers[ i ].DmaxB, 0.0 ) }; + + if( dist >= 0.0 ) { continue; } + + if( smBuforLewy[ i ] ) { + smBuforLewy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); + } + if( smBuforPrawy[ i ] ) { + smBuforPrawy[ i ]->SetTranslate( glm::vec3( dist, 0, 0 ) ); + } + } + } // vehicle within 50m + + // Winger 160204 - podnoszenie pantografow + + // przewody sterowania ukrotnionego + if (physics->Couplers[0].CouplingFlag.HasAll(Coupling::control)) + { + btCCtrl1.Turn( true ); + btnOn = true; + } + // else btCCtrl1.TurnOff(); + if (physics->Couplers[1].CouplingFlag.HasAll(Coupling::control)) + { + btCCtrl2.Turn( true ); + btnOn = true; + } + // else btCCtrl2.TurnOff(); + // McZapkie-181103: mostki przejsciowe + if (physics->Couplers[0].CouplingFlag.HasAll(Coupling::gangway)) + { + btCPass1.Turn( true ); + btnOn = true; + } + // else btCPass1.TurnOff(); + if (physics->Couplers[1].CouplingFlag.HasAll(Coupling::gangway)) + { + btCPass2.Turn( true ); + btnOn = true; + } + // else btCPass2.TurnOff(); + if (physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable()) + { // sygnaly konca pociagu + if (m_endsignals1.Active()) { + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::redmarker_left | light::redmarker_right ) ) { + m_endsignals1.Turn( true ); + btnOn = true; + } + } + else { + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::redmarker_left) && !HeadlightsAoff) + { + m_endsignal13.Turn( true ); + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::redmarker_right) && !HeadlightsAoff) + { + m_endsignal12.Turn( true ); + btnOn = true; + } + } + if (m_endsignals2.Active()) { + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::redmarker_left | light::redmarker_right ) ) { + m_endsignals2.Turn( true ); + btnOn = true; + } + } + else { + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::redmarker_left) && !HeadlightsBoff) + { + m_endsignal23.Turn( true ); + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::redmarker_right) && !HeadlightsBoff) + { + m_endsignal22.Turn( true ); + btnOn = true; + } + } + } + // tablice blaszane: + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::rearendsignals)) { + m_endtab1.Turn( true ); + btnOn = true; + } + // else btEndSignalsTab1.TurnOff(); + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::rearendsignals)) { + m_endtab2.Turn( true ); + btnOn = true; + } + // destination signs + update_destinations(); + // else btEndSignalsTab2.TurnOff(); + // McZapkie-181002: krecenie wahaczem (korzysta z kata obrotu silnika) + if (iAnimType[ANIM_LEVERS]) + for (int i = 0; i < 4; ++i) + if (smWahacze[i]) + smWahacze[i]->SetRotate(float3(1, 0, 0), + fWahaczeAmp * cos(physics->eAngle())); + + // cooling shutters + // NOTE: shutters display _on state when they're closed, _off otherwise + if( true == physics->diesel.heat.water.config.shutters + && false == physics->diesel.heat.zaluzje1 ) { + btShutters1.Turn( true ); + btnOn = true; + } + if( true == physics->diesel.heat.water_aux.config.shutters + && false == physics->diesel.heat.zaluzje2 ) { + btShutters2.Turn( true ); + btnOn = true; + } + + // only external models ( external_only_on / external_only_off ) + btExteriorOnly.Turn(!bDisplayCab); // display only when cab is not rendered + + if( false == bDisplayCab // edge case, lowpoly may act as a stand-in for the hi-fi cab, so make sure not to show the driver when inside + && Mechanik != nullptr + && Mechanik->action() != TAction::actSleep ) { + // rysowanie figurki mechanika + // a player driving a vehicle with a single desk is seen facing the selected direction of travel, as the AI + // is, which changes the cab instead (eu07/maszyna#535) + auto const followsdirection { + Global.DriverFigureFollowsDirection + && SingleDesk + && false == Mechanik->AIControllFlag() }; + auto const figure { driver_figure::shown( physics->CabOccupied(), physics->DirAbsolute, followsdirection ) }; + btMechanik1.Turn( figure > 0 ); + btMechanik2.Turn( figure < 0 ); + if( figure != 0 ) { + btnOn = true; + } + } + + } // vehicle within 400m + + if( physics->lowVoltage.Is24vAvailable() || physics->lowVoltage.Is110vAvailable() ) + { // sygnały czoła pociagu //Ra: wyświetlamy bez + // ograniczeń odległości, by były widoczne z + // daleka + + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_left) + && !HeadlightsAoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp13.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp13.TurnOn(); + } + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_upper) + && !HeadlightsAoff) + { + if( DimHeadlights ) { + m_headlamp11.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp11.TurnOn(); + } + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_right) + && !HeadlightsAoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp12.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp12.TurnOn(); + } + btnOn = true; + } + // else btHeadSignals13.TurnOff(); + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_left) + && !HeadlightsBoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp23.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp23.TurnOn(); + } + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_upper) + && !HeadlightsBoff) + { + if( DimHeadlights ) { + m_headlamp21.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp21.TurnOn(); + } + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_right) + && !HeadlightsBoff && !HighBeamLights) + { + if( DimHeadlights ) { + m_headlamp22.TurnxOnWithOnAsFallback(); + } + else { + m_headlamp22.TurnOn(); + } + btnOn = true; + } + // auxiliary lights + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::auxiliary_left) && !HeadlightsAoff) + { + if( DimHeadlights ) { + m_headsignal13.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal13.TurnOn(); + } + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::auxiliary_right) && !HeadlightsAoff) + { + if( DimHeadlights ) { + m_headsignal12.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal12.TurnOn(); + } + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::auxiliary_left) && !HeadlightsBoff) + { + if( DimHeadlights ) { + m_headsignal23.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal23.TurnOn(); + } + btnOn = true; + } + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::auxiliary_right) && !HeadlightsBoff) + { + if( DimHeadlights ) { + m_headsignal22.TurnxOnWithOnAsFallback(); + } + else { + m_headsignal22.TurnOn(); + } + btnOn = true; + } + + // logika dlugich + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_left) + && !HeadlightsAoff && HighBeamLights) + m_highbeam13.TurnxOnWithOnAsFallback(); + else + m_highbeam13.TurnOff(); + + if (TestFlag(physics->LitLights()[VehicleEnd::front], light::headlight_right) + && !HeadlightsAoff && HighBeamLights) + m_highbeam12.TurnxOnWithOnAsFallback(); + else + m_highbeam12.TurnOff(); + + // i to samo od dupy strony + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_left) + && !HeadlightsBoff && HighBeamLights) + m_highbeam23.TurnxOnWithOnAsFallback(); + else + m_highbeam23.TurnOff(); + + if (TestFlag(physics->LitLights()[VehicleEnd::rear], light::headlight_right) + && !HeadlightsBoff && HighBeamLights) + m_highbeam22.TurnxOnWithOnAsFallback(); + else + m_highbeam22.TurnOff(); + } + // interior light levels + auto sectionlightcolor { glm::vec4( 1.f ) }; + bool cabsection{ true }; + for( auto const §ion : Sections ) { + if( cabsection ) { + // check whether we're still processing cab sections + auto const §ionname { section.compartment->pName }; + cabsection &= sectionname.size() >= 4 && sectionname.starts_with("cab"); + } + // TODO: add cablight devices + auto const sectionlightlevel { section.light_level * ( cabsection ? 1.0f : physics->CompartmentLights.intensity ) }; + sectionlightcolor = glm::vec4( + sectionlightlevel == 0.f || Global.fLuminance > section.compartment->fLight ? + glm::vec3(240.f / 255.f) : // TBD: save and restore initial submodel diffuse instead of enforcing one? + InteriorLight, // TODO: per-compartment (type) light color + sectionlightlevel ); + section.compartment->SetLightLevel( sectionlightcolor, true ); + if( section.load != nullptr ) { + section.load->SetLightLevel( sectionlightcolor, true ); + } + } + // load chunks visibility + for( auto const §ion : Sections ) { + // section isn't guaranteed to have load model, so check that first + if( section.load == nullptr ) { continue; } + section.load->iVisible = section.load_chunks_visible > 0; + // if the section root isn't visible we can skip meddling with its children + if( false == section.load->iVisible ) { continue; } + // if the section root is visible set the state of section chunks + auto *sectionchunk { section.load->ChildGet() }; + auto visiblechunkcount { section.load_chunks_visible }; + while( sectionchunk != nullptr ) { + sectionchunk->iVisible = visiblechunkcount > 0; + --visiblechunkcount; + sectionchunk = sectionchunk->NextGet(); + } + } + + // driver cabs visibility + for( int cabidx = 0; cabidx < LowPolyIntCabs.size(); ++cabidx ) { + if( LowPolyIntCabs[ cabidx ] == nullptr ) { continue; } + LowPolyIntCabs[ cabidx ]->iVisible = mdKabina == nullptr ? true : // there's no hi-fi cab + bDisplayCab == false ? true : // we're in external view + simulation::Train == nullptr ? true : // not a player-driven vehicle, implies external view + simulation::Train->Dynamic() != this ? true : // not a player-driven vehicle, implies external view + JointCabs ? false : // internal view, all cabs share the model so hide them 'all' + simulation::Train->iCabn != cabidx; // internal view, hide occupied cab and show others + } +} + +void +TDynamicObject::update_shake( double const Timedelta ) { + + ShakeStateBefore = ShakeState; + // Ra: mechanik powinien być telepany niezależnie od pozycji pojazdu + // Ra: trzeba zrobić model bujania głową i wczepić go do pojazdu + + // Ra: tu by się przydało uwzględnić rozkład sił: + // - na postoju horyzont prosto, kabina skosem + // - przy szybkiej jeździe kabina prosto, horyzont pochylony + + // McZapkie: najpierw policzę pozycję w/m kabiny + + // ABu: rzucamy kabina tylko przy duzym FPS! + // Mala histereza, zeby bez przerwy nie przelaczalo przy FPS~17 + // Granice mozna ustalic doswiadczalnie. Ja proponuje 14:20 + if( Global.iSlowMotion == 0 ) { // musi być pełna prędkość + + glm::dvec3 shakevector; + if( physics->EngineType == TEngineType::DieselElectric + || physics->EngineType == TEngineType::DieselEngine ) { + if( std::abs( physics->enrot ) > 0.0 ) { + // engine vibration + shakevector.x += + std::sin(physics->eAngle() * 4.0) * Timedelta * + EngineShake.scale + // fade in with rpm above threshold + * std::clamp( + ( physics->enrot - EngineShake.fadein_offset ) * EngineShake.fadein_factor, + 0.0, 1.0 ) + // fade out with rpm above threshold + * std::lerp( + 1.0, 0.0, + std::clamp( + ( physics->enrot - EngineShake.fadeout_offset ) * EngineShake.fadeout_factor, + 0.0, 1.0 ) ); + } + } + + if( HuntingShake.fadein_begin > 0.f + && true == physics->TruckHunting() ) { + // hunting oscillation + HuntingAngle = clamp_circular( HuntingAngle + 4.0 * HuntingShake.frequency * Timedelta * physics->Vel, 360.0 ); + auto const huntingamount = + std::lerp( + 0.0, 1.0, + std::clamp( + ( physics->Vel - HuntingShake.fadein_begin ) / ( HuntingShake.fadein_end - HuntingShake.fadein_begin ), + 0.0, 1.0 ) ); + shakevector.x += + std::sin(glm::radians(HuntingAngle)) * Timedelta * HuntingShake.scale + * huntingamount; + IsHunting = huntingamount > 0.025; + } + + if (FreeFlyModeFlag) + shakevector *= 0; + + auto const iVel { std::min( GetVelocity(), 150.0 ) }; + // an uneven track shakes the cab by itself, in place of the sway drawn from the curve and the jolts drawn at random, as far as it does + auto const replaced { track_uneven::replaced_shake( MyTrack != nullptr ? MyTrack->uneven_underway() : track_uneven::amounts {} ) }; + if( iVel > 0.5 ) { + // acceleration-driven base shake + shakevector += glm::dvec3( + replaced.sway ? 0.0 : -physics->AccN() * Timedelta * 5.0 * Global.ShakingMultiplierRL, // highlight side sway + -physics->AccVert() * Timedelta * Global.ShakingMultiplierUD, + -physics->AccSVBased() * Timedelta * 1.5 * Global.ShakingMultiplierBF); // accent acceleration/deceleration + // unevenness of the track under the outer axles + auto const ride { 0.5 * ( Axle0.UnevenBend() + Axle1.UnevenBend() ) * ( physics->V() * physics->V() ) }; + shakevector += glm::dvec3( + -glm::dot( ride, vLeft ) * Timedelta * 5.0 * Global.ShakingMultiplierRL, + -ride.y * Timedelta * Global.ShakingMultiplierUD, + 0.0 ); + } + + auto shake { 1.25 * ShakeSpring.ComputateForces( shakevector, ShakeState.offset ) }; + + if( false == replaced.jolts && LocalRandom( iVel ) > 25.0 ) { + // extra shake at increased velocity + shake += ShakeSpring.ComputateForces( + glm::dvec3( + ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.x, + ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.y, + ( LocalRandom( iVel * 2 ) - iVel ) / ( iVel * 2 * 4 ) * BaseShake.jolt_scale.z ) +// * (( 200 - DynamicObject->MyTrack->iQualityFlag ) * 0.0075 ) // scale to 75-150% based on track quality + * 1.25, + ShakeState.offset ); + } + shake *= 0.85; + + ShakeState.velocity -= ( shake + ShakeState.velocity * 100.0 ) * (double)( BaseShake.jolt_scale.x + BaseShake.jolt_scale.y + BaseShake.jolt_scale.z ) / 200.0; + + // McZapkie: + ShakeState.offset += ShakeState.velocity * Timedelta; + if( std::abs( ShakeState.offset.y ) > std::abs( BaseShake.jolt_limit ) ) { + ShakeState.velocity.y = -ShakeState.velocity.y; + } + } + else { // hamowanie rzucania przy spadku FPS + ShakeState.offset -= ShakeState.offset * std::min( Timedelta, 1.0 ); // po tym chyba potrafią zostać jakieś ułamki, które powodują zjazd + } +} + +bool +TDynamicObject::axle_passed_joint( axle_sounds &Axle, double const Move, int const Direction ) const { + + // from the follower on its side of the vehicle, as the two can be on different tracks. They stand fAxleDist apart, at the bogie pivots, and + // the offset of the axle is the place of its wheel set, so the two of a bogie come out half of ADist to either side of the pivot + auto const &follower { Axle.offset >= 0.0 ? Axle0 : Axle1 }; + if( auto const railphase { follower.RailPhase( Axle.offset - std::copysign( 0.5 * fAxleDist, Axle.offset ) ) }; railphase >= 0.0 ) { + // the rails under the axle, which aren't always those under the track the vehicle is on + auto const passed { Axle.atjoints && std::abs( railphase - Axle.distance ) > 0.5 * follower.GetTrack()->fSoundDistance }; + Axle.distance = railphase; + Axle.atjoints = true; + return passed; + } + Axle.atjoints = false; + Axle.distance += Move * Direction; + if( Axle.distance >= 0 && Axle.distance <= dRailLength ) { + return false; + } + Axle.distance = clamp_circular( Axle.distance, dRailLength ); + return true; +} + +std::pair +TDynamicObject::shake_angles() const { + + return shake_angles( ShakeState ); +} + +std::pair +TDynamicObject::shake_angles( shake_state const &State ) const { + + return { + std::atan( State.velocity.x * BaseShake.angle_scale.x ), + std::atan( State.velocity.z * BaseShake.angle_scale.z ) }; +} + +TDynamicObject::shake_state +TDynamicObject::shake_between( double const Fraction ) const { + + if( Fraction >= 1.0 ) { + return ShakeState; + } + auto const between { []( glm::dvec3 const &Before, glm::dvec3 const &After, double const Part ) { + return glm::dvec3 { + std::lerp( Before.x, After.x, Part ), + std::lerp( Before.y, After.y, Part ), + std::lerp( Before.z, After.z, Part ) }; } }; + auto const part { std::max( Fraction, 0.0 ) }; + return { + between( ShakeStateBefore.velocity, ShakeState.velocity, part ), + between( ShakeStateBefore.offset, ShakeState.offset, part ) }; +} diff --git a/vehicle/enginestart.cpp b/vehicle/enginestart.cpp index feb4445ce..1366eb43f 100644 --- a/vehicle/enginestart.cpp +++ b/vehicle/enginestart.cpp @@ -10,7 +10,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/enginestart.h" -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" #include "utilities/utilities.h" namespace engine_start { @@ -18,19 +18,19 @@ namespace engine_start { namespace { // whether the vehicle has an engine the cab can start, the same test the tachometers of the vehicles in multiple make -bool has_engine(TMoverParameters const &Vehicle) { +bool has_engine(physics::Vehicle const &Vehicle) { return Vehicle.Power > 0.01; } // walks from Start through its coupler Side along the control cable, and returns the Number-th vehicle with an engine // other than Skipped it meets; Number is lowered by the ones it met when it doesn't get that far -TMoverParameters *find_along(TMoverParameters const &Start, int const Side, TMoverParameters const &Skipped, int &Number) { +physics::Vehicle *find_along(physics::Vehicle const &Start, int const Side, physics::Vehicle const &Skipped, int &Number) { auto const *vehicle{&Start}; auto side{Side}; // a train can't loop back on itself, the limit only guards against a broken chain of couplers for (auto steps = 0; steps < 1000; ++steps) { auto const &coupler{vehicle->Couplers[side]}; - if (coupler.Connected == nullptr || false == TestFlag(coupler.CouplingFlag, coupling::control)) { + if (coupler.Connected == nullptr || false == coupler.CouplingFlag.HasAll(Coupling::control)) { return nullptr; } // onwards through the other end of the next vehicle, whichever way round it stands @@ -49,7 +49,7 @@ TMoverParameters *find_along(TMoverParameters const &Start, int const Side, TMov } // namespace -TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Controlled, int Number) { +physics::Vehicle *engine(physics::Vehicle const &Occupied, physics::Vehicle &Controlled, int Number) { if (Number < 1) { return nullptr; } @@ -59,14 +59,14 @@ TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Con // the cab's own vehicle is the first one auto others{Number - 1}; // behind the cab is the rear end of a vehicle driven from its front cab, and the other way round - int const behind{Occupied.CabOccupied < 0 ? end::front : end::rear}; + int const behind{NumberOf(Occupied.CabOccupied() < 0 ? VehicleEnd::front : VehicleEnd::rear)}; if (auto *found{find_along(Occupied, behind, Controlled, others)}; found != nullptr) { return found; } return find_along(Occupied, 1 - behind, Controlled, others); } -void remote_switch::update(TMoverParameters *Engine, bool const Closeheld, bool const Openheld, double const Deltatime, bool const Closesonrelease) { +void remote_switch::update(physics::Vehicle *Engine, bool const Closeheld, bool const Openheld, double const Deltatime, bool const Closesonrelease) { if (Engine != m_engine) { // another vehicle under the switch, after a change in the train m_engine = Engine; @@ -85,7 +85,7 @@ void remote_switch::update(TMoverParameters *Engine, bool const Closeheld, bool if (Closeheld && Engine->MainSwitchCheck()) { m_heldtime += Deltatime; } - if (m_heldtime > Engine->InitialCtrlDelay) { + if (m_heldtime > Engine->InitialCtrlDelay()) { m_ready = true; } if (m_ready && false == (Closesonrelease && Closeheld)) { @@ -98,12 +98,12 @@ void remote_switch::update(TMoverParameters *Engine, bool const Closeheld, bool } } -bool remote_switch::open(TMoverParameters &Engine) { +bool remote_switch::open(physics::Vehicle &Engine) { return Engine.MainSwitch(false, range_t::local); } -bool remote_switch::is_running(TMoverParameters const &Engine) { - return Engine.Mains || Engine.dizel_startup; +bool remote_switch::is_running(physics::Vehicle const &Engine) { + return Engine.lineBreaker.IsClosed() || Engine.diesel.startupRequested; } } // namespace engine_start diff --git a/vehicle/enginestart.h b/vehicle/enginestart.h index 77b6a2d93..b2696ba46 100644 --- a/vehicle/enginestart.h +++ b/vehicle/enginestart.h @@ -9,20 +9,20 @@ http://mozilla.org/MPL/2.0/. #pragma once -class TMoverParameters; +namespace physics { class Vehicle; } // starting the engines (closing the line breakers) of the vehicles in multiple from the cab (eu07/maszyna#80). in // vehicles like the ST43, the SP32 or the SN61 every engine of the train has its own switches in the cab: main_* work -// the vehicle the cab controls (TTrain::mvControlled: the cab's own vehicle, on an EMU its motor car), mainb_* the +// the vehicle the cab controls (TTrain::controlled: the cab's own vehicle, on an EMU its motor car), mainb_* the // second one and mainc_* the third one under its control. Engine:JointEngineStart=No in the .fiz of the controlled // vehicle (on an EMU the motor car's, not the one of the car with the cab) keeps main_* to that vehicle alone -// (TMoverParameters::MainSwitchRange()); by default it works all of them, as before. +// (physics::Vehicle::MainSwitchRange()); by default it works all of them, as before. namespace engine_start { // the Number-th vehicle with an engine under the cab's control: 1 is Controlled, the cab's own; then the others // connected through the control cable, those behind the cab of Occupied first, the nearest first, then those in front // of it. nullptr when there are fewer of them -TMoverParameters *engine(TMoverParameters const &Occupied, TMoverParameters &Controlled, int Number); +physics::Vehicle *engine(physics::Vehicle const &Occupied, physics::Vehicle &Controlled, int Number); // the switch starting the engine of another vehicle in multiple. like the cab's own switch, it has to be held closed // for the vehicle's InitialCtrlDelay, with the vehicle ready for it, before the engine starts (the line breaker closes) @@ -31,14 +31,14 @@ public: // one step of Deltatime seconds of the switch of Engine, with the switch held closed (Closeheld) or open (Openheld). // with Closesonrelease, the line breaker closes when the switch is let go after the delay, as the impulse switch // of an electric locomotive with series motors does - void update(TMoverParameters *Engine, bool Closeheld, bool Openheld, double Deltatime, bool Closesonrelease); + void update(physics::Vehicle *Engine, bool Closeheld, bool Openheld, double Deltatime, bool Closesonrelease); // opens the line breaker / stops the engine of Engine, the vehicle alone; returns whether it was running - static bool open(TMoverParameters &Engine); + static bool open(physics::Vehicle &Engine); // whether the line breaker of Engine is closed or its engine starting or running - static bool is_running(TMoverParameters const &Engine); + static bool is_running(physics::Vehicle const &Engine); private: - TMoverParameters const *m_engine{nullptr}; // the vehicle the switch worked the last step + physics::Vehicle const *m_engine{nullptr}; // the vehicle the switch worked the last step double m_heldtime{0.0}; // how long the switch is held closed with the vehicle ready to start bool m_ready{false}; // held long enough, the line breaker closes now or when the switch is let go }; diff --git a/vehicle/fieldshunting.cpp b/vehicle/fieldshunting.cpp new file mode 100644 index 000000000..49300f50b --- /dev/null +++ b/vehicle/fieldshunting.cpp @@ -0,0 +1,27 @@ +/* +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/fieldshunting.h" + +namespace fieldshunting { + +bool has_switch(int const Autorelaytype, bool const Fieldshuntswitch) { + return Autorelaytype == 2 && Fieldshuntswitch; +} + +control diesel_electric(int const Autorelaytype, bool const Fieldshuntswitch, bool const Autorelayflag) { + using enum control; + if (Autorelayflag) { + return automatic; + } + return has_switch(Autorelaytype, Fieldshuntswitch) ? off : manual; +} + +} // namespace fieldshunting diff --git a/vehicle/fieldshunting.h b/vehicle/fieldshunting.h new file mode 100644 index 000000000..2dec04be5 --- /dev/null +++ b/vehicle/fieldshunting.h @@ -0,0 +1,32 @@ +/* +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 + +// the field shunting (ScndCtrlPos) of the diesel-electric locomotives +namespace fieldshunting { + +// who sets the field shunting +enum class control : int { + manual, // the driver, with the second controller + automatic, // the shunting relays (RelayType) + off // nobody: the shunting is switched off, the field stays full +}; + +// whether a diesel-electric has the switch that lets the relays shunt the field, as the SU45's and SP45's "załączenie +// bocznikowania" (eu07/maszyna#167): AutoRelay=Optional (Autorelaytype 2) with FieldShuntSwitch=Yes (Fieldshuntswitch) +bool has_switch(int Autorelaytype, bool Fieldshuntswitch); + +// who sets the field shunting of a diesel-electric locomotive, by its AutoRelay (Autorelaytype: 0 No, 1 Yes, 2 Optional), +// its FieldShuntSwitch (Fieldshuntswitch) and its AutoRelayFlag (Autorelayflag). with the flag set, the relays. with the +// switch of the field shunting (has_switch()) switched off, nobody. otherwise the driver, AutoRelay=Optional without +// FieldShuntSwitch included +control diesel_electric(int Autorelaytype, bool Fieldshuntswitch, bool Autorelayflag); + +} // namespace fieldshunting diff --git a/vehicle/gaugewrap.cpp b/vehicle/gaugewrap.cpp new file mode 100644 index 000000000..f16b6e857 --- /dev/null +++ b/vehicle/gaugewrap.cpp @@ -0,0 +1,48 @@ +/* +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/gaugewrap.h" + +#include + +namespace gauge_wrap { + +namespace { + +// how far the positions in a full turn worked out from the scale may be off a whole number: the scales in the cab +// definitions are given to three decimals or so, 0.167 for a sixth gives 5.988 +constexpr double turn_tolerance{0.05}; + +} // namespace + +std::optional full_turn(float const Scale, int const Positions) { + if (Positions < 2 || Scale == 0.f) { + return std::nullopt; + } + auto const perturn{1.0 / std::abs(static_cast(Scale))}; + auto const turn{std::round(perturn)}; + if (std::abs(perturn - turn) > turn_tolerance) { + // the positions don't make a full turn: a lever, or a knob that stops at its ends + return std::nullopt; + } + auto const positions{static_cast(turn)}; + // the way on from the last position to the first one, in positions + if (auto const wayon{positions - (Positions - 1)}; wayon < 1 || 2 * wayon > positions) { + // the positions overlap in a turn, or the knob would turn on more than half a turn + return std::nullopt; + } + return positions; +} + +float turned_round(float const Value, int const Turn, bool const Forward) { + return Forward ? Value - static_cast(Turn) : Value + static_cast(Turn); +} + +} // namespace gauge_wrap diff --git a/vehicle/gaugewrap.h b/vehicle/gaugewrap.h new file mode 100644 index 000000000..126652922 --- /dev/null +++ b/vehicle/gaugewrap.h @@ -0,0 +1,29 @@ +/* +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 + +#include + +// a multi-position rotary switch of the cab turned past its last position to the first one, or back past the first +// one to the last (a selector with Wrap=Yes, such as the light preset selector) +namespace gauge_wrap { + +// the number of positions in one full turn of a rotary switch of Positions positions that turns by Scale of a full turn +// per position, if the switch can turn on past its end the short way round: the full turn is a whole number of positions +// (within the rounding of the scale in the cab definition, e.g. 0.167 for a sixth), all the positions fit in it, and the +// way on from the last position to the first one is at most half a turn. None otherwise +std::optional full_turn(float Scale, int Positions); + +// the value of the switch at Value seen one full turn of Turn positions earlier (Forward: it turns on past its last +// position to the first one) or later (back past the first position to the last one). The knob stands the same there, +// and turning from that value to the new position turns it on the way it was turned rather than all the way back +float turned_round(float Value, int Turn, bool Forward); + +} // namespace gauge_wrap diff --git a/vehicle/handover.cpp b/vehicle/handover.cpp index a36ccde81..1e1ab5622 100644 --- a/vehicle/handover.cpp +++ b/vehicle/handover.cpp @@ -10,51 +10,51 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/handover.h" -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" namespace handover { -void release_ai_controls(TMoverParameters &Occupied, TMoverParameters &Controlling) { +void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlling) { // the AI's hornoff action touches the horn only while the AI drives - Occupied.WarningSignal = 0; + Occupied.SetWarningSignal(0); // the AI drives the sandbox directly, bypassing the manual and automatic sanding states - if (Controlling.SandDose && false == (Controlling.SandDoseManual || Controlling.SandDoseAuto)) { + if (Controlling.SandDose() && false == (Controlling.SandDoseManual || Controlling.SandDoseAuto)) { Controlling.Sandbox(false); } - if (Occupied.DepartureSignal) { + if (Occupied.DepartureSignal()) { Occupied.signal_departure(false); } - if (Occupied.Hamulec->Releaser()) { + if (Occupied.brakes.distributor->Releaser()) { Occupied.BrakeReleaser(0); } } -int light_selector_position(TMoverParameters const &Occupied, int const Lightstable, int const Headlights, int const Inventory) { +int light_selector_position(physics::Vehicle const &Occupied, int const Lightstable, int const Headlights, int const Inventory) { // the selector size comes from the vehicle definition, the table holds a fixed number of positions auto const positioncount{std::min(Occupied.LightsPosNo, static_cast(std::size(Occupied.Lights[0])))}; if (positioncount <= 0 || Lightstable < 0 || Lightstable >= static_cast(std::size(Occupied.Lights))) { - return Occupied.LightsPos; + return Occupied.LightsPos(); } auto const &lights{Occupied.Lights[Lightstable]}; auto const lightsmatch{[&lights, Inventory, Headlights](int const Position) { return (lights[Position - 1] & Inventory) == Headlights; }}; - if (Occupied.LightsPos >= 1 && Occupied.LightsPos <= positioncount && lightsmatch(Occupied.LightsPos)) { - return Occupied.LightsPos; + if (Occupied.LightsPos() >= 1 && Occupied.LightsPos() <= positioncount && lightsmatch(Occupied.LightsPos())) { + return Occupied.LightsPos(); } for (auto position = 1; position <= positioncount; ++position) { if (lightsmatch(position)) { return position; } } - return Occupied.LightsPos; + return Occupied.LightsPos(); } -int dimmer_position(TMoverParameters const &Occupied, bool const Headlightson) { +int dimmer_position(physics::Vehicle const &Occupied, bool const Headlightson) { auto const &positions{Occupied.dimPositions}; - auto const current{Occupied.modernDimmerPosition}; + auto const current{Occupied.DimmerPosition()}; auto const count{static_cast(positions.size())}; auto const isoff{[&positions, count](int const Position) { return Position < 0 || Position >= count || positions[Position].isOff; }}; - if (false == Occupied.enableModernDimmer || false == Headlightson || false == isoff(current)) { + if (false == Occupied.enableModernDimmer() || false == Headlightson || false == isoff(current)) { return current; } if (false == isoff(Occupied.modernDimmerDefaultPosition)) { diff --git a/vehicle/handover.h b/vehicle/handover.h index 32ed57d0a..f02edca68 100644 --- a/vehicle/handover.h +++ b/vehicle/handover.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -class TMoverParameters; +namespace physics { class Vehicle; } // what changes about a vehicle when the AI hands it over to the human driver. the AI operates some // controls directly, bypassing the cab controls a human uses, and only the AI ever releases them; @@ -18,16 +18,16 @@ namespace handover { // releases what the AI latches, but which is held only while pressed for the human driver: // the horn, the sandbox, the departure signal and the brake releaser -void release_ai_controls(TMoverParameters &Occupied, TMoverParameters &Controlling); +void release_ai_controls(physics::Vehicle &Occupied, physics::Vehicle &Controlling); // position of the light preset selector [1..LightsPosNo] for the human driver: the current one when it // gives the head lights the AI has set, else the first one which does, else the current one. // Lightstable is the end of the selector's table in use, Inventory the lights the head end has -int light_selector_position(TMoverParameters const &Occupied, int Lightstable, int Headlights, int Inventory); +int light_selector_position(physics::Vehicle const &Occupied, int Lightstable, int Headlights, int Inventory); // position of the headlight dimmer for the human driver: the current one, unless it's the off position // which would hide the head lights the AI has lit. then the default one, else the first regular one, // else any other than off -int dimmer_position(TMoverParameters const &Occupied, bool Headlightson); +int dimmer_position(physics::Vehicle const &Occupied, bool Headlightson); } // namespace handover diff --git a/vehicle/lightsprogrammer.h b/vehicle/lightsprogrammer.h index 9ae8c2ab0..6e0cd7bbb 100644 --- a/vehicle/lightsprogrammer.h +++ b/vehicle/lightsprogrammer.h @@ -11,7 +11,7 @@ http://mozilla.org/MPL/2.0/. #include -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" // the lights the light preset selector (programmer) of the occupied cab gives one vehicle of the consist namespace lights_programmer { @@ -23,18 +23,18 @@ struct consist_lights { int rear; }; -// Cablights: the selector's lights for the occupied cab's front and back (Lights[end::front / end::rear]). +// Cablights: the selector's lights for the occupied cab's front and back (Lights[VehicleEnd::front / VehicleEnd::rear]). // Cabfacinghead: the occupied cab faces the head of the consist. -// Direction: the vehicle's iDirection, 1 when its end::front is towards the head of the consist. -// Coupled: whether another vehicle is coupled at the vehicle's end::front / end::rear; an end with a coupled +// Direction: the vehicle's iDirection, 1 when its VehicleEnd::front is towards the head of the consist. +// Coupled: whether another vehicle is coupled at the vehicle's VehicleEnd::front / VehicleEnd::rear; an end with a coupled // vehicle stays dark -inline consist_lights vehicle_lights(std::array const &Cablights, bool const Cabfacinghead, int const Direction, std::array const &Coupled) { - auto const headlights{Cablights[Cabfacinghead ? end::front : end::rear]}; - auto const rearlights{Cablights[Cabfacinghead ? end::rear : end::front]}; +inline consist_lights vehicle_lights(ByEnd const &Cablights, bool const Cabfacinghead, int const Direction, ByEnd const &Coupled) { + auto const headlights{Cablights[Cabfacinghead ? VehicleEnd::front : VehicleEnd::rear]}; + auto const rearlights{Cablights[Cabfacinghead ? VehicleEnd::rear : VehicleEnd::front]}; // the head lights go to the vehicle's end towards the head of the consist whichever way the cab faces, // so the coupling which keeps them dark is the one at that same end (eu07/maszyna#395) - auto const headend{Direction > 0 ? end::front : end::rear}; - auto const rearend{Direction > 0 ? end::rear : end::front}; + auto const headend{Direction > 0 ? VehicleEnd::front : VehicleEnd::rear}; + auto const rearend{Direction > 0 ? VehicleEnd::rear : VehicleEnd::front}; return {Coupled[headend] ? 0 : headlights, Coupled[rearend] ? 0 : rearlights}; } diff --git a/vehicle/linebreaker.cpp b/vehicle/linebreaker.cpp index 97eae0325..cc9b2f008 100644 --- a/vehicle/linebreaker.cpp +++ b/vehicle/linebreaker.cpp @@ -12,11 +12,11 @@ http://mozilla.org/MPL/2.0/. namespace linebreaker { -toggle pressed(int const Breakerstate, bool const Latchinglever, bool const Leveron) { - if (Breakerstate == 1) { +toggle pressed(state const Breakerstate, bool const Latchinglever, bool const Leveron) { + if (Breakerstate == state::closed) { return toggle::open; } - if (Breakerstate != 0) { + if (Breakerstate != state::open) { return toggle::none; } // the line breaker is open; a lever left on goes off first diff --git a/vehicle/linebreaker.h b/vehicle/linebreaker.h index 370e992cc..cfcf76003 100644 --- a/vehicle/linebreaker.h +++ b/vehicle/linebreaker.h @@ -12,6 +12,13 @@ http://mozilla.org/MPL/2.0/. // the line breaker (main switch, WS) controls of the cab namespace linebreaker { +// the state the cab keeps of the line breaker, besides the vehicle's own (physics::Vehicle::Mains) +enum class state : int { + open, + closed, + closing // the closing control was held long enough; the line breaker closes when it's released, or right away +}; + enum class toggle : int { none, // the press does nothing close, // the control goes to its on position, and the line breaker closes if it can @@ -19,10 +26,10 @@ enum class toggle : int { }; // what a press of the line breaker toggle does. Breakerstate is the state the cab keeps of the line -// breaker (0: open, 1: closed, 2: freshly closed). Latchinglever is a single two-state switch which -// stays where it was put, Leveron that it stands in its on position. such a lever doesn't follow the -// line breaker: knocked out (by the converter overload relay, say) the breaker opens with the lever -// left on, and the lever has to go off before it can be put on again (eu07/maszyna#394) -toggle pressed(int Breakerstate, bool Latchinglever, bool Leveron); +// breaker. Latchinglever is a single two-state switch which stays where it was put, Leveron that it +// stands in its on position. such a lever doesn't follow the line breaker: knocked out (by the converter +// overload relay, say) the breaker opens with the lever left on, and the lever has to go off before it +// can be put on again (eu07/maszyna#394) +toggle pressed(state Breakerstate, bool Latchinglever, bool Leveron); } // namespace linebreaker diff --git a/vehicle/mainctrlact.h b/vehicle/mainctrlact.h index df61aa061..12cdfc959 100644 --- a/vehicle/mainctrlact.h +++ b/vehicle/mainctrlact.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" // the position the controller position marker of the cab (mainctrlact:) shows namespace main_ctrl_act { @@ -17,17 +17,17 @@ namespace main_ctrl_act { // the diesel engines work the controller position straight away, they have no camshaft or relays of their own that // would follow it, and nothing sets their MainCtrlActualPos; only with a controller of the EIM kind (EIMCtrlType) // it is kept up to date (CheckEIMIC). so their marker shows the position of the controller (MaSzyna-EU07/maszyna#74) -inline bool follows_controller(TMoverParameters const &Vehicle) { +inline bool follows_controller(physics::Vehicle const &Vehicle) { return (Vehicle.EngineType == TEngineType::DieselEngine || Vehicle.EngineType == TEngineType::DieselElectric) && Vehicle.EIMCtrlType == 0; } // Scaletable: the cab's gauge has a scaletable:. only such a marker follows the controller; the cabs that define // mainctrlact: without one (the ST43 so far) keep their marker still, as before, instead of moving it on a scale // nobody has checked -inline float position(TMoverParameters const &Vehicle, bool const Scaletable) { +inline float position(physics::Vehicle const &Vehicle, bool const Scaletable) { auto const controller{Scaletable && follows_controller(Vehicle)}; - auto const main{controller ? Vehicle.MainCtrlPos : Vehicle.MainCtrlActualPos}; - auto const scnd{controller ? Vehicle.ScndCtrlPos : Vehicle.ScndCtrlActualPos}; + auto const main{controller ? Vehicle.MainCtrlPos() : Vehicle.MainCtrlActualPos}; + auto const scnd{controller ? Vehicle.ScndCtrlPos() : Vehicle.ScndCtrlActualPos}; return static_cast(Vehicle.CoupledCtrl ? main + scnd : main); } diff --git a/vehicle/odometer.cpp b/vehicle/odometer.cpp index 8f98cb084..7495cbda2 100644 --- a/vehicle/odometer.cpp +++ b/vehicle/odometer.cpp @@ -15,13 +15,17 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include +#include #include #include #include +#include #include #include #include +#include #include +#include #ifdef _WIN32 #include #else @@ -62,8 +66,61 @@ std::optional parse_number(std::string const &Text) { } } +// the comment line which gives the day the states after it were last updated +constexpr std::string_view stamp_prefix{"# updated "}; + +// a whole number making up all of the text +std::optional parse_integer(std::string_view const Text) { + if (Text.empty() || Text.front() == '-') + return std::nullopt; + int value{0}; + auto const *const end{Text.data() + Text.size()}; + if (auto const [used, error] {std::from_chars(Text.data(), end, value)}; error != std::errc{} || used != end) + return std::nullopt; + return value; +} + +// day written as yyyy-mm-dd +std::optional parse_day(std::string_view const Text) { + if (Text.size() != 10 || Text[4] != '-' || Text[7] != '-') + return std::nullopt; + auto const year{parse_integer(Text.substr(0, 4))}; + auto const month{parse_integer(Text.substr(5, 2))}; + auto const dayofmonth{parse_integer(Text.substr(8, 2))}; + if (false == (year.has_value() && month.has_value() && dayofmonth.has_value())) + return std::nullopt; + std::chrono::year_month_day const date{std::chrono::year{*year}, std::chrono::month{static_cast(*month)}, + std::chrono::day{static_cast(*dayofmonth)}}; + if (false == date.ok()) + return std::nullopt; + return day{date}; +} + +std::string format_day(day const Day) { + std::chrono::year_month_day const date{Day}; + return std::format("{:04}-{:02}-{:02}", static_cast(date.year()), static_cast(date.month()), + static_cast(date.day())); +} + +// the day of a stamp line, as written, a day later than Today included. Today for a malformed one: the states after it +// are kept +day stamp_day(std::string_view const Line, day const Today) { + auto text{Line.substr(stamp_prefix.size())}; + while (false == text.empty() && (text.back() == ' ' || text.back() == '\t')) + text.remove_suffix(1); + return parse_day(text).value_or(Today); +} + } // namespace +day today() { + return std::chrono::floor(std::chrono::system_clock::now()); +} + +std::chrono::days expiry() { + return std::chrono::days{std::max(0, Global.odometer_expiry)}; +} + void reading::begin(double const Km, origin const Source) { km = Km; start = Km; @@ -89,12 +146,16 @@ bool reading::moved() const { return km != start; } -std::size_t store::read(std::istream &Input) { +std::size_t store::read(std::istream &Input, day const Today) { std::size_t count{0}; + // the states with no stamp before them, as the builds without the stamps wrote them, count as updated today + auto stamp{Today}; std::string line; while (std::getline(Input, line)) { if (false == line.empty() && line.back() == '\r') line.pop_back(); + if (line.starts_with(stamp_prefix)) + stamp = stamp_day(line, Today); if (line.empty() || line.front() == '#') continue; // the name goes last, it's the rest of the line after the separator @@ -109,7 +170,8 @@ std::size_t store::read(std::istream &Input) { auto const name{line.substr(separator + 1)}; if (false == km.has_value() || name.empty()) continue; - m_states[name] = state{*km, guessed}; + m_states[name] = state{*km, guessed, stamp}; + m_read_latest = std::max(m_read_latest.value_or(stamp), stamp); ++count; } return count; @@ -117,9 +179,23 @@ std::size_t store::read(std::istream &Input) { void store::write(std::ostream &Output) const { Output << "# odometer states of the vehicles: , ~ for one counted from a made up state\n"; + Output << "# the states after a line \"" << stamp_prefix << "\" were last updated on that day (UTC)\n"; Output << std::fixed << std::setprecision(4); - for (auto const &[name, state] : m_states) - Output << (state.guessed ? "~" : "") << state.km << ' ' << name << '\n'; + // by the day, then by the name as the map has them + std::vector::value_type const *> entries; + entries.reserve(m_states.size()); + for (auto const &entry : m_states) + entries.push_back(&entry); + std::ranges::stable_sort(entries, {}, [](auto const *Entry) { return Entry->second.updated; }); + std::optional group; + for (auto const *entry : entries) { + auto const &written{entry->second}; + if (group != written.updated) { + group = written.updated; + Output << stamp_prefix << format_day(written.updated) << '\n'; + } + Output << (written.guessed ? "~" : "") << written.km << ' ' << entry->first << '\n'; + } } std::optional store::find(std::string const &Vehicle) const { @@ -129,6 +205,13 @@ std::optional store::find(std::string const &Vehicle) const { return lookup->second.km; } +std::optional store::updated(std::string const &Vehicle) const { + auto const lookup{m_states.find(Vehicle)}; + if (lookup == m_states.end()) + return std::nullopt; + return lookup->second.updated; +} + bool store::guessed(std::string const &Vehicle) const { auto const lookup{m_states.find(Vehicle)}; return lookup != m_states.end() && lookup->second.guessed; @@ -140,10 +223,10 @@ bool store::newer(state const &Left, state const &Right) { return Left.km > Right.km; } -void store::record(std::string const &Vehicle, reading const &Odometer) { +void store::record(std::string const &Vehicle, reading const &Odometer, day const Today) { if (Vehicle.empty() || false == valid(Odometer.km)) return; - state const recorded{Odometer.km, Odometer.source == origin::guessed}; + state const recorded{Odometer.km, Odometer.source == origin::guessed, Today}; auto const lookup{m_states.find(Vehicle)}; if (lookup == m_states.end()) { if (false == Odometer.moved()) @@ -154,7 +237,10 @@ void store::record(std::string const &Vehicle, reading const &Odometer) { } if (false == newer(recorded, lookup->second)) return; + // a clock set back doesn't move the day back + auto const latest{std::max(lookup->second.updated, Today)}; lookup->second = recorded; + lookup->second.updated = latest; m_modified = true; } @@ -171,11 +257,32 @@ void record(store &States, std::string const &Vehicle, bool const Drivercab, rea void store::merge(store const &Other) { for (auto const &[name, other] : Other.m_states) { auto const [lookup, added] {m_states.try_emplace(name, other)}; - if (false == added && newer(other, lookup->second)) - lookup->second = other; + if (added) + continue; + auto &mine{lookup->second}; + auto const latest{std::max(mine.updated, other.updated)}; + if (newer(other, mine)) + mine = other; + mine.updated = latest; } } +std::size_t store::expire(day const Today, std::chrono::days const Period) { + if (Period <= std::chrono::days::zero()) + return 0; + // not from a later Today alone: a clock set forward, or the first save after a break, doesn't drop every state not + // run in this session + auto const since{std::min(Today, m_read_latest.value_or(Today))}; + return std::erase_if(m_states, [since, Period](auto const &Entry) { return since - Entry.second.updated > Period; }); +} + +bool store::holds(store const &Other) const { + return std::all_of(Other.m_states.begin(), Other.m_states.end(), [this](auto const &Entry) { + auto const lookup{m_states.find(Entry.first)}; + return lookup != m_states.end() && false == newer(Entry.second, lookup->second); + }); +} + std::optional read_legacy(std::istream &Input) { std::stringstream content; content << Input.rdbuf(); @@ -277,20 +384,46 @@ store &states() { return odometers; } -bool save(store &States, std::filesystem::path const &File) { - if (false == States.modified()) +namespace { + +// the states as the file holds them once written, the km rounded to the digits written +store as_written(store const &States, day const Today) { + std::stringstream text; + States.write(text); + store result; + result.read(text, Today); + return result; +} + +} // namespace + +bool save(store &States, std::filesystem::path const &File, day const Today, std::chrono::days const Period) { + if (false == States.modified() && false == States.unconfirmed()) return true; std::error_code error; + std::size_t expired{0}; if (File.has_parent_path()) std::filesystem::create_directories(File.parent_path(), error); // other simulations on the machine (multiplayer, parallel runs) keep their states in the same file: what they // saved since this one read it is merged in, not overwritten { + store saved; std::ifstream input{File, std::ios::binary}; - if (input.is_open()) { - store saved; - saved.read(input); - States.merge(saved); + if (input.is_open()) + saved.read(input, Today); + States.merge(saved); + // the vehicles not run for long, of this simulation and of the others alike, so the file doesn't keep every + // vehicle ever run. they're logged once the file is written without them: a save that doesn't write it leaves + // them in it (the next save that writes it drops them again), and a write that fails is tried again + expired = States.expire(Today, Period); + // another simulation that read the file before the last save of this one and put its own in place after it + // dropped the states this one wrote. when the file holds them all, the same or newer, there's nothing to write + if (false == States.modified()) { + if (saved.holds(as_written(States, Today))) { + States.confirmed(); + return true; + } + WriteLog("Odometer states saved to \"" + File.string() + "\" are missing from it, saving them again"); } } // written aside first, a crash in the middle of a write doesn't lose the states. the file aside is this process' @@ -325,6 +458,8 @@ bool save(store &States, std::filesystem::path const &File) { return false; } States.saved(); + if (expired > 0) + WriteLog(std::format("Odometer states of {} vehicles not updated for {} days dropped", expired, Period.count())); return true; } diff --git a/vehicle/odometer.h b/vehicle/odometer.h index 9708311f4..4fe369764 100644 --- a/vehicle/odometer.h +++ b/vehicle/odometer.h @@ -9,6 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once +#include #include #include #include @@ -23,6 +24,16 @@ http://mozilla.org/MPL/2.0/. // their own files namespace odometer { +// a calendar day, in UTC +using day = std::chrono::sys_days; +day today(); + +// a state not updated for longer than this is dropped from the store when it's saved: the vehicle wasn't run for that +// long. it's odometer.expiry in eu07.ini (global_settings::odometer_expiry), a year unless set there, 0 for never. +// a year so the vehicles of the scenarios played once a season or once a year, and of the players who take a break of a +// few months, keep their states; the file of the vehicles run within a year stays small all the same +std::chrono::days expiry(); + // the saved odometer states of the vehicles, km by vehicle name. the name is the one the scenario gives the vehicle // (the name of its node, TDynamicObject::name(), e.g. EU07-424), the only identity a vehicle has between the sessions: // the vehicles of the same name in any scenarios share one state, whatever their type, and a vehicle the scenario @@ -31,42 +42,70 @@ namespace odometer { class store { public: // reads the states written by write(). lines " ", "~ " for a state counted - // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read - std::size_t read(std::istream &Input); + // from a made up one, '#' starts a comment line, a malformed line is skipped. returns the number of states read. + // the day a state was last updated is in a comment line "# updated " before it, which the builds + // without the stamps skip as any comment. a state with no stamp before it (a file of such a build) or with a + // malformed one counts as updated Today. a stamp is kept as written, also one later than Today (a clock set back + // doesn't move the days of the states back, expire() doesn't measure from them) + std::size_t read(std::istream &Input, day Today = today()); + // the states grouped by the day they were last updated, the oldest first, each group after its stamp line void write(std::ostream &Output) const; std::optional find(std::string const &Vehicle) const; // the state of the vehicle is counted from a made up one, which the cab's counter can still replace bool guessed(std::string const &Vehicle) const; + // the day the state of the vehicle was last updated + std::optional updated(std::string const &Vehicle) const; // records the state of a vehicle. one not in the store yet gets in only once it has run, so the vehicles // standing in the sceneries don't fill the file. a recorded state is replaced only by a newer one: a larger - // one, or a known one in place of a guessed one - void record(std::string const &Vehicle, reading const &Odometer); + // one, or a known one in place of a guessed one. a state recorded is updated Today, or keeps its later day: the day + // of a state never goes back + void record(std::string const &Vehicle, reading const &Odometer, day Today = today()); // takes the states of the other store (the file, as other simulations have saved it since) newer than these. // the odometers only count up, so of two states of a vehicle the larger is the newer one. they aren't added - // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles + // up: two simulations on one machine (multiplayer) count the same runs of the same vehicles. a state is updated + // on the later of the days the two stores have void merge(store const &Other); + // drops the states not updated for longer than Period, 0 for none. the period is measured back from Today, or from + // the latest day of the states read() took when that's earlier: the last day the file was updated before this + // simulation read it. so a clock set forward doesn't drop the states at once (nor one set back, the days of the + // states are then later than Today), and a player back after a break keeps them in the session he comes back in; + // the states this session records, updated Today, don't count. returns the number dropped + std::size_t expire(day Today, std::chrono::days Period); + // this store holds every state of the other one, the same or a newer one + bool holds(store const &Other) const; // there are states recorded since they were last saved bool modified() const { return m_modified; } - void saved() { m_modified = false; } + // the states were written to the file. until a later save finds them there (confirmed()), they may have been lost to + // another simulation's save, which read the file before this one wrote it and put its own in place after + void saved() { + m_modified = false; + m_unconfirmed = true; + } + bool unconfirmed() const { return m_unconfirmed; } + void confirmed() { m_unconfirmed = false; } std::size_t size() const { return m_states.size(); } private: struct state { double km{0.0}; bool guessed{false}; + day updated{}; }; // the first state is newer than the second one static bool newer(state const &Left, state const &Right); std::map m_states; + // the latest day of the states read() took + std::optional m_read_latest; bool m_modified{false}; + bool m_unconfirmed{false}; }; // the vehicle is one the store keeps: one with a driver's cab, which can show its odometer on the cab's counter or a // python screen. that's -// - a vehicle whose type has a cab (Drivercab, TMoverParameters::HasDriverCab(): it has the driver's brake valve). that +// - a vehicle whose type has a cab (Drivercab, physics::Vehicle::HasDriverCab(): it has the driver's brake valve). that // includes the locomotives and units the AI runs before a player's cab loads them, their made up states stay // replaceable by the cab's counter // - a vehicle whose cab showed the odometer in this session (reading::shown): the cab was loaded for a player, or a @@ -113,9 +152,12 @@ bool persistent(); store &states(); std::filesystem::path file(); // writes the store to the file when anything was recorded since, merged with what other simulations saved in the -// file meanwhile. it's written to a file of this process aside first, then put in place. returns false when the -// write failed -bool save(store &States, std::filesystem::path const &File); +// file meanwhile. it's written to a file of this process aside first, then put in place. with nothing recorded since, +// the file is read once more after a write, and written again when it lacks any of the states (another simulation's +// save put its file over this one's); otherwise left as it is. the states, those of the other simulations included, +// not updated for longer than Period (store::expire()) are dropped first; the number dropped is logged by the save that +// writes the file without them. returns false when the write failed +bool save(store &States, std::filesystem::path const &File, day Today = today(), std::chrono::days Period = expiry()); // saves the store of the simulation to its file. a test run doesn't save it bool save(); diff --git a/vehicle/odometerreading.h b/vehicle/odometerreading.h index 286b2da5a..e5d0e7b00 100644 --- a/vehicle/odometerreading.h +++ b/vehicle/odometerreading.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -// the odometer of a vehicle (eu07/maszyna#72), the part the vehicle physics (TMoverParameters::Odometer) keeps: plain +// the odometer of a vehicle (eu07/maszyna#72), the part the vehicle physics (physics::Vehicle::Odometer) keeps: plain // data, without the store and its files, which are in vehicle/odometer.h namespace odometer { diff --git a/vehicle/pulleemode.h b/vehicle/pulleemode.h new file mode 100644 index 000000000..e1b7a73ed --- /dev/null +++ b/vehicle/pulleemode.h @@ -0,0 +1,35 @@ +/* +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 + +#include +#include + +// the pullee mode ("jazda ciągniona", MaSzyna-EU07/maszyna#64): a vehicle prepared for being hauled dead in a train, +// physics::Vehicle::PulleeModeSwitch(). a scenery asks for it with the parameter H among the ones written after the +// coupling of the vehicle, split by dots: "3.H", or with others, "3.BG.H" +// node -1 0 EU160-001 dynamic pkp/vectron_v1 1293-107 wariant_7w 0 nobody 3.H 0 enddynamic +namespace pullee_mode { + +// whether the parameters of a vehicle, the text after the first dot of its coupling entry, ask for the mode. a +// parameter is told by its first letter, as the others are (B brakes, W wheels, T temperatures, L load), in either +// case; the letters after the H are left for later +inline bool requested(std::string_view const Parameters) { + auto first{true}; // of a parameter + for (auto const character : Parameters) { + if (first && std::toupper(static_cast(character)) == 'H') { + return true; + } + first = character == '.'; + } + return false; +} + +} // namespace pullee_mode diff --git a/vehicle/signalpassing.cpp b/vehicle/signalpassing.cpp new file mode 100644 index 000000000..58d691760 --- /dev/null +++ b/vehicle/signalpassing.cpp @@ -0,0 +1,30 @@ +/* +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/signalpassing.h" + +namespace signal_passing { + +bool seen_ahead_when_found( double const Distance, bool const Standing ) { + + return Distance >= ( Standing ? 0.0 : -moving_tolerance ); +} + +bool seen_ahead_on_update( double const Distance, bool const Seenahead ) { + + return Seenahead || Distance >= 0.0; +} + +bool passed_now( bool const Elapsedbefore, bool const Elapsed, bool const Seenahead ) { + + return Elapsed && !Elapsedbefore && Seenahead; +} + +} // namespace signal_passing diff --git a/vehicle/signalpassing.h b/vehicle/signalpassing.h new file mode 100644 index 000000000..33f2e5265 --- /dev/null +++ b/vehicle/signalpassing.h @@ -0,0 +1,38 @@ +/* +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 + +// when a point of the AI's speed table (a signal above all) counts as passed by the train: the test mode's +// "signal passed at danger" and the blackbox record of passed signals (TController::CheckSignalPassed) +namespace signal_passing { + +// how far behind the head a point found by the scan of a moving train may lie and still count as one the head +// had ahead [m]. GetDistanceToEvent() finds the distance in steps of a metre from the position of the memory +// cell, so a signal just ahead of the head may come out a little behind it +inline constexpr double moving_tolerance { 5.0 }; + +// whether a point the scan finds Distance [m] ahead of the head (negative: behind it) counts as one the head had +// ahead. a moving train may be just passing it, so a point up to moving_tolerance behind counts. a standing train +// isn't passing anything: a point found behind its head was passed before (a train set or stopped past a signal), +// and counts only once an update finds it ahead. +// known gap: the distance can be off by about half a metre (GetDistanceToEvent() takes the nearest of samples a +// metre apart), so a train standing a few decimetres short of a signal may find it just behind the head, and if it +// then runs past it at stop, that isn't reported. a tolerance for a standing train wouldn't close it: the first +// update marks a point behind the head elapsed (TSpeedPos::Update()), so such a train would be reported as passing +// the signal at once, while it stands short of it. the AI stops 8-15 m short of a signal +bool seen_ahead_when_found( double Distance, bool Standing ); + +// whether the head had the point ahead, after an update finds it Distance [m] ahead of the head +bool seen_ahead_on_update( double Distance, bool Seenahead ); + +// whether an update of a point reports it as passed: it became elapsed in this update, and the head had it ahead +bool passed_now( bool Elapsedbefore, bool Elapsed, bool Seenahead ); + +} // namespace signal_passing diff --git a/vehicle/smoke.cpp b/vehicle/smoke.cpp index f5f64bef0..b0805374d 100644 --- a/vehicle/smoke.cpp +++ b/vehicle/smoke.cpp @@ -10,37 +10,37 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "vehicle/smoke.h" -#include "McZapkie/MOVER.h" +#include "physics/vehicle.h" namespace smoke { namespace { // how hard the engine works, scaling the spawn rate of the source -double engine_load(TMoverParameters const &Mover) { - if (Mover.dizel_spinup) { +double engine_load(physics::Vehicle const &Physics) { + if (Physics.diesel.spinningUp) { // starting up, it puffs harder the faster it turns - return ((Mover.enrot / 4) * 0.01); + return ((Physics.enrot / 4) * 0.01); } - auto const rpmrise{(Mover.DElist[Mover.MainCtrlPosNo].RPM - Mover.enrot) / 60}; - if (Mover.DirAbsolute == 0 || Mover.Im == 0) { + auto const rpmrise{(Physics.DElist[Physics.MainCtrlPosNo].RPM - Physics.enrot) / 60}; + if (Physics.DirAbsolute == 0 || Physics.Im == 0) { // idling: speeding up to the revolutions of the master controller - return ((rpmrise * 0.02) * (Mover.EnginePower * 0.005)); + return ((rpmrise * 0.02) * (Physics.EnginePower * 0.005)); } // under load: the more current the traction motors draw, the more smoke - return ((rpmrise * (std::sqrt(Mover.Im) * 0.01) * 0.02) * (Mover.EnginePower * 0.005)); + return ((rpmrise * (std::sqrt(Physics.Im) * 0.01) * 0.02) * (Physics.EnginePower * 0.005)); } } // namespace -float vehicle_spawn_count(TMoverParameters const &Mover, bool const Ontracks, spawn_rate const &Rate, double const Timedelta) { - if (false == Ontracks || Mover.dizel_FiringCountdown > 0.0) { +float vehicle_spawn_count(physics::Vehicle const &Physics, bool const Ontracks, spawn_rate const &Rate, double const Timedelta) { + if (false == Ontracks || Physics.diesel.firingCountdown > 0.0) { return 0.f; } // the steady rate of the source, the way a source of the scenery spawns... auto const steady{std::min(static_cast(Rate.pending + (Rate.rate * Timedelta * Rate.fidelity)), Rate.limit)}; // ...and on top of it the share of the engine - return std::min(static_cast(steady + (Rate.rate * Timedelta * Rate.fidelity * engine_load(Mover))), Rate.limit); + return std::min(static_cast(steady + (Rate.rate * Timedelta * Rate.fidelity * engine_load(Physics))), Rate.limit); } } // namespace smoke diff --git a/vehicle/smoke.h b/vehicle/smoke.h index dbcc131ae..0391c70ff 100644 --- a/vehicle/smoke.h +++ b/vehicle/smoke.h @@ -9,7 +9,7 @@ http://mozilla.org/MPL/2.0/. #pragma once -class TMoverParameters; +namespace physics { class Vehicle; } // the smoke of a vehicle's engine, let out by the smoke sources of its model (rendering/particles.h) namespace smoke { @@ -25,7 +25,7 @@ struct spawn_rate { // number of particles the smoke source of a vehicle has to spawn after Timedelta seconds: the steady rate of the // source, plus a share which grows with the work of its engine. a vehicle taken off the tracks (Ontracks false: gone through a portal, or waiting in the pool of the road // traffic) puffs no more, the particles it already let out fade away as usual -// an engine the starter turns but which hasn't fired yet (TMoverParameters::dizel_FiringCountdown) lets out no smoke either -float vehicle_spawn_count(TMoverParameters const &Mover, bool Ontracks, spawn_rate const &Rate, double Timedelta); +// an engine the starter turns but which hasn't fired yet (physics::Vehicle::diesel.firingCountdown) lets out no smoke either +float vehicle_spawn_count(physics::Vehicle const &Physics, bool Ontracks, spawn_rate const &Rate, double Timedelta); } // namespace smoke diff --git a/vehicle/timetableservice.cpp b/vehicle/timetableservice.cpp new file mode 100644 index 000000000..eac25815b --- /dev/null +++ b/vehicle/timetableservice.cpp @@ -0,0 +1,49 @@ +/* +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/timetableservice.h" + +#include "physics/vehicle.h" + +namespace timetable { + +bool opens_doors(physics::Vehicle const &Vehicle, service_flags const &Flags) { + switch (Vehicle.Doors.open_control) { + case control_t::conductor: + case control_t::driver: + return true; + case control_t::mixed: + // left to the passengers, unless the timetable has the driver open them all + return Flags.central_doors == tristate::yes; + default: + return false; + } +} + +std::optional doorstep(service_flags const &Flags) { + switch (Flags.doorstep) { + case tristate::yes: + return true; + case tristate::no: + return false; + default: + return std::nullopt; + } +} + +bool has_conductor(service_flags const &Flags) { + return Flags.conductor != tristate::no; +} + +bool makes_brake_test(service_flags const &Flags) { + return Flags.brake_test != tristate::no; +} + +} // namespace timetable diff --git a/vehicle/timetableservice.h b/vehicle/timetableservice.h new file mode 100644 index 000000000..b1c32576f --- /dev/null +++ b/vehicle/timetableservice.h @@ -0,0 +1,37 @@ +/* +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 + +#include + +#include "world/timetableflags.h" + +namespace physics { class Vehicle; } + +// what the AI driver does at a stop and on the way, as the service flags of the timetable ask (eu07/maszyna#95). with +// no flags each answer is the one the AI gave before the flags +namespace timetable { + +// whether the driver opens the doors of the consist from the cab at a stop, Vehicle being the one he drives: the doors +// the conductor or the driver opens, and with the central door opening also the ones of mixed control, which are +// otherwise left to the passengers +bool opens_doors(physics::Vehicle const &Vehicle, service_flags const &Flags); + +// the state the driver sets the doorsteps to before he opens the doors at a stop, none when he leaves them as they are +std::optional doorstep(service_flags const &Flags); + +// whether a conductor serves the train: gives the departure signal (by radio or by voice) and keeps the first door +// open for himself until the departure +bool has_conductor(service_flags const &Flags); + +// whether the driver makes the running brake test after the departure +bool makes_brake_test(service_flags const &Flags); + +} // namespace timetable diff --git a/vehicle/universaldrag.h b/vehicle/universaldrag.h new file mode 100644 index 000000000..d25f93c57 --- /dev/null +++ b/vehicle/universaldrag.h @@ -0,0 +1,138 @@ +/* +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 + +#include +#include +#include +#include + +// smooth regulation of the universal cab controls (MaSzyna-EU07/maszyna#62): a universal whose definition in the +// .mmd has "drag: " can be dragged with the mouse to any position between its ends (0 and 1), and stays +// where it is let go, like a window opened a crack or a sun blind pulled half way down. a click without dragging and +// the keys still move it to its ends, as they do any universal. universals without the key work as they always did +namespace universal_drag { + +// the way the mouse moves to take the control towards its end 1 (to open it); none: the control can't be dragged +enum class direction { none, up, down, left, right }; + +// the direction the value of the drag: key gives, nothing for a value it doesn't know +inline std::optional parse(std::string_view const Value) { + if (Value == "yes" || Value == "true" || Value == "1" || Value == "up") { + return direction::up; + } + if (Value == "down") { + return direction::down; + } + if (Value == "left") { + return direction::left; + } + if (Value == "right") { + return direction::right; + } + if (Value == "no" || Value == "false" || Value == "0" || Value == "none") { + return direction::none; + } + return std::nullopt; +} + +// a push (impulse) universal springs back when it is let go, so it can't be left anywhere in between +inline direction effective(direction const Drag, bool const Push) { + return Push ? direction::none : Drag; +} + +// the position of the control, kept between its ends +inline float clamp(double const Position) { + return static_cast(std::clamp(Position, 0.0, 1.0)); +} + +// how far the cursor moving by Dx, Dy pixels (y grows downwards, as the cursor's does) takes the control along the +// Drag direction, as a fraction of its full travel; Size is the move in pixels which takes it from one end to the other +inline double along(direction const Drag, double const Dx, double const Dy, double const Size) { + if (Size <= 0.0) { + return 0.0; + } + switch (Drag) { + case direction::up: + return -Dy / Size; + case direction::down: + return Dy / Size; + case direction::left: + return -Dx / Size; + case direction::right: + return Dx / Size; + default: + return 0.0; + } +} + +// the position the keys and a click move the control to: the end farther from the position it is set to, as for +// the two-state universals: a control open less than half way opens fully, one open half way or more closes +inline float toggled(float const Desired) { + return Desired < 0.5f ? 1.f : 0.f; +} + +// the travel of the cursor along the direction of the drag, as a fraction of the full travel of the control, under +// which letting the button go counts as a click rather than a drag +inline constexpr double click_travel{0.02}; + +// one drag of a control, from the press of the mouse button to its release +class drag { + + public: + drag(direction const Drag, float const Position) : m_direction{Drag}, m_position{clamp(Position)}, m_start{m_position} {} + + // the cursor moved to X, Y; Size is the move in pixels which takes the control from one end to the other. + // the first position of the cursor is only where the drag starts from: when the cursor gets hidden for the drag + // it can be put elsewhere. returns whether the position of the control changed + bool move(double const X, double const Y, double const Size) { + if (false == m_started) { + m_started = true; + m_x = X; + m_y = Y; + return false; + } + auto const step{along(m_direction, X - m_x, Y - m_y, Size)}; + m_x = X; + m_y = Y; + m_travel += std::abs(step); + // the position follows each move from where it is, so after the control reached its end, moving the cursor + // back takes it back at once rather than after the overshoot is undone + auto const position{clamp(m_position + step)}; + if (position == m_position) { + return false; + } + m_position = position; + return true; + } + // the position the control is dragged to + float position() const { + return m_position; + } + // the position the control was in when the drag started + float start() const { + return m_start; + } + // whether letting the button go now is a click rather than a drag: the cursor barely moved along the direction + bool is_click() const { + return m_travel < click_travel; + } + + private: + direction m_direction; + float m_position; + float m_start; + bool m_started{false}; + double m_x{0.0}; + double m_y{0.0}; + double m_travel{0.0}; // the moves of the cursor along the direction, either way, as fractions of the full travel +}; + +} // namespace universal_drag diff --git a/vehicle/uphillstart.cpp b/vehicle/uphillstart.cpp index dd1895b11..534839093 100644 --- a/vehicle/uphillstart.cpp +++ b/vehicle/uphillstart.cpp @@ -12,6 +12,37 @@ http://mozilla.org/MPL/2.0/. namespace uphill_start { +bool begins(situation const &Now) { + + return Now.standing + // the whole train at a stand, not only its head stopped for a moment while the train rolls back + && (Now.consist_velocity > rollback_velocity) && Now.speed_up && Now.speed_asked + // only with the train brake still applied to hold the train + && Now.train_brake_applied + // and charged to what the pipe has, or the brake that holds the train has no air + && Now.consist_charged; +} + +bool rolls_back(situation const &Now) { + + return Now.consist_velocity < rollback_velocity; +} + +bool power_holds(situation const &Now, double const Holdtime) { + + return (Now.velocity > moving_velocity) || (Now.tractive_force > holding_force * Now.grade_force) || (Holdtime > hold_time); +} + +bool released(situation const &Now, double const Releasetime) { + + return Now.consist_released || (Releasetime > release_time); +} + +bool may_add_power(bool const Releasing, double const Tractiveforce, double const Holdingforce) { + + return (false == Releasing) || (Tractiveforce < holding_force * Holdingforce); +} + top_up_action brake_top_up( top_up &State, double const Brakeforce, double const Holdingforce, double const Brakeposition, double const Heldtime, double const Applicationtime) { diff --git a/vehicle/uphillstart.h b/vehicle/uphillstart.h index 108662cbe..e50876588 100644 --- a/vehicle/uphillstart.h +++ b/vehicle/uphillstart.h @@ -20,12 +20,88 @@ auto const top_up_position{4.0}; // full service: the furthest the train brake i // 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}; +auto const hold_time{45.0}; // [s] a locomotive that can't hold the train on its own power gets the brake off after it all the same +auto const release_time{60.0}; // [s] the longest the power stays on against the releasing brake (a hand brake doesn't come off) +auto const rollback_velocity{-0.5}; // [km/h] the train as a whole rolling back faster than this gives a start up +auto const moving_velocity{1.0}; // [km/h] the head of the train going forward faster than this is under way + +// what a start goes by, at a moment +struct situation { + bool standing{false}; // the head of the train at a stand + double velocity{0.0}; // of the head of the train, in the direction of travel [km/h] + // of the whole train, mass-weighted, in the direction of travel [km/h]: 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 + double consist_velocity{0.0}; + bool speed_up{false}; // the driver is asked to speed up + bool speed_asked{false}; // there is a speed to go at + bool train_brake_applied{false}; // the train brake handle is past running + double tractive_force{0.0}; // of the train, in the direction of travel [N] + double grade_force{0.0}; // the grade force on the train [N] + bool consist_released{false}; // the brakes of the train are off, the hold of the start not counted + // the brakes of the train charged to what the pipe has: else the brake that holds the train has no air + bool consist_charged{true}; +}; + +// a start begins: the whole train at a stand on the train brake, charged, and asked to go +bool begins(situation const &Now); +// the train rolls back all the same: the rules for a train slipping back take over +bool rolls_back(situation const &Now); +// the power holds the train, so the train brake can be released. Holdtime: since the start began, or since the last +// step of the top-up [s] +bool power_holds(situation const &Now, double Holdtime); +// the release phase is over: the brakes are off, or they don't come off. Releasetime: since it began [s] +bool released(situation const &Now, double Releasetime); +// power may be added. 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 +bool may_add_power(bool Releasing, double Tractiveforce, double Holdingforce); + // 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 }; +// where a start has got to +enum class Phase { + none, // no start uphill + holding, // the train brake holds the train until the power does + releasing // the power holds the train and the train brake is being released +}; + +// the start uphill as the driver keeps it in mind +struct Progress { + Phase phase{Phase::none}; + bool toppingUp{false}; // in this step the train brake is applied further, before the locomotive brake comes off + top_up brakeTopUp; // what has been done to apply the train brake further + double startTime{0.0}; // when the start began, or the train brake last held the train [s] + double releaseTime{0.0}; // when the release began [s] + double tractiveForce{0.0}; // of the consist, in the direction of travel [N] + double holdingForce{0.0}; // the grade force on the consist [N] + + bool IsActive() const { return phase != Phase::none; } + bool IsHolding() const { return phase == Phase::holding; } + bool IsReleasing() const { return phase == Phase::releasing; } + // the start begins at the given time, the train brake holding the train + void Begin(double const Time) + { + phase = Phase::holding; + brakeTopUp = {}; + startTime = Time; + } + // the power holds the train from the given time, the train brake is released + void Release(double const Time) + { + phase = Phase::releasing; + releaseTime = Time; + } + void End() + { + phase = Phase::none; + toppingUp = false; + } +}; + 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 diff --git a/widgets/map.cpp b/widgets/map.cpp index d750bbb60..19b509814 100644 --- a/widgets/map.cpp +++ b/widgets/map.cpp @@ -8,6 +8,7 @@ #include "vehicle/Driver.h" #include "model/AnimModel.h" #include "application/application.h" +#include "vehicle/DynObj.h" ui::map_panel::map_panel() : ui_panel(STR_C("Map"), false) { diff --git a/widgets/perfgraphs.cpp b/widgets/perfgraphs.cpp index 041a25134..83221d696 100644 --- a/widgets/perfgraphs.cpp +++ b/widgets/perfgraphs.cpp @@ -49,13 +49,13 @@ void perfgraph_panel::render_contents() { if (!stopwatch) return; - history[pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); - const std::string label = std::to_string(history[pos]) + "ms"; + history[history_pos] = static_cast(static_cast(stopwatch->last().count()) / 1000.0); + const std::string label = std::to_string(history[history_pos]) + "ms"; - pos++; - if (pos >= history.size()) - pos = 0; + history_pos++; + if (history_pos >= history.size()) + history_pos = 0; ImGui::SliderFloat(STR_C("Range"), &max, 0.1f, 250.0f); - ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); + ImGui::PlotLines("##timer", &history[0], static_cast(history.size()), static_cast(history_pos), label.c_str(), 0.0f, max, ImVec2(500, 200)); } diff --git a/widgets/perfgraphs.h b/widgets/perfgraphs.h index d3ddb3c6d..961f98fcd 100644 --- a/widgets/perfgraphs.h +++ b/widgets/perfgraphs.h @@ -3,7 +3,7 @@ class perfgraph_panel : public ui_panel { std::array history = { 0 }; - size_t pos = 0; + size_t history_pos = 0; enum timers_e { gfx_total = 0, diff --git a/widgets/trainingcard.cpp b/widgets/trainingcard.cpp index b261a5d4d..3f2f5e0ff 100644 --- a/widgets/trainingcard.cpp +++ b/widgets/trainingcard.cpp @@ -2,6 +2,8 @@ #include "widgets/trainingcard.h" #include "simulation/simulation.h" #include "utilities/utilities.h" +#include "physics/vehicle.h" +#include "vehicle/DynObj.h" #ifdef __linux__ #include @@ -177,7 +179,7 @@ void trainingcard_panel::render_contents() { state.store(2); if (simulation::Trains.sequence().size() > 0) - distance = static_cast(simulation::Trains.sequence()[0]->Dynamic()->MoverParameters->DistCounter); + distance = static_cast(simulation::Trains.sequence()[0]->Dynamic()->physics->DistCounter()); if (save_thread.joinable()) save_thread.join(); diff --git a/widgets/vehicleparams.cpp b/widgets/vehicleparams.cpp index 14ca9923c..60420b5e6 100644 --- a/widgets/vehicleparams.cpp +++ b/widgets/vehicleparams.cpp @@ -4,6 +4,7 @@ #include "application/driveruipanels.h" #include "vehicle/Driver.h" #include "vehicle/Train.h" +#include "physics/vehicle.h" ui::vehicleparams_panel::vehicleparams_panel(const std::string &vehicle) : ui_panel(std::string(STR("Vehicle parameters")) + ": " + vehicle, false), m_vehicle_name(vehicle) { @@ -46,7 +47,7 @@ void ui::vehicleparams_panel::draw_infobutton(const char *str, ImVec2 pos, const ImGui::PopStyleColor(4); } -void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover) +void ui::vehicleparams_panel::draw_mini(const physics::Vehicle &physics) { if (vehicle_mini == null_handle) return; @@ -62,34 +63,34 @@ void ui::vehicleparams_panel::draw_mini(const TMoverParameters &mover) { ImGui::Image((ImTextureID)(intptr_t)(tex.get_id()), ImVec2(x, y), ImVec2(0, 1), ImVec2(1, 0)); - if (mover.Pantographs[end::rear].is_active) + if (physics.pantographs[VehicleEnd::rear].is_active) draw_infobutton("╨╨╨", ImVec2(126, 10)); - if (mover.Pantographs[end::front].is_active) + if (physics.pantographs[VehicleEnd::front].is_active) draw_infobutton("╨╨╨", ImVec2(290, 10)); - if (mover.Battery) + if (physics.lowVoltage.IsBatteryOn()) draw_infobutton(STR_C("bat."), ImVec2(120, 55)); - if (mover.Mains) + if (physics.lineBreaker.IsClosed()) draw_infobutton(STR_C("main.")); - if (mover.ConverterFlag) + if (physics.converter.IsRunning()) draw_infobutton(STR_C("conv.")); - if (mover.CompressorFlag) + if (physics.air.compressor.IsRunning()) draw_infobutton(STR_C("comp.")); - if (mover.WarningSignal) + if (physics.WarningSignal()) draw_infobutton(STR_C("horn"), ImVec2(361, 11)); - if (mover.iLights[end::front] & light::redmarker_left) + if (physics.LitLights()[VehicleEnd::front] & light::redmarker_left) draw_infobutton("o", ImVec2(490, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (mover.iLights[end::front] & light::headlight_left) + else if (physics.LitLights()[VehicleEnd::front] & light::headlight_left) draw_infobutton("O", ImVec2(490, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (mover.iLights[end::front] & light::redmarker_right) + if (physics.LitLights()[VehicleEnd::front] & light::redmarker_right) draw_infobutton("o", ImVec2(443, 71), ImVec4(1.0f, 0.0f, 0.0f, 1.0f)); - else if (mover.iLights[end::front] & light::headlight_right) + else if (physics.LitLights()[VehicleEnd::front] & light::headlight_right) draw_infobutton("O", ImVec2(443, 71), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); - if (mover.iLights[end::front] & light::headlight_upper) + if (physics.LitLights()[VehicleEnd::front] & light::headlight_upper) draw_infobutton("O", ImVec2(467, 18), ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); } ImGui::EndChild(); @@ -137,28 +138,28 @@ void ui::vehicleparams_panel::render_contents() } TDynamicObject &vehicle = *vehicle_ptr; - TMoverParameters &mover = *vehicle.MoverParameters; + physics::Vehicle &physics = *vehicle.physics; std::vector lines; std::array buffer; - auto const isdieselenginepowered{(mover.EngineType == TEngineType::DieselElectric) || (mover.EngineType == TEngineType::DieselEngine)}; - auto const isdieselinshuntmode{mover.ShuntMode && mover.EngineType == TEngineType::DieselElectric}; + auto const isdieselenginepowered{(physics.EngineType == TEngineType::DieselElectric) || (physics.EngineType == TEngineType::DieselEngine)}; + auto const isdieselinshuntmode{physics.ShuntMode && physics.EngineType == TEngineType::DieselElectric}; std::snprintf(buffer.data(), buffer.size(), STR_C("Devices: %c%c%c%c%c%c%c%c%c%c%c%c%c%c%s%s\nPower transfers: %.0f@%.0f%s%s%s%.0f@%.0f"), // devices - (mover.Battery ? 'B' : '.'), (mover.Mains ? 'M' : '.'), (mover.FuseFlag ? '!' : '.'), (mover.Pantographs[end::rear].is_active ? (mover.PantRearVolt > 0.0 ? 'O' : 'o') : '.'), - (mover.Pantographs[end::front].is_active ? (mover.PantFrontVolt > 0.0 ? 'P' : 'p') : '.'), (mover.PantPressLockActive ? '!' : (mover.PantPressSwitchActive ? '*' : '.')), - (mover.WaterPump.is_active ? 'W' : (false == mover.WaterPump.breaker ? '-' : (mover.WaterPump.is_enabled ? 'w' : '.'))), - (true == mover.WaterHeater.is_damaged ? '!' : (mover.WaterHeater.is_active ? 'H' : (false == mover.WaterHeater.breaker ? '-' : (mover.WaterHeater.is_enabled ? 'h' : '.')))), - (mover.FuelPump.is_active ? 'F' : (mover.FuelPump.is_enabled ? 'f' : '.')), (mover.OilPump.is_active ? 'O' : (mover.OilPump.is_enabled ? 'o' : '.')), - (false == mover.ConverterAllowLocal ? '-' : (mover.ConverterAllow ? (mover.ConverterFlag ? 'X' : 'x') : '.')), (mover.ConvOvldFlag ? '!' : '.'), - (mover.CompressorFlag ? 'C' : (false == mover.CompressorAllowLocal ? '-' : ((mover.CompressorAllow || mover.CompressorStart == start_t::automatic) ? 'c' : '.'))), - (mover.CompressorGovernorLock ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(mover.OilPump.pressure, 2) : "").c_str(), + (physics.lowVoltage.IsBatteryOn() ? 'B' : '.'), (physics.lineBreaker.IsClosed() ? 'M' : '.'), (physics.FuseFlag ? '!' : '.'), (physics.pantographs[VehicleEnd::rear].is_active ? (physics.pantographCircuit.RearVoltage() > 0.0 ? 'O' : 'o') : '.'), + (physics.pantographs[VehicleEnd::front].is_active ? (physics.pantographCircuit.FrontVoltage() > 0.0 ? 'P' : 'p') : '.'), (physics.pantographAir.IsPressureLockActive() ? '!' : (physics.pantographAir.IsPressureSwitchPrimed() ? '*' : '.')), + (physics.WaterPump.is_active ? 'W' : (false == physics.WaterPump.breaker ? '-' : (physics.WaterPump.is_enabled ? 'w' : '.'))), + (true == physics.WaterHeater.is_damaged ? '!' : (physics.WaterHeater.is_active ? 'H' : (false == physics.WaterHeater.breaker ? '-' : (physics.WaterHeater.is_enabled ? 'h' : '.')))), + (physics.FuelPump.is_active ? 'F' : (physics.FuelPump.is_enabled ? 'f' : '.')), (physics.OilPump.is_active ? 'O' : (physics.OilPump.is_enabled ? 'o' : '.')), + (false == physics.converter.LocalSwitchOn() ? '-' : (physics.converter.IsAllowed() ? (physics.converter.IsRunning() ? 'X' : 'x') : '.')), (physics.converter.IsOverloaded() ? '!' : '.'), + (physics.air.compressor.IsRunning() ? 'C' : (false == physics.air.compressor.LocalSwitchOn() ? '-' : ((physics.air.compressor.IsAllowed() || physics.air.compressor.config.start == start_t::automatic) ? 'c' : '.'))), + (physics.air.compressor.IsGovernorLocked() ? '!' : '.'), "", std::string(isdieselenginepowered ? STR(" oil pressure: ") + to_string(physics.OilPump.pressure, 2) : "").c_str(), // power transfers - mover.Couplers[end::front].power_high.voltage, mover.Couplers[end::front].power_high.current, std::string(mover.Couplers[end::front].power_high.is_local ? "" : "-").c_str(), - std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(mover.Couplers[end::rear].power_high.is_local ? "" : "-").c_str(), - mover.Couplers[end::rear].power_high.voltage, mover.Couplers[end::rear].power_high.current); + physics.Couplers[VehicleEnd::front].power_high.voltage, physics.Couplers[VehicleEnd::front].power_high.current, std::string(physics.Couplers[VehicleEnd::front].power_high.is_local ? "" : "-").c_str(), + std::string(vehicle.DirectionGet() ? ":<<:" : ":>>:").c_str(), std::string(physics.Couplers[VehicleEnd::rear].power_high.is_local ? "" : "-").c_str(), + physics.Couplers[VehicleEnd::rear].power_high.voltage, physics.Couplers[VehicleEnd::rear].power_high.current); ImGui::TextUnformatted(buffer.data()); @@ -166,20 +167,20 @@ void ui::vehicleparams_panel::render_contents() STR_C("Controllers:\n master: %d(%d), secondary: %s\nEngine output: %.1f, current: %.0f\nRevolutions:\n engine: %.0f, motors: %.0f\n engine fans: %.0f, motor fans: %.0f+%.0f, " "cooling fans: %.0f+%.0f"), // controllers - mover.MainCtrlPos, mover.MainCtrlActualPos, - std::string(isdieselinshuntmode ? to_string(mover.AnPos, 2) + STR(" (shunt mode)") : std::to_string(mover.ScndCtrlPos) + "(" + std::to_string(mover.ScndCtrlActualPos) + ")").c_str(), + physics.MainCtrlPos(), physics.MainCtrlActualPos, + std::string(isdieselinshuntmode ? to_string(physics.AnPos(), 2) + STR(" (shunt mode)") : std::to_string(physics.ScndCtrlPos()) + "(" + std::to_string(physics.ScndCtrlActualPos) + ")").c_str(), // engine - mover.EnginePower, std::abs(mover.TrainType == dt_EZT ? mover.ShowCurrent(0) : mover.Im), + physics.EnginePower, std::abs(physics.TrainType() == train_type::emu ? physics.ShowCurrent(0) : physics.Im), // revolutions - std::abs(mover.enrot) * 60, std::abs(mover.nrot) * mover.Transmision.Ratio * 60, mover.RventRot * 60, std::abs(mover.MotorBlowers[end::front].revolutions), - std::abs(mover.MotorBlowers[end::rear].revolutions), mover.dizel_heat.rpmw, mover.dizel_heat.rpmw2); + std::abs(physics.enrot) * 60, std::abs(physics.nrot()) * physics.Transmision.Ratio * 60, physics.RventRot * 60, std::abs(physics.MotorBlowers[VehicleEnd::front].revolutions), + std::abs(physics.MotorBlowers[VehicleEnd::rear].revolutions), physics.diesel.heat.rpmw, physics.diesel.heat.rpmw2); ImGui::TextUnformatted(buffer.data()); if (isdieselenginepowered) { - std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), mover.dizel_heat.Ts, mover.dizel_heat.To, mover.dizel_heat.temperatura1, - (mover.WaterCircuitsLink ? '-' : '|'), mover.dizel_heat.temperatura2); + std::snprintf(buffer.data(), buffer.size(), STR_C("\nTemperatures:\n engine: %.2f, oil: %.2f, water: %.2f%c%.2f"), physics.diesel.heat.Ts, physics.diesel.heat.To, physics.diesel.heat.temperatura1, + (physics.WaterCircuitsLink() ? '-' : '|'), physics.diesel.heat.temperatura2); ImGui::TextUnformatted(buffer.data()); } @@ -189,7 +190,7 @@ void ui::vehicleparams_panel::render_contents() for (auto const &delay : delays) { - if ((mover.BrakeDelayFlag & delay.first) == delay.first) + if ((physics.brakes.delaySetting & delay.first) == delay.first) { brakedelay += delay.second; } @@ -200,19 +201,19 @@ void ui::vehicleparams_panel::render_contents() STR_C("Brakes:\n train: %.2f, independent: %.2f, mode: %d, delay: %s, load flag: %d\nBrake cylinder pressures:\n train: %.2f, independent: %.2f, status: 0x%.2x\nPipe pressures:\n " "brake: %.2f (hat: %.2f), main: %.2f, control: %.2f\nTank pressures:\n auxiliary: %.2f, main: %.2f, control: %.2f"), // brakes - mover.fBrakeCtrlPos, mover.LocalBrakePosA, mover.BrakeOpModeFlag, brakedelay.c_str(), mover.LoadFlag, + physics.brakes.HandlePositionSmooth(), physics.brakes.IndependentPosition(), physics.brakes.operatingMode, brakedelay.c_str(), physics.brakes.loadSetting, // cylinders - mover.BrakePress, mover.LocBrakePress, mover.Hamulec->GetBrakeStatus(), + physics.brakes.cylinderPressure, physics.brakes.independentCylinderPressure, physics.brakes.distributor->GetBrakeStatus(), // pipes - mover.PipePress, mover.BrakeCtrlPos2, mover.ScndPipePress, mover.CntrlPipePress, + physics.brakePipe.Pressure(), physics.brakes.HandleCapPosition(), physics.mainPipe.Pressure(), physics.brakes.controlReservoirPressure, // tanks - mover.Hamulec->GetBRP(), mover.Compressor, mover.Hamulec->GetCRP()); + physics.brakes.distributor->GetBRP(), physics.air.MainReservoirPressure(), physics.brakes.distributor->GetCRP()); ImGui::TextUnformatted(buffer.data()); - if (mover.EnginePowerSource.SourceType == TPowerSource::CurrentCollector) + if (physics.EnginePowerSource.SourceType == TPowerSource::CurrentCollector) { - std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), mover.PantPress, (mover.bPantKurek3 ? '-' : '|')); + std::snprintf(buffer.data(), buffer.size(), STR_C(" pantograph: %.2f%cMT"), physics.pantographAir.Pressure(), (physics.pantographAir.IsConnectedToMainReservoir() ? '-' : '|')); ImGui::TextUnformatted(buffer.data()); } @@ -220,16 +221,16 @@ void ui::vehicleparams_panel::render_contents() STR_C("Forces:\n tractive: %.1f, brake: %.1f, friction: %.2f%s\nAcceleration:\n tangential: %.2f, normal: %.2f (path radius: %s)\nVelocity: %.2f, distance traveled: %.2f\nPosition: " "[%.2f, %.2f, %.2f]"), // forces - mover.Ft * 0.001f * - (mover.CabActive ? mover.CabActive : + physics.Ft() * 0.001f * + (physics.CabActive ? physics.CabActive : vehicle.ctOwner ? vehicle.ctOwner->Controlling()->CabActive : 1) + 0.001f, - mover.Fb * 0.001f, mover.Adhesive(mover.RunningTrack.friction), (mover.SlippingWheels ? " (!)" : ""), + physics.Fb() * 0.001f, physics.Adhesive(physics.RunningTrack.friction), (physics.SlippingWheels() ? " (!)" : ""), // acceleration - mover.AccSVBased, mover.AccN + 0.001f, std::string(std::abs(mover.RunningShape.R) > 10000.0 ? "~0" : to_string(mover.RunningShape.R, 0)).c_str(), + physics.AccSVBased(), physics.AccN() + 0.001f, std::string(std::abs(physics.RunningShape.R) > 10000.0 ? "~0" : to_string(physics.RunningShape.R, 0)).c_str(), // velocity - vehicle.GetVelocity(), mover.DistCounter, + vehicle.GetVelocity(), physics.DistCounter(), // position vehicle.GetPosition().x, vehicle.GetPosition().y, vehicle.GetPosition().z); @@ -248,8 +249,8 @@ void ui::vehicleparams_panel::render_contents() while (vehicle_iter) { - TrainsetPowerMeter.first += vehicle_iter->MoverParameters->EnergyMeter.first; - TrainsetPowerMeter.second += vehicle_iter->MoverParameters->EnergyMeter.second; + TrainsetPowerMeter.first += vehicle_iter->physics->EnergyMeter.first; + TrainsetPowerMeter.second += vehicle_iter->physics->EnergyMeter.second; vehicle_iter = vehicle_iter->Prev(); } @@ -261,7 +262,7 @@ void ui::vehicleparams_panel::render_contents() ImGui::TextUnformatted(buffer.data()); } - draw_mini(mover); + draw_mini(physics); if (ImGui::Button(STR_C("Radiostop"))) m_relay.post(user_command::radiostopsend, 0.0, 0.0, GLFW_PRESS, 0, vehicle_ptr->GetPosition()); @@ -292,7 +293,7 @@ void ui::vehicleparams_panel::render_contents() if (ImGui::IsItemDeactivated()) m_relay.post(user_command::consistreleaser, 0.0, 0.0, GLFW_RELEASE, 0, glm::vec3(0.0f), &vehicle_ptr->name()); - if (vehicle_ptr->MoverParameters->V < 0.01) + if (vehicle_ptr->physics->V() < 0.01) { if (ImGui::Button(STR_C("Move +500m"))) m_relay.post(user_command::dynamicmove, 500.0, 0.0, GLFW_PRESS, 0, glm::vec3(0.0f), &vehicle_ptr->name()); diff --git a/widgets/vehicleparams.h b/widgets/vehicleparams.h index 787e1e819..d8eb0910e 100644 --- a/widgets/vehicleparams.h +++ b/widgets/vehicleparams.h @@ -14,7 +14,7 @@ class vehicleparams_panel : public ui_panel texture_handle vehicle_mini; void draw_infobutton(const char *str, ImVec2 pos = ImVec2(-1.0f, -1.0f), const ImVec4 color = ImVec4(1.0f, 1.0f, 0.0f, 1.0f)); - void draw_mini(const TMoverParameters &mover); + void draw_mini(const physics::Vehicle &physics); public: vehicleparams_panel(const std::string &vehicle); diff --git a/world/Event.cpp b/world/Event.cpp index 80697cfa2..87cb7a0cd 100644 --- a/world/Event.cpp +++ b/world/Event.cpp @@ -29,10 +29,14 @@ http://mozilla.org/MPL/2.0/. #include "model/AnimModel.h" #include "vehicle/DynObj.h" #include "vehicle/Driver.h" +#include "vehicle/crewchange.h" #include "rendering/renderer.h" #include "utilities/Timer.h" #include "utilities/Logs.h" #include "widgets/map_objects.h" +#include "physics/vehicle.h" + +#include void basic_event::event_conditions::bind( basic_event::node_sequence *Nodes ) { @@ -41,19 +45,25 @@ basic_event::event_conditions::bind( basic_event::node_sequence *Nodes ) { } void -basic_event::event_conditions::init() { +basic_event::event_conditions::init( std::string_view const Eventname ) { tracks.clear(); - if( flags & ( flags::track_busy | flags::track_free ) ) { - for( auto &target : *memcompare_cells ) { - tracks.emplace_back( simulation::Paths.find( std::get( target ) ) ); - if( tracks.back() == nullptr ) { - // legacy compatibility behaviour, instead of disabling the event we disable the memory cell comparison test -// m_ignored = true; // deaktywacja -// ErrorLog( "Bad event: track \"" + std::get( target ) + "\" referenced in event \"" + asName + "\" doesn't exist" ); - flags &= ~( flags::track_busy | flags::track_free ); // zerowanie flag - } + if( ( flags & ( flags::track_busy | flags::track_free ) ) == 0 ) { + return; + } + auto const *testname { ( flags & flags::track_free ) != 0 ? "trackfree" : "trackoccupied" }; + if( memcompare_cells->empty() ) { + // the test goes over the targets of the event, so with none it has nothing to test and passes + ErrorLog( std::format( "Bad event: \"{}\" has no track to test with {}, so this test passes every time", Eventname, testname ) ); + } + for( auto &target : *memcompare_cells ) { + tracks.emplace_back( simulation::Paths.find( std::get( target ) ) ); + if( tracks.back() == nullptr ) { + // legacy compatibility behaviour, instead of disabling the event we disable the memory cell comparison test +// m_ignored = true; // deaktywacja + ErrorLog( std::format( "Bad event: \"{}\" can't test \"{}\" with {}, it isn't a track (an isolated section isn't one either), so this test passes every time", Eventname, std::get( target ), testname ) ); + flags &= ~( flags::track_busy | flags::track_free ); // zerowanie flag } } } @@ -177,110 +187,6 @@ basic_event::event_conditions::test() const { return true; } -void -basic_event::event_conditions::deserialize( cParser &Input ) { - // przetwarzanie warunków, wspólne dla Multiple i UpdateValues - - std::string token; - while( true == Input.getTokens() - && false == (token = Input.peek()).empty() - && false == basic_event::is_keyword(token) ) { - - if( token == "trackoccupied" ) { - flags |= flags::track_busy; - } - else if( token == "trackfree" ) { - flags |= flags::track_free; - } - else if( token == "propability" || token == "probability") { //remove propability in few years after changing old scenery scripts 01.2021 - flags |= flags::probability; - Input.getTokens(); - Input >> probability; - } - else if( token == "memcompare" ) { - Input.getTokens( 1, false ); // case sensitive - if( Input.peek() != "*" ) //"*" - nie brac command pod uwage - { // zapamiętanie łańcucha do porównania - Input >> memcompare_text; - flags |= flags::text; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac val1 pod uwage - { - Input >> memcompare_value1; - flags |= flags::value1; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac val2 pod uwage - { - Input >> memcompare_value2; - flags |= flags::value2; - } - } - else if( token == "memcompareex" ) { - memcompare_pass = comparison_pass_from_string( Input.getToken() ); - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_text_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens( 1, false ); // case sensitive - Input >> memcompare_text; - flags |= flags::text; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_value1_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens(); - Input >> memcompare_value1; - flags |= flags::value1; - } - Input.getTokens(); - if( Input.peek() != "*" ) //"*" - nie brac pod uwage - { // two tokens, operator followed by comparison value - std::string operatorstring; - Input >> operatorstring; - memcompare_value2_operator = comparison_operator_from_string( operatorstring ); - Input.getTokens(); - Input >> memcompare_value2; - flags |= flags::value2; - } - } - } -} - -// sends basic content of the class in legacy (text) format to provided stream -void -basic_event::event_conditions::export_as_text( std::ostream &Output ) const { - - if( flags != 0 ) { - Output << "condition "; - if( ( flags & flags::track_busy ) != 0 ) { - Output << "trackoccupied "; - } - if( ( flags & flags::track_free ) != 0 ) { - Output << "trackfree "; - } - if( ( flags & flags::probability ) != 0 ) { - Output - << "probability " - << probability << ' '; - } - if( ( flags & ( flags::text | flags::value1 | flags::value2 ) ) != 0 ) { - // NOTE: export doesn't preserve original memcompare condition, these are all upgraded to memcompareex format for simplicity - Output - << "memcompareex " - << ( ( flags & flags::text ) == 0 ? "*" : memcompare_text + ' ' + to_string( memcompare_text_operator ) ) << ' ' - << ( ( flags & flags::value1 ) == 0 ? "*" : std::to_string( memcompare_value1 ) + ' ' + to_string( memcompare_value1_operator ) ) << ' ' - << ( ( flags & flags::value2 ) == 0 ? "*" : std::to_string( memcompare_value2 ) + ' ' + to_string( memcompare_value2_operator ) ) << ' '; - } - } -} - basic_event::~basic_event() { m_sibling = nullptr; // nie usuwać podczepionych tutaj @@ -439,12 +345,10 @@ basic_event::input_location() const { return glm::dvec3( 0, 0, 0 ); }; -bool -basic_event::is_keyword( std::string const &Token ) { - // TODO: convert to array lookup if keyword list gets longer - return Token == "endevent" - || Token == "randomdelay" - || Token == "departuredelay"; +TMemCell const * +basic_event::input_cell() const { + + return nullptr; } @@ -469,7 +373,7 @@ updatevalues_event::init() { init_targets( simulation::Memory, "memory cell" ); // conditional data m_conditions.bind( &m_targets ); - m_conditions.init(); + m_conditions.init( m_name ); } // event type string @@ -505,7 +409,7 @@ updatevalues_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpa && false == is_keyword(token) ) { if( token == "condition" ) { - m_conditions.deserialize( Input ); + m_conditions.deserialize( Input, m_name ); // NOTE: condition deserialization leaves preloaded next token } } @@ -676,6 +580,12 @@ getvalues_event::input_location() const { return m_input.data_cell()->location(); // współrzędne podłączonej komórki pamięci } +TMemCell const * +getvalues_event::input_cell() const { + + return m_input.data_cell(); +} + // prepares event for use @@ -716,7 +626,8 @@ putvalues_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) if( contains( token, '#' ) ) { token.erase( token.find( '#' ) ); // obcięcie unikatowości } - win1250_to_ascii( token ); // get rid of non-ascii chars + // NOTE: the name stays as the scenery spells it, with its polish letters; whoever matches it with the name + // a timetable has goes by timetable::stop_point_is_for(), which takes any spelling of the station m_input.command_type = TCommandType::cm_PassengerStopPoint; // nie do kolejki (dla SetVelocity też, ale jak jest do toru dowiązany) m_passive = true; @@ -781,6 +692,12 @@ putvalues_event::run_() { + to_string( m_input.data_value_1, 2 ) + "] [" + to_string( m_input.data_value_2, 2 ) + "]" ); + if( crew::is_command( m_input.data_text ) ) { + // a driver for the vehicle named in the command, or none (eu07/maszyna#510). not a command for a driver or + // a vehicle to take, and it works with nothing setting the event off too (a key, an event launcher) + crew::change( crew::parse( m_input.data_text, m_input.data_value_1, m_input.data_value_2 ), m_activator ); + return; + } if( m_activator == nullptr ) { return; } // zamiana, bo fizyka ma inaczej niż sceneria // NOTE: y & z swap, negative x @@ -813,7 +730,7 @@ putvalues_event::run_() { else { // przekazanie do pojazdu WriteLog( " Vehicle: [" + m_activator->name() +"]" ); - m_activator->MoverParameters->PutCommand( + m_activator->physics->PutCommand( m_input.data_text, m_input.data_value_1, m_input.data_value_2, @@ -1125,7 +1042,7 @@ whois_event::run_() { m_activator->ctOwner ) }; auto const consistbrakelevel { ( owner != nullptr ? - owner->fReady : + owner->BrakesReleaseLevel() : -1.0 ) }; auto const collisiondistance { ( owner != nullptr ? @@ -1133,30 +1050,30 @@ whois_event::run_() { -1.0 ) }; targetcell->UpdateValues( - m_activator->MoverParameters->TypeName, // typ pojazdu + m_activator->physics->TypeName, // typ pojazdu consistbrakelevel, collisiondistance, m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); WriteLog( "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " - + "[type: " + m_activator->MoverParameters->TypeName + "], " + + "[type: " + m_activator->physics->TypeName + "], " + "[consist brake level: " + to_string( consistbrakelevel, 2 ) + "], " + "[obstacle distance: " + to_string( collisiondistance, 2 ) + " m]" ); } else { // jeśli parametry ładunku targetcell->UpdateValues( - m_activator->MoverParameters->LoadType.name, // nazwa ładunku - m_activator->MoverParameters->LoadAmount, // aktualna ilość - m_activator->MoverParameters->MaxLoad, // maksymalna ilość + m_activator->physics->LoadType.name, // nazwa ładunku + m_activator->physics->LoadAmount(), // aktualna ilość + m_activator->physics->MaxLoad(), // maksymalna ilość m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); WriteLog( "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " - + "[load type: " + m_activator->MoverParameters->LoadType.name + "], " - + "[current load: " + to_string( m_activator->MoverParameters->LoadAmount, 2 ) + "], " - + "[max load: " + to_string( m_activator->MoverParameters->MaxLoad, 2 ) + "]" ); + + "[load type: " + m_activator->physics->LoadType.name + "], " + + "[current load: " + to_string( m_activator->physics->LoadAmount(), 2 ) + "], " + + "[max load: " + to_string( m_activator->physics->MaxLoad(), 2 ) + "]" ); } } // +8 @@ -1164,14 +1081,14 @@ whois_event::run_() { targetcell->UpdateValues( m_activator->asDestination, // adres docelowy m_activator->DirectionGet(), // kierunek pojazdu względem czoła składu (1=zgodny,-1=przeciwny) - m_activator->MoverParameters->Power, // moc pojazdu silnikowego: 0 dla wagonu + m_activator->physics->Power, // moc pojazdu silnikowego: 0 dla wagonu m_input.flags & ( flags::text | flags::value1 | flags::value2 ) ); WriteLog( "Type: WhoIs (" + std::to_string( m_input.flags ) + ") - " + "[destination: " + m_activator->asDestination + "], " + "[direction: " + std::to_string( m_activator->DirectionGet() ) + "], " - + "[engine power: " + to_string( m_activator->MoverParameters->Power, 2 ) + "]" ); + + "[engine power: " + to_string( m_activator->physics->Power, 2 ) + "]" ); } // +0 else { @@ -1266,12 +1183,22 @@ multi_event::init() { init_targets( simulation::Memory, "memory cell", conditiontchecksmemcell ); if( m_ignored ) { // legacy compatibility behaviour, instead of disabling the event we disable the memory cell comparison test + if( conditiontchecksmemcell + && std::ranges::any_of( m_targets, []( basic_node const &Target ) { return std::get( Target ) == nullptr; } ) ) { + // init_targets() named the missing cell; say what it does to the event, as it isn't what the scenery asks for + // the track and probability tests still apply, only the comparison is off + auto const otherconditions { ( m_conditions.flags & ( flags::track_busy | flags::track_free | flags::probability ) ) != 0 }; + ErrorLog( std::format( + "Bad event: \"{}\" compares a memory cell which doesn't exist, so its memcompare test is off{}", + m_name, + otherconditions ? std::string() : " and it always runs the events before its else" ) ); + } m_conditions.flags &= ~( flags::text | flags::value1 | flags::value2 ); m_ignored = false; } // conditional data m_conditions.bind( &m_targets ); - m_conditions.init(); + m_conditions.init( m_name ); // child events bindings for( auto &childevent : m_children ) { std::get( childevent ) = simulation::Events.FindEvent( std::get( childevent ) ); @@ -1339,7 +1266,7 @@ multi_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { && false == is_keyword(token) ) { if( token == "condition" ) { - m_conditions.deserialize( Input ); + m_conditions.deserialize( Input, m_name ); // NOTE: condition block comes last so we can bail out afterwards break; } @@ -2054,6 +1981,69 @@ track_event::export_as_text_( std::ostream &Output ) const { +// prepares event for use +void +buckle_event::init() { + + init_targets( simulation::Paths, "track" ); +} + +// event type string +std::string +buckle_event::type() const { + + return "trackbuckle"; +} + +// deserialize() subclass details +void +buckle_event::deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) { + + Input.getTokens(); + Input >> m_buckle.amplitude; + m_buckle.amplitude = std::clamp( m_buckle.amplitude, 0.f, static_cast( 1000.0 * track_buckle::most_amplitude ) ); + Input.getTokens(); + // the length, the centre and the side, each optional + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.length; + if( m_buckle.length > 0.f ) { + m_buckle.length = std::clamp( m_buckle.length, static_cast( track_buckle::least_length ), static_cast( track_buckle::most_length ) ); + } + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + Input >> m_buckle.centre; + Input.getTokens(); + } + if( false == is_keyword( Input.peek() ) ) { + auto side { 0.f }; + Input >> side; + m_buckle.side = ( side > 0.f ? 1 : side < 0.f ? -1 : 0 ); + Input.getTokens(); + } +} + +// run() subclass details +void +buckle_event::run_() { + + WriteLog( "Type: TrackBuckle - [" + to_string( m_buckle.amplitude, 0 ) + " mm]" ); + for( auto &target : m_targets ) { + auto *targettrack = static_cast( std::get( target ) ); + if( targettrack == nullptr ) { continue; } + targettrack->buckle_now( m_buckle, "event " + m_name ); + } +} + +// export_as_text() subclass details +void +buckle_event::export_as_text_( std::ostream &Output ) const { + + Output << m_buckle.amplitude << ' ' << m_buckle.length << ' ' << m_buckle.centre << ' ' << m_buckle.side << ' '; +} + + + // prepares event for use void voltage_event::init() { @@ -2310,6 +2300,7 @@ make_event( cParser &Input, scene::scratch_data &Scratchpad ) { else if( type == "multiple" ) { event = new multi_event(); } else if( type == "switch" ) { event = new switch_event(); } else if( type == "trackvel" ) { event = new track_event(); } + else if( type == "trackbuckle" ) { event = new buckle_event(); } else if( type == "sound" ) { event = new sound_event(); } else if( type == "texture" ) { event = new texture_event(); } else if( type == "animation" ) { event = new animation_event(); } @@ -2477,7 +2468,22 @@ bool event_manager::AddToQuery( basic_event *Event, TDynamicObject const *Owner, double delay ) { if( Event->m_passive ) { return false; } // jeśli może być dodany do kolejki (nie używany w skanowaniu) - if( Event->m_inqueue > 0 ) { return false; } // jeśli nie dodany jeszcze do kolejki + if( Event->m_inqueue > 0 ) { // jeśli nie dodany jeszcze do kolejki + // a call of another train is lost, the event runs once, for whoever queued it first. + // logged once per stay in the queue, as a standing vehicle repeats its event0 call every frame, + // and not for the other vehicles of the same train, which repeat its eventall0 call + if( Owner != Event->m_activator + && false == Event->m_lostcalllogged + && false == ( Owner != nullptr && Owner->is_connected( Event->m_activator ) ) ) { + Event->m_lostcalllogged = true; + WriteLog( std::format( + "EVENT ALREADY IN QUEUE, NOT ADDED{}: {}{}", + Owner ? " by " + Owner->asName : std::string(), + Event->m_name, + Event->m_activator ? " (queued by " + Event->m_activator->asName + ")" : std::string() ) ); + } + return false; + } // kolejka eventów jest posortowana względem (fStartTime) Event->m_activator = Owner; @@ -2498,6 +2504,8 @@ event_manager::AddToQuery( basic_event *Event, TDynamicObject const *Owner, doub if( Event != nullptr && false == Event->m_ignored ) { // standardowe dodanie do kolejki + Event->m_activator = Owner; // a joint event reached above still holds the vehicle of its previous run + Event->m_lostcalllogged = false; ++Event->m_inqueue; // zabezpieczenie przed podwójnym dodaniem do kolejki WriteLog( "EVENT ADDED TO QUEUE" + ( Owner ? " by " + Owner->asName : "" ) + ": " + Event->m_name ); Event->m_launchtime = delay + std::abs( Event->m_delay ) + Timer::GetTime(); // czas od uruchomienia scenerii @@ -2572,6 +2580,7 @@ event_manager::CheckQuery() { QueryRootEvent->m_launchtime = m_workevent->m_launchtime; // czas musi być ten sam, bo nie jest aktualizowany QueryRootEvent->m_activator = m_workevent->m_activator; // pojazd aktywujący QueryRootEvent->m_inqueue = 1; + QueryRootEvent->m_lostcalllogged = false; // w sumie można by go dodać normalnie do kolejki, ale trzeba te połączone posortować wg czasu wykonania } else // a jak nazwa jest unikalna, to kolejka idzie dalej diff --git a/world/Event.h b/world/Event.h index f1d75689b..91ed85973 100644 --- a/world/Event.h +++ b/world/Event.h @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scene.h" #include "utilities/Names.h" #include "world/EvLaunch.h" +#include "world/TrackBuckle.h" #include "utilities/Logs.h" #include "input/command.h" #include "utilities/comparison.h" @@ -84,6 +85,8 @@ public: virtual TCommandType input_command() const; virtual double input_value( int Index ) const; virtual glm::dvec3 input_location() const; + // the memory cell the data comes from, null if the event doesn't read one + virtual TMemCell const *input_cell() const; void group( scene::group_handle Group ); scene::group_handle group() const; std::string const &name() const { return m_name; } @@ -94,6 +97,7 @@ public: bool m_ignored { false }; // replacement for tp_ignored bool m_passive { false }; // false gdy ma nie być dodawany do kolejki (skanowanie sygnałów) int m_inqueue { 0 }; // ile razy dodany do kolejki + bool m_lostcalllogged { false }; // a lost call was already logged during the current stay in the queue TDynamicObject const *m_activator { nullptr }; double m_launchtime { 0.0 }; double m_delay { 0.0 }; @@ -119,9 +123,10 @@ protected: std::vector tracks; // used by conditional_track bool has_else { false }; - void deserialize( cParser &Input ); + // the event name only goes to the log, for the faults found in the condition + void deserialize( cParser &Input, std::string_view Eventname ); void bind( basic_event::node_sequence *Nodes ); - void init(); + void init( std::string_view Eventname ); // verifies whether event meets execution condition(s) bool test() const; // sends basic content of the class in legacy (text) format to provided stream @@ -242,6 +247,7 @@ public: TCommandType input_command() const override; double input_value( int Index ) const override; glm::dvec3 input_location() const override; + TMemCell const *input_cell() const override; private: // methods @@ -527,6 +533,31 @@ private: +// trackbuckle [ [ []]]: the target tracks buckle in the heat as the entry +// "buckle" of a track says (see world/TrackBuckle.h), amplitude 0 straightens them +class buckle_event : public basic_event { + +public: +// methods + // prepares event for use + void init() override; + +private: +// methods + // event type string + std::string type() const override; + // deserialize() subclass details + void deserialize_( cParser &Input, scene::scratch_data &Scratchpad ) override; + // run() subclass details + void run_() override; + // export_as_text() subclass details + void export_as_text_( std::ostream &Output ) const override; +// members + track_buckle::declared m_buckle; +}; + + + class voltage_event : public basic_event { public: diff --git a/world/RailCarve.cpp b/world/RailCarve.cpp index dadacdd45..da72a5569 100644 --- a/world/RailCarve.cpp +++ b/world/RailCarve.cpp @@ -287,9 +287,15 @@ bool continues( carve_rail const &A, carve_rail const &B ) { if( A.track == B.track ) { return false; } + // the knuckle and the point of an obtuse crossing, whose ends lie within the reach at a slip centre, go on from each other only + // nearly straight (less than 2.6 degrees apart; 1:9 is 6.4); the rails at any other joint also where it's kinked by up to 8 degrees, + // as tracks laid by hand often are, so their heads aren't planed there + auto const obtuse = []( carve_rail const &Rail ) { + return std::ranges::any_of( Rail.parts, []( carve_part const &Part ) { return Part.obtuse[ 0 ] || Part.obtuse[ 1 ]; } ); }; + auto const straight { ( obtuse( A ) || obtuse( B ) ) ? 0.999 : 0.99 }; for( int a = 0; a < 2; ++a ) { for( int b = 0; b < 2; ++b ) { - if( glm::length( plan( A.ends[ a ] - B.ends[ b ] ) ) < 0.05 && std::abs( glm::dot( A.directions[ a ], B.directions[ b ] ) ) > 0.999 ) { + if( glm::length( plan( A.ends[ a ] - B.ends[ b ] ) ) < 0.05 && std::abs( glm::dot( A.directions[ a ], B.directions[ b ] ) ) > straight ) { return true; } } diff --git a/world/Road.cpp b/world/Road.cpp index 3455bf791..f9b6cd137 100644 --- a/world/Road.cpp +++ b/world/Road.cpp @@ -20,6 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "utilities/utilities.h" +#include "physics/vehicle.h" namespace { @@ -875,7 +876,7 @@ glm::dvec3 road_node::state::tangent(double const T) const road_node::road_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} // restores content of the node from provided input stream; reads up to and including the closing 'endroad' -void road_node::import(cParser &Input, glm::dvec3 const &Offset) +void road_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const label{m_name.empty() ? std::string{"unnamed road"} : "road \"" + m_name + "\""}; @@ -956,6 +957,14 @@ void road_node::import(cParser &Input, glm::dvec3 const &Offset) m_state.surface = Input.getToken(); replace_slashes(m_state.surface); } + else if (token == "surfacetype") + { + auto const type{Input.getToken()}; + if (false == road_surface::from_name(type, m_state.surfacetype)) + { + ErrorLog("Bad road: unknown surface type \"" + type + "\" defined for " + label + ", paved is used instead"); + } + } else if (token == "texlength") { Input.getTokens(); @@ -2307,7 +2316,7 @@ std::vector junction_node::state::outline(std::vectorMoverParameters->V); - gate.halflength = 0.5 * first->MoverParameters->Dim.L; + gate.speed = std::abs(first->physics->V()); + gate.halflength = 0.5 * first->physics->Dim.L; gate.taken = ways_of(gate, first); gate.active = gate.distance < std::max(gate_zone, gate.speed * gate_gap) + gate.halflength; } @@ -4135,6 +4144,7 @@ void road_node::export_as_text_(std::ostream &Output) const } // appearance Output << "surface " << road.surface << ' ' << "texlength " << road.texturelength << ' '; + Output << road_surface::entry(road.surfacetype); char const *sidenames[]{"left", "right"}; for (int side = 0; side < 2; ++side) { diff --git a/world/Road.h b/world/Road.h index 35222597b..139bbfad9 100644 --- a/world/Road.h +++ b/world/Road.h @@ -19,6 +19,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Names.h" #include "scene/scenenode.h" #include "world/Segment.h" +#include "world/RoadSurfaceType.h" namespace scene { @@ -59,6 +60,7 @@ class owned_shapes // medianround , // kerbs , bank , // bankmaterial , weight , roundabout, +// surfacetype : what the road is made of, which sets how tight the road editor lets it be laid out; paved unless told otherwise, // lanesto : lanes the piece has at the end of its axis, where these aren't the ones it starts with class road_node : public scene::basic_node { @@ -134,7 +136,8 @@ class road_node : public scene::basic_node std::vector lanes; std::vector changes; // permissions to change the lane, one for each pair of neighbouring lanes std::array taper{1.f, 1.f}; // what the widths of the lanes are multiplied by at the start and at the end of the axis - std::string surface{"asphaltdark1"}; + std::string surface{road_surface::default_material(road_surface_type::paved)}; + road_surface_type surfacetype{road_surface_type::paved}; // what the road is made of, as far as laying it out goes float texturelength{4.f}; std::array sides; // left, right float kerbheight{0.12f}; @@ -220,7 +223,7 @@ class road_node : public scene::basic_node explicit road_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing 'endroad' - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; @@ -441,7 +444,7 @@ class junction_node : public scene::basic_node explicit junction_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing 'endjunction' - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; diff --git a/world/RoadPoint.cpp b/world/RoadPoint.cpp index 14ff57a0e..5e5ed6ecb 100644 --- a/world/RoadPoint.cpp +++ b/world/RoadPoint.cpp @@ -26,6 +26,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Logs.h" #include "utilities/parser.h" #include "utilities/utilities.h" +#include "physics/vehicle.h" namespace { @@ -327,7 +328,7 @@ std::vector roadpoint_node::parse_vehicles(std::st } // restores content of the node from provided input stream; reads up to and including the closing statement -void roadpoint_node::import(cParser &Input, glm::dvec3 const &Offset) +void roadpoint_node::import_from(cParser &Input, glm::dvec3 const &Offset) { auto const type{keyword(m_state.kind)}; auto const label{type + " \"" + m_name + "\""}; @@ -859,7 +860,7 @@ void roadpoint_node::prepare() } pooled_vehicle entry; entry.vehicle = vehicle; - entry.velocity = vehicle->MoverParameters->V; + entry.velocity = vehicle->physics->V(); m_pool.emplace_back(entry); // ...which is taken off the road right away, the way the vehicles leaving the scenery are, to wait for its turn if (vehicle->MyTrack != nullptr) @@ -997,7 +998,7 @@ void roadpoint_node::update_spawn(double const Deltatime) entry.standing = 0.0; continue; } - auto const speed{vehicle->MoverParameters->V}; + auto const speed{vehicle->physics->V()}; // forward is the way it went when it was put on the road auto const backwards{speed * entry.velocity < 0.0 && std::abs(speed) > reverse_speed}; if (std::abs(speed) > stuck_speed || simulation::Roadpoints.holds(*vehicle)) @@ -1060,10 +1061,9 @@ void roadpoint_node::update_spawn(double const Deltatime) auto *vehicle{entry.vehicle}; // it comes back the way it was made: whole, at speed, with the driver told to drive on vehicle->bEnabled = true; - vehicle->MoverParameters->DamageFlag = 0; - vehicle->MoverParameters->EngDmgFlag = 0; - vehicle->MoverParameters->V = entry.velocity; - vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->MoverParameters->Dim.L, false); + vehicle->physics->repair_damage(); + vehicle->physics->SetV(entry.velocity); + vehicle->place_on_track(m_lanes.front(), m_offset + 0.5 * vehicle->physics->Dim.L, false); if (vehicle->Mechanik != nullptr) { // the same order a vehicle put in the scenery gets; it has the driver forget the road they knew @@ -1079,7 +1079,7 @@ void roadpoint_node::update_despawn() { for (auto *vehicle : lane->Dynamics) { - if (vehicle == nullptr || false == vehicle->bEnabled || vehicle->MoverParameters->CategoryFlag != 2) + if (vehicle == nullptr || false == vehicle->bEnabled || vehicle->physics->CategoryFlag != 2) { continue; } @@ -1088,7 +1088,7 @@ void roadpoint_node::update_despawn() // not the one the user sits in continue; } - if (planar_distance(vehicle->GetPosition(), m_state.position) > m_state.radius + 0.5 * vehicle->MoverParameters->Dim.L) + if (planar_distance(vehicle->GetPosition(), m_state.position) > m_state.radius + 0.5 * vehicle->physics->Dim.L) { continue; } diff --git a/world/RoadPoint.h b/world/RoadPoint.h index fd5fdc731..f3e1dd0e4 100644 --- a/world/RoadPoint.h +++ b/world/RoadPoint.h @@ -102,7 +102,7 @@ class roadpoint_node : public scene::basic_node explicit roadpoint_node(scene::node_data const &Nodedata); // methods // restores content of the node from provided input stream; reads up to and including the closing statement - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); state const &definition() const { return m_state; diff --git a/world/RoadSurfaceType.h b/world/RoadSurfaceType.h new file mode 100644 index 000000000..d71215ba2 --- /dev/null +++ b/world/RoadSurfaceType.h @@ -0,0 +1,63 @@ +/* +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 + +#include +#include + +// what a road is made of, as far as laying it out goes. a paved road (asphalt, concrete, setts) keeps to the bends and the angles +// of a built road; a dirt road (a track between fields, through a forest) turns tighter, comes in shorter stretches +// and leaves other roads at sharper angles. +// scenery entry: surfacetype , written for a dirt road only +enum class road_surface_type +{ + paved, + dirt +}; + +namespace road_surface +{ + +// the word the scenery uses for the type +inline char const *name(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? "dirt" : "paved"; +} + +// the type going by specified word. returns: false if there's no such type, with Type left as it was +inline bool from_name(std::string_view const Name, road_surface_type &Type) +{ + if (Name == "paved") + { + Type = road_surface_type::paved; + return true; + } + if (Name == "dirt") + { + Type = road_surface_type::dirt; + return true; + } + return false; +} + +// the scenery entry of the type, followed by a space. a paved road, which all the roads made before the types are, writes nothing, +// so the sceneries are saved as they were +inline std::string entry(road_surface_type const Type) +{ + return Type == road_surface_type::paved ? std::string{} : std::string{"surfacetype "} + name(Type) + ' '; +} + +// the material the surface of a road of the type gets unless told otherwise: the default asphalt, or the field road of the game's textures +inline char const *default_material(road_surface_type const Type) +{ + return Type == road_surface_type::dirt ? "droga_polna" : "asphaltdark1"; +} + +} // namespace road_surface diff --git a/world/Segment.cpp b/world/Segment.cpp index 5da1d0ad7..6e0326c33 100644 --- a/world/Segment.cpp +++ b/world/Segment.cpp @@ -141,6 +141,10 @@ bool TSegment::Init(glm::dvec3 &NewPoint1, glm::dvec3 NewCPointOut, glm::dvec3 N // dense enough for the waves; a switch keeps its division, the blades depend on it fStep = std::min( fStep, 2.0 ); } + if( m_setting.buckled ) { + // and for the lobes of a buckle, 9 m and more + fStep = std::min( fStep, 1.0 ); + } // NOTE: optionally replace this part with the commented version, after solving geometry issues with double switches if( pOwner->eType == tt_Switch && fStep * (3.0 * Global.SplineFidelity) > fLength ) { @@ -433,16 +437,36 @@ Math3D::vector3 TSegment::GetPoint(double const fDistance) const }; */ -glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const { - auto const field { track_uneven::field( Point ) }; - glm::dvec3 result { - field.x * Amount.side * track_uneven::stray_side_per_mm, - field.y * Amount.up * track_uneven::stray_up_per_mm, - field.z * Amount.side * track_uneven::stray_side_per_mm }; - result.y -= pOwner->joint_dip( Distance ); +glm::dvec3 TSegment::stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const { + glm::dvec3 result { 0.0 }; + if( m_setting.uneven ) { + auto const field { track_uneven::field( Point ) }; + result = glm::dvec3 { + field.x * Amount.side * track_uneven::stray_side_per_mm, + field.y * Amount.up * track_uneven::stray_up_per_mm, + field.z * Amount.side * track_uneven::stray_side_per_mm }; + result.y -= pOwner->joint_dip( Distance ); + } + if( m_setting.buckled && m_pieces.empty() ) { + result += Across * track_buckle::offset( pOwner->buckle(), Distance ); + } return result; } +double TSegment::buckle_bend( double const Distance, double const Base ) const { + if( false == m_setting.buckled || false == m_pieces.empty() ) { + return 0.0; + } + return track_buckle::mean_bend( pOwner->buckle(), Distance, Base ); +} + +glm::dvec3 TSegment::across_at( double const Distance ) const { + glm::dvec3 point; + glm::dvec3 across; + plan_frame( Distance, point, across ); + return across; +} + glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( false == m_setting.uneven ) { return glm::dvec3 { 0.0 }; @@ -457,12 +481,13 @@ glm::dvec3 TSegment::uneven_bend( double const Distance ) const { if( auto const direction { FastGetDirection( t, 0.1 / fLength ) }; on != At && glm::length( direction ) > 0.0 ) { point += direction * ( ( At - on ) / glm::length( direction ) ); } - return stray( point, pOwner->uneven_at( At, m_setting.path ), At ); }; + // the buckle left out: its curvature is taken on its own, see buckle_bend() + return stray( point, pOwner->uneven_at( At, m_setting.path ), At, glm::dvec3 { 0.0 } ); }; return ( strayed( Distance + reach ) - 2.0 * strayed( Distance ) + strayed( Distance - reach ) ) / ( reach * reach ); } void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const { - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } // the rails settling apart turn about the middle of the track, what's outside them follows the rail; the foot of the ballast stays @@ -472,9 +497,9 @@ void TSegment::settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origi if( share <= 0.0 ) { return; } - auto const amount { pOwner->uneven_at( Distance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( Distance, m_setting.path ) : track_uneven::amounts {} }; Vertex.position.y -= static_cast( share * track_uneven::stray_up_per_mm * amount.cross * track_uneven::level( Origin + glm::dvec3 { Position }, glm::dvec3 { Parallel } ) * across / gauge ); - Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance ) }; + Vertex.position += glm::vec3 { share * stray( Origin + glm::dvec3 { Vertex.position }, amount, Distance, glm::dvec3 { Parallel } ) }; } void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm::vec3 &rotation) const { @@ -505,17 +530,18 @@ void TSegment::RaPositionGet(double const fDistance, glm::dvec3 &position, glm:: rotation.y = static_cast(fStoop); // pochylenie toru prostego rotation.z = static_cast(fDirection); // kierunek toru w planie } - if( false == m_setting.uneven ) { + if( false == m_setting.uneven && false == m_setting.buckled ) { return; } - // direction and slope stay as designed: the physics takes the curve radius and the grade from them + // direction and slope stay as designed: the physics takes the curve radius and the grade from them, and the curvature of a buckle + // on its own (buckle_bend()) auto const gauge { std::max( std::abs( pOwner->fTrackWidth ), 0.1f ) }; glm::dvec3 const across { -std::cos( rotation.z ), 0.0, -std::sin( rotation.z ) }; - auto const amount { pOwner->uneven_at( fDistance, m_setting.path ) }; + auto const amount { m_setting.uneven ? pOwner->uneven_at( fDistance, m_setting.path ) : track_uneven::amounts {} }; rotation.x += static_cast( track_uneven::stray_up_per_mm * ( amount.up * track_uneven::roll( position, across, gauge ) + amount.cross * track_uneven::level( position, across ) / gauge ) ); - position += track_uneven::across_only( stray( position, amount, fDistance ), across ); + position += track_uneven::across_only( stray( position, amount, fDistance, across ), across ); }; void TSegment::plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const { diff --git a/world/Segment.h b/world/Segment.h index 596d95912..88aa9adff 100644 --- a/world/Segment.h +++ b/world/Segment.h @@ -109,6 +109,7 @@ class TSegment struct setting { std::array designrolls { 0.f, 0.f }; // as entered; fRoll1 and fRoll2 can differ at a joint bool uneven { false }; // see TrackUneven.h + bool buckled { false }; // see TrackBuckle.h int path { 0 }; // which path of a switch // where the path meets the next one: the middle of their ends and their common vector across std::array>, 2> joints; @@ -145,8 +146,9 @@ class TSegment // moves a lofted vertex with the unevenness of the track void settle_vertex( gfx::basic_vertex &Vertex, glm::dvec3 const &Origin, glm::vec3 const &Position, glm::vec3 const &Parallel, double const Distance ) const; - // displacement of a point by the unevenness, at a distance along the path - glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance ) const; + // displacement of a point by the unevenness, at a distance along the path, and by the buckle of the track across it, along Across + // (none along a zero vector) + glm::dvec3 stray( glm::dvec3 const &Point, track_uneven::amounts const &Amount, double const Distance, glm::dvec3 const &Across ) const; public: bool bCurve = false; @@ -201,6 +203,10 @@ public: set_uneven( bool const Uneven, int const Path = 0 ) { m_setting.uneven = Uneven; m_setting.path = Path; } + // call before Init too + void + set_buckled( bool const Buckled ) { + m_setting.buckled = Buckled; } // a point of the path and the unit vector across it in the plan, towards the right rail profile; zero for a path never made void plan_frame( double const Distance, glm::dvec3 &Point, glm::dvec3 &Across ) const; @@ -214,6 +220,13 @@ public: // second derivative of the displacement along the path; times speed squared: acceleration of an axle glm::dvec3 uneven_bend( double const Distance ) const; + // the curvature the buckle of the track adds to the path at the distance, 1/m, positive bending towards its right; averaged over Base + // around it, as a bogie or a body takes it + double + buckle_bend( double const Distance, double const Base = 0.0 ) const; + // the unit vector across the path at the distance, towards its right + glm::dvec3 + across_at( double const Distance ) const; glm::dvec3 FastGetPoint(double const t) const; inline glm::dvec3 diff --git a/world/SleeperModels.cpp b/world/SleeperModels.cpp index 0efba7425..e820fc5f6 100644 --- a/world/SleeperModels.cpp +++ b/world/SleeperModels.cpp @@ -23,8 +23,6 @@ http://mozilla.org/MPL/2.0/. #include #include -#include -#include #include #include @@ -328,44 +326,6 @@ double plain_length( TTrack const &Track ) { return 2.0 * ( 0.5 * std::abs( Track.fTrackWidth ) + rail_reach + beam_overhang ); } -namespace { - -// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error -void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { - - namespace fs = std::filesystem; - if( false == Entry.is_regular_file( Error ) ) { - return; - } - auto const extension { ToLower( Entry.path().extension().string() ) }; - if( extension != ".t3d" && extension != ".e3d" ) { - return; - } - auto name { ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ) }; - if( Error || name.empty() ) { - return; - } - if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos - && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { - return; - } - // a timber model has the parts it's put together from, told by their names in the file - std::ifstream file { Entry.path(), std::ios::binary }; - std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; - auto const has = [ &extension, &content ]( std::string const &Part ) { - return ( - extension == ".t3d" ? - content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos - || content.find( "Name: " + Part + "\r" ) != std::string::npos : - content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; - auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; - if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { - Models.emplace_back( std::move( name ), timber ); - } -} - -} // namespace - std::vector const &pack_models() { static std::vector models; @@ -374,20 +334,7 @@ std::vector const &pack_models() { return models; } scanned = true; - namespace fs = std::filesystem; - std::error_code error; - auto const root { fs::path { paths::models } }; - fs::recursive_directory_iterator entry { root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; - fs::recursive_directory_iterator const end; - while( entry != end ) { - if( error ) { - break; - } - add_pack_model( *entry, root, error, models ); - entry.increment( error ); - } - std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { - return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + models = pack_models( std::filesystem::path { paths::models } ); return models; } diff --git a/world/SleeperPack.cpp b/world/SleeperPack.cpp new file mode 100644 index 000000000..b04c573bb --- /dev/null +++ b/world/SleeperPack.cpp @@ -0,0 +1,91 @@ +/* +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 "world/TrackSleepers.h" +#include "utilities/utilities.h" + +#include +#include +#include +#include + +// the models of sleepers and timbers found among the files of a folder, by their names; apart from the models drawn, so the +// unit tests can look through a folder of their own + +namespace track_sleepers { + +namespace { + +// the model of sleepers or timbers of the file added to those found, once by its name, what goes wrong left in the error +void add_pack_model( std::filesystem::directory_entry const &Entry, std::filesystem::path const &Root, std::error_code &Error, std::vector &Models ) { + + namespace fs = std::filesystem; + if( false == Entry.is_regular_file( Error ) ) { + return; + } + // a name with a character the code page lacks throws as it's turned into the narrow names the models are loaded by, which + // couldn't open the file anyway: the file is left out, not the rest of the folder with it + std::string extension; + std::string name; + try { + extension = ToLower( Entry.path().extension().string() ); + if( extension != ".t3d" && extension != ".e3d" ) { + return; + } + name = ToLower( fs::relative( Entry.path(), Root, Error ).replace_extension().generic_string() ); + } + catch( std::exception const & ) { + return; + } + if( Error || name.empty() ) { + return; + } + if( name.find( "podklad" ) == std::string::npos && name.find( "podrozjazd" ) == std::string::npos + && name.find( "sleeper" ) == std::string::npos && name.find( "timber" ) == std::string::npos ) { + return; + } + // a timber model has the parts it's put together from, told by their names in the file + std::ifstream file { Entry.path(), std::ios::binary }; + std::string const content { std::istreambuf_iterator( file ), std::istreambuf_iterator() }; + auto const has = [ &extension, &content ]( std::string const &Part ) { + return ( + extension == ".t3d" ? + content.find( "Name: " + Part + "\n" ) != std::string::npos || content.find( "Name: " + Part + " " ) != std::string::npos + || content.find( "Name: " + Part + "\r" ) != std::string::npos : + content.find( std::string { '\0' } + Part + '\0' ) != std::string::npos ); }; + auto const timber { has( "begin" ) && has( "main" ) && has( "end" ) }; + if( std::ranges::none_of( Models, [ &name ]( pack_model const &Model ) { return Model.name == name; } ) ) { + Models.emplace_back( std::move( name ), timber ); + } +} + +} // namespace + +std::vector pack_models( std::filesystem::path const &Root ) { + + namespace fs = std::filesystem; + std::vector models; + std::error_code error; + fs::recursive_directory_iterator entry { Root, fs::directory_options::follow_directory_symlink | fs::directory_options::skip_permission_denied, error }; + fs::recursive_directory_iterator const end; + while( entry != end ) { + if( error ) { + break; + } + add_pack_model( *entry, Root, error, models ); + entry.increment( error ); + } + std::ranges::sort( models, []( pack_model const &Left, pack_model const &Right ) { + return ( Left.timber != Right.timber ? Left.timber : Left.name < Right.name ); } ); + return models; +} + +} // namespace track_sleepers diff --git a/world/Sweep.cpp b/world/Sweep.cpp index 75270d42d..aacefa142 100644 --- a/world/Sweep.cpp +++ b/world/Sweep.cpp @@ -404,7 +404,7 @@ bool sweep_node::state::operator==(state const &Other) const sweep_node::sweep_node(scene::node_data const &Nodedata) : basic_node(Nodedata) {} -void sweep_node::import(cParser &Input, glm::dvec3 const &Offset) +void sweep_node::import_from(cParser &Input, glm::dvec3 const &Offset) { m_state = state{}; m_state.model = Input.getToken(); diff --git a/world/Sweep.h b/world/Sweep.h index 2e65f5fa9..365c599ac 100644 --- a/world/Sweep.h +++ b/world/Sweep.h @@ -20,7 +20,7 @@ http://mozilla.org/MPL/2.0/. #include "scene/scenenode.h" #include "world/Road.h" #include "world/Segment.h" -#include "vehicle/DynObj.h" +#include "model/materialdata.h" namespace scene { @@ -91,7 +91,7 @@ class sweep_node : public scene::basic_node explicit sweep_node(scene::node_data const &Nodedata); - void import(cParser &Input, glm::dvec3 const &Offset); + void import_from(cParser &Input, glm::dvec3 const &Offset); void define(state const &State); state const &definition() const { diff --git a/world/Track.cpp b/world/Track.cpp index 9111b731d..06aa6ce00 100644 --- a/world/Track.cpp +++ b/world/Track.cpp @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Track.h" #include "world/TrackRails.h" +#include "world/TrackCheck.h" #include "simulation/simulation.h" #include "scene/scene.h" #include "utilities/Globals.h" @@ -30,6 +31,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Timer.h" #include "utilities/Logs.h" #include "rendering/renderer.h" +#include "physics/vehicle.h" #include @@ -773,6 +775,20 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) m_uneven = track_uneven::read_attribute( values, eType == tt_Switch ); } } + else if( str == "buckle" ) { + // buckle ;;[;]: the track buckled by the heat, see TrackBuckle.h + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_buckledeclared = track_buckle::read_buckle( values ); + } + } + else if( str == "cwr" ) { + // cwr ;[;]: the welded rail, for the buckling by the temperature + auto const values { parser->getToken( false, "\n\r\t " ) }; + if( eType == tt_Normal && iCategoryFlag == 1 ) { + m_cwr = track_buckle::read_cwr( values ); + } + } else if( str == "friction" ) { // memory cell holding friction value modifiers m_friction.first = parser->getToken(); @@ -835,8 +851,15 @@ void TTrack::Load(cParser *parser, glm::dvec3 const &pOrigin) // from the scenery is put back after it auto const velocity { fVelocity }; init_segments( true ); + // the buckle goes along the path made + if( Global.track_buckling != global_settings::track_buckling_mode::off && track_buckle::given( m_buckledeclared ) ) { + m_buckle = resolve_buckle( m_buckledeclared, 0 ); + if( false == is_buckled() ) { + ErrorLog( "Bad track: \"" + m_name + "\" too short for its buckle" ); + } + } // made with no unevenness, which is read with the attributes and goes onto them by making them again - if( is_uneven() ) { + if( is_uneven() || is_buckled() ) { init_segments( false ); } if( SwitchExtension ) { @@ -892,6 +915,7 @@ void TTrack::init_segments( bool const Initial ) { } else if( Segment ) { Segment->set_uneven( is_uneven() ); + Segment->set_buckled( is_buckled() ); } switch (eType) { @@ -1283,6 +1307,10 @@ bool TTrack::AddDynamicObject(TDynamicObject *Dynamic) } } } + if( Dynamics.empty() ) { + // a train comes onto the track, which can buckle under it in the heat + buckle_pass_enter( *Dynamic ); + } Dynamics.emplace_back( Dynamic ); Dynamic->MyTrack = this; // ABu: na ktorym torze jesteśmy if( Dynamic->iOverheadMask ) { @@ -1330,6 +1358,10 @@ bool TTrack::RemoveDynamicObject(TDynamicObject *Dynamic) } } } + if( result ) { + // the head of a train leaving the track the pass was drawn to buckle + buckle_pass_leave(); + } if( Global.iMultiplayer ) { // jeśli multiplayer if( true == Dynamics.empty() ) { @@ -2312,7 +2344,7 @@ void trail_switch( TTrack &Track, int const i, TDynamicObject const *o ) { Track.Switch(i); // jeśli się tu nie przełączy, to każdy pojazd powtórzy event rozrprucia if( Track.SwitchExtension->m_movablenose && o != nullptr ) { // the wheels can't push the nose of the frog over, the vehicle runs off the rails at it - o->MoverParameters->Derail( TRAILED_SWITCH ); + o->physics->Derail( TRAILED_SWITCH ); } } @@ -2918,6 +2950,9 @@ TTrack::export_as_text_( std::ostream &Output ) const { Output << "railprofile " << m_profile1.first << ' '; } Output << track_uneven::write_attribute( m_uneven, eType == tt_Switch ); + if( eType == tt_Normal && iCategoryFlag == 1 ) { + Output << track_buckle::write_buckle( m_buckledeclared ) << track_buckle::write_cwr( m_cwr ); + } if( false == m_friction.first.empty() ) { Output << "friction " << m_friction.first << ' '; } @@ -4223,6 +4258,68 @@ path_table::InitTracks() { TTrack::fetch_default_profiles(); } +namespace { + +// the tightest radius of the curve of a path in the plan [m], from the circles through its design points about 5 m apart +// (without the unevenness, whose short waves would bend it): the curve the axles of a vehicle follow, whether the track +// gives the radius or only its control points. 0 for a straight one; a radius over 15 km is taken for one, as +// TDynamicObject::Update() takes it +double tightest_radius(TSegment const &Segment) { + + auto const length { Segment.GetLength() }; + if( length < 0.5 ) { + return 0.0; + } + auto const intervals { std::max( 2, static_cast( std::ceil( length / 5.0 ) ) ) }; + auto const flat = [&]( int const Index ) { + auto const point { Segment.FastGetPoint( static_cast( Index ) / intervals ) }; + return glm::dvec2 { point.x, point.z }; }; + auto tightest { 0.0 }; + for( int index = 1; index < intervals; ++index ) { + auto const a { flat( index - 1 ) }; + auto const b { flat( index ) }; + auto const c { flat( index + 1 ) }; + auto const ab { b - a }; + auto const ac { c - a }; + auto const area2 { std::abs( ab.x * ac.y - ab.y * ac.x ) }; + if( area2 < 1e-9 ) { + continue; + } + auto const radius { glm::length( ab ) * glm::length( c - b ) * glm::length( ac ) / ( 2.0 * area2 ) }; + if( radius < 15000.0 && ( tightest == 0.0 || radius < tightest ) ) { + tightest = radius; + } + } + return tightest; +} + +} // namespace + +void +path_table::CheckTracks() const { + + std::vector tracks; + for( auto *path : sequence() ) { + if( path == nullptr || ( path->iCategoryFlag & 1 ) == 0 || path->Segment == nullptr ) { + continue; + } + track_check::track track; + track.name = path->name(); + track.velocity = path->VelocityGet(); + track.plain = ( path->eType == tt_Normal ); + track.radius = track.plain ? tightest_radius( *path->Segment ) : 0.0; + float roll1 { 0.f }, roll2 { 0.f }; + path->Segment->GetRolls( roll1, roll2 ); + track.gauge = path->fTrackWidth; + auto const spacing { 1000.0 * derailment::contact_spacing( track.gauge ) }; + track.cant = { spacing * std::sin( roll1 ), spacing * std::sin( roll2 ) }; + track.damage = path->iDamageFlag; + track.uneven = path->m_uneven; + tracks.emplace_back( std::move( track ) ); + } + track_check::scan( tracks, []( std::string const &Line ) { WriteLog( Line ); } ); +} + // legacy method, sends list of occupied paths over network void path_table::TrackBusyList() const { diff --git a/world/Track.h b/world/Track.h index e679613eb..3ed6e712a 100644 --- a/world/Track.h +++ b/world/Track.h @@ -22,6 +22,7 @@ http://mozilla.org/MPL/2.0/. #include "world/RailLayout.h" #include "world/TrackSleepers.h" #include "world/TrackBlend.h" +#include "world/TrackBuckle.h" #include "world/TrackUneven.h" #include "model/material.h" #include "scene/scenenode.h" @@ -289,6 +290,8 @@ public: int iAction = 0; // czy modyfikowany eventami (specjalna obsługa przy skanowaniu) float fOverhead = -1.0; // można normalnie pobierać prąd (0 dla jazdy bezprądowej po danym odcinku, >0-z opuszczonym i ograniczeniem prędkości) track_uneven::attribute m_uneven; // plain tracks and switches + track_buckle::declared m_buckledeclared; // the buckle entered in the scenery; plain rail tracks + track_buckle::cwr m_cwr; // the welded rail, for the buckling by the temperature private: double fVelocity = -1.0; // ograniczenie prędkości // prędkość dla AI (powyżej rośnie prawdopowobieństwo wykolejenia) public: @@ -423,6 +426,20 @@ public: track_uneven::amounts uneven_at( double const Distance, int const Path = 0 ); // how much of the displacement a point of the profile at the depth takes double uneven_bed_share( double const Depth ) const; + // the buckle the track has now (see TrackBuckle.h): none with physics.trackbuckling off + track_buckle::shape const &buckle() const { + return m_buckle; } + bool is_buckled() const { + return track_buckle::active( m_buckle ); } + // buckles the track during the game as the values say, or with none straightens it, and makes its geometry again. Cause goes to the log + bool buckle_now( track_buckle::declared const &Values, std::string const &Cause ); + // the buckling of the tracks by the temperature of the rails, physics.trackbuckling auto; once a minute + static void update_buckling( double const Deltatime ); + // the radius of the path in the plan at the distance, 0 straight, and the side away from its centre: -1 left, 1 right, 0 straight + double plan_radius( double const Distance, int &Outward ) const; + // the curvature the buckle adds at the distance, averaged over Base around it, 1/m: positive bending with the curve, on a straight + // track to the right of the path + double buckle_curvature( double const Distance, double const Base ) const; // closes the gaps and steps of cant between the ends of joined paths void share_joints(); double joint_depth() const; // mm @@ -484,6 +501,21 @@ private: int stamp { -1 }; }; switch_stray m_switchstray; + track_buckle::shape m_buckle; + // the buckling by the temperature: the passes of the trains over the track, and the pass which will buckle it as its head leaves + std::uint32_t m_buckle_passes { 0 }; + bool m_buckle_armed { false }; + // the buckle of the values on this track, its place and side drawn with the seed where not given + track_buckle::shape resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const; + // the draws for this track: by its name, by where it is for one with none + std::uint64_t buckle_key() const; + // whether the temperature can buckle the track, and the rise of the rails above its neutral temperature it does it at + bool buckles_by_heat() const; + track_buckle::limits buckle_limits() const; + // a train coming onto the track and its head leaving it, for the buckling under a train + void buckle_pass_enter( TDynamicObject const &Dynamic ); + void buckle_pass_leave(); + void buckle_under_train(); switch_stray const &switch_uneven(); void settle_switch_stray(); void settle_switch_ends(); @@ -534,6 +566,9 @@ public: // legacy method, initializes tracks after deserialization from scenario file void InitTracks(); + // physics.trackcheck: logs the geometry of the rail tracks the checks of world/TrackCheck.h find suspicious + void + CheckTracks() const; // legacy method, sends list of occupied paths over network void TrackBusyList() const; diff --git a/world/TrackBlend.h b/world/TrackBlend.h index b3e2c7c63..a239ced39 100644 --- a/world/TrackBlend.h +++ b/world/TrackBlend.h @@ -25,8 +25,9 @@ class TTrack; // ballast, a switch the trackbed made for it namespace track_blend { -// how far from an end the textures blend, by default -float constexpr default_length { 3.f }; +// how far from an end the textures blend where the scenery doesn't say (blendrails, blendballast, blend): not at all, so a +// scenery from before looks as it did. a joint blends where the tracks on both sides of it ask for it +float constexpr default_length { 0.f }; // the order of the lengths of TTrack::m_blend enum class kind { diff --git a/world/TrackBuckle.cpp b/world/TrackBuckle.cpp new file mode 100644 index 000000000..a3d056db8 --- /dev/null +++ b/world/TrackBuckle.cpp @@ -0,0 +1,246 @@ +/* +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 "world/Track.h" +#include "simulation/simulation.h" +#include "simulation/simulationenvironment.h" +#include "scene/scene.h" +#include "utilities/Globals.h" +#include "utilities/Logs.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" + +#include + +namespace { + +// how often the temperature is checked, s of the simulation +double constexpr check_interval { 60.0 }; +// the tracks the temperature can buckle, found at the first check +std::vector heat_sites; +bool heat_sites_found { false }; +double heat_clock { 0.0 }; +// the tracks to buckle under a train, done with the next update rather than amid the moves of the vehicles +std::vector heat_due; + +double rail_temperature_now() { + + return track_buckle::rail_temperature( Global.AirTemperature, simulation::Environment.sun().getAngle(), Global.Overcast ); +} + +} // namespace + +double TTrack::plan_radius( double const Distance, int &Outward ) const { + + Outward = 0; + if( Segment == nullptr || eType != tt_Normal ) { + return 0.0; + } + auto const length { Segment->GetLength() }; + auto const reach { std::min( 5.0, 0.25 * length ) }; + auto const at { std::clamp( Distance, reach, length - reach ) }; + glm::dvec3 behind, middle, ahead, across; + Segment->plan_frame( at - reach, behind, across ); + Segment->plan_frame( at + reach, ahead, across ); + Segment->plan_frame( at, middle, across ); + auto bend { ( behind + ahead - 2.0 * middle ) / ( reach * reach ) }; + bend.y = 0.0; + auto const curvature { glm::length( bend ) }; + // straighter than the curves the tracks are laid with + if( curvature < 1.0 / 20000.0 ) { + return 0.0; + } + // away from the centre, which the bend points to + Outward = ( glm::dot( bend, across ) > 0.0 ? -1 : 1 ); + return 1.0 / curvature; +} + +double TTrack::buckle_curvature( double const Distance, double const Base ) const { + + if( false == is_buckled() || false == track_buckle::within( m_buckle, Distance ) ) { + return 0.0; + } + auto const bend { track_buckle::mean_bend( m_buckle, Distance, Base ) }; + auto outward { 0 }; + plan_radius( Distance, outward ); + // the centre of the curve is away from the outer side + return outward != 0 ? -outward * bend : bend; +} + +std::uint64_t TTrack::buckle_key() const { + + if( false == m_name.empty() && m_name != "none" ) { + return track_buckle::name_hash( m_name ); + } + auto const point { location() }; + return track_buckle::name_hash( std::format( "{:.1f};{:.1f};{:.1f}", point.x, point.y, point.z ) ); +} + +track_buckle::shape TTrack::resolve_buckle( track_buckle::declared const &Values, std::uint32_t const Seed ) const { + + if( Segment == nullptr || eType != tt_Normal || iCategoryFlag != 1 ) { + return {}; + } + auto const length { Segment->GetLength() }; + auto const key { buckle_key() }; + auto const place { track_buckle::draw( key, Seed, track_buckle::place ) }; + // the side out of the curve where the buckle is + auto const centre { Values.centre >= 0.f ? static_cast( Values.centre ) : 0.5 * length }; + auto outward { 0 }; + auto const radius { plan_radius( centre, outward ) }; + return track_buckle::resolve( Values, length, outward, radius, place, track_buckle::draw( key, Seed, track_buckle::way ) ); +} + +bool TTrack::buckle_now( track_buckle::declared const &Values, std::string const &Cause ) { + + if( Global.track_buckling == global_settings::track_buckling_mode::off ) { + return false; + } + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr ) { + ErrorLog( "Bad track: \"" + m_name + "\" can't buckle, it isn't a plain rail track" ); + return false; + } + auto const shape { resolve_buckle( Values, 0 ) }; + if( track_buckle::given( Values ) && false == track_buckle::active( shape ) ) { + ErrorLog( std::format( "Bad track: \"{}\" too short for a buckle {:.0f} m long", m_name, 2.0 * track_buckle::reach_share * ( Values.length > 0.f ? Values.length : track_buckle::straight_length ) ) ); + return false; + } + m_buckle = shape; + m_buckle_armed = false; + // made again with the buckle, which the rails, the sleepers and the axles on the track follow + init_segments( false ); + auto const rebuild = []( TTrack &Track ) { + auto §ion { simulation::Region->section( Track.location() ) }; + Track.rebuild_geometry( section.m_geometrycreated ? section.m_geometrybank : gfx::geometrybank_handle {} ); }; + rebuild( *this ); + for( auto *crossing : m_crossings ) { + if( crossing != nullptr && crossing != this ) { + rebuild( *crossing ); + } + } + if( is_buckled() ) { + WriteLog( std::format( + "Track \"{}\" buckled ({}): {:.0f} mm to the {} at {:.1f} m, main lobe {:.1f} m, curvature up to 1/{:.0f} m", + m_name, Cause, std::abs( 1000.0 * m_buckle.amplitude ), m_buckle.amplitude > 0.0 ? "right" : "left", m_buckle.centre, m_buckle.length, + 1.0 / track_buckle::peak_bend( m_buckle.amplitude, m_buckle.length ) ) ); + } + else { + WriteLog( "Track \"" + m_name + "\" straightened (" + Cause + ")" ); + } + return true; +} + +bool TTrack::buckles_by_heat() const { + + if( eType != tt_Normal || iCategoryFlag != 1 || Segment == nullptr || is_buckled() || false == m_crossings.empty() ) { + return false; + } + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + // continuous welded rail is laid down to a radius of 190 m (PLK ST-T1-A8) + if( radius > 0.0 && radius < 190.0 ) { + return false; + } + auto const natural { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + if( Segment->GetLength() < 2.0 * ( track_buckle::reach_share * natural.length + track_buckle::end_margin ) ) { + return false; + } + return track_buckle::weak_spot( buckle_key(), Global.random_seed, Segment->GetLength(), m_cwr.worked ); +} + +track_buckle::limits TTrack::buckle_limits() const { + + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + return track_buckle::limits_of( m_cwr, radius, uneven_declared().side ); +} + +void TTrack::update_buckling( double const Deltatime ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic ) { + return; + } + if( false == heat_sites_found ) { + heat_sites_found = true; + for( auto *track : simulation::Paths.sequence() ) { + if( track != nullptr && track->buckles_by_heat() ) { + heat_sites.push_back( track ); + } + } + WriteLog( std::format( "Track buckling: {} places the heat can buckle", heat_sites.size() ) ); + // the first check right away, a scenario can start in the heat + heat_clock = check_interval; + } + for( auto *track : heat_due ) { + track->buckle_under_train(); + } + heat_due.clear(); + heat_clock += Deltatime; + if( heat_clock < check_interval ) { + return; + } + heat_clock = 0.0; + auto const rail { rail_temperature_now() }; + for( auto *track : heat_sites ) { + if( track->is_buckled() ) { + continue; + } + auto const rise { rail - track->m_cwr.neutral }; + if( track_buckle::decide( rise, track->buckle_limits(), false, 1.0 ) == track_buckle::verdict::by_itself ) { + auto outward { 0 }; + auto const radius { track->plan_radius( 0.5 * track->Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, track->Segment->GetLength(), outward, radius, + track_buckle::draw( track->buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + track->buckle_now( values, std::format( "rails at {:.0f} C, {:.0f} K above neutral, {:.0f} kN in each", rail, rise, + 0.001 * track_buckle::thermal_force( track_buckle::rail_area( track->m_profile1.first ), rise ) ) ); + } + } +} + +void TTrack::buckle_pass_enter( TDynamicObject const &Dynamic ) { + + if( Global.track_buckling != global_settings::track_buckling_mode::automatic || is_buckled() || false == heat_sites_found ) { + return; + } + if( std::ranges::find( heat_sites, this ) == heat_sites.end() ) { + return; + } + ++m_buckle_passes; + auto const *physics { Dynamic.physics }; + auto const train { physics != nullptr && track_buckle::stirs( std::abs( physics->Vel ), physics->brakes.cylinderPressure > 0.5 ) }; + auto const rise { rail_temperature_now() - m_cwr.neutral }; + auto const draw { track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::pass, m_buckle_passes ) }; + m_buckle_armed = ( track_buckle::decide( rise, buckle_limits(), train, draw ) != track_buckle::verdict::none ); +} + +void TTrack::buckle_pass_leave() { + + if( false == m_buckle_armed ) { + return; + } + m_buckle_armed = false; + heat_due.push_back( this ); +} + +void TTrack::buckle_under_train() { + + if( is_buckled() ) { + return; + } + // under the rest of the train, which lifts the track between its bogies + auto const rail { rail_temperature_now() }; + auto outward { 0 }; + auto const radius { plan_radius( 0.5 * Segment->GetLength(), outward ) }; + auto values { track_buckle::natural( outward != 0 && radius < track_buckle::curve_radius ) }; + values.centre = static_cast( track_buckle::resolve( values, Segment->GetLength(), outward, radius, + track_buckle::draw( buckle_key(), Global.random_seed, track_buckle::place ), 0.0 ).centre ); + buckle_now( values, std::format( "under a train, rails at {:.0f} C, {:.0f} K above neutral", rail, rail - m_cwr.neutral ) ); +} diff --git a/world/TrackBuckle.h b/world/TrackBuckle.h new file mode 100644 index 000000000..25825ed99 --- /dev/null +++ b/world/TrackBuckle.h @@ -0,0 +1,440 @@ +/* +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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Lateral buckling of continuous welded rail: in the heat the rails, held from growing longer, press on the track along it with +// E*A*alpha*dT, and where the bed holds it too weakly sideways the track jumps out to the side. The track of the scenery takes it as +// a displacement across it (TSegment::stray()), drawn and followed by the axles as the unevenness of TrackUneven.h is. +// Sources: Kish, Samavedam, "Risk analysis based CWR track buckling safety evaluations" (Volpe, about 2001); FRA, "Dynamic buckling +// test analyses of a high degree CWR track"; PKP PLK ST-T1-A8 (2021); the answers of the ministry to interpellations 3875 (2026) and +// 2575 (2025). The thresholds and the shape are fitted to the numbers there, see test_track_buckle.cpp. +namespace track_buckle { + +// the shape: a main lobe and a side lobe of the other way on each side of it, as the buckled shapes of Kerr and Kish have it. A +// cosine of a period twice the main lobe under a window cos^2 over three lobes: the side lobes come to a quarter of the main one, and +// the curvature runs on smoothly all along, into the straight track at the ends too, as a bent rail has it +// straight track jumps out far at once, a curve goes out step by step and less far, to the outside of the curve (Kish, Samavedam) +inline constexpr double straight_amplitude { 0.4 }; // m +inline constexpr double straight_length { 14.0 }; // m, main lobe +inline constexpr double curve_amplitude { 0.2 }; // m +inline constexpr double curve_length { 11.0 }; // m +inline constexpr double curve_radius { 1500.0 }; // m, below which a track counts as a curve for the shape +inline constexpr double end_margin { 2.0 }; // m between the buckle and the ends of the track +inline constexpr double most_amplitude { 1.0 }; // m +inline constexpr double least_length { 4.0 }; // m +inline constexpr double most_length { 60.0 }; // m +// how far the side lobes reach from the centre, in lengths of the main lobe +inline constexpr double reach_share { 1.5 }; + +struct shape { + double amplitude { 0.0 }; // of the main lobe, m: positive to the right of the path looking from its start to its end, negative to the left + double length { 0.0 }; // of the main lobe between the points it crosses the line, m; each side lobe is as long + double centre { 0.0 }; // of the main lobe, distance from the start of the path, m +}; + +inline bool active( shape const &Shape ) { + + return Shape.amplitude != 0.0 && Shape.length > 0.0; +} + +// the wave and the window at a distance from the centre, with their derivatives +struct parts { + double wave, wave1, wave2; + double window, window1, window2; +}; + +inline parts parts_at( shape const &Shape, double const Distance ) { + + auto const from { Distance - Shape.centre }; + auto const k { glm::pi() / Shape.length }; + // cos^2(b x) = ( 1 + cos( 2 b x ) ) / 2 reaching 0 at the ends of the side lobes + auto const b { glm::pi() / ( 2.0 * reach_share * Shape.length ) }; + return { + std::cos( k * from ), -k * std::sin( k * from ), -k * k * std::cos( k * from ), + 0.5 * ( 1.0 + std::cos( 2.0 * b * from ) ), -b * std::sin( 2.0 * b * from ), -2.0 * b * b * std::cos( 2.0 * b * from ) }; +} + +inline bool within( shape const &Shape, double const Distance ) { + + return active( Shape ) && std::abs( Distance - Shape.centre ) < reach_share * Shape.length; +} + +// displacement across the path at a distance along it, m +inline double offset( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * p.wave * p.window; +} + +// its first derivative along the path +inline double slope( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave1 * p.window + p.wave * p.window1 ); +} + +// and the second: the curvature the buckle adds to the path, 1/m, positive bending to the right +inline double bend( shape const &Shape, double const Distance ) { + + if( false == within( Shape, Distance ) ) { + return 0.0; + } + auto const p { parts_at( Shape, Distance ) }; + return Shape.amplitude * ( p.wave2 * p.window + 2.0 * p.wave1 * p.window1 + p.wave * p.window2 ); +} + +// the mean curvature over a stretch around a distance, as a bogie over its wheelbase feels it: the difference of the slopes at its ends +// over its length +inline double mean_bend( shape const &Shape, double const Distance, double const Base ) { + + if( Base <= 0.0 ) { + return bend( Shape, Distance ); + } + return ( slope( Shape, Distance + 0.5 * Base ) - slope( Shape, Distance - 0.5 * Base ) ) / Base; +} + +// and as a body on two bogies: it goes sideways by the mean of its pivots, so its lateral acceleration is v^2 times the mean of the +// curvatures at the pivots, each over the wheelbase of the bogie (without bogies: the pivots are the axles, with no base) +inline double body_bend( shape const &Shape, double const Distance, double const Pivots, double const Base ) { + + return 0.5 * ( mean_bend( Shape, Distance - 0.5 * Pivots, Base ) + mean_bend( Shape, Distance + 0.5 * Pivots, Base ) ); +} + +// how far from the centre the buckle reaches on each side +inline double reach( shape const &Shape ) { + + return active( Shape ) ? reach_share * Shape.length : 0.0; +} + +// the largest curvature of the buckle, 1/m, in the middle of the main lobe: pi^2 a / L^2 of the wave and 2/9 of it from the window +inline double peak_bend( double const Amplitude, double const Length ) { + + return ( 1.0 + 2.0 / ( 4.0 * reach_share * reach_share ) ) * glm::pi() * glm::pi() * std::abs( Amplitude ) / ( Length * Length ); +} + +// the heat + +inline constexpr double steel_modulus { 210e9 }; // Pa +inline constexpr double steel_expansion { 1.15e-5 }; // 1/K +inline constexpr double sun_heating { 17.0 }; // K a rail in full sun is warmer than the air: 30 F (Kish, Samavedam) +inline constexpr float neutral_default { 26.f }; // C, the rail stress-free temperature PLK lays its tracks at since 2025 +inline constexpr double area_60e1 { 76.70e-4 }; // m2 +inline constexpr double area_49e1 { 62.92e-4 }; +inline constexpr double area_s42 { 54.2e-4 }; + +// the rail section by the name of the rail profile, 60E1 if it tells nothing +inline double rail_area( std::string_view const Profile ) { + + auto const has = [ Profile ]( std::string_view const Part ) { + return std::search( Profile.begin(), Profile.end(), Part.begin(), Part.end(), []( char const Left, char const Right ) { + return std::tolower( static_cast( Left ) ) == std::tolower( static_cast( Right ) ); } ) != Profile.end(); }; + if( has( "49" ) ) { + return area_49e1; + } + if( has( "s42" ) ) { + return area_s42; + } + return area_60e1; +} + +// the force along a rail held from growing longer, N, pressing for Rise above the neutral temperature +inline double thermal_force( double const Area, double const Rise ) { + + return steel_modulus * Area * steel_expansion * Rise; +} + +// the temperature of a rail, C, from the air, the height of the sun over the horizon in degrees and the clouds (0 clear, 1 overcast; +// above 1 it rains, which cools as much) +inline double rail_temperature( double const Air, double const Sun, double const Overcast ) { + + auto const sun { std::max( 0.0, std::sin( glm::radians( Sun ) ) ) }; + return Air + sun_heating * sun * ( 1.0 - std::clamp( Overcast, 0.0, 1.0 ) ); +} + +// the state of the track, from the scenery +namespace grade { +inline constexpr int good { 0 }; // concrete sleepers, full ballast shoulder, consolidated +inline constexpr int average { 1 }; +inline constexpr int weak { 2 }; // timber sleepers, ballast missing, or the bed disturbed by tamping or sleeper renewal not yet consolidated +} + +struct cwr { + float neutral { neutral_default }; // C + int grade { grade::average }; + bool worked { false }; // works on the bed lately: weak whatever the grade +}; + +// the rise above the neutral temperature at which the track buckles: from low on under a passing train, which lifts it between the +// bogies and takes away part of its hold sideways, at high and above by itself +struct limits { + double low { 0.0 }; // K + double high { 0.0 }; +}; + +inline constexpr std::array grade_limits { { { 40.0, 55.0 }, { 32.0, 45.0 }, { 22.0, 32.0 } } }; + +// for the grade of the track, lowered in a curve, which presses outwards, and by an uneven line, which gives it a start +inline limits limits_of( cwr const &Track, double const Radius, double const Side ) { + + auto const kind { Track.worked ? grade::weak : std::clamp( Track.grade, grade::good, grade::weak ) }; + auto result { grade_limits[ kind ] }; + auto less { 0.0 }; + auto const radius { std::abs( Radius ) }; + if( radius > 0.0 && radius < 300.0 ) { + less += 6.0; + } + else if( radius > 0.0 && radius < 600.0 ) { + less += 3.0; + } + if( Side > 15.0 ) { + less += 3.0; + } + result.low -= less; + result.high -= less; + return result; +} + +// the share of the passes of a train which buckle the track at the rise: none below low, all at high +inline double chance( double const Rise, limits const &Limits ) { + + if( Limits.high <= Limits.low ) { + return Rise >= Limits.high ? 1.0 : 0.0; + } + return std::clamp( ( Rise - Limits.low ) / ( Limits.high - Limits.low ), 0.0, 1.0 ); +} + +enum class verdict { + none, + under_train, + by_itself +}; + +// with Train the track has a train going over it hard enough, Draw is the draw of the pass, 0 to 1 +inline verdict decide( double const Rise, limits const &Limits, bool const Train, double const Draw ) { + + if( Rise >= Limits.high ) { + return verdict::by_itself; + } + if( Train && Rise >= Limits.low && Draw < chance( Rise, Limits ) ) { + return verdict::under_train; + } + return verdict::none; +} + +// a train stirs the track up when it goes fast or brakes on it +inline constexpr double stirring_speed { 40.0 }; // km/h +inline bool stirs( double const Speed, bool const Braking ) { + + return Speed > stirring_speed || ( Braking && Speed > 5.0 ); +} + +// draws, the same for the same track and seed + +// FNV-1a, which std::hash isn't on every compiler +inline std::uint64_t name_hash( std::string_view const Name ) { + + std::uint64_t hash { 14695981039346656037ULL }; + for( auto const character : Name ) { + hash ^= static_cast( character ); + hash *= 1099511628211ULL; + } + return hash; +} + +// the splitmix64 finalizer, so close numbers give far apart draws +inline std::uint64_t scramble( std::uint64_t Value ) { + + Value += 0x9e3779b97f4a7c15ULL; + Value = ( Value ^ ( Value >> 30 ) ) * 0xbf58476d1ce4e5b9ULL; + Value = ( Value ^ ( Value >> 27 ) ) * 0x94d049bb133111ebULL; + return Value ^ ( Value >> 31 ); +} + +// what a draw is for, so the draws for one track don't go together +enum purpose : std::uint64_t { + pass = 1, + site = 2, + place = 3, + way = 4 +}; + +// a fraction 0 to 1 +inline double draw( std::uint64_t const Name, std::uint32_t const Seed, std::uint64_t const Purpose, std::uint64_t const Number = 0 ) { + + auto const value { scramble( scramble( scramble( Name ^ Purpose ) + Seed ) + Number ) }; + // the 53 high bits + return static_cast( value >> 11 ) / 9007199254740992.0; +} + +// where the track buckles by the temperature on its own: one place in so many metres of track, and the tracks worked on lately. +// Elsewhere the bed holds far beyond the limits of the grade (Sweden: 200 buckles in the hot summer of 2018 on 14 000 km) +inline constexpr double site_spacing { 10000.0 }; // m + +inline bool weak_spot( std::uint64_t const Name, std::uint32_t const Seed, double const Length, bool const Worked ) { + + return Worked || draw( Name, Seed, site ) < Length / site_spacing; +} + +// the entries in the scenery + +// buckle ;;[;] +struct declared { + float amplitude { 0.f }; // mm + float length { -1.f }; // m, negative: by the shape of the track + float centre { -1.f }; // m, negative: drawn + int side { 0 }; +}; + +inline bool given( declared const &Values ) { + + return Values.amplitude > 0.f; +} + +// the numbers of an entry like "400;18;60", NaN where left out +template +std::array read_numbers( std::string_view const Text ) { + + std::array result; + result.fill( std::numeric_limits::quiet_NaN() ); + auto rest { Text }; + for( auto &field : result ) { + auto const end { std::min( rest.find( ';' ), rest.size() ) }; + if( auto value { 0.f }; end > 0 && std::from_chars( rest.data(), rest.data() + end, value ).ec == std::errc {} && std::isfinite( value ) ) { + field = value; + } + if( end == rest.size() ) { + break; + } + rest.remove_prefix( end + 1 ); + } + return result; +} + +inline declared read_buckle( std::string_view const Text ) { + + auto const fields { read_numbers<4>( Text ) }; + declared result; + if( std::isfinite( fields[ 0 ] ) ) { + result.amplitude = std::clamp( fields[ 0 ], 0.f, static_cast( most_amplitude * 1000.0 ) ); + } + if( std::isfinite( fields[ 1 ] ) && fields[ 1 ] > 0.f ) { + result.length = std::clamp( fields[ 1 ], static_cast( least_length ), static_cast( most_length ) ); + } + if( std::isfinite( fields[ 2 ] ) && fields[ 2 ] >= 0.f ) { + result.centre = fields[ 2 ]; + } + if( std::isfinite( fields[ 3 ] ) ) { + result.side = ( fields[ 3 ] > 0.f ? 1 : fields[ 3 ] < 0.f ? -1 : 0 ); + } + return result; +} + +inline std::string write_buckle( declared const &Values ) { + + if( false == given( Values ) ) { + return {}; + } + std::ostringstream text; + text << "buckle " << Values.amplitude << ';'; + if( Values.length > 0.f ) { + text << Values.length; + } + text << ';'; + if( Values.centre >= 0.f ) { + text << Values.centre; + } + if( Values.side != 0 ) { + text << ';' << Values.side; + } + text << ' '; + return text.str(); +} + +// cwr ;[;] +inline cwr read_cwr( std::string_view const Text ) { + + auto const fields { read_numbers<3>( Text ) }; + cwr result; + if( std::isfinite( fields[ 0 ] ) ) { + result.neutral = std::clamp( fields[ 0 ], -20.f, 60.f ); + } + if( std::isfinite( fields[ 1 ] ) ) { + result.grade = std::clamp( static_cast( std::lround( fields[ 1 ] ) ), 0, 2 ); + } + if( std::isfinite( fields[ 2 ] ) ) { + result.worked = fields[ 2 ] > 0.f; + } + return result; +} + +inline std::string write_cwr( cwr const &Values ) { + + if( Values.neutral == neutral_default && Values.grade == grade::average && false == Values.worked ) { + return {}; + } + std::ostringstream text; + text << "cwr " << Values.neutral << ';' << Values.grade; + if( Values.worked ) { + text << ";1"; + } + text << ' '; + return text.str(); +} + +// the buckle of the values on a track of the length, which curves to the side Outward (-1 left, 1 right, 0 straight), with radius +// Radius (0 straight); None for one which doesn't fit into the track. Place and Way are draws for the centre and the side not given +inline shape resolve( declared const &Values, double const Length, int const Outward, double const Radius, double const Place, double const Way ) { + + if( false == given( Values ) ) { + return {}; + } + auto const curve { Outward != 0 && Radius > 0.0 && Radius < curve_radius }; + shape result; + result.length = Values.length > 0.f ? static_cast( Values.length ) : ( curve ? curve_length : straight_length ); + auto const first { reach_share * result.length + end_margin }; + auto const last { Length - reach_share * result.length - end_margin }; + if( last < first ) { + return {}; + } + result.centre = Values.centre >= 0.f ? std::clamp( static_cast( Values.centre ), first, last ) : first + ( last - first ) * Place; + auto const side { Values.side != 0 ? Values.side : Outward != 0 ? Outward : ( Way < 0.5 ? -1 : 1 ) }; + result.amplitude = side * 0.001 * Values.amplitude; + return result; +} + +// the buckle the temperature makes on a track: as large as a curve or a straight one makes +inline declared natural( bool const Curve ) { + + declared result; + result.amplitude = static_cast( 1000.0 * ( Curve ? curve_amplitude : straight_amplitude ) ); + result.length = static_cast( Curve ? curve_length : straight_length ); + return result; +} + +} // namespace track_buckle diff --git a/world/TrackCheck.cpp b/world/TrackCheck.cpp new file mode 100644 index 000000000..c0661bf2f --- /dev/null +++ b/world/TrackCheck.cpp @@ -0,0 +1,240 @@ +/* +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 "world/TrackCheck.h" + +#include +#include +#include + +namespace track_check { + +namespace { + +constexpr double kmh{3.6}; + +reference make_reference(std::string const &Name, double const Mass, double const Length, double const AxleBase, double const BodyHeight, derailment::vehicle_class const Class) { + reference result; + result.name = Name; + result.vehicle.mass = Mass; + result.vehicle.axles = 4; + result.vehicle.length = Length; + result.vehicle.axle_base = AxleBase; + result.vehicle.centre_of_gravity = derailment::default_centre_of_gravity(BodyHeight, Class); + return result; +} + +// the cant [rad] of the given height of the outer rail [mm] +double cant_angle(double const Cant, double const Gauge) { + return std::asin(std::clamp(std::abs(Cant) / (1000.0 * derailment::contact_spacing(Gauge)), 0.0, 1.0)); +} + +void append(std::string &Text, std::string const &Part) { + if (false == Text.empty()) { + Text += "; "; + } + Text += Part; +} + +// the values of the unevenness past the range, as "side 40, cross 30" +std::string uneven_excess(track_uneven::attribute const &Uneven, settings const &Settings) { + std::string result; + auto const test = [&](char const *Name, float const Value, double const Most) { + if (Value > Most) { + if (false == result.empty()) { + result += ", "; + } + result += std::format("{} {:g}", Name, Value); + } + }; + test("value", Uneven.value, Settings.most_uneven); + test("up", Uneven.up, Settings.most_uneven); + test("side", Uneven.side, Settings.most_uneven); + test("cross", Uneven.cross, Settings.most_cross); + test("dip", Uneven.dip, Settings.most_uneven); + test("branch", Uneven.branch, Settings.most_uneven); + test("branch up", Uneven.branchup, Settings.most_uneven); + test("branch side", Uneven.branchside, Settings.most_uneven); + return result; +} + +// what the check of a track found so far +struct collector { + findings &result; + void add(kind const Kind, std::string const &Text) const { + if (std::ranges::find(result.kinds, Kind) == result.kinds.end()) { + result.kinds.push_back(Kind); + } + append(result.text, Text); + } +}; + +derailment::track_state curve_of(track const &Track) { + // with the cant both ends have at the least + auto const cant{std::min(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; + derailment::track_state result; + result.radius = Track.radius; + result.cant = cant_angle(cant, Track.gauge); + result.gauge = Track.gauge; + return result; +} + +// a speed limit over the speed a reference vehicle overturns or climbs the rail at in the curve +void check_limit(track const &Track, std::vector const &References, collector const &Found) { + auto const curve{curve_of(Track)}; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && Track.velocity > overturning) { + Found.add(kind::overturning, std::format("speed limit {:.0f} km/h over the overturning speed of {} {:.0f} km/h", Track.velocity, reference.name, overturning)); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && Track.velocity > *climbing * kmh) { + Found.add(kind::climbing, std::format("speed limit {:.0f} km/h over the flange climbing speed of {} {:.0f} km/h", Track.velocity, reference.name, *climbing * kmh)); + } + } +} + +// a curve without a speed limit: how fast it takes the reference vehicles, when that's under the unlimited velocity +void check_unlimited(track const &Track, std::vector const &References, settings const &Settings, collector const &Found) { + auto const curve{curve_of(Track)}; + auto slowest{Settings.unlimited_velocity}; + std::string what; + for (auto const &reference : References) { + auto const overturning{derailment::overturning_speed(curve.radius, curve.cant, reference.vehicle.centre_of_gravity, curve.gauge) * kmh}; + if (overturning > 0.0 && overturning < slowest) { + slowest = overturning; + what = std::format("the overturning speed of {}", reference.name); + } + if (auto const climbing{derailment::climbing_speed(reference.vehicle, curve)}; climbing.has_value() && *climbing * kmh < slowest) { + slowest = *climbing * kmh; + what = std::format("the flange climbing speed of {}", reference.name); + } + } + if (what.empty()) { + return; + } + Found.result.unlimited_speed = slowest; + Found.add(kind::unlimited_curve, std::format("no speed limit set (not a defect): the curve takes at most {:.0f} km/h, {}", slowest, what)); +} + +} // namespace + +std::vector const &default_references() { + static std::vector const references{ + make_reference("EU07", 80000.0, 15.915, 3.0, 4.348, derailment::vehicle_class::powered), + make_reference("coach", 40000.0, 24.5, 2.5, 4.05, derailment::vehicle_class::unpowered), + }; + return references; +} + +std::string_view name_of(kind const Kind) { + switch (Kind) { + case kind::overturning: + return "overturning"; + case kind::climbing: + return "flange climbing"; + case kind::cant_on_straight: + return "cant on a straight"; + case kind::cant_excess: + return "cant too high"; + case kind::tight_curve: + return "tight curve too fast"; + case kind::uneven: + return "uneven out of range"; + case kind::unlimited_curve: + return "curve without a speed limit"; + default: + return "?"; + } +} + +bool is_defect(kind const Kind) { + return Kind != kind::unlimited_curve; +} + +bool findings::defective() const { + return std::ranges::any_of(kinds, [](kind const Kind) { return is_defect(Kind); }); +} + +findings check(track const &Track, std::vector const &References, settings const &Settings) { + findings result; + collector const found{result}; + auto const curved{Track.radius > 0.0}; + auto const given{Track.velocity >= 0.0}; + + if (Track.plain) { + // a closed track (speed 0) isn't run on + if (curved && given && Track.velocity > 0.0) { + check_limit(Track, References, found); + } + if (curved && false == given) { + check_unlimited(Track, References, Settings, found); + } + // cant held over the whole of a straight track: a transition has it at one end only + if (false == curved && std::abs(Track.cant[0]) > Settings.straight_cant && std::abs(Track.cant[1]) > Settings.straight_cant && Track.cant[0] * Track.cant[1] > 0.0) { + found.add(kind::cant_on_straight, std::format("cant {:.0f} / {:.0f} mm on a straight track", Track.cant[0], Track.cant[1])); + } + if (curved && given && Track.velocity > Settings.tight_velocity && Track.radius < Settings.tight_radius) { + found.add(kind::tight_curve, std::format("radius {:.0f} m with a speed limit of {:.0f} km/h", Track.radius, Track.velocity)); + } + } + if (auto const most{std::max(std::abs(Track.cant[0]), std::abs(Track.cant[1]))}; most > Settings.most_cant) { + found.add(kind::cant_excess, std::format("cant {:.0f} mm over {:.0f} mm", most, Settings.most_cant)); + } + if (auto const excess{uneven_excess(Track.uneven, Settings)}; false == excess.empty()) { + found.add(kind::uneven, std::format("uneven {} mm out of range", excess)); + } + if (false == result.empty()) { + result.text += std::format(" (radius {:.0f} m, cant {:.0f} / {:.0f} mm, speed limit {}, damage {})", Track.radius, Track.cant[0], Track.cant[1], + given ? std::format("{:.0f} km/h", Track.velocity) : std::string{"none"}, Track.damage); + } + return result; +} + +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References, settings const &Settings) { + summary result; + for (auto const &track : Tracks) { + ++result.tracks; + if (track.damage != 0) { + ++result.damage[track.damage]; + } + auto const found{check(track, References, Settings)}; + if (found.empty()) { + continue; + } + if (found.defective()) { + ++result.suspicious; + } + if (found.unlimited_speed > 0.0) { + ++result.unlimited; + result.slowest = result.slowest > 0.0 ? std::min(result.slowest, found.unlimited_speed) : found.unlimited_speed; + } + for (auto const kind : found.kinds) { + ++result.counts[static_cast(kind)]; + } + Log(std::format("trackcheck: {}: {}", track.name.empty() ? std::string{"(none)"} : track.name, found.text)); + } + std::string counts; + for (std::size_t index = 0; index < result.counts.size(); ++index) { + if (auto const kind{static_cast(index)}; is_defect(kind)) { + append(counts, std::format("{} {}", name_of(kind), result.counts[index])); + } + } + Log(std::format("trackcheck: {} rail tracks checked, {} suspicious: {}", result.tracks, result.suspicious, counts)); + Log(std::format("trackcheck: curves without a speed limit: {} taking the reference vehicles under {:.0f} km/h (not a defect){}", result.unlimited, Settings.unlimited_velocity, + result.unlimited > 0 ? std::format(", the slowest at {:.0f} km/h", result.slowest) : std::string{})); + std::string damage; + for (auto const &[flags, count] : result.damage) { + append(damage, std::format("{} on {}", flags, count)); + } + Log(std::format("trackcheck: damage flags: {}", damage.empty() ? std::string{"none"} : damage)); + return result; +} + +} // namespace track_check diff --git a/world/TrackCheck.h b/world/TrackCheck.h new file mode 100644 index 000000000..c7b40feba --- /dev/null +++ b/world/TrackCheck.h @@ -0,0 +1,106 @@ +/* +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 + +#include "physics/derailment.h" +#include "world/TrackUneven.h" + +#include +#include +#include +#include +#include +#include + +// the check of the geometry of the rail tracks of a scenery (physics.trackcheck yes in eu07.ini): what the criteria of +// derailment (physics/derailment.h) and the plain rules of the track find suspicious, to the log once the scenery +// loaded, so a run can tell a faulty scenery from a faulty simulation. one line for a track with all it found +// ("trackcheck: : ..."), and a summary with the count of each kind. the damage flags are only counted: sceneries +// set them for the jolts of a worn track (damage 31 on every track of line 107). a curve without a speed limit of its +// own is no defect (the drivers go by the signals and the timetable there, the tram loops of a town have none), it is +// only told how fast it takes the reference vehicles, apart from the defects. the rail tracks of trams have no category +// of their own (a tram is a vehicle of the category of the trains, on a track of theirs), so they are checked alike +namespace track_check { + +// a rail track as the check sees it +struct track { + std::string name; + double velocity{-1.0}; // the speed limit of the track [km/h], negative when it gives none + double radius{0.0}; // the tightest radius of its curve [m], 0 on a straight one + std::array cant{0.0, 0.0}; // at its ends [mm], positive raising the right rail + double gauge{1.435}; // [m] + int damage{0}; // dtrack_* flags + bool plain{true}; // a plain track, its speed and curve checked; a switch or a crossing has the paths and the + // speeds of its position, only its unevenness and its damage are + track_uneven::attribute uneven; +}; + +// a vehicle the speed limit of a curve is checked for +struct reference { + std::string name; + derailment::vehicle_state vehicle; +}; +// the default vehicles of derailment.h: an EU07 (4 axles, 80 t, 15.9 m, bogies of 3 m, the centre of gravity of its +// 4.35 m high body) and a 4-axle coach (40 t, 24.5 m, bogies of 2.5 m, 4.05 m high), alone, without a .fiz +std::vector const &default_references(); + +struct settings { + // a curve without a speed limit is told of when it takes the reference vehicles slower than this [km/h]: the top + // speed of the EU07, the trains the default vehicles make up run no faster + double unlimited_velocity{125.0}; + double most_cant{160.0}; // [mm], 150 the most of the Polish rules (Id-1), and a margin + double straight_cant{5.0}; // the cant both ends of a straight track have, past which it's cant without a curve [mm] + double tight_radius{40.0}; // a curve tighter than this [m] + double tight_velocity{40.0}; // with a speed limit over this [km/h] + double most_uneven{30.0}; // the value, up, side and dip of the unevenness [mm]: Id-14 lets the poorest track 28 mm + double most_cross{25.0}; // the cross level [mm]: 20 mm in class C of Id-14 +}; + +enum class kind { + overturning, // the speed limit is over the speed a reference vehicle overturns at + climbing, // or over the one its flange climbs the rail at + cant_on_straight, // both ends of a straight track have the same cant + cant_excess, // over the most cant + tight_curve, // a curve tighter than the tight radius with a speed limit over the tight velocity + uneven, // the unevenness out of the plausible range + unlimited_curve, // no defect: a curve without a speed limit, which takes the reference vehicles slower than the + // unlimited velocity + count_ +}; +std::string_view name_of(kind Kind); +// whether the kind is a defect of the scenery, rather than a note +bool is_defect(kind Kind); + +// what the check found on a track +struct findings { + std::vector kinds; + std::string text; // what the log line tells after the name of the track, empty when nothing + double unlimited_speed{0.0}; // the speed a curve without a speed limit takes the reference vehicles at [km/h], 0 when + // not told of + bool empty() const { return kinds.empty(); } + bool defective() const; // has a kind which is a defect +}; +findings check(track const &Track, std::vector const &References = default_references(), settings const &Settings = {}); + +struct summary { + int tracks{0}; // checked + int suspicious{0}; // with a defect + int unlimited{0}; // curves without a speed limit told of, defects or not + double slowest{0.0}; // the lowest speed one of them takes the reference vehicles at [km/h], 0 without any + std::array(kind::count_)> counts{}; + std::map damage; // the tracks of each value of the damage flags, none for 0 + int count(kind const Kind) const { return counts[static_cast(Kind)]; } +}; + +using sink = std::function; +// checks the tracks, logs a line for each one found suspicious and the summary +summary scan(std::vector const &Tracks, sink const &Log, std::vector const &References = default_references(), settings const &Settings = {}); + +} // namespace track_check diff --git a/world/TrackSleepers.cpp b/world/TrackSleepers.cpp index a24bd443b..4dc3d9fe6 100644 --- a/world/TrackSleepers.cpp +++ b/world/TrackSleepers.cpp @@ -79,7 +79,13 @@ double blade_rise( TTrack const &Track ) { double wing_rise( TTrack const &Track ) { - return ( lays( Track ) ? timber_model( Track )->slide : 0.0 ); + if( false == lays( Track ) ) { + return 0.0; + } + // the chairs the blades slide on are those of the model the timbers are laid of: once they're laid, that of the panel the track + // shares them with (lay()), which can be another one than its own or the one of eu07.ini + auto const *model { Track.m_sleepers3d.timbers }; + return ( model != nullptr ? model : timber_model( Track ) )->slide; } glm::dvec2 stock_stretch( TTrack const &Track, int const Path, int const Side ) { @@ -333,6 +339,8 @@ void instance( TTrack &Track, std::vector &&Beams, bool const Fastened ) { void lay( TTrack &Track, bool const Fastened ) { auto &laid { Track.m_sleepers3d }; + // what the rails of the track were made with + auto const rise { wing_rise( Track ) }; std::vector placed; if( laid.active && in_background() && timber_model( Track ) != nullptr ) { // worked out in the background; till then the track keeps what it has, and tries again @@ -362,6 +370,14 @@ void lay( TTrack &Track, bool const Fastened ) { // the layout of the cluster isn't needed by this track any more, the instances below are what's drawn forget_layout( Track ); instance( Track, std::move( beams ), Fastened ); + // the rails were made with the blades and the wing rails raised for the chairs of the model the track had then: where the model + // of the panel raises them otherwise, they're made again, with it. Made again, they keep that model, so this happens once + if( std::abs( wing_rise( Track ) - rise ) > 1e-4 ) { + auto §ion { simulation::Region->section( Track.location() ) }; + if( section.m_geometrycreated ) { + Track.rebuild_geometry( section.m_geometrybank ); + } + } } void fasten( TTrack &Track ) { diff --git a/world/TrackSleepers.h b/world/TrackSleepers.h index 117e68dcf..7fd16f5e8 100644 --- a/world/TrackSleepers.h +++ b/world/TrackSleepers.h @@ -11,6 +11,7 @@ http://mozilla.org/MPL/2.0/. #include #include +#include #include #include #include @@ -158,6 +159,9 @@ struct pack_model { // the models of sleepers and timbers in the scenery data, found once in models/ by the names of their files telling sleepers // or timbers: podklad, podrozjazd, sleeper, timber. the timber ones first, then by the name std::vector const &pack_models(); +// the models of sleepers and timbers among the files under the folder given, named relative to it, in the same order; a file +// named with a character the code page lacks is left out +std::vector pack_models( std::filesystem::path const &Root ); // the beams of the track placed anew, as instances of the parts of the model; with the fastenings, or those left for later void lay( TTrack &Track, bool const Fastened = true ); // the fastenings left out laid on the beams of the track diff --git a/world/Traction.cpp b/world/Traction.cpp index 5aa25e1a5..d85a9599c 100644 --- a/world/Traction.cpp +++ b/world/Traction.cpp @@ -15,6 +15,7 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/Traction.h" #include "world/catenary_span.h" +#include "world/TractionTail.h" #include "simulation/simulation.h" #include "utilities/Globals.h" @@ -138,41 +139,18 @@ TTraction::Load( cParser *parser, glm::dvec3 const &pOrigin ) { >> WireOffset; m_visible = parser->getToken() == "vis"; - std::string token { parser->getToken() }; - std::string catenarytype; - double catenarytension[ 2 ] { 0.0, 0.0 }; - glm::dvec3 catenaryrope2[ 2 ]; - bool catenaryrope2set[ 2 ] { false, false }; - while( false == token.empty() - && token != "endtraction" ) { - - if( token == "parallel" ) { - // jawne wskazanie innego przęsła, na które może przestawić się pantograf - parser->getTokens(); - *parser >> asParallel; - } - else if( token == "type" ) { - // symbol typu sieci, np. YwsC120-2C; starsze wersje symulatora pomijają ten dopisek - catenarytype = parser->getToken( false ); - } - else if( token == "rope2" ) { - // koniec drugiej liny nośnej przy kotwieniu: "rope2 start|end x y z" - auto const which { parser->getToken() }; - auto const point { LoadPoint( *parser ) + pOrigin }; - auto const end { which == "end" ? 1 : 0 }; - catenaryrope2[ end ] = point; - catenaryrope2set[ end ] = true; - } - else if( token == "tension" ) { - // naciąg liny nośnej i przewodów jezdnych w daN inny niż w typie sieci (brakujące ciężary w kotwieniu) - parser->getTokens( 2 ); - *parser >> catenarytension[ 0 ] >> catenarytension[ 1 ]; - } - token = parser->getToken(); - } + // dopiski: "parallel" (jawne wskazanie innego przęsła, na które może przestawić się pantograf), "type" (symbol typu sieci, + // np. YwsC120-2C; starsze wersje symulatora pomijają ten dopisek), "rope2" (koniec drugiej liny nośnej przy kotwieniu), + // "tension" (naciąg liny nośnej i przewodów jezdnych w daN inny niż w typie sieci, brakujące ciężary w kotwieniu) + traction_tail tail; + tail.parallel = asParallel; + read_traction_tail( *parser, pOrigin, tail ); + asParallel = tail.parallel; + // zapamiętane, żeby zapis z edytora ich nie zgubił + m_tail = tail; Init(); // przeliczenie parametrów - catenary_span_assign( *this, catenarytype, catenarytension[ 0 ], catenarytension[ 1 ], catenaryrope2, catenaryrope2set ); + catenary_span_assign( *this, tail.type, tail.tension[ 0 ], tail.tension[ 1 ], tail.rope2.data(), tail.rope2set.data() ); // calculate traction location location( glm::mix( pPoint2, pPoint1, 0.5 ) ); @@ -705,13 +683,11 @@ TTraction::export_as_text_( std::ostream &Output ) const { // visibility // NOTE: 'invis' would be less wrong than 'unvis', but potentially incompatible with old 3rd party tools Output << ( m_visible ? "vis" : "unvis" ) << ' '; - // optional attributes - if( false == asParallel.empty() ) { - Output << "parallel " << asParallel << ' '; - } - if( auto const catenarytype { catenary_span_symbol( *this ) }; false == catenarytype.empty() ) { - Output << "type " << catenarytype << ' '; - } + // optional attributes, all that Load() reads + auto tail { m_tail }; + tail.parallel = asParallel; + tail.type = catenary_span_symbol( *this ); + write_traction_tail( Output, tail ); // footer Output << "endtraction" diff --git a/world/Traction.h b/world/Traction.h index d1a16f497..32ab3d5c5 100644 --- a/world/Traction.h +++ b/world/Traction.h @@ -16,6 +16,7 @@ http://mozilla.org/MPL/2.0/. #include "world/Segment.h" #include "model/material.h" #include "utilities/Names.h" +#include "world/TractionTail.h" class TTractionPowerSource; namespace gfx @@ -62,6 +63,8 @@ class TTraction : public scene::basic_node gfx::geometry_handle m_geometry; // stan przęsła rysowanego wg typu sieci (dopisek "type"); pusty = przęsło rysowane po staremu. szczegóły w world/catenary_span.h std::shared_ptr m_catenaryspan; + // dopiski wpisu "tension" i "rope2" w postaci wczytanej, zapisywane z powrotem przez export_as_text_ + traction_tail m_tail; explicit TTraction( scene::node_data const &Nodedata ); diff --git a/world/TractionTail.h b/world/TractionTail.h new file mode 100644 index 000000000..0d79d51a1 --- /dev/null +++ b/world/TractionTail.h @@ -0,0 +1,74 @@ +/* +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/. +*/ + +// Dopiski wpisu "node ... traction" po "vis"/"unvis", do "endtraction": czytane przy wczytaniu przęsła i zapisywane +// z powrotem przy zapisie z edytora, żeby zapis nie gubił niczego, co wczytanie przeczytało + +#pragma once + +#include +#include +#include + +#include "utilities/parser.h" +#include "utilities/utilities.h" + +struct traction_tail { + std::string parallel; // "parallel ": bieżnia wspólna + std::string type; // "type ": typ sieci, wielkość liter zachowana + std::array tension { 0.0, 0.0 }; // "tension " w daN; 0 = jak w typie + std::array rope2 {}; // "rope2 start|end x y z": końce drugiej liny nośnej, w układzie scenerii + std::array rope2set { false, false }; +}; + +// czyta dopiski do "endtraction" włącznie; Origin: przesunięcie punktów (origin scenerii) +inline void +read_traction_tail( cParser &Parser, glm::dvec3 const &Origin, traction_tail &Tail ) { + auto token { Parser.getToken() }; + while( false == token.empty() && token != "endtraction" ) { + if( token == "parallel" ) { + Parser.getTokens(); + Parser >> Tail.parallel; + } + else if( token == "type" ) { + Tail.type = Parser.getToken( false ); + } + else if( token == "rope2" ) { + auto const which { Parser.getToken() }; + auto const point { LoadPoint( Parser ) + Origin }; + auto const end { which == "end" ? 1 : 0 }; + Tail.rope2[ end ] = point; + Tail.rope2set[ end ] = true; + } + else if( token == "tension" ) { + Parser.getTokens( 2 ); + Parser >> Tail.tension[ 0 ] >> Tail.tension[ 1 ]; + } + token = Parser.getToken(); + } +} + +// zapisuje dopiski w postaci, którą czyta read_traction_tail(), bez "endtraction"; każdy zakończony spacją +inline void +write_traction_tail( std::ostream &Output, traction_tail const &Tail ) { + if( false == Tail.parallel.empty() ) { + Output << "parallel " << Tail.parallel << ' '; + } + if( false == Tail.type.empty() ) { + Output << "type " << Tail.type << ' '; + } + if( Tail.tension[ 0 ] != 0.0 || Tail.tension[ 1 ] != 0.0 ) { + Output << "tension " << Tail.tension[ 0 ] << ' ' << Tail.tension[ 1 ] << ' '; + } + for( int end = 0; end < 2; ++end ) { + if( false == Tail.rope2set[ end ] ) { continue; } + auto const &point { Tail.rope2[ end ] }; + Output << "rope2 " << ( end == 0 ? "start" : "end" ) << ' ' << point.x << ' ' << point.y << ' ' << point.z << ' '; + } +} diff --git a/world/TrkFoll.cpp b/world/TrkFoll.cpp index 986f87a4f..79362a993 100644 --- a/world/TrkFoll.cpp +++ b/world/TrkFoll.cpp @@ -21,6 +21,7 @@ http://mozilla.org/MPL/2.0/. #include "vehicle/DynObj.h" #include "vehicle/Driver.h" #include "utilities/Logs.h" +#include "physics/vehicle.h" namespace { @@ -126,7 +127,7 @@ TTrack * TTrackFollower::SetCurrentTrack(TTrack *pTrack, int end) pCurrentTrack = pTrack; pCurrentSegment = pCurrentTrack != nullptr ? pCurrentTrack->CurrentSegment() : nullptr; if (!pCurrentTrack) - Error(Owner->MoverParameters->Name + " at NULL track"); + Error(Owner->physics->Name + " at NULL track"); return pCurrentTrack; }; @@ -344,7 +345,7 @@ bool TTrackFollower::Move(double fDistance, bool bPrimary) { // gdy zostaje na tym samym torze (przesuwanie już nie zmienia toru) if (bPrimary) { // tylko gdy początkowe ustawienie, dodajemy eventy stania do kolejki - if (Owner->MoverParameters->CabOccupied != 0) { + if (Owner->physics->CabOccupied() != 0) { pCurrentTrack->QueueEvents( pCurrentTrack->m_events1, Owner, -1.0 ); pCurrentTrack->QueueEvents( pCurrentTrack->m_events2, Owner, -1.0 ); @@ -363,6 +364,27 @@ double TTrackFollower::RailPhase( double const Offset ) const { return pCurrentTrack != nullptr ? pCurrentTrack->rail_phase( fCurrentDistance + fDirection * Offset ) : -1.0; } +double TTrackFollower::BuckleCurvature( double const Base ) const { + + return pCurrentTrack != nullptr ? pCurrentTrack->buckle_curvature( fCurrentDistance, Base ) : 0.0; +} + +glm::dvec3 TTrackFollower::PathDirection( double const Reach ) const { + + if( pCurrentSegment == nullptr ) { + return glm::dvec3 { 0.0 }; + } + auto const length { pCurrentSegment->GetLength() }; + glm::dvec3 ahead; + glm::dvec3 behind; + glm::vec3 rotation; + pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance + Reach, 0.0, length ), ahead, rotation ); + pCurrentSegment->RaPositionGet( std::clamp( fCurrentDistance - Reach, 0.0, length ), behind, rotation ); + glm::dvec3 const direction { ( ahead.x - behind.x ) * fDirection, 0.0, ( ahead.z - behind.z ) * fDirection }; + auto const size { glm::length( direction ) }; + return size > 1e-6 ? direction / size : glm::dvec3 { 0.0 }; +} + bool TTrackFollower::ComputatePosition() { // ustalenie współrzędnych XYZ if (pCurrentSegment) // o ile jest tor diff --git a/world/TrkFoll.h b/world/TrkFoll.h index aaef51762..8de41a261 100644 --- a/world/TrkFoll.h +++ b/world/TrkFoll.h @@ -43,6 +43,11 @@ public: return pCurrentSegment ? pCurrentSegment->uneven_bend( fCurrentDistance ) : glm::dvec3 { 0.0 }; }; // TTrack::rail_phase of the point Offset ahead of the axle along the vehicle double RailPhase( double const Offset ) const; + // TTrack::buckle_curvature at the axle, averaged over Base around it + double BuckleCurvature( double const Base ) const; + // the level direction of the path the axle runs on, with its buckle and its uneven track, over Reach [m] behind and + // ahead of it, the way the axle goes forwards; none without a path + glm::dvec3 PathDirection( double const Reach = 1.0 ) const; bool Init(TTrack *pTrack, TDynamicObject *NewOwner, double fDir); void Reset(); void Render(float fNr); diff --git a/world/catenary_catalog.cpp b/world/catenary_catalog.cpp index 51bf7cc5b..38912747a 100644 --- a/world/catenary_catalog.cpp +++ b/world/catenary_catalog.cpp @@ -84,6 +84,8 @@ void structure_catalog::parse( std::vector const &Lines, std::strin std::istringstream stream { head }; std::vector words; for( std::string word; stream >> word; ) { words.push_back( word ); } + // a line of white space other than spaces and tabs (\v, \f, \r) is as empty + if( words.empty() ) { continue; } auto const &keyword { words.front() }; if( keyword == "text" ) { auto const body { trimmed( line.substr( 4 ) ) }; diff --git a/world/catenary_scene.cpp b/world/catenary_scene.cpp index 5c943a69a..37b888096 100644 --- a/world/catenary_scene.cpp +++ b/world/catenary_scene.cpp @@ -29,6 +29,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/parser.h" #include +#include #include #include #include @@ -2302,50 +2303,96 @@ catenary_scene_file_layer( std::string const &File, std::size_t const Layer ) { FileLayers[ File ] = Layer; } +namespace { + +// treść pliku sieci w postaci zapisywanej na dysk: nagłówek, tekstura, wpisy w kolejności listy; usunięte pomijane. CRLF jak +// w pozostałych plikach scenerii. Count: liczba podwieszeń +std::string +file_text( scene_file const &File, std::size_t &Count ) { + std::string text; + std::istringstream header { File.header }; + for( std::string line; std::getline( header, line ); ) { text += line + "\r\n"; } + if( false == File.skin.empty() ) { text += "skin " + File.skin + "\r\n"; } + Count = 0; + for( auto const &suspension : Suspensions ) { + if( suspension.removed || suspension.file != File.name ) { continue; } + text += catenary::write_suspension( suspension.data ) + "\r\n"; + ++Count; + } + for( auto const &chain : Chains ) { + if( chain.removed || chain.file != File.name ) { continue; } + text += catenary::write_chain( chain.data ) + "\r\n"; + } + for( auto const &gantry : Gantries ) { + if( gantry.removed || gantry.file != File.name ) { continue; } + text += catenary::write_gantry( gantry.data ) + "\r\n"; + } + for( auto const &anchor : Anchors ) { + if( anchor.removed || anchor.file != File.name ) { continue; } + text += catenary::write_anchor( anchor.data ) + "\r\n"; + } + return text; +} + +// plik zapisany obok docelowego, pod nazwą tymczasową; false, gdy się nie udało (wtedy go nie ma) +bool +write_aside( std::string const &Path, std::string const &Text ) { + { + std::ofstream output { Path, std::ios::binary | std::ios::trunc }; + if( false == output.is_open() ) { return false; } + output << Text; + output.close(); + if( false == output.fail() ) { return true; } + } + std::error_code error; + std::filesystem::remove( Path, error ); + return false; +} + +} // namespace + bool catenary_scene_save( std::string &Message ) { - std::vector written; + // najpierw wszystkie pliki pod nazwami tymczasowymi, dopiero gdy wszystkie się zapisały, w miejsce dotychczasowych: + // nieudany zapis nie zostawia na dysku części plików sieci nowych, a części starych + struct pending { + scene_file *file; + std::string path; + std::size_t count; + }; + std::vector aside; + auto const drop_aside = [ &aside ]() { + std::error_code error; + for( auto const &item : aside ) { std::filesystem::remove( item.path + ".tmp", error ); } + }; for( auto &file : Files ) { // wpisy w pliku scenerii zapisuje zapis scenerii if( false == file.changed || InlineFiles.count( file.name ) != 0 ) { continue; } - // wpisy w kolejności listy; usunięte pomijane. CRLF jak w pozostałych plikach scenerii - std::string text; - std::istringstream header { file.header }; - for( std::string line; std::getline( header, line ); ) { text += line + "\r\n"; } - if( false == file.skin.empty() ) { text += "skin " + file.skin + "\r\n"; } std::size_t count { 0 }; - for( auto const &suspension : Suspensions ) { - if( suspension.removed || suspension.file != file.name ) { continue; } - text += catenary::write_suspension( suspension.data ) + "\r\n"; - ++count; - } - for( auto const &chain : Chains ) { - if( chain.removed || chain.file != file.name ) { continue; } - text += catenary::write_chain( chain.data ) + "\r\n"; - } - for( auto const &gantry : Gantries ) { - if( gantry.removed || gantry.file != file.name ) { continue; } - text += catenary::write_gantry( gantry.data ) + "\r\n"; - } - for( auto const &anchor : Anchors ) { - if( anchor.removed || anchor.file != file.name ) { continue; } - text += catenary::write_anchor( anchor.data ) + "\r\n"; - } + auto const text { file_text( file, count ) }; auto const path { Global.asCurrentSceneryPath + file.name }; - std::ofstream output { path, std::ios::binary | std::ios::trunc }; - if( false == output.is_open() ) { + if( false == write_aside( path + ".tmp", text ) ) { + drop_aside(); Message = "catenary file \"" + file.name + "\" can't be written"; return false; } - output << text; - output.close(); - if( output.fail() ) { - Message = "catenary file \"" + file.name + "\" wasn't written completely"; + aside.emplace_back( &file, path, count ); + } + std::vector written; + for( std::size_t index = 0; index < aside.size(); ++index ) { + auto const &item { aside[ index ] }; + std::error_code error; + std::filesystem::rename( item.path + ".tmp", item.path, error ); + if( error ) { + // te przed nim są już na miejscu (i zapisane), ten i dalsze zostają zmienione do następnego zapisu + Message = "catenary file \"" + item.file->name + "\" can't be written"; + aside.erase( aside.begin(), aside.begin() + static_cast( index ) ); + drop_aside(); return false; } - file.changed = false; - written.push_back( file.name + " (" + std::to_string( count ) + ")" ); + item.file->changed = false; + written.push_back( item.file->name + " (" + std::to_string( item.count ) + ")" ); } Message.clear(); for( auto const &name : written ) { Message += ( Message.empty() ? "" : ", " ) + name; } diff --git a/world/catenary_span.cpp b/world/catenary_span.cpp index d0a686c33..00b62f73d 100644 --- a/world/catenary_span.cpp +++ b/world/catenary_span.cpp @@ -32,6 +32,7 @@ struct catenary_span { std::vector hangergaps; // odstępy wieszaków dobrane do rozpiętości; puste = odcinek bez wieszaków gfx::geometrybank_handle solidbank; // osobny bank na bryły tego przęsła catenary_solid solid; // bryły do oglądania z bliska + catenary_solid chunks; // fragmenty banku zrobione dla brył, używane ponownie bool solidloaded { false }; std::vector attached; // bryła dołączona (lina kotwienia), układ scenerii std::shared_ptr own; // kopia typu z naciągiem z dopisku "tension" @@ -210,6 +211,25 @@ release( gfx::geometry_handle const &Geometry ) { GfxRenderer->Replace( empty, userdata, Geometry, GL_TRIANGLES ); } +// bryła w fragmencie banku przęsła: fragment zrobiony wcześniej dostaje ją w miejsce dawnej zawartości, nowy powstaje tylko +// za pierwszym razem. Pusta bryła zostawia fragment pusty; zwraca uchwyt do rysowania, pusty, gdy nie ma czego rysować +gfx::geometry_handle +fill_chunk( TTraction &Traction, gfx::geometry_handle &Chunk, std::vector const &Solid ) { + if( Solid.empty() ) { + release( Chunk ); + return {}; + } + auto data { vertices( Traction, Solid ) }; + gfx::userdata_array userdata; + if( Chunk == null_handle ) { + Chunk = GfxRenderer->Insert( data, userdata, Traction.m_catenaryspan->solidbank, GL_TRIANGLES ); + } + else { + GfxRenderer->Replace( data, userdata, Chunk, GL_TRIANGLES ); + } + return Chunk; +} + // wygląd metalu: [ metal: miedź, aluminium ][ przewód, osprzęt ][ stan: nowa, przejściowa, zaśniedziała ] // osprzęt sieci miedzianej jest z brązu albo mosiądzu catenary_metal Metals[ 2 ][ 2 ][ 3 ] { @@ -370,20 +390,11 @@ catenary_span_solid( TTraction &Traction, glm::dvec3 const &Camera ) { if( span.solidbank == null_handle ) { span.solidbank = GfxRenderer->Create_Bank(); } - // każde ponowne wczytanie tworzy nowe fragmenty w banku tego przęsła; poprzednie zostały opróżnione przy zwalnianiu - gfx::userdata_array userdata; - { - auto data { vertices( Traction, wires ) }; - span.solid.wires = GfxRenderer->Insert( data, userdata, span.solidbank, GL_TRIANGLES ); - } - if( false == fittings.empty() ) { - auto data { vertices( Traction, fittings ) }; - span.solid.fittings = GfxRenderer->Insert( data, userdata, span.solidbank, GL_TRIANGLES ); - } - if( false == span.attached.empty() ) { - auto data { vertices( Traction, span.attached ) }; - span.solid.rope = GfxRenderer->Insert( data, userdata, span.solidbank, GL_TRIANGLES ); - } + // ponowne wczytanie wypełnia fragmenty banku zrobione za pierwszym razem (opróżnione przy zwalnianiu), nowe powstają + // tylko za pierwszym razem; bank nie rośnie przy każdym podejściu kamery + span.solid.wires = fill_chunk( Traction, span.chunks.wires, wires ); + span.solid.fittings = fill_chunk( Traction, span.chunks.fittings, fittings ); + span.solid.rope = fill_chunk( Traction, span.chunks.rope, span.attached ); span.solidloaded = ( span.solid.wires != null_handle ); return ( span.solidloaded ? span.solid : catenary_solid() ); } diff --git a/world/deer.cpp b/world/deer.cpp new file mode 100644 index 000000000..65e1e00d3 --- /dev/null +++ b/world/deer.cpp @@ -0,0 +1,758 @@ +/* +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 "world/deer.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include "utilities/Globals.h" +#include "utilities/utilities.h" +#include "model/AnimModel.h" +#include "model/Model3d.h" +#include "scene/scene.h" +#include "scene/scenenode.h" +#include "scene/scenelayers.h" +#include "simulation/simulation.h" +#include "rendering/renderer.h" +#include "vehicle/DynObj.h" +#include "physics/vehicle.h" +#include "world/Track.h" +#include "editor/editorTerrainStreamer.hpp" +#include "scene/heightmapterrain.h" +#include "utilities/Timer.h" +#include "utilities/Logs.h" + +namespace +{ + +// the animations of the deer (textures of the vertices, shader vat with vat_random -1: the game picks the clip and the moment of every +// instance, see vat_turn()). made by jelen_anim2.py; the numbers below are the ones it bakes with +struct vat_clip +{ + std::string_view model; // models/ and the extension left out + double fps; // frames a second + double frames; // of one clip + int clips; +}; +// grazing, 12 s: the head at the grass, raised about 4.5-9.3 s +constexpr vat_clip Grazing{"animals/jelen_je", 20.0, 240.0, 1}; +// startled: from the moments k * Window of the grazing (clip k) to the alarm, in Startletime; two more frames hold the end +constexpr vat_clip Startle{"animals/jelen_zryw", 30.0, 15.0, 16}; +// the flight from the alarm: looks at the train (clip k: the head turned by Looks[k] degrees, to the left when more than 0), bounds +// away and stops in the grazing pose of the moment Grazeafter, in Flighttime; two more frames hold the end +constexpr vat_clip Flight{"animals/jelen_skok", 30.0, 168.0, 6}; +constexpr std::array Looks{50.0, 80.0, 110.0, -50.0, -80.0, -110.0}; +constexpr double Window{0.75}; +constexpr double Startletime{0.4}; +constexpr double Flighttime{5.5}; +constexpr double Grazeafter{5.6}; +// the way it covers in the flight: the speed rises from 0 to Flightspeed in Flight0-Flight1 and falls back in Flight2-Flight3 +// (smoothstep), as the animation moves its hooves +constexpr double Flightspeed{7.0}; +constexpr double Flight0{0.80}; +constexpr double Flight1{1.20}; +constexpr double Flight2{3.95}; +constexpr double Flight3{4.85}; +// the frame an instance starts from at the moment of the change, a little after the frame proper: never the end of the one before +constexpr double Startframe{0.02}; +// the ground under the way of the deer, at equal steps from its start to its end (deer_herd::Groundsamples, about 1.5 m apart) +constexpr std::size_t Groundsamples{17}; +// the ground beside the track (a platform of the terrain) is looked for up to this much above the sleepers, metres +constexpr double Groundceiling{3.0}; +// the way it runs: ground found all along it, no water. down the slope of an embankment or up the one of a cutting: the ground +// no farther than this below or above the sleepers, metres +constexpr double Waybelow{6.0}; +constexpr double Wayabove{4.0}; +// the ground of the way is looked for up to this much above the sleepers, metres (over the highest it may be) +constexpr double Wayceiling{Wayabove + 1.0}; +// no steeper than this between the samples of the ground (a wall, a cliff, a ditch with steep sides), rise to run +constexpr double Wayslope{0.7}; +// the body leans up and down the slope by the ground under its hooves, this far before and behind its middle, metres +constexpr double Halfbody{0.52}; +// at most this much, degrees +constexpr double Maxpitch{30.0}; +// and follows the slope this fast (a share of the difference a second), not jerking at the bends of the ground +constexpr double Pitchrate{8.0}; +// where there's no such ground at the place, the next deer is looked for this much farther, metres +constexpr double Retrydistance{200.0}; +// the track at the place: plain (no switch) from the train to this much past the place, metres +constexpr double Clearpast{100.0}; +// no deer this near a platform (the reach of its model added): an instance of a model with peron in its path (peronowe/...), metres +constexpr double Platformrange{100.0}; +// the platforms are looked for among the instances placed this near, metres (the longest platform model, 400 m, by its middle) +constexpr double Platformsearch{350.0}; +// nor where the ground beside the track, this far from its axis, rises this much over the sleepers (a platform of the terrain) +constexpr std::array Platformside{2.5, 4.0}; +constexpr double Platformrise{0.45}; +// the train past the deer: it came this close, and is this much farther away now, metres +constexpr double Passedclose{300.0}; +constexpr double Passedmargin{200.0}; + +double fraction(double const Value) +{ + return Value - std::floor(Value); +} + +// the integral of smoothstep((T - A) / (B - A)) from minus infinity to T +double ramp_integral(double const T, double const A, double const B) +{ + if (T <= A) + { + return 0.0; + } + if (T >= B) + { + return (B - A) * 0.5 + (T - B); + } + auto const x{(T - A) / (B - A)}; + return (B - A) * (x * x * x - 0.5 * x * x * x * x); +} + +// metres covered in the flight Time seconds after its start +double flight_way(double const Time) +{ + return Flightspeed * (ramp_integral(Time, Flight0, Flight1) - ramp_integral(Time, Flight2, Flight3)); +} + +// the height of the triangle at (X, Z), false when the point isn't in it +bool triangle_height(glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C, double const X, double const Z, double &Height) +{ + auto const d{(B.z - C.z) * (A.x - C.x) + (C.x - B.x) * (A.z - C.z)}; + if (std::abs(d) < 1e-9) + { + return false; + } + auto const a{((B.z - C.z) * (X - C.x) + (C.x - B.x) * (Z - C.z)) / d}; + auto const b{((C.z - A.z) * (X - C.x) + (A.x - C.x) * (Z - C.z)) / d}; + auto const c{1.0 - a - b}; + if ((a < 0.0) || (b < 0.0) || (c < 0.0)) + { + return false; + } + Height = a * A.y + b * B.y + c * C.y; + return true; +} + +// a shape of water: its material named so (water, woda), or with the shader of water +bool is_water(scene::shape_node const &Shape) +{ + if (GfxRenderer == nullptr) + { + return false; + } + auto const *material{GfxRenderer->Material(Shape.data().material)}; + if (material == nullptr) + { + return false; + } + auto name{material->GetName()}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return (name.find("water") != std::string::npos) || (name.find("woda") != std::string::npos) || (name.find("wody") != std::string::npos); +} + +// what's looked for under a point: its place, the highest ground found so far +struct ground_probe +{ + glm::dvec3 point{0.0}; + double ceiling{0.0}; + bool found{false}; + double height{0.0}; + bool water{false}; // the highest surface found is water + bool shape_water{false}; // of the shape looked through + + void triangle(glm::dvec3 const &A, glm::dvec3 const &B, glm::dvec3 const &C) + { + if (double y{0.0}; triangle_height(A, B, C, point.x, point.z, y) && (y <= ceiling) && ((false == found) || (y > height))) + { + found = true; + height = y; + water = shape_water; + } + } + + void geometry(gfx::vertex_array const &Vertices, gfx::index_array const &Indices, glm::dvec3 const &Origin) + { + auto const vertex{[&Vertices, &Origin](std::size_t const Index) { return Origin + glm::dvec3{Vertices[Index].position}; }}; + if (Indices.empty()) + { + for (std::size_t index = 0; index + 2 < Vertices.size(); index += 3) + { + triangle(vertex(index), vertex(index + 1), vertex(index + 2)); + } + return; + } + for (std::size_t index = 0; index + 2 < Indices.size(); index += 3) + { + triangle(vertex(Indices[index]), vertex(Indices[index + 1]), vertex(Indices[index + 2])); + } + } + + void shape(scene::shape_node const &Shape) + { + auto const &data{Shape.data()}; + if ((data.area.radius >= 0.f) && (glm::length(glm::dvec2{data.area.center.x - point.x, data.area.center.z - point.z}) > data.area.radius)) + { + return; + } + shape_water = is_water(Shape); + if (false == data.vertices.empty()) + { + for (std::size_t index = 0; index + 2 < data.vertices.size(); index += 3) + { + triangle(data.vertices[index].position, data.vertices[index + 1].position, data.vertices[index + 2].position); + } + return; + } + // uploaded, the renderer keeps the geometry relative to the origin of the shape + if ((GfxRenderer == nullptr) || ((data.geometry.bank == 0) && (data.geometry.chunk == 0))) + { + return; + } + geometry(GfxRenderer->Vertices(data.geometry), GfxRenderer->Indices(data.geometry), data.origin); + } +}; + +// the point (X, Z) within the outline (x, z) +bool inside(std::vector const &Outline, double const X, double const Z) +{ + auto result{false}; + auto const *previous{&Outline.back()}; + for (auto const ¤t : Outline) + { + if (((current.y > Z) != (previous->y > Z)) && (X < (previous->x - current.x) * (Z - current.y) / (previous->y - current.y) + current.x)) + { + result = !result; + } + previous = ¤t; + } + return result; +} + +// the heightmap terrain under the point, and its bodies of water, as the ground. the chunk there is read from its file if it isn't +// in memory yet: the deer are put far ahead of the camera, where the terrain isn't loaded for drawing +void heightmap_ground(glm::dvec3 const &Point, double const Ceiling, ground_probe &Probe) +{ + if ((false == EditorTerrain.active()) || (EditorTerrain.chunk(heightmap::chunk_at(Point.x, Point.z), true) == nullptr)) + { + return; + } + if (double y{0.0}; EditorTerrain.height_at(Point.x, Point.z, y) && (y <= Ceiling) && ((false == Probe.found) || (y > Probe.height))) + { + Probe.found = true; + Probe.height = y; + Probe.water = false; + } + for (auto const &water : EditorTerrain.manifest().water) + { + if ((water.outline.size() >= 3) && (water.level <= Ceiling) && ((false == Probe.found) || (water.level > Probe.height)) && + inside(water.outline, Point.x, Point.z)) + { + Probe.found = true; + Probe.height = water.level; + Probe.water = true; + } + } +} + +// the ground of the scenery (its shapes and the heightmap terrain) under a point +struct ground +{ + bool found{false}; // none: the ground of terrain models, or none loaded + double height{0.0}; + bool water{false}; +}; + +// the ground under the point, not higher than Ceiling +ground ground_at(glm::dvec3 const &Point, double const Ceiling) +{ + ground result; + if (simulation::Region == nullptr) + { + return result; + } + ground_probe probe; + probe.point = Point; + probe.ceiling = Ceiling; + for (auto *section : simulation::Region->sections(Point, 1.f)) + { + for (auto const &shape : section->m_shapes) + { + probe.shape(shape); + } + for (auto const &cell : section->m_cells) + { + if (glm::length(glm::dvec2{cell.m_area.center.x - Point.x, cell.m_area.center.z - Point.z}) > cell.m_area.radius) + { + continue; + } + for (auto const &shape : cell.m_shapesopaque) + { + probe.shape(shape); + } + for (auto const &shape : cell.m_shapestranslucent) + { + probe.shape(shape); + } + } + } + heightmap_ground(Point, Ceiling, probe); + result.found = probe.found; + result.height = probe.height; + result.water = probe.water; + return result; +} + +// a place on a path: the point of its axis and the way along it, level, of length 1 +struct path_place +{ + glm::dvec3 position{0.0}; + glm::dvec3 forward{0.0, 0.0, 1.0}; +}; + +// the place Distance from Track at Offset along it, going the way of Direction (1 towards its end, -1 towards its start), through the +// connected paths. false where the paths end earlier, or reach a crossing of roads or a switch +bool path_ahead(TTrack *Track, double Offset, double Direction, double Distance, path_place &Place) +{ + auto *track{Track}; + auto left{Distance}; + // as far as a train could go; a loop of paths ends it as well + for (int step = 0; (step < 10000) && (track != nullptr); ++step) + { + auto const length{track->Length()}; + auto const room{Direction > 0.0 ? length - Offset : Offset}; + if (left > room) + { + left -= room; + track = track->Connected(Direction > 0.0 ? 1 : -1, Direction); + if ((track == nullptr) || (track->eType != tt_Normal)) + { + // the end, a crossing of roads, or a switch: the way may go elsewhere by the time the train gets there + return false; + } + Offset = (Direction > 0.0 ? 0.0 : track->Length()); + continue; + } + auto const segment{track->CurrentSegment()}; + if (segment == nullptr) + { + return false; + } + auto const at{std::clamp(Offset + Direction * left, 0.0, length)}; + glm::vec3 rotation; + segment->RaPositionGet(at, Place.position, rotation); + // the way of the path from two points about the place + glm::dvec3 behind; + glm::dvec3 ahead; + segment->RaPositionGet(std::clamp(at - 0.5, 0.0, length), behind, rotation); + segment->RaPositionGet(std::clamp(at + 0.5, 0.0, length), ahead, rotation); + auto way{(ahead - behind) * Direction}; + way.y = 0.0; + if (glm::length(way) < 1e-6) + { + return false; + } + Place.forward = glm::normalize(way); + // on the sleepers, below the heads of the rails + Place.position.y -= track->rail_height(); + return true; + } + return false; +} + +// the way ahead of the train to Distance and Clearpast past it plain track (straight or curved, no switch): Place the place +bool plain_way(TTrack *Track, double const Offset, double const Direction, double const Distance, path_place &Place) +{ + if ((Track == nullptr) || (Track->eType != tt_Normal)) + { + return false; + } + path_place past; + return path_ahead(Track, Offset, Direction, Distance + Clearpast, past) && path_ahead(Track, Offset, Direction, Distance, Place); +} + +// a model of a platform or of what stands on one: peron in the name of its file or of its folder (peronowe/) +bool platform_model(TAnimModel const &Instance) +{ + auto const *model{Instance.Model()}; + if (model == nullptr) + { + return false; + } + auto name{model->NameGet()}; + std::transform(name.begin(), name.end(), name.begin(), [](unsigned char const Character) { return static_cast(std::tolower(Character)); }); + return name.find("peron") != std::string::npos; +} + +// a platform about the place: a model of one near it, or the ground beside the track raised to its height. what was found, empty for none +std::string near_platform(path_place const &Place) +{ + for (auto *section : simulation::Region->sections(Place.position, static_cast(Platformsearch))) + { + for (auto const &cell : section->m_cells) + { + if (glm::length(cell.m_area.center - Place.position) > cell.m_area.radius + Platformsearch) + { + continue; + } + // a long platform (a model of 400 m) is placed by its middle: the reach of the model counts as well + auto const nearby{[&Place](TAnimModel *Instance) { + return (Instance != nullptr) && (glm::length(Instance->location() - Place.position) < Platformrange + Instance->radius()) && + platform_model(*Instance); + }}; + for (auto const *instances : {&cell.m_instancesopaque, &cell.m_instancetranslucent}) + { + if (auto const found{std::ranges::find_if(*instances, nearby)}; found != instances->end()) + { + return std::format("platform model {}", (*found)->Model()->NameGet()); + } + } + } + } + glm::dvec3 const across{Place.forward.z, 0.0, -Place.forward.x}; + for (auto const side : {-1.0, 1.0}) + { + for (auto const distance : Platformside) + { + auto const here{ground_at(Place.position + across * (side * distance), Place.position.y + Groundceiling)}; + if (here.found && (here.height > Place.position.y + Platformrise)) + { + return std::format("platform of the terrain {:.2f} m high {:.1f} m aside", here.height - Place.position.y, side * distance); + } + } + } + return {}; +} + +// the clip of the flight which looks the nearest to Towards (from the deer to the train) for a deer looking along Heading +int look_clip(glm::dvec3 const &Heading, glm::dvec3 const &Towards) +{ + // the left of a heading h is (h.z, 0, -h.x) + auto const left{Towards.x * Heading.z - Towards.z * Heading.x}; + auto const ahead{Towards.x * Heading.x + Towards.z * Heading.z}; + auto const angle{std::atan2(left, ahead) * 180.0 / std::numbers::pi}; + auto const nearest{std::ranges::min_element(Looks, {}, [angle](double const Look) { return std::abs(Look - angle); })}; + return static_cast(std::distance(Looks.begin(), nearest)); +} + +// the yaw of an instance whose model looks along -z, to look along Heading, degrees (-180, 180] +double model_yaw(glm::dvec3 const &Heading) +{ + return std::atan2(-Heading.x, -Heading.z) * 180.0 / std::numbers::pi; +} + +// the turn about the vertical (degrees) for an instance looking along Heading, which plays clip Clip of Animation so that it's at +// frame Frame at the time Time. the whole tenths of a degree come from the heading, the fraction of the tenth tells the shader the +// clip and the moment +float vat_turn(glm::dvec3 const &Heading, vat_clip const &Animation, int const Clip, double const Frame, double const Time) +{ + auto const phase{fraction((Frame - Time * Animation.fps) / Animation.frames)}; + auto const spin{(static_cast(Clip) + 0.25 + 0.5 * phase) / static_cast(Animation.clips)}; + return static_cast((std::floor(model_yaw(Heading) * 10.0) + spin) / 10.0); +} + +// a deer put in the scenery, not a part of it. Moving: the game moves it, so it's drawn on its own +TAnimModel *make_deer(vat_clip const &Animation, glm::dvec3 const &Position, float const Turn, float const Pitch, bool const Moving) +{ + auto const range{static_cast(std::ceil(Global.deer_distance + 500.0))}; + auto const definition{std::format("node {} 0 none model 0 0 0 0 {}.t3d none endmodel", range, Animation.model)}; + auto *model{simulation::State.create_model(definition, "none", Position)}; + if (model == nullptr) + { + return nullptr; + } + // not a part of the scenery: no layer of it, not saved, not edited + scene::Layers.count(model->layer(), scene::layer_item::model, -1); + model->layer(null_handle); + model->m_dirty = false; + model->m_generated = true; + simulation::Region->erase(model); + // leaning about its side, which keeps the turn the shader reads the clip from (the side axis stays level) + model->Angles(glm::vec3{Pitch, Turn, 0.f}); + if (Moving || (Pitch != 0.f)) + { + // out of the groups of the instances of its model, which keep their places, level + model->draw_alone(); + } + simulation::Region->insert(model); + ++scene::node_state_version; + return model; +} + +// the deer moved to another place +void move_deer(TAnimModel &Model, glm::dvec3 const &Position, float const Pitch) +{ + auto angles{Model.Angles()}; + if ((glm::length(Model.location() - Position) < 1e-4) && (std::abs(angles.x - Pitch) < 1e-3f)) + { + return; + } + simulation::Region->erase(&Model); + Model.location(Position); + angles.x = Pitch; + Model.Angles(angles); + simulation::Region->insert(&Model); +} + +void remove_deer(TAnimModel *Model) +{ + if (Model != nullptr) + { + simulation::State.delete_model(Model); + ++scene::node_state_version; + } +} + +// the deer goes on with another animation, at frame Frame of clip Clip at the time Time; where the model can't be made, as it was +void change_deer(TAnimModel *&Model, glm::dvec3 const &Heading, vat_clip const &Animation, int const Clip, double const Frame, double const Time, bool const Moving) +{ + auto *model{make_deer(Animation, Model->location(), vat_turn(Heading, Animation, Clip, Frame, Time), Model->Angles().x, Moving)}; + if (model == nullptr) + { + return; + } + remove_deer(Model); + Model = model; +} + +// the way a deer would run away from Start along Heading: true where it can run over all of it (no water, no wall or cliff, down an +// embankment or up a cutting no farther than Waybelow / Wayabove), Ground then the heights of the ground at equal steps along it +// (the first one Start); Reason why not otherwise +bool run_way(glm::dvec3 const &Start, glm::dvec3 const &Heading, std::array &Ground, std::string &Reason) +{ + Ground.front() = Start.y; + auto const length{flight_way(Flighttime)}; + auto const spacing{length / static_cast(Groundsamples - 1)}; + for (std::size_t sample = 1; sample < Groundsamples; ++sample) + { + auto const point{Start + Heading * (spacing * static_cast(sample))}; + auto const here{ground_at(point, Start.y + Wayceiling)}; + if (false == here.found) + { + Reason = std::format("no ground at {:.1f} m", glm::length(point - Start)); + return false; + } + if (here.water || (here.height < Start.y - Waybelow) || (here.height > Start.y + Wayabove)) + { + Reason = std::format("{} at {:.1f} m, {:.2f} m from the sleepers", here.water ? "water" : "ground", glm::length(point - Start), here.height - Start.y); + return false; + } + if (std::abs(here.height - Ground[sample - 1]) > Wayslope * spacing) + { + Reason = std::format("a step of {:.2f} m at {:.1f} m", here.height - Ground[sample - 1], glm::length(point - Start)); + return false; + } + Ground[sample] = here.height; + } + return true; +} + +// the height of the ground Way metres along the way of a deer (Ground, Length long), the ends held beyond it +double way_height(std::array const &Ground, double const Way, double const Length) +{ + auto const step{std::clamp(Way / Length, 0.0, 1.0) * static_cast(Groundsamples - 1)}; + auto const sample{std::min(static_cast(step), Groundsamples - 2)}; + return std::lerp(Ground[sample], Ground[sample + 1], step - static_cast(sample)); +} + +} // namespace + +simulation::deer_herd simulation::Deer; + +void simulation::deer_herd::update(double const Deltatime) +{ + if (m_region != simulation::Region) + { + // another scenery: the deer went with the one they were put in + m_deer.clear(); + m_travelled = 0.0; + m_region = simulation::Region; + } + auto const *vehicle{simulation::Train != nullptr ? simulation::Train->Dynamic() : nullptr}; + if ((false == Global.deer) || (vehicle == nullptr) || (simulation::Region == nullptr)) + { + for (auto const &animal : m_deer) + { + remove_deer(animal.model); + } + m_deer.clear(); + m_travelled = 0.0; + return; + } + auto const *mover{vehicle->physics}; + m_travelled += std::abs(mover->V()) * Deltatime; + if ((Global.deer_interval > 0.0) && (m_travelled >= Global.deer_interval)) + { + m_travelled = 0.0; + if ((LocalRandom(0.0, 1.0) < Global.deer_chance) && (false == spawn(*vehicle))) + { + // no ground to run over, a switch or a platform there: soon again + m_travelled = std::max(0.0, Global.deer_interval - Retrydistance); + } + } + auto const train{vehicle->GetPosition()}; + auto const speed{std::abs(mover->V())}; + auto const horn{(mover->WarningSignal() & 7) != 0}; + auto const now{Timer::GetTime()}; + std::erase_if(m_deer, [this, &train, speed, horn, now](deer &Animal) { return tend(Animal, train, speed, horn, now); }); +} + +bool simulation::deer_herd::tend(deer &Animal, glm::dvec3 const &Train, double const Speed, bool const Horn, double const Now) const +{ + auto const distance{glm::length(Animal.model->location() - Train)}; + Animal.closest = std::min(Animal.closest, distance); + if (((Animal.closest < Passedclose) && (distance > Animal.closest + Passedmargin)) || (distance > Global.deer_distance + 1500.0)) + { + // the train is past it, or went another way + remove_deer(Animal.model); + return true; + } + switch (Animal.state) + { + case deer_state::grazing: + // the train the time to get away from it (deer.reactiontime) off, or the horn: the faster the train, the sooner + if ((Horn && (distance < Global.deer_hornrange)) || (distance < std::max(static_cast(Global.deer_reactiondistance), Speed * Global.deer_reactiontime))) + { + alarm(Animal, Train, Now); + } + break; + case deer_state::alarmed: + if (Now >= Animal.time) + { + change_deer(Animal.model, Animal.heading, Startle, Animal.clip, Startframe, Animal.time, false); + Animal.state = deer_state::startled; + } + break; + case deer_state::startled: + if (Now >= Animal.time + Startletime) + { + Animal.time += Startletime; + change_deer(Animal.model, Animal.heading, Flight, Animal.look, Startframe, Animal.time, true); + flee(Animal); + } + break; + case deer_state::fleeing: + if (run(Animal, Now)) + { + // grazing again, where it stopped, from the moment of the grazing the flight ends in + Animal.frame = Grazeafter * Grazing.fps + Startframe; + Animal.time += Flighttime; + change_deer(Animal.model, Animal.heading, Grazing, 0, Animal.frame, Animal.time, false); + Animal.state = deer_state::resting; + } + break; + default: + break; + } + return false; +} + +bool simulation::deer_herd::spawn(TDynamicObject const &Vehicle) +{ + // the end of the train the way it goes, or the cab occupied when it stands + auto const *mover{Vehicle.physics}; + auto front{mover->V() > 0.1}; + if (std::abs(mover->V()) <= 0.1) + { + front = (mover->CabOccupied() >= 0); + } + auto const &axle{front ? Vehicle.Axle0 : Vehicle.Axle1}; + auto const direction{front ? axle.GetDirection() : -axle.GetDirection()}; + path_place place; + if (false == plain_way(axle.GetTrack(), axle.GetTranslation(), direction, Global.deer_distance, place)) + { + WriteLog("Deer not put: a switch, a crossing of roads or the end of the track ahead"); + return false; + } + if (auto const platform{near_platform(place)}; false == platform.empty()) + { + WriteLog(std::format("Deer not put at {:.1f} {:.1f} {:.1f}: {}", place.position.x, place.position.y, place.position.z, platform)); + return false; + } + // across the path, a little askew, to the side with ground it can run away over (one picked at random first) + deer animal; + animal.start = place.position; + auto const askew{LocalRandom(-25.0, 25.0) * std::numbers::pi / 180.0}; + auto const first{LocalRandom(0.0, 1.0) < 0.5 ? -1.0 : 1.0}; + auto found{false}; + std::string reasons; + for (auto const side : {first, -first}) + { + glm::dvec3 const across{place.forward.z * side, 0.0, -place.forward.x * side}; + animal.heading = glm::normalize(across * std::cos(askew) + place.forward * std::sin(askew)); + std::string reason; + if (run_way(animal.start, animal.heading, animal.ground, reason)) + { + found = true; + break; + } + reasons += (reasons.empty() ? "" : "; ") + reason; + } + if (false == found) + { + WriteLog(std::format("Deer not put at {:.1f} {:.1f} {:.1f}: {}", place.position.x, place.position.y, place.position.z, reasons)); + return false; + } + // grazing from a moment of its own + animal.frame = LocalRandom(0.0, Grazing.frames); + animal.time = Timer::GetTime(); + animal.model = make_deer(Grazing, place.position, vat_turn(animal.heading, Grazing, 0, animal.frame, animal.time), 0.f, false); + if (animal.model == nullptr) + { + return false; + } + WriteLog(std::format("Deer put at {:.1f} {:.1f} {:.1f}", place.position.x, place.position.y, place.position.z)); + m_deer.emplace_back(animal); + return true; +} + +void simulation::deer_herd::alarm(deer &Animal, glm::dvec3 const &Train, double const Now) const +{ + // it starts from the moment of the grazing nearest ahead whose start it has (every Window seconds) + auto const grazed{fraction((Animal.frame + (Now - Animal.time) * Grazing.fps) / Grazing.frames) * Grazing.frames / Grazing.fps}; + auto const length{Grazing.frames / Grazing.fps}; + auto const windows{static_cast(std::lround(length / Window))}; + auto window{static_cast(std::ceil(grazed / Window - 1e-6))}; + auto wait{static_cast(window) * Window - grazed}; + window %= windows; + Animal.clip = window; + Animal.time = Now + std::max(0.0, wait); + // it looks at the train + Animal.look = look_clip(Animal.heading, Train - Animal.model->location()); + Animal.state = deer_state::alarmed; +} + +void simulation::deer_herd::flee(deer &Animal) const +{ + // the ground along its way was looked at when it was put there + Animal.state = deer_state::fleeing; + Animal.start = Animal.model->location(); + Animal.moved = Animal.time; +} + +bool simulation::deer_herd::run(deer &Animal, double const Now) const +{ + auto const elapsed{std::clamp(Now - Animal.time, 0.0, Flighttime)}; + auto const way{flight_way(elapsed)}; + auto const length{flight_way(Flighttime)}; + auto position{Animal.start + Animal.heading * way}; + position.y = way_height(Animal.ground, way, length); + // leaning with the ground under its hooves, up the slope ahead (the body faces along the heading) + auto const rise{way_height(Animal.ground, way + Halfbody, length) - way_height(Animal.ground, way - Halfbody, length)}; + auto const slope{std::clamp(std::atan2(rise, 2.0 * Halfbody) * 180.0 / std::numbers::pi, -Maxpitch, Maxpitch)}; + Animal.pitch = std::lerp(Animal.pitch, slope, std::clamp((Now - Animal.moved) * Pitchrate, 0.0, 1.0)); + Animal.moved = Now; + move_deer(*Animal.model, position, static_cast(Animal.pitch)); + return (Now - Animal.time >= Flighttime); +} diff --git a/world/deer.h b/world/deer.h new file mode 100644 index 000000000..95629702a --- /dev/null +++ b/world/deer.h @@ -0,0 +1,91 @@ +/* +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 + +#include +#include +#include + +class TAnimModel; +class TDynamicObject; +namespace scene +{ +class basic_region; +} + +// deer at the tracks (Global.deer, off unless eu07.ini turns it on): every Global.deer_interval metres the train of the player +// covers, a deer is put (with the chance Global.deer_chance) on the path the train goes along, Global.deer_distance metres ahead +// of it, grazing (the model animals/jelen_je, animated by textures). the horn of the train within Global.deer_hornrange of it, or +// the train coming closer than Global.deer_reactiontime seconds of its speed (Global.deer_reactiondistance at least), frightens it: +// it raises its head (animals/jelen_zryw), looks at the train and runs away from the tracks in bounds (animals/jelen_skok, moved by +// the game along with the hooves, over the ground, leaning up and down its slopes), and grazes again where it stopped. the game picks the clip and the moment of each of the models (shader vat, vat_random -1), so one hands over to the next +// in the very same pose. the deer go once the train is past them. they aren't parts of the scenery (not saved, not edited) +namespace simulation +{ + +class deer_herd +{ + public: + // after the trains moved, Deltatime: the time of the simulation the frame took, seconds + void update(double const Deltatime); + // deer about at the moment + std::size_t count() const + { + return m_deer.size(); + } + + private: + // the ground under the way the deer runs, at equal steps from its start to its end + static constexpr std::size_t Groundsamples{17}; + enum class deer_state + { + grazing, // till it hears the horn or the train comes close (deer.reactiontime of its speed away) + alarmed, // grazing still, till the moment of the grazing its startle starts from (time) + startled, // raises its head (since time) + fleeing, // looks at the train and runs away (since time) + resting // grazes where it stopped, for good + }; + struct deer + { + TAnimModel *model{nullptr}; + glm::dvec3 start{0.0}; // where it stood when it started to run, or stands + glm::dvec3 heading{0.0, 0.0, 1.0}; // where its head points, level, of length 1 + deer_state state{deer_state::grazing}; + double frame{0.0}; // of the grazing at the time time + double time{0.0}; // of the simulation (Timer::GetTime()), seconds; see deer_state + int clip{0}; // of the startle: the moment of the grazing it starts from + int look{0}; // the clip of the flight which looks at the train + double closest{1e9}; // the train came this close, metres + std::array ground{}; // heights of the ground along the way it runs + double pitch{0.0}; // up the slope it runs on, degrees + double moved{0.0}; // the time of the simulation it was last moved at, seconds + }; + // the train at Train going Speed (m/s), its horn sounding, at the time Now: the deer takes fright, runs, or goes (true) once the + // train is past it + bool tend(deer &Animal, glm::dvec3 const &Train, double const Speed, bool const Horn, double const Now) const; + // puts a deer on the path ahead of the train, where it's plain track (no switch) with ground beside it it can run over (slopes + // of embankments and cuttings too) and no platform near; + // false where there's none + bool spawn(TDynamicObject const &Vehicle); + // the deer took fright: when it starts, where it looks + void alarm(deer &Animal, glm::dvec3 const &Train, double const Now) const; + // the deer starts to run + void flee(deer &Animal) const; + // moves a running deer, true when it stopped + bool run(deer &Animal, double const Now) const; + + std::vector m_deer; + double m_travelled{0.0}; // by the train since the last deer, metres + scene::basic_region const *m_region{nullptr}; // of the scenery the deer were put in +}; + +extern deer_herd Deer; + +} // namespace simulation diff --git a/world/eventconditions.cpp b/world/eventconditions.cpp new file mode 100644 index 000000000..158f58dc0 --- /dev/null +++ b/world/eventconditions.cpp @@ -0,0 +1,136 @@ +/* +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 text of the event conditions: read from the scenery and written back by the editor. kept apart from +// Event.cpp so the unit tests can check that what is written reads back the same + +#include "stdafx.h" +#include "world/Event.h" +#include "utilities/Logs.h" + +#include + +bool +basic_event::is_keyword( std::string const &Token ) { + // TODO: convert to array lookup if keyword list gets longer + return Token == "endevent" + || Token == "randomdelay" + || Token == "departuredelay"; +} + +void +basic_event::event_conditions::deserialize( cParser &Input, std::string_view const Eventname ) { + // przetwarzanie warunków, wspólne dla Multiple i UpdateValues + + std::string token; + while( true == Input.getTokens() + && false == (token = Input.peek()).empty() + && false == basic_event::is_keyword(token) ) { + + if( token == "trackoccupied" ) { + flags |= flags::track_busy; + } + else if( token == "trackfree" ) { + flags |= flags::track_free; + } + else if( token == "propability" || token == "probability") { //remove propability in few years after changing old scenery scripts 01.2021 + flags |= flags::probability; + Input.getTokens(); + Input >> probability; + } + else if( token == "memcompare" ) { + Input.getTokens( 1, false ); // case sensitive + if( Input.peek() != "*" ) //"*" - nie brac command pod uwage + { // zapamiętanie łańcucha do porównania + Input >> memcompare_text; + flags |= flags::text; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac val1 pod uwage + { + Input >> memcompare_value1; + flags |= flags::value1; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac val2 pod uwage + { + Input >> memcompare_value2; + flags |= flags::value2; + } + } + else if( token == "memcompareex" ) { + memcompare_pass = comparison_pass_from_string( Input.getToken() ); + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_text_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens( 1, false ); // case sensitive + Input >> memcompare_text; + flags |= flags::text; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_value1_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens(); + Input >> memcompare_value1; + flags |= flags::value1; + } + Input.getTokens(); + if( Input.peek() != "*" ) //"*" - nie brac pod uwage + { // two tokens, operator followed by comparison value + std::string operatorstring; + Input >> operatorstring; + memcompare_value2_operator = comparison_operator_from_string( operatorstring ); + Input.getTokens(); + Input >> memcompare_value2; + flags |= flags::value2; + } + } + else { + // e.g. a name written after trackfree: the track test takes the targets of the event, never a name of its own + ErrorLog( std::format( "Bad event: \"{}\" has an unknown word \"{}\" in its condition, it's skipped", Eventname, token ) ); + } + } +} + +// sends basic content of the class in legacy (text) format to provided stream +void +basic_event::event_conditions::export_as_text( std::ostream &Output ) const { + + if( flags != 0 ) { + Output << "condition "; + if( ( flags & flags::track_busy ) != 0 ) { + Output << "trackoccupied "; + } + if( ( flags & flags::track_free ) != 0 ) { + Output << "trackfree "; + } + if( ( flags & flags::probability ) != 0 ) { + Output + << "probability " + << probability << ' '; + } + if( ( flags & ( flags::text | flags::value1 | flags::value2 ) ) != 0 ) { + // NOTE: export doesn't preserve original memcompare condition, these are all upgraded to memcompareex format for simplicity + // memcompareex then for the text and both values either * or the operator followed by the compared value, + // the order deserialize() reads them in. a legacy memcompare is the same as memcompareex all with all operators == + Output + << "memcompareex " + << to_string( memcompare_pass ) << ' ' + << ( ( flags & flags::text ) == 0 ? "*" : to_string( memcompare_text_operator ) + ' ' + memcompare_text ) << ' ' + << ( ( flags & flags::value1 ) == 0 ? "*" : to_string( memcompare_value1_operator ) + ' ' + std::to_string( memcompare_value1 ) ) << ' ' + << ( ( flags & flags::value2 ) == 0 ? "*" : to_string( memcompare_value2_operator ) + ' ' + std::to_string( memcompare_value2 ) ) << ' '; + } + } +} diff --git a/world/mtable.cpp b/world/mtable.cpp index 0ac08bc20..bef0e20d8 100644 --- a/world/mtable.cpp +++ b/world/mtable.cpp @@ -9,10 +9,12 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "world/mtable.h" +#include "world/timetablestart.h" #include "utilities/Globals.h" #include "simulation/simulationtime.h" #include "utilities/dictionary.h" #include "utilities/utilities.h" +#include "world/stationnames.h" double TTrainParameters::CheckTrainLatency() const { @@ -109,6 +111,16 @@ sound_source TTrainParameters::current_stop_sound() const { return { sound_placement::engine }; } +timetable::service_flags const &TTrainParameters::stop_flags() const { + + return TimeTable[ timetable::stop_flags_entry( StationIndex, StationCount ) ].flags; +} + +timetable::service_flags const &TTrainParameters::run_flags() const { + + return TimeTable[ timetable::run_flags_entry( StationIndex, StationCount ) ].flags; +} + bool TTrainParameters::UpdateMTable( scenario_time const &Time, std::string const &NewName ) { return UpdateMTable( Time.data().wHour, Time.data().wMinute + Time.data().wSecond * 0.0167, NewName ); @@ -150,12 +162,14 @@ bool TTrainParameters::UpdateMTable(double hh, double mm, std::string_view NewNa bool Mtable::TTrainParameters::RewindTimeTable(std::string actualStationName) { - if( actualStationName.compare( 0, 19, "PassengerStopPoint:" ) == 0 ) { - actualStationName = ToLower( actualStationName.substr( 19 ) ); - } + // the text of a W4 or a plain name, spelled the way its file has it: with or without the polish letters, in any case + auto const isstoppoint { actualStationName.starts_with( timetable::stop_point_prefix ) }; for( auto i = 1; i <= StationCount; ++i ) { // przechodzimy po całej tabelce i sprawdzamy nazwy stacji (bez pierwszej) - if (ToLower(TimeTable[i].StationName) == actualStationName) { + auto const &stationname { TimeTable[i].StationName }; + if( isstoppoint ? + timetable::stop_point_is_for( actualStationName, stationname ) : + timetable::same_station( actualStationName, stationname ) ) { // nazwa stacji zgodna więc ustawiamy na poprzednią, żeby w następnym kroku poprawnie obsłużyć StationIndex = i; NextStationName = TimeTable[ i ].StationName; @@ -208,6 +222,29 @@ std::string TTrainParameters::ShowRelation() const return ""; } +std::string TTrainParameters::relation_caption() const +{ + if (Relation1 != "" && Relation2 != "") + return timetable::station_caption( RelationLabel1 ) + " - " + timetable::station_caption( RelationLabel2 ); + else + return ""; +} + +std::string TTrainParameters::station_caption( std::string const &Name ) const +{ + // the station the train makes for first, then the rest of the table + if( StationIndex >= 0 && StationIndex <= StationCount && TimeTable[ StationIndex ].StationName == Name ) { + return timetable::station_caption( TimeTable[ StationIndex ].StationLabel ); + } + for( auto i = 1; i <= StationCount; ++i ) { + if( TimeTable[ i ].StationName == Name ) { + return timetable::station_caption( TimeTable[ i ].StationLabel ); + } + } + // not a station of the timetable + return timetable::station_caption( Name ); +} + TTrainParameters::TTrainParameters(std::string const &NewTrainName) /*wstępne ustawienie parametrów rozkładu jazdy*/ { @@ -226,6 +263,8 @@ void TTrainParameters::NewName(std::string_view NewTrainName) Direction = 1; Relation1 = ""; Relation2 = ""; + RelationLabel1 = ""; + RelationLabel2 = ""; for (auto &tableline : TimeTable) { tableline = TMTableLine(); @@ -257,21 +296,16 @@ void TTrainParameters::UpdateVelocity(int /*Stationcount*/, double vActual) bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double vmax) // wczytanie pliku-tabeli z rozkładem przesuniętym o (fPlus); (vMax) nie ma znaczenia { - std::string lines; std::string s; std::ifstream fin; - bool EndTable; - double vActual; int conversionerror = 0; - EndTable = false; if (TrainName == "") { // jeśli pusty rozkład // UpdateVelocity(StationCount,vMax); //ograniczenie do prędkości startowej } else { - vActual = -1; s = scnpath + TrainName + ".txt"; replace_slashes(s); // Ra 2014-09: ustalić zasady wyznaczenia pierwotnego pliku przy przesuniętych rozkładach @@ -302,288 +336,28 @@ bool TTrainParameters::LoadTTfile(std::string const &scnpath, int iPlus, double } else { /*analiza rozkładu jazdy*/ - conversionerror = 0; - while (fin.good() && !(conversionerror != 0 || EndTable)) - { - std::getline(fin, lines); /*wczytanie linii*/ - if (contains( lines, "___________________") ) /*linia pozioma górna*/ - { - fin >> s; - if (s == "[") /*lewy pion*/ - { - fin >> s; - if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ - do - { - fin >> s; - } while (!(s == "|") || fin.eof()); /*środkowy pion*/ - } - } - else if (lines == "") - { - fin.close(); - break; - } - fin >> s; /*nazwa pociągu*/ - // if LowerCase(s)<>ExtractFileName(TrainName) then {musi być taka sama, jak nazwa - // pliku} - // ConversionError:=-7 {błąd niezgodności} - TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) - while (fin >> s || fin.bad()) - { - if (contains( s,"_______|") ) - { - break; - } - if (s == "Kategoria") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainCategory; - continue; - } - if (s == "Nazwa") - { - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> TrainLabel; - continue; - } - } // while (!(s == "Seria")); - // else - { /*czytaj naglowek*/ - while (fin >> s || !fin.bad()) - { - if (s == "[") - break; - } // while (!() || (fin.eof())); /*pierwsza linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s != "|") - break; - } // while (!(() || fin.eof())); - if( s != "|" ) { - Relation1 = s; - win1250_to_ascii( Relation1 ); - } - else - conversionerror = -5; - while (fin >> s || !fin.bad()) - { - if (s == "Relacja") - break; - } // while ( - // !( || (fin.eof()))); /*druga linia z relacją*/ - while (fin >> s || !fin.bad()) - { - if (s == "|") - break; - } // while (!( || (fin.eof()))); - fin >> Relation2; - win1250_to_ascii( Relation2 ); - while (fin >> s || !fin.bad()) - { - if (s == "Wymagany") - break; - } // while (!(); - while (fin >> s || !fin.bad()) - { - if (s == "|" || s == "\n") - break; - } // while (!()); - fin >> s; - s = s.substr(0, s.find("%")); - BrakeRatio = atof(s.c_str()); - while (fin >> s || fin.bad()) - { - if (s == "Seria") - break; - } // while (!(s == "Seria")); - do - { - fin >> s; - } while (!(s == "|" || fin.bad())); - fin >> LocSeries; - fin >> LocLoad; // = s2rE(ReadWord(fin)); - do - { - fin >> s; - } while (!(contains( s,"[______________" ) || fin.bad())); - auto activeradiochannel{ -1 }; - while (!fin.bad() && !EndTable) - { - ++StationCount; - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - TMTableLine *record = &TimeTable[StationCount]; - { - if (s == "[") - fin >> s; - else - conversionerror = -4; - if (false == contains( s,"|") ) - { - record->km = static_cast(atof(s.c_str())); - fin >> s; - } - if (contains( s,"|_____|")) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains( s,"|")) - fin >> s; - fin >> record->StationName; - // get rid of non-ascii chars. TODO: run correct version based on locale - win1250_to_ascii( record->StationName ); - do - { - fin >> s; - } while (!(s == "1" || s == "2" || fin.bad())); - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Ah = atoi( s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu - record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu - } - else - { - record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji - record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(s == "[" || fin.bad())); - fin >> s; - if (false == contains(s,"|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (s.find("|_____|") != - std::string::npos) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains(s,"|")) - vActual = atof(s.c_str()); - } - while (false == contains(s,"|")) - fin >> s; - // stationware. added fix for empty entry - fin >> s; - while( false == ( s == "1" - || s == "2" - || fin.bad() ) ) { - record->StationWare += s; - fin >> s; - } - // cache relevant station data - record->is_maintenance = contains(s, "pt"); - { - auto const stationware { Split( record->StationWare, ',' ) }; - for( auto const &entry : stationware ) { - if( entry.front() != 'R' ) { - continue; - } - auto const [entrytype, entrynumber]{ split_string_and_number( entry ) }; - if( entrytype == "R" - && entrynumber <= 10 ) { - auto const radiochannel { entrynumber }; - if( record->radio_channel == -1 - || radiochannel != activeradiochannel ) { - // if the station has more than one radiochannel listed, - // it generally means we should switch to the one we weren't using so far - // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system - record->radio_channel = radiochannel; - } - } - } - if( record->radio_channel != -1 ) { - activeradiochannel = record->radio_channel; - } - } - record->TrackNo = atoi(s.c_str()); - fin >> s; - if (s != "|") - { - if (contains( s, hrsd) ) - { - record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu - record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu - } - else - { - record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji - record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane - } - } - else - { - record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) - record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu - } - do - { - fin >> s; - } while (!(s != "|" || fin.bad())); - if (s != "]") - record->tm = static_cast(atof(s.c_str())); - do - { - fin >> s; - } while (!(contains( s, "[" ) || fin.bad())); - if (false == contains( s, "_|_")) - fin >> s; - if (false == contains( s, "|")) - { - /*tu s moze byc miejscem zmiany predkosci szlakowej*/ - fin >> s; - } - if (contains( s, "|_____|") ) /*zmiana predkosci szlakowej*/ - UpdateVelocity(StationCount, vActual); - else - { - fin >> s; - if (false == contains( s, "|")) - vActual = atof(s.c_str()); - } - while (false == contains( s, "|" ) ) - fin >> s; - while (false == contains(s, "]")) - fin >> s; - if (contains( s,"_|_") ) - EndTable = true; - } /*timetableline*/ - } - } - } /*while eof*/ + timetable_data data; + data.TrainName = TrainName; + conversionerror = read_timetable( fin, data ); fin.close(); + TrainName = data.TrainName; + TrainCategory = data.TrainCategory; + TrainLabel = data.TrainLabel; + Relation1 = data.Relation1; + Relation2 = data.Relation2; + RelationLabel1 = data.RelationLabel1; + RelationLabel2 = data.RelationLabel2; + BrakeRatio = data.BrakeRatio; + LocSeries = data.LocSeries; + LocLoad = data.LocLoad; + StationCount = data.StationCount; + for( auto i = 0; i <= MaxTTableSize; ++i ) { + static_cast( TimeTable[ i ] ) = data.TimeTable[ i ]; + } } } - // jeśli nazwa pierwszego zgodna z relacją - if (conversionerror == 0 && TimeTable[1].StationName == Relation1 && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu + // jeśli nazwa pierwszego zgodna z relacją (bez względu na wielkość liter) + if (conversionerror == 0 && timetable::starts_at( TimeTable[1].StationName, Relation1 ) && TimeTable[1].Ah < 0) // a nie podany czas przyjazdu { // to mamy zatrzymanie na pierwszym, a nie przelot TimeTable[1].Ah = TimeTable[1].Dh; TimeTable[1].Am = TimeTable[1].Dm; diff --git a/world/mtable.h b/world/mtable.h index 841fea815..be8b2c90d 100644 --- a/world/mtable.h +++ b/world/mtable.h @@ -13,32 +13,19 @@ http://mozilla.org/MPL/2.0/. #include "utilities/Classes.h" #include "audio/sound.h" +#include "world/timetablereader.h" namespace Mtable { -static int const MaxTTableSize = 100; // można by to robić dynamicznie static char const *const hrsd = "."; // Ra: pozycja zerowa rozkładu chyba nie ma sensu // Ra: numeracja przystanków jest 1..StationCount -struct TMTableLine +// a station of the timetable as the file gives it (TMTableEntry, world/timetablereader.h), with its name announcement +struct TMTableLine : TMTableEntry { - float km{ 0.f }; // kilometraz linii - float vmax{ -1.f }; // predkosc rozkladowa przed przystankiem - // StationName:string[32]; //nazwa stacji ('_' zamiast spacji) - // StationWare:string[32]; //typ i wyposazenie stacji, oddz. przecinkami} - std::string StationName{ "nowhere" }; // nazwa stacji ('_' zamiast spacji) - std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami} - int TrackNo{ 1 }; // ilosc torow szlakowych - int Ah{ -1 }; - float Am{ -1.f }; // godz. i min. przyjazdu, -1 gdy bez postoju - int Dh{ -1 }; - float Dm{ -1.f }; // godz. i min. odjazdu - float tm{ 0.f }; // czas jazdy do tej stacji w min. (z kolumny) - bool is_maintenance{ false }; - int radio_channel{ -1 }; sound_source name_sound{ sound_placement::engine }; }; @@ -55,10 +42,13 @@ class TTrainParameters double TTVmax; std::string Relation1; std::string Relation2; // nazwy stacji danego odcinka + // the two as the timetable spells them, with their letters (see TMTableEntry::StationLabel) + std::string RelationLabel1; + std::string RelationLabel2; double BrakeRatio; std::string LocSeries; // seria (typ) pojazdu double LocLoad; - TMTable TimeTable; + TMTable TimeTable; // TimeTable[0].flags holds the service flags of the whole train int StationCount; // ilość przystanków (0-techniczny) int StationIndex; // numer najbliższego (aktualnego) przystanku int StationStart; // numer pierwszej stacji pokazywanej na podglądzie rozkładu @@ -68,6 +58,9 @@ class TTrainParameters double CheckTrainLatency() const; /*todo: str hh:mm to int i z powrotem*/ std::string ShowRelation() const; + // the relation and the name of given station for the player: utf-8, with the letters the timetable has + std::string relation_caption() const; + std::string station_caption( std::string const &Name ) const; double WatchMTable(double DistCounter) const; std::string NextStop() const; // wpis rozkladu Offset pozycji za StationIndex (Offset>=1); poza zakresem 1..StationCount @@ -95,6 +88,10 @@ class TTrainParameters int radio_channel() const; // returns: sound file associated with current station, or -1 sound_source current_stop_sound() const; + // service flags (eu07/maszyna#95) which hold at the stop the train makes for or stands at + timetable::service_flags const &stop_flags() const; + // service flags which hold on the way, since the stop the train left last + timetable::service_flags const &run_flags() const; private: void load_sounds(); }; diff --git a/world/station.cpp b/world/station.cpp index 90b443e86..c5572133e 100644 --- a/world/station.cpp +++ b/world/station.cpp @@ -13,6 +13,7 @@ http://mozilla.org/MPL/2.0/. #include "utilities/utilities.h" #include "vehicle/DynObj.h" #include "world/mtable.h" +#include "physics/vehicle.h" namespace simulation { @@ -42,13 +43,13 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch auto *vehicle { First }; while( vehicle != nullptr ) { - auto ¶meters { *vehicle->MoverParameters }; + auto ¶meters { *vehicle->physics }; if( parameters.Doors.range == 0.f ) { goto next; } if( parameters.LoadType.name.empty() ) { // (try to) set the cargo type for empty cars - parameters.LoadAmount = 0.f; // safety measure against edge cases + parameters.SetLoadAmount(0.f); // safety measure against edge cases parameters.AssignLoad( "passengers" ); parameters.ComputeMass(); } @@ -57,18 +58,18 @@ basic_station::update_load( TDynamicObject *First, Mtable::TTrainParameters &Sch // NOTE: for the time being we're doing simple, random load change calculation // TODO: exchange driven by station parameters and time of the day auto unloadcount = static_cast( - TestFlag( parameters.DamageFlag, dtrain_out ) ? parameters.LoadAmount : - laststop ? parameters.LoadAmount : + parameters.DamageFlag.HasAll(VehicleDamage::derailed) ? parameters.LoadAmount() : + laststop ? parameters.LoadAmount() : firststop ? 0 : maintenancestop ? 0 : std::min( - parameters.LoadAmount, - static_cast(Random( parameters.MaxLoad * 0.15f * stationsizemodifier )) ) ); + parameters.LoadAmount(), + static_cast(Random( parameters.MaxLoad() * 0.15f * stationsizemodifier )) ) ); auto loadcount = static_cast( - TestFlag( parameters.DamageFlag, dtrain_out ) ? 0 : + parameters.DamageFlag.HasAll(VehicleDamage::derailed) ? 0 : laststop ? 0 : maintenancestop ? 0 : - Random( parameters.MaxLoad * 0.15f * stationsizemodifier ) ); + Random( parameters.MaxLoad() * 0.15f * stationsizemodifier ) ); if( true == firststop ) { // larger group at the initial station loadcount *= 2; diff --git a/world/stationnames.cpp b/world/stationnames.cpp new file mode 100644 index 000000000..62948d7c8 --- /dev/null +++ b/world/stationnames.cpp @@ -0,0 +1,43 @@ +/* +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 "world/stationnames.h" + +#include "utilities/utilities.h" + +#include + +namespace timetable { + +std::string station_ascii(std::string Name) { + win1250_to_ascii(Name); + return Name; +} + +std::string station_key(std::string_view const Name) { + // the same steps the comparison of a W4 with the timetable always took: the marks off, then the case + auto key{ToLower(station_ascii(std::string{Name}))}; + std::ranges::replace(key, ' ', '_'); + return key; +} + +bool same_station(std::string_view const Left, std::string_view const Right) { + return station_key(Left) == station_key(Right); +} + +bool stop_point_is_for(std::string_view const Text, std::string_view const Station) { + return Text.starts_with(stop_point_prefix) && same_station(Text.substr(stop_point_prefix.size()), Station); +} + +std::string station_caption(std::string const &Name) { + return data_name_to_utf8(Name, true); +} + +} // namespace timetable diff --git a/world/stationnames.h b/world/stationnames.h new file mode 100644 index 000000000..0d171363f --- /dev/null +++ b/world/stationnames.h @@ -0,0 +1,40 @@ +/* +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 + +#include +#include + +// the names of the stations (MaSzyna-EU07/maszyna#94): a timetable and the W4 stop points of a scenery name a station +// each in its own file, in windows-1250, and they don't have to spell it the same way (with or without the polish +// letters, in another case). a name has three forms here: +// - as written, with its letters: what the files hold and what the player is shown (station_caption()) +// - the ascii one, the polish letters without their marks: what the timetable always kept as the name of a station, +// what the scenery events, the scripts and the file names of the announcements and destination boards go by +// (station_ascii()) +// - the key two spellings are the same station by (station_key(), same_station()) +namespace timetable { + +// what a W4 text starts with: "PassengerStopPoint:". in the scenery a "#" follows; the event cuts it as it's read, a memory cell keeps the whole of its text +inline constexpr std::string_view stop_point_prefix{"PassengerStopPoint:"}; + +// the name without the marks of the polish letters of windows-1250, the rest as written +std::string station_ascii(std::string Name); +// the key of a name: the ascii form in lower case, spaces as underscores +std::string station_key(std::string_view Name); +// whether the two names are spellings of the same station +bool same_station(std::string_view Left, std::string_view Right); +// whether the W4 text, as an event or a memory cell holds it, is for the station of given name, in any spelling of the two +bool stop_point_is_for(std::string_view Text, std::string_view Station); +// the name for the player: utf-8, with its letters, underscores as spaces +std::string station_caption(std::string const &Name); + +} // namespace timetable diff --git a/world/timetableflags.cpp b/world/timetableflags.cpp new file mode 100644 index 000000000..5c7d6ae9e --- /dev/null +++ b/world/timetableflags.cpp @@ -0,0 +1,103 @@ +/* +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 "world/timetableflags.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" + +namespace timetable { + +namespace { + +void apply_one(tristate &Flag, tristate const Other) { + if (Other != tristate::unset) { + Flag = Other; + } +} + +tristate *flag_named(std::string_view const Key, service_flags &Flags) { + if (Key == "drzwi_centralne") { + return &Flags.central_doors; + } + if (Key == "stopien") { + return &Flags.doorstep; + } + if (Key == "kierownik") { + return &Flags.conductor; + } + if (Key == "proba_hamulca") { + return &Flags.brake_test; + } + return nullptr; +} + +} // namespace + +void service_flags::apply(service_flags const &Other) { + apply_one(central_doors, Other.central_doors); + apply_one(doorstep, Other.doorstep); + apply_one(conductor, Other.conductor); + apply_one(brake_test, Other.brake_test); +} + +bool read_flag(std::string_view const Entry, service_flags &Flags) { + auto const separator{Entry.find('=')}; + if (separator == std::string_view::npos) { + return false; + } + auto const key{ToLower(std::string{Entry.substr(0, separator)})}; + auto *flag{flag_named(key, Flags)}; + if (flag == nullptr) { + return false; + } + auto const value{ToLower(std::string{Entry.substr(separator + 1)})}; + if (value == "tak" || value == "1") { + *flag = tristate::yes; + } + else if (value == "nie" || value == "0") { + *flag = tristate::no; + } + else { + ErrorLog("Bad timetable: unknown value of " + key + " in \"" + std::string{Entry} + "\", expected tak or nie"); + } + return true; +} + +std::string extract_flags(std::string const &Ware, service_flags &Flags) { + if (false == contains(Ware, '=')) { + // no flags, the list as it was + return Ware; + } + std::string rest; + for (auto const &entry : Split(Ware, ',')) { + if (read_flag(entry, Flags)) { + continue; + } + if (contains(entry, '=')) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in station ware \"" + Ware + "\""); + } + if (false == rest.empty()) { + rest += ','; + } + rest += entry; + } + return rest; +} + +int stop_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex, 0, std::max(StationCount, 0)); +} + +int run_flags_entry(int const StationIndex, int const StationCount) { + return std::clamp(StationIndex - 1, 0, std::max(StationCount, 0)); +} + +} // namespace timetable diff --git a/world/timetableflags.h b/world/timetableflags.h new file mode 100644 index 000000000..8c463d3f3 --- /dev/null +++ b/world/timetableflags.h @@ -0,0 +1,59 @@ +/* +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 + +#include +#include +#include + +// the way a train is served, set by its timetable for the AI driver (eu07/maszyna#95): trams and underground trains +// open all the doors from the cab, have no doorstep, no conductor, no running brake test. each flag the timetable +// leaves out keeps the behaviour of the vehicles, as before the flags. +// +// the whole train: a row of the first box of the header +// [ Flagi AI | kierownik=nie,proba_hamulca=nie ] +// from a station on: entries of its station ware (the second line of the station, with R2, ph, @...) +// [ | | R2,ph,drzwi_centralne=tak,stopien=nie 1 12.47 | ] +// a station's entry holds from that station on, until another station changes it +namespace timetable { + +enum class tristate : std::uint8_t { + unset, // left to the vehicles, as before the flags + yes, + no +}; + +struct service_flags { + tristate central_doors{tristate::unset}; // drzwi_centralne: the driver opens all the doors, of mixed control too + tristate doorstep{tristate::unset}; // stopien: the doorsteps on (tak) or off (nie) before the doors open + tristate conductor{tristate::unset}; // kierownik: no conductor (nie), no departure signal, no door kept open for him + tristate brake_test{tristate::unset}; // proba_hamulca: no running brake test (nie) + + bool operator==(service_flags const &) const = default; + bool empty() const { return *this == service_flags{}; } + // the flags Other sets explicitly override these + void apply(service_flags const &Other); +}; + +// reads one entry, key=value (tak/nie, 1/0), into Flags. returns false for an entry which isn't a flag, so the caller +// keeps it; a flag with a value it doesn't know is reported to the log and taken as handled +bool read_flag(std::string_view Entry, service_flags &Flags); + +// reads the flags out of a station ware list (comma separated entries) into Flags. returns the list without them: the +// list as it was when it had none +std::string extract_flags(std::string const &Ware, service_flags &Flags); + +// the timetable entry whose flags hold at the stop the train makes for or stands at: the current one (StationIndex), +// within 0 (the header's flags) and the last station +int stop_flags_entry(int StationIndex, int StationCount); +// the entry whose flags hold on the way: the station the train left last, 0 (the header's flags) before the first one +int run_flags_entry(int StationIndex, int StationCount); + +} // namespace timetable diff --git a/world/timetablereader.cpp b/world/timetablereader.cpp new file mode 100644 index 000000000..331680f54 --- /dev/null +++ b/world/timetablereader.cpp @@ -0,0 +1,329 @@ +/* +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 "world/timetablereader.h" + +#include "utilities/Logs.h" +#include "utilities/utilities.h" +#include "world/stationnames.h" + +namespace Mtable { + +namespace { + +char const *const hrsd = "."; + +// the rest of the row "Flagi" of the header after its label: flag entries up to the closing bracket. returns true when +// a row with no closing bracket ran into the line under the box +bool read_header_flags(std::istream &fin, timetable_data &Data) { + std::string s; + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + while (fin >> s) { + if (s.starts_with('[')) { + // the next row, or the line under the box + ErrorLog("Bad timetable: row \"Flagi\" of " + Data.TrainName + " without the closing bracket"); + return contains(s, "_______|"); + } + auto const closing{s.ends_with(']')}; + for (auto const &entry : Split(closing ? std::string_view{s}.substr(0, s.size() - 1) : std::string_view{s}, ',')) { + if (false == entry.empty() && false == timetable::read_flag(entry, Data.Flags)) { + ErrorLog("Bad timetable: unknown flag \"" + entry + "\" in row \"Flagi\" of " + Data.TrainName); + } + } + if (closing) { + break; + } + } + return false; +} + +} // namespace + +// the reader as TTrainParameters::LoadTTfile had it, but for: the row "Flagi" of the header and the flags of the +// station ware; the loops end with the end of the file, where they used to spin forever (on a truncated file, or one +// with a number where the reader expects it which isn't one). a file the old reader read gets read the same +int read_timetable(std::istream &fin, timetable_data &Data) { + std::string lines; + std::string s; + bool EndTable{false}; + double vActual{-1}; + int conversionerror{0}; + auto &TimeTable{Data.TimeTable}; + auto &StationCount{Data.StationCount}; + // the table is read from its start, whatever Data held before + StationCount = 0; + TimeTable.fill(TMTableEntry{}); + // zapisywanie prędkości maksymalnej do wcześniejszych odcinków + auto const UpdateVelocity{[&TimeTable, &StationCount](double const Velocity) { + int i = StationCount; + while (i >= 0 && TimeTable[i].vmax == -1) { + TimeTable[i].vmax = static_cast(Velocity); // prędkość dojazdu do przystanku i + --i; // ewentualnie do poprzedniego też + } + }}; + + while (fin.good() && !(conversionerror != 0 || EndTable)) { + std::getline(fin, lines); /*wczytanie linii*/ + if (contains(lines, "___________________")) /*linia pozioma górna*/ + { + fin >> s; + if (s == "[") /*lewy pion*/ + { + fin >> s; + if (s == "Rodzaj") /*"Rodzaj i numer pociagu"*/ + do { + fin >> s; + } while (!(s == "|" || fin.fail())); /*środkowy pion*/ + } + } + else if (lines == "") { + break; + } + fin >> s; /*nazwa pociągu*/ + Data.TrainName = s; // nadanie nazwy z pliku TXT (bez ścieżki do pliku) + while (fin >> s) { + if (contains(s, "_______|")) { + break; + } + if (s == "Kategoria") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainCategory; + continue; + } + if (s == "Nazwa") { + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.TrainLabel; + continue; + } + if (s == "Flagi") { + // service flags of the whole train (eu07/maszyna#95) + if (read_header_flags(fin, Data)) { + break; + } + continue; + } + } + { /*czytaj naglowek*/ + while (fin >> s) { + if (s == "[") + break; + } /*pierwsza linia z relacją*/ + while (fin >> s) { + if (s != "|") + break; + } + if (s != "|") { + // the name is kept as written, for showing; the ascii form is what the rest of the simulator goes by + Data.RelationLabel1 = s; + Data.Relation1 = timetable::station_ascii(s); + } + else + conversionerror = -5; + while (fin >> s) { + if (s == "Relacja") + break; + } /*druga linia z relacją*/ + while (fin >> s) { + if (s == "|") + break; + } + if (fin >> Data.RelationLabel2) { + Data.Relation2 = timetable::station_ascii(Data.RelationLabel2); + } + while (fin >> s) { + if (s == "Wymagany") + break; + } + while (fin >> s) { + if (s == "|" || s == "\n") + break; + } + fin >> s; + s = s.substr(0, s.find("%")); + Data.BrakeRatio = atof(s.c_str()); + while (fin >> s) { + if (s == "Seria") + break; + } + do { + fin >> s; + } while (!(s == "|" || fin.fail())); + fin >> Data.LocSeries; + fin >> Data.LocLoad; // = s2rE(ReadWord(fin)); + do { + fin >> s; + } while (!(contains(s, "[______________") || fin.fail())); + // the header's flags hold from the start, entry 0 keeps them for the stations to inherit + TimeTable[0].flags = Data.Flags; + auto activeradiochannel{-1}; + while (!fin.fail() && !EndTable) { + // both bounds, so TimeTable[StationCount] and TimeTable[StationCount - 1] below stay in the table + if (StationCount < 0 || StationCount >= MaxTTableSize) { + conversionerror = timetable_too_long; + break; + } + ++StationCount; + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + TMTableEntry *record = &TimeTable[StationCount]; + { + if (s == "[") + fin >> s; + else + conversionerror = -4; + if (false == contains(s, "|")) { + record->km = static_cast(atof(s.c_str())); + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + // the name is kept as written, for showing; the W4 stop points, the announcement files, the scenery + // events and the scripts go by its ascii form, as they always did + if (fin >> record->StationLabel) { + record->StationName = timetable::station_ascii(record->StationLabel); + } + do { + fin >> s; + } while (!(s == "1" || s == "2" || fin.fail())); + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Ah = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina przyjazdu + record->Am = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta przyjazdu + } + else { + record->Ah = TimeTable[StationCount - 1].Ah; // godzina z poprzedniej pozycji + record->Am = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(s == "[" || fin.fail())); + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (s.find("|_____|") != std::string::npos) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + // stationware. added fix for empty entry + fin >> s; + while (false == (s == "1" || s == "2" || fin.fail())) { + record->StationWare += s; + fin >> s; + } + // cache relevant station data + record->is_maintenance = contains(s, "pt"); + // service flags (eu07/maszyna#95): the ones of the station before, changed by the ones given here + record->flags = TimeTable[StationCount - 1].flags; + record->StationWare = timetable::extract_flags(record->StationWare, record->flags); + { + auto const stationware{Split(record->StationWare, ',')}; + for (auto const &entry : stationware) { + if (entry.front() != 'R') { + continue; + } + auto const [entrytype, entrynumber]{split_string_and_number(entry)}; + if (entrytype == "R" && entrynumber <= 10) { + auto const radiochannel{entrynumber}; + if (record->radio_channel == -1 || radiochannel != activeradiochannel) { + // if the station has more than one radiochannel listed, + // it generally means we should switch to the one we weren't using so far + // TODO: reverse this behaviour (keep the channel used so far) once W28 signs are included in the system + record->radio_channel = radiochannel; + } + } + } + if (record->radio_channel != -1) { + activeradiochannel = record->radio_channel; + } + } + record->TrackNo = atoi(s.c_str()); + fin >> s; + if (s != "|") { + if (contains(s, hrsd)) { + record->Dh = atoi(s.substr(0, s.find(hrsd)).c_str()); // godzina odjazdu + record->Dm = static_cast(atof(s.substr(s.find(hrsd) + 1, s.length()).c_str())); // minuta odjazdu + } + else { + record->Dh = TimeTable[StationCount - 1].Dh; // godzina z poprzedniej pozycji + record->Dm = static_cast(atof(s.c_str())); // bo tylko minuty podane + } + } + else { + record->Dh = record->Ah; // odjazd o tej samej, co przyjazd (dla ostatniego też) + record->Dm = record->Am; // bo są używane do wyliczenia opóźnienia po dojechaniu + } + do { + fin >> s; + } while (!(s != "|" || fin.fail())); + if (s != "]") + record->tm = static_cast(atof(s.c_str())); + do { + fin >> s; + } while (!(contains(s, "[") || fin.fail())); + if (false == contains(s, "_|_")) + fin >> s; + if (false == contains(s, "|")) { + /*tu s moze byc miejscem zmiany predkosci szlakowej*/ + fin >> s; + } + if (contains(s, "|_____|")) /*zmiana predkosci szlakowej*/ + UpdateVelocity(vActual); + else { + fin >> s; + if (false == contains(s, "|")) + vActual = atof(s.c_str()); + } + while (false == contains(s, "|") && false == fin.fail()) + fin >> s; + while (false == contains(s, "]") && false == fin.fail()) + fin >> s; + if (contains(s, "_|_")) + EndTable = true; + } /*timetableline*/ + } + if (false == EndTable && conversionerror == 0) { + // the old reader went on reading past the end of the file here, forever + conversionerror = timetable_truncated; + } + } + } /*while eof*/ + return conversionerror; +} + +} // namespace Mtable diff --git a/world/timetablereader.h b/world/timetablereader.h new file mode 100644 index 000000000..8c60d3361 --- /dev/null +++ b/world/timetablereader.h @@ -0,0 +1,73 @@ +/* +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 + +#include +#include +#include + +#include "world/timetableflags.h" + +// the reader of the timetable files (.txt next to the scenery), without the parts of the engine the timetable +// of a running train needs (sounds, scenario time), so it can be tested on its own +namespace Mtable { + +static int const MaxTTableSize = 100; // można by to robić dynamicznie + +// one station of a timetable, as the file gives it +struct TMTableEntry { + float km{0.f}; // kilometraz linii + float vmax{-1.f}; // predkosc rozkladowa przed przystankiem + // nazwa stacji ('_' zamiast spacji), bez ogonków: the form the station is matched, looked up and handed over by + // (the W4 stop points, the announcement files, the scenery events, the scripts) + std::string StationName{"nowhere"}; + // the name as the timetable spells it, in windows-1250 with its letters: for showing (timetable::station_caption()) + std::string StationLabel{"nowhere"}; + std::string StationWare; // typ i wyposazenie stacji, oddz. przecinkami, bez flag obsługi + int TrackNo{1}; // ilosc torow szlakowych + int Ah{-1}; + float Am{-1.f}; // godz. i min. przyjazdu, -1 gdy bez postoju + int Dh{-1}; + float Dm{-1.f}; // godz. i min. odjazdu + float tm{0.f}; // czas jazdy do tej stacji w min. (z kolumny) + bool is_maintenance{false}; + int radio_channel{-1}; + // the service flags which hold from this station on: the header's, changed by this and the earlier stations. + // entry 0 holds the header's + timetable::service_flags flags; +}; + +// what a timetable file holds +struct timetable_data { + std::string TrainName; // the name the file is looked up by, then the one the file gives + std::string TrainCategory; + std::string TrainLabel; + // the first and the last station, in the two forms a station name has (see TMTableEntry) + std::string Relation1; + std::string Relation2; + std::string RelationLabel1; + std::string RelationLabel2; + double BrakeRatio{0.0}; + std::string LocSeries; + double LocLoad{0.0}; + timetable::service_flags Flags; // of the whole train, the row "Flagi" of the header + int StationCount{0}; // stations 1..StationCount, entry 0 is the technical one + std::array TimeTable; +}; + +// conversion errors of read_timetable, besides the ones it always had (-4: no station row where expected, -5: no +// first station of the relation) +int const timetable_truncated{-9}; // the file ends before the bottom line of the table (the reader used to hang) +int const timetable_too_long{-10}; // more stations than MaxTTableSize (the reader used to write past the table) + +// reads the timetable from Input into Data. returns the conversion error, 0 when read +int read_timetable(std::istream &Input, timetable_data &Data); + +} // namespace Mtable diff --git a/world/timetablestart.cpp b/world/timetablestart.cpp new file mode 100644 index 000000000..2ece9a71c --- /dev/null +++ b/world/timetablestart.cpp @@ -0,0 +1,25 @@ +/* +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 "world/timetablestart.h" + +#include +#include + +namespace timetable { + +bool starts_at(std::string_view const Firststation, std::string_view const Relationfrom) { + // the station names are plain ascii by now, the timetable loader strips the polish letters + return std::ranges::equal(Firststation, Relationfrom, [](char const Left, char const Right) { + return std::tolower(static_cast(Left)) == std::tolower(static_cast(Right)); + }); +} + +} // namespace timetable diff --git a/world/timetablestart.h b/world/timetablestart.h new file mode 100644 index 000000000..78e6f2c36 --- /dev/null +++ b/world/timetablestart.h @@ -0,0 +1,23 @@ +/* +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 + +#include + +// the first row of a timetable +namespace timetable { + +// whether the first row of a timetable is the station the train sets off from: it names the station +// the relation starts at. such a row is a stop even with no arrival time given, the train waits there +// for its departure time. the names are compared regardless of case, as the timetables write the +// station of departure in capitals as often as not (ZAGORZ in the rows, Zagorz in the relation) +bool starts_at(std::string_view Firststation, std::string_view Relationfrom); + +} // namespace timetable